text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
package org.springusage.mybatis.generator.utils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class PropertyUtils { private static final Log log = LogFactory.getLog(PropertyUtils.class); private static Map<String, Properties> props; public static void init() { props = new ConcurrentHashMap<String, Properties>(); log.debug("Beginning init the PropertyUtils."); List<String> list = null; try { list = scanClassPath(); } catch (URISyntaxException e1) { throw new RuntimeException("scan the classpath appear error!"); } for (String propFile : list) { Properties prop = new Properties(); // String propFile = "jdbc.properties"; InputStream in = PropertyUtils.class.getClassLoader().getResourceAsStream(propFile); try { prop.load(in); log.debug("load " + propFile + " complete."); props.put(propFile, prop); } catch (IOException e) { log.error("Error:load the " + propFile + "faild." + e.getMessage()); e.printStackTrace(); } } log.debug("Initalizied complete for PorpertyUtils."); } private static List<String> scanClassPath() throws URISyntaxException{ List<String> list = new ArrayList<String>(); File classPath = new File(PropertyUtils.class.getResource("/").toURI()); File[] files = classPath.listFiles(); if (files == null) { return list; } for (File f : files) { if (f.isDirectory()) { continue; } String fileName = f.getName(); if (fileName.toLowerCase().endsWith(".properties")) { list.add(fileName); } } return list; } public static String getProperty(String key) { for (Entry<String, Properties> item : props.entrySet()) { Properties prop = item.getValue(); String value = prop.getProperty(key); if (value != null) { return value; } } return null; } public static String getProperty(String key, String defaultValue) { String value = getProperty(key); return value == null ? defaultValue : value; } public static Properties getProperties(String propName) { String suffix = ".properties"; String keyName = propName.toLowerCase(); keyName = keyName.endsWith(suffix) ? keyName : keyName + suffix; return props.get(keyName); } public static void main(String[] args) { PropertyUtils.init(); String test = PropertyUtils.getProperty("runtime.log", "null"); System.out.println(test); } }
{'content_hash': '39f158c080b4f648a3912badd474e691', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 87, 'avg_line_length': 27.612244897959183, 'alnum_prop': 0.6991869918699187, 'repo_name': 'duomn10/spring-usage', 'id': '3af36199c78e5980e6cadb212002928f34df1aea', 'size': '2708', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'mybatis-generator-maven/src/main/java/org/springusage/mybatis/generator/utils/PropertyUtils.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '109077'}, {'name': 'JavaScript', 'bytes': '24138'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>CSV to HTML Table</title> <meta name="author" content="Derek Eder"> <meta content="Display any CSV file as a searchable, filterable, pretty HTML table" /> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <link href="css/dataTables.bootstrap.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container-fluid"> <h2><a target="_blank" href="http://freetamilebooks.com">FreeTamilEbooks.com</a></h2> <p>மின்னூல்கள் பதிவிறக்க அறிக்கை</p> <iframe style="width:100%; height:50px;" frameBorder="0" scrolling="no" src="data/time_total.html"></iframe> <div id='table-container'></div> </div><!-- /.container --> <footer class='footer'> <div class='container-fluid'> <hr /> <p class='pull-right'><a href="https://github.com/nithyadurai87/fte-ebooks-download-counter">source</a> with <a href='https://github.com/derekeder/csv-to-html-table'>CSV to HTML Table</a> by <a href='http://derekeder.com'>Derek Eder</a></p> </div> </footer> <!-- Bootstrap core JavaScript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script src="js/jquery.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.csv.min.js"></script> <script src="js/jquery.dataTables.min.js"></script> <script src="js/dataTables.bootstrap.js"></script> <script src='js/csv_to_html_table.js'></script> <script> function format_link(link){ if (link) return "<a href='" + link + "' target='_blank'>" + link + "</a>"; else return ""; } CsvToHtmlTable.init({ csv_path: 'data/all_files.csv', element: 'table-container', allow_download: true, csv_options: {separator: '~', delimiter: '~'}, datatables_options: {"paging": true, "order": [[ 5, "desc" ]]} }); </script> </body> </html>
{'content_hash': '8f6a40853447c1b01440f7ec12b34122', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 249, 'avg_line_length': 33.1625, 'alnum_prop': 0.5898982284206559, 'repo_name': 'nithyadurai87/fte-ebooks-download-counter', 'id': 'ad86d1e3ec2881dd979bd129a078887e4100e363', 'size': '2707', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12261'}, {'name': 'HTML', 'bytes': '3097'}, {'name': 'JavaScript', 'bytes': '6332'}, {'name': 'Python', 'bytes': '3340'}]}
 #include <aws/ec2/model/ModifyInstancePlacementResponse.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/logging/LogMacros.h> #include <utility> using namespace Aws::EC2::Model; using namespace Aws::Utils::Xml; using namespace Aws::Utils::Logging; using namespace Aws::Utils; using namespace Aws; ModifyInstancePlacementResponse::ModifyInstancePlacementResponse() : m_return(false) { } ModifyInstancePlacementResponse::ModifyInstancePlacementResponse(const Aws::AmazonWebServiceResult<XmlDocument>& result) : m_return(false) { *this = result; } ModifyInstancePlacementResponse& ModifyInstancePlacementResponse::operator =(const Aws::AmazonWebServiceResult<XmlDocument>& result) { const XmlDocument& xmlDocument = result.GetPayload(); XmlNode rootNode = xmlDocument.GetRootElement(); XmlNode resultNode = rootNode; if (!rootNode.IsNull() && (rootNode.GetName() != "ModifyInstancePlacementResponse")) { resultNode = rootNode.FirstChild("ModifyInstancePlacementResponse"); } if(!resultNode.IsNull()) { XmlNode returnNode = resultNode.FirstChild("return"); if(!returnNode.IsNull()) { m_return = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(returnNode.GetText()).c_str()).c_str()); } } if (!rootNode.IsNull()) { XmlNode requestIdNode = rootNode.FirstChild("requestId"); if (!requestIdNode.IsNull()) { m_responseMetadata.SetRequestId(StringUtils::Trim(requestIdNode.GetText().c_str())); } AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::ModifyInstancePlacementResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); } return *this; }
{'content_hash': '11f686904c1132885c9d96318ec3f031', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 140, 'avg_line_length': 31.803571428571427, 'alnum_prop': 0.7400336889387984, 'repo_name': 'aws/aws-sdk-cpp', 'id': 'a8134af8e35031389dff74fe88918c1fe1ee9733', 'size': '1900', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'aws-cpp-sdk-ec2/source/model/ModifyInstancePlacementResponse.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '309797'}, {'name': 'C++', 'bytes': '476866144'}, {'name': 'CMake', 'bytes': '1245180'}, {'name': 'Dockerfile', 'bytes': '11688'}, {'name': 'HTML', 'bytes': '8056'}, {'name': 'Java', 'bytes': '413602'}, {'name': 'Python', 'bytes': '79245'}, {'name': 'Shell', 'bytes': '9246'}]}
"use strict"; $.views.converters({ tonum: function(val) { return +val; // Convert string to number } }); // Register additional validators for dates $.views.tags.validate.validators({ minday: { message: "Choose a date after: %cond%", test: function(condition, val) { var vals = val.split("/"), conds = condition.split("/"); vals = vals[2]*10000 + vals[0]*100 + vals[1]; conds = conds[2]*10000 + conds[0]*100 + conds[1]; return vals < conds; } }, maxday: { message: "Choose a date before: %cond%", test: function(condition, val) { var vals = val.split("/"), conds = condition.split("/"); vals = vals[2]*10000 + vals[0]*100 + vals[1]; conds = conds[2]*10000 + conds[0]*100 + conds[1]; return vals > conds; } }, weekday: { message: "Please choose a weekday!", test: function(condition, val) { var vals = val.split("/"), day = new Date(vals[2], vals[0]-1, vals[1]).getDay(); return condition ^ (day > 0 && day < 6); } } }); var pageTmpl = $.templates("#pageTmpl"), pageOptions = { pane: 0, monthsSpan: 2 }, today = new Date(), model = { startDate: $.datepicker.formatDate("mm/dd/yy", today), endDate: "", middleDate: "" }; pageTmpl.link("#page", model, { page: pageOptions }) .on("click", "#next", function() { if ($.view(this).ctx.tag.validate()) { $.observable(pageOptions).setProperty("pane", pageOptions.pane + 1); } }) .on("click", "#prev", function() { $.observable(pageOptions).setProperty("pane", pageOptions.pane - 1); });
{'content_hash': '193b285e126a3c165ad23b0a957284de', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 72, 'avg_line_length': 26.016129032258064, 'alnum_prop': 0.5709857408555487, 'repo_name': 'BorisMoore/jsviews.com', 'id': 'e36d124dd77b5eb5b05b12875b4db4804f6ada72', 'size': '1613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'samples/tag-controls/jqui/datepicker/with-validation-wizard/sample.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '36557'}, {'name': 'HTML', 'bytes': '91012'}, {'name': 'JavaScript', 'bytes': '20656268'}, {'name': 'TypeScript', 'bytes': '84407'}]}
BitcoinUnits::BitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool BitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString BitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("GEO"); case mBTC: return QString("mGEO"); case uBTC: return QString::fromUtf8("μGEO"); default: return QString("???"); } } QString BitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("HashletCoin"); case mBTC: return QString("milliHashletCoin (1 / 1,000)"); case uBTC: return QString("microHashletCoin (1 / 1,000,000)"); default: return QString("???"); } } //a single unit (.00000001) of HashletCoin is called a "wander." qint64 BitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int BitcoinUnits::amountDigits(int unit) { switch(unit) { case BTC: return 8; // 21,000,000 (# digits, without commas) case mBTC: return 11; // 21,000,000,000 case uBTC: return 14; // 21,000,000,000,000 default: return 0; } } int BitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, qint64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Right-trim excess 0's after the decimal point int nTrim = 0; for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i) ++nTrim; remainder_str.chop(nTrim); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign) { return format(unit, amount, plussign) + QString(" ") + name(unit); } bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); QStringList parts = value.split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } qint64 retvalue = str.toLongLong(&ok); if(val_out) { *val_out = retvalue; } return ok; } int BitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); }
{'content_hash': '64bbca17f8699195c784b5fa42a36305', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 89, 'avg_line_length': 24.282485875706215, 'alnum_prop': 0.6093531875290833, 'repo_name': 'pweatherbee/HashletCoin', 'id': '86fcc05ae6796a2a98c8edc6ad4f298beb855889', 'size': '4350', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/qt/bitcoinunits.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '78230'}, {'name': 'C++', 'bytes': '1371948'}, {'name': 'Objective-C++', 'bytes': '2463'}, {'name': 'Python', 'bytes': '47538'}, {'name': 'Shell', 'bytes': '1402'}, {'name': 'TypeScript', 'bytes': '3810608'}]}
#include <QtCore> #include <QtDeclarative> #include "applicationdata.h" //![0] int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; ApplicationData data; view.rootContext()->setContextProperty("applicationData", &data); view.setSource(QUrl::fromLocalFile("MyItem.qml")); view.show(); return app.exec(); } //![0]
{'content_hash': 'c6aeca6f73ebc91d218a3cc8a5856cc9', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 69, 'avg_line_length': 17.40909090909091, 'alnum_prop': 0.6631853785900783, 'repo_name': 'stephaneAG/PengPod700', 'id': 'd02467590288ae2720b7f2e3e7d0f1e5126cf221', 'size': '2381', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'QtEsrc/backup_qt/qt-everywhere-opensource-src-4.8.5/doc/src/snippets/declarative/qtbinding/context-advanced/main.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '167426'}, {'name': 'Batchfile', 'bytes': '25368'}, {'name': 'C', 'bytes': '3755463'}, {'name': 'C#', 'bytes': '9282'}, {'name': 'C++', 'bytes': '177871700'}, {'name': 'CSS', 'bytes': '600936'}, {'name': 'GAP', 'bytes': '758872'}, {'name': 'GLSL', 'bytes': '32226'}, {'name': 'Groff', 'bytes': '106542'}, {'name': 'HTML', 'bytes': '273585110'}, {'name': 'IDL', 'bytes': '1194'}, {'name': 'JavaScript', 'bytes': '435912'}, {'name': 'Makefile', 'bytes': '289373'}, {'name': 'Objective-C', 'bytes': '1898658'}, {'name': 'Objective-C++', 'bytes': '3222428'}, {'name': 'PHP', 'bytes': '6074'}, {'name': 'Perl', 'bytes': '291672'}, {'name': 'Prolog', 'bytes': '102468'}, {'name': 'Python', 'bytes': '22546'}, {'name': 'QML', 'bytes': '3580408'}, {'name': 'QMake', 'bytes': '2191574'}, {'name': 'Scilab', 'bytes': '2390'}, {'name': 'Shell', 'bytes': '116533'}, {'name': 'TypeScript', 'bytes': '42452'}, {'name': 'Visual Basic', 'bytes': '8370'}, {'name': 'XQuery', 'bytes': '25094'}, {'name': 'XSLT', 'bytes': '252382'}]}
from unittest import TestCase class DummyTests(TestCase): def test_dummy(self): self.assertTrue(True, 'Asser failed should be true')
{'content_hash': 'e1b115c0fe2f1a9870a78d9460b0b7b7', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 60, 'avg_line_length': 21.0, 'alnum_prop': 0.7210884353741497, 'repo_name': 'digsim/tube4droid', 'id': '5d7e0c9ab0aa13b003e41617f2b644180d642e26', 'size': '172', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tube4droid/feedcreator/tests/dummy_test.py', 'mode': '33261', 'license': 'apache-2.0', 'language': []}
namespace Google.Cloud.SecurityCenter.V1P1Beta1.Snippets { // [START securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.SecurityCenter.V1P1Beta1; using Google.Protobuf.WellKnownTypes; using System; public sealed partial class GeneratedSecurityCenterClientSnippets { /// <summary>Snippet for ListAssets</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void ListAssetsRequestObject() { // Create client SecurityCenterClient securityCenterClient = SecurityCenterClient.Create(); // Initialize request argument(s) ListAssetsRequest request = new ListAssetsRequest { ParentAsOrganizationName = OrganizationName.FromOrganization("[ORGANIZATION]"), Filter = "", OrderBy = "", ReadTime = new Timestamp(), CompareDuration = new Duration(), FieldMask = new FieldMask(), }; // Make the request PagedEnumerable<ListAssetsResponse, ListAssetsResponse.Types.ListAssetsResult> response = securityCenterClient.ListAssets(request); // Iterate over all response items, lazily performing RPCs as required foreach (ListAssetsResponse.Types.ListAssetsResult item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAssetsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (ListAssetsResponse.Types.ListAssetsResult item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<ListAssetsResponse.Types.ListAssetsResult> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (ListAssetsResponse.Types.ListAssetsResult item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; } } // [END securitycenter_v1p1beta1_generated_SecurityCenter_ListAssets_sync] }
{'content_hash': '8288dc4d2b76082eb92b2a060e160c90', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 143, 'avg_line_length': 45.01470588235294, 'alnum_prop': 0.6135249918327343, 'repo_name': 'jskeet/google-cloud-dotnet', 'id': '37248a7005aa240c82a494eb5d830f2ffd4a1e09', 'size': '3683', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'apis/Google.Cloud.SecurityCenter.V1P1Beta1/Google.Cloud.SecurityCenter.V1P1Beta1.GeneratedSnippets/SecurityCenterClient.ListAssetsRequestObjectSnippet.g.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '767'}, {'name': 'C#', 'bytes': '268415427'}, {'name': 'CSS', 'bytes': '1346'}, {'name': 'Dockerfile', 'bytes': '3173'}, {'name': 'HTML', 'bytes': '3823'}, {'name': 'JavaScript', 'bytes': '226'}, {'name': 'PowerShell', 'bytes': '3303'}, {'name': 'Python', 'bytes': '2744'}, {'name': 'Shell', 'bytes': '65260'}, {'name': 'sed', 'bytes': '1030'}]}
@javax.xml.bind.annotation.XmlSchema(namespace = "http://pronom.nationalarchives.gov.uk", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package uk.gov.nationalarchives.pronom;
{'content_hash': '5009bcd82df704c3b3e45e18cb75a402', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 157, 'avg_line_length': 67.33333333333333, 'alnum_prop': 0.806930693069307, 'repo_name': 'digital-preservation/droid', 'id': '0186a930bb9667b4e5dadb069c888bcfd83f6cf6', 'size': '1880', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'droid-results/src/main/java/uk/gov/nationalarchives/pronom/package-info.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP.NET', 'bytes': '76'}, {'name': 'ActionScript', 'bytes': '46'}, {'name': 'Alloy', 'bytes': '81'}, {'name': 'Arc', 'bytes': '6322'}, {'name': 'Batchfile', 'bytes': '5582'}, {'name': 'COBOL', 'bytes': '32'}, {'name': 'GLSL', 'bytes': '5'}, {'name': 'HTML', 'bytes': '280290'}, {'name': 'Haskell', 'bytes': '992'}, {'name': 'Java', 'bytes': '4140696'}, {'name': 'JavaScript', 'bytes': '4'}, {'name': 'JetBrains MPS', 'bytes': '16'}, {'name': 'Mathematica', 'bytes': '12'}, {'name': 'Papyrus', 'bytes': '6'}, {'name': 'Perl', 'bytes': '7'}, {'name': 'Portugol', 'bytes': '200'}, {'name': 'PostScript', 'bytes': '8803'}, {'name': 'Q#', 'bytes': '8'}, {'name': 'Rich Text Format', 'bytes': '39'}, {'name': 'Roff', 'bytes': '60'}, {'name': 'RouterOS Script', 'bytes': '28'}, {'name': 'Shell', 'bytes': '5250'}, {'name': 'Squirrel', 'bytes': '24'}, {'name': 'Standard ML', 'bytes': '16'}, {'name': 'XSLT', 'bytes': '22975'}, {'name': 'nesC', 'bytes': '8'}]}
package com.amazonaws.services.kinesis.aggregators.app; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.amazonaws.services.kinesis.aggregators.AggregatorsConstants; import com.amazonaws.services.kinesis.aggregators.configuration.ConfigFileUtils; public class FetchConfigurationServlet extends AbstractQueryServlet { private void respondWith(HttpServletResponse response, Map<String, String> configItems) throws IOException { response.setStatus(200); // cors grant response.setHeader("Access-Control-Allow-Origin", "*"); PrintWriter w = response.getWriter(); int i = 0; // write out the response values as json w.println("{"); int resultCount = 0; for (String s : configItems.keySet()) { resultCount++; String value = configItems.get(s); w.print(String.format("\"%s\":%s", s, value == null ? "null" : String.format("\"%s\"", value))); if (resultCount != configItems.size()) { w.println(","); } } w.print("}"); } @Override protected void doAction(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Map<String, String> config = new HashMap<>(); // required items config.put(AggregatorsConstants.REGION_PARAM, System.getProperty(AggregatorsConstants.REGION_PARAM)); config.put(AggregatorsConstants.STREAM_NAME_PARAM, System.getProperty(AggregatorsConstants.STREAM_NAME_PARAM)); config.put(AggregatorsConstants.APP_NAME_PARAM, System.getProperty(AggregatorsConstants.APP_NAME_PARAM)); config.put(AggregatorsConstants.CONFIG_URL_PARAM, System.getProperty(AggregatorsConstants.CONFIG_URL_PARAM)); config.put( "fetch-config-url", ConfigFileUtils.makeConfigFileURL(System.getProperty(AggregatorsConstants.CONFIG_URL_PARAM))); // optional items config.put(AggregatorsConstants.ENVIRONMENT_PARAM, System.getProperty(AggregatorsConstants.ENVIRONMENT_PARAM)); config.put(AggregatorsConstants.MAX_RECORDS_PARAM, System.getProperty(AggregatorsConstants.MAX_RECORDS_PARAM)); config.put(AggregatorsConstants.FAILURES_TOLERATED_PARAM, System.getProperty(AggregatorsConstants.FAILURES_TOLERATED_PARAM)); respondWith(response, config); } catch (Exception e) { throw new ServletException(e); } } }
{'content_hash': '8510e88070bcbba7df936cb4df08d04a', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 114, 'avg_line_length': 37.58974358974359, 'alnum_prop': 0.638130968622101, 'repo_name': 'MiguelPeralvo/amazon-kinesis-aggregators', 'id': '861c2d52c8a54bfa88c7be2dda5c3653b07321c2', 'size': '3537', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/com/amazonaws/services/kinesis/aggregators/app/FetchConfigurationServlet.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2016'}, {'name': 'HTML', 'bytes': '811'}, {'name': 'Java', 'bytes': '378870'}, {'name': 'Shell', 'bytes': '996'}]}
'use strict'; import * as assert from 'assert'; import {getRandomPort} from '../src/random-port'; describe('Random port generation', () => { it('generates a valid random port number', async () => { const port = await getRandomPort(); // Verify generated port number is valid integer. assert.ok(Number.isInteger(port) && port > 0 && port <= 0xFFFF); }); });
{'content_hash': '1cf8e5a39c6da5a709033e82a0bc6eaa', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 68, 'avg_line_length': 28.923076923076923, 'alnum_prop': 0.6462765957446809, 'repo_name': 'GoogleChrome/chrome-launcher', 'id': '020339d42a55b4f8d69a330b52e319d11eef12e8', 'size': '993', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'test/random-port-test.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'JavaScript', 'bytes': '2947'}, {'name': 'Shell', 'bytes': '1577'}, {'name': 'TypeScript', 'bytes': '46740'}]}
//Problem 23. Series of letters // Write a program that reads a string from the console and replaces all series //of consecutive identical letters with a single one. //Example: //input output //aaaaabbbbbcdddeeeedssaa abcdedsa using System; using System.Linq; using System.Text; class LetterSeries { static void Main() { //Console.Write("Enter a string: "); //string text = Console.ReadLine(); string text = "aaaaabbbbbcdddeeeedssaa"; StringBuilder uniqueLetters = new StringBuilder(); uniqueLetters.Append(text[0]); for (int i = 1; i < text.Length; i++) { if (text[i] != text[i - 1]) { uniqueLetters.Append(text[i]); } } Console.WriteLine("Ta-daaaa! -> " + uniqueLetters); } }
{'content_hash': '5393e28c7fc4bbc8c1950d7831a80e96', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 83, 'avg_line_length': 26.78125, 'alnum_prop': 0.574095682613769, 'repo_name': 'LyubaG/TelerikAcademy', 'id': '6d60f2fdc0dcb16d11dafdaaf0e29a4ea9946d74', 'size': '859', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'C#/2.3.Strings-and-Text-Processing-HW/23.Series_of_Letters/LetterSeries.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '106'}, {'name': 'C#', 'bytes': '851195'}, {'name': 'CSS', 'bytes': '88096'}, {'name': 'CoffeeScript', 'bytes': '3700'}, {'name': 'HTML', 'bytes': '197557'}, {'name': 'JavaScript', 'bytes': '587289'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': '65e7f8b23f5fd8bc3994ccf93dfdfd9c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '5be7036dd855d251fbd6cb291283bf7e3df06c7c', 'size': '184', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Polypodiaceae/Polypodium/Polypodium caudatum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (1.8.0_172) on Sat Jan 18 18:10:31 CET 2020 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class ml.alternet.parser.Grammar.CharToken (Alternet Parsing 1.0 API)</title> <meta name="date" content="2020-01-18"> <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 ml.alternet.parser.Grammar.CharToken (Alternet Parsing 1.0 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="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">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?ml/alternet/parser/class-use/Grammar.CharToken.html" target="_top">Frames</a></li> <li><a href="Grammar.CharToken.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 ml.alternet.parser.Grammar.CharToken" class="title">Uses of Class<br>ml.alternet.parser.Grammar.CharToken</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="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</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="#ml.alternet.parser">ml.alternet.parser</a></td> <td class="colLast"> <div class="block">Allow to design grammar, parse input and generate a custom data structure.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="ml.alternet.parser"> <!-- --> </a> <h3>Uses of <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a> in <a href="../../../../ml/alternet/parser/package-summary.html">ml.alternet.parser</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="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a> in <a href="../../../../ml/alternet/parser/package-summary.html">ml.alternet.parser</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>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.Composed.html" title="class in ml.alternet.parser">Grammar.CharToken.Composed</a></span></code> <div class="block">A token made of a several char ranges.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.Single.html" title="class in ml.alternet.parser">Grammar.CharToken.Single</a></span></code> <div class="block">A token made of a single char range.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../ml/alternet/parser/package-summary.html">ml.alternet.parser</a> declared as <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#Z:Z:Dany">$any</a></span></code> <div class="block">The char token for any Unicode codepoint.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#Z:Z:Dempty">$empty</a></span></code> <div class="block">The char token that matches nothing.</div> </td> </tr> </tbody> </table> <table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../ml/alternet/parser/package-summary.html">ml.alternet.parser</a> that return <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#except-ml.alternet.misc.CharRange...-">except</a></span>(<a href="http://alternet.github.io/alternet-libs/apidocs/ml/alternet/misc/CharRange.html?is-external=true" title="class or interface in ml.alternet.misc">CharRange</a>...&nbsp;charRanges)</code> <div class="block">Remove from this char token the given char ranges.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#except-java.lang.CharSequence-">except</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a>&nbsp;characters)</code> <div class="block">Remove from this char token the given characters.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#except-ml.alternet.parser.Grammar.Token...-">except</a></span>(<a href="../../../../ml/alternet/parser/Grammar.Token.html" title="class in ml.alternet.parser">Grammar.Token</a>...&nbsp;charTokens)</code> <div class="block">Remove from this char token the given char tokens.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#except-int-">except</a></span>(int&nbsp;codepoint)</code> <div class="block">Remove from this char token the given Unicode codepoint.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#except-int-int-">except</a></span>(int&nbsp;startCodepoint, int&nbsp;endCodepoint)</code> <div class="block">Remove from this char token the given range.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#is-int-">is</a></span>(int&nbsp;car)</code> <div class="block">Create a char token.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#isNot-ml.alternet.parser.Grammar.Token...-">isNot</a></span>(<a href="../../../../ml/alternet/parser/Grammar.Token.html" title="class in ml.alternet.parser">Grammar.Token</a>...&nbsp;chars)</code> <div class="block">Create a token based on exclusion.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#isNot-int-">isNot</a></span>(int&nbsp;car)</code> <div class="block">Create a char token based on exclusion.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#isNotOneOf-java.lang.String-">isNotOneOf</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;string)</code> <div class="block">Create a char token, the char is none of the ones of a string.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#isOneOf-java.lang.String-">isOneOf</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>&nbsp;string)</code> <div class="block">Create a char token, the char is one of the ones of a string.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.html#range-int-int-">range</a></span>(int&nbsp;start, int&nbsp;end)</code> <div class="block">Create a range rule.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#union-ml.alternet.misc.CharRange...-">union</a></span>(<a href="http://alternet.github.io/alternet-libs/apidocs/ml/alternet/misc/CharRange.html?is-external=true" title="class or interface in ml.alternet.misc">CharRange</a>...&nbsp;charRanges)</code> <div class="block">Combine this char token with the given char ranges.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#union-java.lang.CharSequence-">union</a></span>(<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/CharSequence.html?is-external=true" title="class or interface in java.lang">CharSequence</a>&nbsp;characters)</code> <div class="block">Combine this char token with the given characters.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#union-ml.alternet.parser.Grammar.Token...-">union</a></span>(<a href="../../../../ml/alternet/parser/Grammar.Token.html" title="class in ml.alternet.parser">Grammar.Token</a>...&nbsp;charTokens)</code> <div class="block">Combine this char token with the given char tokens.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#union-int-">union</a></span>(int&nbsp;codepoint)</code> <div class="block">Combine this char token with the given Unicode codepoint.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">Grammar.CharToken</a></code></td> <td class="colLast"><span class="typeNameLabel">Grammar.CharToken.</span><code><span class="memberNameLink"><a href="../../../../ml/alternet/parser/Grammar.CharToken.html#union-int-int-">union</a></span>(int&nbsp;startCodepoint, int&nbsp;endCodepoint)</code> <div class="block">Combine this char token with the given range.</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="../../../../ml/alternet/parser/Grammar.CharToken.html" title="class in ml.alternet.parser">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?ml/alternet/parser/class-use/Grammar.CharToken.html" target="_top">Frames</a></li> <li><a href="Grammar.CharToken.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; 2020 <a href="http://alternet.github.io">Alternet</a>. All rights reserved.</small></p> </body> </html>
{'content_hash': '5942a7c0c5992a4777ef63e5aa891e0e', 'timestamp': '', 'source': 'github', 'line_count': 305, 'max_line_length': 422, 'avg_line_length': 60.22950819672131, 'alnum_prop': 0.6808383233532934, 'repo_name': 'alternet/alternet.github.io', 'id': 'd3fd3bd6040406d8a535ea69abfd308e79ed2acd', 'size': '18370', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'alternet-libs/parsing/apidocs/ml/alternet/parser/class-use/Grammar.CharToken.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '114584'}, {'name': 'HTML', 'bytes': '23100737'}, {'name': 'JavaScript', 'bytes': '5465'}]}
package com.googlecode.protobuf.netty.exception; import com.googlecode.protobuf.netty.NettyRpcProto.RpcRequest; @SuppressWarnings("serial") public class NoSuchServiceMethodException extends RpcException { public NoSuchServiceMethodException(RpcRequest request, String method) { super(request, "No such method: " + method); } }
{'content_hash': '98c6485f082a249ad1986aaf9b4f6882', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 73, 'avg_line_length': 25.923076923076923, 'alnum_prop': 0.8011869436201781, 'repo_name': 'yamingd/netty-protobuf-rpc', 'id': 'c03e3949ae34d55ef23d14677774f8d077b8ceba', 'size': '1479', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/googlecode/protobuf/netty/exception/NoSuchServiceMethodException.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '136300'}, {'name': 'Protocol Buffer', 'bytes': '4779'}]}
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/shape_chart_item" ></item> <item android:state_checked="false" android:drawable="@drawable/shape_chart_item2"></item> </selector>
{'content_hash': '76150138b5bc7a08097cbcedd19937ea', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 94, 'avg_line_length': 61.8, 'alnum_prop': 0.7249190938511327, 'repo_name': 'hukell/fhl', 'id': '9c47e34b5f947aecca823397f5935b12ce937487', 'size': '309', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/drawable/selector_button_color2.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '492514'}]}
@import url(https://fonts.googleapis.com/css?family=Open+Sans:300i,400,700); @import url('https://rsms.me/inter/inter.css'); @import url('jetbrains-mono.css'); :root { --default-gray: #f4f4f4; --default-font-color: black; --header-font-color: var(--default-font-color); --breadcrumb-font-color: #637282; --breadcrumb-margin: 24px; --hover-link-color: #5B5DEF; --footer-height: 64px; --footer-padding-top: 48px; --footer-background: var(--default-gray); --footer-font-color: var(--average-color); --footer-go-to-top-color: white; --horizontal-spacing-for-content: 16px; --mobile-horizontal-spacing-for-content: 8px; --bottom-spacing: 16px; --color-scrollbar: rgba(39, 40, 44, 0.40); --color-scrollbar-track: var(--default-gray); --default-white: #fff; --background-color: var(--default-white); --dark-mode-and-search-icon-color: var(--default-white); --color-dark: #27282c; --default-font-family: system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Droid Sans, Helvetica Neue, Arial, sans-serif; --default-monospace-font-family: JetBrains Mono, SFMono-Regular, Consolas, Liberation Mono, Menlo, Courier, monospace; --default-font-size: 15px; --average-color: var(--color-dark); --brief-color: var(--average-color); --copy-icon-color: rgba(39, 40, 44, .7); --copy-icon-hover-color: var(--color-dark); --code-background: rgba(39, 40, 44, .05); --border-color: rgba(39, 40, 44, .2); --navigation-highlight-color: rgba(39, 40, 44, 0.05); --top-navigation-height: 73px; --max-width: 1160px; --white-10: hsla(0, 0%, 100%, .1); --active-tab-border-color: var(--hover-link-color); --inactive-tab-border-color: #DADFE6; } :root.theme-dark { --background-color: #27282c; --color-dark: #3d3d41; --default-font-color: hsla(0, 0%, 100%, 0.8); --border-color: hsla(0, 0%, 100%, 0.2); --code-background: hsla(0, 0%, 100%, 0.05); --breadcrumb-font-color: #8c8c8e; --brief-color: hsla(0, 0%, 100%, 0.4); --copy-icon-color: hsla(0, 0%, 100%, 0.6); --copy-icon-hover-color: #fff; --active-tab-border-color: var(--default-font-color); --inactive-tab-border-color: var(--border-color); --navigation-highlight-color: rgba(255, 255, 255, 0.05); --footer-background: hsla(0, 0%, 100%, 0.05); --footer-font-color: hsla(0, 0%, 100%, 0.6); --footer-go-to-top-color: var(--footer-font-color); } html { height: 100%; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); scrollbar-color: rgba(39, 40, 44, 0.40) #F4F4F4; scrollbar-color: var(--color-scrollbar) var(--color-scrollbar-track); text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; color: var(--default-font-color); } html ::-webkit-scrollbar { width: 8px; height: 8px; } html ::-webkit-scrollbar-track { background-color: var(--color-scrollbar-track); } html ::-webkit-scrollbar-thumb { width: 8px; border-radius: 6px; background: rgba(39, 40, 44, 0.40); background: var(--color-scrollbar); } .main-content { padding-bottom: var(--bottom-spacing); z-index: 0; max-width: var(--max-width); width: 100%; margin-left: auto; margin-right: auto; } .main-content > * { margin-left: var(--horizontal-spacing-for-content); margin-right: var(--horizontal-spacing-for-content); } .navigation-wrapper { display: flex; flex-wrap: wrap; position: sticky; top: 0; background-color: var(--color-dark); z-index: 4; color: #fff; font-family: var(--default-font-family); letter-spacing: -0.1px; align-items: center; /* Reset margin and use padding for border */ margin-left: 0; margin-right: 0; padding: 19px var(--horizontal-spacing-for-content) 18px; } .navigation-wrapper > .library-name { font-weight: 700; margin-right: 12px; } .navigation-wrapper a { color: #fff; } #searchBar { margin-left: 16px; display: inline-flex; align-content: center; align-items: center; width: 36px; height: 36px; } .breadcrumbs, .breadcrumbs a, .breadcrumbs a:hover { margin-top: var(--breadcrumb-margin); color: var(--breadcrumb-font-color); overflow-wrap: break-word; } .tabs-section > .section-tab:first-child, .platform-hinted > .platform-bookmarks-row > .platform-bookmark:first-child { margin-left: 0; } .section-tab { border: 0; background-color: transparent; border-bottom: 1px solid var(--inactive-tab-border-color); } .platform-hinted > .platform-bookmarks-row { margin-bottom: 16px; } .section-tab, .platform-hinted > .platform-bookmarks-row > .platform-bookmark { margin: 0 8px; padding: 11px 3px; cursor: pointer; outline: none; font-size: var(--default-font-size); color: inherit; } .section-tab:hover { border-bottom: 2px solid var(--active-tab-border-color); } .section-tab[data-active=''] { border-bottom: 2px solid var(--active-tab-border-color); } .tabs-section-body > div { margin-top: 12px; } .tabs-section-body .with-platform-tabs { padding-top: 12px; padding-bottom: 12px; } .cover > .platform-hinted { padding-top: 12px; margin-top: 12px; padding-bottom: 12px; } .cover { display: flex; flex-direction: column; } .cover .platform-hinted.with-platform-tabs .sourceset-depenent-content > .block ~ .symbol { padding-top: 16px; padding-left: 0; } .cover .sourceset-depenent-content > .block { padding: 16px 0; font-size: 18px; line-height: 28px; } .cover .platform-hinted.with-platform-tabs .sourceset-depenent-content > .block { padding: 0; font-size: var(--default-font-size); } .cover ~ .divergent-group { margin-top: 24px; padding: 24px 8px 8px 8px; } .cover ~ .divergent-group .main-subrow .symbol { width: 100%; } .main-content p.paragraph, .sample-container { margin-top: 8px; } p.paragraph:first-child, .brief p.paragraph { margin-top: 0; } .divergent-group { background-color: var(--background-color); padding: 16px 0 8px 0; margin-bottom: 2px; } .divergent-group .table-row, tbody > tr { border-bottom: 1px solid var(--border-color); } .divergent-group .table-row:last-of-type, tbody > tr:last-of-type { border-bottom: none; } .title > .divergent-group:first-of-type { padding-top: 0; } #container { display: flex; flex-direction: row; height: calc(100% - var(--top-navigation-height)); } #container > div { height: 100%; max-height: calc(100vh - var(--top-navigation-height)); overflow: auto; } #main { width: 100%; max-width: calc(100% - 280px); display: flex; flex-direction: column; } #leftColumn { width: 280px; border-right: 1px solid var(--border-color); display: flex; flex-direction: column; } #sideMenu { padding-top: 22px; overflow-y: auto; font-size: 12px; font-weight: 400; line-height: 16px; height: 100%; } .sample-container, div.CodeMirror { position: relative; display: flex; flex-direction: column; } code.paragraph { display: block; } .overview > .navButton { align-items: center; display: flex; justify-content: flex-end; padding: 2px 2px 2px 0; margin-right: 5px; cursor: pointer; } .strikethrough { text-decoration: line-through; } .symbol:empty { padding: 0; } .symbol:not(.token), code { background-color: var(--code-background); align-items: center; box-sizing: border-box; white-space: pre-wrap; font-family: var(--default-monospace-font-family); font-size: var(--default-font-size); } .symbol:not(.token), code.block { display: block; padding: 12px 32px 12px 12px; border-radius: 8px; line-height: 24px; position: relative; } .symbol > a { color: var(--hover-link-color); } .copy-icon { cursor: pointer; } .symbol span.copy-icon, .sample-container span.copy-icon { display: none; } .symbol:hover span.copy-icon, .sample-container:hover span.copy-icon { display: inline-block; } .symbol span.copy-icon::before, .sample-container span.copy-icon::before { width: 24px; height: 24px; display: inline-block; content: ''; /* masks are required if you want to change color of the icon dynamically instead of using those provided with the SVG */ -webkit-mask: url("../images/copy-icon.svg") no-repeat 50% 50%; mask: url("../images/copy-icon.svg") no-repeat 50% 50%; -webkit-mask-size: cover; mask-size: cover; background-color: var(--copy-icon-color); } .symbol span.copy-icon:hover::before, .sample-container span.copy-icon:hover::before { background-color: var(--copy-icon-hover-color); } .copy-popup-wrapper { display: none; align-items: center; position: absolute; z-index: 1000; background: white; font-weight: normal; font-family: var(--default-font-family); width: max-content; font-size: var(--default-font-size); cursor: default; border: 1px solid #D8DCE1; box-sizing: border-box; box-shadow: 0px 5px 10px var(--ring-popup-shadow-color); border-radius: 3px; color: initial; } .copy-popup-wrapper > .copy-popup-icon::before { content: url("../images/copy-successful-icon.svg"); padding: 8px; } .copy-popup-wrapper > .copy-popup-icon { position: relative; top: 3px; } .copy-popup-wrapper.popup-to-left { /* since it is in position absolute we can just move it to the left to make it always appear on the left side of the icon */ left: -15em; } .symbol:hover .copy-popup-wrapper.active-popup, .sample-container:hover .copy-popup-wrapper.active-popup { display: flex !important; } .copy-popup-wrapper:hover { font-weight: normal; } .copy-popup-wrapper > span:last-child { padding-right: 14px; } .symbol .top-right-position, .sample-container .top-right-position { /* it is important for a parent to have a position: relative */ position: absolute; top: 8px; right: 8px; } .sideMenuPart > .overview { display: flex; align-items: center; position: relative; user-select: none; /* there's a weird bug with text selection */ padding: 8px 0; } .sideMenuPart a { display: block; align-items: center; color: var(--default-font-color); overflow: hidden; } .sideMenuPart a:hover { text-decoration: none; color: var(--default-font-color); } .sideMenuPart > .overview:before { box-sizing: border-box; content: ''; top: 0; width: 280px; right: 0; bottom: 0; position: absolute; z-index: -1; } .overview:hover:before { background-color: var(--navigation-highlight-color); } #nav-submenu { padding-left: 24px; } .sideMenuPart { padding-left: 12px; box-sizing: border-box; } .sideMenuPart.hidden > .overview .navButtonContent::before { transform: rotate(0deg); } .sideMenuPart > .overview .navButtonContent::before { content: ''; -webkit-mask: url("../images/arrow_down.svg") no-repeat 50% 50%; mask: url("../images/arrow_down.svg") no-repeat 50% 50%; -webkit-mask-size: cover; mask-size: cover; background-color: var(--default-font-color); display: flex; flex-direction: row; align-items: center; justify-content: center; transform: rotate(90deg); width: 16px; height: 16px; } .sideMenuPart[data-active] > .overview .navButtonContent::before { background-color: var(--default-white); } .sideMenuPart.hidden > .navButton .navButtonContent::after { content: '\02192'; } .sideMenuPart.hidden > .sideMenuPart { display: none; } .filtered > a, .filtered > .navButton { display: none; } body { height: 100%; } body, table { font-family: var(--default-font-family); background: var(--background-color); font-style: normal; font-weight: normal; font-size: var(--default-font-size); line-height: 24px; margin: 0; } table { width: 100%; border-collapse: collapse; padding: 5px; } tbody > tr { min-height: 56px; } td:first-child { width: 20vw; } .brief { white-space: pre-wrap; overflow: hidden; } p, ul, ol, table, pre, dl { margin: 0; } h1 { font-size: 40px; line-height: 48px; letter-spacing: -1px; } h1.cover { font-size: 60px; line-height: 64px; letter-spacing: -1.5px; margin-bottom: 0; padding-bottom: 32px; display: block; } h2 { font-size: 31px; line-height: 40px; letter-spacing: -0.5px; } h3 { font-size: 20px; line-height: 28px; letter-spacing: -0.2px; } .UnderCoverText { font-size: 16px; line-height: 28px; } .UnderCoverText code { font-size: inherit; } .UnderCoverText table { margin: 8px 0 8px 0; word-break: break-word; } a { text-decoration: none; } #main a:not([data-name]) { padding-bottom: 2px; border-bottom: 1px solid var(--border-color); cursor: pointer; text-decoration: none; color: inherit; font-size: inherit; line-height: inherit; transition: color .1s, border-color .1s; } #main a:hover { border-bottom-color: unset; color: inherit } a small { font-size: 11px; margin-top: -0.6em; display: block; } blockquote { border-left: 1px solid #e5e5e5; margin: 0; padding: 0 0 0 20px; font-style: italic; } pre { display: block; } th, td { text-align: left; vertical-align: top; padding: 12px 10px 11px; } dt { color: #444; font-weight: 700; } p.paragraph img { display: block; } img { max-width: 100%; } small { font-size: 11px; } .platform-tag { display: flex; flex-direction: row; padding: 4px 8px; height: 24px; border-radius: 100px; box-sizing: border-box; border: 1px solid transparent; margin: 2px; font-family: Inter, Arial, sans-serif; font-size: 12px; font-weight: 400; font-style: normal; font-stretch: normal; line-height: normal; letter-spacing: normal; text-align: center; outline: none; color: #fff } .platform-tags { display: flex; flex-wrap: wrap; padding-bottom: 8px; } .platform-tags > .platform-tag { align-self: center; } .platform-tags > .platform-tag:first-of-type { margin-left: auto; } .platform-tag.jvm-like { background-color: #4DBB5F; color: white; } .platform-tag.js-like { background-color: #FED236; color: white; } .platform-tag.native-like { background-color: #CD74F6; color: white; } .platform-tag.common-like { background-color: #A6AFBA; color: white; } .filter-section { display: flex; flex-direction: row; align-self: flex-end; min-height: 36px; z-index: 0; flex-wrap: wrap; align-items: center; } .platform-selector:hover { border: 1px solid #A6AFBA !important; } [data-filterable-current=''] { display: none !important; } .platform-selector:not([data-active]) { border: 1px solid #DADFE6; background-color: transparent; color: var(--average-color); } .navigation-wrapper .platform-selector:not([data-active]) { color: #FFFFFF; } td.content { padding-left: 24px; padding-top: 16px; display: flex; flex-direction: column; } .main-subrow { display: flex; flex-direction: row; padding: 0; flex-wrap: wrap; } .main-subrow > div > span { display: flex; position: relative; } .main-subrow:hover .anchor-icon { opacity: 1; transition: 0.2s; } .main-subrow .anchor-icon { opacity: 0; transition: 0.2s 0.5s; } .main-subrow .anchor-icon::before { content: url("../images/anchor-copy-button.svg"); } .main-subrow .anchor-icon:hover { cursor: pointer; } .main-subrow .anchor-icon:hover > svg path { fill: var(--hover-link-color); } .main-subrow .anchor-wrapper { position: relative; width: 24px; height: 16px; margin-left: 3px; } .inline-flex { display: inline-flex; } .platform-hinted { flex: auto; display: block; } .platform-hinted > .platform-bookmarks-row > .platform-bookmark { min-width: 64px; border: 2px solid var(--background-color); background: inherit; outline: none; flex: none; order: 5; align-self: flex-start; } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.jvm-like { border-bottom: 2px solid rgba(77, 187, 95, 0.3); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.js-like { border-bottom: 2px solid rgba(254, 175, 54, 0.3); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.native-like { border-bottom: 2px solid rgba(105, 118, 249, 0.3); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.common-like { border-bottom: 2px solid rgba(161, 170, 180, 0.3); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.jvm-like[data-active=''], .platform-hinted > .platform-bookmarks-row > .platform-bookmark.jvm-like:hover { border: 2px solid var(--background-color); border-bottom: 2px solid #4DBB5F; background: var(--background-color); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.js-like[data-active=''], .platform-hinted > .platform-bookmarks-row > .platform-bookmark.js-like:hover { border: 2px solid var(--background-color); border-bottom: 2px solid #FED236; background: var(--background-color); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.native-like[data-active=''], .platform-hinted > .platform-bookmarks-row > .platform-bookmark.native-like:hover { border: 2px solid var(--background-color); border-bottom: 2px solid #CD74F6; background: var(--background-color); } .platform-hinted > .platform-bookmarks-row > .platform-bookmark.common-like[data-active=''], .platform-hinted > .platform-bookmarks-row > .platform-bookmark.common-like:hover { border: 2px solid var(--background-color); border-bottom: 2px solid #A6AFBA; background: var(--background-color); } .platform-hinted > .content:not([data-active]), .tabs-section-body > *:not([data-active]) { display: none; } /*Work around an issue: https://github.com/JetBrains/kotlin-playground/issues/91*/ .platform-hinted[data-togglable="Samples"] > .content:not([data-active]), .tabs-section-body > *[data-togglable="Samples"]:not([data-active]) { display: block !important; visibility: hidden; height: 0; position: fixed; top: 0; } .with-platform-tags { display: flex; } .with-platform-tags ~ .main-subrow { padding-top: 8px; } .cover .with-platform-tabs { font-size: var(--default-font-size); } .cover > .with-platform-tabs > .content { padding: 8px 16px; border: 1px solid var(--border-color); } .cover > .block { padding-top: 48px; padding-bottom: 24px; font-size: 18px; line-height: 28px; } .cover > .block:empty { padding-bottom: 0; } .table-row .with-platform-tabs .sourceset-depenent-content .brief { padding: 8px; } .sideMenuPart[data-active] > .overview:before { background: var(--color-dark); } .sideMenuPart[data-active] > .overview > a { color: var(--default-white); } .table { display: flex; flex-direction: column; } .table-row { display: flex; flex-direction: column; border-bottom: 1px solid var(--border-color); padding: 11px 0 12px 0; background-color: var(--background-color); } .table-row:last-of-type { border-bottom: none; } .table-row .brief-comment { color: var(--brief-color); } .platform-dependent-row { display: grid; padding-top: 8px; } .title-row { display: grid; grid-template-columns: auto auto 7em; width: 100%; } .keyValue { display: grid; } @media print, screen and (min-width: 960px) { .keyValue { grid-template-columns: 20% 80%; } .title-row { grid-template-columns: 20% auto 7em; } } @media print, screen and (max-width: 960px) { div.wrapper { width: auto; margin: 0; } header, section, footer { float: none; position: static; width: auto; } header { padding-right: 320px; } section { border: 1px solid #e5e5e5; border-width: 1px 0; padding: 20px 0; margin: 0 0 20px; } header a small { display: inline; } header ul { position: absolute; right: 50px; top: 52px; } } .footer { clear: both; display: flex; align-items: center; position: relative; min-height: var(--footer-height); font-size: 12px; line-height: 16px; letter-spacing: 0.2px; color: var(--footer-font-color); margin-top: auto; background-color: var(--footer-background); } .footer span.go-to-top-icon { border-radius: 2em; padding: 11px 10px !important; background-color: var(--footer-go-to-top-color); } .footer span.go-to-top-icon > a::before { content: url("../images/go-to-top-icon.svg"); } .footer > span:first-child { margin-left: var(--horizontal-spacing-for-content); padding-left: 0; } .footer > span:last-child { margin-right: var(--horizontal-spacing-for-content); padding-right: 0; } .footer > span { padding: 0 16px; } .footer a { color: var(--breadcrumb-font-color); } .footer span.go-to-top-icon > #go-to-top-link { padding: 0; border: none; } .footer .padded-icon { padding-left: 0.5em; } .footer .padded-icon::before { content: url("../images/footer-go-to-link.svg"); } .pull-right { float: right; margin-left: auto } div.runnablesample { height: fit-content; } .anchor-highlight { border: 1px solid var(--hover-link-color) !important; box-shadow: 0 0 0 0.2em #c8e1ff; margin-top: 0.2em; margin-bottom: 0.2em; } .w-100 { width: 100%; } .no-gutters { margin: 0; padding: 0; } .d-flex { display: flex; } #theme-toggle { content: url("../images/theme-toggle.svg"); } #theme-toggle-button { width: 36px; height: 36px; display: inline-flex; justify-content: center; align-items: center; border-radius: 24px; margin-left: 16px; background-color: inherit; border: none; cursor: pointer; } #theme-toggle-button:hover { background: var(--white-10); } .filtered-message { margin: 25px; font-size: 20px; font-weight: bolder; } @media screen and (max-width: 1119px) { h1.cover { font-size: 48px; line-height: 48px; padding-bottom: 8px; } } @media screen and (max-width: 759px) { #main { max-width: 100%; } #leftColumn { position: fixed; margin-left: -280px; transition: margin .2s ease-out; z-index: 4; background: white; height: 100%; } #leftColumn.open { margin-left: 0; } #leftColumn.open ~ #main #searchBar { display: none; } #leftToggler { z-index: 5; font-size: 20px; transition: margin .2s ease-out; margin-right: 16px; color: var(--background-color); } #leftToggler .icon-toggler:hover { cursor: pointer; } #leftColumn.open ~ #main #leftToggler { margin-left: 280px; } .icon-toggler::before { content: "\2630"; } #leftColumn.open ~ #main .icon-toggler::before { content: "\2630"; padding-right: 0.5em; margin-left: -0.5em; } .main-content > * { margin-left: var(--mobile-horizontal-spacing-for-content); margin-right: var(--mobile-horizontal-spacing-for-content); } .navigation-wrapper { padding-left: var(--mobile-horizontal-spacing-for-content); padding-right: var(--mobile-horizontal-spacing-for-content); } #sideMenu { padding-bottom: 16px; overflow: auto; } h1.cover { font-size: 32px; line-height: 32px; } #theme-toggle-button { display: none; } }
{'content_hash': '2aa02fc62f4d552c2ec3b4597eacf1ed', 'timestamp': '', 'source': 'github', 'line_count': 1168, 'max_line_length': 164, 'avg_line_length': 20.694349315068493, 'alnum_prop': 0.6291837325720905, 'repo_name': 'ACRA/acra', 'id': '7ebf675ea82231aca80fe4942cf187ea20e5b646', 'size': '24171', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'web/static/javadoc/5.9.0/styles/style.css', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1328'}, {'name': 'Java', 'bytes': '16532'}, {'name': 'JavaScript', 'bytes': '5285'}, {'name': 'Kotlin', 'bytes': '407998'}, {'name': 'Shell', 'bytes': '199'}]}
import React from 'react'; class CollectionItem extends React.Component { constructor(props) { super(props); this.handleUpdate = this.handleUpdate.bind(this); } handleUpdate (e) { e.preventDefault(); // Update which row is highlighted this.props.updateCollection(this.props.id); } render () { const { activeCollectionId, id } = this.props; const isActive = activeCollectionId === id; const rowColorClasses = isActive ? 'blue inverted ui table' : ''; const baseButtonClasses = 'ui button CollectionItem__centered-button'; const buttonClasses = isActive ? 'inverted white ' + baseButtonClasses : baseButtonClasses; const buttonText = isActive ? 'Selected' : 'Choose'; return ( <tr className={rowColorClasses}> <td>{this.props.name}</td> <td>created by {this.props.createdBy}</td> <td> <button onClick={(e) => this.handleUpdate(e)} className={buttonClasses} > {buttonText} </button> </td> </tr> ) } } export default CollectionItem; // the name entered in input will need to go to the seeddata/database and then // show up in the dashboard games list first with its collection
{'content_hash': '06584eaf5de15f08627e5aa970e2d195', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 95, 'avg_line_length': 27.88888888888889, 'alnum_prop': 0.6366533864541832, 'repo_name': 'civicparty/legitometer', 'id': '5a4ed393933a11157f0bba3b50498e1de2c2b2e5', 'size': '1255', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'react-ui/src/components/Admin/CollectionItem.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14604'}, {'name': 'HTML', 'bytes': '1252'}, {'name': 'JavaScript', 'bytes': '45784'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>FST - Taylor Green</title> <meta name="description" content="Keep track of the statistics from Taylor Green. Average heat score, heat wins, heat wins percentage, epic heats road to the final"> <meta name="author" content=""> <link rel="apple-touch-icon" sizes="57x57" href="/favicon/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/favicon/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/favicon/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/favicon/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/favicon/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/favicon/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/favicon/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/favicon/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/favicon/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png"> <link rel="manifest" href="/manifest.json"> <meta name="msapplication-TileColor" content="#ffffff"> <meta name="msapplication-TileImage" content="/ms-icon-144x144.png"> <meta name="theme-color" content="#ffffff"> <meta property="og:title" content="Fantasy Surfing tips"/> <meta property="og:image" content="https://fantasysurfingtips.com/img/just_waves.png"/> <meta property="og:description" content="See how great Taylor Green is surfing this year"/> <!-- Bootstrap Core CSS - Uses Bootswatch Flatly Theme: https://bootswatch.com/flatly/ --> <link href="https://fantasysurfingtips.com/css/bootstrap.css" rel="stylesheet"> <!-- Custom CSS --> <link href="https://fantasysurfingtips.com/css/freelancer.css" rel="stylesheet"> <link href="https://cdn.datatables.net/plug-ins/1.10.7/integration/bootstrap/3/dataTables.bootstrap.css" rel="stylesheet" /> <!-- Custom Fonts --> <link href="https://fantasysurfingtips.com/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> <script src="https://code.jquery.com/jquery-2.x-git.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ujs/1.2.1/rails.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script src="https://www.w3schools.com/lib/w3data.js"></script> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-2675412311042802", enable_page_level_ads: true }); </script> </head> <body> <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v2.6"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <!-- Navigation --> <div w3-include-html="https://fantasysurfingtips.com/layout/header.html"></div> <!-- Header --> <div w3-include-html="https://fantasysurfingtips.com/layout/sponsor.html"></div> <section > <div class="container"> <div class="row"> <div class="col-sm-3 "> <div class="col-sm-2 "> </div> <div class="col-sm-8 "> <!-- <img src="http://fantasysurfingtips.com/img/surfers/tgre.png" class="img-responsive" alt=""> --> <h3 style="text-align:center;">Taylor Green</h3> <a href="https://twitter.com/share" class="" data-via="fansurfingtips"><i class="fa fa-twitter"></i> Share on Twitter</i></a> <br/> <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http%3A%2F%2Ffantasysurfingtips.com%2Fsurfers%2Ftgre&amp;src=sdkpreparse"><i class="fa fa-facebook"></i> Share on Facebook</a> </div> <div class="col-sm-2 "> </div> </div> <div class="col-sm-3 portfolio-item"> </div> <div class="col-sm-3 portfolio-item"> <h6 style="text-align:center;">Avg Heat Score (FST DATA)</h6> <h1 style="text-align:center;">5.03</h1> </div> </div> <hr/> <h4 style="text-align:center;" >Heat Stats (FST data)</h4> <div class="row"> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heats</h6> <h2 style="text-align:center;">1</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">Heat wins</h6> <h2 style="text-align:center;">0</h2> </div> <div class="col-sm-4 portfolio-item"> <h6 style="text-align:center;">HEAT WINS PERCENTAGE</h6> <h2 style="text-align:center;">0.0%</h2> </div> </div> <hr/> <h4 style="text-align:center;">Avg Heat Score progression</h4> <div id="avg_chart" style="height: 250px;"></div> <hr/> <h4 style="text-align:center;">Heat stats progression</h4> <div id="heat_chart" style="height: 250px;"></div> <hr/> <style type="text/css"> .heats-all{ z-index: 3; margin-left: 5px; cursor: pointer; } </style> <div class="container"> <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = "http://fantasysurfingtips.com/surfers/tgre"; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = '6137'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = '//fantasysurfingtips.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> </div> </section> <script type="text/javascript"> $('.heats-all').click(function(){ $('.heats-all-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('.heats-2016').click(function(){ $('.heats-2016-stat').css('display', 'none') $('#'+$(this).attr('id')+'-stat').css('display', 'block') }); $('document').ready(function(){ new Morris.Line({ // ID of the element in which to draw the chart. element: 'avg_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [{"year":"2018","avg":5.03,"avg_all":5.03}], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['avg', 'avg_all'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Avg score in year', 'Avg score FST DATA'] }); new Morris.Bar({ // ID of the element in which to draw the chart. element: 'heat_chart', // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [{"year":"2018","heats":1,"wins":0,"percs":"0.0%"}], // The name of the data record attribute that contains x-values. xkey: 'year', // A list of names of data record attributes that contain y-values. ykeys: ['heats', 'wins', 'percs'], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ['Heats surfed', 'Heats won', 'Winning percentage'] }); }); </script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> <!-- Footer --> <div w3-include-html="https://fantasysurfingtips.com/layout/footer.html"></div> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-74337819-1', 'auto'); // Replace with your property ID. ga('send', 'pageview'); </script> <script> w3IncludeHTML(); </script> <!-- jQuery --> <script src="https://fantasysurfingtips.com/js/jquery.js"></script> <script src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="https://fantasysurfingtips.com/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <script src="https://fantasysurfingtips.com/js/classie.js"></script> <script src="https://fantasysurfingtips.com/js/cbpAnimatedHeader.js"></script> <!-- Contact Form JavaScript --> <script src="https://fantasysurfingtips.com/js/jqBootstrapValidation.js"></script> <script src="https://fantasysurfingtips.com/js/contact_me.js"></script> <!-- Custom Theme JavaScript --> <script src="https://fantasysurfingtips.com/js/freelancer.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script> <script type="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script> </body> </html>
{'content_hash': '4299e6213d03584b5dee3e7af95b02f3', 'timestamp': '', 'source': 'github', 'line_count': 284, 'max_line_length': 295, 'avg_line_length': 39.63380281690141, 'alnum_prop': 0.6305970149253731, 'repo_name': 'chicofilho/fst', 'id': '4d66a488b7c4c841233a5db989bc70f0b71bb337', 'size': '11256', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'surfers/wqs/tgre.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '25157'}, {'name': 'HTML', 'bytes': '114679577'}, {'name': 'JavaScript', 'bytes': '43263'}, {'name': 'PHP', 'bytes': '1097'}]}
{-# LANGUAGE OverloadedStrings #-} {-| DRBD proc file parser This module holds the definition of the parser that extracts status information from the DRBD proc file. -} {- Copyright (C) 2012 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Storage.Drbd.Parser (drbdStatusParser, commaIntParser) where import Prelude () import Ganeti.Prelude import Control.Applicative ((<|>)) import qualified Data.Attoparsec.Text as A import qualified Data.Attoparsec.Combinator as AC import Data.Attoparsec.Text (Parser) import Data.List import Data.Maybe import Data.Text (Text, unpack) import Ganeti.Storage.Drbd.Types -- | Our own space-skipping function, because A.skipSpace also skips -- newline characters. It skips ZERO or more spaces, so it does not -- fail if there are no spaces. skipSpaces :: Parser () skipSpaces = A.skipWhile A.isHorizontalSpace -- | Skips spaces and the given string, then executes a parser and -- returns its result. skipSpacesAndString :: Text -> Parser a -> Parser a skipSpacesAndString s parser = skipSpaces *> A.string s *> parser -- | Predicate verifying (potentially bad) end of lines isBadEndOfLine :: Char -> Bool isBadEndOfLine c = (c == '\0') || A.isEndOfLine c -- | Takes a parser and returns it with the content wrapped in a Maybe -- object. The resulting parser never fails, but contains Nothing if -- it couldn't properly parse the string. optional :: Parser a -> Parser (Maybe a) optional parser = (Just <$> parser) <|> pure Nothing -- | The parser for a whole DRBD status file. drbdStatusParser :: [DrbdInstMinor] -> Parser DRBDStatus drbdStatusParser instMinor = DRBDStatus <$> versionInfoParser <*> deviceParser instMinor `AC.manyTill` A.endOfInput <* A.endOfInput -- | The parser for the version information lines. versionInfoParser :: Parser VersionInfo versionInfoParser = do versionF <- optional versionP apiF <- optional apiP protoF <- optional protoP srcVersionF <- optional srcVersion ghF <- fmap unpack <$> optional gh builderF <- fmap unpack <$> optional builder if isNothing versionF && isNothing apiF && isNothing protoF && isNothing srcVersionF && isNothing ghF && isNothing builderF then fail "versionInfo" else pure $ VersionInfo versionF apiF protoF srcVersionF ghF builderF where versionP = A.string "version:" *> skipSpaces *> fmap unpack (A.takeWhile $ not . A.isHorizontalSpace) apiP = skipSpacesAndString "(api:" . fmap unpack $ A.takeWhile (/= '/') protoP = A.string "/proto:" *> fmap Data.Text.unpack (A.takeWhile (/= ')')) <* A.takeTill A.isEndOfLine <* A.endOfLine srcVersion = A.string "srcversion:" *> AC.skipMany1 A.space *> fmap unpack (A.takeTill A.isEndOfLine) <* A.endOfLine gh = A.string "GIT-hash:" *> skipSpaces *> A.takeWhile (not . A.isHorizontalSpace) builder = skipSpacesAndString "build by" $ skipSpaces *> A.takeTill A.isEndOfLine <* A.endOfLine -- | The parser for a (multi-line) string representing a device. deviceParser :: [DrbdInstMinor] -> Parser DeviceInfo deviceParser instMinor = do _ <- additionalEOL deviceNum <- skipSpaces *> A.decimal <* A.char ':' cs <- skipSpacesAndString "cs:" connStateParser if cs == Unconfigured then do _ <- additionalEOL return $ UnconfiguredDevice deviceNum else do ro <- skipSpaces *> skipRoleString *> localRemoteParser roleParser ds <- skipSpacesAndString "ds:" $ localRemoteParser diskStateParser replicProtocol <- A.space *> A.anyChar io <- skipSpaces *> ioFlagsParser <* A.skipWhile isBadEndOfLine pIndicators <- perfIndicatorsParser syncS <- conditionalSyncStatusParser cs reS <- optional resyncParser act <- optional actLogParser _ <- additionalEOL let inst = find ((deviceNum ==) . dimMinor) instMinor iName = fmap dimInstName inst return $ DeviceInfo deviceNum cs ro ds replicProtocol io pIndicators syncS reS act iName where conditionalSyncStatusParser SyncSource = Just <$> syncStatusParser conditionalSyncStatusParser SyncTarget = Just <$> syncStatusParser conditionalSyncStatusParser _ = pure Nothing skipRoleString = A.string "ro:" <|> A.string "st:" resyncParser = skipSpacesAndString "resync:" additionalInfoParser actLogParser = skipSpacesAndString "act_log:" additionalInfoParser additionalEOL = A.skipWhile A.isEndOfLine -- | The parser for the connection state. connStateParser :: Parser ConnState connStateParser = standAlone <|> disconnecting <|> unconnected <|> timeout <|> brokenPipe <|> networkFailure <|> protocolError <|> tearDown <|> wfConnection <|> wfReportParams <|> connected <|> startingSyncS <|> startingSyncT <|> wfBitMapS <|> wfBitMapT <|> wfSyncUUID <|> syncSource <|> syncTarget <|> pausedSyncS <|> pausedSyncT <|> verifyS <|> verifyT <|> unconfigured where standAlone = A.string "StandAlone" *> pure StandAlone disconnecting = A.string "Disconnectiog" *> pure Disconnecting unconnected = A.string "Unconnected" *> pure Unconnected timeout = A.string "Timeout" *> pure Timeout brokenPipe = A.string "BrokenPipe" *> pure BrokenPipe networkFailure = A.string "NetworkFailure" *> pure NetworkFailure protocolError = A.string "ProtocolError" *> pure ProtocolError tearDown = A.string "TearDown" *> pure TearDown wfConnection = A.string "WFConnection" *> pure WFConnection wfReportParams = A.string "WFReportParams" *> pure WFReportParams connected = A.string "Connected" *> pure Connected startingSyncS = A.string "StartingSyncS" *> pure StartingSyncS startingSyncT = A.string "StartingSyncT" *> pure StartingSyncT wfBitMapS = A.string "WFBitMapS" *> pure WFBitMapS wfBitMapT = A.string "WFBitMapT" *> pure WFBitMapT wfSyncUUID = A.string "WFSyncUUID" *> pure WFSyncUUID syncSource = A.string "SyncSource" *> pure SyncSource syncTarget = A.string "SyncTarget" *> pure SyncTarget pausedSyncS = A.string "PausedSyncS" *> pure PausedSyncS pausedSyncT = A.string "PausedSyncT" *> pure PausedSyncT verifyS = A.string "VerifyS" *> pure VerifyS verifyT = A.string "VerifyT" *> pure VerifyT unconfigured = A.string "Unconfigured" *> pure Unconfigured -- | Parser for recognizing strings describing two elements of the -- same type separated by a '/'. The first one is considered local, -- the second remote. localRemoteParser :: Parser a -> Parser (LocalRemote a) localRemoteParser parser = LocalRemote <$> parser <*> (A.char '/' *> parser) -- | The parser for resource roles. roleParser :: Parser Role roleParser = primary <|> secondary <|> unknown where primary = A.string "Primary" *> pure Primary secondary = A.string "Secondary" *> pure Secondary unknown = A.string "Unknown" *> pure Unknown -- | The parser for disk states. diskStateParser :: Parser DiskState diskStateParser = diskless <|> attaching <|> failed <|> negotiating <|> inconsistent <|> outdated <|> dUnknown <|> consistent <|> upToDate where diskless = A.string "Diskless" *> pure Diskless attaching = A.string "Attaching" *> pure Attaching failed = A.string "Failed" *> pure Failed negotiating = A.string "Negotiating" *> pure Negotiating inconsistent = A.string "Inconsistent" *> pure Inconsistent outdated = A.string "Outdated" *> pure Outdated dUnknown = A.string "DUnknown" *> pure DUnknown consistent = A.string "Consistent" *> pure Consistent upToDate = A.string "UpToDate" *> pure UpToDate -- | The parser for I/O flags. ioFlagsParser :: Parser String ioFlagsParser = fmap unpack . A.takeWhile $ not . isBadEndOfLine -- | The parser for performance indicators. perfIndicatorsParser :: Parser PerfIndicators perfIndicatorsParser = PerfIndicators <$> skipSpacesAndString "ns:" A.decimal <*> skipSpacesAndString "nr:" A.decimal <*> skipSpacesAndString "dw:" A.decimal <*> skipSpacesAndString "dr:" A.decimal <*> skipSpacesAndString "al:" A.decimal <*> skipSpacesAndString "bm:" A.decimal <*> skipSpacesAndString "lo:" A.decimal <*> skipSpacesAndString "pe:" A.decimal <*> skipSpacesAndString "ua:" A.decimal <*> skipSpacesAndString "ap:" A.decimal <*> optional (skipSpacesAndString "ep:" A.decimal) <*> optional (skipSpacesAndString "wo:" A.anyChar) <*> optional (skipSpacesAndString "oos:" A.decimal) <* skipSpaces <* A.endOfLine -- | The parser for the syncronization status. syncStatusParser :: Parser SyncStatus syncStatusParser = do _ <- statusBarParser percent <- skipSpacesAndString "sync'ed:" $ skipSpaces *> A.double <* A.char '%' partSyncSize <- skipSpaces *> A.char '(' *> A.decimal totSyncSize <- A.char '/' *> A.decimal <* A.char ')' sizeUnit <- sizeUnitParser <* optional A.endOfLine timeToEnd <- skipSpacesAndString "finish:" $ skipSpaces *> timeParser sp <- skipSpacesAndString "speed:" $ skipSpaces *> commaIntParser <* skipSpaces <* A.char '(' <* commaIntParser <* A.char ')' w <- skipSpacesAndString "want:" ( skipSpaces *> (Just <$> commaIntParser) ) <|> pure Nothing sSizeUnit <- skipSpaces *> sizeUnitParser sTimeUnit <- A.char '/' *> timeUnitParser _ <- A.endOfLine return $ SyncStatus percent partSyncSize totSyncSize sizeUnit timeToEnd sp w sSizeUnit sTimeUnit -- | The parser for recognizing (and discarding) the sync status bar. statusBarParser :: Parser () statusBarParser = skipSpaces *> A.char '[' *> A.skipWhile (== '=') *> A.skipWhile (== '>') *> A.skipWhile (== '.') *> A.char ']' *> pure () -- | The parser for recognizing data size units (only the ones -- actually found in DRBD files are implemented). sizeUnitParser :: Parser SizeUnit sizeUnitParser = kilobyte <|> megabyte where kilobyte = A.string "K" *> pure KiloByte megabyte = A.string "M" *> pure MegaByte -- | The parser for recognizing time (hh:mm:ss). timeParser :: Parser Time timeParser = Time <$> h <*> m <*> s where h = A.decimal :: Parser Int m = A.char ':' *> A.decimal :: Parser Int s = A.char ':' *> A.decimal :: Parser Int -- | The parser for recognizing time units (only the ones actually -- found in DRBD files are implemented). timeUnitParser :: Parser TimeUnit timeUnitParser = second where second = A.string "sec" *> pure Second -- | Haskell does not recognise ',' as the thousands separator every 3 -- digits but DRBD uses it, so we need an ah-hoc parser. -- If a number beginning with more than 3 digits without a comma is -- parsed, only the first 3 digits are considered to be valid, the rest -- is not consumed, and left for further parsing. commaIntParser :: Parser Int commaIntParser = do first <- AC.count 3 A.digit <|> AC.count 2 A.digit <|> AC.count 1 A.digit allDigits <- commaIntHelper (read first) pure allDigits -- | Helper (triplet parser) for the commaIntParser commaIntHelper :: Int -> Parser Int commaIntHelper acc = nextTriplet <|> end where nextTriplet = do _ <- A.char ',' triplet <- AC.count 3 A.digit commaIntHelper $ acc * 1000 + (read triplet :: Int) end = pure acc :: Parser Int -- | Parser for the additional information provided by DRBD <= 8.0. additionalInfoParser::Parser AdditionalInfo additionalInfoParser = AdditionalInfo <$> skipSpacesAndString "used:" A.decimal <*> (A.char '/' *> A.decimal) <*> skipSpacesAndString "hits:" A.decimal <*> skipSpacesAndString "misses:" A.decimal <*> skipSpacesAndString "starving:" A.decimal <*> skipSpacesAndString "dirty:" A.decimal <*> skipSpacesAndString "changed:" A.decimal <* A.endOfLine
{'content_hash': '2ec425a4e0ff10d6cf8121e7c8a0ff1f', 'timestamp': '', 'source': 'github', 'line_count': 364, 'max_line_length': 76, 'avg_line_length': 37.67307692307692, 'alnum_prop': 0.6673959016991177, 'repo_name': 'onponomarev/ganeti', 'id': '8dee72c88a6d65dc7b15631d694f2b6c8f636ff2', 'size': '13713', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/Ganeti/Storage/Drbd/Parser.hs', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Haskell', 'bytes': '2639381'}, {'name': 'Python', 'bytes': '5967379'}, {'name': 'Shell', 'bytes': '118007'}]}
package fr.minuskube.inv.opener; import com.google.common.base.Preconditions; import fr.minuskube.inv.InventoryManager; import fr.minuskube.inv.SmartInventory; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; public class ChestInventoryOpener implements InventoryOpener { @Override public Inventory open(SmartInventory inv, Player player) { Preconditions.checkArgument(inv.getColumns() == 9, "The column count for the chest inventory must be 9, found: %s.", inv.getColumns()); Preconditions.checkArgument(inv.getRows() >= 1 && inv.getRows() <= 6, "The row count for the chest inventory must be between 1 and 6, found: %s", inv.getRows()); InventoryManager manager = inv.getManager(); Inventory handle = Bukkit.createInventory(player, inv.getRows() * inv.getColumns(), inv.getTitle()); fill(handle, manager.getContents(player).get()); player.openInventory(handle); return handle; } @Override public boolean supports(InventoryType type) { return type == InventoryType.CHEST || type == InventoryType.ENDER_CHEST; } }
{'content_hash': '337ecbfe0dcbcf1c33136405448049a9', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 108, 'avg_line_length': 36.470588235294116, 'alnum_prop': 0.7016129032258065, 'repo_name': 'MinusKube/SmartInvs', 'id': 'daed5fb33a9ed888c9c3b1a75722563c89598136', 'size': '1240', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/fr/minuskube/inv/opener/ChestInventoryOpener.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '36187'}]}
namespace draco { void MeshStripifier::GenerateStripsFromCorner(int local_strip_id, CornerIndex ci) { // Clear the storage for strip faces. strip_faces_[local_strip_id].clear(); // Start corner of the strip (where the strip starts). CornerIndex start_ci = ci; FaceIndex fi = corner_table_->Face(ci); // We need to grow the strip both forward and backward (2 passes). // Note that the backward pass can change the start corner of the strip (the // start corner is going to be moved to the end of the backward strip). for (int pass = 0; pass < 2; ++pass) { if (pass == 1) { // Backward pass. // Start the traversal from the B that is the left sibling of the next // corner to the start corner C = |start_ci|. // // *-------*-------*-------* // / \ / \C / \ / // / \ / \ / \ / // / \ / B\ / \ / // *-------*-------*-------* // // Perform the backward pass only when there is no attribute seam between // the initial face and the first face of the backward traversal. if (GetOppositeCorner(corner_table_->Previous(start_ci)) == kInvalidCornerIndex) { break; // Attribute seam or a boundary. } ci = corner_table_->Next(start_ci); ci = corner_table_->SwingLeft(ci); if (ci == kInvalidCornerIndex) { break; } fi = corner_table_->Face(ci); } int num_added_faces = 0; while (!is_face_visited_[fi]) { is_face_visited_[fi] = true; strip_faces_[local_strip_id].push_back(fi); ++num_added_faces; if (num_added_faces > 1) { // Move to the correct source corner to traverse to the next face. if (num_added_faces & 1) { // Odd number of faces added. ci = corner_table_->Next(ci); } else { // Even number of faces added. if (pass == 1) { // If we are processing the backward pass, update the start corner // of the strip on every even face reached (we cannot use odd faces // for start of the strip as the strips would start in a wrong // direction). start_ci = ci; } ci = corner_table_->Previous(ci); } } ci = GetOppositeCorner(ci); if (ci == kInvalidCornerIndex) { break; } fi = corner_table_->Face(ci); } // Strip end reached. if (pass == 1 && (num_added_faces & 1)) { // If we processed the backward strip and we add an odd number of faces to // the strip, we need to remove the last one as it cannot be used to start // the strip (the strip would start in a wrong direction from that face). is_face_visited_[strip_faces_[local_strip_id].back()] = false; strip_faces_[local_strip_id].pop_back(); } } strip_start_corners_[local_strip_id] = start_ci; // Reset all visited flags for all faces (we need to process other strips from // the given face before we choose the final strip that we are going to use). for (int i = 0; i < strip_faces_[local_strip_id].size(); ++i) { is_face_visited_[strip_faces_[local_strip_id][i]] = false; } } } // namespace draco
{'content_hash': '1b06b6d63c220296636f55d08b3534e0', 'timestamp': '', 'source': 'github', 'line_count': 86, 'max_line_length': 80, 'avg_line_length': 38.2906976744186, 'alnum_prop': 0.5614940783480109, 'repo_name': 'google/filament', 'id': 'f68062eba6861983606641272da65098d167c9cf', 'size': '3933', 'binary': False, 'copies': '9', 'ref': 'refs/heads/main', 'path': 'third_party/draco/src/draco/mesh/mesh_stripifier.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '2833995'}, {'name': 'Batchfile', 'bytes': '4607'}, {'name': 'C', 'bytes': '2796377'}, {'name': 'C#', 'bytes': '1099'}, {'name': 'C++', 'bytes': '7044879'}, {'name': 'CMake', 'bytes': '209759'}, {'name': 'CSS', 'bytes': '17232'}, {'name': 'Dockerfile', 'bytes': '2404'}, {'name': 'F#', 'bytes': '710'}, {'name': 'GLSL', 'bytes': '223763'}, {'name': 'Go', 'bytes': '61019'}, {'name': 'Groovy', 'bytes': '11811'}, {'name': 'HTML', 'bytes': '80095'}, {'name': 'Java', 'bytes': '780083'}, {'name': 'JavaScript', 'bytes': '90947'}, {'name': 'Kotlin', 'bytes': '345783'}, {'name': 'Objective-C', 'bytes': '55990'}, {'name': 'Objective-C++', 'bytes': '314291'}, {'name': 'Python', 'bytes': '76565'}, {'name': 'RenderScript', 'bytes': '1769'}, {'name': 'Ruby', 'bytes': '4436'}, {'name': 'Shell', 'bytes': '76965'}, {'name': 'TypeScript', 'bytes': '3293'}]}
require("../../BASE.js"); BASE.require.loader.setRoot("./"); BASE.require([ "BASE.testing.TestRunner", "BASE.testing.ConsoleOutput" ], function () { var testDirectory = process.argv[2]; if (testDirectory == null) { throw new Error("No test directory passed as an argument."); } var TestRunner = BASE.testing.TestRunner; var ConsoleOutput = BASE.testing.ConsoleOutput; var testRunner = new TestRunner(testDirectory); var consoleOutput = new ConsoleOutput(testRunner); testRunner.run(); });
{'content_hash': '82352acce83ad58b47f0b2fd77dbca7c', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 68, 'avg_line_length': 26.428571428571427, 'alnum_prop': 0.6522522522522523, 'repo_name': 'jaredjbarnes/WoodlandCreatures', 'id': 'c916a7034a85a94b712e0235aac80e82589f0d45', 'size': '557', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/weblib/lib/BASE/BASE/testing/ConsoleRunner.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '1370'}, {'name': 'CSS', 'bytes': '81480'}, {'name': 'HTML', 'bytes': '330325'}, {'name': 'JavaScript', 'bytes': '3583926'}, {'name': 'Shell', 'bytes': '1490'}]}
describe( 'iteration flag "params"', function () { it( 'should be an array', function () { var spy = sinon.spy(); genData(1, spy); spy.firstCall.args[3].params.should.be.an.instanceOf(Array); }); it( 'should be an array of all passed parameters', function () { var spyA = sinon.spy(), spyB = sinon.spy(), arg1 = {}, arg2 = 'foo' ; genData(1, arg2, spyA, arg1, spyB); spyA.firstCall.args[3].params .should.have.lengthOf(5) .and.satisfy(function (paramsArray) { return paramsArray[0] === 1 && paramsArray[1] === arg2 && paramsArray[2] === spyA && paramsArray[3] === arg1 && paramsArray[4] === spyB; }, 'params array values match the parameter order' ); }); });
{'content_hash': 'fbd4b7b020a99a3f8c10c389315586c8', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 66, 'avg_line_length': 28.107142857142858, 'alnum_prop': 0.5527318932655655, 'repo_name': 'bemson/genData', 'id': '6dd04b1a094fc25b11c48cfd2344551dc2fc9112', 'size': '787', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'test/iteration_flag_params.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '17056'}]}
/** * @class Ext.form.HtmlEditor * @extends Ext.form.Field * Provides a lightweight HTML Editor component. Some toolbar features are not supported by Safari and will be * automatically hidden when needed. These are noted in the config options where appropriate. * <br><br>The editor's toolbar buttons have tooltips defined in the {@link #buttonTips} property, but they are not * enabled by default unless the global {@link Ext.QuickTips} singleton is {@link Ext.QuickTips#init initialized}. * <br><br><b>Note: The focus/blur and validation marking functionality inherited from Ext.form.Field is NOT * supported by this editor.</b> * <br><br>An Editor is a sensitive component that can't be used in all spots standard fields can be used. Putting an Editor within * any element that has display set to 'none' can cause problems in Safari and Firefox due to their default iframe reloading bugs. * <br><br>Example usage: * <pre><code> // Simple example rendered with default options: Ext.QuickTips.init(); // enable tooltips new Ext.form.HtmlEditor({ renderTo: Ext.getBody(), width: 800, height: 300 }); // Passed via xtype into a container and with custom options: Ext.QuickTips.init(); // enable tooltips new Ext.Panel({ title: 'HTML Editor', renderTo: Ext.getBody(), width: 600, height: 300, frame: true, layout: 'fit', items: { xtype: 'htmleditor', enableColors: false, enableAlignments: false } }); </code></pre> * @constructor * Create a new HtmlEditor * @param {Object} config * @xtype htmleditor */ Ext.form.HtmlEditor = Ext.extend(Ext.form.Field, { /** * @cfg {Boolean} enableFormat Enable the bold, italic and underline buttons (defaults to true) */ enableFormat : true, /** * @cfg {Boolean} enableFontSize Enable the increase/decrease font size buttons (defaults to true) */ enableFontSize : true, /** * @cfg {Boolean} enableColors Enable the fore/highlight color buttons (defaults to true) */ enableColors : true, /** * @cfg {Boolean} enableAlignments Enable the left, center, right alignment buttons (defaults to true) */ enableAlignments : true, /** * @cfg {Boolean} enableLists Enable the bullet and numbered list buttons. Not available in Safari. (defaults to true) */ enableLists : true, /** * @cfg {Boolean} enableSourceEdit Enable the switch to source edit button. Not available in Safari. (defaults to true) */ enableSourceEdit : true, /** * @cfg {Boolean} enableLinks Enable the create link button. Not available in Safari. (defaults to true) */ enableLinks : true, /** * @cfg {Boolean} enableFont Enable font selection. Not available in Safari. (defaults to true) */ enableFont : true, /** * @cfg {String} createLinkText The default text for the create link prompt */ createLinkText : 'Please enter the URL for the link:', /** * @cfg {String} defaultLinkValue The default value for the create link prompt (defaults to http:/ /) */ defaultLinkValue : 'http:/'+'/', /** * @cfg {Array} fontFamilies An array of available font families */ fontFamilies : [ 'Arial', 'Courier New', 'Tahoma', 'Times New Roman', 'Verdana' ], defaultFont: 'tahoma', /** * @cfg {String} defaultValue A default value to be put into the editor to resolve focus issues (defaults to &#160; (Non-breaking space) in Opera and IE6, &#8203; (Zero-width space) in all other browsers). */ defaultValue: (Ext.isOpera || Ext.isIE6) ? '&#160;' : '&#8203;', // private properties actionMode: 'wrap', validationEvent : false, deferHeight: true, initialized : false, activated : false, sourceEditMode : false, onFocus : Ext.emptyFn, iframePad:3, hideMode:'offsets', defaultAutoCreate : { tag: "textarea", style:"width:500px;height:300px;", autocomplete: "off" }, // private initComponent : function(){ this.addEvents( /** * @event initialize * Fires when the editor is fully initialized (including the iframe) * @param {HtmlEditor} this */ 'initialize', /** * @event activate * Fires when the editor is first receives the focus. Any insertion must wait * until after this event. * @param {HtmlEditor} this */ 'activate', /** * @event beforesync * Fires before the textarea is updated with content from the editor iframe. Return false * to cancel the sync. * @param {HtmlEditor} this * @param {String} html */ 'beforesync', /** * @event beforepush * Fires before the iframe editor is updated with content from the textarea. Return false * to cancel the push. * @param {HtmlEditor} this * @param {String} html */ 'beforepush', /** * @event sync * Fires when the textarea is updated with content from the editor iframe. * @param {HtmlEditor} this * @param {String} html */ 'sync', /** * @event push * Fires when the iframe editor is updated with content from the textarea. * @param {HtmlEditor} this * @param {String} html */ 'push', /** * @event editmodechange * Fires when the editor switches edit modes * @param {HtmlEditor} this * @param {Boolean} sourceEdit True if source edit, false if standard editing. */ 'editmodechange' ) }, // private createFontOptions : function(){ var buf = [], fs = this.fontFamilies, ff, lc; for(var i = 0, len = fs.length; i< len; i++){ ff = fs[i]; lc = ff.toLowerCase(); buf.push( '<option value="',lc,'" style="font-family:',ff,';"', (this.defaultFont == lc ? ' selected="true">' : '>'), ff, '</option>' ); } return buf.join(''); }, /* * Protected method that will not generally be called directly. It * is called when the editor creates its toolbar. Override this method if you need to * add custom toolbar buttons. * @param {HtmlEditor} editor */ createToolbar : function(editor){ var items = []; var tipsEnabled = Ext.QuickTips && Ext.QuickTips.isEnabled(); function btn(id, toggle, handler){ return { itemId : id, cls : 'x-btn-icon', iconCls: 'x-edit-'+id, enableToggle:toggle !== false, scope: editor, handler:handler||editor.relayBtnCmd, clickEvent:'mousedown', tooltip: tipsEnabled ? editor.buttonTips[id] || undefined : undefined, overflowText: editor.buttonTips[id].title || undefined, tabIndex:-1 }; } if(this.enableFont && !Ext.isSafari2){ var fontSelectItem = new Ext.Toolbar.Item({ autoEl: { tag:'select', cls:'x-font-select', html: this.createFontOptions() } }); items.push( fontSelectItem, '-' ); } if(this.enableFormat){ items.push( btn('bold'), btn('italic'), btn('underline') ); } if(this.enableFontSize){ items.push( '-', btn('increasefontsize', false, this.adjustFont), btn('decreasefontsize', false, this.adjustFont) ); } if(this.enableColors){ items.push( '-', { itemId:'forecolor', cls:'x-btn-icon', iconCls: 'x-edit-forecolor', clickEvent:'mousedown', tooltip: tipsEnabled ? editor.buttonTips.forecolor || undefined : undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ allowReselect: true, focus: Ext.emptyFn, value:'000000', plain:true, listeners: { scope: this, select: function(cp, color){ this.execCmd('forecolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); this.deferFocus(); } }, clickEvent:'mousedown' }) }, { itemId:'backcolor', cls:'x-btn-icon', iconCls: 'x-edit-backcolor', clickEvent:'mousedown', tooltip: tipsEnabled ? editor.buttonTips.backcolor || undefined : undefined, tabIndex:-1, menu : new Ext.menu.ColorMenu({ focus: Ext.emptyFn, value:'FFFFFF', plain:true, allowReselect: true, listeners: { scope: this, select: function(cp, color){ if(Ext.isGecko){ this.execCmd('useCSS', false); this.execCmd('hilitecolor', color); this.execCmd('useCSS', true); this.deferFocus(); }else{ this.execCmd(Ext.isOpera ? 'hilitecolor' : 'backcolor', Ext.isWebKit || Ext.isIE ? '#'+color : color); this.deferFocus(); } } }, clickEvent:'mousedown' }) } ); } if(this.enableAlignments){ items.push( '-', btn('justifyleft'), btn('justifycenter'), btn('justifyright') ); } if(!Ext.isSafari2){ if(this.enableLinks){ items.push( '-', btn('createlink', false, this.createLink) ); } if(this.enableLists){ items.push( '-', btn('insertorderedlist'), btn('insertunorderedlist') ); } if(this.enableSourceEdit){ items.push( '-', btn('sourceedit', true, function(btn){ this.toggleSourceEdit(!this.sourceEditMode); }) ); } } // build the toolbar var tb = new Ext.Toolbar({ renderTo: this.wrap.dom.firstChild, items: items }); if (fontSelectItem) { this.fontSelect = fontSelectItem.el; this.mon(this.fontSelect, 'change', function(){ var font = this.fontSelect.dom.value; this.relayCmd('fontname', font); this.deferFocus(); }, this); } // stop form submits this.mon(tb.el, 'click', function(e){ e.preventDefault(); }); this.tb = tb; }, onDisable: function(){ this.wrap.mask(); Ext.form.HtmlEditor.superclass.onDisable.call(this); }, onEnable: function(){ this.wrap.unmask(); Ext.form.HtmlEditor.superclass.onEnable.call(this); }, setReadOnly: function(readOnly){ Ext.form.HtmlEditor.superclass.setReadOnly.call(this, readOnly); if(this.initialized){ this.setDesignMode(!readOnly); var bd = this.getEditorBody(); if(bd){ bd.style.cursor = this.readOnly ? 'default' : 'text'; } this.disableItems(readOnly); } }, /** * Protected method that will not generally be called directly. It * is called when the editor initializes the iframe with HTML contents. Override this method if you * want to change the initialization markup of the iframe (e.g. to add stylesheets). * * Note: IE8-Standards has unwanted scroller behavior, so the default meta tag forces IE7 compatibility */ getDocMarkup : function(){ return '<html><head><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;}</style></head><body></body></html>'; }, // private getEditorBody : function(){ var doc = this.getDoc(); return doc.body || doc.documentElement; }, // private getDoc : function(){ return Ext.isIE ? this.getWin().document : (this.iframe.contentDocument || this.getWin().document); }, // private getWin : function(){ return Ext.isIE ? this.iframe.contentWindow : window.frames[this.iframe.name]; }, // private onRender : function(ct, position){ Ext.form.HtmlEditor.superclass.onRender.call(this, ct, position); this.el.dom.style.border = '0 none'; this.el.dom.setAttribute('tabIndex', -1); this.el.addClass('x-hidden'); if(Ext.isIE){ // fix IE 1px bogus margin this.el.applyStyles('margin-top:-1px;margin-bottom:-1px;') } this.wrap = this.el.wrap({ cls:'x-html-editor-wrap', cn:{cls:'x-html-editor-tb'} }); this.createToolbar(this); this.disableItems(true); this.tb.doLayout(); this.createIFrame(); if(!this.width){ var sz = this.el.getSize(); this.setSize(sz.width, this.height || sz.height); } this.resizeEl = this.positionEl = this.wrap; }, createIFrame: function(){ var iframe = document.createElement('iframe'); iframe.name = Ext.id(); iframe.frameBorder = '0'; iframe.style.overflow = 'auto'; this.wrap.dom.appendChild(iframe); this.iframe = iframe; this.monitorTask = Ext.TaskMgr.start({ run: this.checkDesignMode, scope: this, interval:100 }); }, initFrame : function(){ Ext.TaskMgr.stop(this.monitorTask); var doc = this.getDoc(); this.win = this.getWin(); doc.open(); doc.write(this.getDocMarkup()); doc.close(); var task = { // must defer to wait for browser to be ready run : function(){ var doc = this.getDoc(); if(doc.body || doc.readyState == 'complete'){ Ext.TaskMgr.stop(task); this.setDesignMode(true); this.initEditor.defer(10, this); } }, interval : 10, duration:10000, scope: this }; Ext.TaskMgr.start(task); }, checkDesignMode : function(){ if(this.wrap && this.wrap.dom.offsetWidth){ var doc = this.getDoc(); if(!doc){ return; } if(!doc.editorInitialized || this.getDesignMode() != 'on'){ this.initFrame(); } } }, /* private * set current design mode. To enable, mode can be true or 'on', off otherwise */ setDesignMode : function(mode){ var doc ; if(doc = this.getDoc()){ if(this.readOnly){ mode = false; } doc.designMode = (/on|true/i).test(String(mode).toLowerCase()) ?'on':'off'; } }, // private getDesignMode : function(){ var doc = this.getDoc(); if(!doc){ return ''; } return String(doc.designMode).toLowerCase(); }, disableItems: function(disabled){ if(this.fontSelect){ this.fontSelect.dom.disabled = disabled; } this.tb.items.each(function(item){ if(item.getItemId() != 'sourceedit'){ item.setDisabled(disabled); } }); }, // private onResize : function(w, h){ Ext.form.HtmlEditor.superclass.onResize.apply(this, arguments); if(this.el && this.iframe){ if(Ext.isNumber(w)){ var aw = w - this.wrap.getFrameWidth('lr'); this.el.setWidth(aw); this.tb.setWidth(aw); this.iframe.style.width = Math.max(aw, 0) + 'px'; } if(Ext.isNumber(h)){ var ah = h - this.wrap.getFrameWidth('tb') - this.tb.el.getHeight(); this.el.setHeight(ah); this.iframe.style.height = Math.max(ah, 0) + 'px'; var bd = this.getEditorBody(); if(bd){ bd.style.height = Math.max((ah - (this.iframePad*2)), 0) + 'px'; } } } }, /** * Toggles the editor between standard and source edit mode. * @param {Boolean} sourceEdit (optional) True for source edit, false for standard */ toggleSourceEdit : function(sourceEditMode){ if(sourceEditMode === undefined){ sourceEditMode = !this.sourceEditMode; } this.sourceEditMode = sourceEditMode === true; var btn = this.tb.getComponent('sourceedit'); if(btn.pressed !== this.sourceEditMode){ btn.toggle(this.sourceEditMode); if(!btn.xtbHidden){ return; } } if(this.sourceEditMode){ this.disableItems(true); this.syncValue(); this.iframe.className = 'x-hidden'; this.el.removeClass('x-hidden'); this.el.dom.removeAttribute('tabIndex'); this.el.focus(); }else{ if(this.initialized){ this.disableItems(this.readOnly); } this.pushValue(); this.iframe.className = ''; this.el.addClass('x-hidden'); this.el.dom.setAttribute('tabIndex', -1); this.deferFocus(); } var lastSize = this.lastSize; if(lastSize){ delete this.lastSize; this.setSize(lastSize); } this.fireEvent('editmodechange', this, this.sourceEditMode); }, // private used internally createLink : function(){ var url = prompt(this.createLinkText, this.defaultLinkValue); if(url && url != 'http:/'+'/'){ this.relayCmd('createlink', url); } }, // private initEvents : function(){ this.originalValue = this.getValue(); }, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ markInvalid : Ext.emptyFn, /** * Overridden and disabled. The editor element does not support standard valid/invalid marking. @hide * @method */ clearInvalid : Ext.emptyFn, // docs inherit from Field setValue : function(v){ Ext.form.HtmlEditor.superclass.setValue.call(this, v); this.pushValue(); return this; }, /** * Protected method that will not generally be called directly. If you need/want * custom HTML cleanup, this is the method you should override. * @param {String} html The HTML to be cleaned * @return {String} The cleaned HTML */ cleanHtml: function(html) { html = String(html); if(Ext.isWebKit){ // strip safari nonsense html = html.replace(/\sclass="(?:Apple-style-span|khtml-block-placeholder)"/gi, ''); } /* * Neat little hack. Strips out all the non-digit characters from the default * value and compares it to the character code of the first character in the string * because it can cause encoding issues when posted to the server. */ if(html.charCodeAt(0) == this.defaultValue.replace(/\D/g, '')){ html = html.substring(1); } return html; }, /** * Protected method that will not generally be called directly. Syncs the contents * of the editor iframe with the textarea. */ syncValue : function(){ if(this.initialized){ var bd = this.getEditorBody(); var html = bd.innerHTML; if(Ext.isWebKit){ var bs = bd.getAttribute('style'); // Safari puts text-align styles on the body element! var m = bs.match(/text-align:(.*?);/i); if(m && m[1]){ html = '<div style="'+m[0]+'">' + html + '</div>'; } } html = this.cleanHtml(html); if(this.fireEvent('beforesync', this, html) !== false){ this.el.dom.value = html; this.fireEvent('sync', this, html); } } }, //docs inherit from Field getValue : function() { this[this.sourceEditMode ? 'pushValue' : 'syncValue'](); return Ext.form.HtmlEditor.superclass.getValue.call(this); }, /** * Protected method that will not generally be called directly. Pushes the value of the textarea * into the iframe editor. */ pushValue : function(){ if(this.initialized){ var v = this.el.dom.value; if(!this.activated && v.length < 1){ v = this.defaultValue; } if(this.fireEvent('beforepush', this, v) !== false){ this.getEditorBody().innerHTML = v; if(Ext.isGecko){ // Gecko hack, see: https://bugzilla.mozilla.org/show_bug.cgi?id=232791#c8 this.setDesignMode(false); //toggle off first } this.setDesignMode(true); this.fireEvent('push', this, v); } } }, // private deferFocus : function(){ this.focus.defer(10, this); }, // docs inherit from Field focus : function(){ if(this.win && !this.sourceEditMode){ this.win.focus(); }else{ this.el.focus(); } }, // private initEditor : function(){ //Destroying the component during/before initEditor can cause issues. try{ var dbody = this.getEditorBody(), ss = this.el.getStyles('font-size', 'font-family', 'background-image', 'background-repeat'), doc, fn; ss['background-attachment'] = 'fixed'; // w3c dbody.bgProperties = 'fixed'; // ie Ext.DomHelper.applyStyles(dbody, ss); doc = this.getDoc(); if(doc){ try{ Ext.EventManager.removeAll(doc); }catch(e){} } /* * We need to use createDelegate here, because when using buffer, the delayed task is added * as a property to the function. When the listener is removed, the task is deleted from the function. * Since onEditorEvent is shared on the prototype, if we have multiple html editors, the first time one of the editors * is destroyed, it causes the fn to be deleted from the prototype, which causes errors. Essentially, we're just anonymizing the function. */ fn = this.onEditorEvent.createDelegate(this); Ext.EventManager.on(doc, { mousedown: fn, dblclick: fn, click: fn, keyup: fn, buffer:100 }); if(Ext.isGecko){ Ext.EventManager.on(doc, 'keypress', this.applyCommand, this); } if(Ext.isIE || Ext.isWebKit || Ext.isOpera){ Ext.EventManager.on(doc, 'keydown', this.fixKeys, this); } doc.editorInitialized = true; this.initialized = true; this.pushValue(); this.setReadOnly(this.readOnly); this.fireEvent('initialize', this); }catch(e){} }, // private onDestroy : function(){ if(this.monitorTask){ Ext.TaskMgr.stop(this.monitorTask); } if(this.rendered){ Ext.destroy(this.tb); var doc = this.getDoc(); if(doc){ try{ Ext.EventManager.removeAll(doc); for (var prop in doc){ delete doc[prop]; } }catch(e){} } if(this.wrap){ this.wrap.dom.innerHTML = ''; this.wrap.remove(); } } if(this.el){ this.el.removeAllListeners(); this.el.remove(); } this.purgeListeners(); }, // private onFirstFocus : function(){ this.activated = true; this.disableItems(this.readOnly); if(Ext.isGecko){ // prevent silly gecko errors this.win.focus(); var s = this.win.getSelection(); if(!s.focusNode || s.focusNode.nodeType != 3){ var r = s.getRangeAt(0); r.selectNodeContents(this.getEditorBody()); r.collapse(true); this.deferFocus(); } try{ this.execCmd('useCSS', true); this.execCmd('styleWithCSS', false); }catch(e){} } this.fireEvent('activate', this); }, // private adjustFont: function(btn){ var adjust = btn.getItemId() == 'increasefontsize' ? 1 : -1, doc = this.getDoc(), v = parseInt(doc.queryCommandValue('FontSize') || 2, 10); if((Ext.isSafari && !Ext.isSafari2) || Ext.isChrome || Ext.isAir){ // Safari 3 values // 1 = 10px, 2 = 13px, 3 = 16px, 4 = 18px, 5 = 24px, 6 = 32px if(v <= 10){ v = 1 + adjust; }else if(v <= 13){ v = 2 + adjust; }else if(v <= 16){ v = 3 + adjust; }else if(v <= 18){ v = 4 + adjust; }else if(v <= 24){ v = 5 + adjust; }else { v = 6 + adjust; } v = v.constrain(1, 6); }else{ if(Ext.isSafari){ // safari adjust *= 2; } v = Math.max(1, v+adjust) + (Ext.isSafari ? 'px' : 0); } this.execCmd('FontSize', v); }, // private onEditorEvent : function(e){ this.updateToolbar(); }, /** * Protected method that will not generally be called directly. It triggers * a toolbar update by reading the markup state of the current selection in the editor. */ updateToolbar: function(){ if(this.readOnly){ return; } if(!this.activated){ this.onFirstFocus(); return; } var btns = this.tb.items.map, doc = this.getDoc(); if(this.enableFont && !Ext.isSafari2){ var name = (doc.queryCommandValue('FontName')||this.defaultFont).toLowerCase(); if(name != this.fontSelect.dom.value){ this.fontSelect.dom.value = name; } } if(this.enableFormat){ btns.bold.toggle(doc.queryCommandState('bold')); btns.italic.toggle(doc.queryCommandState('italic')); btns.underline.toggle(doc.queryCommandState('underline')); } if(this.enableAlignments){ btns.justifyleft.toggle(doc.queryCommandState('justifyleft')); btns.justifycenter.toggle(doc.queryCommandState('justifycenter')); btns.justifyright.toggle(doc.queryCommandState('justifyright')); } if(!Ext.isSafari2 && this.enableLists){ btns.insertorderedlist.toggle(doc.queryCommandState('insertorderedlist')); btns.insertunorderedlist.toggle(doc.queryCommandState('insertunorderedlist')); } Ext.menu.MenuMgr.hideAll(); this.syncValue(); }, // private relayBtnCmd : function(btn){ this.relayCmd(btn.getItemId()); }, /** * Executes a Midas editor command on the editor document and performs necessary focus and * toolbar updates. <b>This should only be called after the editor is initialized.</b> * @param {String} cmd The Midas command * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null) */ relayCmd : function(cmd, value){ (function(){ this.focus(); this.execCmd(cmd, value); this.updateToolbar(); }).defer(10, this); }, /** * Executes a Midas editor command directly on the editor document. * For visual commands, you should use {@link #relayCmd} instead. * <b>This should only be called after the editor is initialized.</b> * @param {String} cmd The Midas command * @param {String/Boolean} value (optional) The value to pass to the command (defaults to null) */ execCmd : function(cmd, value){ var doc = this.getDoc(); doc.execCommand(cmd, false, value === undefined ? null : value); this.syncValue(); }, // private applyCommand : function(e){ if(e.ctrlKey){ var c = e.getCharCode(), cmd; if(c > 0){ c = String.fromCharCode(c); switch(c){ case 'b': cmd = 'bold'; break; case 'i': cmd = 'italic'; break; case 'u': cmd = 'underline'; break; } if(cmd){ this.win.focus(); this.execCmd(cmd); this.deferFocus(); e.preventDefault(); } } } }, /** * Inserts the passed text at the current cursor position. Note: the editor must be initialized and activated * to insert text. * @param {String} text */ insertAtCursor : function(text){ if(!this.activated){ return; } if(Ext.isIE){ this.win.focus(); var doc = this.getDoc(), r = doc.selection.createRange(); if(r){ r.pasteHTML(text); this.syncValue(); this.deferFocus(); } }else{ this.win.focus(); this.execCmd('InsertHTML', text); this.deferFocus(); } }, // private fixKeys : function(){ // load time branching for fastest keydown performance if(Ext.isIE){ return function(e){ var k = e.getKey(), doc = this.getDoc(), r; if(k == e.TAB){ e.stopEvent(); r = doc.selection.createRange(); if(r){ r.collapse(true); r.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }else if(k == e.ENTER){ r = doc.selection.createRange(); if(r){ var target = r.parentElement(); if(!target || target.tagName.toLowerCase() != 'li'){ e.stopEvent(); r.pasteHTML('<br />'); r.collapse(false); r.select(); } } } }; }else if(Ext.isOpera){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.win.focus(); this.execCmd('InsertHTML','&nbsp;&nbsp;&nbsp;&nbsp;'); this.deferFocus(); } }; }else if(Ext.isWebKit){ return function(e){ var k = e.getKey(); if(k == e.TAB){ e.stopEvent(); this.execCmd('InsertText','\t'); this.deferFocus(); }else if(k == e.ENTER){ e.stopEvent(); this.execCmd('InsertHtml','<br /><br />'); this.deferFocus(); } }; } }(), /** * Returns the editor's toolbar. <b>This is only available after the editor has been rendered.</b> * @return {Ext.Toolbar} */ getToolbar : function(){ return this.tb; }, /** * Object collection of toolbar tooltips for the buttons in the editor. The key * is the command id associated with that button and the value is a valid QuickTips object. * For example: <pre><code> { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, ... </code></pre> * @type Object */ buttonTips : { bold : { title: 'Bold (Ctrl+B)', text: 'Make the selected text bold.', cls: 'x-html-editor-tip' }, italic : { title: 'Italic (Ctrl+I)', text: 'Make the selected text italic.', cls: 'x-html-editor-tip' }, underline : { title: 'Underline (Ctrl+U)', text: 'Underline the selected text.', cls: 'x-html-editor-tip' }, increasefontsize : { title: 'Grow Text', text: 'Increase the font size.', cls: 'x-html-editor-tip' }, decreasefontsize : { title: 'Shrink Text', text: 'Decrease the font size.', cls: 'x-html-editor-tip' }, backcolor : { title: 'Text Highlight Color', text: 'Change the background color of the selected text.', cls: 'x-html-editor-tip' }, forecolor : { title: 'Font Color', text: 'Change the color of the selected text.', cls: 'x-html-editor-tip' }, justifyleft : { title: 'Align Text Left', text: 'Align text to the left.', cls: 'x-html-editor-tip' }, justifycenter : { title: 'Center Text', text: 'Center text in the editor.', cls: 'x-html-editor-tip' }, justifyright : { title: 'Align Text Right', text: 'Align text to the right.', cls: 'x-html-editor-tip' }, insertunorderedlist : { title: 'Bullet List', text: 'Start a bulleted list.', cls: 'x-html-editor-tip' }, insertorderedlist : { title: 'Numbered List', text: 'Start a numbered list.', cls: 'x-html-editor-tip' }, createlink : { title: 'Hyperlink', text: 'Make the selected text a hyperlink.', cls: 'x-html-editor-tip' }, sourceedit : { title: 'Source Edit', text: 'Switch to source editing mode.', cls: 'x-html-editor-tip' } } // hide stuff that is not compatible /** * @event blur * @hide */ /** * @event change * @hide */ /** * @event focus * @hide */ /** * @event specialkey * @hide */ /** * @cfg {String} fieldClass @hide */ /** * @cfg {String} focusClass @hide */ /** * @cfg {String} autoCreate @hide */ /** * @cfg {String} inputType @hide */ /** * @cfg {String} invalidClass @hide */ /** * @cfg {String} invalidText @hide */ /** * @cfg {String} msgFx @hide */ /** * @cfg {String} validateOnBlur @hide */ /** * @cfg {Boolean} allowDomMove @hide */ /** * @cfg {String} applyTo @hide */ /** * @cfg {String} autoHeight @hide */ /** * @cfg {String} autoWidth @hide */ /** * @cfg {String} cls @hide */ /** * @cfg {String} disabled @hide */ /** * @cfg {String} disabledClass @hide */ /** * @cfg {String} msgTarget @hide */ /** * @cfg {String} readOnly @hide */ /** * @cfg {String} style @hide */ /** * @cfg {String} validationDelay @hide */ /** * @cfg {String} validationEvent @hide */ /** * @cfg {String} tabIndex @hide */ /** * @property disabled * @hide */ /** * @method applyToMarkup * @hide */ /** * @method disable * @hide */ /** * @method enable * @hide */ /** * @method validate * @hide */ /** * @event valid * @hide */ /** * @method setDisabled * @hide */ /** * @cfg keys * @hide */ }); Ext.reg('htmleditor', Ext.form.HtmlEditor);
{'content_hash': '44c14df6ef2f96c6721c51235f0754d5', 'timestamp': '', 'source': 'github', 'line_count': 1247, 'max_line_length': 209, 'avg_line_length': 30.982357658380113, 'alnum_prop': 0.4898149346447522, 'repo_name': 'regestaexe/OD', 'id': 'ef07bab3ffcb7dfa1e549126b6b9072d3118ee3e', 'size': '38759', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'WebContent/js/ext-js/widgets/form/HtmlEditor.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12316326'}, {'name': 'Java', 'bytes': '1011498'}, {'name': 'JavaScript', 'bytes': '33573288'}, {'name': 'Ruby', 'bytes': '24371'}, {'name': 'Shell', 'bytes': '47'}]}
import React, { PropTypes } from 'react'; import classnames from 'classnames'; const TextFieldGroup = ({ error, field, value, label, onChange, type, ion }) => { return ( <div className="single-input"> {ion ? <i className={classnames(ion, 'Login-ion')} /> : null} <input className={classnames({ 'input-txt': ion })} onChange={onChange} value={value} type={type} name={field} placeholder={label} /> { error && ion && <span className={classnames({ 'error': error })}>{error}</span>} </div> ); }; TextFieldGroup.propTypes = { field: PropTypes.string.isRequired, value: PropTypes.string.isRequired, label: PropTypes.string.isRequired, error: PropTypes.string, ion: PropTypes.string, type: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired }; TextFieldGroup.defaultProps = { type: 'text' }; export default TextFieldGroup;
{'content_hash': 'e4228fa9be5a08e4d008e1cf5ca99c64', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 88, 'avg_line_length': 27.470588235294116, 'alnum_prop': 0.6413276231263383, 'repo_name': 'YingQQQ/React-Blog', 'id': 'c2686c74397cefc337b65a7461f73c2f13168a69', 'size': '934', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/client/components/TextFieldGroup.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '24967'}, {'name': 'HTML', 'bytes': '1559'}, {'name': 'JavaScript', 'bytes': '42694'}]}
import {loadScript, validateData} from '../3p/3p'; /** * @param {!Window} global * @param {!Object} data */ export function kuadio(global, data) { validateData(data, ['widgetId'], ['region', 'baseUrl', 'betaMode', 'debugMode', 'fastParse']); global._pvmax = { region: data.region, baseUrl: data.baseUrl, betaMode: data.betaMode === 'true', debugMode: data.debugMode === 'true', fastParse: data.fastParse !== 'false', }; const e = global.document.createElement('div'); e.className = '_pvmax_recommend'; e.setAttribute('data-widget-id', data.widgetId); e.setAttribute('data-ref', window.context.canonicalUrl); global.document.getElementById('c').appendChild(e); loadScript(global, 'https://api.pvmax.net/v1.0/pvmax.js'); }
{'content_hash': 'aa301b20224e1f74f822b1612b7deb36', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 67, 'avg_line_length': 27.642857142857142, 'alnum_prop': 0.6563307493540051, 'repo_name': 'aghassemi/amphtml', 'id': '08b536473ed9670ed8e633656faf75966636626b', 'size': '1401', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'ads/kuadio.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '340017'}, {'name': 'Go', 'bytes': '15254'}, {'name': 'HTML', 'bytes': '1335168'}, {'name': 'Java', 'bytes': '37155'}, {'name': 'JavaScript', 'bytes': '12136559'}, {'name': 'Python', 'bytes': '72484'}, {'name': 'Shell', 'bytes': '21186'}, {'name': 'Yacc', 'bytes': '22627'}]}
import asyncio import json from aio_jsonrpc_20 import RequestResolver async def foo(msg, time): await asyncio.sleep(time) return 'foobar ' + str(msg) router = {'foo': foo} resolver = RequestResolver(router) json_request = json.dumps([ {"jsonrpc": "2.0", "method": "foo", "params": ["toto", 1], "id": 1}, {"jsonrpc": "2.0", "method": "foo", "params": ["tata", 0.5], "id": 2}, {"jsonrpc": "2.0", "method": "foo", "params": ["tutu", 0.5], "id": 3}, ]) async def main(): json_response = await resolver.handle(json_request) print(json_response) loop = asyncio.get_event_loop() loop.run_until_complete(main())
{'content_hash': 'c1df55d98636af3bce0587a007a36d5e', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 74, 'avg_line_length': 25.56, 'alnum_prop': 0.6165884194053208, 'repo_name': 'steffgrez/aio-jsonrpc-2.0', 'id': '44369a610a0fb7b5a001b56465745c404304e44b', 'size': '639', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'exemples/batch_resolver.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '29695'}]}
<?php use \Httpful\Request; use Underscore\Types\Arrays; class WikidataItem { const WIKIDATA_ENDPOINT = "%s/wikidata/entity?q=%s&lang=%s"; private $qid, $item, $lang; function __construct($qid, $lang) { $this->qid = $qid; $this->lang = $lang; $this->item = $this->getItem(); } public function addValues($properties) { foreach ($properties as $key => $pid) { $this->item->{$key} = $this->getClaimValues($pid); } } private function getClaimValues($pid) { $claim = $this->getClaim($pid); if (!$claim) return false; $values = array_map(function($value) { if ($value->datatype == "globe-coordinate") { return $value->value; } if ($value->datatype == "time") { $time = $this->parseProlepticDate($value->value->time); return date_parse($time); } if ($value->datatype == "wikibase-item") { return [ "label" => isset($value->value_labels) ? $value->value_labels : false, "id" => $value->value ]; } if ($value->datatype == "string") { return $value->value; } return false; }, $claim->values); // Remove empty labels return array_filter($values); } // HACK: This is really, pretty ugly // See < https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar > private function parseProlepticDate($str) { $date = substr($str, 1); return ltrim($date, '0'); } public function getItemData() { return $this->item; } public function getClaim($pid) { if (!isset($this->item->claims)) return false; foreach ($this->item->claims as $claim) { if ($claim->property_id == $pid) { return $claim; } } return false; } public function hasClaimWhere($queries) { foreach ($queries as $query) { foreach ($query as $propid => $itemid) { $prop = $this->getClaim($propid); if (!$prop) continue; foreach ($prop->values as $value) { if ($value->value == $itemid) { return true; } } } } return false; } private function getItem() { $url = sprintf(self::WIKIDATA_ENDPOINT, API_ENDPOINT, $this->qid, $this->lang); $res = Request::get($url)->send(); if ($res->code == 500) { throw new Exception("Could not connect to API", 500); } if (!$res->body->response) { throw new Exception("This item does not exist", 404); } return reset($res->body->response); } }
{'content_hash': 'f97a8d75125afde7e11f99f6c4c9cb53', 'timestamp': '', 'source': 'github', 'line_count': 109, 'max_line_length': 90, 'avg_line_length': 26.71559633027523, 'alnum_prop': 0.4848901098901099, 'repo_name': 'hay/sum', 'id': '0f4ecd2f4d8c7c5050309c8335edd57db6c2a20d', 'size': '2912', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/lib/class-wikidataitem.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '294'}, {'name': 'CSS', 'bytes': '4023'}, {'name': 'HTML', 'bytes': '24569'}, {'name': 'JavaScript', 'bytes': '3450'}, {'name': 'PHP', 'bytes': '19872'}, {'name': 'Ruby', 'bytes': '139'}, {'name': 'Shell', 'bytes': '339'}]}
A Jupyter notebook that summarizes info from your boards.
{'content_hash': 'c9e8f4119f3b125540cf508aef83940c', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 58, 'avg_line_length': 59.0, 'alnum_prop': 0.8135593220338984, 'repo_name': 'colarusso/trello-sum', 'id': '8dd5dbd7a45b648e33f1f70b42ae6bc32f19e91f', 'size': '72', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4958'}, {'name': 'Jupyter Notebook', 'bytes': '26456'}]}
<?php namespace Sheepla\Response\Shipment; use JMS\Serializer\Annotation as JMS; use Sheepla\Response\AbstractResponse; class ShipmentByEDTN extends AbstractResponse { /** * @var string * @JMS\Type("string") * @JMS\XmlAttribute() * @JMS\AccessType("public_method") */ private $edtn; /** * @var string * @JMS\Type("string") * @JMS\XmlElement(cdata=false) * @JMS\AccessType("public_method") */ private $shipmentLabelLink; /** * Get EDTN * * @return string */ public function getEdtn() { return $this->edtn; } /** * Set EDTN * * @param mixed $edtn */ public function setEdtn($edtn) { $this->edtn = $edtn; return $this; } /** * Get shipment label link * * @return string */ public function getShipmentLabelLink() { return $this->shipmentLabelLink; } /** * Set shipment label link * * @param string $shipmentLabelLink * * @return $this */ public function setShipmentLabelLink($shipmentLabelLink) { $this->shipmentLabelLink = $shipmentLabelLink; return $this; } }
{'content_hash': 'e95d1e175b36baaf37109d37ce9f20fd', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 60, 'avg_line_length': 17.3943661971831, 'alnum_prop': 0.551417004048583, 'repo_name': 'shwrm/sheepla-sdk-php', 'id': 'b09cc9230f0642f3aa25ce8b7734594ea7e1e9b2', 'size': '1235', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Response/Shipment/ShipmentByEDTN.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '90324'}]}
#include <QApplication> #include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #if QT_VERSION >= 0x050000 #include <QUrlQuery> #else #include <QUrl> #endif #include <QTextDocument> // for Qt::mightBeRichText #include <QAbstractItemView> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin URI if(!uri.isValid() || uri.scheme() != QString("CompuCoin")) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("CompuCoin://")) { uri.replace(0, 11, "CompuCoin:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item (global clipboard) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Clipboard); // Copy first item (global mouse selection for e.g. X11 - NOP on Windows) QApplication::clipboard()->setText(selection.at(0).data(role).toString(), QClipboard::Selection); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "CompuCoin.lnk"; } bool GetStartOnSystemStartup() { // check for Bitcoin.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "CompuCoin.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=CompuCoin\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, NULL); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = NULL; LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, NULL); if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return NULL; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, bitcoinAppUrl, NULL, NULL); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("CompuCoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " CompuCoin-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("CompuCoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stdout, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On Windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
{'content_hash': '74945854153c0c4ef9c865bae82809ab', 'timestamp': '', 'source': 'github', 'line_count': 535, 'max_line_length': 123, 'avg_line_length': 30.429906542056074, 'alnum_prop': 0.6367321867321867, 'repo_name': 'taimpal/Compucoin-source-code', 'id': 'f37c82d78c172988723f5272831e5315e5822dfe', 'size': '16280', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/qt/guiutil.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '92223'}, {'name': 'C++', 'bytes': '2529054'}, {'name': 'CSS', 'bytes': '1127'}, {'name': 'IDL', 'bytes': '14696'}, {'name': 'Objective-C++', 'bytes': '5864'}, {'name': 'Python', 'bytes': '37270'}, {'name': 'Shell', 'bytes': '10010'}, {'name': 'TypeScript', 'bytes': '5229559'}]}
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="keywords" content="W3C SVG 1.1 2nd Edition Test Suite"/> <meta name="description" content="W3C SVG 1.1 2nd Edition Object Test Suite"/> <title> </title> <style type="text/css"> <!-- .bodytext { font-family:verdana, helvetica, sans-serif; font-size: 12pt; line-height: 125%; text-align: Left; margin-top: 0; margin-bottom: 0 } .pageTitle { line-height: 150%; font-size: 20pt; font-weight : 900; margin-bottom: 20pt } .pageSubTitle { color : blue; line-height: 100%; font-size: 24pt; font-weight : 900 } .openChapter { color : blue; line-height: 125%; font-weight : 900 } .openSection { color : blue; line-height: 125%; font-weight : 900 } .info { color : black; line-height: 110%; font-size: 10pt; font-weight : 100 } p { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } blockquote { margin-top:0; margin-bottom:0; padding-top:0; padding-bottom:0 } .opscript { margin-left: 3%; margin-right: 3%; } .opscript p { margin-top: 0.7em } .navbar { background: black; color: white; font-weight: bold } a,a:visited { color: blue } --> </style> </head> <body class="bodytext"> <table align="center" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" colspan="3"> <table border="0" cellpadding="8"> <tr> </tr> <tr class="navbar"> <td align="center"> SVG Image - The test </td> <td align="center"> PNG Image - The reference </td> </tr> <tr> <td align="right" > <object id="test" data="http://t/core/standards/SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/svg/test/painting-marker-properties-01-f.svg" width="480" height="360" type="image/svg+xml"> </object> </td> <td align="left"> <img id="ref" alt="raster image of painting-marker-properties-01-f.svg" src="http://t/core/standards/SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/svg/ref/painting-marker-properties-01-f.png " width="480" height="360"/> </td> </tr> </table> </td> </tr> </table> </div> </div> </body> </html> </body> </html>
{'content_hash': 'c9ba26f27e1aefc8c77e51f32f42101a', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 242, 'avg_line_length': 37.859154929577464, 'alnum_prop': 0.5695684523809523, 'repo_name': 'Ms2ger/presto-testo', 'id': '13106152364311e38c736e29980ed2b26bbed497', 'size': '2688', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'SVG/Testsuites/W3C-1_1F2/harness/htmlObjectMini/modified/painting-marker-properties-01-f.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '2312'}, {'name': 'ActionScript', 'bytes': '23470'}, {'name': 'AutoHotkey', 'bytes': '8832'}, {'name': 'Batchfile', 'bytes': '5001'}, {'name': 'C', 'bytes': '116512'}, {'name': 'C++', 'bytes': '219233'}, {'name': 'CSS', 'bytes': '207914'}, {'name': 'Erlang', 'bytes': '18523'}, {'name': 'Groff', 'bytes': '674'}, {'name': 'HTML', 'bytes': '103272540'}, {'name': 'Haxe', 'bytes': '3874'}, {'name': 'Java', 'bytes': '125658'}, {'name': 'JavaScript', 'bytes': '22516936'}, {'name': 'Makefile', 'bytes': '13409'}, {'name': 'PHP', 'bytes': '524911'}, {'name': 'Perl', 'bytes': '321672'}, {'name': 'Python', 'bytes': '948191'}, {'name': 'Ruby', 'bytes': '1006850'}, {'name': 'Shell', 'bytes': '12140'}, {'name': 'Smarty', 'bytes': '1860'}, {'name': 'XSLT', 'bytes': '2567445'}]}
package com.facebook.buck.core.rules.impl; import com.facebook.buck.core.build.buildable.context.BuildableContext; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.cell.CellPathResolver; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.BuildTargetFactory; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.BuildRuleParams; import com.facebook.buck.core.rules.TestBuildRuleParams; import com.facebook.buck.core.rules.attr.SupportsDependencyFileRuleKey; import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem; import com.facebook.buck.step.Step; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.nio.file.Path; import java.util.function.Predicate; import javax.annotation.Nullable; /** A fake {@link BuildRule} that implements {@link SupportsDependencyFileRuleKey}. */ public class FakeDepFileBuildRule extends AbstractBuildRuleWithDeclaredAndExtraDeps implements SupportsDependencyFileRuleKey { private Path outputPath; private Predicate<SourcePath> coveredPredicate = (SourcePath path) -> true; private Predicate<SourcePath> interestingPredicate = (SourcePath path) -> false; private ImmutableList<SourcePath> actualInputPaths = ImmutableList.of(); public FakeDepFileBuildRule(String fullyQualifiedName) { this(BuildTargetFactory.newInstance(fullyQualifiedName)); } public FakeDepFileBuildRule(BuildTarget target) { this(target, new FakeProjectFilesystem(), TestBuildRuleParams.create()); } public FakeDepFileBuildRule( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams buildRuleParams) { super(buildTarget, projectFilesystem, buildRuleParams); } public FakeDepFileBuildRule setOutputPath(Path outputPath) { this.outputPath = outputPath; return this; } public FakeDepFileBuildRule setCoveredByDepFilePredicate(ImmutableSet<SourcePath> coveredPaths) { return setCoveredByDepFilePredicate(coveredPaths::contains); } public FakeDepFileBuildRule setCoveredByDepFilePredicate(Predicate<SourcePath> coveredPredicate) { this.coveredPredicate = coveredPredicate; return this; } public FakeDepFileBuildRule setExistenceOfInterestPredicate( ImmutableSet<SourcePath> interestingPaths) { return setExistenceOfInterestPredicate(interestingPaths::contains); } public FakeDepFileBuildRule setExistenceOfInterestPredicate( Predicate<SourcePath> interestingPredicate) { this.interestingPredicate = interestingPredicate; return this; } public FakeDepFileBuildRule setInputsAfterBuildingLocally( ImmutableList<SourcePath> actualInputPaths) { this.actualInputPaths = actualInputPaths; return this; } @Override public boolean useDependencyFileRuleKeys() { return true; } @Override public Predicate<SourcePath> getCoveredByDepFilePredicate(SourcePathResolver pathResolver) { return coveredPredicate; } @Override public Predicate<SourcePath> getExistenceOfInterestPredicate(SourcePathResolver pathResolver) { return interestingPredicate; } @Override public ImmutableList<SourcePath> getInputsAfterBuildingLocally( BuildContext context, CellPathResolver cellPathResolver) { return actualInputPaths; } @Override public ImmutableList<Step> getBuildSteps( BuildContext context, BuildableContext buildableContext) { return ImmutableList.of(); } @Nullable @Override public SourcePath getSourcePathToOutput() { if (outputPath == null) { return null; } return ExplicitBuildTargetSourcePath.of(getBuildTarget(), outputPath); } }
{'content_hash': '9bdc52dcad95740416c05897aff67d5d', 'timestamp': '', 'source': 'github', 'line_count': 116, 'max_line_length': 100, 'avg_line_length': 34.46551724137931, 'alnum_prop': 0.7983991995997999, 'repo_name': 'brettwooldridge/buck', 'id': '012e38b5f8a76929adb20058ef23d86fce5aabd5', 'size': '4603', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'test/com/facebook/buck/core/rules/impl/FakeDepFileBuildRule.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1585'}, {'name': 'Batchfile', 'bytes': '3875'}, {'name': 'C', 'bytes': '280326'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '18771'}, {'name': 'CSS', 'bytes': '56106'}, {'name': 'D', 'bytes': '1017'}, {'name': 'Dockerfile', 'bytes': '2081'}, {'name': 'Go', 'bytes': '9822'}, {'name': 'Groovy', 'bytes': '3362'}, {'name': 'HTML', 'bytes': '10916'}, {'name': 'Haskell', 'bytes': '1008'}, {'name': 'IDL', 'bytes': '480'}, {'name': 'Java', 'bytes': '28622919'}, {'name': 'JavaScript', 'bytes': '938678'}, {'name': 'Kotlin', 'bytes': '23444'}, {'name': 'Lex', 'bytes': '7502'}, {'name': 'MATLAB', 'bytes': '47'}, {'name': 'Makefile', 'bytes': '1916'}, {'name': 'OCaml', 'bytes': '4935'}, {'name': 'Objective-C', 'bytes': '176943'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '2244'}, {'name': 'Python', 'bytes': '2069290'}, {'name': 'Roff', 'bytes': '1207'}, {'name': 'Rust', 'bytes': '5214'}, {'name': 'Scala', 'bytes': '5082'}, {'name': 'Shell', 'bytes': '76854'}, {'name': 'Smalltalk', 'bytes': '194'}, {'name': 'Swift', 'bytes': '11393'}, {'name': 'Thrift', 'bytes': '47828'}, {'name': 'Yacc', 'bytes': '323'}]}
<?php /** * DooViewBasic class file. * * @package doo.view * @since 1.3 */ class DooViewBasic { public $controller; public $data; protected static $forceCompile = false; protected static $safeVariableResult = null; protected static $uniqueId = 0; protected $tags; protected $mainRenderFolder; protected $tagClassName; protected $tagModuleName; protected $tagBlock_start = '{%'; protected $tagBlock_end = '%}'; protected $tagVariable_start = '{{'; protected $tagVariable_end = '}}'; protected $tagComment_start = '{#'; protected $tagComment_end = '#}'; protected $layoutFileName = 'layout'; protected $rootViewPath = null; protected $defaultRootViewPath = null; protected $rootCompiledPath = null; protected $relativeViewPath = ''; protected $usingRecursiveRender = false; protected $filterFunctionPrefix = 'filter_'; protected $useSafeVariableAccess = false; protected $fileManager = null; public function __construct() { Doo::loadHelper('DooFile'); $this->fileManager = new DooFile(0777); $this->defaultRootViewPath = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'view/'; $this->rootViewPath = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'view/'; $this->rootCompiledPath = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'viewc/'; if (self::$uniqueId == 0) { self::$uniqueId = time(); } } /** * Specify the root folder where default views should reside. Will look here if view not found in main folder * This must be the FULL PATH and not relative * @param string $path The path to the folder where the views should be found. Should include / at the end */ public function setDefaultRootViewPath($path) { $this->defaultRootViewPath = $path; } /** * Specify the root folder where views should reside. Will look here first for a view before trying default path * This must be the FULL PATH and not relative * @param string $path The path to the folder where the views should be found. Should include / at the end */ public function setRootViewPath($path) { $this->rootViewPath = $path; } /** * Specify the root folder where compiled views should reside. * This must be the FULL PATH and not relative * @param string $path The root path where the compiled files should be stored */ public function setRootCompiledPath($path) { $this->rootCompiledPath = $path; } /** * Specify the prefix string to be appended to filter functions * For example if the prefix is 'filter_' and you use a filter foo|default then in your TemplateTags your * function would be called filter_default * * @param string $prefix the prefix to prepend to filter function calls */ public function setFilterFunctionPrefix($prefix = 'filter_') { $this->filterFunctionPrefix = $prefix; } /** * Specify the name of the layout file to be used for processing this request * @param string $filename name of the layout file including extension. Eg 'layout.html' */ public function setLayoutFileName($filename) { $this->layoutFileName = $filename; } /** * If you want to ensure that you do not have php_warnings triggered when a user * attempts to access a variable which is not defined within the scope of the * template you can enable the safe variable access which will check that a given * variable is defined and if its not it will return the $defaultValue * @param bool $enable Should safe variable access be enabled? * @param mixed $defaultValue Default result returned when variable is not set */ public function enableSafeVariableAccess($enable = true, $defaultValue = null) { $this->useSafeVariableAccess = $enable; DooViewBasic::$safeVariableResult = $defaultValue; } /** * Set the start and end tags for blocks. These are things like if, else, for, endif, endfor etc... * @param string $startTag The start tag. Defaults to {% * @param string $endTag The end tag. Defaults to %} */ public function setBlockTags($startTag, $endTag) { $this->tagBlock_start = $startTag; $this->tagBlock_end = $endTag; } /** * Set the start and end tags for variable and funcction output. These are things like {{foo.bar}} * @param string $startTag The start tag. Defaults to {{ * @param string $endTag The end tag. Defaults to }} */ public function setVariableTags($startTag, $endTag) { $this->tagVariable_start = $startTag; $this->tagVariable_end = $endTag; } /** * Set the start and end tags for comments. For example {# I am a comment #} * @param string $startTag The start tag. Defaults to {# * @param string $endTag The end tag. Defaults to #} */ public function setCommentTags($startTag, $endTag) { $this->tagComment_start = $startTag; $this->tagComment_end = $endTag; } /** * Determine which class to use as template tag. * * If $module is equal to '/', the main app's template tag class will be used. * * @param string $class Template tag class name * @param string $module Folder name of the module. Define this module name if the tag class is from another module. */ public function setTagClass($class, $module=null){ $this->tagClassName = $class; $this->tagModuleName = $module; } /** * Includes the native PHP template file to be output. * * @param string $file PHP template file name without extension .php * @param array $data Associative array of the data to be used in the template view. * @param object $controller The controller object, pass this in so that in views you can access the controller. * @param bool $includeTagClass If true, DooView will determine which Template tag class to include. Else, no files will be loaded */ public function renderc($file, $data=NULL, $controller=NULL, $includeTagClass=TRUE){ $this->data = $data; $this->controller = $controller; if($includeTagClass===TRUE) $this->loadTagClass(); include $this->rootCompiledPath . $file . '.php'; } /** * Include template view files * @param string $file File name without extension (.php) */ public function inc($file){ include $this->rootCompiledPath . $file . '.php'; } public function __call($name, $arguments) { if($this->controller!=NULL){ return call_user_func_array(array(&$this->controller, $name), $arguments); } } public function __get($name) { if($this->controller!=NULL){ return $this->controller->{$name}; } } /** * Writes the generated output produced by render() to file. * @param string $path Path to save the generated output. * @param string $templatefile Template file name (without extension name) * @param array $data Associative array of the data to be used in the Template file. eg. <b>$data['username']</b>, you should use <b>{{username}}</b> in the template. * @return string|false The file name of the rendered output saved (html). */ public function saveRendered($path, $templatefile, $data=NULL){ ob_start(); $this->render($templatefile, $data, null, true); $data = ob_get_contents(); ob_end_clean(); if(file_put_contents($path, $data)>0){ $filename = explode('/',$path); return $filename[sizeof($filename)-1]; } return false; } /** * Writes the generated output produced by renderc() to file. * @param string $path Path to save the generated output. * @param string $templatefile Template file name (without extension name) * @param array $data Associative array of the data to be used in the Template file. eg. <b>$data['username']</b>, you should use <b>{{username}}</b> in the template. * @param object $controller The controller object, pass this in so that in views you can access the controller. * @param bool $includeTagClass If true, DooView will determine which Template tag class to include. Else, no files will be loaded * @return string|false The file name of the rendered output saved (html). */ public function saveRenderedC($path, $templatefile, $data=NULL, $controller=NULL, $includeTagClass=TRUE){ ob_start(); $this->renderc($templatefile, $data, $controller, $includeTagClass); $data = ob_get_contents(); ob_end_clean(); if(file_put_contents($path, $data)>0){ $filename = explode('/',$path); return $filename[sizeof($filename)-1]; } return false; } /** * Renders the view file, generates compiled version of the view template if necessary * @param string $file Template file name (without extension name) * @param array $data Associative array of the data to be used in the Template file. eg. <b>$data['username']</b>, you should use <b>{{username}}</b> in the template. * @param bool $process If TRUE, checks the template's last modified time against the compiled version. Regenerates if template is newer. * @param bool $forceCompile Ignores last modified time checking and force compile the template everytime it is visited. */ public function render($file, $data=NULL, $process=NULL, $forceCompile=false){ if(isset(Doo::conf()->TEMPLATE_COMPILE_ALWAYS) && Doo::conf()->TEMPLATE_COMPILE_ALWAYS==true){ $process = $forceCompile = true; } //if process not set, then check the app mode, if production mode, skip the process(false) and just include the compiled files else if($process===NULL){ $process = (Doo::conf()->APP_MODE!='prod'); } self::$forceCompile = $forceCompile; $this->usingRecursiveRender = false; $this->mainRenderFolder = substr($file, 0, strrpos('/', $file)); if($process == false){ $this->loadTagClass(); include $this->rootCompiledPath . $file . '.php'; } else { $cfilename = $this->rootCompiledPath . $file . '.php'; if (file_exists($this->rootViewPath . $file . '.html')) { $vfilename = $this->rootViewPath . $file . '.html'; } else { $vfilename = $this->defaultRootViewPath . $file . '.html'; } //if file exist and is not older than the html template file, include the compiled php instead and exit the function if(!$forceCompile){ if(file_exists($cfilename)){ if(filemtime($cfilename)>=filemtime($vfilename)){ $this->setTags(); include $cfilename; return; } } } $this->data = $data; $this->compile($file, $vfilename, $cfilename); include $cfilename; } } /** * Recursivly searches for $file.html in relative folder. If not found in there * it goes up a directory in relative path and tries there. It will repeat this until * it reaches the root view folder. Should this fail it will then try in the default * root folder. If it still has no luck will render an error notice in compiled view * * @param string $relativeFolder relative path from view root where we should start looking for $file (excluding /) * @param string $file file name to look for excluding extension * @param array $data Associative array of the data to be used in the Template file. eg. <b>$data['username']</b>, you should use <b>{{username}}</b> in the template. * @param bool Ignores last modified time checking and force compile the template everytime it is visited. */ public function renderFileRecursive($relativeFolder, $file, $data=NULL, $forceCompile = false) { if(isset(Doo::conf()->TEMPLATE_COMPILE_ALWAYS) && Doo::conf()->TEMPLATE_COMPILE_ALWAYS==true){ $forceCompile = true; } self::$forceCompile = $forceCompile; $this->usingRecursiveRender = true; $this->mainRenderFolder = $relativeFolder; $file = '/' . $file; $path = $relativeFolder; $cfilename = $this->rootCompiledPath . $path . $file . '.php'; while(($found = file_exists($this->rootViewPath . $path . $file . '.html')) == false) { if ($path == '.' || $path == '') break; $path = dirname($path); } if ($found == true) { $vfilename = $this->rootViewPath . $path . $file . '.html'; } else { $path = $relativeFolder; while(($found = file_exists($this->defaultRootViewPath . $path . $file . '.html')) == false) { if ($path == '.' || $path == '') break; $path = dirname($path); } $vfilename = $this->defaultRootViewPath . $path . $file . '.html'; } //if file exist and is not older than the html template file, include the compiled php instead and exit the function if(!$forceCompile){ if(file_exists($cfilename)){ if(filemtime($cfilename)>=filemtime($vfilename)){ $this->setTags(); include $cfilename; return; } } } $this->data = $data; $this->compile($file, $vfilename, $cfilename); include $cfilename; } /** * Parse and compile the template file. Templates generated in protected/viewc folder * @param string $file Template file name without extension .html * @param string $vfilename Full path of the template file * @param string $cfilename Full path of the compiled file to be saved */ protected function compile($file, $vfilename, $cfilename){ if (($viewContent = $this->fileManager->readFileContents($vfilename)) == false) { $viewContent = '<span style="color:#ff0000;">View Not Found: ' . $file . "</span>\n"; } $compiledContent = $this->compileTags($viewContent); $this->fileManager->create($cfilename, $compiledContent); } /** * Renders layouts * @param string $viewFolder Path where all template files to be found for the active layout * @param array $data Associative array of the data to be used in the Template file. eg. <b>$data['username']</b>, you should use <b>{{username}}</b> in the template. * @param bool $process If TRUE, checks the template's last modified time against the compiled version. Regenerates if template is newer. * @param bool $forceCompile Ignores last modified time checking and force compile the template everytime it is visited. */ public function renderLayout($viewFolder, $data=NULL, $process=NULL, $forceCompile=false) { if (empty($viewFolder)){ echo "View folder can not be empty. Must be a folder within the view path"; exit; } if(isset(Doo::conf()->TEMPLATE_COMPILE_ALWAYS) && Doo::conf()->TEMPLATE_COMPILE_ALWAYS==true){ $process = $forceCompile = true; } else if($process===NULL){ $process = (Doo::conf()->APP_MODE!='prod'); } self::$forceCompile = $forceCompile; $this->usingRecursiveRender = true; $this->mainRenderFolder = $viewFolder; //just include the compiled file if process is false if($process==false){ //includes user defined template tags for template use $this->loadTagClass(); include $this->rootCompiledPath . $this->layoutFileName . '/' . $viewFolder . '/index.php'; } else{ $lfilename = $this->rootViewPath . $this->layoutFileName . '.html'; $cfilename = $this->rootCompiledPath . $this->layoutFileName . '/' . $viewFolder . '/index.php'; if(!$forceCompile){ if(file_exists($cfilename)){ if(filemtime($cfilename)>=filemtime($lfilename)){ $this->setTags(); include $cfilename; return; } } } $this->data = $data; $this->compileLayout($lfilename, $cfilename); include $cfilename; } } /** * Parses and compiled a view into a layout to fill in placeholders and * stores the resulting view file to then be processed as normal by DooView::compile * @param string $viewFile The original location of the view without extension .html * @param string $lfilename Full path to the layout file * @param string $vfilename Full path to the view to be merged into the layout * @param string $cfilename Full path of the compiled file to be saved */ protected function compileLayout($layoutFilePath, $compiledFilePath) { if (($layout = $this->fileManager->readFileContents($layoutFilePath)) == false) { echo "Layout File Not Found: {$layoutFilePath}"; exit; } $viewContent = preg_replace_callback('/<!-- placeholder:([a-zA-Z0-9\_\-]+?) -->([\s\S]*?)<!-- endplaceholder -->/', array( &$this, 'replacePlaceholder'), $layout); $compiledContent = $this->compileTags($viewContent); $this->fileManager->create($compiledFilePath, $compiledContent); } protected function replacePlaceholder($matches) { $fileName = '/' . $matches[1] . '.html'; $path = $this->mainRenderFolder; $content = false; while($content === false) { $content = $this->fileManager->readFileContents($this->rootViewPath . $path . $fileName); if ($path == '.') break; $path = dirname($path); } if ($content === false) { $content = $matches[2]; } return $content; } /** * Load the template class and returns the class name. * @return string Name of the class that is loaded. */ public function loadTagClass(){ /* if include tag class is not defined load TemplateTag for main app * else if render() is called from a module, load ModulenameTag */ $tagFile = ''; if( !isset($this->tagClassName) ){ if( !isset(Doo::conf()->PROTECTED_FOLDER_ORI) ){ $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'plugin/TemplateTag.php'; $tagcls = 'TemplateTag'; }else{ $tagcls = explode('/', Doo::conf()->PROTECTED_FOLDER); $tagcls = ucfirst($tagcls[sizeof($tagcls)-2]) . 'Tag'; $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'plugin/' . $tagcls .'.php'; } }else{ //load the main app's TemplateTag if module is '/' if($this->tagModuleName=='/'){ $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER_ORI . 'plugin/'. $this->tagClassName .'.php'; } else if($this->tagModuleName===Null){ $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER . 'plugin/'. $this->tagClassName .'.php'; } else{ if(isset(Doo::conf()->PROTECTED_FOLDER_ORI)) $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER_ORI .'module/'. $this->tagModuleName . '/plugin/'. $this->tagClassName .'.php'; else $tagFile = Doo::conf()->SITE_PATH . Doo::conf()->PROTECTED_FOLDER .'module/'. $this->tagModuleName . '/plugin/'. $this->tagClassName .'.php'; } $tagcls = $this->tagClassName; } if (file_exists($tagFile)) { require_once $tagFile; return $tagcls; } else { return false; } } private function setTags(){ $tagcls = $this->loadTagClass(); if ($tagcls === false) { $template_tags = array(); } else { $tagMethod = get_class_methods($tagcls); if(!empty($tagMethod)){ if( !empty(Doo::conf()->TEMPLATE_GLOBAL_TAGS) ) $template_tags = array_merge(Doo::conf()->TEMPLATE_GLOBAL_TAGS, $tagMethod); else $template_tags = $tagMethod; $template_tags['_methods'] = $tagMethod; $template_tags['_class'] = $tagcls; } else if( !empty(Doo::conf()->TEMPLATE_GLOBAL_TAGS) ){ $template_tags = Doo::conf()->TEMPLATE_GLOBAL_TAGS; } else{ $template_tags = array(); } foreach($template_tags as $k=>$v ){ if(is_int($k)) $template_tags[$k] = strtolower($v); else $template_tags[$k] = $v; } } Doo::conf()->add('TEMPLATE_TAGS', $template_tags); return $template_tags; } /** * Processes a string containing DooPHP Template tags and replaces them with the relevant PHP code required * @param string $str This is the html template markup from View files * @return string The PHP markedup version of the View file */ protected function compileTags($str) { // Includes user defined template tags and checks for the tag and compile. if($this->tags===NULL){ if(!isset(Doo::conf()->TEMPLATE_TAGS)){ $this->tags = $this->setTags(); }else{ $this->tags = Doo::conf()->TEMPLATE_TAGS; } } // Reduce our workload and remove commented parts before we do anything else if(!isset(Doo::conf()->TEMPLATE_SHOW_COMMENT) || Doo::conf()->TEMPLATE_SHOW_COMMENT!=true){ $str = preg_replace('/' . $this->tagComment_start . '[\s\S]*?' . $this->tagComment_end . '/', '', $str); } // Handel any PHP Tags based on configured rules if( isset(Doo::conf()->TEMPLATE_ALLOW_PHP) ){ if( Doo::conf()->TEMPLATE_ALLOW_PHP === false ){ $str = preg_replace('/<\?(php|\=|\+)?([\S|\s]*)\?>/Ui', '', $str); } }else{ $str = preg_replace_callback('/<\?(php|\=|\+)?([\S|\s]*)\?>/Ui', array( &$this, 'convertPhpFunction'), $str); } // Handle Variable output in the form of {{foo}}, {{foo.bar}}, {{foo.@bar}}, {{func(foo, 'bar'}}, {{+foo}}, {{+func(foo)}} $str = preg_replace_callback('/' . $this->tagVariable_start . '[ ]*?([^\t\r\n]+?)[ ]*?' . $this->tagVariable_end . '/', array( &$this, 'convertOutputVariable'), $str); // Find and replace blocks in the form of {% blockHanlerFunction DATA %} $str = preg_replace_callback('/' . $this->tagBlock_start . '[ ]*([a-zA-Z0-9\-\_]+)([\s\S]*?)[ ]*' . $this->tagBlock_end . '/', array( &$this, 'convertBlock'), $str); return $str; } // Inherited stuff from DooView private function convertPhpFunction($matches){ if(stripos($matches[0], '<?php')!==0 && strpos($matches[0], '<?=')!==0 && strpos($matches[0], '<?+')!==0 && strpos($matches[0], '<? ')!==0 ){ return $matches[0]; } $str = preg_replace_callback('/([^ \t\r\n\(\)}]+)([\s\t]*?)\(/', array( &$this, 'parsePHPFunc'), $matches[2]); if(strpos($str, 'php')===0) $str = substr($str, 3); //if short tag <?=, convert to <?php echo if($matches[2][0]=='='){ $str = substr($str, 1); return '<?php echo ' . $str .' ?>'; } //write the variable value else if($matches[2][0]=='+'){ $str = substr($str, 1); return eval('return ' . $str); } return '<?php ' . $str .' ?>'; } private function parsePHPFunc($matches){ //matches and check function name against template tag if(!empty($matches[1])){ $funcName = trim(strtolower($matches[1])); if($funcName[0]=='+' || $funcName[0]=='=') $funcName = substr($funcName, 1); $controls = array('if','elseif','else if','while','switch','for','foreach','switch','return','include','require','include_once','require_once','declare','define','defined','die','constant','array'); //skip checking static method usage: TemplateTag::go(), Doo::conf() if(stripos($funcName, $this->tags['_class'] . '::')===False && stripos($funcName, 'Doo')===False){ //$funcname = str_ireplace($this->tags['_class'] . '::', '', $funcname); if(!in_array($funcName, $controls)){ if(!in_array($funcName, $this->tags)) { return 'function_deny('; } } } } return $matches[1].'('; } // Handel variable/function return value outputting private function convertOutputVariable($matches){ if ($matches[1][0] == '+') { $matches[1] = substr($matches[1], 1); $writeStaticValue = true; } $dataIndex = $this->strToStmt($matches[1]); if (!empty($writeStaticValue)) { $dataIndex = str_replace('$data', '$this->data', $dataIndex); return eval('return ' . $dataIndex .';'); } else { return '<?php echo ' . $dataIndex .'; ?>'; } } // BLOCK HANDLERS protected function convertBlock($matches) { $blockName = $matches[1]; $blockParams = isset($matches[2]) ? $matches[2] : ''; // Remove newlines from parameters for block and replace tabs with 4 spaces $blockParams = str_replace(array("\r\n", "\n", "\r", "\t"), array('','','',' '), $blockParams); // Remove any PHP tags from outputting $blockParams = $this->stripPHPTags($blockParams); $blockName = 'block_' . $blockName; if (method_exists($this, $blockName)) { return $this->$blockName($blockParams); } else { return '<span style="color:#ff0000;">Unknown Template Tag : ' . $blockName . '</span>'; } } protected function block_set($params) { preg_match('/[ ]*([^\t\r\n ]+) as (.*)[ ]*/', $params, $matches); $variable = $this->extractDataPath($matches[1], true); return '<?php ' . $variable . ' = ' . $this->strToStmt($matches[2]) . '; ?>'; } protected function block_if($params) { return '<?php if(' . $this->strToStmt($params) . '): ?>'; } protected function block_elseif($params) { return '<?php elseif(' . $this->strToStmt($params) . '): ?>'; } protected function block_else($params) { return '<?php else: ?>'; } protected function block_endif($params) { return '<?php endif; ?>'; } protected function block_for($params) { $metaIdentifer = false; $preForStatement = ''; $forStmt = ''; $postForStatement = ''; $namespace = isset(Doo::conf()->APP_NAMESPACE) ? Doo::conf()->APP_NAMESPACE : 'doo'; $loopVar = $this->getUniqueVarId(); //for: i from 0 to 10 if (preg_match('/([a-z0-9\-_]+) from ([^\t\r\n]+) to ([^\t\r\n]+?) step ([^\t\r\n]+?)( with meta)?$/i', $params, $matches)){ $step = $this->strToStmt($matches[4]); $metaIdentifer = isset($matches[5]) ? $matches[1] : false; if ($metaIdentifer !== false) { $preForStatement .= $loopVar . ' = range(' . $this->strToStmt($matches[2]) . ', ' . $this->strToStmt($matches[3]) . ', ' . $step . ");\n"; $preForStatement .= 'if (!empty(' . $loopVar . ")):\n"; $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['length'] = count({$loopVar});\n"; $forStmt .= 'foreach(' . $loopVar . ' as $data[\'' . $matches[1] . '\']):'; } else { $forStmt .= $loopVar . ' = range(' . $this->strToStmt($matches[2]) . ', ' . $this->strToStmt($matches[3]) . ', ' . $step . ");\n"; $forStmt .= 'if (!empty(' . $loopVar . ")):\n"; $forStmt .= 'foreach(' . $loopVar . ' as $data[\'' . $matches[1] . '\']):'; } } elseif (preg_match('/([a-z0-9\-_]+) from ([^\t\r\n]+) to ([^\t\r\n]+?)( with meta)?$/i', $params, $matches)){ $metaIdentifer = isset($matches[4]) ? $matches[1] : false; if ($metaIdentifer !== false) { $preForStatement .= $loopVar . ' = range(' . $this->strToStmt($matches[2]) . ', ' . $this->strToStmt($matches[3]) . ", 1);\n"; $preForStatement .= 'if (!empty(' . $loopVar . ")):\n"; $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['length'] = count({$loopVar});\n"; $forStmt .= 'foreach(' . $loopVar . ' as $data[\'' . $matches[1] . '\']):'; } else { $forStmt .= $loopVar . ' = range(' . $this->strToStmt($matches[2]) . ', ' . $this->strToStmt($matches[3]) . ", 1);\n"; $forStmt .= 'if (!empty(' . $loopVar . ")):\n"; $forStmt .= 'foreach(' . $loopVar . ' as $data[\'' . $matches[1] . '\']):'; } } // for: 'myArray as key=>val' else if (preg_match('/([^\t\r\n ]+) as ([a-zA-Z0-9\-_]+)[ ]?=>[ ]?([a-zA-Z0-9\-_]+)( with meta)?/', $params, $matches)) { $metaIdentifer = isset($matches[4]) ? $matches[3] : false; $arrName = $this->strToStmt($matches[1]); $preForStatement .= $loopVar . ' = ' . $arrName . ";\n"; $preForStatement .= 'if (!empty(' . $loopVar . ")):\n"; if ($metaIdentifer !== false) { $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['length'] = count(" . $loopVar . ");\n"; } $forStmt = 'foreach(' . $loopVar .' as $data[\''.$matches[2].'\']=>$data[\''.$matches[3].'\']):'; } // for: 'myArray as val' else if (preg_match('/([^\t\r\n ]+) as ([a-zA-Z0-9\-_]+)( with meta)?/', $params, $matches)) { $metaIdentifer = isset($matches[3]) ? $matches[2] : false; $arrName = $this->strToStmt($matches[1]); $preForStatement .= $loopVar . ' = ' . $arrName . ";\n"; $preForStatement .= 'if (!empty(' . $loopVar . ")):\n"; if ($metaIdentifer !== false) { $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['length'] = count(" . $loopVar . ");\n"; } $forStmt = 'foreach(' . $loopVar .' as $data[\''.$matches[2].'\']):'; } if ($metaIdentifer !== false) { $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['index'] = 0;\n"; $preForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['index0'] = -1;\n"; $postForStatement = "\$data['{$namespace}']['for']['{$metaIdentifer}']['index']++;\n"; $postForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['index0']++;\n"; $postForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['first'] = (\$data['{$namespace}']['for']['{$metaIdentifer}']['index0']) == 0 ? true : false;\n"; $postForStatement .= "\$data['{$namespace}']['for']['{$metaIdentifer}']['last'] = (\$data['{$namespace}']['for']['{$metaIdentifer}']['index']) == \$data['{$namespace}']['for']['{$metaIdentifer}']['length'] ? true : false;\n"; } return '<?php ' . $preForStatement . $forStmt . "\n" . $postForStatement . '?>'; } protected function block_ifempty($params) { return "<?php endforeach;\n else: ?>"; } protected function block_endfor($params) { return "<?php endforeach;\n endif; ?>"; } protected function block_continue($params) { return '<?php continue; ?>'; } protected function block_break($params) { return '<?php break; ?>'; } protected function block_cache($params) { if ( preg_match('/\(([^\t\r\n]+?)(([,][ ]*)([0-9]+[ ]*))?[ ]*\)[ ]*$/', $params, $matches)) { $matches[1] = $this->strToStmt($matches[1]); if (count($matches) == 5) { return "<?php if (!Doo::cache('front')->getPart({$matches[1]}, {$matches[4]})): ?>\n<?php Doo::cache('front')->start({$matches[1]}); ?>"; } else { return "<?php if (!Doo::cache('front')->getPart({$matches[1]})): ?>\n<?php Doo::cache('front')->start({$matches[1]}); ?>"; } } return "<span style=\"color:#ff0000\">Invalid cache parameters specified.</span>"; } protected function block_endcache($params) { return "\n<?php Doo::cache('front')->end(); ?>\n<?php endif; ?>"; } protected function block_include_old($params) { $result = $this->compileSubView($params); if ($result[0] == true) { return "<?php include '{$result[1]}'; ?>"; } else { return $result[1]; } } protected function block_include($params) { $params = trim($params); // Using a static string for the include if (preg_match('/^[\'|\"](.+)[\'|\"]$/', $params, $matches)){ $result = $this->compileSubView($matches[1]); if ($result[0] == true) { return "<?php include '{$result[1]}'; ?>"; } else { return $result[1]; } // Using dynamic variable for the include } elseif (preg_match('/^([^\t\r\n ]+)$/', $params, $matches)) { $filePath = $this->strToStmt($params); $resultVar = $this->getUniqueVarId(); $content = "<?php\n"; $content .= "\tif({$filePath} != DooViewBasic::\$safeVariableResult){\n"; $content .= "\t\t{$resultVar} = \$this->compileSubView({$filePath});\n"; $content .= "\t\tif ({$resultVar}[0] == true) {\n"; $content .= "\t\t\tinclude {$resultVar}[1];\n"; $content .= "\t\t} else {\n"; $content .= "\t\t\techo {$resultVar}[1];\n"; $content .= "\t\t}\n"; $content .= "\t} else {\n"; $content .= "\t\techo '<span style=\"color:#ff0000\">{$params} is not set</span>';\n"; $content .= "\t}\n"; $content .= "?>"; return $content; } else { return "<span style=\"color:#ff0000\">Unrecognised view. Must be string OR \$data index. Got: {$params}</span>"; } } protected function block_insert($params) { $result = $this->compileSubView($params); if ($result[0] == true) { return "\n" . file_get_contents($result[1]) . "\n"; } else { return $result[1]; } } protected function block_cycle($params) { if (preg_match('/ using ([^\t\r\n]+)$/i', $params, $matches)){ // Got an array to use $cycleVar = $this->extractDataPath($matches[1], true); $preCycleStatement = ''; } else { $cycleVar = $this->getUniqueVarId(); $preCycleStatement = "if (!isset(" . $cycleVar . "))\n\t" . $cycleVar . ' = ' . $this->strToStmt($params) . ";\n"; } $cycleStatement = 'echo current(' . $cycleVar . ");\n"; $cycleStatement .= 'if (next(' . $cycleVar . ")===false)\n\treset(" . $cycleVar . ");\n"; return "<?php\n" . $preCycleStatement . $cycleStatement . '?>'; } public function compileSubView($file) { /* $params = trim($params); if (preg_match('/^[\'|\"](.+)[\'|\"]$/', $params, $matches)){ $file = $matches[1]; } elseif (preg_match('/([a-zA-Z0-9\-\_]+)/', $params, $matches)) { if (isset($this->data[$matches[1]])) { $file = $this->data[$matches[1]]; } else { return array(false, "<span style=\"color:#ff0000\">Invalid view. Could not find \$data[{$matches[1]}]</span>"); } } else { return array(false, "<span style=\"color:#ff0000\">Unrecognised view. Must be string OR \$data index.</span>"); } */ $cfilename = $vfilename = ""; if (substr($file, 0, 1) == '/') { $file = substr($file, 1); $cfilename = str_replace('\\', '/', "{$this->rootCompiledPath}{$this->mainRenderFolder}/$file.php"); if (file_exists("{$this->rootViewPath}/{$file}.html")) { $vfilename = "{$this->rootViewPath}/{$file}.html"; } else { $vfilename = "{$this->defaultRootViewPath}/{$file}.html"; } } else { $cfilename = str_replace('\\', '/', "{$this->rootCompiledPath}{$this->mainRenderFolder}/$file.php"); if ($this->usingRecursiveRender == true) { $fileName = '/' . $file . '.html'; $path = $this->mainRenderFolder; while (($found = file_exists($this->rootViewPath . $path . $fileName)) == false) { //echo $path . "<br />"; if ($path == '.' || $path == '') break; $path = dirname($path); } if ($found == true) { $vfilename = $this->rootViewPath . $path . $fileName; } else { $path = $this->mainRenderFolder; while (($found = file_exists($this->defaultRootViewPath . $path . $fileName)) == false) { //echo $path . "<br />"; if ($path == '.' || $path == '') break; $path = dirname($path); } $vfilename = $this->defaultRootViewPath . $path . $fileName; } } else { if (file_exists("{$this->rootViewPath}{$this->mainRenderFolder}/{$file}.html")) { $vfilename = "{$this->rootViewPath}{$this->mainRenderFolder}/{$file}.html"; } else { $vfilename = "{$this->defaultRootViewPath}{$this->mainRenderFolder}/{$file}.html"; } } } if (!file_exists($vfilename)) { return array(false, "<span style=\"color:#ff0000\">View file <strong>{$file}.html</strong> not found</span>"); } else { if (!$this->forceCompile && file_exists($cfilename)) { if (filemtime($vfilename) > filemtime($cfilename)) { $this->compile($file, $vfilename, $cfilename); } } else { $this->compile($file, $vfilename, $cfilename); } } return array(true, $cfilename); } // UTILITY STUFF protected function strToStmt($str) { $this->debug("strToStmt: {$str}"); $result = ''; $currentToken = ''; $numChars = strlen($str); $functionDepth = 0; $arrayDepth = 0; $inFilter = false; $tokens = array(); for($i = 0; $i < $numChars; $i++) { $char = $str[$i]; switch($char) { case '\'': case '"': $currentToken .= $this->findEndOfString($str, $i); break; case '(': $currentToken .= $char; $functionDepth++; break; case ')': $currentToken .= $char; $functionDepth--; break; case '[': $currentToken .= $char; $arrayDepth++; break; case ']': $currentToken .= $char; $arrayDepth--; break; case '|': if (isset($str[$i+1]) && $str[$i+1] == '|') { $currentToken .= $char . '|'; $i++; continue; } elseif ($arrayDepth == 0 && $functionDepth == 0 && trim($currentToken) != '|') { $inFilter = true; $tokens[] = $currentToken; $currentToken = ''; } else { $currentToken .= $char; } break; case ',': case ' ': if ($arrayDepth == 0 && $functionDepth == 0) { if ($inFilter) { $tokens[] = $currentToken; $filterResult = $tokens[0]; for ($j = 1; $j < count($tokens); $j++) { $token = $tokens[$j]; if (($functionStartPos = strpos($token, '(')) !== false) { $filterResult = $this->filterFunctionPrefix . substr($token, 0, $functionStartPos) . '(' . $filterResult . ', ' . substr($token, $functionStartPos + 1); } else { $filterResult = $this->filterFunctionPrefix . $token . '(' . $filterResult . ')'; } } $result .= $this->processStmt($filterResult); } else { $result .= $this->processStmt($currentToken); if ($char == ',') { $result .= ','; } } $inFilter = false; $tokens = array(); $currentToken = ''; } else { $currentToken .= $char; } break; default: $currentToken .= $char; } } if ($inFilter) { $tokens[] = $currentToken; $filterResult = $tokens[0]; for ($j = 1; $j < count($tokens); $j++) { $token = $tokens[$j]; if (($functionStartPos = strpos($token, '(')) !== false) { $filterResult = $this->filterFunctionPrefix . substr($token, 0, $functionStartPos) . '(' . $filterResult . ',' . substr($token, $functionStartPos + 1); } else { $filterResult = $this->filterFunctionPrefix . $token . '(' . $filterResult . ')'; } } $result .= $this->processStmt($filterResult); } else { $result .= $this->processStmt($currentToken); } $this->debug("strToStmt:: {$result}"); return $result; } protected function processStmt($str) { $str = $str . ' '; $this->debug("processStmt: {$str}"); $result = ''; $currentToken = ''; $numChars = strlen($str); $functionDepth = 0; $arrayDepth = 0; $inSingleQuoteString = false; $inDoubleQuoteString = false; $inFilter = false; for($i = 0; $i < $numChars; $i++) { $char = $str[$i]; switch($char) { case '(': // Moving into a function if (!$inSingleQuoteString && !$inDoubleQuoteString) { if (trim($currentToken) != '' && !strpos($currentToken, '->')) { $result .= $this->convertToFunction($currentToken); } else { if (trim($currentToken) != '') { $result .= $this->extractDataPath($currentToken, true); } } $currentToken = ''; $functionDepth++; while ($functionDepth > 0 && isset($str[++$i])) { switch($str[$i]) { case '"': case '\'': $currentToken .= $this->findEndOfString($str, $i); break; case '(': $currentToken .= '('; $functionDepth++; break; case ')': $functionDepth--; if ($functionDepth == 0) { break; } else { $currentToken .= ')'; } break; default: $currentToken .= $str[$i]; } } $this->debug("Function Loop Found: $currentToken"); $result .= '(' . $this->processStmt($currentToken) . ')'; $currentToken = ''; } break; case '[': if (!$inSingleQuoteString && !$inDoubleQuoteString) { if ($currentToken != '') { // We have an index like foo.bar[abc] to become $data['foo']['bar'][$data['abc']] $currentToken .= $char; } else { $result .= 'array('; $currentToken .= ''; $arrayDepth++; } break; } $currentToken .= $char; break; case ']': if (!$inSingleQuoteString && !$inDoubleQuoteString) { if ($arrayDepth > 0) { $result .= $this->strToStmt($currentToken) . ')'; $currentToken = ''; $arrayDepth--; } else { $currentToken .= $char; } break; } $currentToken .= $char; case '\'': case '"': $quoteType = $char; $currentToken .= $char; while (isset($str[$i + 1])) { $currentToken .= $str[$i + 1]; if ($str[$i + 1] == '\\') { if (isset($str[$i + 2]) && $str[$i + 2] == $quoteType) { $currentToken .= $quoteType; $i++; } } elseif($str[$i+1] == $quoteType) { $i++; break; } $i++; } break; case '=': // If = appears in an array then its used for associatve array // Otherwise its a delimiter for example <= == etc.. if ($arrayDepth > 0) { if (!$inSingleQuoteString && !($inDoubleQuoteString)) { if ($currentToken != '' && $currentToken[0] != '\'' && $currentToken[0] != '"') { $currentToken = '\'' . $currentToken . '\''; } $result .= strtolower($currentToken) . '=>'; $currentToken = ''; break; } } $currentToken .= $char; break; case ',': // Reached the end of a parameter if (!$inSingleQuoteString && !$inDoubleQuoteString) { $result .= $this->strToStmt($currentToken) . $char; $currentToken = ''; } else { $currentToken .= $char; } break; case ' ': if ($inSingleQuoteString || $inDoubleQuoteString) { $currentToken .= $char; } else { $result .= $this->extractArgument($currentToken); $currentToken = ''; } break; default: // Not doing anything - keep moving $currentToken .= $char; } } $this->debug("CurrentToken:: $currentToken"); $result .= $this->extractArgument($currentToken); $this->debug("processStmt:: {$result}"); return $result; } protected function extractArgument($arg) { $this->debug("extractArgument: {$arg}"); $result = null; if (in_array($arg, array('', '&&', '||', '<=', '==', '>=', '!=', '===', '!==', '<', '>', '+', '-', '*', '/', '%'))) { $result = $arg; } elseif (strtolower($arg)=='true' || strtolower($arg)=='false' || strtolower($arg)=='null') { $result = $arg; } elseif (preg_match('/^[-]?[0-9]*\\.?[0-9]{0,}$/', $arg)) { // Is a number $result = $arg; } elseif (preg_match('/^[\'\"].*[\'\"]$/', $arg)) { // Is a string 'anything' OR "anything" $result = str_replace('\/\.\;', ',', $arg); } else { // Got parameter values to handle $result = $this->extractDataPath($arg); } $this->debug("extractArgument:: {$result}"); return $result; } protected function extractDataPath($str, $ignoreSafe = false) { $this->debug("extractDataPath: $str"); $result = '$data'; $currentToken = ''; $numChars = strlen($str); $isNumericIndex = false; $processingArrayIndex = true; // True if an array index. False for object index for($i = 0; $i < $numChars; $i++) { $char = $str[$i]; switch($char) { case '(': $depth = 1; $functionContentToken = ''; for($j=$i+1; $j < $numChars && $depth != 0; $j++) { switch ($str[$j]) { case '(': $depth++; $functionContentToken .= $str[$j]; break; case ')': $depth--; if ($depth != 0) { $functionContentToken .= $str[$j]; } break; default: $functionContentToken .= $str[$j]; } } $i = $j - 1; $this->debug("FunctionContentToken: $functionContentToken"); $currentToken .= '(' . $this->strToStmt($functionContentToken) . ')'; break; case '[': $depth = 1; $arrayIndexContentToken = ''; for($j=$i+1; $j < $numChars && $depth != 0; $j++) { switch ($str[$j]) { case '[': $depth++; $arrayIndexContentToken .= $str[$j]; break; case ']': $depth--; if ($depth != 0) { $arrayIndexContentToken .= $str[$j]; } break; default: $arrayIndexContentToken .= $str[$j]; } } $i = $j-1; $result .= $currentToken . '[' . $this->extractDataPath($arrayIndexContentToken, true) . ']'; $arrayIndexContentToken = ''; $currentToken = ''; $processingArrayIndex = false; break; case '-': if (isset($str[$i+1])) { if($str[$i+1] == '>') { if ($processingArrayIndex) { if (is_numeric($currentToken)) $result .= '[' . $currentToken . ']->'; else $result .= '[\'' . $currentToken . '\']->'; } else { $result .= $currentToken . '->'; } $processingArrayIndex = false; $currentToken = ''; $i++; break; } } $currentToken .= $char; break; case '.': if ($processingArrayIndex) { if (is_numeric($currentToken)) $result .= '[' . $currentToken . ']'; else $result .= '[\'' . $currentToken . '\']'; } else { $result .= $currentToken; } $currentToken = ''; $processingArrayIndex = true; break; default: $currentToken .= $char; } } if ($currentToken != '') { if ($processingArrayIndex) { if (is_numeric($currentToken)) $result .= '[' . $currentToken . ']'; else $result .= '[\'' . $currentToken . '\']'; } else { $result .= $currentToken; } } $this->debug("extractDataPath:: $result"); if (!$ignoreSafe && $this->useSafeVariableAccess) { return 'DooViewBasic::is_set_or(' . $result . ')'; } else { return $result; } } private function convertToFunction($funcName) { $this->debug("convertToFunction: $funcName"); if(!in_array(strtolower($funcName), $this->tags)) { return 'function_deny'; } if(isset($this->tags['_methods']) && in_array($funcName, $this->tags['_methods'])===True){ $funcName = $this->tags['_class'] . '::' . $funcName; } $this->debug("convertToFunction:: $funcName"); return $funcName; } private function findEndOfString(&$str, &$i) { $this->debug("findEndOfString: $str"); $start = $i+1; $quoteType = $str[$i]; while (isset($str[$i + 1])) { if ($str[$i + 1] == '\\') { if (isset($str[$i + 2]) && $str[$i + 2] == $quoteType) { $i++; } } elseif($str[$i+1] == $quoteType) { $i++; break; } $i++; } $this->debug("findEndOfString::" . $quoteType . substr($str, $start, $i - $start) . $quoteType); return $quoteType . substr($str, $start, $i - $start) . $quoteType; } private function stripCommaStr($matches) { $str = implode('\/\.\;', explode(',', $matches[0]) ); $str = substr($str, 1, strlen($str)-2); return "'".$str."'"; } private function stripPHPTags($str) { $str = str_replace('<?php echo ', '', $str); return str_replace('; ?>', '', $str); } public function getUniqueVarId() { return '$doo_view_basic_' . self::$uniqueId++; } public static function is_set_or(&$var) { return (isset($var)) ? $var : DooViewBasic::$safeVariableResult; } private function debug($str) { //echo $str . '<br />'; } }
{'content_hash': '68ff654f45ee463fc3a1d26a58ece440', 'timestamp': '', 'source': 'github', 'line_count': 1367, 'max_line_length': 229, 'avg_line_length': 34.93343087051939, 'alnum_prop': 0.5702977761025254, 'repo_name': 'lienvdsteen/TumblrMotifInspector', 'id': 'b6be49f675b2e1092737df6cee53b432720bbd6f', 'size': '47754', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'dooframework/view/DooViewBasic.php', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '2197'}, {'name': 'JavaScript', 'bytes': '8641'}, {'name': 'PHP', 'bytes': '897549'}, {'name': 'Perl', 'bytes': '268'}]}
package gexec_test import ( "bytes" . "github.com/onsi/gomega/gexec" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("PrefixedWriter", func() { var buffer *bytes.Buffer var writer *PrefixedWriter BeforeEach(func() { buffer = &bytes.Buffer{} writer = NewPrefixedWriter("[p]", buffer) }) It("should emit the prefix on newlines", func() { writer.Write([]byte("abc")) writer.Write([]byte("def\n")) writer.Write([]byte("hij\n")) writer.Write([]byte("\n\n")) writer.Write([]byte("klm\n\nnop")) writer.Write([]byte("")) writer.Write([]byte("qrs")) writer.Write([]byte("\ntuv\nwx")) writer.Write([]byte("yz\n\n")) Expect(buffer.String()).Should(Equal(`[p]abcdef [p]hij [p] [p] [p]klm [p] [p]nopqrs [p]tuv [p]wxyz [p] `)) }) })
{'content_hash': '49cfa925414079895b3d24d12901ba28', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 50, 'avg_line_length': 18.232558139534884, 'alnum_prop': 0.6262755102040817, 'repo_name': 'ironcladlou/origin', 'id': 'e847b150195511682d469489ac751f9de31ca15c', 'size': '784', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/onsi/gomega/gexec/prefixed_writer_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'Dockerfile', 'bytes': '2240'}, {'name': 'Go', 'bytes': '2321943'}, {'name': 'Makefile', 'bytes': '6395'}, {'name': 'Python', 'bytes': '14593'}, {'name': 'Shell', 'bytes': '310343'}]}
<?xml version="1.0" encoding="utf-8"?> <project name="essential-gray-flat" default=".help"> <!-- The build-impl.xml file imported here contains the guts of the build process. It is a great idea to read that file to understand how the process works, but it is best to limit your changes to this file. --> <import file="${basedir}/.sencha/package/build-impl.xml"/> <!-- The following targets can be provided to inject logic before and/or after key steps of the build process: The "init-local" target is used to initialize properties that may be personalized for the local machine. <target name="-before-init-local"/> <target name="-after-init-local"/> The "clean" target is used to clean build output from the build.dir. <target name="-before-clean"/> <target name="-after-clean"/> The general "init" target is used to initialize all other properties, including those provided by Sencha Cmd. <target name="-before-init"/> <target name="-after-init"/> The "build" target performs the call to Sencha Cmd to build the application. <target name="-before-build"/> <target name="-after-build"/> --> </project>
{'content_hash': '2154cb85e692c046f020c3ab057cd038', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 89, 'avg_line_length': 35.24324324324324, 'alnum_prop': 0.6257668711656442, 'repo_name': 'EssentialDeveloper/sencha-extjs-themes', 'id': '64344d4d90273e77f41a56739d0a5f3bf6d9941e', 'size': '1304', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'essential-gray-flat/build.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5321'}, {'name': 'HTML', 'bytes': '2105'}, {'name': 'JavaScript', 'bytes': '118078'}, {'name': 'Ruby', 'bytes': '56'}]}
#ifndef __UISCROLLVIEW_H__ #define __UISCROLLVIEW_H__ #include "gui/UILayout.h" #include "gui/UIScrollInterface.h" NS_CC_BEGIN namespace ui { enum SCROLLVIEW_DIR { SCROLLVIEW_DIR_NONE, SCROLLVIEW_DIR_VERTICAL, SCROLLVIEW_DIR_HORIZONTAL, SCROLLVIEW_DIR_BOTH }; typedef enum { SCROLLVIEW_EVENT_SCROLL_TO_TOP, SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM, SCROLLVIEW_EVENT_SCROLL_TO_LEFT, SCROLLVIEW_EVENT_SCROLL_TO_RIGHT, SCROLLVIEW_EVENT_SCROLLING, SCROLLVIEW_EVENT_BOUNCE_TOP, SCROLLVIEW_EVENT_BOUNCE_BOTTOM, SCROLLVIEW_EVENT_BOUNCE_LEFT, SCROLLVIEW_EVENT_BOUNCE_RIGHT }ScrollviewEventType; typedef void (Ref::*SEL_ScrollViewEvent)(Ref*, ScrollviewEventType); #define scrollvieweventselector(_SELECTOR) (SEL_ScrollViewEvent)(&_SELECTOR) class ScrollView : public Layout , public UIScrollInterface { public: /** * Default constructor */ ScrollView(); /** * Default destructor */ virtual ~ScrollView(); /** * Allocates and initializes. */ static ScrollView* create(); /** * Changes scroll direction of scrollview. * * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll * * @param SCROLLVIEW_DIR */ virtual void setDirection(SCROLLVIEW_DIR dir); /** * Gets scroll direction of scrollview. * * @see SCROLLVIEW_DIR SCROLLVIEW_DIR_VERTICAL means vertical scroll, SCROLLVIEW_DIR_HORIZONTAL means horizontal scroll * * @return SCROLLVIEW_DIR */ SCROLLVIEW_DIR getDirection(); /** * Gets inner container of scrollview. * * Inner container is the container of scrollview's children. * * @return inner container. */ Layout* getInnerContainer(); /** * Scroll inner container to bottom boundary of scrollview. */ void scrollToBottom(float time, bool attenuated); /** * Scroll inner container to top boundary of scrollview. */ void scrollToTop(float time, bool attenuated); /** * Scroll inner container to left boundary of scrollview. */ void scrollToLeft(float time, bool attenuated); /** * Scroll inner container to right boundary of scrollview. */ void scrollToRight(float time, bool attenuated); /** * Scroll inner container to top and left boundary of scrollview. */ void scrollToTopLeft(float time, bool attenuated); /** * Scroll inner container to top and right boundary of scrollview. */ void scrollToTopRight(float time, bool attenuated); /** * Scroll inner container to bottom and left boundary of scrollview. */ void scrollToBottomLeft(float time, bool attenuated); /** * Scroll inner container to bottom and right boundary of scrollview. */ void scrollToBottomRight(float time, bool attenuated); /** * Scroll inner container to vertical percent position of scrollview. */ void scrollToPercentVertical(float percent, float time, bool attenuated); /** * Scroll inner container to horizontal percent position of scrollview. */ void scrollToPercentHorizontal(float percent, float time, bool attenuated); /** * Scroll inner container to both direction percent position of scrollview. */ void scrollToPercentBothDirection(const Point& percent, float time, bool attenuated); /** * Move inner container to bottom boundary of scrollview. */ void jumpToBottom(); /** * Move inner container to top boundary of scrollview. */ void jumpToTop(); /** * Move inner container to left boundary of scrollview. */ void jumpToLeft(); /** * Move inner container to right boundary of scrollview. */ void jumpToRight(); /** * Move inner container to top and left boundary of scrollview. */ void jumpToTopLeft(); /** * Move inner container to top and right boundary of scrollview. */ void jumpToTopRight(); /** * Move inner container to bottom and left boundary of scrollview. */ void jumpToBottomLeft(); /** * Move inner container to bottom and right boundary of scrollview. */ void jumpToBottomRight(); /** * Move inner container to vertical percent position of scrollview. */ void jumpToPercentVertical(float percent); /** * Move inner container to horizontal percent position of scrollview. */ void jumpToPercentHorizontal(float percent); /** * Move inner container to both direction percent position of scrollview. */ void jumpToPercentBothDirection(const Point& percent); /** * Changes inner container size of scrollview. * * Inner container size must be larger than or equal scrollview's size. * * @param inner container size. */ void setInnerContainerSize(const Size &size); /** * Gets inner container size of scrollview. * * Inner container size must be larger than or equal scrollview's size. * * @return inner container size. */ const Size& getInnerContainerSize() const; /** * Add call back function called scrollview event triggered */ void addEventListenerScrollView(Ref* target, SEL_ScrollViewEvent selector); virtual void addChild(Node * child) override; /** * Adds a child to the container with a z-order * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** * Adds a child to the container with z order and tag * * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; //override "removeAllChildrenAndCleanUp" method of widget. virtual void removeAllChildren() override; virtual void removeAllChildrenWithCleanup(bool cleanup) override; //override "removeChild" method of widget. virtual void removeChild(Node* child, bool cleaup = true) override; //override "getChildren" method of widget. virtual Vector<Node*>& getChildren() override; virtual const Vector<Node*>& getChildren() const override; virtual ssize_t getChildrenCount() const override; virtual Node * getChildByTag(int tag) override; virtual Widget* getChildByName(const char* name) override; virtual bool onTouchBegan(Touch *touch, Event *unusedEvent) override; virtual void onTouchMoved(Touch *touch, Event *unusedEvent) override; virtual void onTouchEnded(Touch *touch, Event *unusedEvent) override; virtual void onTouchCancelled(Touch *touch, Event *unusedEvent) override; virtual void update(float dt) override; void setBounceEnabled(bool enabled); bool isBounceEnabled() const; void setInertiaScrollEnabled(bool enabled); bool isInertiaScrollEnabled() const; /** * Sets LayoutType. * * @see LayoutType * * @param LayoutType */ virtual void setLayoutType(LayoutType type) override; /** * Gets LayoutType. * * @see LayoutType * * @return LayoutType */ virtual LayoutType getLayoutType() const override; /** * Returns the "class name" of widget. */ virtual std::string getDescription() const override; virtual void onEnter() override; protected: virtual bool init() override; virtual void initRenderer() override; void moveChildren(float offsetX, float offsetY); void autoScrollChildren(float dt); void bounceChildren(float dt); void checkBounceBoundary(); bool checkNeedBounce(); void startAutoScrollChildrenWithOriginalSpeed(const Point& dir, float v, bool attenuated, float acceleration); void startAutoScrollChildrenWithDestination(const Point& des, float time, bool attenuated); void jumpToDestination(const Point& des); void stopAutoScrollChildren(); void startBounceChildren(float v); void stopBounceChildren(); bool checkCustomScrollDestination(float* touchOffsetX, float* touchOffsetY); virtual bool scrollChildren(float touchOffsetX, float touchOffsetY); bool bounceScrollChildren(float touchOffsetX, float touchOffsetY); void startRecordSlidAction(); virtual void endRecordSlidAction(); virtual void handlePressLogic(const Point &touchPoint) override; virtual void handleMoveLogic(const Point &touchPoint) override; virtual void handleReleaseLogic(const Point &touchPoint) override; virtual void interceptTouchEvent(int handleState,Widget* sender,const Point &touchPoint) override; virtual void checkChildInfo(int handleState,Widget* sender,const Point &touchPoint) override; void recordSlidTime(float dt); void scrollToTopEvent(); void scrollToBottomEvent(); void scrollToLeftEvent(); void scrollToRightEvent(); void scrollingEvent(); void bounceTopEvent(); void bounceBottomEvent(); void bounceLeftEvent(); void bounceRightEvent(); virtual void onSizeChanged() override; virtual Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; virtual void copyClonedWidgetChildren(Widget* model) override; virtual void setClippingEnabled(bool able) override{Layout::setClippingEnabled(able);}; virtual void doLayout() override; protected: Layout* _innerContainer; SCROLLVIEW_DIR _direction; Point _touchBeganPoint; Point _touchMovedPoint; Point _touchEndedPoint; Point _touchMovingPoint; Point _autoScrollDir; float _topBoundary; float _bottomBoundary; float _leftBoundary; float _rightBoundary; float _bounceTopBoundary; float _bounceBottomBoundary; float _bounceLeftBoundary; float _bounceRightBoundary; bool _autoScroll; float _autoScrollAddUpTime; float _autoScrollOriginalSpeed; float _autoScrollAcceleration; bool _isAutoScrollSpeedAttenuated; bool _needCheckAutoScrollDestination; Point _autoScrollDestination; bool _bePressed; float _slidTime; Point _moveChildPoint; float _childFocusCancelOffset; bool _leftBounceNeeded; bool _topBounceNeeded; bool _rightBounceNeeded; bool _bottomBounceNeeded; bool _bounceEnabled; bool _bouncing; Point _bounceDir; float _bounceOriginalSpeed; bool _inertiaScrollEnabled; Ref* _scrollViewEventListener; SEL_ScrollViewEvent _scrollViewEventSelector; }; } NS_CC_END #endif /* defined(__CocoGUI__ScrollView__) */
{'content_hash': '0ab7362ece2f4302154e0714ed870549', 'timestamp': '', 'source': 'github', 'line_count': 389, 'max_line_length': 128, 'avg_line_length': 29.308483290488432, 'alnum_prop': 0.676607315147794, 'repo_name': 'MiaoMiaosha/Cocos', 'id': '07e1fd14e7ca2dc58fd2ad45752598ce4282f41f', 'size': '12656', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SampleFlashImport/cocos2d/cocos/gui/UIScrollView.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1332950'}, {'name': 'C++', 'bytes': '14873098'}, {'name': 'Java', 'bytes': '326759'}, {'name': 'JavaScript', 'bytes': '726954'}, {'name': 'Lua', 'bytes': '267794'}, {'name': 'Objective-C', 'bytes': '929701'}, {'name': 'Objective-C++', 'bytes': '398253'}, {'name': 'Perl', 'bytes': '131258'}, {'name': 'Prolog', 'bytes': '1094'}, {'name': 'Python', 'bytes': '263634'}, {'name': 'Shell', 'bytes': '115543'}]}
package dbdoc.impl; import org.apache.log4j.Logger; import dbdoc.ProgressListener; /** * @author jk * */ public class LoggingProgressListener implements ProgressListener { private Logger logger; public LoggingProgressListener(Logger logger) { this.logger = logger; } /* * (non-Javadoc) * * @see dbdoc.ProgressListener#nextAction(java.lang.String, * java.lang.String) */ @Override public void nextAction(String objType, String objName) { if (ProgressListener.T_COLUMN.equals(objType)) { return; } logger.info(String.format("Processing %s %s", objType, objName)); } }
{'content_hash': 'edfd1371be79e9adbf420a69dcf0de95', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 67, 'avg_line_length': 18.363636363636363, 'alnum_prop': 0.7112211221122112, 'repo_name': 'extronics/dbdoc', 'id': '5514d1e9b8f9b03aeb08d2105dc4d132d5ad0e2e', 'size': '606', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/dbdoc/impl/LoggingProgressListener.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '116438'}, {'name': 'JavaScript', 'bytes': '103562'}]}
#include <jni.h> #include <string> #include <iomanip> #include <sstream> #include <fcntl.h> #include <android/asset_manager_jni.h> #include <android/log.h> #include <android/sharedmem.h> #include <sys/mman.h> #include "simple_model.h" extern "C" JNIEXPORT jlong JNICALL Java_com_example_android_nnapidemo_MainActivity_initModel( JNIEnv *env, jobject /* this */, jobject _assetManager, jstring _assetName) { // Get the file descriptor of the the model data file. AAssetManager *assetManager = AAssetManager_fromJava(env, _assetManager); const char *assetName = env->GetStringUTFChars(_assetName, NULL); AAsset *asset = AAssetManager_open(assetManager, assetName, AASSET_MODE_BUFFER); if(asset == nullptr) { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to open the asset."); return 0; } env->ReleaseStringUTFChars(_assetName, assetName); off_t offset, length; int fd = AAsset_openFileDescriptor(asset, &offset, &length); AAsset_close(asset); if (fd < 0) { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to open the model_data file descriptor."); return 0; } SimpleModel* nn_model = new SimpleModel(length, PROT_READ, fd, offset); if (!nn_model->CreateCompiledModel()) { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, "Failed to prepare the model."); return 0; } return (jlong)(uintptr_t)nn_model; } extern "C" JNIEXPORT jfloat JNICALL Java_com_example_android_nnapidemo_MainActivity_startCompute( JNIEnv *env, jobject /* this */, jlong _nnModel, jfloat inputValue1, jfloat inputValue2) { SimpleModel* nn_model = (SimpleModel*) _nnModel; float result = 0.0f; nn_model->Compute(inputValue1, inputValue2, &result); return result; } extern "C" JNIEXPORT void JNICALL Java_com_example_android_nnapidemo_MainActivity_destroyModel( JNIEnv *env, jobject /* this */, jlong _nnModel) { SimpleModel* nn_model = (SimpleModel*) _nnModel; delete(nn_model); }
{'content_hash': 'bbcd659ab262ead408cbda75e99be69d', 'timestamp': '', 'source': 'github', 'line_count': 75, 'max_line_length': 85, 'avg_line_length': 28.8, 'alnum_prop': 0.6458333333333334, 'repo_name': 'ggfan/android-ndk', 'id': '8c5f27ad46013711eeed306789cefc3b1fef3902', 'size': '2776', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kotlin-app/nn-sample-kotlinApp/app/src/main/cpp/nn_sample.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2240'}, {'name': 'C', 'bytes': '1161403'}, {'name': 'C++', 'bytes': '4001465'}, {'name': 'CMake', 'bytes': '41106'}, {'name': 'GLSL', 'bytes': '32592'}, {'name': 'Java', 'bytes': '275252'}, {'name': 'Kotlin', 'bytes': '9808'}, {'name': 'Makefile', 'bytes': '26484'}, {'name': 'Shell', 'bytes': '15405'}]}
<?xml version="1.0" encoding="utf-8" standalone="yes"?> <!-- Translated using Transifex web application. For support, or if you would like to to help out, please visit your language team! --> <!-- Russian language-Team URL: http://www.transifex.com/projects/p/xbmc-addons/language/ru/ --> <!-- Report language file syntax bugs at: [email protected] --> <strings> <string id="30002">Просмотр по стилю</string> <string id="30004">Поиск</string> <string id="30105">Показать подстили</string> <!-- Messages --> <string id="30200">Ошибка сети</string> </strings>
{'content_hash': '23dec4818f71f63311079d57dc8d026c', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 135, 'avg_line_length': 44.61538461538461, 'alnum_prop': 0.6862068965517242, 'repo_name': 'aplicatii-romanesti/allinclusive-kodi-pi', 'id': '37cc7d38ca12ad5ed35e3437655e7dd50d5eab02', 'size': '626', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': '.kodi/addons/plugin.video.itunes_podcasts/resources/language/Russian/strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Perl', 'bytes': '6178'}, {'name': 'Python', 'bytes': '8657978'}, {'name': 'Shell', 'bytes': '198'}]}
#ifndef SerializedResource_h #define SerializedResource_h #include "platform/SharedBuffer.h" #include "platform/weborigin/KURL.h" #include "wtf/Allocator.h" #include "wtf/text/WTFString.h" namespace blink { struct SerializedResource { DISALLOW_NEW_EXCEPT_PLACEMENT_NEW(); KURL url; String mimeType; RefPtr<SharedBuffer> data; SerializedResource(const KURL& url, const String& mimeType, PassRefPtr<SharedBuffer> data) : url(url) , mimeType(mimeType) , data(data) { } }; } // namespace blink #endif // SerializedResource_h
{'content_hash': '9e2cc22b1f573c051384458ed6ea9871', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 94, 'avg_line_length': 19.4, 'alnum_prop': 0.6941580756013745, 'repo_name': 'was4444/chromium.src', 'id': 'eb15f690b3f2f5dca4baea74972a106328314ddf', 'size': '2144', 'binary': False, 'copies': '9', 'ref': 'refs/heads/nw15', 'path': 'third_party/WebKit/Source/platform/SerializedResource.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE675_Duplicate_Operations_on_Resource__fopen_52b.c Label Definition File: CWE675_Duplicate_Operations_on_Resource.label.xml Template File: sources-sinks-52b.tmpl.c */ /* * @description * CWE: 675 Duplicate Operations on Resource * BadSource: fopen Open and close a file using fopen() and flose() * GoodSource: Open a file using fopen() * Sinks: * GoodSink: Do nothing * BadSink : Close the file * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files * * */ #include "std_testcase.h" #ifndef OMITBAD /* bad function declaration */ void CWE675_Duplicate_Operations_on_Resource__fopen_52c_badSink(FILE * data); void CWE675_Duplicate_Operations_on_Resource__fopen_52b_badSink(FILE * data) { CWE675_Duplicate_Operations_on_Resource__fopen_52c_badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void CWE675_Duplicate_Operations_on_Resource__fopen_52c_goodG2BSink(FILE * data); void CWE675_Duplicate_Operations_on_Resource__fopen_52b_goodG2BSink(FILE * data) { CWE675_Duplicate_Operations_on_Resource__fopen_52c_goodG2BSink(data); } /* goodB2G uses the BadSource with the GoodSink */ void CWE675_Duplicate_Operations_on_Resource__fopen_52c_goodB2GSink(FILE * data); void CWE675_Duplicate_Operations_on_Resource__fopen_52b_goodB2GSink(FILE * data) { CWE675_Duplicate_Operations_on_Resource__fopen_52c_goodB2GSink(data); } #endif /* OMITGOOD */
{'content_hash': 'ffdf5c7ec33bd8749582d6b533b14c5a', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 129, 'avg_line_length': 32.04, 'alnum_prop': 0.7303370786516854, 'repo_name': 'maurer/tiamat', 'id': '52aa4ab7bf54f160fcf8f01990a8830b4c5a347d', 'size': '1602', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'samples/Juliet/testcases/CWE675_Duplicate_Operations_on_Resource/CWE675_Duplicate_Operations_on_Resource__fopen_52b.c', 'mode': '33188', 'license': 'mit', 'language': []}
class TokyoMetro::App::Renderer::StationFacility::Platform < TokyoMetro::Factory::Decorate::MetaClass def initialize( request , station_facility_info ) super( request ) @station_facility_info = station_facility_info @platform_infos_grouped_by_railway_line = platform_infos_grouped_by_railway_line @type_of_platform_infos = type_of_platform_infos end def to_a ary = ::Array.new case @type_of_platform_infos when :between_wakoshi_and_hikawadai # puts @type_of_platform_infos ary << ::TokyoMetro::App::Renderer::StationFacility::Platform::Info::BetweenWakoshiAndHikawadai::Whole.new( request , @platform_infos_grouped_by_railway_line.values.first , ::Railway::Line::Info.where( id: railway_line_info_ids_of_platform_infos ) ) when :kotake_mukaihara # puts @type_of_platform_infos ary << ::TokyoMetro::App::Renderer::StationFacility::Platform::Info::KotakeMukaihara::Whole.new( request , @platform_infos_grouped_by_railway_line.values.first , ::Railway::Line::Info.where( id: railway_line_info_ids_of_platform_infos ) ) when :meguro_and_shirokanedai # puts @type_of_platform_infos ary << ::TokyoMetro::App::Renderer::StationFacility::Platform::Info::MeguroAndShirokanedai::Whole.new( request , @platform_infos_grouped_by_railway_line.values.first , ::Railway::Line::Info.where( same_as: [ "odpt.Railway:TokyoMetro.Namboku" , "odpt.Railway:Toei.Mita" ] ).order( :id ) ) when :shirokane_takanawa # puts @type_of_platform_infos ary << ::TokyoMetro::App::Renderer::StationFacility::Platform::Info::ShirokaneTakanawa::Whole.new( request , @platform_infos_grouped_by_railway_line.values.first , ::Railway::Line::Info.where( same_as: [ "odpt.Railway:TokyoMetro.Namboku" , "odpt.Railway:Toei.Mita" ] ).order( :id ) ) when :normal # puts @type_of_platform_infos @platform_infos_grouped_by_railway_line.each do | railway_line_info_id , platform_infos | ary << ::TokyoMetro::App::Renderer::StationFacility::Platform::Info::Normal::Whole.new( request , platform_infos , ::Railway::Line::Info.find( railway_line_info_id ) ) end end ::TokyoMetro::App::Renderer::StationFacility::Platform::List.new( @resuest , ary ) end def self.make_list( request , station_facility_info ) self.new( request , station_facility_info ).to_a end private def platform_infos_grouped_by_railway_line @station_facility_info.platform_infos.includes( :railway_direction , :platform_barrier_free_facility_infos , :platform_transfer_infos , :platform_surrounding_areas , :barrier_free_facility_infos , :surrounding_areas ).group_by( &:railway_line_info_id ) end def type_of_platform_infos if platform_infos_of_yurakucho_and_fukutoshin_line_between_wakoshi_and_hikawadai? :between_wakoshi_and_hikawadai elsif platform_infos_of_yurakucho_and_fukutoshin_line_at_kotake_mukaihara? :kotake_mukaihara elsif platform_infos_of_namboku_and_toei_mita_line_at_meguro_or_shirokanedai? :meguro_and_shirokanedai elsif platform_infos_of_namboku_and_toei_mita_line_at_shirokane_takanawa? :shirokane_takanawa else :normal end end def railway_line_info_ids_of_platform_infos @platform_infos_grouped_by_railway_line.keys.sort end # @!group 路線と駅の判定 def platform_infos_of_yurakucho_and_fukutoshin_line_between_wakoshi_and_hikawadai? platform_infos_of_yurakucho_and_fukutoshin_line? and between_wakoshi_and_hikawadai? end def platform_infos_of_yurakucho_and_fukutoshin_line_at_kotake_mukaihara? platform_infos_of_yurakucho_and_fukutoshin_line? and at_kotake_mukaihara? end def platform_infos_of_namboku_and_toei_mita_line_at_meguro_or_shirokanedai? platform_infos_of_namboku_line? and ( at_meguro? or at_shirokanedai? ) end def platform_infos_of_namboku_and_toei_mita_line_at_shirokane_takanawa? platform_infos_of_namboku_line? and at_shirokane_takanawa? end # @!group 路線の判定 def platform_infos_of_yurakucho_and_fukutoshin_line? platform_infos_of?( *( ::TokyoMetro::Modules::Dictionary::Common::RailwayLine::StringList.yurakucho_and_fukutoshin_line_same_as ) ) end def platform_infos_of_namboku_line? platform_infos_of?( "odpt.Railway:TokyoMetro.Namboku" ) end def platform_infos_of?( *ary ) railway_line_info_ids_of_platform_infos.map { | railway_line_info_id | ::Railway::Line::Info.find( railway_line_info_id ).same_as } == ary end # @!group 駅の判定 def between_wakoshi_and_hikawadai? ary = ::TokyoMetro::Modules::Dictionary::Common::Station::StringList.between_wakoshi_and_hikawadai_in_system at_these_stations?( ary ) end def between_meguro_and_shirokane_takanawa? ary = ::TokyoMetro::Modules::Dictionary::Common::Station::StringList.namboku_and_toei_mita_line_common_stations_in_system at_these_stations?( ary ) end [ :kotake_mukaihara , :meguro , :shirokanedai , :shirokane_takanawa ].each do | station_name | eval <<-DEF def at_#{ station_name }? at_these_stations?( "#{ station_name.camelize }" ) end DEF end def at_these_stations?( *stations_in_system ) [ stations_in_system ].flatten.map { | station | "odpt.StationFacility:TokyoMetro.#{station}" }.include?( @station_facility_info.same_as ) end # @!endgroup end
{'content_hash': '3ed0579530406e3b0b24bc9d8e57dcbe', 'timestamp': '', 'source': 'github', 'line_count': 155, 'max_line_length': 142, 'avg_line_length': 35.66451612903226, 'alnum_prop': 0.6892185238784371, 'repo_name': 'osorubeki-fujita/odpt_tokyo_metro', 'id': '99b733400afa36e755f785190d6e8099e64f1ea7', 'size': '5560', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/tokyo_metro/app/renderer/station_facility/platform.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '1712210'}, {'name': 'Shell', 'bytes': '115'}]}
'use strict'; describe('$compile', function() { var element, directive, $compile, $rootScope; beforeEach(module(provideLog, function($provide, $compileProvider){ element = null; directive = $compileProvider.directive; directive('log', function(log) { return { restrict: 'CAM', priority:0, compile: valueFn(function(scope, element, attrs) { log(attrs.log || 'LOG'); }) }; }); directive('highLog', function(log) { return { restrict: 'CAM', priority:3, compile: valueFn(function(scope, element, attrs) { log(attrs.highLog || 'HIGH'); })}; }); directive('mediumLog', function(log) { return { restrict: 'CAM', priority:2, compile: valueFn(function(scope, element, attrs) { log(attrs.mediumLog || 'MEDIUM'); })}; }); directive('greet', function() { return { restrict: 'CAM', priority:10, compile: valueFn(function(scope, element, attrs) { element.text("Hello " + attrs.greet); })}; }); directive('set', function() { return function(scope, element, attrs) { element.text(attrs.set); }; }); directive('mediumStop', valueFn({ priority: 2, terminal: true })); directive('stop', valueFn({ terminal: true })); directive('negativeStop', valueFn({ priority: -100, // even with negative priority we still should be able to stop descend terminal: true })); return function(_$compile_, _$rootScope_) { $rootScope = _$rootScope_; $compile = _$compile_; }; })); function compile(html) { element = angular.element(html); $compile(element)($rootScope); } afterEach(function(){ dealoc(element); }); describe('configuration', function() { it('should register a directive', function() { module(function() { directive('div', function(log) { return { restrict: 'ECA', link: function(scope, element) { log('OK'); element.text('SUCCESS'); } }; }) }); inject(function($compile, $rootScope, log) { element = $compile('<div></div>')($rootScope); expect(element.text()).toEqual('SUCCESS'); expect(log).toEqual('OK'); }) }); it('should allow registration of multiple directives with same name', function() { module(function() { directive('div', function(log) { return { restrict: 'ECA', link: { pre: log.fn('pre1'), post: log.fn('post1') } }; }); directive('div', function(log) { return { restrict: 'ECA', link: { pre: log.fn('pre2'), post: log.fn('post2') } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div></div>')($rootScope); expect(log).toEqual('pre1; pre2; post2; post1'); }); }); it('should throw an exception if a directive is called "hasOwnProperty"', function() { module(function() { expect(function() { directive('hasOwnProperty', function() { }); }).toThrowMinErr('ng','badname', "hasOwnProperty is not a valid directive name"); }); inject(function($compile) {}); }); }); describe('compile phase', function() { it('should attach scope to the document node when it is compiled explicitly', inject(function($document){ $compile($document)($rootScope); expect($document.scope()).toBe($rootScope); })); it('should wrap root text nodes in spans', inject(function($compile, $rootScope) { element = jqLite('<div>A&lt;a&gt;B&lt;/a&gt;C</div>'); var text = element.contents(); expect(text[0].nodeName).toEqual('#text'); text = $compile(text)($rootScope); expect(text[0].nodeName).toEqual('SPAN'); expect(element.find('span').text()).toEqual('A<a>B</a>C'); })); it('should not wrap root whitespace text nodes in spans', function() { element = jqLite( '<div> <div>A</div>\n '+ // The spaces and newlines here should not get wrapped '<div>B</div>C\t\n '+ // The "C", tabs and spaces here will be wrapped '</div>'); $compile(element.contents())($rootScope); var spans = element.find('span'); expect(spans.length).toEqual(1); expect(spans.text().indexOf('C')).toEqual(0); }); it('should not leak memory when there are top level empty text nodes', function() { var calcCacheSize = function() { var size = 0; forEach(jqLite.cache, function(item, key) { size++; }); return size; }; // We compile the contents of element (i.e. not element itself) // Then delete these contents and check the cache has been reset to zero // First with only elements at the top level element = jqLite('<div><div></div></div>'); $compile(element.contents())($rootScope); element.html(''); expect(calcCacheSize()).toEqual(0); // Next with non-empty text nodes at the top level // (in this case the compiler will wrap them in a <span>) element = jqLite('<div>xxx</div>'); $compile(element.contents())($rootScope); element.html(''); expect(calcCacheSize()).toEqual(0); // Next with comment nodes at the top level element = jqLite('<div><!-- comment --></div>'); $compile(element.contents())($rootScope); element.html(''); expect(calcCacheSize()).toEqual(0); // Finally with empty text nodes at the top level element = jqLite('<div> \n<div></div> </div>'); $compile(element.contents())($rootScope); element.html(''); expect(calcCacheSize()).toEqual(0); }); it('should not blow up when elements with no childNodes property are compiled', inject( function($compile, $rootScope) { // it turns out that when a browser plugin is bound to an DOM element (typically <object>), // the plugin's context rather than the usual DOM apis are exposed on this element, so // childNodes might not exist. if (msie < 9) return; element = jqLite('<div>{{1+2}}</div>'); element[0].childNodes[1] = {nodeType: 3, nodeName: 'OBJECT', textContent: 'fake node'}; if (!element[0].childNodes[1]) return; //browser doesn't support this kind of mocking expect(element[0].childNodes[1].textContent).toBe('fake node'); $compile(element)($rootScope); $rootScope.$apply(); // object's children can't be compiled in this case, so we expect them to be raw expect(element.html()).toBe("3"); })); describe('multiple directives per element', function() { it('should allow multiple directives per element', inject(function($compile, $rootScope, log){ element = $compile( '<span greet="angular" log="L" x-high-log="H" data-medium-log="M"></span>') ($rootScope); expect(element.text()).toEqual('Hello angular'); expect(log).toEqual('L; M; H'); })); it('should recurse to children', inject(function($compile, $rootScope){ element = $compile('<div>0<a set="hello">1</a>2<b set="angular">3</b>4</div>')($rootScope); expect(element.text()).toEqual('0hello2angular4'); })); it('should allow directives in classes', inject(function($compile, $rootScope, log) { element = $compile('<div class="greet: angular; log:123;"></div>')($rootScope); expect(element.html()).toEqual('Hello angular'); expect(log).toEqual('123'); })); it('should ignore not set CSS classes on SVG elements', inject(function($compile, $rootScope, log) { if (!window.SVGElement) return; // According to spec SVG element className property is readonly, but only FF // implements it this way which causes compile exceptions. element = $compile('<svg><text>{{1}}</text></svg>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1'); })); it('should allow directives in comments', inject( function($compile, $rootScope, log) { element = $compile('<div>0<!-- directive: log angular -->1</div>')($rootScope); expect(log).toEqual('angular'); } )); it('should receive scope, element, and attributes', function() { var injector; module(function() { directive('log', function($injector, $rootScope) { injector = $injector; return { restrict: 'CA', compile: function(element, templateAttr) { expect(typeof templateAttr.$normalize).toBe('function'); expect(typeof templateAttr.$set).toBe('function'); expect(isElement(templateAttr.$$element)).toBeTruthy(); expect(element.text()).toEqual('unlinked'); expect(templateAttr.exp).toEqual('abc'); expect(templateAttr.aa).toEqual('A'); expect(templateAttr.bb).toEqual('B'); expect(templateAttr.cc).toEqual('C'); return function(scope, element, attr) { expect(element.text()).toEqual('unlinked'); expect(attr).toBe(templateAttr); expect(scope).toEqual($rootScope); element.text('worked'); } } }; }); }); inject(function($rootScope, $compile, $injector) { element = $compile( '<div class="log" exp="abc" aa="A" x-Bb="B" daTa-cC="C">unlinked</div>')($rootScope); expect(element.text()).toEqual('worked'); expect(injector).toBe($injector); // verify that directive is injectable }); }); }); describe('error handling', function() { it('should handle exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('factoryError', function() { throw 'FactoryError'; }); directive('templateError', valueFn({ compile: function() { throw 'TemplateError'; } })); directive('linkingError', valueFn(function() { throw 'LinkingError'; })); }); inject(function($rootScope, $compile, $exceptionHandler) { element = $compile('<div factory-error template-error linking-error></div>')($rootScope); expect($exceptionHandler.errors[0]).toEqual('FactoryError'); expect($exceptionHandler.errors[1][0]).toEqual('TemplateError'); expect(ie($exceptionHandler.errors[1][1])). toEqual('<div factory-error linking-error template-error>'); expect($exceptionHandler.errors[2][0]).toEqual('LinkingError'); expect(ie($exceptionHandler.errors[2][1])). toEqual('<div class="ng-scope" factory-error linking-error template-error>'); // crazy stuff to make IE happy function ie(text) { var list = [], parts, elementName; parts = lowercase(text). replace('<', ''). replace('>', ''). split(' '); elementName = parts.shift(); parts.sort(); parts.unshift(elementName); forEach(parts, function(value, key){ if (value.substring(0,3) == 'ng-') { } else { value = value.replace('=""', ''); var match = value.match(/=(.*)/); if (match && match[1].charAt(0) != '"') { value = value.replace(/=(.*)/, '="$1"'); } list.push(value); } }); return '<' + list.join(' ') + '>'; } }); }); it('should allow changing the template structure after the current node', function() { module(function(){ directive('after', valueFn({ compile: function(element) { element.after('<span log>B</span>'); } })); }); inject(function($compile, $rootScope, log){ element = jqLite("<div><div after>A</div></div>"); $compile(element)($rootScope); expect(element.text()).toBe('AB'); expect(log).toEqual('LOG'); }); }); it('should allow changing the template structure after the current node inside ngRepeat', function() { module(function(){ directive('after', valueFn({ compile: function(element) { element.after('<span log>B</span>'); } })); }); inject(function($compile, $rootScope, log){ element = jqLite('<div><div ng-repeat="i in [1,2]"><div after>A</div></div></div>'); $compile(element)($rootScope); $rootScope.$digest(); expect(element.text()).toBe('ABAB'); expect(log).toEqual('LOG; LOG'); }); }); it('should allow modifying the DOM structure in post link fn', function() { module(function() { directive('removeNode', valueFn({ link: function($scope, $element) { $element.remove(); } })); }); inject(function($compile, $rootScope) { element = jqLite('<div><div remove-node></div><div>{{test}}</div></div>'); $rootScope.test = 'Hello'; $compile(element)($rootScope); $rootScope.$digest(); expect(element.children().length).toBe(1); expect(element.text()).toBe('Hello'); }); }) }); describe('compiler control', function() { describe('priority', function() { it('should honor priority', inject(function($compile, $rootScope, log){ element = $compile( '<span log="L" x-high-log="H" data-medium-log="M"></span>') ($rootScope); expect(log).toEqual('L; M; H'); })); }); describe('terminal', function() { it('should prevent further directives from running', inject(function($rootScope, $compile) { element = $compile('<div negative-stop><a set="FAIL">OK</a></div>')($rootScope); expect(element.text()).toEqual('OK'); } )); it('should prevent further directives from running, but finish current priority level', inject(function($rootScope, $compile, log) { // class is processed after attrs, so putting log in class will put it after // the stop in the current level. This proves that the log runs after stop element = $compile( '<div high-log medium-stop log class="medium-log"><a set="FAIL">OK</a></div>')($rootScope); expect(element.text()).toEqual('OK'); expect(log.toArray().sort()).toEqual(['HIGH', 'MEDIUM']); }) ); }); describe('restrict', function() { it('should allow restriction of attributes', function() { module(function() { forEach({div:'E', attr:'A', clazz:'C', all:'EAC'}, function(restrict, name) { directive(name, function(log) { return { restrict: restrict, compile: valueFn(function(scope, element, attr) { log(name); }) }; }); }); }); inject(function($rootScope, $compile, log) { dealoc($compile('<span div class="div"></span>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<div></div>')($rootScope)); expect(log).toEqual('div'); log.reset(); dealoc($compile('<attr class=""attr"></attr>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<span attr></span>')($rootScope)); expect(log).toEqual('attr'); log.reset(); dealoc($compile('<clazz clazz></clazz>')($rootScope)); expect(log).toEqual(''); log.reset(); dealoc($compile('<span class="clazz"></span>')($rootScope)); expect(log).toEqual('clazz'); log.reset(); dealoc($compile('<all class="all" all></all>')($rootScope)); expect(log).toEqual('all; all; all'); }); }); }); describe('template', function() { beforeEach(module(function() { directive('replace', valueFn({ restrict: 'CAM', replace: true, template: '<div class="log" style="width: 10px" high-log>Replace!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('append', valueFn({ restrict: 'CAM', template: '<div class="log" style="width: 10px" high-log>Append!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('replaceWithInterpolatedClass', valueFn({ replace: true, template: '<div class="class_{{1+1}}">Replace with interpolated class!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); directive('replaceWithInterpolatedStyle', valueFn({ replace: true, template: '<div style="width:{{1+1}}px">Replace with interpolated style!</div>', compile: function(element, attr) { attr.$set('compiled', 'COMPILED'); expect(element).toBe(attr.$$element); } })); })); it('should replace element with template', inject(function($compile, $rootScope) { element = $compile('<div><div replace>ignore</div><div>')($rootScope); expect(element.text()).toEqual('Replace!'); expect(element.find('div').attr('compiled')).toEqual('COMPILED'); })); it('should append element with template', inject(function($compile, $rootScope) { element = $compile('<div><div append>ignore</div><div>')($rootScope); expect(element.text()).toEqual('Append!'); expect(element.find('div').attr('compiled')).toEqual('COMPILED'); })); it('should compile template when replacing', inject(function($compile, $rootScope, log) { element = $compile('<div><div replace medium-log>ignore</div><div>') ($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Replace!'); expect(log).toEqual('LOG; HIGH; MEDIUM'); })); it('should compile template when appending', inject(function($compile, $rootScope, log) { element = $compile('<div><div append medium-log>ignore</div><div>') ($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Append!'); expect(log).toEqual('LOG; HIGH; MEDIUM'); })); it('should merge attributes including style attr', inject(function($compile, $rootScope) { element = $compile( '<div><div replace class="medium-log" style="height: 20px" ></div><div>') ($rootScope); var div = element.find('div'); expect(div.hasClass('medium-log')).toBe(true); expect(div.hasClass('log')).toBe(true); expect(div.css('width')).toBe('10px'); expect(div.css('height')).toBe('20px'); expect(div.attr('replace')).toEqual(''); expect(div.attr('high-log')).toEqual(''); })); it('should prevent multiple templates per element', inject(function($compile) { try { $compile('<div><span replace class="replace"></span></div>'); this.fail(new Error('should have thrown Multiple directives error')); } catch(e) { expect(e.message).toMatch(/Multiple directives .* asking for template/); } })); it('should play nice with repeater when replacing', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1,2]" replace></div>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Replace!Replace!'); })); it('should play nice with repeater when appending', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1,2]" append></div>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('Append!Append!'); })); it('should handle interpolated css class from replacing directive', inject( function($compile, $rootScope) { element = $compile('<div replace-with-interpolated-class></div>')($rootScope); $rootScope.$digest(); expect(element).toHaveClass('class_2'); })); if (!msie || msie > 10) { // style interpolation not working on IE<11. it('should handle interpolated css style from replacing directive', inject( function($compile, $rootScope) { element = $compile('<div replace-with-interpolated-style></div>')($rootScope); $rootScope.$digest(); expect(element.css('width')).toBe('2px'); })); } it('should merge interpolated css class', inject(function($compile, $rootScope) { element = $compile('<div class="one {{cls}} three" replace></div>')($rootScope); $rootScope.$apply(function() { $rootScope.cls = 'two'; }); expect(element).toHaveClass('one'); expect(element).toHaveClass('two'); // interpolated expect(element).toHaveClass('three'); expect(element).toHaveClass('log'); // merged from replace directive template })); it('should merge interpolated css class with ngRepeat', inject(function($compile, $rootScope) { element = $compile( '<div>' + '<div ng-repeat="i in [1]" class="one {{cls}} three" replace></div>' + '</div>')($rootScope); $rootScope.$apply(function() { $rootScope.cls = 'two'; }); var child = element.find('div').eq(0); expect(child).toHaveClass('one'); expect(child).toHaveClass('two'); // interpolated expect(child).toHaveClass('three'); expect(child).toHaveClass('log'); // merged from replace directive template })); it("should fail if replacing and template doesn't have a single root element", function() { module(function() { directive('noRootElem', function() { return { replace: true, template: 'dada' } }); directive('multiRootElem', function() { return { replace: true, template: '<div></div><div></div>' } }); directive('singleRootWithWhiteSpace', function() { return { replace: true, template: ' <div></div> \n' } }); }); inject(function($compile) { expect(function() { $compile('<p no-root-elem></p>'); }).toThrowMinErr("$compile", "tplrt", "Template for directive 'noRootElem' must have exactly one root element. "); expect(function() { $compile('<p multi-root-elem></p>'); }).toThrowMinErr("$compile", "tplrt", "Template for directive 'multiRootElem' must have exactly one root element. "); // ws is ok expect(function() { $compile('<p single-root-with-white-space></p>'); }).not.toThrow(); }); }); }); describe('template as function', function() { beforeEach(module(function() { directive('myDirective', valueFn({ replace: true, template: function($element, $attrs) { expect($element.text()).toBe('original content'); expect($attrs.myDirective).toBe('some value'); return '<div id="templateContent">template content</div>'; }, compile: function($element, $attrs) { expect($element.text()).toBe('template content'); expect($attrs.id).toBe('templateContent'); } })); })); it('should evaluate `template` when defined as fn and use returned string as template', inject( function($compile, $rootScope) { element = $compile('<div my-directive="some value">original content<div>')($rootScope); expect(element.text()).toEqual('template content'); })); }); describe('templateUrl', function() { beforeEach(module( function() { directive('hello', valueFn({ restrict: 'CAM', templateUrl: 'hello.html', transclude: true })); directive('cau', valueFn({ restrict: 'CAM', templateUrl: 'cau.html' })); directive('crossDomainTemplate', valueFn({ restrict: 'CAM', templateUrl: 'http://example.com/should-not-load.html' })); directive('trustedTemplate', function($sce) { return { restrict: 'CAM', templateUrl: function() { return $sce.trustAsResourceUrl('http://example.com/trusted-template.html'); }}; }); directive('cError', valueFn({ restrict: 'CAM', templateUrl:'error.html', compile: function() { throw Error('cError'); } })); directive('lError', valueFn({ restrict: 'CAM', templateUrl: 'error.html', compile: function() { throw Error('lError'); } })); directive('iHello', valueFn({ restrict: 'CAM', replace: true, templateUrl: 'hello.html' })); directive('iCau', valueFn({ restrict: 'CAM', replace: true, templateUrl:'cau.html' })); directive('iCError', valueFn({ restrict: 'CAM', replace: true, templateUrl:'error.html', compile: function() { throw Error('cError'); } })); directive('iLError', valueFn({ restrict: 'CAM', replace: true, templateUrl: 'error.html', compile: function() { throw Error('lError'); } })); directive('replace', valueFn({ replace: true, template: '<span>Hello, {{name}}!</span>' })); } )); it('should not load cross domain templates by default', inject( function($compile, $rootScope, $templateCache, $sce) { expect(function() { $templateCache.put('http://example.com/should-not-load.html', 'Should not load even if in cache.'); $compile('<div class="crossDomainTemplate"></div>')($rootScope); }).toThrowMinErr('$sce', 'insecurl', 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: http://example.com/should-not-load.html'); })); it('should load cross domain templates when trusted', inject( function($compile, $httpBackend, $rootScope, $sce) { $httpBackend.expect('GET', 'http://example.com/trusted-template.html').respond('<span>example.com/trusted_template_contents</span>'); element = $compile('<div class="trustedTemplate"></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div class="trustedTemplate"></div>'); $httpBackend.flush(); expect(sortedHtml(element)). toEqual('<div class="trustedTemplate"><span>example.com/trusted_template_contents</span></div>'); })); it('should append template via $http and cache it in $templateCache', inject( function($compile, $httpBackend, $templateCache, $rootScope, $browser) { $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span> World!'); $templateCache.put('cau.html', '<span>Cau!</span>'); element = $compile('<div><b class="hello">ignore</b><b class="cau">ignore</b></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div><b class="hello"></b><b class="cau"></b></div>'); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"></b><b class="cau"><span>Cau!</span></b></div>'); $httpBackend.flush(); expect(sortedHtml(element)).toEqual( '<div>' + '<b class="hello"><span>Hello!</span> World!</b>' + '<b class="cau"><span>Cau!</span></b>' + '</div>'); } )); it('should inline template via $http and cache it in $templateCache', inject( function($compile, $httpBackend, $templateCache, $rootScope) { $httpBackend.expect('GET', 'hello.html').respond('<span>Hello!</span>'); $templateCache.put('cau.html', '<span>Cau!</span>'); element = $compile('<div><b class=i-hello>ignore</b><b class=i-cau>ignore</b></div>')($rootScope); expect(sortedHtml(element)). toEqual('<div><b class="i-hello"></b><b class="i-cau"></b></div>'); $rootScope.$digest(); expect(sortedHtml(element)).toBeOneOf( '<div><b class="i-hello"></b><span class="i-cau">Cau!</span></div>', '<div><b class="i-hello"></b><span class="i-cau" i-cau="">Cau!</span></div>' //ie8 ); $httpBackend.flush(); expect(sortedHtml(element)).toBeOneOf( '<div><span class="i-hello">Hello!</span><span class="i-cau">Cau!</span></div>', '<div><span class="i-hello" i-hello="">Hello!</span><span class="i-cau" i-cau="">Cau!</span></div>' //ie8 ); } )); it('should compile, link and flush the template append', inject( function($compile, $templateCache, $rootScope, $browser) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class="hello"></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>'); } )); it('should compile, link and flush the template inline', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class=i-hello></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)).toBeOneOf( '<div><span class="i-hello">Hello, Elvis!</span></div>', '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8 ); } )); it('should compile, flush and link the template append', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div><b class="hello"></b></div>'); element = template($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span>Hello, Elvis!</span></b></div>'); } )); it('should compile, flush and link the template inline', inject( function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<span>Hello, {{name}}!</span>'); $rootScope.name = 'Elvis'; var template = $compile('<div><b class=i-hello></b></div>'); element = template($rootScope); $rootScope.$digest(); expect(sortedHtml(element)).toBeOneOf( '<div><span class="i-hello">Hello, Elvis!</span></div>', '<div><span class="i-hello" i-hello="">Hello, Elvis!</span></div>' //ie8 ); } )); it('should compile template when replacing element in another template', inject(function($compile, $templateCache, $rootScope) { $templateCache.put('hello.html', '<div replace></div>'); $rootScope.name = 'Elvis'; element = $compile('<div><b class="hello"></b></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<div><b class="hello"><span replace="">Hello, Elvis!</span></b></div>'); })); it('should compile template when replacing root element', inject(function($compile, $templateCache, $rootScope) { $rootScope.name = 'Elvis'; element = $compile('<div replace></div>')($rootScope); $rootScope.$digest(); expect(sortedHtml(element)). toEqual('<span replace="">Hello, Elvis!</span>'); })); it('should resolve widgets after cloning in append mode', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>'); $httpBackend.expect('GET', 'error.html').respond('<div></div>'); $templateCache.put('cau.html', '<span>{{name}}</span>'); $rootScope.greeting = 'Hello'; $rootScope.name = 'Elvis'; var template = $compile( '<div>' + '<b class="hello"></b>' + '<b class="cau"></b>' + '<b class=c-error></b>' + '<b class=l-error></b>' + '</div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Hello Elvis'); expect(e2.text()).toEqual('Hello Elvis'); expect($exceptionHandler.errors.length).toEqual(2); expect($exceptionHandler.errors[0][0].message).toEqual('cError'); expect($exceptionHandler.errors[1][0].message).toEqual('lError'); dealoc(e1); dealoc(e2); }); }); it('should resolve widgets after cloning in inline mode', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($compile, $templateCache, $rootScope, $httpBackend, $browser, $exceptionHandler) { $httpBackend.expect('GET', 'hello.html').respond('<span>{{greeting}} </span>'); $httpBackend.expect('GET', 'error.html').respond('<div></div>'); $templateCache.put('cau.html', '<span>{{name}}</span>'); $rootScope.greeting = 'Hello'; $rootScope.name = 'Elvis'; var template = $compile( '<div>' + '<b class=i-hello></b>' + '<b class=i-cau></b>' + '<b class=i-c-error></b>' + '<b class=i-l-error></b>' + '</div>'); var e1; var e2; e1 = template($rootScope.$new(), noop); // clone expect(e1.text()).toEqual(''); $httpBackend.flush(); e2 = template($rootScope.$new(), noop); // clone $rootScope.$digest(); expect(e1.text()).toEqual('Hello Elvis'); expect(e2.text()).toEqual('Hello Elvis'); expect($exceptionHandler.errors.length).toEqual(2); expect($exceptionHandler.errors[0][0].message).toEqual('cError'); expect($exceptionHandler.errors[1][0].message).toEqual('lError'); dealoc(e1); dealoc(e2); }); }); it('should be implicitly terminal and not compile placeholder content in append', inject( function($compile, $templateCache, $rootScope, log) { // we can't compile the contents because that would result in a memory leak $templateCache.put('hello.html', 'Hello!'); element = $compile('<div><b class="hello"><div log></div></b></div>')($rootScope); expect(log).toEqual(''); } )); it('should be implicitly terminal and not compile placeholder content in inline', inject( function($compile, $templateCache, $rootScope, log) { // we can't compile the contents because that would result in a memory leak $templateCache.put('hello.html', 'Hello!'); element = $compile('<div><b class=i-hello><div log></div></b></div>')($rootScope); expect(log).toEqual(''); } )); it('should throw an error and clear element content if the template fails to load', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html').respond(404, 'Not Found!'); element = $compile('<div><b class="hello">content</b></div>')($rootScope); expect(function() { $httpBackend.flush(); }).toThrowMinErr('$compile', 'tpload', 'Failed to load template: hello.html'); expect(sortedHtml(element)).toBe('<div><b class="hello"></b></div>'); } )); it('should prevent multiple templates per element', function() { module(function() { directive('sync', valueFn({ restrict: 'C', template: '<span></span>' })); directive('async', valueFn({ restrict: 'C', templateUrl: 'template.html' })); }); inject(function($compile, $httpBackend){ $httpBackend.whenGET('template.html').respond('<p>template.html</p>'); expect(function() { $compile('<div><div class="sync async"></div></div>'); $httpBackend.flush(); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [async, sync] asking for template on: '+ '<div class="sync async">'); }); }); describe('delay compile / linking functions until after template is resolved', function(){ var template; beforeEach(module(function() { function logDirective (name, priority, options) { directive(name, function(log) { return (extend({ priority: priority, compile: function() { log(name + '-C'); return { pre: function() { log(name + '-PreL'); }, post: function() { log(name + '-PostL'); } } } }, options || {})); }); } logDirective('first', 10); logDirective('second', 5, { templateUrl: 'second.html' }); logDirective('third', 3); logDirective('last', 0); logDirective('iFirst', 10, {replace: true}); logDirective('iSecond', 5, {replace: true, templateUrl: 'second.html' }); logDirective('iThird', 3, {replace: true}); logDirective('iLast', 0, {replace: true}); })); it('should flush after link append', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>'); template = $compile('<div><span first second last></span></div>'); element = template($rootScope); expect(log).toEqual('first-C'); log('FLUSH'); $httpBackend.flush(); $rootScope.$digest(); expect(log).toEqual( 'first-C; FLUSH; second-C; last-C; third-C; ' + 'first-PreL; second-PreL; last-PreL; third-PreL; ' + 'third-PostL; last-PostL; second-PostL; first-PostL'); var span = element.find('span'); expect(span.attr('first')).toEqual(''); expect(span.attr('second')).toEqual(''); expect(span.find('div').attr('third')).toEqual(''); expect(span.attr('last')).toEqual(''); expect(span.text()).toEqual('3'); })); it('should flush after link inline', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>'); template = $compile('<div><span i-first i-second i-last></span></div>'); element = template($rootScope); expect(log).toEqual('iFirst-C'); log('FLUSH'); $httpBackend.flush(); $rootScope.$digest(); expect(log).toEqual( 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' + 'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' + 'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL'); var div = element.find('div'); expect(div.attr('i-first')).toEqual(''); expect(div.attr('i-second')).toEqual(''); expect(div.attr('i-third')).toEqual(''); expect(div.attr('i-last')).toEqual(''); expect(div.text()).toEqual('3'); })); it('should flush before link append', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div third>{{1+2}}</div>'); template = $compile('<div><span first second last></span></div>'); expect(log).toEqual('first-C'); log('FLUSH'); $httpBackend.flush(); expect(log).toEqual('first-C; FLUSH; second-C; last-C; third-C'); element = template($rootScope); $rootScope.$digest(); expect(log).toEqual( 'first-C; FLUSH; second-C; last-C; third-C; ' + 'first-PreL; second-PreL; last-PreL; third-PreL; ' + 'third-PostL; last-PostL; second-PostL; first-PostL'); var span = element.find('span'); expect(span.attr('first')).toEqual(''); expect(span.attr('second')).toEqual(''); expect(span.find('div').attr('third')).toEqual(''); expect(span.attr('last')).toEqual(''); expect(span.text()).toEqual('3'); })); it('should flush before link inline', inject( function($compile, $rootScope, $httpBackend, log) { $httpBackend.expect('GET', 'second.html').respond('<div i-third>{{1+2}}</div>'); template = $compile('<div><span i-first i-second i-last></span></div>'); expect(log).toEqual('iFirst-C'); log('FLUSH'); $httpBackend.flush(); expect(log).toEqual('iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C'); element = template($rootScope); $rootScope.$digest(); expect(log).toEqual( 'iFirst-C; FLUSH; iSecond-C; iThird-C; iLast-C; ' + 'iFirst-PreL; iSecond-PreL; iThird-PreL; iLast-PreL; ' + 'iLast-PostL; iThird-PostL; iSecond-PostL; iFirst-PostL'); var div = element.find('div'); expect(div.attr('i-first')).toEqual(''); expect(div.attr('i-second')).toEqual(''); expect(div.attr('i-third')).toEqual(''); expect(div.attr('i-last')).toEqual(''); expect(div.text()).toEqual('3'); })); }); it('should allow multiple elements in template', inject(function($compile, $httpBackend) { $httpBackend.expect('GET', 'hello.html').respond('before <b>mid</b> after'); element = jqLite('<div hello></div>'); $compile(element); $httpBackend.flush(); expect(element.text()).toEqual('before mid after'); })); it('should work when directive is on the root element', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html'). respond('<span>3==<span ng-transclude></span></span>'); element = jqLite('<b class="hello">{{1+2}}</b>'); $compile(element)($rootScope); $httpBackend.flush(); expect(element.text()).toEqual('3==3'); } )); it('should work when directive is in a repeater', inject( function($compile, $httpBackend, $rootScope) { $httpBackend.expect('GET', 'hello.html'). respond('<span>i=<span ng-transclude></span>;</span>'); element = jqLite('<div><b class=hello ng-repeat="i in [1,2]">{{i}}</b></div>'); $compile(element)($rootScope); $httpBackend.flush(); expect(element.text()).toEqual('i=1;i=2;'); } )); it("should fail if replacing and template doesn't have a single root element", function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('template', function() { return { replace: true, templateUrl: 'template.html' } }); }); inject(function($compile, $templateCache, $rootScope, $exceptionHandler) { // no root element $templateCache.put('template.html', 'dada'); $compile('<p template></p>'); $rootScope.$digest(); expect($exceptionHandler.errors.pop().message). toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/); // multi root $templateCache.put('template.html', '<div></div><div></div>'); $compile('<p template></p>'); $rootScope.$digest(); expect($exceptionHandler.errors.pop().message). toMatch(/\[\$compile:tplrt\] Template for directive 'template' must have exactly one root element\. template\.html/); // ws is ok $templateCache.put('template.html', ' <div></div> \n'); $compile('<p template></p>'); $rootScope.$apply(); expect($exceptionHandler.errors).toEqual([]); }); }); it('should resume delayed compilation without duplicates when in a repeater', function() { // this is a test for a regression // scope creation, isolate watcher setup, controller instantiation, etc should happen // only once even if we are dealing with delayed compilation of a node due to templateUrl // and the template node is in a repeater var controllerSpy = jasmine.createSpy('controller'); module(function($compileProvider) { $compileProvider.directive('delayed', valueFn({ controller: controllerSpy, templateUrl: 'delayed.html', scope: { title: '@' } })); }); inject(function($templateCache, $compile, $rootScope) { $rootScope.coolTitle = 'boom!'; $templateCache.put('delayed.html', '<div>{{title}}</div>'); element = $compile( '<div><div ng-repeat="i in [1,2]"><div delayed title="{{coolTitle + i}}"></div>|</div></div>' )($rootScope); $rootScope.$apply(); expect(controllerSpy.callCount).toBe(2); expect(element.text()).toBe('boom!1|boom!2|'); }); }); it('should support templateUrl with replace', function() { // a regression https://github.com/angular/angular.js/issues/3792 module(function($compileProvider) { $compileProvider.directive('simple', function() { return { templateUrl: '/some.html', replace: true }; }); }); inject(function($templateCache, $rootScope, $compile) { $templateCache.put('/some.html', '<div ng-switch="i">' + '<div ng-switch-when="1">i = 1</div>' + '<div ng-switch-default>I dont know what `i` is.</div>' + '</div>'); element = $compile('<div simple></div>')($rootScope); $rootScope.$apply(function() { $rootScope.i = 1; }); expect(element.html()).toContain('i = 1'); }); }); }); describe('templateUrl as function', function() { beforeEach(module(function() { directive('myDirective', valueFn({ replace: true, templateUrl: function($element, $attrs) { expect($element.text()).toBe('original content'); expect($attrs.myDirective).toBe('some value'); return 'my-directive.html'; }, compile: function($element, $attrs) { expect($element.text()).toBe('template content'); expect($attrs.id).toBe('templateContent'); } })); })); it('should evaluate `templateUrl` when defined as fn and use returned value as url', inject( function($compile, $rootScope, $templateCache) { $templateCache.put('my-directive.html', '<div id="templateContent">template content</span>'); element = $compile('<div my-directive="some value">original content<div>')($rootScope); expect(element.text()).toEqual(''); $rootScope.$digest(); expect(element.text()).toEqual('template content'); })); }); describe('scope', function() { var iscope; beforeEach(module(function() { forEach(['', 'a', 'b'], function(name) { directive('scope' + uppercase(name), function(log) { return { scope: true, restrict: 'CA', compile: function() { return {pre: function (scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }}; } }; }); directive('iscope' + uppercase(name), function(log) { return { scope: {}, restrict: 'CA', compile: function() { return function (scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScopeNoTemplate')).toBe(scope); }; } }; }); directive('tscope' + uppercase(name), function(log) { return { scope: true, restrict: 'CA', templateUrl: 'tscope.html', compile: function() { return function (scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }; } }; }); directive('trscope' + uppercase(name), function(log) { return { scope: true, replace: true, restrict: 'CA', templateUrl: 'trscope.html', compile: function() { return function (scope, element) { log(scope.$id); expect(element.data('$scope')).toBe(scope); }; } }; }); directive('tiscope' + uppercase(name), function(log) { return { scope: {}, restrict: 'CA', templateUrl: 'tiscope.html', compile: function() { return function (scope, element) { iscope = scope; log(scope.$id); expect(element.data('$isolateScope')).toBe(scope); }; } }; }); }); directive('log', function(log) { return { restrict: 'CA', link: {pre: function(scope) { log('log-' + scope.$id + '-' + (scope.$parent && scope.$parent.$id || 'no-parent')); }} }; }); })); it('should allow creation of new scopes', inject(function($rootScope, $compile, log) { element = $compile('<div><span scope><a log></a></span></div>')($rootScope); expect(log).toEqual('002; log-002-001; LOG'); expect(element.find('span').hasClass('ng-scope')).toBe(true); })); it('should allow creation of new isolated scopes for directives', inject( function($rootScope, $compile, log) { element = $compile('<div><span iscope><a log></a></span></div>')($rootScope); expect(log).toEqual('log-001-no-parent; LOG; 002'); $rootScope.name = 'abc'; expect(iscope.$parent).toBe($rootScope); expect(iscope.name).toBeUndefined(); })); it('should allow creation of new scopes for directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'tscope.html').respond('<a log>{{name}}; scopeId: {{$id}}</a>'); element = $compile('<div><span tscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-002-001; LOG; 002'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 002'); expect(element.find('span').scope().$id).toBe('002'); })); it('should allow creation of new scopes for replace directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'trscope.html'). respond('<p><a log>{{name}}; scopeId: {{$id}}</a></p>'); element = $compile('<div><span trscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-002-001; LOG; 002'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 002'); expect(element.find('a').scope().$id).toBe('002'); })); it('should allow creation of new scopes for replace directives with templates in a repeater', inject(function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'trscope.html'). respond('<p><a log>{{name}}; scopeId: {{$id}} |</a></p>'); element = $compile('<div><span ng-repeat="i in [1,2,3]" trscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-003-002; LOG; 003; log-005-004; LOG; 005; log-007-006; LOG; 007'); $rootScope.name = 'Jozo'; $rootScope.$apply(); expect(element.text()).toBe('Jozo; scopeId: 003 |Jozo; scopeId: 005 |Jozo; scopeId: 007 |'); expect(element.find('p').scope().$id).toBe('003'); expect(element.find('a').scope().$id).toBe('003'); })); it('should allow creation of new isolated scopes for directives with templates', inject( function($rootScope, $compile, log, $httpBackend) { $httpBackend.expect('GET', 'tiscope.html').respond('<a log></a>'); element = $compile('<div><span tiscope></span></div>')($rootScope); $httpBackend.flush(); expect(log).toEqual('log-002-001; LOG; 002'); $rootScope.name = 'abc'; expect(iscope.$parent).toBe($rootScope); expect(iscope.name).toBeUndefined(); })); it('should correctly create the scope hierachy', inject( function($rootScope, $compile, log) { element = $compile( '<div>' + //1 '<b class=scope>' + //2 '<b class=scope><b class=log></b></b>' + //3 '<b class=log></b>' + '</b>' + '<b class=scope>' + //4 '<b class=log></b>' + '</b>' + '</div>' )($rootScope); expect(log).toEqual('002; 003; log-003-002; LOG; log-002-001; LOG; 004; log-004-001; LOG'); }) ); it('should allow more than one new scope directives per element, but directives should share' + 'the scope', inject( function($rootScope, $compile, log) { element = $compile('<div class="scope-a; scope-b"></div>')($rootScope); expect(log).toEqual('002; 002'); }) ); it('should not allow more then one isolate scope creation per element', inject( function($rootScope, $compile) { expect(function(){ $compile('<div class="iscope-a; scope-b"></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [iscopeA, scopeB] asking for new/isolated scope on: ' + '<div class="iscope-a; scope-b">'); }) ); it('should create new scope even at the root of the template', inject( function($rootScope, $compile, log) { element = $compile('<div scope-a></div>')($rootScope); expect(log).toEqual('002'); }) ); it('should create isolate scope even at the root of the template', inject( function($rootScope, $compile, log) { element = $compile('<div iscope></div>')($rootScope); expect(log).toEqual('002'); }) ); describe('scope()/isolate() scope getters', function() { describe('with no directives', function() { it('should return the scope of the parent node', inject( function($rootScope, $compile) { element = $compile('<div></div>')($rootScope); expect(element.scope()).toBe($rootScope); }) ); }); describe('with new scope directives', function() { it('should return the new scope at the directive element', inject( function($rootScope, $compile) { element = $compile('<div scope></div>')($rootScope); expect(element.scope().$parent).toBe($rootScope); }) ); it('should return the new scope for children in the original template', inject( function($rootScope, $compile) { element = $compile('<div scope><a></a></div>')($rootScope); expect(element.find('a').scope().$parent).toBe($rootScope); }) ); it('should return the new scope for children in the directive template', inject( function($rootScope, $compile, $httpBackend) { $httpBackend.expect('GET', 'tscope.html').respond('<a></a>'); element = $compile('<div tscope></div>')($rootScope); $httpBackend.flush(); expect(element.find('a').scope().$parent).toBe($rootScope); }) ); }); describe('with isolate scope directives', function() { it('should return the root scope for directives at the root element', inject( function($rootScope, $compile) { element = $compile('<div iscope></div>')($rootScope); expect(element.scope()).toBe($rootScope); }) ); it('should return the non-isolate scope at the directive element', inject( function($rootScope, $compile) { var directiveElement; element = $compile('<div><div iscope></div></div>')($rootScope); directiveElement = element.children(); expect(directiveElement.scope()).toBe($rootScope); expect(directiveElement.isolateScope().$parent).toBe($rootScope); }) ); it('should return the isolate scope for children in the original template', inject( function($rootScope, $compile) { element = $compile('<div iscope><a></a></div>')($rootScope); expect(element.find('a').scope()).toBe($rootScope); //xx }) ); it('should return the isolate scope for children in directive template', inject( function($rootScope, $compile, $httpBackend) { $httpBackend.expect('GET', 'tiscope.html').respond('<a></a>'); element = $compile('<div tiscope></div>')($rootScope); expect(element.isolateScope()).toBeUndefined(); // this is the current behavior, not desired feature $httpBackend.flush(); expect(element.find('a').scope()).toBe(element.isolateScope()); expect(element.isolateScope()).not.toBe($rootScope); }) ); }); describe('with isolate scope directives and directives that manually create a new scope', function() { it('should return the new scope at the directive element', inject( function($rootScope, $compile) { var directiveElement; element = $compile('<div><a ng-if="true" iscope></a></div>')($rootScope); $rootScope.$apply(); directiveElement = element.find('a'); expect(directiveElement.scope().$parent).toBe($rootScope); expect(directiveElement.scope()).not.toBe(directiveElement.isolateScope()); }) ); it('should return the isolate scope for child elements', inject( function($rootScope, $compile, $httpBackend) { var directiveElement, child; $httpBackend.expect('GET', 'tiscope.html').respond('<span></span>'); element = $compile('<div><a ng-if="true" tiscope></a></div>')($rootScope); $rootScope.$apply(); $httpBackend.flush(); directiveElement = element.find('a'); child = directiveElement.find('span'); expect(child.scope()).toBe(directiveElement.isolateScope()); }) ); }); }); }); }); }); describe('interpolation', function() { var observeSpy, directiveAttrs; beforeEach(module(function() { directive('observer', function() { return function(scope, elm, attr) { directiveAttrs = attr; observeSpy = jasmine.createSpy('$observe attr'); expect(attr.$observe('someAttr', observeSpy)).toBe(observeSpy); }; }); directive('replaceSomeAttr', valueFn({ compile: function(element, attr) { attr.$set('someAttr', 'bar-{{1+1}}'); expect(element).toBe(attr.$$element); } })); })); it('should compile and link both attribute and text bindings', inject( function($rootScope, $compile) { $rootScope.name = 'angular'; element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); }) ); it('should process attribute interpolation in pre-linking phase at priority 100', function() { module(function() { directive('attrLog', function(log) { return { compile: function($element, $attrs) { log('compile=' + $attrs.myName); return { pre: function($scope, $element, $attrs) { log('preLinkP0=' + $attrs.myName); }, post: function($scope, $element, $attrs) { log('postLink=' + $attrs.myName); } } } } }); }); module(function() { directive('attrLogHighPriority', function(log) { return { priority: 101, compile: function() { return { pre: function($scope, $element, $attrs) { log('preLinkP101=' + $attrs.myName); } }; } } }); }); inject(function($rootScope, $compile, log) { element = $compile('<div attr-log-high-priority attr-log my-name="{{name}}"></div>')($rootScope); $rootScope.name = 'angular'; $rootScope.$apply(); log('digest=' + element.attr('my-name')); expect(log).toEqual('compile={{name}}; preLinkP101={{name}}; preLinkP0=; postLink=; digest=angular'); }); }); describe('SCE values', function() { it('should resolve compile and link both attribute and text bindings', inject( function($rootScope, $compile, $sce) { $rootScope.name = $sce.trustAsHtml('angular'); element = $compile('<div name="attr: {{name}}">text: {{name}}</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('text: angular'); expect(element.attr('name')).toEqual('attr: angular'); })); }); it('should decorate the binding with ng-binding and interpolation function', inject( function($compile, $rootScope) { element = $compile('<div>{{1+2}}</div>')($rootScope); expect(element.hasClass('ng-binding')).toBe(true); expect(element.data('$binding')[0].exp).toEqual('{{1+2}}'); })); it('should observe interpolated attrs', inject(function($rootScope, $compile) { $compile('<div some-attr="{{value}}" observer></div>')($rootScope); // should be async expect(observeSpy).not.toHaveBeenCalled(); $rootScope.$apply(function() { $rootScope.value = 'bound-value'; }); expect(observeSpy).toHaveBeenCalledOnceWith('bound-value'); })); it('should set interpolated attrs to initial interpolation value', inject(function($rootScope, $compile) { $rootScope.whatever = 'test value'; $compile('<div some-attr="{{whatever}}" observer></div>')($rootScope); expect(directiveAttrs.someAttr).toBe($rootScope.whatever); })); it('should allow directive to replace interpolated attributes before attr interpolation compilation', inject( function($compile, $rootScope) { element = $compile('<div some-attr="foo-{{1+1}}" replace-some-attr></div>')($rootScope); $rootScope.$digest(); expect(element.attr('some-attr')).toEqual('bar-2'); })); it('should call observer of non-interpolated attr through $evalAsync', inject(function($rootScope, $compile) { $compile('<div some-attr="nonBound" observer></div>')($rootScope); expect(directiveAttrs.someAttr).toBe('nonBound'); expect(observeSpy).not.toHaveBeenCalled(); $rootScope.$digest(); expect(observeSpy).toHaveBeenCalled(); }) ); it('should delegate exceptions to $exceptionHandler', function() { observeSpy = jasmine.createSpy('$observe attr').andThrow('ERROR'); module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); directive('error', function() { return function(scope, elm, attr) { attr.$observe('someAttr', observeSpy); attr.$observe('someAttr', observeSpy); }; }); }); inject(function($compile, $rootScope, $exceptionHandler) { $compile('<div some-attr="{{value}}" error></div>')($rootScope); $rootScope.$digest(); expect(observeSpy).toHaveBeenCalled(); expect(observeSpy.callCount).toBe(2); expect($exceptionHandler.errors).toEqual(['ERROR', 'ERROR']); }); }); it('should translate {{}} in terminal nodes', inject(function($rootScope, $compile) { element = $compile('<select ng:model="x"><option value="">Greet {{name}}!</option></select>')($rootScope) $rootScope.$digest(); expect(sortedHtml(element).replace(' selected="true"', '')). toEqual('<select ng:model="x">' + '<option value="">Greet !</option>' + '</select>'); $rootScope.name = 'Misko'; $rootScope.$digest(); expect(sortedHtml(element).replace(' selected="true"', '')). toEqual('<select ng:model="x">' + '<option value="">Greet Misko!</option>' + '</select>'); })); it('should support custom start/end interpolation symbols in template and directive template', function() { module(function($interpolateProvider, $compileProvider) { $interpolateProvider.startSymbol('##').endSymbol(']]'); $compileProvider.directive('myDirective', function() { return { template: '<span>{{hello}}|{{hello|uppercase}}</span>' }; }); }); inject(function($compile, $rootScope) { element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope); $rootScope.hello = 'ahoj'; $rootScope.$digest(); expect(element.text()).toBe('AHOJ|ahoj|AHOJ'); }); }); it('should support custom start/end interpolation symbols in async directive template', function() { module(function($interpolateProvider, $compileProvider) { $interpolateProvider.startSymbol('##').endSymbol(']]'); $compileProvider.directive('myDirective', function() { return { templateUrl: 'myDirective.html' }; }); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('myDirective.html', '<span>{{hello}}|{{hello|uppercase}}</span>'); element = $compile('<div>##hello|uppercase]]|<div my-directive></div></div>')($rootScope); $rootScope.hello = 'ahoj'; $rootScope.$digest(); expect(element.text()).toBe('AHOJ|ahoj|AHOJ'); }); }); it('should make attributes observable for terminal directives', function() { module(function() { directive('myAttr', function(log) { return { terminal: true, link: function(scope, element, attrs) { attrs.$observe('myAttr', function(val) { log(val); }); } } }); }); inject(function($compile, $rootScope, log) { element = $compile('<div my-attr="{{myVal}}"></div>')($rootScope); expect(log).toEqual([]); $rootScope.myVal = 'carrot'; $rootScope.$digest(); expect(log).toEqual(['carrot']); }); }) }); describe('link phase', function() { beforeEach(module(function() { forEach(['a', 'b', 'c'], function(name) { directive(name, function(log) { return { restrict: 'ECA', compile: function() { log('t' + uppercase(name)) return { pre: function() { log('pre' + uppercase(name)); }, post: function linkFn() { log('post' + uppercase(name)); } }; } }; }); }); })); it('should not store linkingFns for noop branches', inject(function ($rootScope, $compile) { element = jqLite('<div name="{{a}}"><span>ignore</span></div>'); var linkingFn = $compile(element); // Now prune the branches with no directives element.find('span').remove(); expect(element.find('span').length).toBe(0); // and we should still be able to compile without errors linkingFn($rootScope); })); it('should compile from top to bottom but link from bottom up', inject( function($compile, $rootScope, log) { element = $compile('<a b><c></c></a>')($rootScope); expect(log).toEqual('tA; tB; tC; preA; preB; preC; postC; postB; postA'); } )); it('should support link function on directive object', function() { module(function() { directive('abc', valueFn({ link: function(scope, element, attrs) { element.text(attrs.abc); } })); }); inject(function($compile, $rootScope) { element = $compile('<div abc="WORKS">FAIL</div>')($rootScope); expect(element.text()).toEqual('WORKS'); }); }); it('should support $observe inside link function on directive object', function() { module(function() { directive('testLink', valueFn({ templateUrl: 'test-link.html', link: function(scope, element, attrs) { attrs.$observe( 'testLink', function ( val ) { scope.testAttr = val; }); } })); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('test-link.html', '{{testAttr}}' ); element = $compile('<div test-link="{{1+2}}"></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('3'); }); }); }); describe('attrs', function() { it('should allow setting of attributes', function() { module(function() { directive({ setter: valueFn(function(scope, element, attr) { attr.$set('name', 'abc'); attr.$set('disabled', true); expect(attr.name).toBe('abc'); expect(attr.disabled).toBe(true); }) }); }); inject(function($rootScope, $compile) { element = $compile('<div setter></div>')($rootScope); expect(element.attr('name')).toEqual('abc'); expect(element.attr('disabled')).toEqual('disabled'); }); }); it('should read boolean attributes as boolean only on control elements', function() { var value; module(function() { directive({ input: valueFn({ restrict: 'ECA', link:function(scope, element, attr) { value = attr.required; } }) }); }); inject(function($rootScope, $compile) { element = $compile('<input required></input>')($rootScope); expect(value).toEqual(true); }); }); it('should read boolean attributes as text on non-controll elements', function() { var value; module(function() { directive({ div: valueFn({ restrict: 'ECA', link:function(scope, element, attr) { value = attr.required; } }) }); }); inject(function($rootScope, $compile) { element = $compile('<div required="some text"></div>')($rootScope); expect(value).toEqual('some text'); }); }); it('should create new instance of attr for each template stamping', function() { module(function($provide) { var state = { first: [], second: [] }; $provide.value('state', state); directive({ first: valueFn({ priority: 1, compile: function(templateElement, templateAttr) { return function(scope, element, attr) { state.first.push({ template: {element: templateElement, attr:templateAttr}, link: {element: element, attr: attr} }); } } }), second: valueFn({ priority: 2, compile: function(templateElement, templateAttr) { return function(scope, element, attr) { state.second.push({ template: {element: templateElement, attr:templateAttr}, link: {element: element, attr: attr} }); } } }) }); }); inject(function($rootScope, $compile, state) { var template = $compile('<div first second>'); dealoc(template($rootScope.$new(), noop)); dealoc(template($rootScope.$new(), noop)); // instance between directives should be shared expect(state.first[0].template.element).toBe(state.second[0].template.element); expect(state.first[0].template.attr).toBe(state.second[0].template.attr); // the template and the link can not be the same instance expect(state.first[0].template.element).not.toBe(state.first[0].link.element); expect(state.first[0].template.attr).not.toBe(state.first[0].link.attr); // each new template needs to be new instance expect(state.first[0].link.element).not.toBe(state.first[1].link.element); expect(state.first[0].link.attr).not.toBe(state.first[1].link.attr); expect(state.second[0].link.element).not.toBe(state.second[1].link.element); expect(state.second[0].link.attr).not.toBe(state.second[1].link.attr); }); }); it('should properly $observe inside ng-repeat', function() { var spies = []; module(function() { directive('observer', function() { return function(scope, elm, attr) { spies.push(jasmine.createSpy('observer ' + spies.length)); attr.$observe('some', spies[spies.length - 1]); }; }); }); inject(function($compile, $rootScope) { element = $compile('<div><div ng-repeat="i in items">'+ '<span some="id_{{i.id}}" observer></span>'+ '</div></div>')($rootScope); $rootScope.$apply(function() { $rootScope.items = [{id: 1}, {id: 2}]; }); expect(spies[0]).toHaveBeenCalledOnceWith('id_1'); expect(spies[1]).toHaveBeenCalledOnceWith('id_2'); spies[0].reset(); spies[1].reset(); $rootScope.$apply(function() { $rootScope.items[0].id = 5; }); expect(spies[0]).toHaveBeenCalledOnceWith('id_5'); }); }); describe('$set', function() { var attr; beforeEach(function(){ module(function() { directive('input', valueFn({ restrict: 'ECA', link: function(scope, element, attr) { scope.attr = attr; } })); }); inject(function($compile, $rootScope) { element = $compile('<input></input>')($rootScope); attr = $rootScope.attr; expect(attr).toBeDefined(); }); }); it('should set attributes', function() { attr.$set('ngMyAttr', 'value'); expect(element.attr('ng-my-attr')).toEqual('value'); expect(attr.ngMyAttr).toEqual('value'); }); it('should allow overriding of attribute name and remember the name', function() { attr.$set('ngOther', '123', true, 'other'); expect(element.attr('other')).toEqual('123'); expect(attr.ngOther).toEqual('123'); attr.$set('ngOther', '246'); expect(element.attr('other')).toEqual('246'); expect(attr.ngOther).toEqual('246'); }); it('should remove attribute', function() { attr.$set('ngMyAttr', 'value'); expect(element.attr('ng-my-attr')).toEqual('value'); attr.$set('ngMyAttr', undefined); expect(element.attr('ng-my-attr')).toBe(undefined); attr.$set('ngMyAttr', 'value'); attr.$set('ngMyAttr', null); expect(element.attr('ng-my-attr')).toBe(undefined); }); it('should not set DOM element attr if writeAttr false', function() { attr.$set('test', 'value', false); expect(element.attr('test')).toBeUndefined(); expect(attr.test).toBe('value'); }); }); }); describe('isolated locals', function() { var componentScope, regularScope; beforeEach(module(function() { directive('myComponent', function() { return { scope: { attr: '@', attrAlias: '@attr', ref: '=', refAlias: '= ref', reference: '=', optref: '=?', optrefAlias: '=? optref', optreference: '=?', expr: '&', exprAlias: '&expr' }, link: function(scope) { componentScope = scope; } }; }); directive('badDeclaration', function() { return { scope: { attr: 'xxx' } }; }); directive('storeScope', function() { return { link: function(scope) { regularScope = scope; } } }); })); it('should give other directives the parent scope', inject(function($rootScope) { compile('<div><input type="text" my-component store-scope ng-model="value"></div>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.find('input').val()).toBe('from-parent'); expect(componentScope).not.toBe(regularScope); expect(componentScope.$parent).toBe(regularScope) })); it('should not give the isolate scope to other directive template', function() { module(function() { directive('otherTplDir', function() { return { template: 'value: {{value}}' }; }); }); inject(function($rootScope) { compile('<div my-component other-tpl-dir>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); it('should not give the isolate scope to other directive template (with templateUrl)', function() { module(function() { directive('otherTplDir', function() { return { templateUrl: 'other.html' }; }); }); inject(function($rootScope, $templateCache) { $templateCache.put('other.html', 'value: {{value}}') compile('<div my-component other-tpl-dir>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); it('should not give the isolate scope to regular child elements', function() { inject(function($rootScope) { compile('<div my-component>value: {{value}}</div>'); $rootScope.$apply(function() { $rootScope.value = 'from-parent'; }); expect(element.html()).toBe('value: from-parent'); }); }); describe('attribute', function() { it('should copy simple attribute', inject(function() { compile('<div><span my-component attr="some text">'); expect(componentScope.attr).toEqual('some text'); expect(componentScope.attrAlias).toEqual('some text'); expect(componentScope.attrAlias).toEqual(componentScope.attr); })); it('should set up the interpolation before it reaches the link function', inject(function() { $rootScope.name = 'misko'; compile('<div><span my-component attr="hello {{name}}">'); expect(componentScope.attr).toEqual('hello misko'); expect(componentScope.attrAlias).toEqual('hello misko'); })); it('should update when interpolated attribute updates', inject(function() { compile('<div><span my-component attr="hello {{name}}">'); $rootScope.name = 'igor'; $rootScope.$apply(); expect(componentScope.attr).toEqual('hello igor'); expect(componentScope.attrAlias).toEqual('hello igor'); })); }); describe('object reference', function() { it('should update local when origin changes', inject(function() { compile('<div><span my-component ref="name">'); expect(componentScope.ref).toBe(undefined); expect(componentScope.refAlias).toBe(componentScope.ref); $rootScope.name = 'misko'; $rootScope.$apply(); expect($rootScope.name).toBe('misko'); expect(componentScope.ref).toBe('misko'); expect(componentScope.refAlias).toBe('misko'); $rootScope.name = {}; $rootScope.$apply(); expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); })); it('should update local when both change', inject(function() { compile('<div><span my-component ref="name">'); $rootScope.name = {mark:123}; componentScope.ref = 'misko'; $rootScope.$apply(); expect($rootScope.name).toEqual({mark:123}) expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); $rootScope.name = 'igor'; componentScope.ref = {}; $rootScope.$apply(); expect($rootScope.name).toEqual('igor') expect(componentScope.ref).toBe($rootScope.name); expect(componentScope.refAlias).toBe($rootScope.name); })); it('should complain on non assignable changes', inject(function() { compile('<div><span my-component ref="\'hello \' + name">'); $rootScope.name = 'world'; $rootScope.$apply(); expect(componentScope.ref).toBe('hello world'); componentScope.ref = 'ignore me'; expect($rootScope.$apply). toThrowMinErr("$compile", "nonassign", "Expression ''hello ' + name' used with directive 'myComponent' is non-assignable!"); expect(componentScope.ref).toBe('hello world'); // reset since the exception was rethrown which prevented phase clearing $rootScope.$$phase = null; $rootScope.name = 'misko'; $rootScope.$apply(); expect(componentScope.ref).toBe('hello misko'); })); // regression it('should stabilize model', inject(function() { compile('<div><span my-component reference="name">'); var lastRefValueInParent; $rootScope.$watch('name', function(ref) { lastRefValueInParent = ref; }); $rootScope.name = 'aaa'; $rootScope.$apply(); componentScope.reference = 'new'; $rootScope.$apply(); expect(lastRefValueInParent).toBe('new'); })); }); describe('optional object reference', function() { it('should update local when origin changes', inject(function() { compile('<div><span my-component optref="name">'); expect(componentScope.optRef).toBe(undefined); expect(componentScope.optRefAlias).toBe(componentScope.optRef); $rootScope.name = 'misko'; $rootScope.$apply(); expect(componentScope.optref).toBe($rootScope.name); expect(componentScope.optrefAlias).toBe($rootScope.name); $rootScope.name = {}; $rootScope.$apply(); expect(componentScope.optref).toBe($rootScope.name); expect(componentScope.optrefAlias).toBe($rootScope.name); })); it('should not throw exception when reference does not exist', inject(function() { compile('<div><span my-component>'); expect(componentScope.optref).toBe(undefined); expect(componentScope.optrefAlias).toBe(undefined); expect(componentScope.optreference).toBe(undefined); })); }); describe('executable expression', function() { it('should allow expression execution with locals', inject(function() { compile('<div><span my-component expr="count = count + offset">'); $rootScope.count = 2; expect(typeof componentScope.expr).toBe('function'); expect(typeof componentScope.exprAlias).toBe('function'); expect(componentScope.expr({offset: 1})).toEqual(3); expect($rootScope.count).toEqual(3); expect(componentScope.exprAlias({offset: 10})).toEqual(13); expect($rootScope.count).toEqual(13); })); }); it('should throw on unknown definition', inject(function() { expect(function() { compile('<div><span bad-declaration>'); }).toThrowMinErr("$compile", "iscp", "Invalid isolate scope definition for directive 'badDeclaration'. Definition: {... attr: 'xxx' ...}"); })); it('should expose a $$isolateBindings property onto the scope', inject(function() { compile('<div><span my-component>'); expect(typeof componentScope.$$isolateBindings).toBe('object'); expect(componentScope.$$isolateBindings.attr).toBe('@attr'); expect(componentScope.$$isolateBindings.attrAlias).toBe('@attr'); expect(componentScope.$$isolateBindings.ref).toBe('=ref'); expect(componentScope.$$isolateBindings.refAlias).toBe('=ref'); expect(componentScope.$$isolateBindings.reference).toBe('=reference'); expect(componentScope.$$isolateBindings.expr).toBe('&expr'); expect(componentScope.$$isolateBindings.exprAlias).toBe('&expr'); })); }); describe('controller', function() { it('should get required controller', function() { module(function() { directive('main', function(log) { return { priority: 2, controller: function() { this.name = 'main'; }, link: function(scope, element, attrs, controller) { log(controller.name); } }; }); directive('dep', function(log) { return { priority: 1, require: 'main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); directive('other', function(log) { return { link: function(scope, element, attrs, controller) { log(!!controller); // should be false } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main dep other></div>')($rootScope); expect(log).toEqual('false; dep:main; main'); }); }); it('should get required controller via linkingFn (template)', function() { module(function() { directive('dirA', function() { return { controller: function() { this.name = 'dirA'; } }; }); directive('dirB', function(log) { return { require: 'dirA', template: '<p>dirB</p>', link: function(scope, element, attrs, dirAController) { log('dirAController.name: ' + dirAController.name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div dir-a dir-b></div>')($rootScope); expect(log).toEqual('dirAController.name: dirA'); }); }); it('should get required controller via linkingFn (templateUrl)', function() { module(function() { directive('dirA', function() { return { controller: function() { this.name = 'dirA'; } }; }); directive('dirB', function(log) { return { require: 'dirA', templateUrl: 'dirB.html', link: function(scope, element, attrs, dirAController) { log('dirAController.name: ' + dirAController.name); } }; }); }); inject(function(log, $compile, $rootScope, $templateCache) { $templateCache.put('dirB.html', '<p>dirB</p>'); element = $compile('<div dir-a dir-b></div>')($rootScope); $rootScope.$digest(); expect(log).toEqual('dirAController.name: dirA'); }); }); it('should require controller of an isolate directive from a non-isolate directive on the ' + 'same element', function() { var IsolateController = function() {}; var isolateDirControllerInNonIsolateDirective; module(function() { directive('isolate', function() { return { scope: {}, controller: IsolateController }; }); directive('nonIsolate', function() { return { require: 'isolate', link: function(_, __, ___, isolateDirController) { isolateDirControllerInNonIsolateDirective = isolateDirController; } }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(isolateDirControllerInNonIsolateDirective).toBeDefined(); expect(isolateDirControllerInNonIsolateDirective instanceof IsolateController).toBe(true); }); }); it('should give the isolate scope to the controller of another replaced directives in the template', function() { module(function() { directive('testDirective', function() { return { replace: true, restrict: 'E', scope: {}, template: '<input type="checkbox" ng-model="model">' }; }); }); inject(function($rootScope) { compile('<div><test-directive></test-directive></div>'); element = element.children().eq(0); expect(element[0].checked).toBe(false); element.isolateScope().model = true; $rootScope.$digest(); expect(element[0].checked).toBe(true); }); }); it('should share isolate scope with replaced directives (template)', function() { var normalScope; var isolateScope; module(function() { directive('isolate', function() { return { replace: true, scope: {}, template: '<span ng-init="name=\'WORKS\'">{{name}}</span>', link: function(s) { isolateScope = s; } }; }); directive('nonIsolate', function() { return { link: function(s) { normalScope = s; } }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(normalScope).toBe($rootScope); expect(normalScope.name).toEqual(undefined); expect(isolateScope.name).toEqual('WORKS'); $rootScope.$digest(); expect(element.text()).toEqual('WORKS'); }); }); it('should share isolate scope with replaced directives (templateUrl)', function() { var normalScope; var isolateScope; module(function() { directive('isolate', function() { return { replace: true, scope: {}, templateUrl: 'main.html', link: function(s) { isolateScope = s; } }; }); directive('nonIsolate', function() { return { link: function(s) { normalScope = s; } }; }); }); inject(function($compile, $rootScope, $templateCache) { $templateCache.put('main.html', '<span ng-init="name=\'WORKS\'">{{name}}</span>'); element = $compile('<div isolate non-isolate></div>')($rootScope); $rootScope.$apply(); expect(normalScope).toBe($rootScope); expect(normalScope.name).toEqual(undefined); expect(isolateScope.name).toEqual('WORKS'); expect(element.text()).toEqual('WORKS'); }); }); it('should not get confused about where to use isolate scope when a replaced directive is used multiple times', function() { module(function() { directive('isolate', function() { return { replace: true, scope: {}, template: '<span scope-tester="replaced"><span scope-tester="inside"></span></span>' }; }); directive('scopeTester', function(log) { return { link: function($scope, $element) { log($element.attr('scope-tester') + '=' + ($scope.$root === $scope ? 'non-isolate' : 'isolate')); } } }); }); inject(function($compile, $rootScope, log) { element = $compile('<div>' + '<div isolate scope-tester="outside"></div>' + '<span scope-tester="sibling"></span>' + '</div>')($rootScope); $rootScope.$digest(); expect(log).toEqual('inside=isolate; ' + 'outside replaced=non-isolate; ' + // outside 'outside replaced=isolate; ' + // replaced 'sibling=non-isolate') }); }); it('should require controller of a non-isolate directive from an isolate directive on the ' + 'same element', function() { var NonIsolateController = function() {}; var nonIsolateDirControllerInIsolateDirective; module(function() { directive('isolate', function() { return { scope: {}, require: 'nonIsolate', link: function(_, __, ___, nonIsolateDirController) { nonIsolateDirControllerInIsolateDirective = nonIsolateDirController; } }; }); directive('nonIsolate', function() { return { controller: NonIsolateController }; }); }); inject(function($compile, $rootScope) { element = $compile('<div isolate non-isolate></div>')($rootScope); expect(nonIsolateDirControllerInIsolateDirective).toBeDefined(); expect(nonIsolateDirControllerInIsolateDirective instanceof NonIsolateController).toBe(true); }); }); it('should support controllerAs', function() { module(function() { directive('main', function() { return { templateUrl: 'main.html', transclude: true, scope: {}, controller: function() { this.name = 'lucas'; }, controllerAs: 'mainCtrl' }; }); }); inject(function($templateCache, $compile, $rootScope) { $templateCache.put('main.html', '<span>template:{{mainCtrl.name}} <div ng-transclude></div></span>'); element = $compile('<div main>transclude:{{mainCtrl.name}}</div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('template:lucas transclude:'); }); }); it('should support controller alias', function() { module(function($controllerProvider) { $controllerProvider.register('MainCtrl', function() { this.name = 'lucas'; }); directive('main', function() { return { templateUrl: 'main.html', scope: {}, controller: 'MainCtrl as mainCtrl' }; }); }); inject(function($templateCache, $compile, $rootScope) { $templateCache.put('main.html', '<span>{{mainCtrl.name}}</span>'); element = $compile('<div main></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe('lucas'); }); }); it('should require controller on parent element',function() { module(function() { directive('main', function(log) { return { controller: function() { this.name = 'main'; } }; }); directive('dep', function(log) { return { require: '^main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:main'); }); }); it("should throw an error if required controller can't be found",function() { module(function() { directive('dep', function(log) { return { require: '^main', link: function(scope, element, attrs, controller) { log('dep:' + controller.name); } }; }); }); inject(function(log, $compile, $rootScope) { expect(function() { $compile('<div main><div dep></div></div>')($rootScope); }).toThrowMinErr("$compile", "ctreq", "Controller 'main', required by directive 'dep', can't be found!"); }); }); it('should have optional controller on current element', function() { module(function() { directive('dep', function(log) { return { require: '?main', link: function(scope, element, attrs, controller) { log('dep:' + !!controller); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div main><div dep></div></div>')($rootScope); expect(log).toEqual('dep:false'); }); }); it('should support multiple controllers', function() { module(function() { directive('c1', valueFn({ controller: function() { this.name = 'c1'; } })); directive('c2', valueFn({ controller: function() { this.name = 'c2'; } })); directive('dep', function(log) { return { require: ['^c1', '^c2'], link: function(scope, element, attrs, controller) { log('dep:' + controller[0].name + '-' + controller[1].name); } }; }); }); inject(function(log, $compile, $rootScope) { element = $compile('<div c1 c2><div dep></div></div>')($rootScope); expect(log).toEqual('dep:c1-c2'); }); }); it('should instantiate the controller just once when template/templateUrl', function() { var syncCtrlSpy = jasmine.createSpy('sync controller'), asyncCtrlSpy = jasmine.createSpy('async controller'); module(function() { directive('myDirectiveSync', valueFn({ template: '<div>Hello!</div>', controller: syncCtrlSpy })); directive('myDirectiveAsync', valueFn({ templateUrl: 'myDirectiveAsync.html', controller: asyncCtrlSpy, compile: function() { return function() { } } })); }); inject(function($templateCache, $compile, $rootScope) { expect(syncCtrlSpy).not.toHaveBeenCalled(); expect(asyncCtrlSpy).not.toHaveBeenCalled(); $templateCache.put('myDirectiveAsync.html', '<div>Hello!</div>'); element = $compile('<div>'+ '<span xmy-directive-sync></span>' + '<span my-directive-async></span>' + '</div>')($rootScope); expect(syncCtrlSpy).not.toHaveBeenCalled(); expect(asyncCtrlSpy).not.toHaveBeenCalled(); $rootScope.$apply(); //expect(syncCtrlSpy).toHaveBeenCalledOnce(); expect(asyncCtrlSpy).toHaveBeenCalledOnce(); }); }); it('should instantiate controllers in the parent->child order when transluction, templateUrl and replacement ' + 'are in the mix', function() { // When a child controller is in the transclusion that replaces the parent element that has a directive with // a controller, we should ensure that we first instantiate the parent and only then stuff that comes from the // transclusion. // // The transclusion moves the child controller onto the same element as parent controller so both controllers are // on the same level. module(function() { directive('parentDirective', function() { return { transclude: true, replace: true, templateUrl: 'parentDirective.html', controller: function (log) { log('parentController'); } }; }); directive('childDirective', function() { return { require: '^parentDirective', templateUrl: 'childDirective.html', controller : function(log) { log('childController'); } }; }); }); inject(function($templateCache, log, $compile, $rootScope) { $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>'); $templateCache.put('childDirective.html', '<span>childTemplateText;</span>'); element = $compile('<div parent-directive><div child-directive></div>childContentText;</div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('parentController; childController'); expect(element.text()).toBe('childTemplateText;childContentText;') }); }); it('should instantiate the controller after the isolate scope bindings are initialized (with template)', function () { module(function () { var Ctrl = function ($scope, log) { log('myFoo=' + $scope.myFoo); }; directive('myDirective', function () { return { scope: { myFoo: "=" }, template: '<p>Hello</p>', controller: Ctrl }; }); }); inject(function ($templateCache, $compile, $rootScope, log) { $rootScope.foo = "bar"; element = $compile('<div my-directive my-foo="foo"></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('myFoo=bar'); }); }); it('should instantiate the controller after the isolate scope bindings are initialized (with templateUrl)', function () { module(function () { var Ctrl = function ($scope, log) { log('myFoo=' + $scope.myFoo); }; directive('myDirective', function () { return { scope: { myFoo: "=" }, templateUrl: 'hello.html', controller: Ctrl }; }); }); inject(function ($templateCache, $compile, $rootScope, log) { $templateCache.put('hello.html', '<p>Hello</p>'); $rootScope.foo = "bar"; element = $compile('<div my-directive my-foo="foo"></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('myFoo=bar'); }); }); it('should instantiate controllers in the parent->child->baby order when nested transluction, templateUrl and ' + 'replacement are in the mix', function() { // similar to the test above, except that we have one more layer of nesting and nested transclusion module(function() { directive('parentDirective', function() { return { transclude: true, replace: true, templateUrl: 'parentDirective.html', controller: function (log) { log('parentController'); } }; }); directive('childDirective', function() { return { require: '^parentDirective', transclude: true, replace: true, templateUrl: 'childDirective.html', controller : function(log) { log('childController'); } }; }); directive('babyDirective', function() { return { require: '^childDirective', templateUrl: 'babyDirective.html', controller : function(log) { log('babyController'); } }; }); }); inject(function($templateCache, log, $compile, $rootScope) { $templateCache.put('parentDirective.html', '<div ng-transclude>parentTemplateText;</div>'); $templateCache.put('childDirective.html', '<span ng-transclude>childTemplateText;</span>'); $templateCache.put('babyDirective.html', '<span>babyTemplateText;</span>'); element = $compile('<div parent-directive>' + '<div child-directive>' + 'childContentText;' + '<div baby-directive>babyContent;</div>' + '</div>' + '</div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('parentController; childController; babyController'); expect(element.text()).toBe('childContentText;babyTemplateText;') }); }); it('should allow controller usage in pre-link directive functions with templateUrl', function () { module(function () { var Ctrl = function (log) { log('instance'); }; directive('myDirective', function () { return { scope: true, templateUrl: 'hello.html', controller: Ctrl, compile: function () { return { pre: function (scope, template, attr, ctrl) {}, post: function () {} }; } }; }); }); inject(function ($templateCache, $compile, $rootScope, log) { $templateCache.put('hello.html', '<p>Hello</p>'); element = $compile('<div my-directive></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('instance'); expect(element.text()).toBe('Hello'); }); }); it('should allow controller usage in pre-link directive functions with a template', function () { module(function () { var Ctrl = function (log) { log('instance'); }; directive('myDirective', function () { return { scope: true, template: '<p>Hello</p>', controller: Ctrl, compile: function () { return { pre: function (scope, template, attr, ctrl) {}, post: function () {} }; } }; }); }); inject(function ($templateCache, $compile, $rootScope, log) { element = $compile('<div my-directive></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('instance'); expect(element.text()).toBe('Hello'); }); }); }); describe('transclude', function() { describe('content transclusion', function() { it('should support transclude directive', function() { module(function() { directive('trans', function() { return { transclude: 'content', replace: true, scope: true, template: '<ul><li>W:{{$parent.$id}}-{{$id}};</li><li ng-transclude></li></ul>' } }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div trans>T:{{$parent.$id}}-{{$id}}<span>;</span></div></div>') ($rootScope); $rootScope.$apply(); expect(element.text()).toEqual('W:001-002;T:001-003;'); expect(jqLite(element.find('span')[0]).text()).toEqual('T:001-003'); expect(jqLite(element.find('span')[1]).text()).toEqual(';'); }); }); it('should transclude transcluded content', function() { module(function() { directive('book', valueFn({ transclude: 'content', template: '<div>book-<div chapter>(<div ng-transclude></div>)</div></div>' })); directive('chapter', valueFn({ transclude: 'content', templateUrl: 'chapter.html' })); directive('section', valueFn({ transclude: 'content', template: '<div>section-!<div ng-transclude></div>!</div></div>' })); return function($httpBackend) { $httpBackend. expect('GET', 'chapter.html'). respond('<div>chapter-<div section>[<div ng-transclude></div>]</div></div>'); } }); inject(function(log, $rootScope, $compile, $httpBackend) { element = $compile('<div><div book>paragraph</div></div>')($rootScope); $rootScope.$apply(); expect(element.text()).toEqual('book-'); $httpBackend.flush(); $rootScope.$apply(); expect(element.text()).toEqual('book-chapter-section-![(paragraph)]!'); }); }); it('should only allow one content transclusion per element', function() { module(function() { directive('first', valueFn({ transclude: true })); directive('second', valueFn({ transclude: true })); }); inject(function($compile) { expect(function() { $compile('<div first="" second=""></div>'); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/); }); }); it('should remove transclusion scope, when the DOM is destroyed', function() { module(function() { directive('box', valueFn({ transclude: true, scope: { name: '=', show: '=' }, template: '<div><h1>Hello: {{name}}!</h1><div ng-transclude></div></div>', link: function(scope, element) { scope.$watch( 'show', function(show) { if (!show) { element.find('div').find('div').remove(); } } ); } })); }); inject(function($compile, $rootScope) { $rootScope.username = 'Misko'; $rootScope.select = true; element = $compile( '<div><div box name="username" show="select">user: {{username}}</div></div>') ($rootScope); $rootScope.$apply(); expect(element.text()).toEqual('Hello: Misko!user: Misko'); var widgetScope = $rootScope.$$childHead; var transcludeScope = widgetScope.$$nextSibling; expect(widgetScope.name).toEqual('Misko'); expect(widgetScope.$parent).toEqual($rootScope); expect(transcludeScope.$parent).toEqual($rootScope); $rootScope.select = false; $rootScope.$apply(); expect(element.text()).toEqual('Hello: Misko!'); expect(widgetScope.$$nextSibling).toEqual(null); }); }); it('should add a $$transcluded property onto the transcluded scope', function() { module(function() { directive('trans', function() { return { transclude: true, replace: true, scope: true, template: '<div><span>I:{{$$transcluded}}</span><div ng-transclude></div></div>' }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div trans>T:{{$$transcluded}}</div></div>') ($rootScope); $rootScope.$apply(); expect(jqLite(element.find('span')[0]).text()).toEqual('I:'); expect(jqLite(element.find('span')[1]).text()).toEqual('T:true'); }); }); it('should clear contents of the ng-translude element before appending transcluded content', function() { module(function() { directive('trans', function() { return { transclude: true, template: '<div ng-transclude>old stuff! </div>' }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div trans>unicorn!</div>')($rootScope); $rootScope.$apply(); expect(sortedHtml(element.html())).toEqual('<div ng-transclude=""><span>unicorn!</span></div>'); }); }); it('should throw on an ng-translude element inside no transclusion directive', function() { inject(function ($rootScope, $compile) { // we need to do this because different browsers print empty attributres differently try { $compile('<div><div ng-transclude></div></div>')($rootScope); } catch(e) { expect(e.message).toMatch(new RegExp( '^\\\[ngTransclude:orphan\\\] ' + 'Illegal use of ngTransclude directive in the template! ' + 'No parent directive that requires a transclusion found\. ' + 'Element: <div ng-transclude.+')); } }); }); it('should make the result of a transclusion available to the parent directive in post-linking phase' + '(template)', function() { module(function() { directive('trans', function(log) { return { transclude: true, template: '<div ng-transclude></div>', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent directive in post-linking phase' + '(templateUrl)', function() { // when compiling an async directive the transclusion is always processed before the directive // this is different compared to sync directive. delaying the transclusion makes little sense. module(function() { directive('trans', function(log) { return { transclude: true, templateUrl: 'trans.html', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile, $templateCache) { $templateCache.put('trans.html', '<div ng-transclude></div>'); element = $compile('<div trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' + '(template)', function() { module(function() { directive('replacedTrans', function(log) { return { transclude: true, replace: true, template: '<div ng-transclude></div>', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should make the result of a transclusion available to the parent *replace* directive in post-linking phase' + ' (templateUrl)', function() { module(function() { directive('replacedTrans', function(log) { return { transclude: true, replace: true, templateUrl: 'trans.html', link: { pre: function($scope, $element) { log('pre(' + $element.text() + ')'); }, post: function($scope, $element) { log('post(' + $element.text() + ')'); } } }; }); }); inject(function(log, $rootScope, $compile, $templateCache) { $templateCache.put('trans.html', '<div ng-transclude></div>'); element = $compile('<div replaced-trans><span>unicorn!</span></div>')($rootScope); $rootScope.$apply(); expect(log).toEqual('pre(); post(unicorn!)'); }); }); it('should copy the directive controller to all clones', function() { var transcludeCtrl, cloneCount = 2; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { transcludeCtrl = this; }, link: function(scope, el, attr, ctrl, $transclude) { var i; for (i=0; i<cloneCount; i++) { $transclude(cloneAttach); } function cloneAttach(clone) { el.append(clone); } } })); }); inject(function($compile) { element = $compile('<div transclude><span></span></div>')($rootScope); var children = element.children(), i; expect(transcludeCtrl).toBeDefined(); expect(element.data('$transcludeController')).toBe(transcludeCtrl); for (i=0; i<cloneCount; i++) { expect(children.eq(i).data('$transcludeController')).toBeUndefined(); } }); }); it('should provide the $transclude controller local as 5th argument to the pre and post-link function', function() { var ctrlTransclude, preLinkTransclude, postLinkTransclude; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { ctrlTransclude = $transclude; }, compile: function() { return { pre: function(scope, el, attr, ctrl, $transclude) { preLinkTransclude = $transclude; }, post: function(scope, el, attr, ctrl, $transclude) { postLinkTransclude = $transclude; } }; } })); }); inject(function($compile) { element = $compile('<div transclude></div>')($rootScope); expect(ctrlTransclude).toBeDefined(); expect(ctrlTransclude).toBe(preLinkTransclude); expect(ctrlTransclude).toBe(postLinkTransclude); }); }); it('should allow an optional scope argument in $transclude', function() { var capturedChildCtrl; module(function() { directive('transclude', valueFn({ transclude: 'content', link: function(scope, element, attr, ctrl, $transclude) { $transclude(scope, function(clone) { element.append(clone); }); } })); }); inject(function($compile) { element = $compile('<div transclude>{{$id}}</div>')($rootScope); $rootScope.$apply(); expect(element.text()).toBe($rootScope.$id); }); }); it('should expose the directive controller to transcluded children', function() { var capturedChildCtrl; module(function() { directive('transclude', valueFn({ transclude: 'content', controller: function() { }, link: function(scope, element, attr, ctrl, $transclude) { $transclude(function(clone) { element.append(clone); }); } })); directive('child', valueFn({ require: '^transclude', link: function(scope, element, attr, ctrl) { capturedChildCtrl = ctrl; } })); }); inject(function($compile) { element = $compile('<div transclude><div child></div></div>')($rootScope); expect(capturedChildCtrl).toBeTruthy(); }); }); }); describe('element transclusion', function() { it('should support basic element transclusion', function() { module(function() { directive('trans', function(log) { return { transclude: 'element', priority: 2, controller: function($transclude) { this.$transclude = $transclude; }, compile: function(element, attrs, template) { log('compile: ' + angular.mock.dump(element)); return function(scope, element, attrs, ctrl) { log('link'); var cursor = element; template(scope.$new(), function(clone) {cursor.after(cursor = clone)}); ctrl.$transclude(function(clone) {cursor.after(clone)}); }; } } }); }); inject(function(log, $rootScope, $compile) { element = $compile('<div><div high-log trans="text" log>{{$parent.$id}}-{{$id}};</div></div>') ($rootScope); $rootScope.$apply(); expect(log).toEqual('compile: <!-- trans: text -->; link; LOG; LOG; HIGH'); expect(element.text()).toEqual('001-002;001-003;'); }); }); it('should only allow one element transclusion per element', function() { module(function() { directive('first', valueFn({ transclude: 'element' })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile) { expect(function() { $compile('<div first second></div>'); }).toThrowMinErr('$compile', 'multidir', 'Multiple directives [first, second] asking for transclusion on: ' + '<!-- first: -->'); }); }); it('should only allow one element transclusion per element when directives have different priorities', function() { // we restart compilation in this case and we need to remember the duplicates during the second compile // regression #3893 module(function() { directive('first', valueFn({ transclude: 'element', priority: 100 })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile) { expect(function() { $compile('<div first second></div>'); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <div .+/); }); }); it('should only allow one element transclusion per element when async replace directive is in the mix', function() { module(function() { directive('template', valueFn({ templateUrl: 'template.html', replace: true })); directive('first', valueFn({ transclude: 'element', priority: 100 })); directive('second', valueFn({ transclude: 'element' })); }); inject(function($compile, $httpBackend) { $httpBackend.expectGET('template.html').respond('<p second>template.html</p>'); $compile('<div template first></div>'); expect(function() { $httpBackend.flush(); }).toThrowMinErr('$compile', 'multidir', /Multiple directives \[first, second\] asking for transclusion on: <p .+/); }); }); it('should support transcluded element on root content', function() { var comment; module(function() { directive('transclude', valueFn({ transclude: 'element', compile: function(element, attr, linker) { return function(scope, element, attr) { comment = element; }; } })); }); inject(function($compile, $rootScope) { var element = jqLite('<div>before<div transclude></div>after</div>').contents(); expect(element.length).toEqual(3); expect(nodeName_(element[1])).toBe('DIV'); $compile(element)($rootScope); expect(nodeName_(element[1])).toBe('#comment'); expect(nodeName_(comment)).toBe('#comment'); }); }); it('should terminate compilation only for element trasclusion', function() { module(function() { directive('elementTrans', function(log) { return { transclude: 'element', priority: 50, compile: log.fn('compile:elementTrans') }; }); directive('regularTrans', function(log) { return { transclude: true, priority: 50, compile: log.fn('compile:regularTrans') }; }); }); inject(function(log, $compile, $rootScope) { $compile('<div><div element-trans log="elem"></div><div regular-trans log="regular"></div></div>')($rootScope); expect(log).toEqual('compile:elementTrans; compile:regularTrans; regular'); }); }); it('should instantiate high priority controllers only once, but low priority ones each time we transclude', function() { module(function() { directive('elementTrans', function(log) { return { transclude: 'element', priority: 50, controller: function($transclude, $element) { log('controller:elementTrans'); $transclude(function(clone) { $element.after(clone); }); $transclude(function(clone) { $element.after(clone); }); $transclude(function(clone) { $element.after(clone); }); } }; }); directive('normalDir', function(log) { return { controller: function() { log('controller:normalDir'); } }; }); }); inject(function($compile, $rootScope, log) { element = $compile('<div><div element-trans normal-dir></div></div>')($rootScope); expect(log).toEqual([ 'controller:elementTrans', 'controller:normalDir', 'controller:normalDir', 'controller:normalDir' ]); }); }); it('should allow to access $transclude in the same directive', function() { var _$transclude; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function($transclude) { _$transclude = $transclude; } })); }); inject(function($compile) { element = $compile('<div transclude></div>')($rootScope); expect(_$transclude).toBeDefined() }); }); it('should copy the directive controller to all clones', function() { var transcludeCtrl, cloneCount = 2; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function() { transcludeCtrl = this; }, link: function(scope, el, attr, ctrl, $transclude) { var i; for (i=0; i<cloneCount; i++) { $transclude(cloneAttach); } function cloneAttach(clone) { el.after(clone); } } })); }); inject(function($compile) { element = $compile('<div><div transclude></div></div>')($rootScope); var children = element.children(), i; for (i=0; i<cloneCount; i++) { expect(children.eq(i).data('$transcludeController')).toBe(transcludeCtrl); } }); }); it('should expose the directive controller to transcluded children', function() { var capturedTranscludeCtrl; module(function() { directive('transclude', valueFn({ transclude: 'element', controller: function() { }, link: function(scope, element, attr, ctrl, $transclude) { $transclude(scope, function(clone) { element.after(clone); }); } })); directive('child', valueFn({ require: '^transclude', link: function(scope, element, attr, ctrl) { capturedTranscludeCtrl = ctrl; } })); }); inject(function($compile) { element = $compile('<div transclude><div child></div></div>')($rootScope); expect(capturedTranscludeCtrl).toBeTruthy(); }); }); it('should allow access to $transclude in a templateUrl directive', function() { var transclude; module(function() { directive('template', valueFn({ templateUrl: 'template.html', replace: true })); directive('transclude', valueFn({ transclude: 'content', controller: function($transclude) { transclude = $transclude; } })); }); inject(function($compile, $httpBackend) { $httpBackend.expectGET('template.html').respond('<div transclude></div>'); element = $compile('<div template></div>')($rootScope); $httpBackend.flush(); expect(transclude).toBeDefined(); }); }); }); it('should safely create transclude comment node and not break with "-->"', inject(function($rootScope) { // see: https://github.com/angular/angular.js/issues/1740 element = $compile('<ul><li ng-repeat="item in [\'-->\', \'x\']">{{item}}|</li></ul>')($rootScope); $rootScope.$digest(); expect(element.text()).toBe('-->|x|'); })); }); describe('img[src] sanitization', function() { it('should NOT require trusted values for img src', inject(function($rootScope, $compile, $sce) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = 'http://example.com/image.png'; $rootScope.$digest(); expect(element.attr('src')).toEqual('http://example.com/image.png'); // But it should accept trusted values anyway. $rootScope.testUrl = $sce.trustAsUrl('http://example.com/image2.png'); $rootScope.$digest(); expect(element.attr('src')).toEqual('http://example.com/image2.png'); })); it('should sanitize javascript: urls', inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('src')).toBe('unsafe:javascript:doEvilStuff()'); })); it('should sanitize non-image data: urls', inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "data:application/javascript;charset=US-ASCII,alert('evil!');"; $rootScope.$apply(); expect(element.attr('src')).toBe("unsafe:data:application/javascript;charset=US-ASCII,alert('evil!');"); $rootScope.testUrl = "data:,foo"; $rootScope.$apply(); expect(element.attr('src')).toBe("unsafe:data:,foo"); })); it('should not sanitize data: URIs for images', inject(function($compile, $rootScope) { element = $compile('<img src="{{dataUri}}"></img>')($rootScope); // image data uri // ref: http://probablyprogramming.com/2009/03/15/the-tiniest-gif-ever $rootScope.dataUri = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; $rootScope.$apply(); expect(element.attr('src')).toBe('data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='); })); // Fails on IE <= 10 with "TypeError: Access is denied" when trying to set img[src] if (!msie || msie > 10) { it('should sanitize mailto: urls', inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "mailto:[email protected]"; $rootScope.$apply(); expect(element.attr('src')).toBe('unsafe:mailto:[email protected]'); })); } it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); // case-sensitive $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()"; $rootScope.$apply(); expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); // tab in protocol $rootScope.testUrl = "java\u0009script:doEvilStuff()"; $rootScope.$apply(); expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); // space before $rootScope.testUrl = " javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); // ws chars before $rootScope.testUrl = " \u000e javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); // post-fixed with proper url $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; $rootScope.$apply(); expect(element[0].src).toBeOneOf( 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' ); })); it('should sanitize ng-src bindings as well', inject(function($compile, $rootScope) { element = $compile('<img ng-src="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); })); it('should not sanitize valid urls', inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "foo/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('foo/bar'); $rootScope.testUrl = "/foo/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('/foo/bar'); $rootScope.testUrl = "../foo/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('../foo/bar'); $rootScope.testUrl = "#foo"; $rootScope.$apply(); expect(element.attr('src')).toBe('#foo'); $rootScope.testUrl = "http://foo.com/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('http://foo.com/bar'); $rootScope.testUrl = " http://foo.com/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe(' http://foo.com/bar'); $rootScope.testUrl = "https://foo.com/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('https://foo.com/bar'); $rootScope.testUrl = "ftp://foo.com/bar"; $rootScope.$apply(); expect(element.attr('src')).toBe('ftp://foo.com/bar'); $rootScope.testUrl = "file:///foo/bar.html"; $rootScope.$apply(); expect(element.attr('src')).toBe('file:///foo/bar.html'); })); it('should not sanitize attributes other than src', inject(function($compile, $rootScope) { element = $compile('<img title="{{testUrl}}"></img>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('title')).toBe('javascript:doEvilStuff()'); })); it('should allow reconfiguration of the src whitelist', function() { module(function($compileProvider) { expect($compileProvider.imgSrcSanitizationWhitelist() instanceof RegExp).toBe(true); var returnVal = $compileProvider.imgSrcSanitizationWhitelist(/javascript:/); expect(returnVal).toBe($compileProvider); }); inject(function($compile, $rootScope) { element = $compile('<img src="{{testUrl}}"></img>')($rootScope); // Fails on IE <= 11 with "TypeError: Object doesn't support this property or method" when // trying to set img[src] if (!msie || msie > 11) { $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('src')).toBe('javascript:doEvilStuff()'); } $rootScope.testUrl = "http://recon/figured"; $rootScope.$apply(); expect(element.attr('src')).toBe('unsafe:http://recon/figured'); }); }); }); describe('a[href] sanitization', function() { it('should sanitize javascript: urls', inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('href')).toBe('unsafe:javascript:doEvilStuff()'); })); it('should sanitize data: urls', inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "data:evilPayload"; $rootScope.$apply(); expect(element.attr('href')).toBe('unsafe:data:evilPayload'); })); it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); // case-sensitive $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()"; $rootScope.$apply(); expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); // tab in protocol $rootScope.testUrl = "java\u0009script:doEvilStuff()"; $rootScope.$apply(); expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); // space before $rootScope.testUrl = " javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); // ws chars before $rootScope.testUrl = " \u000e javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].href).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); // post-fixed with proper url $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; $rootScope.$apply(); expect(element[0].href).toBeOneOf( 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' ); })); it('should sanitize ngHref bindings as well', inject(function($compile, $rootScope) { element = $compile('<a ng-href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element[0].href).toBe('unsafe:javascript:doEvilStuff()'); })); it('should not sanitize valid urls', inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('foo/bar'); $rootScope.testUrl = "/foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('/foo/bar'); $rootScope.testUrl = "../foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('../foo/bar'); $rootScope.testUrl = "#foo"; $rootScope.$apply(); expect(element.attr('href')).toBe('#foo'); $rootScope.testUrl = "http://foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('http://foo/bar'); $rootScope.testUrl = " http://foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe(' http://foo/bar'); $rootScope.testUrl = "https://foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('https://foo/bar'); $rootScope.testUrl = "ftp://foo/bar"; $rootScope.$apply(); expect(element.attr('href')).toBe('ftp://foo/bar'); $rootScope.testUrl = "mailto:[email protected]"; $rootScope.$apply(); expect(element.attr('href')).toBe('mailto:[email protected]'); $rootScope.testUrl = "file:///foo/bar.html"; $rootScope.$apply(); expect(element.attr('href')).toBe('file:///foo/bar.html'); })); it('should not sanitize href on elements other than anchor', inject(function($compile, $rootScope) { element = $compile('<div href="{{testUrl}}"></div>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('href')).toBe('javascript:doEvilStuff()'); })); it('should not sanitize attributes other than href', inject(function($compile, $rootScope) { element = $compile('<a title="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('title')).toBe('javascript:doEvilStuff()'); })); it('should allow reconfiguration of the href whitelist', function() { module(function($compileProvider) { expect($compileProvider.aHrefSanitizationWhitelist() instanceof RegExp).toBe(true); var returnVal = $compileProvider.aHrefSanitizationWhitelist(/javascript:/); expect(returnVal).toBe($compileProvider); }); inject(function($compile, $rootScope) { element = $compile('<a href="{{testUrl}}"></a>')($rootScope); $rootScope.testUrl = "javascript:doEvilStuff()"; $rootScope.$apply(); expect(element.attr('href')).toBe('javascript:doEvilStuff()'); $rootScope.testUrl = "http://recon/figured"; $rootScope.$apply(); expect(element.attr('href')).toBe('unsafe:http://recon/figured'); }); }); }); describe('interpolation on HTML DOM event handler attributes onclick, onXYZ, formaction', function() { it('should disallow interpolation on onclick', inject(function($compile, $rootScope) { // All interpolations are disallowed. $rootScope.onClickJs = ""; expect(function() { $compile('<button onclick="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); expect(function() { $compile('<button ONCLICK="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); expect(function() { $compile('<button ng-attr-onclick="{{onClickJs}}"></script>')($rootScope); }).toThrowMinErr( "$compile", "nodomevents", "Interpolations for HTML DOM event attributes are disallowed. " + "Please use the ng- versions (such as ng-click instead of onclick) instead."); })); it('should pass through arbitrary values on onXYZ event attributes that contain a hyphen', inject(function($compile, $rootScope) { element = $compile('<button on-click="{{onClickJs}}"></script>')($rootScope); $rootScope.onClickJs = 'javascript:doSomething()'; $rootScope.$apply(); expect(element.attr('on-click')).toEqual('javascript:doSomething()'); })); it('should pass through arbitrary values on "on" and "data-on" attributes', inject(function($compile, $rootScope) { element = $compile('<button data-on="{{dataOnVar}}"></script>')($rootScope); $rootScope.dataOnVar = 'data-on text'; $rootScope.$apply(); expect(element.attr('data-on')).toEqual('data-on text'); element = $compile('<button on="{{onVar}}"></script>')($rootScope); $rootScope.onVar = 'on text'; $rootScope.$apply(); expect(element.attr('on')).toEqual('on text'); })); }); describe('iframe[src]', function() { it('should pass through src attributes for the same domain', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "different_page"; $rootScope.$apply(); expect(element.attr('src')).toEqual('different_page'); })); it('should clear out src attributes for a different domain', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "http://a.different.domain.example.com"; expect(function() { $rootScope.$apply() }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "http://a.different.domain.example.com"); })); it('should clear out JS src attributes', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = "javascript:alert(1);"; expect(function() { $rootScope.$apply() }).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: " + "javascript:alert(1);"); })); it('should clear out non-resource_url src attributes', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = $sce.trustAsUrl("javascript:doTrustedStuff()"); expect($rootScope.$apply).toThrowMinErr( "$interpolate", "interr", "Can't interpolate: {{testUrl}}\nError: [$sce:insecurl] Blocked " + "loading resource from url not allowed by $sceDelegate policy. URL: javascript:doTrustedStuff()"); })); it('should pass through $sce.trustAs() values in src attributes', inject(function($compile, $rootScope, $sce) { element = $compile('<iframe src="{{testUrl}}"></iframe>')($rootScope); $rootScope.testUrl = $sce.trustAsResourceUrl("javascript:doTrustedStuff()"); $rootScope.$apply(); expect(element.attr('src')).toEqual('javascript:doTrustedStuff()'); })); }); describe('ngAttr* attribute binding', function() { it('should bind after digest but not before', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span ng-attr-test="{{name}}"></span>')($rootScope); expect(element.attr('test')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); })); it('should work with different prefixes', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span ng:attr:test="{{name}}" ng-Attr-test2="{{name}}" ng_Attr_test3="{{name}}"></span>')($rootScope); expect(element.attr('test')).toBeUndefined(); expect(element.attr('test2')).toBeUndefined(); expect(element.attr('test3')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test')).toBe('Misko'); expect(element.attr('test2')).toBe('Misko'); expect(element.attr('test3')).toBe('Misko'); })); it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) { $rootScope.name = "Misko"; element = $compile('<span data-ng-attr-test2="{{name}}" x-ng-attr-test3="{{name}}" data-ng:attr-test4="{{name}}"></span>')($rootScope); expect(element.attr('test2')).toBeUndefined(); expect(element.attr('test3')).toBeUndefined(); expect(element.attr('test4')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('test2')).toBe('Misko'); expect(element.attr('test3')).toBe('Misko'); expect(element.attr('test4')).toBe('Misko'); })); describe('when an attribute has a dash-separated name', function () { it('should work with different prefixes', inject(function($compile, $rootScope) { $rootScope.name = "JamieMason"; element = $compile('<span ng:attr:dash-test="{{name}}" ng-Attr-dash-test2="{{name}}" ng_Attr_dash-test3="{{name}}"></span>')($rootScope); expect(element.attr('dash-test')).toBeUndefined(); expect(element.attr('dash-test2')).toBeUndefined(); expect(element.attr('dash-test3')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('dash-test')).toBe('JamieMason'); expect(element.attr('dash-test2')).toBe('JamieMason'); expect(element.attr('dash-test3')).toBe('JamieMason'); })); it('should work if they are prefixed with x- or data-', inject(function($compile, $rootScope) { $rootScope.name = "JamieMason"; element = $compile('<span data-ng-attr-dash-test2="{{name}}" x-ng-attr-dash-test3="{{name}}" data-ng:attr-dash-test4="{{name}}"></span>')($rootScope); expect(element.attr('dash-test2')).toBeUndefined(); expect(element.attr('dash-test3')).toBeUndefined(); expect(element.attr('dash-test4')).toBeUndefined(); $rootScope.$digest(); expect(element.attr('dash-test2')).toBe('JamieMason'); expect(element.attr('dash-test3')).toBe('JamieMason'); expect(element.attr('dash-test4')).toBe('JamieMason'); })); }); }); describe('multi-element directive', function() { it('should group on link function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-show-start="show"></span>' + '<span ng-show-end></span>' + '</div>')($rootScope); $rootScope.$digest(); var spans = element.find('span'); expect(spans.eq(0)).toBeHidden(); expect(spans.eq(1)).toBeHidden(); })); it('should group on compile function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + '<span ng-repeat-end>{{i}}B;</span>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1A1B;2A2B;'); })); it('should support grouping over text nodes', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + ':' + // Important: proves that we can iterate over non-elements '<span ng-repeat-end>{{i}}B;</span>' + '</div>')($rootScope); $rootScope.$digest(); expect(element.text()).toEqual('1A:1B;2A:2B;'); })); it('should group on $root compile function', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<span ng-repeat-start="i in [1,2]">{{i}}A</span>' + '<span ng-repeat-end>{{i}}B;</span>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1A1B;2A2B;'); })); it('should group on nested groups of same directive', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<div ng-repeat-start="i in [1,2]">{{i}}A</div>' + '<span ng-bind-start="\'.\'"></span>' + '<span ng-bind-end></span>' + '<div ng-repeat-end>{{i}}B;</div>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1A..1B;2A..2B;'); })); it('should group on nested groups', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div></div>' + '<div ng-repeat-start="i in [1,2]">{{i}}(</div>' + '<span ng-repeat-start="j in [2,3]">{{j}}-</span>' + '<span ng-repeat-end>{{j}}</span>' + '<div ng-repeat-end>){{i}};</div>' + '<div></div>')($rootScope); $rootScope.$digest(); element = jqLite(element[0].parentNode.childNodes); // reset because repeater is top level. expect(element.text()).toEqual('1(2-23-3)1;2(2-23-3)2;'); })); it('should throw error if unterminated', function () { module(function($compileProvider) { $compileProvider.directive('foo', function() { return { }; }); }); inject(function($compile, $rootScope) { expect(function() { element = $compile( '<div>' + '<span foo-start></span>' + '</div>'); }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); }); }); it('should correctly collect ranges on multiple directives on a single element', function () { module(function($compileProvider) { $compileProvider.directive('emptyDirective', function() { return function (scope, element) { element.data('x', 'abc'); }; }); $compileProvider.directive('rangeDirective', function() { return { link: function (scope) { scope.x = 'X'; scope.y = 'Y'; } }; }); }); inject(function ($compile, $rootScope) { element = $compile( '<div>' + '<div range-directive-start empty-directive>{{x}}</div>' + '<div range-directive-end>{{y}}</div>' + '</div>' )($rootScope); $rootScope.$digest(); expect(element.text()).toBe('XY'); expect(angular.element(element[0].firstChild).data('x')).toBe('abc'); }); }); it('should throw error if unterminated (containing termination as a child)', function () { module(function($compileProvider) { $compileProvider.directive('foo', function() { return { }; }); }); inject(function($compile) { expect(function() { element = $compile( '<div>' + '<span foo-start><span foo-end></span></span>' + '</div>'); }).toThrowMinErr("$compile", "uterdir", "Unterminated attribute, found 'foo-start' but no matching 'foo-end' found."); }); }); it('should support data- and x- prefix', inject(function($compile, $rootScope) { $rootScope.show = false; element = $compile( '<div>' + '<span data-ng-show-start="show"></span>' + '<span data-ng-show-end></span>' + '<span x-ng-show-start="show"></span>' + '<span x-ng-show-end></span>' + '</div>')($rootScope); $rootScope.$digest(); var spans = element.find('span'); expect(spans.eq(0)).toBeHidden(); expect(spans.eq(1)).toBeHidden(); expect(spans.eq(2)).toBeHidden(); expect(spans.eq(3)).toBeHidden(); })); }); describe('$animate animation hooks', function() { beforeEach(module('mock.animate')); it('should automatically fire the addClass and removeClass animation hooks', inject(function($compile, $animate, $rootScope) { var data, element = jqLite('<div class="{{val1}} {{val2}} fire"></div>'); $compile(element)($rootScope); $rootScope.$digest(); data = $animate.flushNext('removeClass'); expect(element.hasClass('fire')).toBe(true); $rootScope.val1 = 'ice'; $rootScope.val2 = 'rice'; $rootScope.$digest(); data = $animate.flushNext('addClass'); expect(data.params[1]).toBe('ice rice'); expect(element.hasClass('ice')).toBe(true); expect(element.hasClass('rice')).toBe(true); expect(element.hasClass('fire')).toBe(true); $rootScope.val2 = 'dice'; $rootScope.$digest(); data = $animate.flushNext('removeClass'); expect(data.params[1]).toBe('rice'); data = $animate.flushNext('addClass'); expect(data.params[1]).toBe('dice'); expect(element.hasClass('ice')).toBe(true); expect(element.hasClass('dice')).toBe(true); expect(element.hasClass('fire')).toBe(true); $rootScope.val1 = ''; $rootScope.val2 = ''; $rootScope.$digest(); data = $animate.flushNext('removeClass'); expect(data.params[1]).toBe('ice dice'); expect(element.hasClass('ice')).toBe(false); expect(element.hasClass('dice')).toBe(false); expect(element.hasClass('fire')).toBe(true); })); }); });
{'content_hash': '1fc2763b9c88502cc389f65ccdfeb5b7', 'timestamp': '', 'source': 'github', 'line_count': 4521, 'max_line_length': 170, 'avg_line_length': 36.325591683255915, 'alnum_prop': 0.5330637893660034, 'repo_name': 'jodytate/angular.js', 'id': '85ee17d2ae6e9b5f30ed127c04a9a15dff4d4ca3', 'size': '164228', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/ng/compileSpec.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '21090'}, {'name': 'JavaScript', 'bytes': '4207236'}, {'name': 'Ruby', 'bytes': '223'}, {'name': 'Shell', 'bytes': '6128'}]}
<?xml version="1.0" encoding="utf-8"?> <extension version="1.5" type="plugin" group="wiki"> <name>Wiki - Default Parser</name> <author>HUBzero</author> <authorUrl>hubzero.org</authorUrl> <authorEmail>[email protected]</authorEmail> <copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright> <license>http://opensource.org/licenses/MIT MIT</license> <description>Loads a wiki parser and performs any called actions on text passed to it</description> <files> <filename plugin="parserdefault">parserdefault.php</filename> </files> <languages> <language tag="en-GB">en-GB.plg_wiki_parserdefault.ini</language> </languages> <config> </config> </extension>
{'content_hash': 'dc8b77ac676a48fc29cf2eccdd8c71d1', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 100, 'avg_line_length': 37.666666666666664, 'alnum_prop': 0.7418879056047197, 'repo_name': 'anthonyfuentes/hubzero-cms', 'id': '90186508bb645c00e3bf543e24dd1a2bfbf9cab4', 'size': '678', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'core/plugins/wiki/parserdefault/parserdefault.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '171251'}, {'name': 'AngelScript', 'bytes': '1638'}, {'name': 'CSS', 'bytes': '2719754'}, {'name': 'HTML', 'bytes': '1289374'}, {'name': 'JavaScript', 'bytes': '12613354'}, {'name': 'PHP', 'bytes': '24940952'}, {'name': 'Shell', 'bytes': '10678'}, {'name': 'TSQL', 'bytes': '572'}]}
namespace org { namespace allseen { namespace LSF { // Methods public ref class LampServiceClearLampFaultCalledEventArgs sealed { public: LampServiceClearLampFaultCalledEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info, _In_ uint32 interface_lampFaultCode); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property LampServiceClearLampFaultResult^ Result { LampServiceClearLampFaultResult^ get() { return m_result; } void set(_In_ LampServiceClearLampFaultResult^ value) { m_result = value; } } property uint32 LampFaultCode { uint32 get() { return m_interface_lampFaultCode; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<LampServiceClearLampFaultResult^>^ GetResultAsync(LampServiceClearLampFaultCalledEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<LampServiceClearLampFaultResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<LampServiceClearLampFaultResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; LampServiceClearLampFaultResult^ m_result; uint32 m_interface_lampFaultCode; }; // Readable Properties public ref class LampServiceGetVersionRequestedEventArgs sealed { public: LampServiceGetVersionRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property LampServiceGetVersionResult^ Result { LampServiceGetVersionResult^ get() { return m_result; } void set(_In_ LampServiceGetVersionResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<LampServiceGetVersionResult^>^ GetResultAsync(LampServiceGetVersionRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<LampServiceGetVersionResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<LampServiceGetVersionResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; LampServiceGetVersionResult^ m_result; }; public ref class LampServiceGetLampServiceVersionRequestedEventArgs sealed { public: LampServiceGetLampServiceVersionRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property LampServiceGetLampServiceVersionResult^ Result { LampServiceGetLampServiceVersionResult^ get() { return m_result; } void set(_In_ LampServiceGetLampServiceVersionResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<LampServiceGetLampServiceVersionResult^>^ GetResultAsync(LampServiceGetLampServiceVersionRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<LampServiceGetLampServiceVersionResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<LampServiceGetLampServiceVersionResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; LampServiceGetLampServiceVersionResult^ m_result; }; public ref class LampServiceGetLampFaultsRequestedEventArgs sealed { public: LampServiceGetLampFaultsRequestedEventArgs(_In_ Windows::Devices::AllJoyn::AllJoynMessageInfo^ info); property Windows::Devices::AllJoyn::AllJoynMessageInfo^ MessageInfo { Windows::Devices::AllJoyn::AllJoynMessageInfo^ get() { return m_messageInfo; } } property LampServiceGetLampFaultsResult^ Result { LampServiceGetLampFaultsResult^ get() { return m_result; } void set(_In_ LampServiceGetLampFaultsResult^ value) { m_result = value; } } Windows::Foundation::Deferral^ GetDeferral(); static Windows::Foundation::IAsyncOperation<LampServiceGetLampFaultsResult^>^ GetResultAsync(LampServiceGetLampFaultsRequestedEventArgs^ args) { args->InvokeAllFinished(); auto t = concurrency::create_task(args->m_tce); return concurrency::create_async([t]() -> concurrency::task<LampServiceGetLampFaultsResult^> { return t; }); } private: void Complete(); void InvokeAllFinished(); void InvokeCompleteHandler(); bool m_raised; int m_completionsRequired; concurrency::task_completion_event<LampServiceGetLampFaultsResult^> m_tce; std::mutex m_lock; Windows::Devices::AllJoyn::AllJoynMessageInfo^ m_messageInfo; LampServiceGetLampFaultsResult^ m_result; }; // Writable Properties } } }
{'content_hash': '2a1d1b99a497e3eec4cd634cab503de9', 'timestamp': '', 'source': 'github', 'line_count': 176, 'max_line_length': 162, 'avg_line_length': 33.39204545454545, 'alnum_prop': 0.7129487833928875, 'repo_name': 'sgrebnov/ajn-sample-win10', 'id': '850b232497d53d54b2391aa1b7cbf825a328475d', 'size': '6825', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'AllJoyn.Lamp.Sample/AllJoyn.Lamp.WinRuntime/LampServiceServiceEventArgs.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '7839'}, {'name': 'C++', 'bytes': '572004'}]}
'use strict'; 'require view'; 'require ui'; 'require fs'; return view.extend({ load: function() { return fs.trimmed('/proc/sys/kernel/hostname'); }, handleArchiveUpload: function(ev) { return ui.uploadFile('/tmp/nlbw-restore.tar.gz').then(function() { return fs.exec('/usr/libexec/nlbwmon-action', [ 'restore' ]).then(function(res) { if (res.code != 0) throw new Error(res.stderr || res.stdout); var json = JSON.parse(res.stdout || '{}'), list = (L.isObject(json) && Array.isArray(json.restored)) ? json.restored : []; ui.showModal(_('Restore complete'), [ E('p', [ _('The following database files have been restored:') ]), E('ul', list.map(function(file) { return E('li', [ file ]) })), E('div', { 'class': 'right' }, [ E('button', { 'click': ui.hideModal }, [ _('Dismiss') ]) ]) ]); }).catch(function(err) { ui.addNotification(null, E('p', [ _('Failed to restore backup archive: %s').format(err.message) ])); }); }); }, handleArchiveDownload: function(hostname, ev) { return fs.exec_direct('/usr/libexec/nlbwmon-action', [ 'backup' ], 'blob').then(function(blob) { var url = window.URL.createObjectURL(blob), date = new Date(), name = 'nlbwmon-backup-%s-%04d-%02d-%02d.tar.gz'.format(hostname, date.getFullYear(), date.getMonth() + 1, date.getDate()), link = E('a', { 'style': 'display:none', 'href': url, 'download': name }); document.body.appendChild(link); link.click(); document.body.removeChild(link); window.URL.revokeObjectURL(url); }).catch(function(err) { ui.addNotification(null, E('p', [ _('Failed to download backup archive: %s').format(err.message) ])); }); }, render: function(hostname) { return E([], [ E('h2', [ _('Netlink Bandwidth Monitor - Backup / Restore') ]), E('h5', [ _('Restore Database Backup') ]), E('p', [ E('button', { 'click': ui.createHandlerFn(this, 'handleArchiveUpload') }, [ _('Restore') ]) ]), E('h5', [ _('Download Database Backup') ]), E('p', [ E('button', { 'click': ui.createHandlerFn(this, 'handleArchiveDownload', hostname) }, [ _('Generate Backup') ]) ]) ]); }, handleSave: null, handleSaveApply: null, handleReset: null });
{'content_hash': '66d5d2089344ce2bd14636854fd006bf', 'timestamp': '', 'source': 'github', 'line_count': 70, 'max_line_length': 130, 'avg_line_length': 32.27142857142857, 'alnum_prop': 0.5949535192563081, 'repo_name': 'tobiaswaldvogel/luci', 'id': 'c5fcfe5cf84987379e546da5dd9d280e6173b8cc', 'size': '2259', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'applications/luci-app-nlbwmon/htdocs/luci-static/resources/view/nlbw/backup.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '526'}, {'name': 'C', 'bytes': '1291071'}, {'name': 'C#', 'bytes': '42820'}, {'name': 'C++', 'bytes': '7790'}, {'name': 'Java', 'bytes': '49574'}, {'name': 'JavaScript', 'bytes': '67062'}, {'name': 'Lua', 'bytes': '1601852'}, {'name': 'Perl', 'bytes': '56448'}, {'name': 'Ruby', 'bytes': '771'}, {'name': 'Shell', 'bytes': '140197'}, {'name': 'Visual Basic', 'bytes': '33030'}]}
import sys import unittest from StringIO import StringIO from superlance.tests.dummy import * class MemmonTests(unittest.TestCase): def _getTargetClass(self): from superlance.memmon import Memmon return Memmon def _makeOne(self, *opts): return self._getTargetClass()(*opts) def _makeOnePopulated(self, programs, groups, any): rpc = DummyRPCServer() sendmail = 'cat - > /dev/null' email = '[email protected]' memmon = self._makeOne(programs, groups, any, sendmail, email, rpc) memmon.stdin = StringIO() memmon.stdout = StringIO() memmon.stderr = StringIO() memmon.pscommand = 'echo 22%s' return memmon def test_runforever_notatick(self): programs = {'foo':0, 'bar':0, 'baz_01':0 } groups = {} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:NOTATICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) self.assertEqual(memmon.stderr.getvalue(), '') def test_runforever_tick_programs(self): programs = {'foo':0, 'bar':0, 'baz_01':0 } groups = {} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 8) self.assertEqual(lines[0], 'Checking programs foo=0, bar=0, baz_01=0') self.assertEqual(lines[1], 'RSS of foo:foo is 2264064') self.assertEqual(lines[2], 'Restarting foo:foo') self.assertEqual(lines[3], 'RSS of bar:bar is 2265088') self.assertEqual(lines[4], 'Restarting bar:bar') self.assertEqual(lines[5], 'RSS of baz:baz_01 is 2265088') self.assertEqual(lines[6], 'Restarting baz:baz_01') self.assertEqual(lines[7], '') mailed = memmon.mailed.split('\n') self.assertEqual(len(mailed), 4) self.assertEqual(mailed[0], 'To: [email protected]') self.assertEqual(mailed[1], 'Subject: memmon: process baz:baz_01 restarted') self.assertEqual(mailed[2], '') self.failUnless(mailed[3].startswith('memmon.py restarted')) def test_runforever_tick_groups(self): programs = {} groups = {'foo':0} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 4) self.assertEqual(lines[0], 'Checking groups foo=0') self.assertEqual(lines[1], 'RSS of foo:foo is 2264064') self.assertEqual(lines[2], 'Restarting foo:foo') self.assertEqual(lines[3], '') mailed = memmon.mailed.split('\n') self.assertEqual(len(mailed), 4) self.assertEqual(mailed[0], 'To: [email protected]') self.assertEqual(mailed[1], 'Subject: memmon: process foo:foo restarted') self.assertEqual(mailed[2], '') self.failUnless(mailed[3].startswith('memmon.py restarted')) def test_runforever_tick_any(self): programs = {} groups = {} any = 0 memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 8) self.assertEqual(lines[0], 'Checking any=0') self.assertEqual(lines[1], 'RSS of foo:foo is 2264064') self.assertEqual(lines[2], 'Restarting foo:foo') self.assertEqual(lines[3], 'RSS of bar:bar is 2265088') self.assertEqual(lines[4], 'Restarting bar:bar') self.assertEqual(lines[5], 'RSS of baz:baz_01 is 2265088') self.assertEqual(lines[6], 'Restarting baz:baz_01') self.assertEqual(lines[7], '') mailed = memmon.mailed.split('\n') self.assertEqual(len(mailed), 4) def test_runforever_tick_programs_and_groups(self): programs = {'baz_01':0} groups = {'foo':0} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 7) self.assertEqual(lines[0], 'Checking programs baz_01=0') self.assertEqual(lines[1], 'Checking groups foo=0') self.assertEqual(lines[2], 'RSS of foo:foo is 2264064') self.assertEqual(lines[3], 'Restarting foo:foo') self.assertEqual(lines[4], 'RSS of baz:baz_01 is 2265088') self.assertEqual(lines[5], 'Restarting baz:baz_01') self.assertEqual(lines[6], '') mailed = memmon.mailed.split('\n') self.assertEqual(len(mailed), 4) self.assertEqual(mailed[0], 'To: [email protected]') self.assertEqual(mailed[1], 'Subject: memmon: process baz:baz_01 restarted') self.assertEqual(mailed[2], '') self.failUnless(mailed[3].startswith('memmon.py restarted')) def test_runforever_tick_programs_norestart(self): programs = {'foo': sys.maxint} groups = {} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 3) self.assertEqual(lines[0], 'Checking programs foo=%s' % sys.maxint) self.assertEqual(lines[1], 'RSS of foo:foo is 2264064') self.assertEqual(lines[2], '') self.assertEqual(memmon.mailed, False) def test_stopprocess_fault_tick_programs_norestart(self): programs = {'foo': sys.maxint} groups = {} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) memmon.runforever(test=True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 3) self.assertEqual(lines[0], 'Checking programs foo=%s' % sys.maxint) self.assertEqual(lines[1], 'RSS of foo:foo is 2264064') self.assertEqual(lines[2], '') self.assertEqual(memmon.mailed, False) def test_stopprocess_fails_to_stop(self): programs = {'BAD_NAME': 0} groups = {} any = None memmon = self._makeOnePopulated(programs, groups, any) memmon.stdin.write('eventname:TICK len:0\n') memmon.stdin.seek(0) from supervisor.process import ProcessStates memmon.rpc.supervisor.all_process_info = [ { 'name':'BAD_NAME', 'group':'BAD_NAME', 'pid':11, 'state':ProcessStates.RUNNING, 'statename':'RUNNING', 'start':0, 'stop':0, 'spawnerr':'', 'now':0, 'description':'BAD_NAME description', } ] import xmlrpclib self.assertRaises(xmlrpclib.Fault, memmon.runforever, True) lines = memmon.stderr.getvalue().split('\n') self.assertEqual(len(lines), 4) self.assertEqual(lines[0], 'Checking programs BAD_NAME=%s' % 0) self.assertEqual(lines[1], 'RSS of BAD_NAME:BAD_NAME is 2264064') self.assertEqual(lines[2], 'Restarting BAD_NAME:BAD_NAME') self.failUnless(lines[3].startswith('Failed')) mailed = memmon.mailed.split('\n') self.assertEqual(len(mailed), 4) self.assertEqual(mailed[0], 'To: [email protected]') self.assertEqual(mailed[1], 'Subject: memmon: failed to stop process BAD_NAME:BAD_NAME, exiting') self.assertEqual(mailed[2], '') self.failUnless(mailed[3].startswith('Failed')) if __name__ == '__main__': unittest.main()
{'content_hash': '41cedc8d0000486c2e93b2f7a1761c6e', 'timestamp': '', 'source': 'github', 'line_count': 196, 'max_line_length': 79, 'avg_line_length': 42.10204081632653, 'alnum_prop': 0.603974793989336, 'repo_name': 'zxl200406/minos', 'id': '09ee40fb52db9308edf988b9abe6c6a8d663a7cb', 'size': '8252', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'supervisor/superlance/tests/memmon_test.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '3667'}, {'name': 'HTML', 'bytes': '90526'}, {'name': 'JavaScript', 'bytes': '1342845'}, {'name': 'Makefile', 'bytes': '1006'}, {'name': 'Puppet', 'bytes': '1642'}, {'name': 'Python', 'bytes': '1823817'}, {'name': 'Shell', 'bytes': '14110'}, {'name': 'Smarty', 'bytes': '8245'}, {'name': 'XSLT', 'bytes': '1335'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template not_</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../proto/reference.html#header.boost.proto.matches_hpp" title="Header &lt;boost/proto/matches.hpp&gt;"> <link rel="prev" href="_/impl.html" title="Struct template impl"> <link rel="next" href="not_/impl.html" title="Struct template impl"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="_/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.matches_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="not_/impl.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.proto.not_"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template not_</span></h2> <p>boost::proto::not_ &#8212; Inverts the set of expressions matched by a grammar. When used as a transform, <code class="computeroutput">proto::not_&lt;&gt;</code> returns the current expression unchanged. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../proto/reference.html#header.boost.proto.matches_hpp" title="Header &lt;boost/proto/matches.hpp&gt;">boost/proto/matches.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Grammar<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="not_.html" title="Struct template not_">not_</a> <span class="special">:</span> <span class="keyword"></span> <a class="link" href="transform.html" title="Struct template transform">proto::transform</a>&lt;not_&lt;Grammar&gt; &gt; <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <span class="identifier">not_</span> <a name="boost.proto.not_.proto_grammar"></a><span class="identifier">proto_grammar</span><span class="special">;</span> <span class="comment">// member classes/structs/unions</span> <span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> <a class="link" href="../../Expr.html" title="Concept Expr">Expr</a><span class="special">,</span> <span class="keyword">typename</span> State<span class="special">,</span> <span class="keyword">typename</span> Data<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="not_/impl.html" title="Struct template impl">impl</a> <span class="special">:</span> <span class="keyword"></span> <a class="link" href="transform_impl.html" title="Struct template transform_impl">proto::transform_impl</a>&lt;Expr, State, Data&gt; <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <span class="identifier">Expr</span> <a class="link" href="not_/impl.html#boost.proto.not_.impl.result_type"><span class="identifier">result_type</span></a><span class="special">;</span> <span class="comment">// <a class="link" href="not_/impl.html#idp928014176-bb">public member functions</a></span> <span class="identifier">Expr</span> <a class="link" href="not_/impl.html#idp928014736-bb"><span class="keyword">operator</span><span class="special">(</span><span class="special">)</span></a><span class="special">(</span><span class="keyword">typename</span> <span class="identifier">impl</span><span class="special">::</span><span class="identifier">expr_param</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">impl</span><span class="special">::</span><span class="identifier">state_param</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">impl</span><span class="special">::</span><span class="identifier">data_param</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idp556187952"></a><h2>Description</h2> <p> If an expression type <code class="computeroutput">E</code> does not match a grammar <code class="computeroutput">G</code>, then <code class="computeroutput">E</code> <span class="emphasis"><em>does</em></span> match <code class="computeroutput">proto::not_&lt;G&gt;</code>. For example, <code class="computeroutput"><a class="link" href="not_.html" title="Struct template not_">proto::not_</a>&lt;<a class="link" href="terminal.html" title="Struct template terminal">proto::terminal</a>&lt;<a class="link" href="_.html" title="Struct _">proto::_</a>&gt; &gt;</code> will match any non-terminal. </p> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2008 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="_/impl.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../proto/reference.html#header.boost.proto.matches_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="not_/impl.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': '589940f2cda1079a0ae694dc4af5bfa8', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 583, 'avg_line_length': 94.32467532467533, 'alnum_prop': 0.6637752994630318, 'repo_name': 'keichan100yen/ode-ext', 'id': '9693dc438cbf834c1a9480016abc0d4616aa48d6', 'size': '7263', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'boost/doc/html/boost/proto/not_.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '309067'}, {'name': 'Batchfile', 'bytes': '37875'}, {'name': 'C', 'bytes': '2967570'}, {'name': 'C#', 'bytes': '40804'}, {'name': 'C++', 'bytes': '189322982'}, {'name': 'CMake', 'bytes': '119251'}, {'name': 'CSS', 'bytes': '456744'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Groff', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '181460055'}, {'name': 'IDL', 'bytes': '28'}, {'name': 'JavaScript', 'bytes': '419776'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '1088024'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '11406'}, {'name': 'Objective-C++', 'bytes': '630'}, {'name': 'PHP', 'bytes': '68641'}, {'name': 'Perl', 'bytes': '36491'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Python', 'bytes': '1612978'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Ruby', 'bytes': '5532'}, {'name': 'Shell', 'bytes': '354720'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'XSLT', 'bytes': '553585'}, {'name': 'Yacc', 'bytes': '19623'}]}
package org.kie.workbench.common.stunner.core.definition.clone; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class DefaultCloneProcessTest extends AbstractCloneProcessTest { private DefaultCloneProcess defaultCloneProcess; @Before public void setUp() throws Exception { super.setUp(); defaultCloneProcess = new DefaultCloneProcess(factoryManager, adapterManager); } @Test(expected = NullPointerException.class) public void testCloneNull() throws Exception { defaultCloneProcess.clone(null); } @Test public void testClone() throws Exception { Object clone = defaultCloneProcess.clone(def1); testPropertySet(clone, def1, nameProperty2, nameValue); } @Test public void testCloneParam() throws Exception { Object clone = defaultCloneProcess.clone(def1, def3); testPropertySet(clone, def1, nameProperty3, nameValue); } }
{'content_hash': 'e763d12014c951a3760ce01be9b79b7d', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 86, 'avg_line_length': 28.56756756756757, 'alnum_prop': 0.7313150425733207, 'repo_name': 'jhrcek/kie-wb-common', 'id': '6581c9d1e2dcd117a005f9875a8f4cb4834c36b3', 'size': '1676', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/test/java/org/kie/workbench/common/stunner/core/definition/clone/DefaultCloneProcessTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2591'}, {'name': 'CSS', 'bytes': '115195'}, {'name': 'Dockerfile', 'bytes': '210'}, {'name': 'FreeMarker', 'bytes': '36496'}, {'name': 'GAP', 'bytes': '86275'}, {'name': 'HTML', 'bytes': '331778'}, {'name': 'Java', 'bytes': '38263821'}, {'name': 'JavaScript', 'bytes': '20277'}, {'name': 'Shell', 'bytes': '905'}, {'name': 'Visual Basic', 'bytes': '84832'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tarski-geometry: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.6.1 / tarski-geometry - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tarski-geometry <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-10-23 08:52:47 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-10-23 08:52:47 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.6.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/tarski-geometry&quot; license: &quot;GPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/TarskiGeometry&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: geometry&quot; &quot;keyword: Tarski&#39;s geometry&quot; &quot;keyword: congruence&quot; &quot;keyword: between property&quot; &quot;keyword: orthogonality&quot; &quot;category: Mathematics/Geometry/General&quot; &quot;date: 2006-03&quot; ] authors: [ &quot;Julien Narboux &lt;[email protected]&gt; [http://dpt-info.u-strasbg.fr/~narboux/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/tarski-geometry/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/tarski-geometry.git&quot; synopsis: &quot;Tarski&#39;s geometry&quot; description: &quot;&quot;&quot; http://dpt-info.u-strasbg.fr/~narboux/tarski.html This is a formalization of geometry using a simplified version of Tarski&#39;s axiom system. The development contains a formalization of the chapters 1-8 of the book &quot;Metamathematische Methoden in der Geometrie&quot; by W. Schwabhäuser, W. Szmielew and A. Tarski. This includes between properties, congruence properties, midpoint, perpendicular lines, point reflection, orthogonality ... This development aims to be a low level complement for Frédérique Guilhot&#39;s development about high-school geometry. For more information see: Mechanical Theorem Proving in Tarski&#39;s geometry in the post-proceeding of ADG 2006, F. Botana and T. Recio (Eds.), LNAI 4869, pages 139-156, 2007.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/tarski-geometry/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=5c4cfcb3d4729304ebb823e9ed87de9e&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tarski-geometry.8.8.0 coq.8.6.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.6.1). The following dependencies couldn&#39;t be met: - coq-tarski-geometry -&gt; coq &gt;= 8.8 -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tarski-geometry.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{'content_hash': '29c91ce516c8d70eaf83e45514a60ab1', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 268, 'avg_line_length': 45.554913294797686, 'alnum_prop': 0.569217104428372, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': 'ea534d6a901b4fa888416857269b728654da1d6b', 'size': '7909', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.03.0-2.0.5/released/8.6.1/tarski-geometry/8.8.0.html', 'mode': '33188', 'license': 'mit', 'language': []}
""" Just for Python 3 """ import logging import pprint import tornado.web import tornado.httpserver from tornado.options import define, options, parse_command_line from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext import baked from sqlalchemy.orm import Session # models BAKERY = baked.bakery() Base = declarative_base() ENGINE = create_engine('sqlite:///:memory:', echo=False) class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String) fullname = Column(String) password = Column(String) def __repr__(self): return "<User(name='%s', fullname='%s', password='%s')>" % ( self.name, self.fullname, self.password) # request class MainHandler(tornado.web.RequestHandler): @property def session(self): return Session(bind=ENGINE) def get(self): uid = self.get_argument("uid") def fn(session): logging.warn("call fn %s", fn) return session.query(User).filter(User.id == uid) baked_query = BAKERY(fn) logging.info("fn %s", fn.__code__) logging.warn("baked_query _cache_key: %s", baked_query._cache_key) user_list = baked_query(self.session).all() self.write("user_list:\n{}\n".format(pprint.pformat(user_list))) def main(): Base.metadata.create_all(ENGINE) # add test user session = Session(bind=ENGINE) for uid in range(20): user = User(name='ed {}'.format(uid), fullname='Ed Jones {}'.format(uid), password='edspassword') session.add(user) session.commit() # start application application = tornado.web.Application([ (r"/", MainHandler), ], ) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(options.port) tornado.ioloop.IOLoop.current().start() if __name__ == "__main__": define("port", default=8888, help="run on the given port", type=int) parse_command_line() main()
{'content_hash': '93c0f38237e5af099b2e3ef567270231', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 105, 'avg_line_length': 24.03448275862069, 'alnum_prop': 0.6389287422285987, 'repo_name': 'mikegreen7892003/PythonToy', 'id': 'f72b8df9aa69d2cc28657e451f4a61aca75b3217', 'size': '2091', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'toys/sqlalchemy_bakery.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '12724'}]}
package com.weather.app.model; public class Province { private int id; private String provinceName; private String ProvinceCode; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProvinceName() { return provinceName; } public void setProvinceName(String provinceName) { this.provinceName = provinceName; } public String getProvinceCode() { return ProvinceCode; } public void setProvinceCode(String provinceCode) { ProvinceCode = provinceCode; } }
{'content_hash': '641a3dc6c0aadb89b2ef8c837f8b4e9e', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 51, 'avg_line_length': 18.20689655172414, 'alnum_prop': 0.7272727272727273, 'repo_name': 'wing2407/weather', 'id': 'bbcf5575634b245e147417a4d509474773bfdc18', 'size': '528', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/weather/app/model/Province.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '30394'}]}
/** * 弹出选择列表插件 * 此组件依赖 listpcker ,请在页面中先引入 mui.picker.css + mui.picker.js * varstion 1.0.1 * by Houfeng * [email protected] */ (function($, document) { //创建 DOM $.dom = function(str) { if (typeof(str) !== 'string') { if ((str instanceof Array) || (str[0] && str.length)) { return [].slice.call(str); } else { return [str]; } } if (!$.__create_dom_div__) { $.__create_dom_div__ = document.createElement('div'); } $.__create_dom_div__.innerHTML = str; return [].slice.call($.__create_dom_div__.childNodes); }; var panelBuffer = '<div class="mui-poppicker">\ <div class="mui-poppicker-header">\ <button class="mui-btn mui-poppicker-btn-cancel">取消</button>\ <button class="mui-btn mui-btn-blue mui-poppicker-btn-ok">确定</button>\ <div class="mui-poppicker-clear"></div>\ </div>\ <div class="mui-poppicker-body">\ </div>\ </div>'; var pickerBuffer = '<div class="mui-picker">\ <div class="mui-picker-inner">\ <div class="mui-pciker-rule mui-pciker-rule-ft"></div>\ <ul class="mui-pciker-list">\ </ul>\ <div class="mui-pciker-rule mui-pciker-rule-bg"></div>\ </div>\ </div>'; //定义弹出选择器类 var PopPicker = $.PopPicker = $.Class.extend({ //构造函数 init: function(options) { var self = this; self.options = options || {}; self.options.buttons = self.options.buttons || ['取消', '确定']; self.panel = $.dom(panelBuffer)[0]; document.body.appendChild(self.panel); self.ok = self.panel.querySelector('.mui-poppicker-btn-ok'); self.cancel = self.panel.querySelector('.mui-poppicker-btn-cancel'); self.body = self.panel.querySelector('.mui-poppicker-body'); self.mask = $.createMask(); self.cancel.innerText = self.options.buttons[0]; self.ok.innerText = self.options.buttons[1]; self.cancel.addEventListener('tap', function(event) { self.hide(); }, false); self.ok.addEventListener('tap', function(event) { if (self.callback) { var rs = self.callback(self.getSelectedItems()); if (rs !== false) { self.hide(); } } }, false); self.mask[0].addEventListener('tap', function() { self.hide(); }, false); self._createPicker(); //防止滚动穿透 self.panel.addEventListener($.EVENT_START, function(event) { event.preventDefault(); }, false); self.panel.addEventListener($.EVENT_MOVE, function(event) { event.preventDefault(); }, false); }, _createPicker: function() { var self = this; var layer = self.options.layer || 1; var width = (100 / layer) + '%'; self.pickers = []; for (var i = 1; i <= layer; i++) { var pickerElement = $.dom(pickerBuffer)[0]; pickerElement.style.width = width; self.body.appendChild(pickerElement); var picker = $(pickerElement).picker(); self.pickers.push(picker); pickerElement.addEventListener('change', function(event) { var nextPickerElement = this.nextSibling; if (nextPickerElement && nextPickerElement.picker) { var eventData = event.detail || {}; var preItem = eventData.item || {}; nextPickerElement.picker.setItems(preItem.children); } }, false); } }, //填充数据 setData: function(data) { var self = this; data = data || []; self.pickers[0].setItems(data); }, //获取选中的项(数组) getSelectedItems: function() { var self = this; var items = []; for (var i in self.pickers) { if(self.pickers.hasOwnProperty(i)) { // 修复for in会访问继承属性造成items报错情况 var picker = self.pickers[i]; items.push(picker.getSelectedItem() || {}); } } return items; }, //显示 show: function(callback) { var self = this; self.callback = callback; self.mask.show(); document.body.classList.add($.className('poppicker-active-for-page')); self.panel.classList.add($.className('active')); //处理物理返回键 self.__back = $.back; $.back = function() { self.hide(); }; }, //隐藏 hide: function() { var self = this; if (self.disposed) return; self.panel.classList.remove($.className('active')); self.mask.close(); document.body.classList.remove($.className('poppicker-active-for-page')); //处理物理返回键 $.back=self.__back; }, dispose: function() { var self = this; self.hide(); setTimeout(function() { self.panel.parentNode.removeChild(self.panel); for (var name in self) { self[name] = null; delete self[name]; }; self.disposed = true; }, 300); } }); })(mui, document);
{'content_hash': 'bffdd65098158478eea76fbec10bf850', 'timestamp': '', 'source': 'github', 'line_count': 160, 'max_line_length': 76, 'avg_line_length': 27.8375, 'alnum_prop': 0.6154018859452178, 'repo_name': 'csxiaoyaojianxian/JavaScriptStudy', 'id': '4c4ce1eed55f94e6fca06da6d855992b2c5771fb', 'size': '4648', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': '12-前端框架/06-vue/vue-demo/app/static/vendor/mui/examples/hello-mui/js/mui.poppicker.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1641'}, {'name': 'CSS', 'bytes': '169666'}, {'name': 'Go', 'bytes': '1739'}, {'name': 'HTML', 'bytes': '3408161'}, {'name': 'Java', 'bytes': '223295'}, {'name': 'JavaScript', 'bytes': '15969943'}, {'name': 'Less', 'bytes': '68'}, {'name': 'Makefile', 'bytes': '94'}, {'name': 'Objective-C', 'bytes': '85461'}, {'name': 'PHP', 'bytes': '64209'}, {'name': 'PLpgSQL', 'bytes': '1195'}, {'name': 'Ruby', 'bytes': '1863'}, {'name': 'Shell', 'bytes': '375'}, {'name': 'Starlark', 'bytes': '1720'}, {'name': 'Stylus', 'bytes': '148'}, {'name': 'TypeScript', 'bytes': '115678'}, {'name': 'Vue', 'bytes': '224599'}]}
package org.maltparser.parser.algorithm.planar; import org.maltparser.core.exception.MaltChainedException; import org.maltparser.core.syntaxgraph.DependencyStructure; import org.maltparser.core.syntaxgraph.node.DependencyNode; import org.maltparser.parser.DependencyParserConfig; import org.maltparser.parser.Oracle; import org.maltparser.parser.ParserConfiguration; import org.maltparser.parser.history.GuideUserHistory; import org.maltparser.parser.history.action.GuideUserAction; /** * @author Carlos Gomez Rodriguez * */ public class PlanarArcEagerOracle extends Oracle { public PlanarArcEagerOracle(DependencyParserConfig manager, GuideUserHistory history) throws MaltChainedException { super(manager, history); setGuideName("Planar"); } public GuideUserAction predict(DependencyStructure gold, ParserConfiguration config) throws MaltChainedException { PlanarConfig planarConfig = (PlanarConfig)config; DependencyStructure dg = planarConfig.getDependencyGraph(); DependencyNode stackPeek = planarConfig.getStack().peek(); int stackPeekIndex = stackPeek.getIndex(); int inputPeekIndex = planarConfig.getInput().peek().getIndex(); if (!stackPeek.isRoot() && gold.getTokenNode(stackPeekIndex).getHead().getIndex() == inputPeekIndex && !checkIfArcExists ( dg , inputPeekIndex , stackPeekIndex ) ) { return updateActionContainers(Planar.LEFTARC, gold.getTokenNode(stackPeekIndex).getHeadEdge().getLabelSet()); } else if (gold.getTokenNode(inputPeekIndex).getHead().getIndex() == stackPeekIndex && !checkIfArcExists ( dg , stackPeekIndex , inputPeekIndex ) ) { return updateActionContainers(Planar.RIGHTARC, gold.getTokenNode(inputPeekIndex).getHeadEdge().getLabelSet()); } else if (gold.getTokenNode(inputPeekIndex).hasLeftDependent() && gold.getTokenNode(inputPeekIndex).getLeftmostDependent().getIndex() < stackPeekIndex) { return updateActionContainers(Planar.REDUCE, null); } else if (gold.getTokenNode(inputPeekIndex).getHead().getIndex() < stackPeekIndex && ( !gold.getTokenNode(inputPeekIndex).getHead().isRoot() || planarConfig.getRootHandling()==PlanarConfig.NORMAL ) ) { return updateActionContainers(Planar.REDUCE, null); } else { return updateActionContainers(Planar.SHIFT, null); } } private boolean checkIfArcExists ( DependencyStructure dg , int index1 , int index2 ) throws MaltChainedException { return dg.getTokenNode(index2).hasHead() && dg.getTokenNode(index2).getHead().getIndex() == index1; } public void finalizeSentence(DependencyStructure dependencyGraph) throws MaltChainedException {} public void terminate() throws MaltChainedException {} }
{'content_hash': '337a8c38ed07d360a3f946e70186208d', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 117, 'avg_line_length': 47.80701754385965, 'alnum_prop': 0.7666055045871559, 'repo_name': 'jhamalt/maltparser', 'id': '315ae50694cf78d1e4c953046aa5f56fc63ab3d6', 'size': '2725', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/org/maltparser/parser/algorithm/planar/PlanarArcEagerOracle.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '9242'}, {'name': 'Java', 'bytes': '1745929'}]}
<?php /** * * * * */ namespace MagentoHackathon\Composer\Magento; use Composer\Config; use Composer\Installer; use Composer\Package\AliasPackage; use Composer\Script\Event; use MagentoHackathon\Composer\Helper; use MagentoHackathon\Composer\Magento\Event\EventManager; use MagentoHackathon\Composer\Magento\Event\PackageDeployEvent; use MagentoHackathon\Composer\Magento\Factory\DeploystrategyFactory; use MagentoHackathon\Composer\Magento\Factory\EntryFactory; use MagentoHackathon\Composer\Magento\Factory\ParserFactory; use MagentoHackathon\Composer\Magento\Factory\PathTranslationParserFactory; use MagentoHackathon\Composer\Magento\Patcher\Bootstrap; use MagentoHackathon\Composer\Magento\Repository\InstalledPackageFileSystemRepository; use MagentoHackathon\Composer\Magento\UnInstallStrategy\UnInstallStrategy; use MagentoHackathon\Composer\Magento\Factory\InstallStrategyFactory; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Plugin\PluginInterface; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\Script\ScriptEvents; use Composer\Util\Filesystem; use Symfony\Component\Process\Process; class Plugin implements PluginInterface, EventSubscriberInterface { /** * The type of packages this plugin supports */ const PACKAGE_TYPE = 'magento-module'; const VENDOR_DIR_KEY = 'vendor-dir'; const BIN_DIR_KEY = 'bin-dir'; const THESEER_AUTOLOAD_EXEC_BIN_PATH = '/phpab'; const THESEER_AUTOLOAD_EXEC_REL_PATH = '/theseer/autoload/composer/bin/phpab'; /** * @var IOInterface */ protected $io; /** * @var ProjectConfig */ protected $config; /** * @var DeployManager */ protected $deployManager; /** * @var Composer */ protected $composer; /** * @var Filesystem */ protected $filesystem; /** * @var EntryFactory */ protected $entryFactory; /** * @var EventManager */ private $eventManager; /** * @var ModuleManager */ private $moduleManager; /** * init the DeployManager * * @param Composer $composer * @param IOInterface $io */ protected function initDeployManager(Composer $composer, IOInterface $io, EventManager $eventManager) { $this->deployManager = new DeployManager($eventManager); $this->deployManager->setSortPriority($this->getSortPriority($composer)); $this->applyEvents($eventManager); } protected function applyEvents(EventManager $eventManager) { if ($this->config->hasAutoAppendGitignore()) { $gitIgnoreLocation = sprintf('%s/.gitignore', $this->config->getMagentoRootDir()); $gitIgnore = new GitIgnoreListener(new GitIgnore($gitIgnoreLocation)); $eventManager->listen('post-package-deploy', [$gitIgnore, 'addNewInstalledFiles']); $eventManager->listen('post-package-uninstall', [$gitIgnore, 'removeUnInstalledFiles']); } $io = $this->io; if ($this->io->isDebug()) { $eventManager->listen('pre-package-deploy', function (PackageDeployEvent $event) use ($io) { $io->write('Start magento deploy for ' . $event->getDeployEntry()->getPackageName()); }); } } /** * get Sort Priority from extra Config * * @param \Composer\Composer $composer * * @return array */ private function getSortPriority(Composer $composer) { $extra = $composer->getPackage()->getExtra(); return isset($extra[ProjectConfig::SORT_PRIORITY_KEY]) ? $extra[ProjectConfig::SORT_PRIORITY_KEY] : array(); } /** * Apply plugin modifications to composer * * @param Composer $composer * @param IOInterface $io */ public function activate(Composer $composer, IOInterface $io) { $this->io = $io; $this->composer = $composer; $this->filesystem = new Filesystem(); $this->config = new ProjectConfig($composer->getPackage()->getExtra(), $composer->getConfig()->all()); if (!$this->config->skipSuggestComposerRepositories()) { $this->suggestComposerRepositories(); } $this->entryFactory = new EntryFactory( $this->config, new DeploystrategyFactory($this->config), new PathTranslationParserFactory(new ParserFactory($this->config), $this->config) ); $this->initDeployManager($composer, $io, $this->getEventManager()); $this->writeDebug('activate magento plugin'); } /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to */ public static function getSubscribedEvents() { return array( ScriptEvents::POST_INSTALL_CMD => array( array('onNewCodeEvent', 0), ), ScriptEvents::POST_UPDATE_CMD => array( array('onNewCodeEvent', 0), ), ); } /** * event listener is named this way, as it listens for events leading to changed code files * * @param Event $event */ public function onNewCodeEvent(Event $event) { $packageTypeToMatch = static::PACKAGE_TYPE; $magentoModules = array_filter( $this->composer->getRepositoryManager()->getLocalRepository()->getPackages(), function (PackageInterface $package) use ($packageTypeToMatch) { if ($package instanceof AliasPackage) { return false; } return $package->getType() === $packageTypeToMatch; } ); $vendorDir = rtrim($this->composer->getConfig()->get(self::VENDOR_DIR_KEY), '/'); Helper::initMagentoRootDir( $this->config, $this->io, $this->filesystem, $vendorDir ); $this->applyEvents($this->getEventManager()); if (in_array('--redeploy', $event->getArguments())) { $this->writeDebug('remove all deployed modules'); $this->getModuleManager()->updateInstalledPackages(array()); } $this->writeDebug('start magento module deploy via moduleManager'); $this->getModuleManager()->updateInstalledPackages($magentoModules); $this->deployLibraries(); $patcher = Bootstrap::fromConfig($this->config); $patcher->setIo($this->io); try { $patcher->patch(); } catch (\DomainException $e) { $this->io->write('<comment>'.$e->getMessage().'</comment>'); } } /** * test configured repositories and give message about adding recommended ones */ protected function suggestComposerRepositories() { $foundFiregento = false; $foundMagento = false; foreach ($this->config->getComposerRepositories() as $repository) { if (!isset($repository["type"]) || $repository["type"] !== "composer") { continue; } if (strpos($repository["url"], "packages.firegento.com") !== false) { $foundFiregento = true; } if (strpos($repository["url"], "packages.magento.com") !== false) { $foundMagento = true; } }; $message1 = "<comment>you may want to add the %s repository to composer.</comment>"; $message2 = "<comment>add it with:</comment> composer.phar config -g repositories.%s composer %s"; if (!$foundFiregento) { $this->io->write(sprintf($message1, 'packages.firegento.com')); $this->io->write(sprintf($message2, 'firegento', 'http://packages.firegento.com')); } if (!$foundMagento) { $this->io->write(sprintf($message1, 'packages.magento.com')); $this->io->write(sprintf($message2, 'magento', 'https?://packages.magento.com')); } } /** * deploy Libraries */ protected function deployLibraries() { $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getPackages(); $autoloadDirectories = array(); $libraryPath = $this->config->getLibraryPath(); if ($libraryPath === null) { $this->writeDebug('jump over deployLibraries as no Magento libraryPath is set'); return; } $vendorDir = rtrim($this->composer->getConfig()->get(self::VENDOR_DIR_KEY), '/'); $this->filesystem->removeDirectory($libraryPath); $this->filesystem->ensureDirectoryExists($libraryPath); foreach ($packages as $package) { /** @var PackageInterface $package */ $packageConfig = $this->config->getLibraryConfigByPackagename($package->getName()); if ($packageConfig === null) { continue; } if (!isset($packageConfig['autoload'])) { $packageConfig['autoload'] = array('/'); } foreach ($packageConfig['autoload'] as $path) { $autoloadDirectories[] = $libraryPath . '/' . $package->getName() . "/" . $path; } $this->writeDebug(sprintf('Magento deployLibraries executed for %s', $package->getName())); $libraryTargetPath = $libraryPath . '/' . $package->getName(); $this->filesystem->removeDirectory($libraryTargetPath); $this->filesystem->ensureDirectoryExists($libraryTargetPath); $this->copyRecursive($vendorDir . '/' . $package->getPrettyName(), $libraryTargetPath); } if (false !== ($executable = $this->getTheseerAutoloadExecutable())) { $this->writeDebug('Magento deployLibraries executes autoload generator'); $params = $this->getTheseerAutoloadParams($libraryPath, $autoloadDirectories); $process = new Process($executable . $params); $process->run(); } } /** * return the autoload generator binary path or false if not found * * @return bool|string */ protected function getTheseerAutoloadExecutable() { $executable = $this->composer->getConfig()->get(self::BIN_DIR_KEY) . self::THESEER_AUTOLOAD_EXEC_BIN_PATH; if (!file_exists($executable)) { $executable = $this->composer->getConfig()->get(self::VENDOR_DIR_KEY) . self::THESEER_AUTOLOAD_EXEC_REL_PATH; } if (!file_exists($executable)) { $this->writeDebug( 'Magento deployLibraries autoload generator not available, you should require "theseer/autoload"', $executable ); return false; } return $executable; } /** * get Theseer Autoload Generator Params * * @param string $libraryPath * @param array $autoloadDirectories * * @return string */ protected function getTheseerAutoloadParams($libraryPath, $autoloadDirectories) { // @todo --blacklist 'test\\\\*' return " -b {$libraryPath} -o {$libraryPath}/autoload.php " . implode(' ', $autoloadDirectories); } /** * Copy then delete is a non-atomic version of {@link rename}. * * Some systems can't rename and also don't have proc_open, * which requires this solution. * * copied from \Composer\Util\Filesystem::copyThenRemove and removed the remove part * * @param string $source * @param string $target */ protected function copyRecursive($source, $target) { $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST); $this->filesystem->ensureDirectoryExists($target); foreach ($ri as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName(); if ($file->isDir()) { $this->filesystem->ensureDirectoryExists($targetPath); } else { copy($file->getPathname(), $targetPath); } } } /** * print Debug Message * * @param $message */ private function writeDebug($message, $varDump = null) { if ($this->io->isDebug()) { $this->io->write($message); if (!is_null($varDump)) { var_dump($varDump); } } } /** * @param PackageInterface $package * @return string */ public function getPackageInstallPath(PackageInterface $package) { $vendorDir = realpath(rtrim($this->composer->getConfig()->get('vendor-dir'), '/')); return sprintf('%s/%s', $vendorDir, $package->getPrettyName()); } /** * @return EventManager */ protected function getEventManager() { if (null === $this->eventManager) { $this->eventManager = new EventManager; } return $this->eventManager; } /** * @return ModuleManager */ protected function getModuleManager() { if (null === $this->moduleManager) { $this->moduleManager = new ModuleManager( new InstalledPackageFileSystemRepository( rtrim($this->composer->getConfig()->get(self::VENDOR_DIR_KEY), '/') . '/installed.json', new InstalledPackageDumper() ), $this->getEventManager(), $this->config, new UnInstallStrategy($this->filesystem, $this->config->getMagentoRootDir()), new InstallStrategyFactory($this->config, new ParserFactory($this->config)) ); } return $this->moduleManager; } }
{'content_hash': '7213321188d812cb6c0304e831e8725a', 'timestamp': '', 'source': 'github', 'line_count': 455, 'max_line_length': 114, 'avg_line_length': 32.074725274725274, 'alnum_prop': 0.5959298341784295, 'repo_name': 'hansbonini/cloud9-magento', 'id': 'e4c819f5dbfc64ad43591b5fa4beb739524e6156', 'size': '14594', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'vendor/magento-hackathon/magento-composer-installer/src/MagentoHackathon/Composer/Magento/Plugin.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '20063'}, {'name': 'ApacheConf', 'bytes': '6515'}, {'name': 'Batchfile', 'bytes': '1036'}, {'name': 'CSS', 'bytes': '1761053'}, {'name': 'HTML', 'bytes': '5281773'}, {'name': 'JavaScript', 'bytes': '1126889'}, {'name': 'PHP', 'bytes': '47400395'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Ruby', 'bytes': '288'}, {'name': 'Shell', 'bytes': '3879'}, {'name': 'XSLT', 'bytes': '2135'}]}
/** * */ package gov.nih.nci.cagrid.portal.portlet.browse; import java.util.Map; import javax.portlet.PortletMode; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.liferay.portal.kernel.portlet.BaseFriendlyURLMapper; import com.liferay.portal.kernel.portlet.LiferayPortletURL; /** * @author <a href="mailto:[email protected]>Joshua Phillips</a> * */ public class BrowseFriendlyURLMapper extends BaseFriendlyURLMapper { private static final Log logger = LogFactory.getLog(BrowseFriendlyURLMapper.class); private static final String PORTLETID = "BrowsePortlet"; private static final String MAPPING = "browse_catalog"; /* (non-Javadoc) * @see com.liferay.portal.kernel.portlet.BaseFriendlyURLMapper#getPortletId() */ @Override public String getPortletId() { return PORTLETID; } /* (non-Javadoc) * @see com.liferay.portal.kernel.portlet.FriendlyURLMapper#buildPath(com.liferay.portal.kernel.portlet.LiferayPortletURL) */ public String buildPath(LiferayPortletURL portletURL) { String path = null; // String path = "/" + MAPPING + "/" + portletURL.getParameter("entryId"); // logger.debug("returning friendly path: " + path); return path; } /* (non-Javadoc) * @see com.liferay.portal.kernel.portlet.FriendlyURLMapper#getMapping() */ public String getMapping() { return MAPPING; } /* (non-Javadoc) * @see com.liferay.portal.kernel.portlet.FriendlyURLMapper#populateParams(java.lang.String, java.util.Map) */ public void populateParams(String friendlyURLPath, Map<String, String[]> params) { logger.debug("friendlyURLPath: " + friendlyURLPath); addParam(params, "p_p_id", PORTLETID); addParam(params, "p_p_lifecycle", "0"); addParam(params, "p_p_mode", PortletMode.VIEW); int x = friendlyURLPath.indexOf("/", 1); if(x == -1){ logger.debug("no id provided 1"); addParam(params, "operation", "view"); return; } if((x + 1) == friendlyURLPath.length()){ logger.debug("no id provided 2"); addParam(params, "operation", "view"); return; } String entryId = null; int y = friendlyURLPath.indexOf("/", x + 1); if(y != -1){ entryId = friendlyURLPath.substring(x + 1, y); }else{ entryId = friendlyURLPath.substring(x + 1); } addParam(params, "operation", "viewDetails"); addParam(params, "entryId", entryId); logger.debug("Params: " + params); } }
{'content_hash': '217853cbedcd9f0abfa6bbe1df471a76', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 123, 'avg_line_length': 26.791208791208792, 'alnum_prop': 0.7022149302707137, 'repo_name': 'NCIP/cagrid', 'id': '21f2fb80511b20a55bf44861bda1b425f7b201c7', 'size': '2438', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cagrid/Software/portal/cagrid-portal/portlets/src/java/gov/nih/nci/cagrid/portal/portlet/browse/BrowseFriendlyURLMapper.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '438360'}, {'name': 'Java', 'bytes': '25536538'}, {'name': 'JavaScript', 'bytes': '265984'}, {'name': 'Perl', 'bytes': '115674'}, {'name': 'Scala', 'bytes': '405'}, {'name': 'Shell', 'bytes': '85928'}, {'name': 'XSLT', 'bytes': '75865'}]}
#pragma once #include <medAbstractDataSource.h> #include <medMoveCommandItem.h> class medPacsDataSourcePrivate; class medToolBox; /** * @class Pacs connection datasource that comes with treeview, * searchpanel and source selector (DICOM-nodes) */ class medPacsDataSource : public medAbstractDataSource { Q_OBJECT public: medPacsDataSource(QWidget* parent = 0); ~medPacsDataSource(); QWidget* mainViewWidget(); QWidget* sourceSelectorWidget(); QString tabName(); QList<medToolBox*> getToolBoxes(); QString description() const; private slots: void onPacsMove( const QVector<medMoveCommandItem>& cmdList); private: medPacsDataSourcePrivate* d; };
{'content_hash': 'cd78d6fbd8f7972e30dff16d92814f98', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 65, 'avg_line_length': 17.146341463414632, 'alnum_prop': 0.7311522048364154, 'repo_name': 'aabadie/medInria-public', 'id': '054d4af0107c558d8611be7e88e8fb67e348ee59', 'size': '1101', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'app/medInria/medPacsDataSource.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '112085'}, {'name': 'C++', 'bytes': '4083079'}, {'name': 'CMake', 'bytes': '128199'}, {'name': 'GLSL', 'bytes': '15515'}, {'name': 'HTML', 'bytes': '669'}, {'name': 'Objective-C', 'bytes': '14534'}]}
'use strict'; /*! * Module dependencies. */ var SchemaType = require('../schematype'); var Subdocument = require('../types/subdocument'); var castToNumber = require('./operators/helpers').castToNumber; var geospatial = require('./operators/geospatial'); module.exports = Embedded; /** * Sub-schema schematype constructor * * @param {Schema} schema * @param {String} key * @param {Object} options * @inherits SchemaType * @api public */ function Embedded(schema, path, options) { var _embedded = function(value, path, parent) { var _this = this; Subdocument.apply(this, arguments); this.$parent = parent; if (parent) { parent.on('save', function() { _this.emit('save', _this); }); parent.on('isNew', function(val) { _this.isNew = val; _this.emit('isNew', val); }); } }; _embedded.prototype = Object.create(Subdocument.prototype); _embedded.prototype.$__setSchema(schema); _embedded.schema = schema; _embedded.$isSingleNested = true; _embedded.prototype.$basePath = path; _embedded.prototype.toBSON = function() { return this.toObject({ transform: false, retainKeyOrder: schema.options.retainKeyOrder }); }; // apply methods for (var i in schema.methods) { _embedded.prototype[i] = schema.methods[i]; } // apply statics for (i in schema.statics) { _embedded[i] = schema.statics[i]; } this.caster = _embedded; this.schema = schema; this.$isSingleNested = true; SchemaType.call(this, path, options, 'Embedded'); } Embedded.prototype = Object.create(SchemaType.prototype); /** * Special case for when users use a common location schema to represent * locations for use with $geoWithin. * https://docs.mongodb.org/manual/reference/operator/query/geoWithin/ * * @param {Object} val * @api private */ Embedded.prototype.$conditionalHandlers.$geoWithin = function(val) { return { $geometry: this.castForQuery(val.$geometry) }; }; /*! * ignore */ Embedded.prototype.$conditionalHandlers.$near = Embedded.prototype.$conditionalHandlers.$nearSphere = geospatial.cast$near; Embedded.prototype.$conditionalHandlers.$within = Embedded.prototype.$conditionalHandlers.$geoWithin = geospatial.cast$within; Embedded.prototype.$conditionalHandlers.$geoIntersects = geospatial.cast$geoIntersects; Embedded.prototype.$conditionalHandlers.$minDistance = castToNumber; Embedded.prototype.$conditionalHandlers.$maxDistance = castToNumber; /** * Casts contents * * @param {Object} value * @api private */ Embedded.prototype.cast = function(val, doc, init) { if (val && val.$isSingleNested) { return val; } var subdoc = new this.caster(void 0, doc ? doc.$__.selected : void 0, doc); if (init) { subdoc.init(val); } else { subdoc.set(val, undefined, true); } return subdoc; }; /** * Casts contents for query * * @param {string} [$conditional] optional query operator (like `$eq` or `$in`) * @param {any} value * @api private */ Embedded.prototype.castForQuery = function($conditional, val) { var handler; if (arguments.length === 2) { handler = this.$conditionalHandlers[$conditional]; if (!handler) { throw new Error('Can\'t use ' + $conditional); } return handler.call(this, val); } val = $conditional; if (val == null) { return val; } return new this.caster(val); }; /** * Async validation on this single nested doc. * * @api private */ Embedded.prototype.doValidate = function(value, fn) { SchemaType.prototype.doValidate.call(this, value, function(error) { if (error) { return fn(error); } if (!value) { return fn(null); } value.validate(fn, {__noPromise: true}); }); }; /** * Synchronously validate this single nested doc * * @api private */ Embedded.prototype.doValidateSync = function(value) { var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value); if (schemaTypeError) { return schemaTypeError; } if (!value) { return; } return value.validateSync(); };
{'content_hash': '426b434ab848beddf1716d512ebdd4bf', 'timestamp': '', 'source': 'github', 'line_count': 177, 'max_line_length': 79, 'avg_line_length': 23.050847457627118, 'alnum_prop': 0.6664215686274509, 'repo_name': 'anshul313/chibleetestbackend', 'id': 'cb5ed851e5c5cc51e67c236e2ed55042bfc36694', 'size': '4080', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'node_modules/mongoose/lib/schema/embedded.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '715'}, {'name': 'HTML', 'bytes': '9655'}, {'name': 'JavaScript', 'bytes': '274572'}, {'name': 'Shell', 'bytes': '685'}]}
<component name="libraryTable"> <library name="firebase-auth-module-9.0.2"> <CLASSES> <root url="file://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.google.firebase/firebase-auth-module/9.0.2/res" /> <root url="jar://$PROJECT_DIR$/app/build/intermediates/exploded-aar/com.google.firebase/firebase-auth-module/9.0.2/jars/classes.jar!/" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
{'content_hash': 'b6c1824bf059365cc6f1caf04dfba09a', 'timestamp': '', 'source': 'github', 'line_count': 10, 'max_line_length': 143, 'avg_line_length': 43.8, 'alnum_prop': 0.682648401826484, 'repo_name': 'ashish1dev/AndroidSqliteFirebaseCloudSync', 'id': 'eac8b248a51cc90320655468976a99254dce9b5f', 'size': '438', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': '.idea/libraries/firebase_auth_module_9_0_2.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '705759'}]}
<!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_13) on Fri Aug 14 15:51:17 CDT 2009 --> <TITLE> TFloatIterator (GNU Trove for Java API v2.1.0) </TITLE> <META NAME="date" CONTENT="2009-08-14"> <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="TFloatIterator (GNU Trove for Java API v2.1.0)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TFloatIterator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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-files/index-1.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> <a href="http://trove4j.sourceforge.net/">GNU Trove</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../gnu/trove/TFloatIntProcedure.html" title="interface in gnu.trove"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../gnu/trove/TFloatLongHashMap.html" title="class in gnu.trove"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?gnu/trove/TFloatIterator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TFloatIterator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <!-- ======== START OF CLASS DATA ======== --> <H2> <FONT SIZE="-1"> gnu.trove</FONT> <BR> Class TFloatIterator</H2> <PRE> java.lang.Object <IMG SRC="../../resources/inherit.gif" ALT="extended by "><B>gnu.trove.TFloatIterator</B> </PRE> <HR> <DL> <DT><PRE>public class <B>TFloatIterator</B><DT>extends java.lang.Object</DL> </PRE> <P> Iterator for float collections. <P> <P> <DL> <DT><B>Version:</B></DT> <DD>$Id: PIterator.template,v 1.1 2006/11/10 23:28:00 robeden Exp $</DD> <DT><B>Author:</B></DT> <DD>Eric D. Friedman</DD> </DL> <HR> <P> <!-- =========== FIELD SUMMARY =========== --> <A NAME="field_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Field Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#_expectedSize">_expectedSize</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;the number of elements this iterator believes are in the data structure it accesses.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#_index">_index</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;the index used for iteration.</TD> </TR> </TABLE> &nbsp; <!-- ======== CONSTRUCTOR SUMMARY ======== --> <A NAME="constructor_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Constructor Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#TFloatIterator(gnu.trove.TFloatHash)">TFloatIterator</A></B>(<A HREF="../../gnu/trove/TFloatHash.html" title="class in gnu.trove">TFloatHash</A>&nbsp;hash)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Creates a TFloatIterator for the elements in the specified collection.</TD> </TR> </TABLE> &nbsp; <!-- ========== METHOD SUMMARY =========== --> <A NAME="method_summary"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> <B>Method Summary</B></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;boolean</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#hasNext()">hasNext</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns true if the iterator can be advanced past its current location.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#moveToNextIndex()">moveToNextIndex</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the internal <tt>index</tt> so that the `next' object can be returned.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;float</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#next()">next</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Advances the iterator to the next element in the underlying collection and returns it.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;int</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#nextIndex()">nextIndex</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the index of the next value in the data structure or a negative value if the iterator is exhausted.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B><A HREF="../../gnu/trove/TFloatIterator.html#remove()">remove</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Removes the last entry returned by the iterator.</TD> </TR> </TABLE> &nbsp;<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD> </TR> </TABLE> &nbsp; <P> <!-- ============ FIELD DETAIL =========== --> <A NAME="field_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Field Detail</B></FONT></TH> </TR> </TABLE> <A NAME="_expectedSize"><!-- --></A><H3> _expectedSize</H3> <PRE> protected int <B>_expectedSize</B></PRE> <DL> <DD>the number of elements this iterator believes are in the data structure it accesses. <P> <DL> </DL> </DL> <HR> <A NAME="_index"><!-- --></A><H3> _index</H3> <PRE> protected int <B>_index</B></PRE> <DL> <DD>the index used for iteration. <P> <DL> </DL> </DL> <!-- ========= CONSTRUCTOR DETAIL ======== --> <A NAME="constructor_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Constructor Detail</B></FONT></TH> </TR> </TABLE> <A NAME="TFloatIterator(gnu.trove.TFloatHash)"><!-- --></A><H3> TFloatIterator</H3> <PRE> public <B>TFloatIterator</B>(<A HREF="../../gnu/trove/TFloatHash.html" title="class in gnu.trove">TFloatHash</A>&nbsp;hash)</PRE> <DL> <DD>Creates a TFloatIterator for the elements in the specified collection. <P> </DL> <!-- ============ METHOD DETAIL ========== --> <A NAME="method_detail"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2"> <B>Method Detail</B></FONT></TH> </TR> </TABLE> <A NAME="next()"><!-- --></A><H3> next</H3> <PRE> public float <B>next</B>()</PRE> <DL> <DD>Advances the iterator to the next element in the underlying collection and returns it. <P> <DD><DL> <DT><B>Returns:</B><DD>the next float in the collection <DT><B>Throws:</B> <DD><CODE>NoSuchElementException</CODE> - if the iterator is already exhausted</DL> </DD> </DL> <HR> <A NAME="nextIndex()"><!-- --></A><H3> nextIndex</H3> <PRE> protected final int <B>nextIndex</B>()</PRE> <DL> <DD>Returns the index of the next value in the data structure or a negative value if the iterator is exhausted. <P> <DD><DL> </DL> </DD> <DD><DL> <DT><B>Returns:</B><DD>an <code>int</code> value <DT><B>Throws:</B> <DD><CODE>java.util.ConcurrentModificationException</CODE> - if the underlying collection's size has been modified since the iterator was created.</DL> </DD> </DL> <HR> <A NAME="hasNext()"><!-- --></A><H3> hasNext</H3> <PRE> public boolean <B>hasNext</B>()</PRE> <DL> <DD>Returns true if the iterator can be advanced past its current location. <P> <DD><DL> <DT><B>Returns:</B><DD>a <code>boolean</code> value</DL> </DD> </DL> <HR> <A NAME="remove()"><!-- --></A><H3> remove</H3> <PRE> public void <B>remove</B>()</PRE> <DL> <DD>Removes the last entry returned by the iterator. Invoking this method more than once for a single entry will leave the underlying data structure in a confused state. <P> <DD><DL> </DL> </DD> </DL> <HR> <A NAME="moveToNextIndex()"><!-- --></A><H3> moveToNextIndex</H3> <PRE> protected final void <B>moveToNextIndex</B>()</PRE> <DL> <DD>Sets the internal <tt>index</tt> so that the `next' object can be returned. <P> <DD><DL> </DL> </DD> </DL> <!-- ========= END OF CLASS DATA ========= --> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="class-use/TFloatIterator.html"><FONT CLASS="NavBarFont1"><B>Use</B></FONT></A>&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-files/index-1.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> <a href="http://trove4j.sourceforge.net/">GNU Trove</a></EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../gnu/trove/TFloatIntProcedure.html" title="interface in gnu.trove"><B>PREV CLASS</B></A>&nbsp; &nbsp;<A HREF="../../gnu/trove/TFloatLongHashMap.html" title="class in gnu.trove"><B>NEXT CLASS</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../index.html?gnu/trove/TFloatIterator.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="TFloatIterator.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> <TR> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> SUMMARY:&nbsp;NESTED&nbsp;|&nbsp;<A HREF="#field_summary">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_summary">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_summary">METHOD</A></FONT></TD> <TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:&nbsp;<A HREF="#field_detail">FIELD</A>&nbsp;|&nbsp;<A HREF="#constructor_detail">CONSTR</A>&nbsp;|&nbsp;<A HREF="#method_detail">METHOD</A></FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> GNU Trove is copyright © 2001-2009 Eric D. Friedman. All Rights Reserved. </BODY> </HTML>
{'content_hash': '368479d27493bd031a6cc7e2322b0192', 'timestamp': '', 'source': 'github', 'line_count': 432, 'max_line_length': 220, 'avg_line_length': 35.53472222222222, 'alnum_prop': 0.6384600351768615, 'repo_name': 'jgaltidor/VarJ', 'id': '08632c3da7590fb14ed3444d5bd2732aaedd06e1', 'size': '15351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'analyzed_libs/trove-2.1.0/javadocs/gnu/trove/TFloatIterator.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2125'}, {'name': 'CSS', 'bytes': '9913'}, {'name': 'Emacs Lisp', 'bytes': '12570'}, {'name': 'Java', 'bytes': '31711742'}, {'name': 'JavaScript', 'bytes': '3251'}, {'name': 'Makefile', 'bytes': '257'}, {'name': 'Perl', 'bytes': '5179'}, {'name': 'Prolog', 'bytes': '292'}, {'name': 'Python', 'bytes': '1080'}, {'name': 'Scala', 'bytes': '42424'}, {'name': 'Shell', 'bytes': '43707'}, {'name': 'TeX', 'bytes': '372287'}]}
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System; using System.Collections.Immutable; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class ValueSetFactory { /// <summary> /// A value set that only supports equality and works by including or excluding specific values. /// This is used for value set of <see cref="System.String"/> because the language defines no /// relational operators for it; such a set can be formed only by including explicitly mentioned /// members (or the inverse, excluding them, by complementing the set). /// </summary> private sealed class EnumeratedValueSet<T, TTC> : IValueSet<T> where TTC : struct, IEquatableValueTC<T> where T : notnull { /// <summary> /// In <see cref="_included"/>, then members are listed by inclusion. Otherwise all members /// are assumed to be contained in the set unless excluded. /// </summary> private readonly bool _included; private readonly ImmutableHashSet<T> _membersIncludedOrExcluded; private EnumeratedValueSet(bool included, ImmutableHashSet<T> membersIncludedOrExcluded) => (this._included, this._membersIncludedOrExcluded) = (included, membersIncludedOrExcluded); public static readonly EnumeratedValueSet<T, TTC> AllValues = new EnumeratedValueSet<T, TTC>(included: false, ImmutableHashSet<T>.Empty); public static readonly EnumeratedValueSet<T, TTC> NoValues = new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty); internal static EnumeratedValueSet<T, TTC> Including(T value) => new EnumeratedValueSet<T, TTC>(included: true, ImmutableHashSet<T>.Empty.Add(value)); public bool IsEmpty => _included && _membersIncludedOrExcluded.IsEmpty; ConstantValue IValueSet.Sample { get { if (IsEmpty) throw new ArgumentException(); var tc = default(TTC); if (_included) return tc.ToConstantValue(_membersIncludedOrExcluded.OrderBy(k => k).First()); if (typeof(T) == typeof(string)) { // try some simple strings. if (this.Any(BinaryOperatorKind.Equal, (T)(object)"")) return tc.ToConstantValue((T)(object)""); for (char c = 'A'; c <= 'z'; c++) if (this.Any(BinaryOperatorKind.Equal, (T)(object)c.ToString())) return tc.ToConstantValue((T)(object)c.ToString()); } // If that doesn't work, choose from a sufficiently large random selection of values. // Since this is an excluded set, they cannot all be excluded var candidates = tc.RandomValues(_membersIncludedOrExcluded.Count + 1, new Random(0), _membersIncludedOrExcluded.Count + 1); foreach (var value in candidates) { if (this.Any(BinaryOperatorKind.Equal, value)) return tc.ToConstantValue(value); } throw ExceptionUtilities.Unreachable; } } public bool Any(BinaryOperatorKind relation, T value) { switch (relation) { case BinaryOperatorKind.Equal: return _included == _membersIncludedOrExcluded.Contains(value); default: return true; // supported for error recovery } } bool IValueSet.Any(BinaryOperatorKind relation, ConstantValue value) => value.IsBad || Any(relation, default(TTC).FromConstantValue(value)); public bool All(BinaryOperatorKind relation, T value) { switch (relation) { case BinaryOperatorKind.Equal: if (!_included) return false; switch (_membersIncludedOrExcluded.Count) { case 0: return true; case 1: return _membersIncludedOrExcluded.Contains(value); default: return false; } default: return false; // supported for error recovery } } bool IValueSet.All(BinaryOperatorKind relation, ConstantValue value) => !value.IsBad && All(relation, default(TTC).FromConstantValue(value)); public IValueSet<T> Complement() => new EnumeratedValueSet<T, TTC>(!_included, _membersIncludedOrExcluded); IValueSet IValueSet.Complement() => this.Complement(); public IValueSet<T> Intersect(IValueSet<T> o) { if (this == o) return this; var other = (EnumeratedValueSet<T, TTC>)o; var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this); switch (larger._included, smaller._included) { case (true, true): return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded)); case (true, false): return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded)); case (false, false): return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded)); case (false, true): return new EnumeratedValueSet<T, TTC>(true, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded)); } } IValueSet IValueSet.Intersect(IValueSet other) => Intersect((IValueSet<T>)other); public IValueSet<T> Union(IValueSet<T> o) { if (this == o) return this; var other = (EnumeratedValueSet<T, TTC>)o; var (larger, smaller) = (this._membersIncludedOrExcluded.Count > other._membersIncludedOrExcluded.Count) ? (this, other) : (other, this); switch (larger._included, smaller._included) { case (false, false): return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Intersect(smaller._membersIncludedOrExcluded)); case (false, true): return new EnumeratedValueSet<T, TTC>(false, larger._membersIncludedOrExcluded.Except(smaller._membersIncludedOrExcluded)); case (true, true): return new EnumeratedValueSet<T, TTC>(true, larger._membersIncludedOrExcluded.Union(smaller._membersIncludedOrExcluded)); case (true, false): return new EnumeratedValueSet<T, TTC>(false, smaller._membersIncludedOrExcluded.Except(larger._membersIncludedOrExcluded)); } } IValueSet IValueSet.Union(IValueSet other) => Union((IValueSet<T>)other); public override bool Equals(object? obj) => obj is EnumeratedValueSet<T, TTC> other && this._included == other._included && this._membersIncludedOrExcluded.SetEquals(other._membersIncludedOrExcluded); public override int GetHashCode() => Hash.Combine(this._included.GetHashCode(), this._membersIncludedOrExcluded.GetHashCode()); public override string ToString() => $"{(this._included ? "" : "~")}{{{string.Join(",", _membersIncludedOrExcluded.Select(o => o.ToString()))}{"}"}"; } } }
{'content_hash': '1cc449c6dd942427222248ce762c2d95', 'timestamp': '', 'source': 'github', 'line_count': 163, 'max_line_length': 162, 'avg_line_length': 52.079754601226995, 'alnum_prop': 0.5682648132877842, 'repo_name': 'genlu/roslyn', 'id': '1a6405efeb8ad8dccd2e4c3781483b98762e7285', 'size': '8491', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.EnumeratedValueSet.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '257760'}, {'name': 'Batchfile', 'bytes': '9059'}, {'name': 'C#', 'bytes': '139228314'}, {'name': 'C++', 'bytes': '5602'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2450'}, {'name': 'F#', 'bytes': '549'}, {'name': 'PowerShell', 'bytes': '242675'}, {'name': 'Shell', 'bytes': '92965'}, {'name': 'Visual Basic .NET', 'bytes': '71735255'}]}
package org.kie.workbench.common.stunner.bpmn.workitem.service; import org.jboss.errai.bus.server.annotations.Remote; import org.kie.workbench.common.stunner.core.diagram.Metadata; @Remote public interface WorkItemDefinitionLookupService extends WorkItemDefinitionService<Metadata> { }
{'content_hash': '1db9c985a71b95963d7a6402d0214d84', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 63, 'avg_line_length': 24.916666666666668, 'alnum_prop': 0.8160535117056856, 'repo_name': 'droolsjbpm/kie-wb-common', 'id': 'bab095f54e282e9ac42bee184b427d27713a4ed0', 'size': '918', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'kie-wb-common-stunner/kie-wb-common-stunner-sets/kie-wb-common-stunner-bpmn/kie-wb-common-stunner-bpmn-api/src/main/java/org/kie/workbench/common/stunner/bpmn/workitem/service/WorkItemDefinitionLookupService.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '38549'}, {'name': 'FreeMarker', 'bytes': '37490'}, {'name': 'GAP', 'bytes': '86275'}, {'name': 'HTML', 'bytes': '127323'}, {'name': 'Java', 'bytes': '19056067'}]}
package org.wso2.carbon.registry.security.vault.ui; import org.apache.axis2.AxisFault; import org.apache.axis2.client.Options; import org.apache.axis2.client.ServiceClient; import org.apache.axis2.context.ConfigurationContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.CarbonConstants; import org.wso2.carbon.registry.common.ui.UIConstants; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceRegistryExceptionException; import org.wso2.carbon.registry.properties.stub.PropertiesAdminServiceStub; import org.wso2.carbon.registry.properties.stub.beans.xsd.PropertiesBean; import org.wso2.carbon.registry.properties.stub.beans.xsd.RetentionBean; import org.wso2.carbon.registry.properties.stub.utils.xsd.Property; import org.wso2.carbon.registry.security.stub.RegistrySecurityAdminServiceCryptoExceptionException; import org.wso2.carbon.registry.security.stub.RegistrySecurityAdminServiceStub; import org.wso2.carbon.registry.security.vault.cipher.tool.CipherTool; import org.wso2.carbon.registry.security.vault.util.SecureVaultConstants; import org.wso2.carbon.ui.CarbonUIUtil; import org.wso2.carbon.utils.ServerConstants; import java.rmi.RemoteException; import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class PropertiesServiceClient { public static final String NAME = "name"; public static final String VALUE = "value"; public static final String PATH = "path"; private static final Log log = LogFactory.getLog(PropertiesServiceClient.class); private PropertiesAdminServiceStub propertAdminServicestub; private RegistrySecurityAdminServiceStub securityAdminServiceStub; private HttpSession session; private CipherTool cipherTool; public PropertiesServiceClient(ServletConfig config, HttpSession session) throws RegistryException { this.session = session; String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_COOKIE); String backendServerURL = CarbonUIUtil.getServerURL(config.getServletContext(), this.session); ConfigurationContext configContext = (ConfigurationContext) config.getServletContext() .getAttribute(CarbonConstants.CONFIGURATION_CONTEXT); String propertyEPR = backendServerURL + "PropertiesAdminService"; String registrySecurityEPR = backendServerURL + "RegistrySecurityAdminService"; try { propertAdminServicestub = new PropertiesAdminServiceStub(configContext, propertyEPR); ServiceClient client = propertAdminServicestub._getServiceClient(); Options option = client.getOptions(); option.setManageSession(true); option.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); // securityAdminServiceStub = new RegistrySecurityAdminServiceStub(configContext, registrySecurityEPR); ServiceClient securityclient = propertAdminServicestub._getServiceClient(); Options securityoption = securityclient.getOptions(); securityoption.setManageSession(true); securityoption.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, cookie); cipherTool = new CipherTool(securityAdminServiceStub); } catch (AxisFault axisFault) { String msg = "Failed to initiate resource service client. " + axisFault.getMessage(); log.error(msg, axisFault); throw new RegistryException(msg, axisFault); } } /** * Retrieving the length of the properties in selected registry resource * * @return * @throws RegistryException */ public int getPropertiesLenght() throws RegistryException { String path = SecureVaultConstants.ENCRYPTED_PROPERTY_CONFIG_REGISTRY_PATH; PropertiesBean bean = null; try { bean = propertAdminServicestub.getProperties(path, "no"); } catch (Exception axisFault) { String msg = "Failed to initiate resource service client. " + axisFault.getMessage(); log.error(msg, axisFault); throw new RegistryException(msg, axisFault); } return bean.getSysProperties().length; } public PropertiesBean getProperties(HttpServletRequest request, int pageNumber) throws Exception { String path = SecureVaultConstants.ENCRYPTED_PROPERTY_CONFIG_REGISTRY_PATH; Boolean view = (Boolean) request.getSession().getAttribute(UIConstants.SHOW_SYSPROPS_ATTR); String viewProps; if (view != null) { if (view.booleanValue()) { viewProps = "yes"; } else { viewProps = "no"; } } else { viewProps = "no"; } PropertiesBean bean = null; bean = propertAdminServicestub.getProperties(path, viewProps); int itemPerPage = (int) (RegistryConstants.ITEMS_PER_PAGE * 1.5); int start = (int) ((pageNumber) * itemPerPage); if (start >= 0 && bean.getSysProperties() != null && bean.getSysProperties().length > 0) { int length = start > 0 ? ((bean.getSysProperties().length - start) - 1) : bean.getSysProperties().length; if (length > itemPerPage) { length = itemPerPage; } String[] prams = new String[length > 0 ? length : 1]; for (int i = 0; i <= itemPerPage - 1; i++) { if (i < prams.length) { prams[i] = bean.getSysProperties()[i + start]; } } bean.setSysProperties(prams); } if (bean == null) { return null; } if (bean.getLifecycleProperties() == null) { bean.setLifecycleProperties(new String[0]); } if (bean.getSysProperties() == null) { bean.setSysProperties(new String[0]); } if (bean.getValidationProperties() == null) { bean.setValidationProperties(new String[0]); } if (bean.getProperties() == null) { bean.setProperties(new Property[0]); } return bean; } /** * Method to add a property, if there already exist a property with the same name, this * will add the value to the existing property name. (So please remove the old property with * the same name before calling this method). * * @param request Http request with parameters. * @throws RegistryException throws if there is an error. */ public void setProperty(HttpServletRequest request) throws RegistryException { String path = SecureVaultConstants.ENCRYPTED_PROPERTY_CONFIG_REGISTRY_PATH; String name = (String) Utils.getParameter(request, NAME); String value = (String) Utils.getParameter(request, VALUE); try { // do the encryption.. String encrypted = cipherTool.doEncryption(value); propertAdminServicestub.setProperty(path, name, encrypted); } catch (RemoteException | PropertiesAdminServiceRegistryExceptionException e) { throw new RegistryException("Failed to add property" + name + "to resource at path " + path, e); } catch (RegistrySecurityAdminServiceCryptoExceptionException e) { throw new RegistryException("Failed to encrypt the property " + name, e); } } /** * Method to update a property (This removes the old property with the oldName) * * @param request Http request with parameters. * @throws RegistryException throws if there is an error. */ public void updateProperty(HttpServletRequest request) throws RegistryException { String path = SecureVaultConstants.ENCRYPTED_PROPERTY_CONFIG_REGISTRY_PATH; String name = (String) Utils.getParameter(request, NAME); String value = (String) Utils.getParameter(request, VALUE); String oldName = (String) Utils.getParameter(request, "oldName"); try { // do the encryption.. String encrypted = cipherTool.doEncryption(value); propertAdminServicestub.updateProperty(path, name, encrypted, oldName); } catch (RemoteException | PropertiesAdminServiceRegistryExceptionException e) { throw new RegistryException("Failed to update the property" + name + "at resource path " + path, e); } catch (RegistrySecurityAdminServiceCryptoExceptionException e) { throw new RegistryException("Failed to encrypt the property " + name, e); } } /** * Method to remove property from a resource. * * @param request Http request with parameters. * @throws RegistryException throws if there is an error. */ public void removeProperty(HttpServletRequest request) throws RegistryException { String path = (String) Utils.getParameter(request, PATH); String name = (String) Utils.getParameter(request, NAME); try { propertAdminServicestub.removeProperty(path, name); } catch (RemoteException | PropertiesAdminServiceRegistryExceptionException e) { throw new RegistryException("Failed to remove the property" + name + "at resource path " + path, e); } } /** * Method to set resource retention properties of a resource. * * @param request Http request with parameters. * @throws RegistryException throws if there is an error */ public boolean setRetentionProperties(HttpServletRequest request) throws RegistryException { String path = request.getParameter(PATH); try { RetentionBean bean; String fromDate = request.getParameter("fromDate"); if (fromDate == null || "".equals(fromDate)) { bean = null; } else { bean = new RetentionBean(); bean.setFromDate(fromDate); bean.setToDate(request.getParameter("toDate")); String lockedOperationsParam = request.getParameter("lockedOperations"); bean.setWriteLocked(lockedOperationsParam.contains("write")); bean.setDeleteLocked(lockedOperationsParam.contains("delete")); } propertAdminServicestub.setRetentionProperties(path, bean); } catch (RemoteException | PropertiesAdminServiceRegistryExceptionException e) { throw new RegistryException("Failed to add retention to resource at path" + path, e); } return true; } /** * Method to get resource retention properties of a given resource. * * @param request Http request with parameters. * @throws RegistryException */ public RetentionBean getRetentionProperties(HttpServletRequest request) throws RegistryException { String path = request.getParameter(PATH); try { return propertAdminServicestub.getRetentionProperties(request.getParameter(PATH)); } catch (Exception e) { throw new RegistryException("Could not retrieve retention details at path" + path, e); } } }
{'content_hash': '97ef7ed298a385fad549946ed1b8de8d', 'timestamp': '', 'source': 'github', 'line_count': 266, 'max_line_length': 121, 'avg_line_length': 41.64661654135338, 'alnum_prop': 0.6962448095324065, 'repo_name': 'wso2/carbon-registry', 'id': '66dd5a719c7a13972783769310b0cda60e138a93', 'size': '11755', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'components/registry/org.wso2.carbon.registry.security.ui/src/main/java/org/wso2/carbon/registry/security/vault/ui/PropertiesServiceClient.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '62597'}, {'name': 'CSS', 'bytes': '62539'}, {'name': 'HTML', 'bytes': '46318'}, {'name': 'Java', 'bytes': '6126317'}, {'name': 'JavaScript', 'bytes': '333055'}, {'name': 'PLSQL', 'bytes': '186568'}, {'name': 'SQLPL', 'bytes': '50286'}, {'name': 'Shell', 'bytes': '70140'}, {'name': 'TSQL', 'bytes': '62416'}, {'name': 'XSLT', 'bytes': '78182'}]}
/* * $Id: Dummy.cpp 471747 2006-11-06 14:31:56Z amassari $ */ #include <xercesc/sax/AttributeList.hpp> #include <xercesc/sax/DocumentHandler.hpp> #include <xercesc/sax/DTDHandler.hpp> #include <xercesc/sax/EntityResolver.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/sax/HandlerBase.hpp> #include <xercesc/sax/InputSource.hpp> #include <xercesc/sax/Locator.hpp> #include <xercesc/sax/Parser.hpp> #include <xercesc/sax/SAXException.hpp> #include <xercesc/sax/SAXParseException.hpp> XERCES_CPP_NAMESPACE_BEGIN XERCES_CPP_NAMESPACE_END
{'content_hash': 'ce7f03564a23990b51a2644dded080df', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 56, 'avg_line_length': 26.523809523809526, 'alnum_prop': 0.7737881508078994, 'repo_name': 'JLUCPGROUP/cp', 'id': '7da384f2ea4c54d318b8ce99e37faecf596bcdcf', 'size': '1361', 'binary': False, 'copies': '53', 'ref': 'refs/heads/master', 'path': 'cp/Xercesc/include/xercesc/sax/Dummy.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '198775'}, {'name': 'C++', 'bytes': '9960662'}, {'name': 'Makefile', 'bytes': '2272'}]}
#include "LIEF/config.h" #include "logging.hpp" #include "LIEF/ART/json.hpp" #ifdef LIEF_JSON_SUPPORT #include "ART/json_internal.hpp" #endif #include "LIEF/ART.hpp" namespace LIEF { namespace ART { std::string to_json(const Object& v) { #ifdef LIEF_JSON_SUPPORT JsonVisitor visitor; v.accept(visitor); return visitor.get().dump(); #else LIEF_WARN("JSON support is not enabled"); return ""; #endif } } // namespace VDEX } // namespace LIEF
{'content_hash': 'eb49de05910f5a656e90eae8358771cb', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 43, 'avg_line_length': 16.88888888888889, 'alnum_prop': 0.6995614035087719, 'repo_name': 'lief-project/LIEF', 'id': 'e56ad073d1c8e0a0584c466fe6b46268a21ae0bf', 'size': '1087', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ART/json_api.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '115380'}, {'name': 'C++', 'bytes': '5516502'}, {'name': 'CMake', 'bytes': '185657'}, {'name': 'Dockerfile', 'bytes': '994'}, {'name': 'Objective-C', 'bytes': '736'}, {'name': 'Python', 'bytes': '305524'}, {'name': 'Shell', 'bytes': '21907'}, {'name': 'SourcePawn', 'bytes': '130615'}]}
class EmptyView < UIView end class AnotherView < EmptyView end
{'content_hash': 'a2209874fd53015a90a38cdee1a5c885', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 29, 'avg_line_length': 12.6, 'alnum_prop': 0.8095238095238095, 'repo_name': 'rubymotion/ib', 'id': '3e521fafb0896ceaef1100cedd5fba76f4cd7dc8', 'size': '63', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'spec/fixtures/common/empty_view.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '1953'}, {'name': 'Ruby', 'bytes': '40105'}]}
define(["thenjs", "excel-builder", "downloadify", "bootstrap-icheck"], function(then, excelBuilder, downloader) { return [["orderCtrl", ["$scope", "$rootScope", "$remote", "$modal", "$scopeData", "$config", "$constants", "$dict", function($scope, $rootScope, $remote, $modal, $scopeData, $config, $constants, $dict) { //初始化页面数据域数据 $scope.initPage = function(){ $scope.currentPage = 1; $scope.maxSize = 5; $scope.pageSize = 20; $scope._Query = {} $scope._Query.begindate = new Date().format("yyyyMMdd"); $scope._Query.enddate = new Date().format("yyyyMMdd"); $scope.TimeList = [ {key:1, value: '1天'}, {key:3, value: '3天'}, {key:7, value: '7天'}, {key:30, value: '30天'}, {key:90, value: '90天'}, {key:180, value: '180天'}, {key:365, value: '365天'} ]; $scope.OrderStatusList = [ {key: 0, value: "订单生成"}, {key: 1, value: "订单入仓"}, {key: 2, value: "订单出货"}, {key: 3, value: "国际物流"}, {key: 4, value: "清关中"}, {key: 9, value: "完成"}, {key: 99, value: "系统提示"} ] $scope.BatchPathStatusList = [ {key: 2, value: "订单出货"}, {key: 3, value: "国际物流"}, {key: 4, value: "清关中"}, {key: 9, value: "完成"} ] var billArr = $scope.initOptions("TypeBill"); $scope.TypeBillList = billArr[0]; $scope.typeBill = $scope.TypeBillList[0] $scope.flagFix = 0 $scope.flagProtect = 0 $scope.flagCollect = 0 } //重置查询条件 $scope.resetQuery = function(){ $rootScope.Query = {}; } //关闭按钮触发时初始化页面 $scope.rePageIndex = function(){ $scope.showModule(0); $scope.initPage(); $scope.resetQuery(); } //初始化查询条件 $scope.initPageQuery = function(){ var postData = {}; postData.createrSchema = $rootScope.backInfo._id postData.id = $scope.Query.id||null postData.idBatch = $scope.Query.idBatch||null postData.idAirline = $scope.Query.idAirline||null postData.creater = $scope.Query.creater||null postData.receiveName = $scope.Query.receiveName||null if($scope.Query.status != null){ postData.status = $scope.Query.status.key } if($scope.Query.time){ if($scope.Query.time == -1){ var begin = $scope.checkDate($scope._Query.begindate); var end = $scope.checkDate($scope._Query.enddate); if(!begin || !end){ var msg = {text:$constants.MESSAGE_DATE_FORMAT_ERROR}; $scope.showMessage(msg); return false; } postData.time = -1; postData.timeBegin = begin; postData.timeEnd = end; }else{ postData.time = $scope.Query.time.key } } return postData; } $scope.selectCancel = function(){ $scope.selectedOrder = null; } $scope.listOrder = function(init){ $scope.selectCancel(); var postData = $scope.initPageQuery(); if(!postData){ return } $remote.post("/order/count", postData, function(data){ $scope.totalItems = data; if(init){ postData.currentPage = 1; postData.pageSize = 20; }else{ postData.currentPage = $scope.currentPage; postData.pageSize = $scope.pageSize; } $remote.post("/order/list", postData, function(data){ $scope.OrderList = data; }) }); } $scope.pageChanged = function() { $scope.listOrder(); }; $scope.selectOrder = function(item, index){ if($scope.selectedOrder){ if($scope.selectedOrder.index == index){ $scope.selectedOrder = null; }else{ $scope.selectedOrder = item; $scope.selectedOrder.index = index; } }else{ $scope.selectedOrder = item; $scope.selectedOrder.index = index; } } $scope.detailOrder = function(){ if($scope.selectedOrder){ var postData = { id: $scope.selectedOrder.id } $scope.selectCancel(); $remote.post("/order/detail", postData, function(data){ $scope.Order = data; var result = $scope.initOptions("TypeBill", $scope.Order.typeBill); $scope.EBillTypeList = result[0]; $scope.Order.typeBill = $scope.EBillTypeList[result[1]]; $scope.showModule(2) $scope.$apply() }); } } //删除指定批次数据 $scope.delBatch = function(batchId){ var postData = {batchId : batchId}; var msg = {type:$constants.MESSAGE_DIALOG_TYPE_CONF, text: batchId + "-" + $constants.MESSAGE_CONF_DEL_BATCH, confCallback:function(){ $remote.post("/order/delBatch", postData, function(data){ $scope.listOrder(true); $scope.rePageIndex(); $scope.selectedOrder = null; }); }}; $scope.showMessage(msg); } $scope.newOrder = function(){ if($scope.checkForm($scope.addForm)){ var postData = { id: $scope.id, typeBill: $scope.typeBill.key, name: $scope.name, remark: $scope.remark, creater: $rootScope.backInfo.loginId || "", createrSchema: $rootScope.backInfo._id || "", goods: $scope.goods || "", brand: $scope.brand || "", total: $scope.total || 0, idNo: $scope.idNo || "", sendName: $scope.sendName || "", sendAddress: $scope.sendAddress || "", sendPhone: $scope.sendPhone || "", receiveName: $scope.receiveName || "", receiveAddress: $scope.receiveAddress || "", receivePhone: $scope.receivePhone || "", receiveZipCode: $scope.receiveZipCode || "", worldTransId: $scope.worldTransId || "", worldTransName: $scope.worldTransName || "", chinaTransId: $scope.chinaTransId || "", chinaTransName: $scope.chinaTransName || "", flagFix: $scope.flagFix||0, flagProtect: $scope.flagFix||0, amtPackage: $scope.amtPackage||0, flagCollect: $scope.flagFix||0, weight: $scope.weight||0 } $remote.post("/order/add", postData, function(data){ $scope.listOrder(true); $scope.rePageIndex(); }); } } $scope.editOrder = function(){ if($scope.checkForm($scope.editForm)){ var postData = { _id: $scope.Order._id, typeBill: $scope.Order.typeBill.key, name: $scope.Order.name, remark: $scope.Order.remark, goods: $scope.Order.goods || "", brand: $scope.Order.brand || "", total: $scope.Order.total || 0, idNo: $scope.Order.idNo || "", sendName: $scope.Order.sendName || "", sendAddress: $scope.Order.sendAddress || "", sendPhone: $scope.Order.sendPhone || "", weight: $scope.Order.weight||0, receiveName: $scope.Order.receiveName || "", receiveAddress: $scope.Order.receiveAddress || "", receivePhone: $scope.Order.receivePhone || "", receiveZipCode: $scope.Order.receiveZipCode || "", worldTransId: $scope.Order.worldTransId || "", worldTransName: $scope.Order.worldTransName || "", chinaTransId: $scope.Order.chinaTransId || "", chinaTransName: $scope.Order.chinaTransName || "", flagFix: $scope.Order.flagFix||0, flagProtect: $scope.Order.flagFix||0, amtPackage: $scope.Order.amtPackage||0, flagCollect: $scope.Order.flagFix||0 } $remote.post("/order/edit", postData, function(data){ $scope.listOrder(true); $scope.rePageIndex(); }); } } //删除指定订单信息 $scope.deleteOrder = function(){ if($scope.selectedOrder){ //若订单状态"已出库"状态,则不允许删除 if($scope.selectedOrder.status != 0 && $scope.selectedOrder.status != 1){ var msg = {text:"订单状态不是【订单生成】或【订单入仓】状态,不能删除"}; $scope.showMessage(msg); return } if($scope.selectedOrder.creater != $scope.backInfo.loginId){ var msg = {text:"订单创建者非本人,不能删除"}; $scope.showMessage(msg); return } var postData = { id: $scope.selectedOrder._id } $scope.selectCancel(); var msg = {type:$constants.MESSAGE_DIALOG_TYPE_CONF, text:$constants.MESSAGE_CONF_DEL_ORDER, confCallback:function(){ $remote.post("/order/delete", postData, function(data){ $scope.listOrder(true); $scope.rePageIndex(); $scope.selectedOrder = null; }); }}; $scope.showMessage(msg); } } //批量打印面单 $scope.batchPrint = function(){ var postData = $scope.initPageQuery(); //先进行打印数量查询,确保一次性打印笔数过多造成前端假死或崩溃 $remote.post("/order/count", postData, function(data){ if(data && data > 200){ var msg = {text: $constants.MESSAGE_PRINT_BATCH_LIMITED} $scope.showMessage(msg); return; } $remote.post("/order/list", postData, function(data){ var iframe = document.getElementById("printPage"); iframe.contentWindow.focus(); iframe.contentWindow.doSettingValues(data); iframe.contentWindow.print(); }) }) } //单个打印面单界面 $scope.printOrder = function(){ if($scope.selectedOrder){ var postData = { id: $scope.selectedOrder.id } $scope.selectCancel(); $remote.post("/order/detail", postData, function(data){ var orders = []; orders.push(data) var iframe = document.getElementById("printPage"); iframe.contentWindow.focus(); iframe.contentWindow.doSettingValues(orders); iframe.contentWindow.print(); //console.log(iframe.contentWindow.Order); }); } } $scope.rePageIndex(); $scope.listOrder(true); /** * 批量导入相关处理方法 */ var orderTemplate = { _rowBegin: 2, header:[ {id: "A", cn:"面单号", name: "id", style:"empty"}, {id: "B", cn:"申报类型", name: "typeBill", style:"option", list:"A类,B类,C类,D类"}, {id: "C", cn:"渠道", name: "name", style:"empty"}, {id: "D", cn:"内件详情", name: "goods", style:"empty"}, {id: "E", cn:"品牌", name: "brand", style:"empty"}, {id: "F", cn:"物品总数", name: "total", style:"number"}, {id: "G", cn:"收件人", name: "receiveName", style:"empty"}, {id: "H", cn:"收件省份", name: "receiveProvince", style:"empty"}, {id: "I", cn:"收件城市", name: "receiveCity", style:"empty"}, {id: "J", cn:"收件地区", name: "receiveArea", style:"empty"}, {id: "K", cn:"收件地址", name: "receiveAddress", style:"empty"}, {id: "L", cn:"收件电话", name: "receivePhone", style:"number"}, {id: "M", cn:"收件邮编", name: "receiveZipCode", style:"number"}, {id: "N", cn:"寄件人", name: "sendName", style:"empty"}, {id: "O", cn:"寄件地址", name: "sendAddress", style:"empty"}, {id: "P", cn:"寄件电话", name: "sendPhone", style:"number"}, {id: "Q", cn:"清关身份证", name: "idNo", style:"empty"}, {id: "R", cn:"备注", name: "remark"}, {id: "S", cn:"国际物流商", name: "worldTransName", style:"empty"}, {id: "T", cn:"国际物流单号", name: "worldTransId", style:"empty"}, {id: "U", cn:"是否加固", name: "flagFix", style:"option", list:"0,1"}, {id: "V", cn:"是否保险", name: "flagProtect", style:"option", list:"0,1"}, {id: "W", cn:"申报价值", name: "amtPackage", style:"number"}, {id: "X", cn:"是否代收", name: "flagCollect", style:"option", list:"0,1"} ] } $scope.$watch("files", function(){ if($scope.files){ $scope.ProgressBar = null; $scope._excelErr = null; $scope.ordersData = null; $scope.httpOrders = null; $scope.convert(); } }) function checkStyle(header, value){ var style = header.style; var cnName = header.cn; if(style){ if(style == "empty" || style == "id"){ if(!value || value.length == 0){ return cnName + "不能为空"; } }else if(style == "option"){ var lists = header.list; if(!value || lists.indexOf(value) == -1){ return cnName + "取值范围只能为:" + lists; } }else if(style == "number"){ var regex = /^[0-9]+.?[0-9]*$/; if (!value || !regex.test(value)){ return cnName + "必须为数字类型"; } } } return null } var DEFAULT_ERR = "批量导入文档内容存在错误,请参照提示修复完成后再行提交上传"; $scope.convert = function(){ var files = $scope.files; var i,f; for (i = 0, f = files[i]; i != files.length; ++i) { var reader = new FileReader(); var name = f.name; reader.onload = function(e) { var data = e.target.result; var workbook = window.xlsx.read(data, {type: 'binary'}); var reg = /^([a-zA-Z]*)(\d*)$/; var sheet_name_list = workbook.SheetNames; if(sheet_name_list.length != 1){ $scope._excelErr = "使用的批量数据模板不符合上传模板格式,请使用正确模板进行数据操作" $scope.$apply(); return; } var oData,oIds,oMap,oPureData; sheet_name_list.forEach(function(sheet_name, index) { var worksheet = workbook.Sheets[sheet_name]; var range = worksheet['!ref'].split(':'); // 获取sheet表格的范围 var maxRow,maxCol; var template; if(index == 0){ template = orderTemplate; } var result = reg.exec(range[1]); maxRow = parseInt(result[2]); maxCol = result[1]; var startRow = template._rowBegin; var list = []; var pureList = []; var ids = []; var idMap = {}; for (var i = startRow; i <= maxRow; i++) { var data = {}; var pureData = {}; for (var j = 0; j < template.header.length; j++) { var header = template.header[j]; var cell = header.id + i; var value = worksheet[cell] ? (worksheet[cell].w + '').trim() : ''; var item = {}; item.error = checkStyle(header, value); if(item.error && !$scope._excelErr){ $scope._excelErr = DEFAULT_ERR; } if(header.id == "B"){ value = $dict.get("TypeBillName")[value]; } item.value = value; data[header.name] = item; pureData[header.name] = value; } list.push(data); pureList.push(pureData); } if(index == 0){ oIds = ids; oMap = idMap; oData = list; oPureData = pureList; } }); $scope.ordersData = oData; $scope.httpOrders = oPureData; $scope.$apply(); }; reader.readAsBinaryString(f); } } $scope.submitBatch = function(){ if($scope.httpOrders){ var postData = { creater: $scope.backInfo.loginId, createrSchema: $scope.backInfo._id, orders: $scope.httpOrders } $remote.post("/order/batchImport", postData, function(data){ $scope.listOrder(true); $scope.rePageIndex(); }); } } //批量导出数据文件 $scope.exports = function(){ var postData = $scope.initPageQuery(); //先进行打印数量查询,确保一次性导出数据不超过阈值 $remote.post("/order/count", postData, function(data){ if(data && data > 200){ var msg = {text: $constants.OVER_MAX_EXPORTS_ROWS} $scope.showMessage(msg); return; } $remote.post("/order/list", postData, function(data){ var srcData = data var exportedExcel = excelBuilder.createWorkbook(); var stylesheet = exportedExcel.getStyleSheet(); var boldDXF = stylesheet.createDifferentialStyle({ font: { italic: true } }); //Excel表头样式 var header = stylesheet.createFormat({ font: { size: 10, bold: true, color: '000000' }, fill: { type: 'pattern', patternType: 'solid', fgColor: '83c6e8' } }); //Excel数据样式 var border = "A3A3A3"; var bodyer = stylesheet.createFormat({ font: { size: 10, bold: false, color: '3A3A3A' }, fill: { type: 'pattern', patternType: 'solid' }, border: { bottom: {color: border, style: 'thin'}, top: {color: border, style: 'thin'}, left: {color: border, style: 'thin'}, right: {color: border, style: 'thin'} } }); var albumList = exportedExcel.createWorksheet({name: '出库运单'}); albumList.setRowInstructions(1, {height: 30, style: boldDXF.id}); //数据体,预先准备数据头 var excelData = [ [ {value:'序号', metadata: {style: header.id}}, {value:'运单编号', metadata: {style: header.id}}, {value:"渠道", metadata: {style: header.id}}, {value:"内件详情", metadata: {style: header.id}}, {value:"品牌", metadata: {style: header.id}}, {value:"物品总数", metadata: {style: header.id}}, {value:'发件人', metadata: {style: header.id}}, {value:'发件人地址', metadata: {style: header.id}}, {value:'发件人电话', metadata: {style: header.id}}, {value:'收件人', metadata: {style: header.id}}, {value:'收件人电话', metadata: {style: header.id}}, {value:'收件人邮编', metadata: {style: header.id}}, {value:'省份', metadata: {style: header.id}}, {value:'城市', metadata: {style: header.id}}, {value:'地区', metadata: {style: header.id}}, {value:'收件人地址', metadata: {style: header.id}}, {value:'创建人', metadata: {style: header.id}}, {value:'包裹重量', metadata: {style: header.id}}, {value:'证件号码', metadata: {style: header.id}}, {value:'是否加固', metadata: {style: header.id}}, {value:'是否保险', metadata: {style: header.id}}, {value:"申报价值", metadata: {style: header.id}}, {value:"是否代收", metadata: {style: header.id}} ] ]; var seq = 1; srcData.forEach(function(order){ var row = []; var seqCol = {metadata: {style: bodyer.id}}; seqCol.value = seq++; row.push(seqCol); row.push({value: "" + order.id||"", metadata: {style: bodyer.id}}); row.push({value: order.name||"", metadata: {style: bodyer.id}}); row.push({value: order.goods||"", metadata: {style: bodyer.id}}); row.push({value: order.brand||"", metadata: {style: bodyer.id}}); row.push({value: order.total||"", metadata: {style: bodyer.id}}); row.push({value: order.sendName||"", metadata: {style: bodyer.id}}); row.push({value: order.sendAddress||"", metadata: {style: bodyer.id}}); row.push({value: order.sendPhone||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveName||"", metadata: {style: bodyer.id}}); row.push({value: order.receivePhone||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveZipCode||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveProvince||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveCity||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveArea||"", metadata: {style: bodyer.id}}); row.push({value: order.receiveAddress||"", metadata: {style: bodyer.id}}); row.push({value: order.creater||"", metadata: {style: bodyer.id}}); row.push({value: order.weight||0, metadata: {style: bodyer.id}}); row.push({value: order.idNo||"", metadata: {style: bodyer.id}}); row.push({value: order.flagFix||0, metadata: {style: bodyer.id}}); row.push({value: order.flagProtect||0, metadata: {style: bodyer.id}}); row.push({value: order.amtPackage||0, metadata: {style: bodyer.id}}); row.push({value: order.flagCollect||0, metadata: {style: bodyer.id}}); excelData.push(row); }); albumList.setData(excelData); //<-- Here's the important part exportedExcel.addWorksheet(albumList); var data = excelBuilder.createFile(exportedExcel); var file = new Date().format("yyyyMMdd") + '_' + $constants.NAME_EXPORT_ORDER_EXCEL; $scope.download(data, file); }) }) } $scope.download = function(data, fileName){ Downloadify.create('downloader',{ filename: function(){ return fileName; }, data: data, onComplete: function(){ $("#downloader").hide(); }, //onCancel: function(){ alert('You have cancelled the saving of this file.'); }, onError: function(){ alert("文件保存失败!"); }, swf: 'js/dev/lib/downloadify/media/downloadify.swf', downloadImage: 'js/dev/lib/downloadify/images/excel2.png', width: 30, dataType: 'base64', height: 37.5, transparent: true, append: false }); $("#downloader").show(); } //进入订单轨迹更新界面 $scope.pathOrder = function(){ $scope.selectedOrder.paths.forEach(function(each){ var result = $scope.initOptions("OrderStatus", each.status); each.status = $scope.OrderStatusList[result[1]]; //each.status = $scope.OrderStatusList[each.status]; }) $scope.showModule(4) } //订单轨迹更新 $scope.addPath = function(){ var data = { updater:$rootScope.backInfo.loginId, time: Date.now(), status: $scope.OrderStatusList[3] } if(!$scope.selectedOrder.paths){ $scope.selectedOrder.paths = [] } $scope.selectedOrder.paths.push(data); } $scope.removePath = function(index){ $scope.selectedOrder.paths.splice(index,1); } $scope.pathUpdate = function(){ $scope.selectedOrder.paths.forEach(function(each){ each.status = each.status.key; }) var postData = { _id: $scope.selectedOrder._id, //status: $scope.selectedOrder.status.key, paths: $scope.selectedOrder.paths } $remote.post("/order/pathUpdate", postData, function(data){ var msg = {text:$constants.MESSAGE_ORDER_PATH_UPDATE_SUCCESS}; $scope.showMessage(msg); $scope.rePageIndex() }); } //进入订单轨迹更新界面 $scope.pathBatch = function(){ $scope.paths = [] $scope.status = $scope.BatchPathStatusList[0]; $scope.showModule(5) } //订单批次轨迹更新 $scope.addBatchPath = function(){ var data = { updater:$rootScope.backInfo.loginId, time: Date.now(), status: $scope.BatchPathStatusList[0] } if(!$scope.paths){ $scope.paths = [] } $scope.paths.push(data); } $scope.removeBatchPath = function(index){ $scope.paths.splice(index,1); } $scope.updateBatchPath = function(){ $scope.paths.forEach(function(each){ each.status = each.status.key; }) var postData = { idBatch: $scope.selectedOrder.idBatch, status: $scope.status.key, paths: $scope.paths } console.log(postData) $remote.post("/order/pathBatchUpdate", postData, function(data){ var msg = {text:$constants.MESSAGE_ORDER_PATH_UPDATE_SUCCESS}; $scope.showMessage(msg); $scope.rePageIndex() }); } }] ]]; });
{'content_hash': '28f0ee436ef4f2c93cb1ca35686c5cd7', 'timestamp': '', 'source': 'github', 'line_count': 734, 'max_line_length': 150, 'avg_line_length': 44.4141689373297, 'alnum_prop': 0.3911963190184049, 'repo_name': 'Annlover/express2.0', 'id': '06979d4a23a2372d0f47e911314ff67f9087713e', 'size': '33720', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web/js/dev/mCtrl/order/order.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '106'}, {'name': 'ActionScript', 'bytes': '25406'}, {'name': 'Batchfile', 'bytes': '250'}, {'name': 'C#', 'bytes': '1090'}, {'name': 'CSS', 'bytes': '564554'}, {'name': 'HTML', 'bytes': '808799'}, {'name': 'Java', 'bytes': '6124'}, {'name': 'JavaScript', 'bytes': '5282521'}, {'name': 'Makefile', 'bytes': '3216'}, {'name': 'PHP', 'bytes': '78774'}]}
<?php namespace Kunstmaan\PagePartBundle\Tests\unit\PagePartConfigurationReader; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\KernelInterface; class LocatingKernelStub implements KernelInterface { public function locateResource($name, $dir = null, $first = true) { list (, $path) = explode('/', $name, 2); return __DIR__ . DIRECTORY_SEPARATOR . $path; } public function serialize(){} public function unserialize($serialized){} public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true){} public function registerBundles(){} public function registerContainerConfiguration(LoaderInterface $loader){} public function boot(){} public function shutdown(){} public function getBundles(){} public function isClassInActiveBundle($class){} public function getBundle($name, $first = true){} public function getName(){} public function getEnvironment(){} public function isDebug(){} public function getRootDir(){} public function getContainer(){} public function getStartTime(){} public function getCacheDir(){} public function getLogDir(){} public function getCharset(){} }
{'content_hash': '2a8b089441214388ba80b0e69d5c220b', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 91, 'avg_line_length': 23.321428571428573, 'alnum_prop': 0.7059724349157733, 'repo_name': 'diskwriter/KunstmaanBundlesCMS', 'id': '7c91fa6e80dbe7c6c2393ff0d32e82615c03c61e', 'size': '1306', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Kunstmaan/PagePartBundle/Tests/unit/PagePartConfigurationReader/LocatingKernelStub.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '204635'}, {'name': 'Gherkin', 'bytes': '22178'}, {'name': 'HTML', 'bytes': '444119'}, {'name': 'Hack', 'bytes': '20'}, {'name': 'JavaScript', 'bytes': '543111'}, {'name': 'PHP', 'bytes': '3952710'}, {'name': 'Shell', 'bytes': '220'}]}
<?php /* |-------------------------------------------------------------------------- | Application & Route Filters |-------------------------------------------------------------------------- | | Below you will find the "before" and "after" events for the application | which may be used to do any work before or after a request into your | application. Here you may also register your custom route filters. | */ App::before(function($request) { // }); App::after(function($request, $response) { // }); /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. | */ Route::filter('auth', function() { if (Auth::guest()) return Redirect::guest('login'); }); Route::filter('auth.basic', function() { return Auth::basic(); }); /* |-------------------------------------------------------------------------- | Guest Filter |-------------------------------------------------------------------------- | | The "guest" filter is the counterpart of the authentication filters as | it simply checks that the current user is not logged in. A redirect | response will be issued if they are, which you may freely change. | */ Route::filter('guest', function() { if (Auth::check()) return Redirect::to('/'); }); /* |-------------------------------------------------------------------------- | CSRF Protection Filter |-------------------------------------------------------------------------- | | The CSRF filter is responsible for protecting your application against | cross-site request forgery attacks. If this special token in a user | session does not match the one given in this request, we'll bail. | */ Route::filter('csrf', function() { if (Session::token() != Input::get('_token')) { throw new Illuminate\Session\TokenMismatchException; } });
{'content_hash': '36dcb4be923affffd437c14d9c65ea62', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 75, 'avg_line_length': 27.1, 'alnum_prop': 0.48154981549815495, 'repo_name': 'silentninja/laravel', 'id': 'a099ba438374334f39f31b602f5406bee2559e85', 'size': '2168', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'jubilant-janey-03/app/filters.php', 'mode': '33188', 'license': 'mit', 'language': []}
package com.intellij.tests; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; public final class BootstrapTests { static { ExternalClasspathClassLoader.install(); } public static Test suite() throws Throwable { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String[] classes = System.getProperty("bootstrap.testcases").split(","); TestSuite suite = new TestSuite(); for (String s : classes) { final Class<?> aClass = Class.forName(s, true, cl); if (TestCase.class.isAssignableFrom(aClass)) { @SuppressWarnings("unchecked") final Class<? extends TestCase> testClass = (Class<? extends TestCase>)aClass; suite.addTestSuite(testClass); } else { suite.addTest((Test)aClass.getMethod("suite").invoke(null)); } } return suite; } }
{'content_hash': '111d6ab651d7932cfda3c24528f03ca3', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 117, 'avg_line_length': 30.448275862068964, 'alnum_prop': 0.6840317100792752, 'repo_name': 'Maccimo/intellij-community', 'id': 'fc650b5eb549fe6a7f361ef7cc83daf3ea53eb01', 'size': '1024', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'platform/testFramework/bootstrap/src/com/intellij/tests/BootstrapTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_activated="true" android:drawable="@color/item_activated" /> <item android:drawable="@color/item" /> </selector>
{'content_hash': 'ff209a0d52c2eb4cb279e7a256fede78', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 84, 'avg_line_length': 50.0, 'alnum_prop': 0.704, 'repo_name': 'Doist/RecyclerViewExtensions', 'id': 'a805dbf3509a5f4b7f356aaa1b7d5ca588ae2036', 'size': '250', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/src/main/res/drawable/item_background.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '160135'}, {'name': 'Kotlin', 'bytes': '8378'}]}
import {data} from './testdata/valid_css_at_rules_amp.reserialized'; import {getAmpAdMetadata} from '../amp-ad-utils'; describe('getAmpAdMetadata', () => { it('should parse metadata successfully', () => { const creativeMetadata = getAmpAdMetadata(data.reserialized); expect(creativeMetadata).to.be.ok; expect(creativeMetadata.minifiedCreative).to.equal(data.minifiedCreative); expect(creativeMetadata.customElementExtensions.length).to.equal(1); expect(creativeMetadata.customElementExtensions[0]).to.equal('amp-font'); expect(creativeMetadata.customStylesheets.length).to.equal(1); expect(creativeMetadata.customStylesheets[0]).to.deep.equal({ 'href': 'https://fonts.googleapis.com/css?family=Questrial', }); expect(creativeMetadata.images).to.not.be.ok; }); it('should parse metadata despite missing offsets', () => { const creativeMetadata = getAmpAdMetadata(data.reserializedMissingOffset); expect(creativeMetadata).to.be.ok; expect(creativeMetadata.minifiedCreative).to.equal(data.minifiedCreative); expect(creativeMetadata.customElementExtensions.length).to.equal(1); expect(creativeMetadata.customElementExtensions[0]).to.equal('amp-font'); expect(creativeMetadata.customStylesheets.length).to.equal(1); expect(creativeMetadata.customStylesheets[0]).to.deep.equal({ 'href': 'https://fonts.googleapis.com/css?family=Questrial', }); expect(creativeMetadata.images).to.not.be.ok; }); it('should return null -- bad offset', () => { const creativeMetadata = getAmpAdMetadata(data.reserializedInvalidOffset); expect(creativeMetadata).to.be.null; }); it('should return null -- missing closing script tag', () => { const creativeMetadata = getAmpAdMetadata( data.reserializedMissingScriptTag); expect(creativeMetadata).to.be.null; }); });
{'content_hash': 'be0ffbc82fa45c9484e8f98683f4f479', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 78, 'avg_line_length': 41.55555555555556, 'alnum_prop': 0.7299465240641712, 'repo_name': 'techhtml/amphtml', 'id': 'a408d0d6a5bb9b369c4461477115647c1e537833', 'size': '2497', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'extensions/amp-a4a/0.1/test/test-amp-ad-utils.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '343883'}, {'name': 'Go', 'bytes': '7459'}, {'name': 'HTML', 'bytes': '1410137'}, {'name': 'Java', 'bytes': '37155'}, {'name': 'JavaScript', 'bytes': '12333775'}, {'name': 'Python', 'bytes': '72953'}, {'name': 'Shell', 'bytes': '14948'}, {'name': 'Yacc', 'bytes': '22627'}]}
<!DOCTYPE html> <html> <head> <title>Ebook App Testing</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css"> <link type="text/css" rel="stylesheet" href="css/register.css"></link> </head> <body> <h1>Bookstack</h1> <h2>Change Password</h2> <form id="regform"> Email:<br> <div class="transparent"><input type="text" class="radius" name="email" id="email" placeholder="Your Email"></div><br> Old Password:<br> <div class="transparent"><input type="password" class="radius" name="password" id="password" placeholder="Your Password"></div><br> New Password:<br> <div class="transparent"><input type="password" class="radius" name="newpassword" id="newpassword" placeholder="New Password"></div><br> <button name="Change Password" type="button" value="Change Password" id="changepasswordbutton" class="btn-info"> Change Password </button> <div > <p id="loginmessage"> </p><a id="continue" href="http://google.com"></a><a id="register" href="http://google.com"></a> </div> </form> </body> <script src="https://cdn.firebase.com/js/client/2.2.9/firebase.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="js/changepassword.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </html>
{'content_hash': '07083787a59595f8ffb8f5f07eed4308', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 142, 'avg_line_length': 51.58064516129032, 'alnum_prop': 0.6622889305816135, 'repo_name': 'kelechiodoemelam/kelechiodoemelam.github.io', 'id': '1e97982c663ec2a708ff287ca41ba519b2ee22f9', 'size': '1599', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'changepassword.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1087'}, {'name': 'HTML', 'bytes': '11791'}, {'name': 'JavaScript', 'bytes': '11019'}]}
<?php /** Internally used classes */ require_once 'Zend/Pdf/Element/Array.php'; require_once 'Zend/Pdf/Element/Name.php'; /** Zend_Pdf_Resource_Font */ require_once 'Zend/Pdf/Resource/Font.php'; /** * Adobe PDF composite fonts implementation * * A composite font is one whose glyphs are obtained from other fonts or from fontlike * objects called CIDFonts ({@link Zend_Pdf_Resource_Font_CidFont}), organized hierarchically. * In PDF, a composite font is represented by a font dictionary whose Subtype value is Type0; * this is also called a Type 0 font (the Type 0 font at the top level of the hierarchy is the * root font). * * In PDF, a Type 0 font is a CID-keyed font. * * CID-keyed fonts provide effective method to operate with multi-byte character encodings. * * The CID-keyed font architecture specifies the external representation of certain font programs, * called CMap and CIDFont files, along with some conventions for combining and using those files. * * A CID-keyed font is the combination of a CMap with one or more CIDFonts, simple fonts, * or composite fonts containing glyph descriptions. * * The term 'CID-keyed font' reflects the fact that CID (character identifier) numbers * are used to index and access the glyph descriptions in the font. * * * Font objects should be normally be obtained from the factory methods * {@link Zend_Pdf_Font::fontWithName} and {@link Zend_Pdf_Font::fontWithPath}. * * @package Zend_Pdf * @subpackage Fonts * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Pdf_Resource_Font_Type0 extends Zend_Pdf_Resource_Font { /** * Descendant CIDFont * * @var Zend_Pdf_Resource_Font_CidFont */ private $_descendantFont; /** * Generate ToUnicode character map data * * @return string */ static private function getToUnicodeCMapData() { return '/CIDInit /ProcSet findresource begin ' . "\n" . '12 dict begin ' . "\n" . 'begincmap ' . "\n" . '/CIDSystemInfo ' . "\n" . '<</Registry (Adobe) ' . "\n" . '/Ordering (UCS) ' . "\n" . '/Supplement 0' . "\n" . '>> def' . "\n" . '/CMapName /Adobe-Identity-UCS def ' . "\n" . '/CMapType 2 def ' . "\n" . '1 begincodespacerange' . "\n" . '<0000> <FFFF> ' . "\n" . 'endcodespacerange ' . "\n" . '1 beginbfrange ' . "\n" . '<0000> <FFFF> <0000> ' . "\n" . 'endbfrange ' . "\n" . 'endcmap ' . "\n" . 'CMapName currentdict /CMap defineresource pop ' . "\n" . 'end ' . 'end '; } /** * Object constructor * */ public function __construct(Zend_Pdf_Resource_Font_CidFont $descendantFont) { parent::__construct(); $this->_objectFactory->attach($descendantFont->getFactory()); $this->_fontType = Zend_Pdf_Font::TYPE_TYPE_0; $this->_descendantFont = $descendantFont; $this->_fontNames = $descendantFont->getFontNames(); $this->_isBold = $descendantFont->isBold(); $this->_isItalic = $descendantFont->isItalic(); $this->_isMonospaced = $descendantFont->isMonospace(); $this->_underlinePosition = $descendantFont->getUnderlinePosition(); $this->_underlineThickness = $descendantFont->getUnderlineThickness(); $this->_strikePosition = $descendantFont->getStrikePosition(); $this->_strikeThickness = $descendantFont->getStrikeThickness(); $this->_unitsPerEm = $descendantFont->getUnitsPerEm(); $this->_ascent = $descendantFont->getAscent(); $this->_descent = $descendantFont->getDescent(); $this->_lineGap = $descendantFont->getLineGap(); $this->_resource->Subtype = new Zend_Pdf_Element_Name('Type0'); $this->_resource->BaseFont = new Zend_Pdf_Element_Name($descendantFont->getResource()->BaseFont->value); $this->_resource->DescendantFonts = new Zend_Pdf_Element_Array(array( $descendantFont->getResource() )); $this->_resource->Encoding = new Zend_Pdf_Element_Name('Identity-H'); $toUnicode = $this->_objectFactory->newStreamObject(self::getToUnicodeCMapData()); $this->_resource->ToUnicode = $toUnicode; } /** * Returns an array of glyph numbers corresponding to the Unicode characters. * * Zend_Pdf uses 'Identity-H' encoding for Type 0 fonts. * So we don't need to perform any conversion * * See also {@link glyphNumberForCharacter()}. * * @param array $characterCodes Array of Unicode character codes (code points). * @return array Array of glyph numbers. */ public function glyphNumbersForCharacters($characterCodes) { return $characterCodes; } /** * Returns the glyph number corresponding to the Unicode character. * * Zend_Pdf uses 'Identity-H' encoding for Type 0 fonts. * So we don't need to perform any conversion * * @param integer $characterCode Unicode character code (code point). * @return integer Glyph number. */ public function glyphNumberForCharacter($characterCode) { return $characterCode; } /** * Returns a number between 0 and 1 inclusive that indicates the percentage * of characters in the string which are covered by glyphs in this font. * * Since no one font will contain glyphs for the entire Unicode character * range, this method can be used to help locate a suitable font when the * actual contents of the string are not known. * * Note that some fonts lie about the characters they support. Additionally, * fonts don't usually contain glyphs for control characters such as tabs * and line breaks, so it is rare that you will get back a full 1.0 score. * The resulting value should be considered informational only. * * @param string $string * @param string $charEncoding (optional) Character encoding of source text. * If omitted, uses 'current locale'. * @return float */ public function getCoveredPercentage($string, $charEncoding = '') { return $this->_descendantFont->getCoveredPercentage($string, $charEncoding); } /** * Returns the widths of the glyphs. * * The widths are expressed in the font's glyph space. You are responsible * for converting to user space as necessary. See {@link unitsPerEm()}. * * Throws an exception if the glyph number is out of range. * * See also {@link widthForGlyph()}. * * @param array &$glyphNumbers Array of glyph numbers. * @return array Array of glyph widths (integers). * @throws Zend_Pdf_Exception */ public function widthsForGlyphs($glyphNumbers) { return $this->_descendantFont->widthsForChars($glyphNumbers); } /** * Returns the width of the glyph. * * Like {@link widthsForGlyphs()} but used for one glyph at a time. * * @param integer $glyphNumber * @return integer * @throws Zend_Pdf_Exception */ public function widthForGlyph($glyphNumber) { return $this->_descendantFont->widthForChar($glyphNumber); } /** * Convert string to the font encoding. * * The method is used to prepare string for text drawing operators * * @param string $string * @param string $charEncoding Character encoding of source text. * @return string */ public function encodeString($string, $charEncoding) { return iconv($charEncoding, 'UTF-16BE', $string); } /** * Convert string from the font encoding. * * The method is used to convert strings retrieved from existing content streams * * @param string $string * @param string $charEncoding Character encoding of resulting text. * @return string */ public function decodeString($string, $charEncoding) { return iconv('UTF-16BE', $charEncoding, $string); } }
{'content_hash': 'e27db52e06e3e11f13f4e0031506c5ed', 'timestamp': '', 'source': 'github', 'line_count': 238, 'max_line_length': 119, 'avg_line_length': 37.390756302521005, 'alnum_prop': 0.5889425778177323, 'repo_name': 'jupeter/zf1', 'id': '60b8ec737f9d3c013f7fe8f7aee7f32fca201807', 'size': '9609', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'library/Zend/Pdf/Resource/Font/Type0.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '30072'}, {'name': 'PHP', 'bytes': '30469269'}, {'name': 'Shell', 'bytes': '6541'}]}
""" Copyright (c) Bojan Mihelac and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # Copied from: https://raw.githubusercontent.com/django-import-export/django-import-export/5795e114210adf250ac6e146db2fa413f38875de/import_export/tmp_storages.py import os import tempfile from uuid import uuid4 from django.core.cache import cache from django.core.files.base import ContentFile from django.core.files.storage import default_storage class BaseStorage: def __init__(self, name=None): self.name = name def save(self, data, mode='w'): raise NotImplementedError def read(self, read_mode='r'): raise NotImplementedError def remove(self): raise NotImplementedError class TempFolderStorage(BaseStorage): def open(self, mode='r'): if self.name: return open(self.get_full_path(), mode) else: tmp_file = tempfile.NamedTemporaryFile(delete=False) self.name = tmp_file.name return tmp_file def save(self, data, mode='w'): with self.open(mode=mode) as file: file.write(data) def read(self, mode='r'): with self.open(mode=mode) as file: return file.read() def remove(self): os.remove(self.get_full_path()) def get_full_path(self): return os.path.join( tempfile.gettempdir(), self.name ) class CacheStorage(BaseStorage): """ By default memcache maximum size per key is 1MB, be careful with large files. """ CACHE_LIFETIME = 86400 CACHE_PREFIX = 'django-import-export-' def save(self, data, mode=None): if not self.name: self.name = uuid4().hex cache.set(self.CACHE_PREFIX + self.name, data, self.CACHE_LIFETIME) def read(self, read_mode='r'): return cache.get(self.CACHE_PREFIX + self.name) def remove(self): cache.delete(self.name) class MediaStorage(BaseStorage): MEDIA_FOLDER = 'django-import-export' def save(self, data, mode=None): if not self.name: self.name = uuid4().hex default_storage.save(self.get_full_path(), ContentFile(data)) def read(self, read_mode='rb'): with default_storage.open(self.get_full_path(), mode=read_mode) as f: return f.read() def remove(self): default_storage.delete(self.get_full_path()) def get_full_path(self): return os.path.join( self.MEDIA_FOLDER, self.name )
{'content_hash': '2c28b110d2e7e494fe7bbf224136c291', 'timestamp': '', 'source': 'github', 'line_count': 118, 'max_line_length': 161, 'avg_line_length': 32.101694915254235, 'alnum_prop': 0.6858500527983105, 'repo_name': 'kaedroho/wagtail', 'id': '02d4e642474cf502166f217c9baee15d41c4310d', 'size': '3788', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'wagtail/contrib/redirects/tmp_storages.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '3323'}, {'name': 'Dockerfile', 'bytes': '2041'}, {'name': 'HTML', 'bytes': '505436'}, {'name': 'JavaScript', 'bytes': '279901'}, {'name': 'Makefile', 'bytes': '977'}, {'name': 'Python', 'bytes': '4671883'}, {'name': 'SCSS', 'bytes': '201389'}, {'name': 'Shell', 'bytes': '7662'}, {'name': 'TypeScript', 'bytes': '30266'}]}
/* Easy way to allow for build of multiple binaries */ #include "config.h" #include "floatfann.h" #include "fann.c" #include "fann_io.c" #include "fann_train.c" #include "fann_train_data.c" #include "fann_error.c" #include "fann_cascade.c"
{'content_hash': '2a144d02535c0578d43ea6c2bbfddd94', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 54, 'avg_line_length': 18.76923076923077, 'alnum_prop': 0.7008196721311475, 'repo_name': 'zseymour/phrase2vec', 'id': 'db4667cf643e4aeea3311340b461a80cab11d876', 'size': '1052', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'fann/src/floatfann.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '580858'}, {'name': 'C++', 'bytes': '16811'}, {'name': 'Shell', 'bytes': '2569'}]}
adding your own types ===================== Sometimes, overriding Sol to make it handle certain ``struct``'s and ``class``'es as something other than just userdata is desirable. The way to do this is to take advantage of the 4 customization points for Sol. These are ``sol::lua_size<T>``, ``sol::stack::pusher<T, C>``, ``sol::stack::getter<T, C>``, ``sol::stack::checker<T, sol::type t, C>``. These are template class/structs, so you'll override them using a technique C++ calls *class/struct specialization*. Below is an example of a struct that gets broken apart into 2 pieces when going in the C++ --> Lua direction, and then pulled back into a struct when going in the Lua --> C++: .. code-block:: cpp :caption: two_things.hpp :name: customization-overriding #include <sol.hpp> struct two_things { int a; bool b; }; namespace sol { // First, the expected size // Specialization of a struct // We expect 2, so use 2 template <> struct lua_size<two_things> : std::integral_constant<int, 2> {}; // Now, specialize various stack structures namespace stack { template <> struct checker<two_things> { template <typename Handler> static bool check(lua_State* L, int index, Handler&& handler, record& tracking) { // indices can be negative to count backwards from the top of the stack, // rather than the bottom up // to deal with this, we adjust the index to // its absolute position using the lua_absindex function int absolute_index = lua_absindex(L, index); // Check first and second second index for being the proper types bool success = stack::check<int>(L, absolute_index - 1, handler) && stack::check<bool>(L, absolute_index, handler); tracking.use(2); return success; } }; template <> struct getter<two_things> { static two_things get(lua_State* L, int index, record& tracking) { int absolute_index = lua_absindex(L, index); // Get the first element int a = stack::get<int>(L, absolute_index - 1); // Get the second element, // in the +1 position from the first bool b = stack::get<bool>(L, absolute_index); // we use 2 slots, each of the previous takes 1 tracking.use(2); return two_things{ a, b }; } }; template <> struct pusher<two_things> { static int push(lua_State* L, const two_things& things) { int amount = stack::push(L, things.a); // amount will be 1: int pushes 1 item amount += stack::push(L, things.b); // amount 2 now, since bool pushes a single item // Return 2 things return amount; } }; } } This is the base formula that you can follow to extend to your own classes. Using it in the rest of the library should then be seamless: .. code-block:: cpp :caption: customization: using it :name: customization-using #include <sol.hpp> #include <two_things.hpp> int main () { sol::state lua; // Create a pass-through style of function lua.script("function f ( a, b ) return a, b end"); // get the function out of Lua sol::function f = lua["f"]; two_things things = f(two_things{24, true}); // things.a == 24 // things.b == true return 0; } And that's it! A few things of note about the implementation: First, there's an auxiliary parameter of type :doc:`sol::stack::record<../api/stack>` for the getters and checkers. This keeps track of what the last complete operation performed. Since we retrieved 2 members, we use ``tracking.use(2);`` to indicate that we used 2 stack positions (one for ``bool``, one for ``int``). The second thing to note here is that we made sure to use the ``index`` parameter, and then proceeded to add 1 to it for the next one. You can make something pushable into Lua, but not get-able in the same way if you only specialize one part of the system. If you need to retrieve it (as a return using one or multiple values from Lua), you should specialize the ``sol::stack::getter`` template class and the ``sol::stack::checker`` template class. If you need to push it into Lua at some point, then you'll want to specialize the ``sol::stack::pusher`` template class. The ``sol::lua_size`` template class trait needs to be specialized for both cases, unless it only pushes 1 item, in which case the default implementation will assume 1. In general, this is fine since most getters/checkers only use 1 stack point. But, if you're doing more complex nested classes, it would be useful to use ``tracking.last`` to understand how many stack indices the last getter/checker operation did and increment it by ``index + tracking.last`` after using a ``stack::check<..>( L, index, tracking)`` call. You can read more about the structs themselves :ref:`over on the API page for stack<extension_points>`, and if there's something that goes wrong or you have anymore questions, please feel free to drop a line on the Github Issues page or send an e-mail!
{'content_hash': '3a220910a09ebf3af5a20ad07f14abe5', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 603, 'avg_line_length': 43.41228070175438, 'alnum_prop': 0.6872095372802587, 'repo_name': 'nshcat/sol2', 'id': '31fcad46568cca81d9672bccffb8330cdb8f05fb', 'size': '4949', 'binary': False, 'copies': '2', 'ref': 'refs/heads/develop', 'path': 'docs/source/tutorial/customization.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '3861'}, {'name': 'C++', 'bytes': '489773'}, {'name': 'CMake', 'bytes': '620'}, {'name': 'Objective-C', 'bytes': '1669'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '3b979f71d67dd1dd6b2761dc455e87e4', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'b0894ec5beb2a447a68159317b6f2b37f1305fab', 'size': '202', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Chlorophyta/Zygnematophyceae/Zygnematales/Desmidiaceae/Cosmarium/Cosmarium rectangulare/Cosmarium rectangulare boldtii/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
> Smith IRP Calculations Web App ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report ``` For detailed explanation on how things work, checkout the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader).
{'content_hash': 'a7256b0bc60b636e1004337e0d5dc57c', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 170, 'avg_line_length': 24.42105263157895, 'alnum_prop': 0.7586206896551724, 'repo_name': 'coryg-io/smith_web_app', 'id': 'ccc17bd3a05086215e580b5d7c45936655922d1d', 'size': '486', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '292004'}, {'name': 'CoffeeScript', 'bytes': '2764'}, {'name': 'HTML', 'bytes': '32034'}, {'name': 'JavaScript', 'bytes': '301825'}]}
package testjar; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.hadoop.io.WritableComparable; /** * This is an example simple writable class. This is used as a class external to * the Hadoop IO classes for testing of user Writable classes. * */ public class ExternalWritable implements WritableComparable { private String message = null; public ExternalWritable() { } public ExternalWritable(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void readFields(DataInput in) throws IOException { message = null; boolean hasMessage = in.readBoolean(); if (hasMessage) { message = in.readUTF(); } } public void write(DataOutput out) throws IOException { boolean hasMessage = (message != null && message.length() > 0); out.writeBoolean(hasMessage); if (hasMessage) { out.writeUTF(message); } } public int compareTo(Object o) { if (!(o instanceof ExternalWritable)) { throw new IllegalArgumentException("Input not an ExternalWritable"); } ExternalWritable that = (ExternalWritable) o; return this.message.compareTo(that.message); } public String toString() { return this.message; } }
{'content_hash': '2de898e1038d79a2a055706d5b40e745', 'timestamp': '', 'source': 'github', 'line_count': 67, 'max_line_length': 80, 'avg_line_length': 22.388059701492537, 'alnum_prop': 0.636, 'repo_name': 'dongpf/hadoop-0.19.1', 'id': '1fd9d29bc5d27ceb327d74585ee6848d70119bad', 'size': '2306', 'binary': False, 'copies': '1', 'ref': 'refs/heads/rsc', 'path': 'src/test/testjar/ExternalWritable.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '631'}, {'name': 'C', 'bytes': '368366'}, {'name': 'C++', 'bytes': '506373'}, {'name': 'Java', 'bytes': '11404415'}, {'name': 'JavaScript', 'bytes': '60544'}, {'name': 'Objective-C', 'bytes': '118487'}, {'name': 'PHP', 'bytes': '884765'}, {'name': 'Perl', 'bytes': '150452'}, {'name': 'Python', 'bytes': '1619112'}, {'name': 'Ruby', 'bytes': '28485'}, {'name': 'Shell', 'bytes': '878487'}, {'name': 'Smalltalk', 'bytes': '56562'}, {'name': 'XML', 'bytes': '243803'}]}
package com.iluwatar.hexagonal.domain; import com.iluwatar.hexagonal.database.LotteryTicketRepository; import java.util.Optional; /** * Lottery utilities */ public class LotteryUtils { private LotteryUtils() { } /** * Checks if lottery ticket has won */ public static LotteryTicketCheckResult checkTicketForPrize(LotteryTicketRepository repository, LotteryTicketId id, LotteryNumbers winningNumbers) { Optional<LotteryTicket> optional = repository.findById(id); if (optional.isPresent()) { if (optional.get().getNumbers().equals(winningNumbers)) { return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.WIN_PRIZE, 1000); } else { return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.NO_PRIZE); } } else { return new LotteryTicketCheckResult(LotteryTicketCheckResult.CheckResult.TICKET_NOT_SUBMITTED); } } }
{'content_hash': '2500204dabf9916676b16aa12c2456e3', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 116, 'avg_line_length': 30.59375, 'alnum_prop': 0.7048008171603677, 'repo_name': 'fluxw42/java-design-patterns', 'id': '2f3c3be222a03cbb7a669a0fee063fa722a79de6', 'size': '2123', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'hexagonal/src/main/java/com/iluwatar/hexagonal/domain/LotteryUtils.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '827'}, {'name': 'Gherkin', 'bytes': '1078'}, {'name': 'HTML', 'bytes': '7241'}, {'name': 'Java', 'bytes': '1605343'}, {'name': 'JavaScript', 'bytes': '1186'}, {'name': 'Shell', 'bytes': '1713'}]}
package kvm import ( "crypto/rand" "errors" "fmt" "io/ioutil" "net" "path/filepath" "github.com/appc/cni/pkg/types" "github.com/coreos/go-systemd/unit" "github.com/coreos/rkt/networking" "github.com/hashicorp/errwrap" ) // GetNetworkDescriptions explicitly convert slice of activeNets to slice of netDescribers // which is slice required by GetKVMNetArgs func GetNetworkDescriptions(n *networking.Networking) []netDescriber { var nds []netDescriber for _, an := range n.GetActiveNetworks() { nds = append(nds, an) } return nds } // netDescriber is something that describes network configuration type netDescriber interface { GuestIP() net.IP Mask() net.IP IfName() string IPMasq() bool Name() string Gateway() net.IP Routes() []types.Route } // GetKVMNetArgs returns additional arguments that need to be passed // to lkvm tool to configure networks properly. // Logic is based on Network configuration extracted from Networking struct // and essentially from activeNets that expose netDescriber behavior func GetKVMNetArgs(nds []netDescriber) ([]string, error) { var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArg := fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()) lkvmArgs = append(lkvmArgs, lkvmArg) } return lkvmArgs, nil } // generateMacAddress returns net.HardwareAddr filled with fixed 3 byte prefix // complemented by 3 random bytes. func generateMacAddress() (net.HardwareAddr, error) { mac := []byte{ 2, // locally administered unicast 0x65, 0x02, // OUI (randomly chosen by jell) 0, 0, 0, // bytes to randomly overwrite } _, err := rand.Read(mac[3:6]) if err != nil { return nil, errwrap.Wrap(errors.New("cannot generate random mac address"), err) } return mac, nil } func setMacCommand(ifName, mac string) string { return fmt.Sprintf("/bin/ip link set dev %s address %s", ifName, mac) } func addAddressCommand(address, ifName string) string { return fmt.Sprintf("/bin/ip address add %s dev %s", address, ifName) } func addRouteCommand(destination, router string) string { return fmt.Sprintf("/bin/ip route add %s via %s", destination, router) } func downInterfaceCommand(ifName string) string { return fmt.Sprintf("/bin/ip link set dev %s down", ifName) } func upInterfaceCommand(ifName string) string { return fmt.Sprintf("/bin/ip link set dev %s up", ifName) } func GenerateNetworkInterfaceUnits(unitsPath string, netDescriptions []netDescriber) error { for i, netDescription := range netDescriptions { ifName := fmt.Sprintf(networking.IfNamePattern, i) netAddress := net.IPNet{ IP: netDescription.GuestIP(), Mask: net.IPMask(netDescription.Mask()), } address := netAddress.String() mac, err := generateMacAddress() if err != nil { return err } opts := []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Network configuration for device: %v", ifName)), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Service", "Type", "oneshot"), unit.NewUnitOption("Service", "RemainAfterExit", "true"), unit.NewUnitOption("Service", "ExecStartPre", downInterfaceCommand(ifName)), unit.NewUnitOption("Service", "ExecStartPre", setMacCommand(ifName, mac.String())), unit.NewUnitOption("Service", "ExecStartPre", upInterfaceCommand(ifName)), unit.NewUnitOption("Service", "ExecStart", addAddressCommand(address, ifName)), unit.NewUnitOption("Install", "RequiredBy", "default.target"), } for _, route := range netDescription.Routes() { gw := route.GW if gw == nil { gw = netDescription.Gateway() } opts = append( opts, unit.NewUnitOption( "Service", "ExecStartPost", addRouteCommand(route.Dst.String(), gw.String()), ), ) } unitName := fmt.Sprintf("interface-%s", ifName) + ".service" unitBytes, err := ioutil.ReadAll(unit.Serialize(opts)) if err != nil { return errwrap.Wrap(fmt.Errorf("failed to serialize network unit file to bytes %q", unitName), err) } err = ioutil.WriteFile(filepath.Join(unitsPath, unitName), unitBytes, 0644) if err != nil { return errwrap.Wrap(fmt.Errorf("failed to create network unit file %q", unitName), err) } rlog.Printf("network unit created: %q in %q (iface=%q, addr=%q)", unitName, unitsPath, ifName, address) } return nil }
{'content_hash': '8514cb968ecbb2956c5a128db53c6553', 'timestamp': '', 'source': 'github', 'line_count': 150, 'max_line_length': 109, 'avg_line_length': 29.48, 'alnum_prop': 0.7062415196743554, 'repo_name': 'cloverstd/open-falcon-agent-in-docker', 'id': 'e4eccc2011229e1d20c5385655634303d598a5a4', 'size': '5015', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/coreos/rkt/stage1/init/kvm/network.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '76683'}, {'name': 'Go', 'bytes': '92152'}, {'name': 'HTML', 'bytes': '15200'}, {'name': 'JavaScript', 'bytes': '10195'}, {'name': 'Shell', 'bytes': '2311'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'd7606298f2eb7817b3d438a6791b3efd', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'd6083b3b313b5a11f61c76ea537aa2a862edd4c3', 'size': '205', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Lysimachia/Lysimachia hybrida/ Syn. Steironema hybridum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
local PANEL = {} AccessorFunc( PANEL, "m_bSizeToContents", "AutoSize" ) AccessorFunc( PANEL, "m_bStretchHorizontally", "StretchHorizontally" ) AccessorFunc( PANEL, "m_bNoSizing", "NoSizing" ) AccessorFunc( PANEL, "m_bSortable", "Sortable" ) AccessorFunc( PANEL, "m_fAnimTime", "AnimTime" ) AccessorFunc( PANEL, "m_fAnimEase", "AnimEase" ) AccessorFunc( PANEL, "m_strDraggableName", "DraggableName" ) AccessorFunc( PANEL, "Spacing", "Spacing" ) AccessorFunc( PANEL, "Padding", "Padding" ) function PANEL:Init() self:SetDraggableName( "GlobalDPanel" ) self.pnlCanvas = vgui.Create( "DPanel", self ) self.pnlCanvas:SetPaintBackground( false ) self.pnlCanvas.OnMousePressed = function( self, code ) self:GetParent():OnMousePressed( code ) end self.pnlCanvas.OnChildRemoved = function() self:OnChildRemoved() end self.pnlCanvas:SetMouseInputEnabled( true ) self.pnlCanvas.InvalidateLayout = function() self:InvalidateLayout() end self.Items = {} self.YOffset = 0 self.m_fAnimTime = 0 self.m_fAnimEase = -1 -- means ease in out self.m_iBuilds = 0 self:SetSpacing( 0 ) self:SetPadding( 0 ) self:EnableHorizontal( false ) self:SetAutoSize( false ) self:SetPaintBackground( true ) self:SetNoSizing( false ) self:SetMouseInputEnabled( true ) -- This turns off the engine drawing self:SetPaintBackgroundEnabled( false ) self:SetPaintBorderEnabled( false ) end function PANEL:OnModified() -- Override me end function PANEL:SizeToContents() self:SetSize( self.pnlCanvas:GetSize() ) end function PANEL:GetItems() -- Should we return a copy of this to stop -- people messing with it? return self.Items end function PANEL:EnableHorizontal( bHoriz ) self.Horizontal = bHoriz end function PANEL:EnableVerticalScrollbar() if ( self.VBar ) then return end self.VBar = vgui.Create( "DVScrollBar", self ) end function PANEL:GetCanvas() return self.pnlCanvas end function PANEL:Clear( bDelete ) for k, panel in pairs( self.Items ) do if ( !IsValid( panel ) ) then continue end panel:SetVisible( false ) if ( bDelete ) then panel:Remove() end end self.Items = {} end function PANEL:AddItem( item, strLineState ) if ( !IsValid( item ) ) then return end item:SetVisible( true ) item:SetParent( self:GetCanvas() ) item.m_strLineState = strLineState || item.m_strLineState table.insert( self.Items, item ) --[[if ( self.m_bSortable ) then local DragSlot = item:MakeDraggable( self:GetDraggableName(), self ) DragSlot.OnDrop = self.DropAction end]] item:SetSelectable( self.m_bSelectionCanvas ) self:InvalidateLayout() end function PANEL:InsertBefore( before, insert, strLineState ) table.RemoveByValue( self.Items, insert ) self:AddItem( insert, strLineState ) local key = table.KeyFromValue( self.Items, before ) if ( key ) then table.RemoveByValue( self.Items, insert ) table.insert( self.Items, key, insert ) end end function PANEL:InsertAfter( before, insert, strLineState ) table.RemoveByValue( self.Items, insert ) self:AddItem( insert, strLineState ) local key = table.KeyFromValue( self.Items, before ) if ( key ) then table.RemoveByValue( self.Items, insert ) table.insert( self.Items, key + 1, insert ) end end function PANEL:InsertAtTop( insert, strLineState ) table.RemoveByValue( self.Items, insert ) self:AddItem( insert, strLineState ) local key = 1 if ( key ) then table.RemoveByValue( self.Items, insert ) table.insert( self.Items, key, insert ) end end function PANEL.DropAction( Slot, RcvSlot ) local PanelToMove = Slot.Panel if ( dragndrop.m_MenuData == "copy" ) then if ( PanelToMove.Copy ) then PanelToMove = Slot.Panel:Copy() PanelToMove.m_strLineState = Slot.Panel.m_strLineState else return end end PanelToMove:SetPos( RcvSlot.Data.pnlCanvas:ScreenToLocal( gui.MouseX() - dragndrop.m_MouseLocalX, gui.MouseY() - dragndrop.m_MouseLocalY ) ) if ( dragndrop.DropPos == 4 || dragndrop.DropPos == 8 ) then RcvSlot.Data:InsertBefore( RcvSlot.Panel, PanelToMove ) else RcvSlot.Data:InsertAfter( RcvSlot.Panel, PanelToMove ) end end function PANEL:RemoveItem( item, bDontDelete ) for k, panel in pairs( self.Items ) do if ( panel == item ) then self.Items[ k ] = nil if ( !bDontDelete ) then panel:Remove() end self:InvalidateLayout() end end end function PANEL:CleanList() for k, panel in pairs( self.Items ) do if ( !IsValid( panel ) || panel:GetParent() != self.pnlCanvas ) then self.Items[k] = nil end end end function PANEL:Rebuild() local Offset = 0 self.m_iBuilds = self.m_iBuilds + 1 self:CleanList() if ( self.Horizontal ) then local x, y = self.Padding, self.Padding for k, panel in pairs( self.Items ) do if ( panel:IsVisible() ) then local OwnLine = ( panel.m_strLineState && panel.m_strLineState == "ownline" ) local w = panel:GetWide() local h = panel:GetTall() if ( x > self.Padding && ( x + w > self:GetWide() || OwnLine ) ) then x = self.Padding y = y + h + self.Spacing end if ( self.m_fAnimTime > 0 && self.m_iBuilds > 1 ) then panel:MoveTo( x, y, self.m_fAnimTime, 0, self.m_fAnimEase ) else panel:SetPos( x, y ) end x = x + w + self.Spacing Offset = y + h + self.Spacing if ( OwnLine ) then x = self.Padding y = y + h + self.Spacing end end end else for k, panel in pairs( self.Items ) do if ( panel:IsVisible() ) then if ( self.m_bNoSizing ) then panel:SizeToContents() if ( self.m_fAnimTime > 0 && self.m_iBuilds > 1 ) then panel:MoveTo( ( self:GetCanvas():GetWide() - panel:GetWide() ) * 0.5, self.Padding + Offset, self.m_fAnimTime, 0, self.m_fAnimEase ) else panel:SetPos( ( self:GetCanvas():GetWide() - panel:GetWide() ) * 0.5, self.Padding + Offset ) end else panel:SetSize( self:GetCanvas():GetWide() - self.Padding * 2, panel:GetTall() ) if ( self.m_fAnimTime > 0 && self.m_iBuilds > 1 ) then panel:MoveTo( self.Padding, self.Padding + Offset, self.m_fAnimTime, self.m_fAnimEase ) else panel:SetPos( self.Padding, self.Padding + Offset ) end end -- Changing the width might ultimately change the height -- So give the panel a chance to change its height now, -- so when we call GetTall below the height will be correct. -- True means layout now. panel:InvalidateLayout( true ) Offset = Offset + panel:GetTall() + self.Spacing end end Offset = Offset + self.Padding end self:GetCanvas():SetTall( Offset + self.Padding - self.Spacing ) -- Although this behaviour isn't exactly implied, center vertically too if ( self.m_bNoSizing && self:GetCanvas():GetTall() < self:GetTall() ) then self:GetCanvas():SetPos( 0, ( self:GetTall() - self:GetCanvas():GetTall() ) * 0.5 ) end end function PANEL:OnMouseWheeled( dlta ) if ( self.VBar ) then return self.VBar:OnMouseWheeled( dlta ) end end function PANEL:Paint( w, h ) derma.SkinHook( "Paint", "PanelList", self, w, h ) return true end function PANEL:OnVScroll( iOffset ) self.pnlCanvas:SetPos( 0, iOffset ) end function PANEL:PerformLayout() local Wide = self:GetWide() local Tall = self.pnlCanvas:GetTall() local YPos = 0 if ( !self.Rebuild ) then debug.Trace() end self:Rebuild() if ( self.VBar ) then self.VBar:SetPos( self:GetWide() - 13, 0 ) self.VBar:SetSize( 13, self:GetTall() ) self.VBar:SetUp( self:GetTall(), self.pnlCanvas:GetTall() ) -- Disables scrollbar if nothing to scroll YPos = self.VBar:GetOffset() if ( self.VBar.Enabled ) then Wide = Wide - 13 end end self.pnlCanvas:SetPos( 0, YPos ) self.pnlCanvas:SetWide( Wide ) self:Rebuild() if ( self:GetAutoSize() ) then self:SetTall( self.pnlCanvas:GetTall() ) self.pnlCanvas:SetPos( 0, 0 ) end if ( self.VBar && !self:GetAutoSize() && Tall != self.pnlCanvas:GetTall() ) then self.VBar:SetScroll( self.VBar:GetScroll() ) -- Make sure we are not too far down! end end function PANEL:OnChildRemoved() self:CleanList() self:InvalidateLayout() end function PANEL:ScrollToChild( panel ) local x, y = self.pnlCanvas:GetChildPosition( panel ) local w, h = panel:GetSize() y = y + h * 0.5 y = y - self:GetTall() * 0.5 self.VBar:AnimateTo( y, 0.5, 0, 0.5 ) end function PANEL:SortByMember( key, desc ) desc = desc || true table.sort( self.Items, function( a, b ) if ( desc ) then local ta = a local tb = b a = tb b = ta end if ( a[ key ] == nil ) then return false end if ( b[ key ] == nil ) then return true end return a[ key ] > b[ key ] end ) end derma.DefineControl( "DPanelList", "A Panel that neatly organises other panels", PANEL, "DPanel" )
{'content_hash': '7400f62072fedd57170961b5c43ee2e8', 'timestamp': '', 'source': 'github', 'line_count': 427, 'max_line_length': 141, 'avg_line_length': 20.536299765807964, 'alnum_prop': 0.6794389326034895, 'repo_name': 'OctoEnigma/shiny-octo-system', 'id': '94bbfdc7734b88156320f6c70b4362f176745e51', 'size': '8770', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lua/vgui/dpanellist.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '6665379'}, {'name': 'Python', 'bytes': '2605'}]}
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _componentsTestUtils = require("@looker/components-test-utils"); var _react = require("@testing-library/react"); var _react2 = _interopRequireDefault(require("react")); var _ParamFilter = require("./ParamFilter"); describe('ParamFilter tests', function () { var enumerations = [{ label: 'First', value: 'first' }, { label: 'Second', value: 'second' }, { label: 'Third', value: 'third' }]; it('should select new option when clicked', (0, _asyncToGenerator2["default"])(regeneratorRuntime.mark(function _callee() { var select; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: (0, _componentsTestUtils.renderWithTheme)(_react2["default"].createElement(_ParamFilter.ParamFilter, { item: { id: 1, value: ['first'] }, enumerations: enumerations })); _context.next = 3; return _react.screen.findByText('First'); case 3: select = _context.sent; expect(select).toBeVisible(); case 5: case "end": return _context.stop(); } } }, _callee); }))); }); //# sourceMappingURL=ParamFilter.spec.js.map
{'content_hash': '9eda8e9636cefce0678187559af2849c', 'timestamp': '', 'source': 'github', 'line_count': 54, 'max_line_length': 125, 'avg_line_length': 28.574074074074073, 'alnum_prop': 0.5897602073882048, 'repo_name': 'looker-open-source/components', 'id': 'a62cd995dbc10d33fb808b3abda895cd5d02faef', 'size': '1543', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'packages/filter-components/lib/cjs/Filter/components/AdvancedFilter/components/TierFilter/components/ParamFilter/ParamFilter.spec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '10788'}, {'name': 'HTML', 'bytes': '10602733'}, {'name': 'JavaScript', 'bytes': '125821'}, {'name': 'Shell', 'bytes': '5731'}, {'name': 'TypeScript', 'bytes': '6564851'}]}
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <SimpleMenuPreference android:key="scan_method" android:title="@string/pref_scan_method" android:summary="%s" android:entries="@array/pref_scan_method_arrays" android:entryValues="@array/pref_scan_method_value" android:defaultValue="0"/> </PreferenceScreen>
{'content_hash': '2eadddc38935abf425ca04ebbe7e0b7e', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 77, 'avg_line_length': 35.18181818181818, 'alnum_prop': 0.7493540051679587, 'repo_name': 'fython/NyanpasuTile', 'id': '2454880551e12b172eb985e1ba3ec3cd972095e0', 'size': '387', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/xml/settings_scan_qr.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '790396'}]}
var assert = require('assert'); var cassie = require('../lib/cassie'), Schema = cassie.Schema; var connectOptions = {hosts: ["127.0.0.1:9042"], keyspace: "CassieTest"}; cassie.connect(connectOptions); var UserSchema = new Schema({user_id: {type: Number, primary: true}, name: String}); var User = cassie.model('User', UserSchema); var options = {}; cassie.deleteKeyspace(connectOptions, options, function(err) { cassie.syncTables(connectOptions, options, function(err) { if(err) console.log(err); var new_user_1 = new User({user_id: 1000, name: 'Bob'}); var new_user_2 = new User({user_id: 2000, name: 'Steve'}); var query_1 = new_user_1.save(); var query_2 = new_user_2.save(); var batchOptions = {debug: true, prettyDebug: true, timing: true}; cassie.batch([query_1, query_2], batchOptions, function(err) { //Handle errors, etc. if(err) console.log(err); cassie.close(); }); }); });
{'content_hash': 'baf97d189d94495a66021501a97e135d', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 84, 'avg_line_length': 24.75609756097561, 'alnum_prop': 0.6049261083743842, 'repo_name': 'Flux159/cassie-odm', 'id': 'c33c6531f09787cc99e7b01fb3f1ada7b48c7889', 'size': '1016', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'readme-tests/batch_test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '151116'}]}
package org.zaproxy.zap.extension.quickstart.launch; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import org.parosproxy.paros.Constant; import org.parosproxy.paros.model.OptionsParam; import org.parosproxy.paros.view.AbstractParamPanel; import org.zaproxy.zap.view.LayoutHelper; public class OptionsQuickStartLaunchPanel extends AbstractParamPanel { private static final long serialVersionUID = -1L; /** * The name of the options panel. */ private static final String NAME = Constant.messages .getString("quickstart.launch.optionspanel.name"); private JComboBox<String> startPageOption; private JTextField startUrl; public OptionsQuickStartLaunchPanel() { super(); setName(NAME); setLayout(new GridBagLayout()); JPanel panel = new JPanel(new GridBagLayout()); panel.setBorder(new EmptyBorder(2, 2, 2, 2)); JLabel startOptionLabel = new JLabel( Constant.messages .getString("quickstart.launch.start.option.label")); startOptionLabel.setLabelFor(getStartPageOption()); panel.add(startOptionLabel, LayoutHelper.getGBC(0, 0, 1, 1.0, new Insets(2, 2, 2, 2))); panel.add(getStartPageOption(), LayoutHelper.getGBC(1, 0, 1, 1.0, new Insets(2, 2, 2, 2))); JLabel startUrlLabel = new JLabel( Constant.messages .getString("quickstart.launch.start.url.label")); startOptionLabel.setLabelFor(getStartUrl()); panel.add(startUrlLabel, LayoutHelper.getGBC(0, 1, 1, 1.0, new Insets(2, 2, 2, 2))); panel.add(getStartUrl(), LayoutHelper.getGBC(1, 1, 1, 1.0, new Insets(2, 2, 2, 2))); add(panel, LayoutHelper.getGBC(0, 0, 1, 1.0)); add(new JLabel(), LayoutHelper.getGBC(0, 10, 1, 1.0, 1.0)); // Spacer } @Override public void initParam(Object obj) { final OptionsParam options = (OptionsParam) obj; final QuickStartLaunchParam param = options .getParamSet(QuickStartLaunchParam.class); if (param.isZapStartPage()) { getStartPageOption().setSelectedIndex(0); } else if (param.isBlankStartPage()) { getStartPageOption().setSelectedIndex(1); } else { getStartPageOption().setSelectedIndex(2); getStartUrl().setText(param.getStartPage()); } } @Override public void validateParam(Object obj) throws Exception { if (getStartPageOption().getSelectedIndex() == 2) { try { // Validate the url new URL(getStartUrl().getText()); } catch (Exception e) { getStartUrl().requestFocus(); throw new IllegalArgumentException( Constant.messages .getString("quickstart.launch.start.url.warn")); } } } @Override public void saveParam(Object obj) throws Exception { final OptionsParam options = (OptionsParam) obj; final QuickStartLaunchParam param = options .getParamSet(QuickStartLaunchParam.class); switch (getStartPageOption().getSelectedIndex()) { case 0: param.setZapStartPage(); break; case 1: param.setBlankStartPage(); break; case 2: param.setStartPage(new URL(getStartUrl().getText())); break; default: param.setZapStartPage(); break; } } @Override public String getHelpIndex() { return "quickstart.launch.options"; } private JComboBox<String> getStartPageOption() { if (startPageOption == null) { startPageOption = new JComboBox<String>(); /* * Note that the indexes are explicitly used in setUrlFieldState() * initParam(Object obj) validateParam(Object obj) */ startPageOption.addItem(Constant.messages .getString("quickstart.launch.start.pulldown.zap")); startPageOption.addItem(Constant.messages .getString("quickstart.launch.start.pulldown.blank")); startPageOption.addItem(Constant.messages .getString("quickstart.launch.start.pulldown.url")); startPageOption.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { setUrlFieldState(); } }); } return startPageOption; } private void setUrlFieldState() { switch (startPageOption.getSelectedIndex()) { case 0: getStartUrl().setEnabled(false); break; case 1: getStartUrl().setEnabled(false); break; case 2: getStartUrl().setEnabled(true); break; default: getStartUrl().setEnabled(false); break; } } private JTextField getStartUrl() { if (startUrl == null) { startUrl = new JTextField(); } return startUrl; } }
{'content_hash': 'a2553b8eb394e7de77be04f93a6f67e1', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 80, 'avg_line_length': 33.72352941176471, 'alnum_prop': 0.57282400139543, 'repo_name': 'rnehra01/zap-extensions', 'id': 'a3b91cce1aef17807e8db6ab84605bce759bed60', 'size': '6492', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/org/zaproxy/zap/extension/quickstart/launch/OptionsQuickStartLaunchPanel.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '86316'}, {'name': 'C', 'bytes': '1448'}, {'name': 'ColdFusion', 'bytes': '9100'}, {'name': 'HTML', 'bytes': '1846815'}, {'name': 'Haskell', 'bytes': '272095'}, {'name': 'Java', 'bytes': '1574580'}, {'name': 'JavaScript', 'bytes': '1004'}, {'name': 'PHP', 'bytes': '111175'}, {'name': 'Perl', 'bytes': '16431'}, {'name': 'Shell', 'bytes': '10000'}]}
var path = require('path'), fs = require('fs'); exports.safe_merge = function(merge_what) { merge_what = merge_what || {}; Array.prototype.slice.call(arguments).forEach(function(merge_with, i) { if (i == 0) return; for (var key in merge_with) { if (!merge_with.hasOwnProperty(key) || key in merge_what) continue; merge_what[key] = merge_with[key]; } }); return merge_what; }; exports.humanize = function(underscored) { var res = underscored.replace(/_/g, ' '); return res[0].toUpperCase() + res.substr(1); }; exports.camelize = function(underscored, upcaseFirstLetter) { var res = ''; underscored.split('_').forEach(function(part) { res += part[0].toUpperCase() + part.substr(1); }); return upcaseFirstLetter ? res : res[0].toLowerCase() + res.substr(1); }; exports.classify = function(str) { return exports.camelize(exports.singularize(str)); }; exports.underscore = function(camelCaseStr) { var initialUnderscore = camelCaseStr.match(/^_/) ? '_' : ''; var str = camelCaseStr .replace(/^_([A-Z])/g, '$1') .replace(/([A-Z])/g, '_$1') .replace(/^_/, initialUnderscore); return str.toLowerCase(); }; exports.singularize = function singularize(str, singular) { return require('inflection').singularize(str, singular); }; exports.pluralize = function pluralize(str, plural) { return require('inflection').pluralize(str, plural) }; // Stylize a string function stylize(str, style) { if (typeof window !== 'undefined') return str; var styles = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'cyan' : [96, 39], 'blue' : [34, 39], 'yellow' : [33, 39], 'green' : [32, 39], 'red' : [31, 39], 'grey' : [90, 39], 'green-hi' : [92, 32] }; var s = styles[style]; return '\033[' + s[0] + 'm' + str + '\033[' + s[1] + 'm'; } var $ = function(str) { str = new(String)(str); ['bold', 'grey', 'yellow', 'red', 'green', 'cyan', 'blue', 'italic', 'underline'].forEach(function(style) { Object.defineProperty(str, style, { get: function() { return $(stylize(this, style)); } }); }); return str; }; stylize.$ = $; exports.stylize = stylize; exports.addCoverage = function(code, filename) { if (!global.__cov) return code; return require('semicov').addCoverage(code, filename); }; // cache for source code var cache = {}; function addSpaces(str, len, to_start) { var str_len = str.length; for (var i = str_len; i < len; i += 1) { if (!to_start) { str += ' '; } else { str = ' ' + str; } } return str; } exports.addSpaces = addSpaces; function readYaml(file) { try { var yaml = require(['yaml', 'js'].join('-')); var obj = yaml.load(fs.readFileSync(file).toString()); if (obj && obj.shift) { obj = obj.shift(); } return obj; } catch (e) { console.log('Error in reading', file); console.log(e.message); console.log(e.stack); } } exports.readYaml = readYaml; exports.existsSync = fs.existsSync || path.existsSync; function recursivelyWalkDir(directory, filter, callback) { if(!callback) { callback = filter; filter = null; } var results = []; fs.readdir(directory, function(err, list) { if (err) return callback(err); var pending = list.length; if (!pending) return callback(null, results); list.forEach(function(file) { file = directory + '/' + file; fs.stat(file, function(err, stat) { if (stat && stat.isDirectory()) { recursivelyWalkDir(file, filter, function(err, res) { results = results.concat(res); if (!--pending) callback(null, results); }); } else { results.push(file); if (!--pending) callback(null, results); } }); }); }); } exports.recursivelyWalkDir = recursivelyWalkDir; function ensureDirectoryExists(directory, root) { var dirs = directory.split('/') , dir = dirs.shift(); root = (root || '') + dir + '/'; try { fs.mkdirSync(root); } catch (e) { if(!fs.statSync(root).isDirectory()) throw new Error(e); } return !dirs.length || ensureDirectoryExists(dirs.join('/'), root); } exports.ensureDirectoryExists = ensureDirectoryExists; exports.bind = bind; function bind(fn, context) { var curriedArgs = Array.prototype.slice.call(arguments, 2); if (curriedArgs.length) { return function () { var allArgs = curriedArgs.slice(0); for (var i = 0, n = arguments.length; i < n; ++i) { allArgs.push(arguments[i]); } fn.apply(context, allArgs); }; } else { return function () { return fn.apply(context, arguments); }; } } /** * Forward `functions` from `from` to `to`. * * The `this` context of forwarded functions remains bound to the `to` object, * ensuring that property pollution does not occur. * * @param {Object} from * @param {Object} to * @param {Array} functions * @api private */ exports.forward = forward; function forward(from, to, functions) { for (var i = 0, len = functions.length; i < len; i++) { var method = functions[i]; from[method] = bind(to[method], to); } }
{'content_hash': '18b13d29e56e9c3950e592b1003be90e', 'timestamp': '', 'source': 'github', 'line_count': 201, 'max_line_length': 111, 'avg_line_length': 28.09950248756219, 'alnum_prop': 0.5506373937677054, 'repo_name': 'taoyuan/maroon', 'id': '7dfd6f162fa50967bf9b9134c309352aab0d89db', 'size': '5648', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/utils.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '26560'}]}
// Copyright (c) 2005-2009 Jaroslav Gresula // // Distributed under the MIT license (See accompanying file // LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) // #ifndef BINRESOURCES_JG2239_H__ #define BINRESOURCES_JG2239_H__ namespace jag { namespace binres { extern const Byte icc_adobe_rgb[]; extern const size_t icc_adobe_rgb_size; extern const Byte icc_srgb[]; extern const size_t icc_srgb_size; }} // namespace jag::binres #endif // BINRESOURCES_JG2239_H__ /** EOF @file */
{'content_hash': '7347279876a33c8e783fa5c16a7e33dd', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 59, 'avg_line_length': 21.391304347826086, 'alnum_prop': 0.7195121951219512, 'repo_name': 'jgresula/jagpdf', 'id': '797e0ed85f1bfe1093045088ea3920fafeb34385', 'size': '492', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'code/include/resources/resourcebox/binresources.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1904'}, {'name': 'C', 'bytes': '16283'}, {'name': 'C++', 'bytes': '1491801'}, {'name': 'CMake', 'bytes': '89989'}, {'name': 'Java', 'bytes': '21790'}, {'name': 'Python', 'bytes': '631818'}, {'name': 'Shell', 'bytes': '61805'}]}
require 'flavour_saver/lexer' describe FlavourSaver::Lexer do it 'is an RLTK lexer' do expect(subject).to be_a(RLTK::Lexer) end describe 'Tokens' do describe 'Expressions' do describe '{{foo}}' do subject { FlavourSaver::Lexer.lex "{{foo}}" } it 'begins with an EXPRST' do expect(subject.first.type).to eq :EXPRST end it 'ends with an EXPRE' do expect(subject[-2].type).to eq :EXPRE end it 'contains only the identifier "foo"' do expect(subject[1..-3].size).to eq 1 expect(subject[1].type).to eq :IDENT expect(subject[1].value).to eq 'foo' end end describe '{{foo bar}}' do subject { FlavourSaver::Lexer.lex "{{foo bar}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :WHITE, :IDENT, :EXPRE, :EOS ] end it 'has values in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar' ] end end describe '{{foo "bar"}}' do subject { FlavourSaver::Lexer.lex "{{foo \"bar\"}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :WHITE, :STRING, :EXPRE, :EOS ] end it 'has values in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar' ] end end describe '{{foo (bar "baz")}}' do subject { FlavourSaver::Lexer.lex "{{foo (bar 'baz')}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :WHITE, :OPAR, :IDENT, :WHITE, :S_STRING, :CPAR, :EXPRE, :EOS ] end it 'has values in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar', 'baz' ] end end describe '{{foo bar="baz" hello="goodbye"}}' do subject { FlavourSaver::Lexer.lex '{{foo bar="baz" hello="goodbye"}}' } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :WHITE, :IDENT, :EQ, :STRING, :WHITE, :IDENT, :EQ, :STRING, :EXPRE, :EOS ] end it 'has values in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar', 'baz', 'hello', 'goodbye' ] end end describe '{{0}}' do subject { FlavourSaver::Lexer.lex "{{0}}" } it 'properly lexes the expression' do expect(subject.map(&:type)).to eq( [:EXPRST, :NUMBER, :EXPRE, :EOS] ) end it 'contains only the number "0"' do expect(subject[1..-3].size).to eq 1 expect(subject[1].type).to eq :NUMBER expect(subject[1].value).to eq '0' end end describe '{{0.0123456789}}' do subject { FlavourSaver::Lexer.lex "{{0.0123456789}}" } it 'properly lexes the expression' do expect(subject.map(&:type)).to eq( [:EXPRST, :NUMBER, :EXPRE, :EOS] ) end it 'contains only the number "0.0123456789"' do expect(subject[1..-3].size).to eq 1 expect(subject[1].type).to eq :NUMBER expect(subject[1].value).to eq '0.0123456789' end end end describe 'Identities' do it 'supports as ruby methods' do ids = %w( _ __ __123__ __ABC__ ABC123 Abc134def ) ids.each do |id| subject = FlavourSaver::Lexer.lex "{{#{id}}}" expect(subject[1].type).to eq :IDENT expect(subject[1].value).to eq id end end it 'maps non-ruby identities to literals' do ids = %w( A-B 12_Mine - :example 0A test? ) ids.each do |id| subject = FlavourSaver::Lexer.lex "{{#{id}}}" expect(subject[1].type).to eq :LITERAL expect(subject[1].value).to eq id end end end describe '{{foo bar=(baz qux)}}' do subject { FlavourSaver::Lexer.lex '{{foo bar=(baz qux)}}' } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:EXPRST, :IDENT, :WHITE, :IDENT, :EQ, :OPAR, :IDENT, :WHITE, :IDENT, :CPAR, :EXPRE, :EOS] end it 'has values in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar', 'baz', 'qux' ] end end describe '{{else}}' do subject { FlavourSaver::Lexer.lex '{{else}}' } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :ELSE, :EXPRE, :EOS ] end end describe 'Object path expressions' do describe '{{foo.bar}}' do subject { FlavourSaver::Lexer.lex "{{foo.bar}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :DOT, :IDENT, :EXPRE, :EOS ] end it 'has the correct values' do expect(subject.map(&:value).compact).to eq ['foo', 'bar'] end end describe '{{foo.[10].bar}}' do subject { FlavourSaver::Lexer.lex "{{foo.[10].bar}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :DOT, :LITERAL, :DOT, :IDENT, :EXPRE, :EOS ] end it 'has the correct values' do expect(subject.map(&:value).compact).to eq ['foo', '10', 'bar'] end end describe '{{foo.[he!@#$(&@klA)].bar}}' do subject { FlavourSaver::Lexer.lex '{{foo.[he!@#$(&@klA)].bar}}' } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :IDENT, :DOT, :LITERAL, :DOT, :IDENT, :EXPRE, :EOS ] end it 'has the correct values' do expect(subject.map(&:value).compact).to eq ['foo', 'he!@#$(&@klA)', 'bar'] end end end describe 'Triple-stash expressions' do subject { FlavourSaver::Lexer.lex "{{{foo}}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :TEXPRST, :IDENT, :TEXPRE, :EOS ] end end describe 'Comment expressions' do subject { FlavourSaver::Lexer.lex "{{! WAT}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :BANG, :COMMENT, :EXPRE, :EOS ] end end describe 'Backtrack expression' do subject { FlavourSaver::Lexer.lex "{{../foo}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:EXPRST, :DOT, :DOT, :FWSL, :IDENT, :EXPRE, :EOS] end end describe 'Carriage-return and new-lines' do subject { FlavourSaver::Lexer.lex "{{foo}}\n{{bar}}\r{{baz}}" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:EXPRST,:IDENT,:EXPRE,:OUT,:EXPRST,:IDENT,:EXPRE,:OUT,:EXPRST,:IDENT,:EXPRE,:EOS] end end describe 'Block Expressions' do subject { FlavourSaver::Lexer.lex "{{#foo}}{{bar}}{{/foo}}" } describe '{{#foo}}{{bar}}{{/foo}}' do it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [ :EXPRST, :HASH, :IDENT, :EXPRE, :EXPRST, :IDENT, :EXPRE, :EXPRST, :FWSL, :IDENT, :EXPRE, :EOS ] end it 'has identifiers in the correct order' do expect(subject.map(&:value).compact).to eq [ 'foo', 'bar', 'foo' ] end end end describe 'Carriage return' do subject { FlavourSaver::Lexer.lex "\r" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:OUT,:EOS] end end describe 'New line' do subject { FlavourSaver::Lexer.lex "\n" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:OUT,:EOS] end end describe 'Single curly bracket' do subject { FlavourSaver::Lexer.lex "{" } it 'has tokens in the correct order' do expect(subject.map(&:type)).to eq [:OUT,:EOS] end end end end
{'content_hash': '6d5e8d1f6e45876f4206ea93b5fa474b', 'timestamp': '', 'source': 'github', 'line_count': 263, 'max_line_length': 137, 'avg_line_length': 30.984790874524716, 'alnum_prop': 0.5485335624002945, 'repo_name': 'jamesotron/FlavourSaver', 'id': '43c4f150fb54b1305fceb8b2f4913f418cdd554f', 'size': '8149', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/lib/flavour_saver/lexer_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '95070'}]}
package mocks import ( reflect "reflect" do "github.com/digitalocean/doctl/do" gomock "github.com/golang/mock/gomock" ) // MockActionsService is a mock of ActionsService interface. type MockActionsService struct { ctrl *gomock.Controller recorder *MockActionsServiceMockRecorder } // MockActionsServiceMockRecorder is the mock recorder for MockActionsService. type MockActionsServiceMockRecorder struct { mock *MockActionsService } // NewMockActionsService creates a new mock instance. func NewMockActionsService(ctrl *gomock.Controller) *MockActionsService { mock := &MockActionsService{ctrl: ctrl} mock.recorder = &MockActionsServiceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockActionsService) EXPECT() *MockActionsServiceMockRecorder { return m.recorder } // Get mocks base method. func (m *MockActionsService) Get(arg0 int) (*do.Action, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0) ret0, _ := ret[0].(*do.Action) ret1, _ := ret[1].(error) return ret0, ret1 } // Get indicates an expected call of Get. func (mr *MockActionsServiceMockRecorder) Get(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockActionsService)(nil).Get), arg0) } // List mocks base method. func (m *MockActionsService) List() (do.Actions, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List") ret0, _ := ret[0].(do.Actions) ret1, _ := ret[1].(error) return ret0, ret1 } // List indicates an expected call of List. func (mr *MockActionsServiceMockRecorder) List() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockActionsService)(nil).List)) }
{'content_hash': '4b04f0c9c89eacec3b5ae2b1c98380a7', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 115, 'avg_line_length': 29.721311475409838, 'alnum_prop': 0.7429674572531716, 'repo_name': 'digitalocean/doctl', 'id': '692b4fce902d9d122e3303da3ce3d9569fcf99b9', 'size': '1927', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'do/mocks/ActionService.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '634'}, {'name': 'Go', 'bytes': '1902689'}, {'name': 'Makefile', 'bytes': '5736'}, {'name': 'Shell', 'bytes': '13059'}]}
package com.lion.materialshowcaseview; import android.content.Context; import android.content.SharedPreferences; public class PrefsManager { private static final String PREFS_NAME = "material_showcaseview_prefs"; private static final String FIRED_KEY = "has_fired_"; private String showcaseID = null; private Context context; public PrefsManager(Context context, String showcaseID) { this.context = context; this.showcaseID = showcaseID; } boolean hasFired() { return context .getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) .getBoolean(FIRED_KEY + showcaseID, false); } public static boolean hasFired(Context context, String showcaseID) { return context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) .getBoolean(FIRED_KEY + showcaseID, false); } void setFired() { SharedPreferences internal = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); internal.edit().putBoolean(FIRED_KEY + showcaseID, true).apply(); } public void resetShowcase() { resetShowcase(context, showcaseID); } static void resetShowcase(Context context, String showcaseID){ SharedPreferences internal = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); internal.edit().putBoolean(FIRED_KEY + showcaseID, false).apply(); } public static void resetAll(Context context){ SharedPreferences internal = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); internal.edit().clear().apply(); } public void close(){ context = null; } }
{'content_hash': '77e0548fbf827772258e087fa24c2df7', 'timestamp': '', 'source': 'github', 'line_count': 51, 'max_line_length': 100, 'avg_line_length': 32.88235294117647, 'alnum_prop': 0.6887298747763864, 'repo_name': 'liyinyin/MaterialShowcaseView', 'id': 'f449d0b88aabd2f93c1006408159e90061add98d', 'size': '1677', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'library/src/main/java/com/lion/materialshowcaseview/PrefsManager.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '68937'}]}
define([ 'jquery', 'underscore', 'backbone', 'marionette' , 'tpl!templates/entry.html' ], function ($, _, Backbone, Marionette, EntryTemplate) { return Marionette.ItemView.extend({ template: EntryTemplate, ui: { mainDiv: 'div' }, events: { "click": 'disableEllipsis' }, initialize: function () { this.bindUIElements(); }, disableEllipsis: function (e) { this.ui.mainDiv.removeClass("ellipsis"); console.log(e); } }); });
{'content_hash': 'ff627c34b2c447e97c4072dbe20b1f2f', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 144, 'avg_line_length': 28.1, 'alnum_prop': 0.5195729537366548, 'repo_name': 'msurdi/redeye', 'id': '3e18fe8a1def63996e28014427cb943660cb407f', 'size': '562', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/resources/assets/js/views/EntryView.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '44780'}, {'name': 'Groovy', 'bytes': '2088'}, {'name': 'Java', 'bytes': '95888'}, {'name': 'JavaScript', 'bytes': '310657'}, {'name': 'Python', 'bytes': '10773'}]}
(function(angular) { 'use strict'; angular.module('rd.frontend.constants').constant('FrontendMessages_lang_en', { registration: 'Registration', number_seats_placeholder: 'How many persons can have a seat in your flat?', misc_notes_placeholder:'Do you have any further notes?', teampartner_placeholder: 'Email of your partner wish (if any)', registration_validate: 'Next', registration_perform: 'Register now!', registration_finish: 'Finish registration', registration_finish_check: 'Verify your data:', registration_date_expired: 'You cannot register any longer, due to the registration deadline is over.', registration_can_host: 'You have enough seats for being a host in this event.', registration_no_host: 'You have not enough seats for being a host in this event, ' + 'hence it will be tried to mix you in a team with a partner with enough seats', registration_activation_title: 'Confirmation of registration', registration_activation_congratulation_title: 'Successful confirmation', registration_activation_congratulation_text: 'Congratulations, you have successfully confirmed your registration for ' + '<strong><a href="{{ publicDinnerUrl }}" target="_blank">{{ publicDinnerTitle }}</a></strong>!<br/>Soon you will receive further ' + 'information from the organizer (<a href="mailto:{{ adminEmail }}">{{ adminEmail }}</a>) of the event.', registration_activation_error_title: 'Error during confirmation', registration_activation_error_text: 'Unfortunately there occurred an error during trying to confirm your registration. ' + 'Please try it again later. <br/> ' + 'If the error still occurs, please send an email to <a href="mailto:{{ adminEmail }}">{{ adminEmail }}</a>.', teampartner_wish_summary_not_existing: 'You have entered <em>{{ teamPartnerWish }}</em> as team partner wish. ' + 'This wished partner will receive an invitation email for this dinner event as soon as you confirm your registration. ' + 'If <em>{{ teamPartnerWish }}</em> eventually registers to this event, you will be mixed up into one team.', teampartner_wish_summary_match: 'You will cook together with <em>{{ teamPartnerWish }}</em> in one team.', teampartner_wish_summary: 'You have entered <em>{{ teamPartnerWish }}</em> as team partner wish.', gender_unknown: "No information", registration_finished_headline: 'Registration finished!', registration_finished_text: 'You have successfully registrated. In the next minutes you will receive an email with a confirmation link and further information. ' + '<br/>Your registration will only be completed when you open this confirmation link. ' + 'If you did not receive any email, then please send an email to <a href="mailto:{{ adminEmail }}">{{ adminEmail }}</a>.', street_placeholder: 'Your street + nr', address_remarks_help: 'Optional: If you are host and your flat is not easy to find, this remarks can help other teams to find your flat.', team_partner_wish_help: 'Do you want to cook together with a friend? ' + 'By entering his email address, your friend will automatically be invited to join this event (if not already registered). ' + 'You will then be mixed up into one team.', misc_notes_help: 'Optional, for any further notes. These notes will only be visible to the organizer of the event.', mealspecifics_summary_text: 'You have entered the following eating habits', dinner_event_not_found_text: 'No dinner event found for this URL!', dinner_event_deadline_text: 'Registration deadline is on {{ endOfRegistrationDate }}.', goto_registration: 'Open Registration', data_processing_acknowledge: 'I aggree that my data will be processed.', data_processing_acknowledge_hint: 'The <a href="{{ privacyLink }}" target="_blank" class="actionlink">Privacy Statement (DE)</a> contains further information.', notification_demo_no_registration_text: 'This is just a demo event and no "real" event. A registration for testing purposes is possible, but will have no effect.', public_dinner_events_headline: 'Public Running Dinner Events', public_dinner_events_empty_text: 'Currently there exist no public running dinner events. You can change this issue by organzing one by yourself.', public_dinner_events_empty_headline: 'No events found', public_dinner_events_empty_goto_wizard: 'Goto creation wizard', for_organizers_headline: 'For Organizers', create_event_headline: 'Create your own event', create_event_description: 'Create stupid simply your own (private) Running Dinner event - without the need of a registration!<br>' + 'You decide whether the event is completely public or whether it is only visible for your private friends.', manage_event_headline: 'Manage Event', manage_event_description: 'After creation of your running dinner event, almost anything is automatically performed by the application.\n' + 'All processes like e.g. creating team arrangements or dinner route calculation is done with help of the application.\n' + 'Nevertheless you can all the time interfere like e.g. changing team arrangements to fit your purposes.', manage_event_link: 'Features for Event Management', manage_event_party_headline: 'Just run the event &amp; enjoy', manage_event_party_description: 'All those cumbersome and complicated work for organzing a running dinner event is completely removed from you, ' + 'like e.g. sending personalized emails to your participants / teams.<br/>' + 'The responsibility for the whole event per se is however still at you.<br><br>Have fun!', for_participants_headline: 'For Participants', discover_public_events_headline: 'Discover Public Events', discover_public_events_description: 'Find public events close to you and registrate straightforward! ' + 'You don\'t need to registrate on this platform, you just registrate directly to the event of the organizer.', discover_public_events_link: 'Find public event...', public_events_no_event_found_headline: 'No public event found?', public_events_no_event_found_description: 'Most events are closed and/or private.<br>' + 'If there is an event in your circle of friends and acquainrances, you will likely receive a secret link for registration (e.g. by mail, facebook, ...), ' + 'or maybe you were already added as participant.<br>If you received such a link, you can use this link for opening the event.', privacy_question_headline: 'What happens with my data?', privacy_question_description: 'You don\'t need to register to the platform itself, you just need to register to a specific event on which you want to participate.<br> ' + 'Therefore you must obviously provide some personal data. This data is however only visible for the event organizer and ' + 'will be automatically deleted after the event end.', privacy_more_infos_link: 'More infos about privacy', teaser_what_is_running_dinner_headline: 'What is a Running Dinner?', teaser_running_dinner_general_description: 'The concept of a running dinner is also known under the german name "rudirockt - Kochen und Kontakte knüpfen" and was awarded several times ' + '(see also <a class="jumbotron-link" href="https://www.wikipedia.de/" target="_blank">Wikipedia</a>).<br>' + 'It is also known under the names Flying Dinner or Jumping Dinner.', teaser_running_dinner_general_application: 'With <strong>runyourdinner</strong> you can organize your own running dinner event as a no-brainer. ' + 'Alternatively you can participate in a public running dinner event located next to you.', teaser_organize_event_text: 'Create Event', teaser_search_public_event_text: 'Find Public Event', teaser_how_does_it_work: 'How does it work?', teaser_workflow_team_generation: 'After registration deadline all participants will be mixed up into 2er teams.', teaser_workflow_team_meals: 'Each team gets notified about which meal (appetizer, main course, dessert) it has the responsibility to cook.', teaser_workflow_team_host: 'The assigned meal is cooked in the flat of one team member.', teaser_workflow_team_guest: 'Two other teams join this meal as a guest (thus each team cooks for 6 persons total).', teaser_workflow_dinner_route: 'After you are finished with eating the meal, you will move on to another team, till all meals are taken.', teaser_workflow_dinner_route_finish: 'At the end of the event, each team has met 8 other teams.', teaser_example_appetizer: 'The appetizer is cooked in the own flat of one team member. Here two other teams join this meal.', teaser_example_main_course: 'After you are finished with eating, you have to hurry to the next flat of another team. ' + 'Here you will meet two other teams, the host team and another guest team.<br>' + 'This time you are the guest and you will eat the main course of the host team.', teaser_example_dessert: 'The same applies to the dessert.', teaser_example_summary: 'Consequently each meal will be eaten with different teams, thus each team will meet 12 other people during the event. ' + 'Hopefully no team knows who will join them as a guest team ' + 'and furthermore each team should only know the addresses of the teams they will visit.', create_your_own_event_hedline: 'Create your own running dinner event', quickstart_description: 'You can create your own running dinner event with just a few clicks by using the wizard.', uncertain_headline: 'Having doubts?', uncertain_description: 'You can also create a demo running dinner event for test purposes. ' + 'This event will automatically be populated with example participants. So you can test all features before starting with a "real" running dinner event.', create_demo_dinner_link: 'Create Demo Dinner', visibilities_text: 'Choose between 3 different kinds of visibility', team_arrangements_meal_feature: 'Automatic team arrangement generation and meal assignment', team_arrangements_distribution_feature: 'Random team arrangement distribution or by specific criteria (e.g. gender)', team_arrangements_swap_feature: 'Comfortable changes of team arrangements possible by drag & drop', dinner_route_calculation_feature: 'Optimal calculation of dinner routes', dinner_route_view_feature: 'View of dinner routes', dinner_route_googlemaps_feature: 'Google-Maps Integration', mail_sending_personalized: 'Personalized sending of mails', mail_sending_personalized_description: 'Simple and customizable way for sending individual mails to your participants / teams.', mail_sending_personalized_participants: 'Mails to participants', mail_sending_personalized_teams: 'Mails for team arrangements', mail_sending_personalized_dinnerroutes: 'Mails for Dinner-Routes', participant_management_headline: 'Manage Participants', participant_management_crud_feature: 'Add / edit / delete participant', participant_management_overview_feature: 'Simple overview of all participants', participant_management_waitinglist_feature: 'Waiting list function', participant_features: 'Participant Features', participant_feature_self_registrate: 'Self registrate to non-closed events', participant_feature_change_host: 'Team can change the host assignment by themself', participant_feature_live_dinnerroute: 'Live view of dinner route', misc_feature_dashboard: 'Dashboard with activity stream, checklist, etc.', misc_feature_new_participants: 'See new registrations at once', misc_feature_cancel_teams: 'Handling of cancellations of teams / participants', misc_feature_team_partner_wish: 'Handling of partner wish', misc_feature_languages: 'Available in English and German language', start_title: 'Application for calculating and performing running dinner events', registration_finished_title: 'Registration completed', registration_confirm_title: 'Confirm registration', create_wizard_title: 'Create and Manage your own Running Dinner', impressum_title: 'Impressum & Privacy', x: 'x' }); })(angular);
{'content_hash': '5dae65fc9873fda26b705064b13f33ab', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 191, 'avg_line_length': 65.33684210526316, 'alnum_prop': 0.7296600612212019, 'repo_name': 'Clemens85/runningdinner', 'id': 'efece0796b7c069af77c19c3bf02595f203343bb', 'size': '12415', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'runningdinner-backend/src/main/client/js/frontend/constants/FrontendMessages_lang_en.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '9964'}, {'name': 'HTML', 'bytes': '220884'}, {'name': 'Java', 'bytes': '1059912'}, {'name': 'JavaScript', 'bytes': '915942'}, {'name': 'Less', 'bytes': '18959'}, {'name': 'Shell', 'bytes': '3096'}, {'name': 'TypeScript', 'bytes': '656882'}]}
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/cert/internal/trust_store_nss.h" #include <cert.h> #include <certdb.h> #include "base/memory/ptr_util.h" #include "crypto/nss_util.h" #include "net/cert/internal/cert_errors.h" #include "net/cert/internal/parsed_certificate.h" // TODO(mattm): structure so that supporting ChromeOS multi-profile stuff is // doable (Have a TrustStoreChromeOS which uses net::NSSProfileFilterChromeOS, // similar to CertVerifyProcChromeOS.) namespace net { TrustStoreNSS::TrustStoreNSS(SECTrustType trust_type) : trust_type_(trust_type) {} TrustStoreNSS::~TrustStoreNSS() = default; void TrustStoreNSS::FindTrustAnchorsForCert( const scoped_refptr<ParsedCertificate>& cert, TrustAnchors* out_anchors) const { crypto::EnsureNSSInit(); SECItem name; // Use the original issuer value instead of the normalized version. NSS does a // less extensive normalization in its Name comparisons, so our normalized // version may not match the unnormalized version. name.len = cert->tbs().issuer_tlv.Length(); name.data = const_cast<uint8_t*>(cert->tbs().issuer_tlv.UnsafeData()); // |validOnly| in CERT_CreateSubjectCertList controls whether to return only // certs that are valid at |sorttime|. Expiration isn't meaningful for trust // anchors, so request all the matches. CERTCertList* found_certs = CERT_CreateSubjectCertList( nullptr /* certList */, CERT_GetDefaultCertDB(), &name, PR_Now() /* sorttime */, PR_FALSE /* validOnly */); if (!found_certs) return; for (CERTCertListNode* node = CERT_LIST_HEAD(found_certs); !CERT_LIST_END(node, found_certs); node = CERT_LIST_NEXT(node)) { CERTCertTrust trust; if (CERT_GetCertTrust(node->cert, &trust) != SECSuccess) continue; // TODO(mattm): handle explicit distrust (blacklisting)? const int ca_trust = CERTDB_TRUSTED_CA; if ((SEC_GET_TRUST_FLAGS(&trust, trust_type_) & ca_trust) != ca_trust) continue; CertErrors errors; scoped_refptr<ParsedCertificate> anchor_cert = ParsedCertificate::Create( node->cert->derCert.data, node->cert->derCert.len, {}, &errors); if (!anchor_cert) { // TODO(crbug.com/634443): return errors better. LOG(ERROR) << "Error parsing issuer certificate:\n" << errors.ToDebugString(); continue; } out_anchors->push_back(TrustAnchor::CreateFromCertificateNoConstraints( std::move(anchor_cert))); } CERT_DestroyCertList(found_certs); } } // namespace net
{'content_hash': '39a35e38b02ddd27baa52afd3d7cc614', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 80, 'avg_line_length': 36.43835616438356, 'alnum_prop': 0.7037593984962406, 'repo_name': 'google-ar/WebARonARCore', 'id': 'dd214dca4cf6efdb3501cef6327e4e79baf8a4d6', 'size': '2660', 'binary': False, 'copies': '2', 'ref': 'refs/heads/webarcore_57.0.2987.5', 'path': 'net/cert/internal/trust_store_nss.cc', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package com.treasure_data.model; public class DeleteTableResult extends TableSpecifyResult<Table> { public DeleteTableResult(Database database, String tableName) { super(new Table(database, tableName)); } }
{'content_hash': '4a02dd0ed11f9dd07874c832cb063521', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 67, 'avg_line_length': 28.125, 'alnum_prop': 0.7511111111111111, 'repo_name': 'xerial/td-client-java', 'id': '6e840cb311534d7515011995cf1e9acd5e03473c', 'size': '910', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/treasure_data/model/DeleteTableResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '494520'}]}
package com.graphhopper.routing.util; import com.graphhopper.reader.Way; /** * Specifies the settings for cycletouring/trekking * <p/> * @author ratrun * @author Peter Karich */ public class BikeFlagEncoder extends BikeCommonFlagEncoder { public BikeFlagEncoder() { this(4, 2, 0); } public BikeFlagEncoder( String propertiesStr ) { this((int) parseLong(propertiesStr, "speedBits", 4), parseDouble(propertiesStr, "speedFactor", 2), parseBoolean(propertiesStr, "turnCosts", false) ? 3 : 0); this.setBlockFords(parseBoolean(propertiesStr, "blockFords", true)); } public BikeFlagEncoder( int speedBits, double speedFactor, int maxTurnCosts ) { super(speedBits, speedFactor, maxTurnCosts); addPushingSection("path"); addPushingSection("footway"); addPushingSection("pedestrian"); addPushingSection("steps"); avoidHighwayTags.add("trunk"); avoidHighwayTags.add("trunk_link"); avoidHighwayTags.add("primary"); avoidHighwayTags.add("primary_link"); avoidHighwayTags.add("secondary"); avoidHighwayTags.add("secondary_link"); // preferHighwayTags.add("road"); preferHighwayTags.add("service"); preferHighwayTags.add("tertiary"); preferHighwayTags.add("tertiary_link"); preferHighwayTags.add("residential"); preferHighwayTags.add("unclassified"); } @Override boolean isPushingSection( Way way ) { String highway = way.getTag("highway"); String trackType = way.getTag("tracktype"); return way.hasTag("highway", pushingSections) || way.hasTag("railway", "platform") || "track".equals(highway) && trackType != null && !"grade1".equals(trackType); } @Override public String toString() { return "bike"; } }
{'content_hash': '5036826d10fd757d12fbae63dbd312fa', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 95, 'avg_line_length': 29.676923076923078, 'alnum_prop': 0.6303784344219803, 'repo_name': 'engaric/graphhopper', 'id': 'ad916cc0184e4d1200387a1bcd133b69bc62eba8', 'size': '2743', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/graphhopper/routing/util/BikeFlagEncoder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '29019'}, {'name': 'Gherkin', 'bytes': '257135'}, {'name': 'HTML', 'bytes': '18540'}, {'name': 'Java', 'bytes': '2928898'}, {'name': 'JavaScript', 'bytes': '376593'}, {'name': 'Shell', 'bytes': '23743'}]}