text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
""" ================================================== Multiclass Receiver Operating Characteristic (ROC) ================================================== This example describes the use of the Receiver Operating Characteristic (ROC) metric to evaluate the quality of multiclass classifiers. ROC curves typically feature true positive rate (TPR) on the Y axis, and false positive rate (FPR) on the X axis. This means that the top left corner of the plot is the "ideal" point - a FPR of zero, and a TPR of one. This is not very realistic, but it does mean that a larger area under the curve (AUC) is usually better. The "steepness" of ROC curves is also important, since it is ideal to maximize the TPR while minimizing the FPR. ROC curves are typically used in binary classification, where the TPR and FPR can be defined unambiguously. In the case of multiclass classification, a notion of TPR or FPR is obtained only after binarizing the output. This can be done in 2 different ways: - the One-vs-Rest scheme compares each class against all the others (assumed as one); - the One-vs-One scheme compares every unique pairwise combination of classes. In this example we explore both schemes and demo the concepts of micro and macro averaging as different ways of summarizing the information of the multiclass ROC curves. .. note:: See :ref:`sphx_glr_auto_examples_model_selection_plot_roc_crossval.py` for an extension of the present example estimating the variance of the ROC curves and their respective AUC. """ # %% # Load and prepare data # ===================== # # We import the :ref:`iris_dataset` which contains 3 classes, each one # corresponding to a type of iris plant. One class is linearly separable from # the other 2; the latter are **not** linearly separable from each other. # # Here we binarize the output and add noisy features to make the problem harder. import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split iris = load_iris() target_names = iris.target_names X, y = iris.data, iris.target y = iris.target_names[y] random_state = np.random.RandomState(0) n_samples, n_features = X.shape n_classes = len(np.unique(y)) X = np.concatenate([X, random_state.randn(n_samples, 200 * n_features)], axis=1) ( X_train, X_test, y_train, y_test, ) = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0) # %% # We train a :class:`~sklearn.linear_model.LogisticRegression` model which can # naturally handle multiclass problems, thanks to the use of the multinomial # formulation. from sklearn.linear_model import LogisticRegression classifier = LogisticRegression() y_score = classifier.fit(X_train, y_train).predict_proba(X_test) # %% # One-vs-Rest multiclass ROC # ========================== # # The One-vs-the-Rest (OvR) multiclass strategy, also known as one-vs-all, # consists in computing a ROC curve per each of the `n_classes`. In each step, a # given class is regarded as the positive class and the remaining classes are # regarded as the negative class as a bulk. # # .. note:: One should not confuse the OvR strategy used for the **evaluation** # of multiclass classifiers with the OvR strategy used to **train** a # multiclass classifier by fitting a set of binary classifiers (for instance # via the :class:`~sklearn.multiclass.OneVsRestClassifier` meta-estimator). # The OvR ROC evaluation can be used to scrutinize any kind of classification # models irrespectively of how they were trained (see :ref:`multiclass`). # # In this section we use a :class:`~sklearn.preprocessing.LabelBinarizer` to # binarize the target by one-hot-encoding in a OvR fashion. This means that the # target of shape (`n_samples`,) is mapped to a target of shape (`n_samples`, # `n_classes`). from sklearn.preprocessing import LabelBinarizer label_binarizer = LabelBinarizer().fit(y_train) y_onehot_test = label_binarizer.transform(y_test) y_onehot_test.shape # (n_samples, n_classes) # %% # We can as well easily check the encoding of a specific class: label_binarizer.transform(["virginica"]) # %% # ROC curve showing a specific class # ---------------------------------- # # In the following plot we show the resulting ROC curve when regarding the iris # flowers as either "virginica" (`class_id=2`) or "non-virginica" (the rest). class_of_interest = "virginica" class_id = np.flatnonzero(label_binarizer.classes_ == class_of_interest)[0] class_id # %% import matplotlib.pyplot as plt from sklearn.metrics import RocCurveDisplay RocCurveDisplay.from_predictions( y_onehot_test[:, class_id], y_score[:, class_id], name=f"{class_of_interest} vs the rest", color="darkorange", ) plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)") plt.axis("square") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("One-vs-Rest ROC curves:\nVirginica vs (Setosa & Versicolor)") plt.legend() plt.show() # %% # ROC curve using micro-averaged OvR # ---------------------------------- # # Micro-averaging aggregates the contributions from all the classes (using # :func:`np.ravel`) to compute the average metrics as follows: # # :math:`TPR=\frac{\sum_{c}TP_c}{\sum_{c}(TP_c + FN_c)}` ; # # :math:`FPR=\frac{\sum_{c}FP_c}{\sum_{c}(FP_c + TN_c)}` . # # We can briefly demo the effect of :func:`np.ravel`: print(f"y_score:\n{y_score[0:2,:]}") print() print(f"y_score.ravel():\n{y_score[0:2,:].ravel()}") # %% # In a multi-class classification setup with highly imbalanced classes, # micro-averaging is preferable over macro-averaging. In such cases, one can # alternatively use a weighted macro-averaging, not demoed here. RocCurveDisplay.from_predictions( y_onehot_test.ravel(), y_score.ravel(), name="micro-average OvR", color="darkorange", ) plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)") plt.axis("square") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Micro-averaged One-vs-Rest\nReceiver Operating Characteristic") plt.legend() plt.show() # %% # In the case where the main interest is not the plot but the ROC-AUC score # itself, we can reproduce the value shown in the plot using # :class:`~sklearn.metrics.roc_auc_score`. from sklearn.metrics import roc_auc_score micro_roc_auc_ovr = roc_auc_score( y_test, y_score, multi_class="ovr", average="micro", ) print(f"Micro-averaged One-vs-Rest ROC AUC score:\n{micro_roc_auc_ovr:.2f}") # %% # This is equivalent to computing the ROC curve with # :class:`~sklearn.metrics.roc_curve` and then the area under the curve with # :class:`~sklearn.metrics.auc` for the raveled true and predicted classes. from sklearn.metrics import roc_curve, auc # store the fpr, tpr, and roc_auc for all averaging strategies fpr, tpr, roc_auc = dict(), dict(), dict() # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_onehot_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) print(f"Micro-averaged One-vs-Rest ROC AUC score:\n{roc_auc['micro']:.2f}") # %% # .. note:: By default, the computation of the ROC curve adds a single point at # the maximal false positive rate by using linear interpolation and the # McClish correction [:doi:`Analyzing a portion of the ROC curve Med Decis # Making. 1989 Jul-Sep; 9(3):190-5.<10.1177/0272989x8900900307>`]. # # ROC curve using the OvR macro-average # ------------------------------------- # # Obtaining the macro-average requires computing the metric independently for # each class and then taking the average over them, hence treating all classes # equally a priori. We first aggregate the true/false positive rates per class: for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_onehot_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i]) fpr_grid = np.linspace(0.0, 1.0, 1000) # Interpolate all ROC curves at these points mean_tpr = np.zeros_like(fpr_grid) for i in range(n_classes): mean_tpr += np.interp(fpr_grid, fpr[i], tpr[i]) # linear interpolation # Average it and compute AUC mean_tpr /= n_classes fpr["macro"] = fpr_grid tpr["macro"] = mean_tpr roc_auc["macro"] = auc(fpr["macro"], tpr["macro"]) print(f"Macro-averaged One-vs-Rest ROC AUC score:\n{roc_auc['macro']:.2f}") # %% # This computation is equivalent to simply calling macro_roc_auc_ovr = roc_auc_score( y_test, y_score, multi_class="ovr", average="macro", ) print(f"Macro-averaged One-vs-Rest ROC AUC score:\n{macro_roc_auc_ovr:.2f}") # %% # Plot all OvR ROC curves together # -------------------------------- from itertools import cycle fig, ax = plt.subplots(figsize=(6, 6)) plt.plot( fpr["micro"], tpr["micro"], label=f"micro-average ROC curve (AUC = {roc_auc['micro']:.2f})", color="deeppink", linestyle=":", linewidth=4, ) plt.plot( fpr["macro"], tpr["macro"], label=f"macro-average ROC curve (AUC = {roc_auc['macro']:.2f})", color="navy", linestyle=":", linewidth=4, ) colors = cycle(["aqua", "darkorange", "cornflowerblue"]) for class_id, color in zip(range(n_classes), colors): RocCurveDisplay.from_predictions( y_onehot_test[:, class_id], y_score[:, class_id], name=f"ROC curve for {target_names[class_id]}", color=color, ax=ax, ) plt.plot([0, 1], [0, 1], "k--", label="ROC curve for chance level (AUC = 0.5)") plt.axis("square") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\nto One-vs-Rest multiclass") plt.legend() plt.show() # %% # One-vs-One multiclass ROC # ========================= # # The One-vs-One (OvO) multiclass strategy consists in fitting one classifier # per class pair. Since it requires to train `n_classes` * (`n_classes` - 1) / 2 # classifiers, this method is usually slower than One-vs-Rest due to its # O(`n_classes` ^2) complexity. # # In this section, we demonstrate the macro-averaged AUC using the OvO scheme # for the 3 possible combinations in the :ref:`iris_dataset`: "setosa" vs # "versicolor", "versicolor" vs "virginica" and "virginica" vs "setosa". Notice # that micro-averaging is not defined for the OvO scheme. # # ROC curve using the OvO macro-average # ------------------------------------- # # In the OvO scheme, the first step is to identify all possible unique # combinations of pairs. The computation of scores is done by treating one of # the elements in a given pair as the positive class and the other element as # the negative class, then re-computing the score by inversing the roles and # taking the mean of both scores. from itertools import combinations pair_list = list(combinations(np.unique(y), 2)) print(pair_list) # %% pair_scores = [] mean_tpr = dict() for ix, (label_a, label_b) in enumerate(pair_list): a_mask = y_test == label_a b_mask = y_test == label_b ab_mask = np.logical_or(a_mask, b_mask) a_true = a_mask[ab_mask] b_true = b_mask[ab_mask] idx_a = np.flatnonzero(label_binarizer.classes_ == label_a)[0] idx_b = np.flatnonzero(label_binarizer.classes_ == label_b)[0] fpr_a, tpr_a, _ = roc_curve(a_true, y_score[ab_mask, idx_a]) fpr_b, tpr_b, _ = roc_curve(b_true, y_score[ab_mask, idx_b]) mean_tpr[ix] = np.zeros_like(fpr_grid) mean_tpr[ix] += np.interp(fpr_grid, fpr_a, tpr_a) mean_tpr[ix] += np.interp(fpr_grid, fpr_b, tpr_b) mean_tpr[ix] /= 2 mean_score = auc(fpr_grid, mean_tpr[ix]) pair_scores.append(mean_score) fig, ax = plt.subplots(figsize=(6, 6)) plt.plot( fpr_grid, mean_tpr[ix], label=f"Mean {label_a} vs {label_b} (AUC = {mean_score :.2f})", linestyle=":", linewidth=4, ) RocCurveDisplay.from_predictions( a_true, y_score[ab_mask, idx_a], ax=ax, name=f"{label_a} as positive class", ) RocCurveDisplay.from_predictions( b_true, y_score[ab_mask, idx_b], ax=ax, name=f"{label_b} as positive class", ) plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)") plt.axis("square") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title(f"{target_names[idx_a]} vs {label_b} ROC curves") plt.legend() plt.show() print(f"Macro-averaged One-vs-One ROC AUC score:\n{np.average(pair_scores):.2f}") # %% # One can also assert that the macro-average we computed "by hand" is equivalent # to the implemented `average="macro"` option of the # :class:`~sklearn.metrics.roc_auc_score` function. macro_roc_auc_ovo = roc_auc_score( y_test, y_score, multi_class="ovo", average="macro", ) print(f"Macro-averaged One-vs-One ROC AUC score:\n{macro_roc_auc_ovo:.2f}") # %% # Plot all OvO ROC curves together # -------------------------------- ovo_tpr = np.zeros_like(fpr_grid) fig, ax = plt.subplots(figsize=(6, 6)) for ix, (label_a, label_b) in enumerate(pair_list): ovo_tpr += mean_tpr[ix] plt.plot( fpr_grid, mean_tpr[ix], label=f"Mean {label_a} vs {label_b} (AUC = {pair_scores[ix]:.2f})", ) ovo_tpr /= sum(1 for pair in enumerate(pair_list)) plt.plot( fpr_grid, ovo_tpr, label=f"One-vs-One macro-average (AUC = {macro_roc_auc_ovo:.2f})", linestyle=":", linewidth=4, ) plt.plot([0, 1], [0, 1], "k--", label="chance level (AUC = 0.5)") plt.axis("square") plt.xlabel("False Positive Rate") plt.ylabel("True Positive Rate") plt.title("Extension of Receiver Operating Characteristic\nto One-vs-One multiclass") plt.legend() plt.show() # %% # We confirm that the classes "versicolor" and "virginica" are not well # identified by a linear classifier. Notice that the "virginica"-vs-the-rest # ROC-AUC score (0.77) is between the OvO ROC-AUC scores for "versicolor" vs # "virginica" (0.64) and "setosa" vs "virginica" (0.90). Indeed, the OvO # strategy gives additional information on the confusion between a pair of # classes, at the expense of computational cost when the number of classes # is large. # # The OvO strategy is recommended if the user is mainly interested in correctly # identifying a particular class or subset of classes, whereas evaluating the # global performance of a classifier can still be summarized via a given # averaging strategy. # # Micro-averaged OvR ROC is dominated by the more frequent class, since the # counts are pooled. The macro-averaged alternative better reflects the # statistics of the less frequent classes, and then is more appropriate when # performance on all the classes is deemed equally important.
{'content_hash': 'e83637930c554c8b2ad04c6ae878d68a', 'timestamp': '', 'source': 'github', 'line_count': 441, 'max_line_length': 86, 'avg_line_length': 33.31065759637188, 'alnum_prop': 0.6757658270932607, 'repo_name': 'betatim/scikit-learn', 'id': 'e47d283e3e7834eedca8cf4de40fb750537cfe38', 'size': '14690', 'binary': False, 'copies': '4', 'ref': 'refs/heads/main', 'path': 'examples/model_selection/plot_roc.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '42335'}, {'name': 'C++', 'bytes': '147316'}, {'name': 'Cython', 'bytes': '668499'}, {'name': 'Makefile', 'bytes': '1644'}, {'name': 'Python', 'bytes': '10504881'}, {'name': 'Shell', 'bytes': '41551'}]}
package org.apache.oodt.cas.pushpull.filerestrictions.parsers; // JUnit static imports import static org.junit.Assert.assertThat; // JDK imports import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.net.URISyntaxException; import java.util.List; import org.apache.oodt.cas.metadata.Metadata; // OODT imports import org.apache.oodt.cas.pushpull.exceptions.ParserException; import org.apache.oodt.cas.pushpull.filerestrictions.FileRestrictions; import org.apache.oodt.cas.pushpull.filerestrictions.VirtualFileStructure; // JUnit imports import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * Test class for {@link GenericEmailParser}. * * @author [email protected] (Brian Foster) */ @RunWith(JUnit4.class) public class GenericEmailParserTest { private File emailFile; @Before public void setUp() throws URISyntaxException { emailFile = new File(ClassLoader.getSystemResource("TestEmail.txt").toURI()); } @Test public void testGenericEmailParser() throws ParserException, FileNotFoundException { GenericEmailParser parser = new GenericEmailParser( "Wav File: ([^\\s]+)", "Dear Lousy Customer,", null); VirtualFileStructure vfs = parser.parse(new FileInputStream(emailFile), new Metadata()); List<String> filePaths = FileRestrictions.toStringList(vfs.getRootVirtualFile()); assertThat(filePaths.size(), Matchers.is(1)); assertThat(filePaths.get(0), Matchers.is("/some/path/to/a/wav/file.wav")); } @Test (expected = ParserException.class) public void testFailedValidEmailCheck() throws ParserException, FileNotFoundException { GenericEmailParser parser = new GenericEmailParser( "Wav File: ([^\\s]+)", "Phrase Not Found", null); parser.parse(new FileInputStream(emailFile), new Metadata()); } }
{'content_hash': '8acb3c3de828d378d39c5ae7e5faf709', 'timestamp': '', 'source': 'github', 'line_count': 60, 'max_line_length': 92, 'avg_line_length': 31.983333333333334, 'alnum_prop': 0.7592496091714435, 'repo_name': 'LeStarch/oodt', 'id': 'e098c878ae71a8a1304acf66dec5085e56eb314e', 'size': '2720', 'binary': False, 'copies': '4', 'ref': 'refs/heads/trunk', 'path': 'pushpull/src/test/org/apache/oodt/cas/pushpull/filerestrictions/parsers/GenericEmailParserTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ApacheConf', 'bytes': '2030'}, {'name': 'C++', 'bytes': '22622'}, {'name': 'CSS', 'bytes': '130561'}, {'name': 'HTML', 'bytes': '105622'}, {'name': 'Java', 'bytes': '7509195'}, {'name': 'JavaScript', 'bytes': '189227'}, {'name': 'Makefile', 'bytes': '1135'}, {'name': 'PHP', 'bytes': '432498'}, {'name': 'PLSQL', 'bytes': '3736'}, {'name': 'Perl', 'bytes': '4459'}, {'name': 'Python', 'bytes': '131018'}, {'name': 'Ruby', 'bytes': '4884'}, {'name': 'Scala', 'bytes': '1015'}, {'name': 'Shell', 'bytes': '108646'}, {'name': 'TeX', 'bytes': '862979'}, {'name': 'XSLT', 'bytes': '28584'}]}
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-4-8.js * @description Array.prototype.map - Side effects produced by step 2 are visible when an exception occurs */ function testcase() { var obj = { 0: 11, 1: 12 }; var accessed = false; Object.defineProperty(obj, "length", { get: function () { accessed = true; return 2; }, configurable: true }); try { Array.prototype.map.call(obj, null); return false; } catch (ex) { return ex instanceof TypeError && accessed; } } runTestCase(testcase);
{'content_hash': '164e548837f682ac95924f69a0cf423d', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 106, 'avg_line_length': 25.17241379310345, 'alnum_prop': 0.5287671232876713, 'repo_name': 'hnafar/jint', 'id': '7746b3e81c0abc132e1b5a9373a5b1a2d211ce85', 'size': '730', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'Jint.Tests.Ecma/TestCases/ch15/15.4/15.4.4/15.4.4.19/15.4.4.19-4-8.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '63'}, {'name': 'C#', 'bytes': '3889201'}, {'name': 'JavaScript', 'bytes': '11429348'}]}
import scala.reflect.runtime.universe._ // Originally composed to accommodate pull request feedback, this test has // uncovered a handful of bugs in FromJavaClassCompleter, namely: // * SI-7071 non-public ctors get lost // * SI-7072 inner classes are read incorrectly // I'm leaving the incorrect results of FromJavaClassCompleters in the check // file, so that we get notified when something changes there. package object foo { def testAll(): Unit = { test(typeOf[foo.PackagePrivateJavaClass].typeSymbol) test(typeOf[foo.PackagePrivateJavaClass].typeSymbol.companion) test(typeOf[foo.JavaClass_1].typeSymbol) test(typeOf[foo.JavaClass_1].typeSymbol.companion) } def test(sym: Symbol): Unit = { printSymbolDetails(sym) if (sym.isClass || sym.isModule) { sym.info.decls.toList.sortBy(_.name.toString) foreach test } } def printSymbolDetails(sym: Symbol): Unit = { def stableSignature(sym: Symbol) = sym.info match { case ClassInfoType(_, _, _) => "ClassInfoType(...)" case tpe => tpe.toString } println("============") println(s"sym = $sym, signature = ${stableSignature(sym)}, owner = ${sym.owner}") println(s"isPrivate = ${sym.isPrivate}") println(s"isProtected = ${sym.isProtected}") println(s"isPublic = ${sym.isPublic}") println(s"privateWithin = ${sym.privateWithin}") } } object Test extends dotty.runtime.LegacyApp { foo.testAll() }
{'content_hash': '04dd903571f66f061808a1688649ff51', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 85, 'avg_line_length': 34.214285714285715, 'alnum_prop': 0.6917188587334725, 'repo_name': 'VladimirNik/dotty', 'id': '891f8f6c2ee2f0dedbeb668e3f88252f88ca7a9a', 'size': '1437', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'tests/pending/run/t6989/Test_2.scala', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '195073'}, {'name': 'Scala', 'bytes': '6340826'}, {'name': 'Shell', 'bytes': '9455'}]}
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _DateTHead = require('./DateTHead'); var _DateTHead2 = _interopRequireDefault(_DateTHead); var _DateTBody = require('./DateTBody'); var _DateTBody2 = _interopRequireDefault(_DateTBody); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var DateTable = function (_React$Component) { (0, _inherits3['default'])(DateTable, _React$Component); function DateTable() { (0, _classCallCheck3['default'])(this, DateTable); return (0, _possibleConstructorReturn3['default'])(this, (DateTable.__proto__ || Object.getPrototypeOf(DateTable)).apply(this, arguments)); } (0, _createClass3['default'])(DateTable, [{ key: 'render', value: function render() { var props = this.props; var prefixCls = props.prefixCls; return _react2['default'].createElement( 'table', { className: prefixCls + '-table', cellSpacing: '0', role: 'grid' }, _react2['default'].createElement(_DateTHead2['default'], props), _react2['default'].createElement(_DateTBody2['default'], props) ); } }]); return DateTable; }(_react2['default'].Component); exports['default'] = DateTable; module.exports = exports['default'];
{'content_hash': '0c2c136cddf2632559e35cb181f5ec18', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 143, 'avg_line_length': 31.403225806451612, 'alnum_prop': 0.7015921931176169, 'repo_name': 'RisenEsports/RisenEsports.github.io', 'id': '8118026a0d7401854b05b6fa1a47570d71507879', 'size': '1947', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'Console/app/node_modules/rc-calendar/lib/date/DateTable.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '583'}, {'name': 'HTML', 'bytes': '8106'}, {'name': 'JavaScript', 'bytes': '25228'}]}
using System; using System.IO; using GroupDocs.Conversion.Options.Convert; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert MHT file into XLS format. /// For more details about MIME Encapsulation of Aggregate HTML (.mht) to Microsoft Excel Binary File Format (.xls) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-mht-to-xls /// </summary> internal static class ConvertMhtToXls { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "mht-converted-to.xls"); // Load the source MHT file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_MHT)) { SpreadsheetConvertOptions options = new SpreadsheetConvertOptions { Format = GroupDocs.Conversion.FileTypes.SpreadsheetFileType.Xls }; // Save converted XLS file converter.Convert(outputFile, options); } Console.WriteLine("\nConversion to xls completed successfully. \nCheck output in {0}", outputFolder); } } }
{'content_hash': '6fc1497bdc8c68e3dae84a9e7987afa3', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 171, 'avg_line_length': 43.03333333333333, 'alnum_prop': 0.6653756777691712, 'repo_name': 'groupdocsconversion/GroupDocs_Conversion_NET', 'id': '71294e25a5d96cebcdf6d85c74ae347edc073cb6', 'size': '1291', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToSpreadsheet/ConvertToXls/ConvertMhtToXls.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118'}, {'name': 'C#', 'bytes': '13615'}, {'name': 'HTML', 'bytes': '253055'}]}
namespace ash { // A test class for preparing the MultiUserContextMenu. class MultiUserContextMenuChromeOSTest : public ChromeAshTestBase { public: MultiUserContextMenuChromeOSTest() : fake_user_manager_(new FakeChromeUserManager), user_manager_enabler_(base::WrapUnique(fake_user_manager_)) {} MultiUserContextMenuChromeOSTest(const MultiUserContextMenuChromeOSTest&) = delete; MultiUserContextMenuChromeOSTest& operator=( const MultiUserContextMenuChromeOSTest&) = delete; void SetUp() override; void TearDown() override; protected: // Set up the test environment for this many windows. void SetUpForThisManyWindows(int windows); // Ensures there are |n| logged-in users. void SetLoggedInUsers(size_t n) { DCHECK_LE(fake_user_manager_->GetLoggedInUsers().size(), n); while (fake_user_manager_->GetLoggedInUsers().size() < n) { AccountId account_id = AccountId::FromUserEmail( base::StringPrintf("generated-user-%" PRIuS "@consumer.example.com", fake_user_manager_->GetLoggedInUsers().size())); fake_user_manager_->AddUser(account_id); fake_user_manager_->LoginUser(account_id); } } aura::Window* window() { return window_; } private: // A window which can be used for testing. aura::Window* window_; // Owned by |user_manager_enabler_|. FakeChromeUserManager* fake_user_manager_ = nullptr; user_manager::ScopedUserManager user_manager_enabler_; }; void MultiUserContextMenuChromeOSTest::SetUp() { ChromeAshTestBase::SetUp(); window_ = CreateTestWindowInShellWithId(0); window_->Show(); MultiUserWindowManagerHelper::CreateInstanceForTest( AccountId::FromUserEmail("a")); } void MultiUserContextMenuChromeOSTest::TearDown() { delete window_; MultiUserWindowManagerHelper::DeleteInstance(); ChromeAshTestBase::TearDown(); } // Check that an unowned window will never create a menu. TEST_F(MultiUserContextMenuChromeOSTest, UnownedWindow) { EXPECT_EQ(nullptr, CreateMultiUserContextMenu(window()).get()); // Add more users. SetLoggedInUsers(2); EXPECT_EQ(nullptr, CreateMultiUserContextMenu(window()).get()); } // Check that an owned window will never create a menu. TEST_F(MultiUserContextMenuChromeOSTest, OwnedWindow) { // Make the window owned and check that there is no menu (since only a single // user exists). MultiUserWindowManagerHelper::GetWindowManager()->SetWindowOwner( window(), AccountId::FromUserEmail("a")); EXPECT_EQ(nullptr, CreateMultiUserContextMenu(window()).get()); // After adding another user a menu should get created. { SetLoggedInUsers(2); std::unique_ptr<ui::MenuModel> menu = CreateMultiUserContextMenu(window()); ASSERT_TRUE(menu.get()); EXPECT_EQ(1u, menu.get()->GetItemCount()); } { SetLoggedInUsers(3); std::unique_ptr<ui::MenuModel> menu = CreateMultiUserContextMenu(window()); ASSERT_TRUE(menu.get()); EXPECT_EQ(2u, menu.get()->GetItemCount()); } } } // namespace ash
{'content_hash': '0428992318e4d1bffb59d67b0808877d', 'timestamp': '', 'source': 'github', 'line_count': 94, 'max_line_length': 79, 'avg_line_length': 32.308510638297875, 'alnum_prop': 0.7151794534079684, 'repo_name': 'chromium/chromium', 'id': '522456468e2d000adcbf2cbf6c3a9bf444ebdecd', 'size': '3968', 'binary': False, 'copies': '6', 'ref': 'refs/heads/main', 'path': 'chrome/browser/ui/ash/multi_user/multi_user_context_menu_chromeos_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
<refentry xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:src="http://nwalsh.com/xmlns/litprog/fragment" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="5.0" xml:id="chunk.separate.lots"> <refmeta> <refentrytitle>chunk.separate.lots</refentrytitle> <refmiscinfo class="other" otherclass="datatype">boolean</refmiscinfo> </refmeta> <refnamediv> <refname>chunk.separate.lots</refname> <refpurpose>Should each LoT be in its own separate chunk?</refpurpose> </refnamediv> <refsynopsisdiv> <src:fragment xml:id="chunk.separate.lots.frag"> <xsl:param name="chunk.separate.lots" select="0"/> </src:fragment> </refsynopsisdiv> <refsection><info><title>Description</title></info> <para>If non-zero, each of the ToC and LoTs (List of Examples, List of Figures, etc.) will be put in its own separate chunk. The title page includes generated links to each of the separate files. </para> <para> This feature depends on the <literal>chunk.tocs.and.lots</literal> parameter also being non-zero. </para> </refsection> </refentry>
{'content_hash': '90830b1926a51edec955a158b60ec7be', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 70, 'avg_line_length': 32.25, 'alnum_prop': 0.7200689061154177, 'repo_name': 'aabbassia-soat/git-scribe', 'id': 'd2f07469eba906c5bbfde6d853281f20056be6a8', 'size': '1161', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'docbook-xsl/params/chunk.separate.lots.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '360'}, {'name': 'CSS', 'bytes': '7762'}, {'name': 'HTML', 'bytes': '3251'}, {'name': 'Perl', 'bytes': '2756'}, {'name': 'Python', 'bytes': '9339'}, {'name': 'Ruby', 'bytes': '41321'}, {'name': 'Shell', 'bytes': '1261'}, {'name': 'XSLT', 'bytes': '5107632'}]}
package org.apache.ignite.ml.dataset.primitive; import java.io.Serializable; import java.util.Iterator; import org.apache.ignite.ml.dataset.PartitionDataBuilder; import org.apache.ignite.ml.dataset.UpstreamEntry; import org.apache.ignite.ml.environment.LearningEnvironment; import org.apache.ignite.ml.preprocessing.Preprocessor; import org.apache.ignite.ml.structures.LabeledVector; import org.apache.ignite.ml.tree.data.DecisionTreeData; /** * A partition {@code data} builder that makes {@link DecisionTreeData}. * * @param <K> Type of a key in <tt>upstream</tt> data. * @param <V> Type of a value in <tt>upstream</tt> data. * @param <C> Type of a partition <tt>context</tt>. * @param <CO> Typer of COordinate for vectorizer. */ public class FeatureMatrixWithLabelsOnHeapDataBuilder<K, V, C extends Serializable, CO extends Serializable> implements PartitionDataBuilder<K, V, C, FeatureMatrixWithLabelsOnHeapData> { /** Serial version uid. */ private static final long serialVersionUID = 6273736987424171813L; /** Function that extracts features and labels from an {@code upstream} data. */ private final Preprocessor<K, V> preprocessor; /** * Constructs a new instance of decision tree data builder. * * @param preprocessor Function that extracts features with labels from an {@code upstream} data. */ public FeatureMatrixWithLabelsOnHeapDataBuilder(Preprocessor<K, V> preprocessor) { this.preprocessor = preprocessor; } /** {@inheritDoc} */ @Override public FeatureMatrixWithLabelsOnHeapData build( LearningEnvironment env, Iterator<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, C ctx) { double[][] features = new double[Math.toIntExact(upstreamDataSize)][]; double[] labels = new double[Math.toIntExact(upstreamDataSize)]; int ptr = 0; while (upstreamData.hasNext()) { UpstreamEntry<K, V> entry = upstreamData.next(); LabeledVector<Double> labeledVector = preprocessor.apply(entry.getKey(), entry.getValue()); features[ptr] = labeledVector.features().asArray(); labels[ptr] = labeledVector.label(); ptr++; } return new FeatureMatrixWithLabelsOnHeapData(features, labels); } }
{'content_hash': '6198a3ec45cabfee842096ee5e007551', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 108, 'avg_line_length': 38.09836065573771, 'alnum_prop': 0.7030981067125646, 'repo_name': 'shroman/ignite', 'id': '8ab5da2baa0802dc11b1c23a58a683645047811f', 'size': '3126', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/ml/src/main/java/org/apache/ignite/ml/dataset/primitive/FeatureMatrixWithLabelsOnHeapDataBuilder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '61105'}, {'name': 'C', 'bytes': '5286'}, {'name': 'C#', 'bytes': '6232757'}, {'name': 'C++', 'bytes': '3683409'}, {'name': 'CSS', 'bytes': '281251'}, {'name': 'Dockerfile', 'bytes': '16027'}, {'name': 'Groovy', 'bytes': '15081'}, {'name': 'HTML', 'bytes': '822376'}, {'name': 'Java', 'bytes': '40680974'}, {'name': 'JavaScript', 'bytes': '1785625'}, {'name': 'M4', 'bytes': '21724'}, {'name': 'Makefile', 'bytes': '121296'}, {'name': 'PHP', 'bytes': '486991'}, {'name': 'PLpgSQL', 'bytes': '623'}, {'name': 'PowerShell', 'bytes': '13000'}, {'name': 'Python', 'bytes': '342274'}, {'name': 'Scala', 'bytes': '1011929'}, {'name': 'Shell', 'bytes': '615621'}, {'name': 'TSQL', 'bytes': '6130'}, {'name': 'TypeScript', 'bytes': '476855'}]}
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:kie="http://drools.org/schema/kie-spring" xsi:schemaLocation=" http://drools.org/schema/kie-spring http://drools.org/schema/kie-spring.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd "> <!-- Imports the KieBase and KieSessions from the classpath dependencies --> <kie:import /> <!-- Defined the server endpoint to create the cxf-rs consumer --> <cxf:rsServer id="rsServer" address="http://localhost:58001/rest" serviceClass="org.kie.jax.rs.CommandExecutorImpl"> <cxf:providers> <bean class="org.kie.jax.rs.CommandMessageBodyReader"/> </cxf:providers> </cxf:rsServer> <bean id="kiePolicy" class="org.kie.camel.component.KiePolicy" /> <camelContext id="camel" xmlns="http://camel.apache.org/schema/spring"> <route> <from uri="cxfrs://bean://rsServer"/> <policy ref="kiePolicy"> <unmarshal ref="xstream" /> <to uri="kie:ksession1" /> <marshal ref="xstream" /> </policy> </route> <route id="x1"> <from uri="direct://http"/> <policy ref="kiePolicy"> <to uri="cxfrs://http://localhost:58001/rest"/> </policy> </route> </camelContext> </beans>
{'content_hash': '6e4ab778153f711cae26ea3515f70fd2', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 115, 'avg_line_length': 41.07692307692308, 'alnum_prop': 0.6666666666666666, 'repo_name': 'chirino/fuse-bxms-integ', 'id': '6e3e360408110f15823f2431ad21f8f7a530c077', 'size': '2670', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'camel/kie-camel/src/test/resources/org/kie/camel/component/CxfRsSpringWithImport.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '892'}, {'name': 'HTML', 'bytes': '6607'}, {'name': 'Java', 'bytes': '1535739'}, {'name': 'Shell', 'bytes': '1177'}]}
require "testup/testcase" # class Sketchup::Face # http://www.sketchup.com/intl/en/en/developer/docs/ourdoc/face class TC_Sketchup_Face < TestUp::TestCase def setup start_with_empty_model end def teardown # ... end # ========================================================================== # # Local test utilities. # If any of these utilities are needed in other test cases they should be # moved to TestUp's utility library. def create_face entities = Sketchup.active_model.active_entities face = entities.add_face([0, 0, 0], [100, 0, 0], [100, 100, 0], [0, 100, 0]) face.reverse! face end def create_face_with_glued_instance face = create_face component = Sketchup.active_model.definitions.add("tester") point1 = [10, 10, 0] point2 = [20, 10, 0] point3 = [20, 20, 0] point4 = [10, 20, 0] inner_face = component.entities.add_face(point1, point2, point3, point4) component.behavior.is2d = true inner_face.pushpull(-20, true) instance = Sketchup.active_model.active_entities.add_instance( component, Geom::Transformation.new) instance.glued_to = face [face, instance] end def create_material path = Sketchup.temp_dir full_name = File.join(path, "temp_image.jpg") Sketchup.active_model.active_view.write_image( full_name, 500, 500, false, 0.0) material = Sketchup.active_model.materials.add("Test Material") material.texture = full_name material end def create_face_with_hole p1, p2, p3, p4 = [-1000, -1000, 0], [1000, -1000, 0], [1000, 1000,0], [-1000, 1000, 0] face1 = Sketchup.active_model.active_entities.add_face(p1, p2, p3, p4) face2 = create_face face1 end # ========================================================================== # # method Sketchup::Face.all_connected # http://www.sketchup.com/intl/en/en/developer/docs/ourdoc/face#all_connected def test_all_connected_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) connected = face.all_connected end def test_all_connected_return_type face = create_face connected = face.all_connected assert_kind_of(Array, connected) end def test_all_connected_return_length face = create_face connected = face.all_connected assert_equal(5, connected.size) end def test_all_connected_return_faces_length face = create_face connected = face.all_connected faces = connected.grep(Sketchup::Face) assert_equal(1, faces.size) end def test_all_connected_return_edges_length face = create_face connected = face.all_connected edges = connected.grep(Sketchup::Edge) assert_equal(4, edges.size) end def test_all_connected_return_validity face = create_face connected = face.all_connected assert(connected.all? { |entity| entity.valid? }) end def test_all_connected_return_parent face = create_face connected = face.all_connected assert(connected.all? { |entity| entity.parent == face.parent }, "Returned entities did not come from the correct parent.") end def test_all_connected_return_model face = create_face connected = face.all_connected assert(connected.all? { |entity| entity.model == face.model }, "Returned entities did not come from the correct model.") end def test_all_connected_arity assert_equal(0, Sketchup::Face.instance_method(:all_connected).arity) end def test_all_connected_incorrect_number_of_arguments face = create_face assert_raises(ArgumentError) do face.all_connected(1) end end # ========================================================================== # # method Sketchup::Face.area # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#area def test_area_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) area = face.area end def test_area_return_type face = create_face area = face.area assert_kind_of(Float, area) end def test_area_return_value face = create_face area = face.area assert_in_delta(10000.0, area, SKETCHUP_FLOAT_TOLERANCE) end def test_area_arity assert_equal(-1, Sketchup::Face.instance_method(:area).arity) end def test_area_invalid_arguments face = create_face assert_raises(TypeError) do face.area("String!") end assert_raises(ArgumentError) do face.area(["Array that is not a transformation matrix"], "An array that did not contain a Transformation Matrix was accepted as a valid argument") end assert_raises(TypeError) do face.area(false) end assert_raises(TypeError) do face.area(nil) end end def test_area_transformed face = create_face transform = Geom::Transformation.new( [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]) area = face.area(transform) assert_in_delta(2500.0, area, SKETCHUP_FLOAT_TOLERANCE) end def test_area_valid_argument_transformation_object face = create_face transform = Geom::Transformation.new( [0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]) area = face.area(transform) assert_kind_of(Float, area) end def test_area_valid_argument_array_transformation_matrix face = create_face area = face.area([0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 0.5, 0, 0, 0, 0, 1]) assert_kind_of(Float, area) end # ========================================================================== # # method Sketchup::Face.back_material # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#back_material def test_back_material_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) # Add a material to the back face, then check to see that it was added face.back_material = "red" material = face.back_material end def test_back_material_return_type face = create_face face.back_material = "red" result = face.back_material assert_kind_of(Sketchup::Material, result) end def test_back_material_arity assert_equal(0, Sketchup::Face.instance_method(:back_material).arity) end def test_back_material_invalid_arguments face = create_face assert_raises(ArgumentError) do face.back_material("String!") end assert_raises(ArgumentError) do face.back_material(["Array"]) end assert_raises(ArgumentError) do face.back_material(false) end assert_raises(ArgumentError) do face.back_material(nil) end end # ========================================================================== # # method Sketchup::Face.back_material= # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#back_material= def test_back_material_Set_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) status = face.back_material = "red" end def test_back_material_Set_Integer face = create_face result = face.back_material = 255 assert_kind_of(Integer, result) end def test_back_material_Set_HexInteger face = create_face result = face.back_material = 0xff assert_kind_of(Integer, result) end def test_back_material_Set_HexString face = create_face result = face.back_material = '#ff0000' assert_kind_of(String, result) end def test_back_material_Set_ArrayFloat face = create_face result = face.back_material = [1.0, 0.0, 0.0] assert_kind_of(Array, result) end def test_back_material_Set_ArrayInteger face = create_face result = face.back_material = [255, 0, 0] assert_kind_of(Array, result) end def test_back_material_Set_string face = create_face result = face.back_material = "red" assert_kind_of(String, result) end def test_back_material_Set_material_object face = create_face material = Sketchup.active_model.materials.add("Material") material.color = "red" result = face.back_material = (material) assert_kind_of(Sketchup::Material, result) end def test_back_material_Set_sketchupcolor face = create_face result = face.back_material = (Sketchup::Color.new("red")) assert_kind_of(Sketchup::Color, result) end def test_back_material_Set_arity assert_equal(1, Sketchup::Face.instance_method(:back_material=).arity) end def test_back_material_Set_invalid_arguments skip("Broken in SU2014") if Sketchup.version.to_i == 14 face = create_face #assert_raises(TypeError) do # face.back_material = nil #end assert_raises(ArgumentError) do face.back_material = "invalid color name" end assert_raises(ArgumentError) do face.back_material = ["Array"] end end # ========================================================================== # # method Sketchup::Face.classify_point # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#classify_point def test_classify_point_api_example model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [9, 0, 0] pts[2] = [9, 9, 0] pts[3] = [0, 9, 0] # Add the face to the entities in the model face = entities.add_face(pts) # Check a point that should be outside the face. pt = Geom::Point3d.new(50, 50, 0) result = face.classify_point(pt) if result == Sketchup::Face::PointOutside puts "#{pt.to_s} is outside the face" end # Check a point that should be outside inside the face. pt = Geom::Point3d.new(1, 1, 0) result = face.classify_point(pt) if result == Sketchup::Face::PointInside puts "#{pt.to_s} is inside the face" end # Check a point that should be on the vertex of the face. pt = Geom::Point3d.new(0, 0, 0) result = face.classify_point(pt) if result == Sketchup::Face::PointOnVertex puts "#{pt.to_s} is on a vertex" end # Check a point that should be on the edge of the face. pt = Geom::Point3d.new(0, 1, 0) result = face.classify_point(pt) if result == Sketchup::Face::PointOnEdge puts "#{pt.to_s} is on an edge of the face" end # Check a point that should be off the plane of the face. pt = Geom::Point3d.new(1, 1, 10) result = face.classify_point(pt) if result == Sketchup::Face::PointNotOnPlane puts "#{pt.to_s} is not on the same plane as the face" end end def test_classify_point_outside face = create_face # Check a point that should be outside the face. pt = Geom::Point3d.new(500, 500, 0) result = face.classify_point(pt) assert_equal(Sketchup::Face::PointOutside, result) end def test_classify_point_inside face = create_face # Check a point that should be inside the face. pt = Geom::Point3d.new(1, 1, 0) result = face.classify_point(pt) assert_equal(Sketchup::Face::PointInside, result) end def test_classify_point_on_vertex face = create_face # Check a point that should be on the vertex of the face. pt = Geom::Point3d.new(0, 0, 0) result = face.classify_point(pt) assert_equal(Sketchup::Face::PointOnVertex, result) end def test_classify_point_on_edge face = create_face # Check a point that should be on the edge of the face. pt = Geom::Point3d.new(1, 0, 0) result = face.classify_point(pt) assert_equal(Sketchup::Face::PointOnEdge, result) end def test_classify_point_off_plane face = create_face # Check a point that should be off the plane of the face. pt = Geom::Point3d.new(1, 1, 10) result = face.classify_point(pt) assert_equal(Sketchup::Face::PointNotOnPlane, result) end def test_classify_point_arity assert_equal(1, Sketchup::Face.instance_method(:classify_point).arity) end def test_classify_point_invalid_arguments face = create_face assert_raises(ArgumentError) do face.classify_point("Strings are not valid!") end assert_raises(ArgumentError) do face.classify_point(["Array"]) end assert_raises(ArgumentError) do face.classify_point(true) end assert_raises(ArgumentError) do face.classify_point(nil) end end # ========================================================================== # # method Sketchup::Face.edges # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#edges def test_edges_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) edges = face.edges end def test_edges_return_type face = create_face result = face.edges assert_kind_of(Array, result) end def test_edges_return_value face = create_face result = face.edges assert(result.all? { |entity| entity.is_a?(Sketchup::Edge) }, 'Not all entities returned were edges.') end def test_edges_return_array_length face = create_face result = face.edges assert_equal(result.length, 4) end def test_edges_arity assert_equal(0, Sketchup::Face.instance_method(:edges).arity) end def test_edges_invalid_arguments face = create_face assert_raises(ArgumentError) do face.edges("Strings are not valid!") end assert_raises(ArgumentError) do face.edges(["Can't use array"]) end assert_raises(ArgumentError) do face.edges(12) end assert_raises(ArgumentError) do face.edges(false) end assert_raises(ArgumentError) do face.edges(nil) end end # ========================================================================== # # method Sketchup::Face.followme # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#followme def test_followme_api_example model = Sketchup.active_model entities = model.active_entities point1 = Geom::Point3d.new(0, 0, 0) point2 = Geom::Point3d.new(0, 0, 100) depth = 100 width = 100 pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) # Add the line which we will "follow" to the entities in the model line = entities.add_line(point1, point2) status = face.followme(line) end def test_followme_edge_argument_result face = create_face point1 = Geom::Point3d.new(0, 0, 0) point2 = Geom::Point3d.new(0, 0, 100) edge = Sketchup.active_model.active_entities.add_edges(point1, point2) result = face.followme(edge) assert_kind_of(TrueClass, result) end def test_followme_edge_array_argument_result face = create_face point1 = Geom::Point3d.new(0, 0, 0) point2 = Geom::Point3d.new(0, 0, 100) point3 = Geom::Point3d.new(100, 0, 200) point4 = Geom::Point3d.new(200, 0, 200) edge1 = Sketchup.active_model.active_entities.add_edges(point1, point2) edge2 = Sketchup.active_model.active_entities.add_edges(point2, point3) edge3 = Sketchup.active_model.active_entities.add_edges(point3, point4) result = face.followme(edge1, edge2, edge3) assert_kind_of(TrueClass, result) end def test_followme_return_array_length face = create_face start_ents = Sketchup.active_model.active_entities.length point1 = Geom::Point3d.new(0, 0, 0) point2 = Geom::Point3d.new(0, 0, 100) edge = Sketchup.active_model.active_entities.add_edges(point1, point2) face.followme(edge) end_ents = Sketchup.active_model.active_entities.length total_added_ents = end_ents - start_ents assert_equal(13, total_added_ents) end def test_followme_arity assert_equal(-1, Sketchup::Face.instance_method(:followme).arity) end def test_followme_too_few_arguments face = create_face assert_raises(ArgumentError) do face.followme end end def test_followme_invalid_arguments face = create_face assert_raises(TypeError) do face.followme(["Can't use array"]) end #assert_raises(ArgumentError) do # face.followme(nil) #end end # ========================================================================== # # method Sketchup::Face.get_glued_instances # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#get_glued_instances def test_get_glued_instances_api_example # Create a series of points that define a new face. model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [9, 0, 0] pts[2] = [9, 9, 0] pts[3] = [0, 9, 0] # Add the face to the entities in the model face = entities.add_face(pts) glued_array = face.get_glued_instances end def test_get_glued_instances_result_type returned_array = create_face_with_glued_instance face = returned_array[0] glued_array = face.get_glued_instances assert_kind_of(Array, glued_array) end def test_get_glued_instances_return_array_length returned_array = create_face_with_glued_instance face = returned_array[0] glued_array = face.get_glued_instances assert_equal(1, glued_array.length) end def test_get_glued_instances_return_none_glued face = create_face glued_array = face.get_glued_instances assert_equal(0, glued_array.length) end def test_get_glued_instances_arity assert_equal(-1, Sketchup::Face.instance_method(:followme).arity) end def test_get_glued_instances_invalid_arguments face = create_face assert_raises(ArgumentError) do face.get_glued_instances(["Can't use array"]) end assert_raises(ArgumentError) do face.get_glued_instances(12) end assert_raises(ArgumentError) do face.get_glued_instances(false) end assert_raises(ArgumentError) do face.get_glued_instances(nil) end end # ========================================================================== # # method Sketchup::Face.get_texture_projection # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#get_texture_projection def test_get_texture_projection_api_example model = Sketchup.active_model entities = model.active_entities materials = model.materials # Create a face and add it to the model entities pts = [] pts[0] = [0, 0, 1] pts[1] = [10, 0, 1] pts[2] = [10, 10, 1] face = entities.add_face(pts) # Export an image to use as a texture path = Sketchup.temp_dir full_name = File.join(path, "temp_image.jpg") model.active_view.write_image(full_name, 500, 500, false, 0.0) # Create a material and assign the texture to it material = materials.add("Test Material") material.texture = full_name # Assign the new material to our face we created face.material = material # Set the projection of the applied material face.set_texture_projection(face.normal, true) # Get the projection of the applied material vector = face.get_texture_projection(true) end def test_get_texture_projection_return_type face = create_face material = create_material face.material = material vector = [rand, rand, rand] face.set_texture_projection(vector, true) result = face.get_texture_projection(true) assert_kind_of(Geom::Vector3d, result) end def test_get_texture_projection_back_face_return_type face = create_face material = create_material face.back_material = material vector = [rand, rand, rand] face.set_texture_projection(vector, false) result = face.get_texture_projection(false) assert_kind_of(Geom::Vector3d, result) end def test_get_texture_projection_given_vector_matched_returned_vector face = create_face material = create_material face.back_material = material vector = [rand, rand, rand] vector.normalize! face.set_texture_projection(vector, false) result = face.get_texture_projection(false) assert_equal(true, (result == vector), "Vector #{vector.to_s} was assigned to the projection, but #{result.to_s} was returned. They should compare equal.") end def test_get_texture_projection_return_no_material face = create_face assert_nil(face.get_texture_projection(true)) end def test_get_texture_projection_return_material_not_projected face = create_face material = create_material face.material = material assert_nil(face.get_texture_projection(true)) end def test_get_texture_projection_arity assert_equal(1, Sketchup::Face.instance_method( :get_texture_projection).arity) end #def test_get_texture_projection_invalid_arguments # No tests for invalid arguments, since no incorrect arguments are throwing # errors. We should consider adding better error handling for incorrect # arguments to most of the methods in this class. There are many arguments # that are allowed, even though they are wrong. #end # ========================================================================== # # method Sketchup::Face.get_UVHelper # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#get_UVHelper def test_get_UVHelper_api_example model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [9, 0, 0] pts[2] = [9, 9, 0] pts[3] = [0, 9, 0] # Add the face to the entities in the model face = entities.add_face(pts) tw = Sketchup.create_texture_writer uvHelp = face.get_UVHelper(true, true, tw) end def test_get_UVHelper_result_type_front_back face = create_face tw = Sketchup.create_texture_writer uvHelp = face.get_UVHelper(true, true, tw) assert_kind_of(Sketchup::UVHelper, uvHelp) end def test_get_UVHelper_result_type_front_only face = create_face tw = Sketchup.create_texture_writer uvHelp = face.get_UVHelper(true, false, tw) assert_kind_of(Sketchup::UVHelper, uvHelp) end def test_get_UVHelper_result_type_back_only face = create_face tw = Sketchup.create_texture_writer uvHelp = face.get_UVHelper(false, true, tw) assert_kind_of(Sketchup::UVHelper, uvHelp) end def test_get_UVHelper_result_no_params face = create_face uvHelp = face.get_UVHelper assert_kind_of(Sketchup::UVHelper, uvHelp) end def test_get_UVHelper_arity assert_equal(-1, Sketchup::Face.instance_method(:get_UVHelper).arity) end def test_get_UVHelper_invalid_arguments face = create_face assert_raises(TypeError) do face.get_UVHelper([1], [1], [1]) end assert_raises(TypeError) do face.get_UVHelper(nil, nil, nil) end assert_raises(TypeError) do face.get_UVHelper("st", "ri", "ng") end end # ========================================================================== # # method Sketchup::Face.loops # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#loops def test_loops_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) loops = face.loops end def test_loops_return_type face = create_face_with_hole result = face.loops assert_kind_of(Array, result) end def test_loops_return_value face = create_face_with_hole result = face.loops assert(result.all? { |entity| entity.is_a?(Sketchup::Loop) }, 'Not all entities returned were Loops.') end def test_loops_return_array_length face = create_face_with_hole result = face.loops assert_equal(result.length, 2) end def test_loops_arity assert_equal(0, Sketchup::Face.instance_method(:loops).arity) end def test_loops_invalid_arguments face = create_face_with_hole assert_raises(ArgumentError) do face.loops("Strings are not valid!") end assert_raises(ArgumentError) do face.loops(["Can't use array"]) end assert_raises(ArgumentError) do face.loops(12) end assert_raises(ArgumentError) do face.loops(false) end assert_raises(ArgumentError) do face.loops(nil) end end # ========================================================================== # # method Sketchup::Face.material # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#material def test_material_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) # Add a material to the back face, then check to see that it was added face.material = "red" material = face.material end def test_material face = create_face face.material = "red" result = face.material assert_kind_of(Sketchup::Material, result) end def test_material_arity assert_equal(0, Sketchup::Face.instance_method(:material).arity) end def test_material_invalid_arguments face = create_face assert_raises(ArgumentError) do face.material("String!") end assert_raises(ArgumentError) do face.material(["Array"]) end assert_raises(ArgumentError) do face.material(false) end assert_raises(ArgumentError) do face.material(nil) end end # ========================================================================== # # method Sketchup::Face.material= # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#material= def test_material_Set_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) status = face.material = "red" end def test_material_Set_Integer face = create_face result = face.material = 255 assert_kind_of(Integer, result) end def test_material_Set_HexInteger face = create_face result = face.material = 0xff assert_kind_of(Integer, result) end def test_material_Set_HexString face = create_face result = face.material = '#ff0000' assert_kind_of(String, result) end def test_material_Set_ArrayFloat face = create_face result = face.material = [1.0, 0.0, 0.0] assert_kind_of(Array, result) end def test_material_Set_ArrayInteger face = create_face result = face.material = [255, 0, 0] assert_kind_of(Array, result) end def test_material_Set_string face = create_face result = face.material = "red" assert_kind_of(String, result) end def test_material_Set_material_object face = create_face material = Sketchup.active_model.materials.add("Material") material.color = "red" result = face.material = material assert_kind_of(Sketchup::Material, result) end def test_material_Set_sketchupcolor face = create_face result = face.material = (Sketchup::Color.new("red")) assert_kind_of(Sketchup::Color, result) end def test_material_Set_deleted_material face = create_face material = create_material Sketchup.active_model.materials.remove(material) assert_raises(ArgumentError) do face.back_material = material end end def test_material_Set_arity assert_equal(1, Sketchup::Face.instance_method(:material=).arity) end def test_material_Set_invalid_arguments skip("Broken in SU2014") if Sketchup.version.to_i == 14 face = create_face assert_raises(ArgumentError) do face.material = "invalid color name" end assert_raises(ArgumentError) do face.material = ["Array"] end #assert_raises(TypeError) do # face.material = nil #end end # ========================================================================== # # method Sketchup::Face.mesh # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#mesh def test_mesh_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) mesh = face.mesh(7) end def test_mesh_return_type face = create_face_with_hole # Valid flags include: # 0: Include PolygonMeshPoints, # 1: Include PolygonMeshUVQFront, # 2: Include PolygonMeshUVQBack, # 4: Include PolygonMeshNormals. # Add these numbers together to combine flags. # A value of 7 will include all flags. result = face.mesh(7) assert_kind_of(Geom::PolygonMesh, result) end def test_mesh_arity assert_equal(-1, Sketchup::Face.instance_method(:mesh).arity) end def test_mesh_invalid_arguments face = create_face_with_hole assert_raises(TypeError) do face.mesh("Strings are not valid!") end assert_raises(TypeError) do face.mesh(["Can't use array"]) end assert_raises(TypeError) do face.mesh(false) end assert_raises(TypeError) do face.mesh(nil) end end def test_mesh_arguments_out_of_range face = create_face_with_hole # Should raise an error, but does not #assert_raises(TypeError) do # face.mesh(12) #end assert_raises(RangeError) do face.mesh(-5) end end # ========================================================================== # # method Sketchup::Face.normal # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#normal def test_normal_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) normal = face.normal end def test_normal_return_value_face_on_ground entities = Sketchup.active_model.active_entities face = entities.add_face([0, 0, 0], [100, 0, 0], [100, 100, 0], [0, 100, 0]) vector = Geom::Vector3d.new(0, 0, -1) result = face.normal assert_equal(vector,result) end def test_normal_return_value_face_in_space p1,p2,p3 = [0, 0, 0], [10, 0, 10], [20, 10, 10] face = Sketchup.active_model.active_entities.add_face(p1, p2, p3) vector = Geom::Vector3d.new( -0.5773502691896258, 0.5773502691896257, 0.5773502691896258) result = face.normal assert_equal(true, (vector == result)) end def test_normal_arity assert_equal(0, Sketchup::Face.instance_method(:normal).arity) end def test_normal_invalid_arguments face = create_face assert_raises(ArgumentError) do face.normal(-5) end assert_raises(ArgumentError) do face.normal(true) end assert_raises(ArgumentError) do face.normal("string") end assert_raises(ArgumentError) do face.normal(["Array"]) end assert_raises(ArgumentError) do face.normal(nil) end end # ========================================================================== # # method Sketchup::Face.outer_loop # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#outer_loop def test_outer_loop_api_example # Create a series of points that define a new face. model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [9, 0, 0] pts[2] = [9, 9, 0] pts[3] = [0, 9, 0] # Add the face to the entities in the model face = entities.add_face(pts) loop = face.outer_loop end def test_outer_loop_return_type face = create_face_with_hole result = face.outer_loop assert_kind_of(Sketchup::Loop, result) end def test_outer_loop_arity assert_equal(0, Sketchup::Face.instance_method(:outer_loop).arity) end def test_outer_loop_invalid_arguments face = create_face_with_hole assert_raises(ArgumentError) do face.outer_loop("Strings are not valid!") end assert_raises(ArgumentError) do face.outer_loop(["Can't use array"]) end assert_raises(ArgumentError) do face.outer_loop(12) end assert_raises(ArgumentError) do face.outer_loop(false) end assert_raises(ArgumentError) do face.outer_loop(nil) end end # ========================================================================== # # method Sketchup::Face.plane # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#plane def test_plane_api_example point1 = Geom::Point3d.new(0,0,0) point2 = Geom::Point3d.new(0,0,100) depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) plane = face.plane end def test_plane_return_type face = create_face result = face.plane assert_kind_of(Array, result) end def test_plane_return_value face = create_face result = face.plane assert_equal([-0.0, -0.0, 1.0, -0.0], result) end def test_plane_arity assert_equal(0, Sketchup::Face.instance_method(:plane).arity) end def test_plane_invalid_arguments face = create_face assert_raises(ArgumentError) do face.plane(-5) end assert_raises(ArgumentError) do face.plane(true) end assert_raises(ArgumentError) do face.plane("string") end assert_raises(ArgumentError) do face.plane(["Array"]) end assert_raises(ArgumentError) do face.plane(nil) end end # ========================================================================== # # method Sketchup::Face.position_material # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#position_material def test_position_material_api_example model = Sketchup.active_model entities = model.active_entities # Create a face and add it to the model entities pts = [] pts[0] = [0, 0, 1] pts[1] = [9, 0, 1] pts[2] = [9, 9, 1] pts[3] = [0, 9, 1] face = entities.add_face(pts) # Export an image to use as a texture path = Sketchup.temp_dir full_name = File.join(path, "temp_image.jpg") model.active_view.write_image(full_name, 500, 500, false, 0.0) # Create a material and assign the texture to it material = model.materials.add("Test Material") material.texture = full_name # Assign the new material to our face we created face.material = material pt_array = [] pt_array[0] = Geom::Point3d.new(3, 0, 0) pt_array[1] = Geom::Point3d.new(0, 0, 0) on_front = true face.position_material(material, pt_array, on_front) end def test_position_material_return_type face = create_face material = create_material face.material = material pt_array = [] pt_array[0] = Geom::Point3d.new(3, 0, 0) pt_array[1] = Geom::Point3d.new(0, 0, 0) result = face.position_material(material, pt_array, true) assert_kind_of(Sketchup::Face, result) end def test_position_material_return_value face = create_face material = create_material face.material = material pt_array = [] pt_array[0] = Geom::Point3d.new(3, 0, 0) pt_array[1] = Geom::Point3d.new(0, 0, 0) result = face.position_material(material, pt_array, true) assert_equal(face, result) end def test_position_material_arity assert_equal(3, Sketchup::Face.instance_method(:position_material).arity) end def test_position_material_invalid_arguments face = create_face material = create_material face.material = material assert_raises(ArgumentError) do face.position_material("st", "ri", "ng") end assert_raises(TypeError) do face.position_material(false, false, false) end #assert_raises(ArgumentError) do # face.position_material(1, 2, 3) #end #assert_raises(ArgumentError) do # face.position_material(nil, nil, nil) #end end # ========================================================================== # # method Sketchup::Face.pushpull # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#pushpull def test_pushpull_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) status = face.pushpull(100, true) end def test_pushpull_return_type face = create_face result = face.pushpull(100, true) assert_nil(result) end def test_pushpull_entity_count_face_not_copied face = create_face pre_pushpull = Sketchup.active_model.entities.length face.pushpull(100, false) face.pushpull(100, false) post_pushpull = Sketchup.active_model.entities.length entity_increase = post_pushpull - pre_pushpull assert_equal(13, entity_increase) end def test_pushpull_entity_count_face_copied face = create_face new_face = [] pre_pushpull = Sketchup.active_model.entities.length face.pushpull(100, true) face.all_connected.grep(Sketchup::Face).each do |e| new_face = e if (e.normal == face.normal) && (e != face) end new_face.pushpull(100, true) post_pushpull = Sketchup.active_model.entities.length entity_increase = post_pushpull - pre_pushpull assert_equal(26, entity_increase) end def test_pushpull_arity assert_equal(-1, Sketchup::Face.instance_method(:pushpull).arity) end def test_pushpull_invalid_arguments face = create_face material = create_material face.material = material assert_raises(TypeError) do face.pushpull("st", "ri") end assert_raises(TypeError) do face.pushpull(false, false) end #assert_raises(ArgumentError) do # face.pushpull(1, 2) #end assert_raises(TypeError) do face.pushpull(nil, nil) end end # ========================================================================== # # method Sketchup::Face.reverse! # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#reverse! def test_reverse_Bang_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) status = face.reverse! end def test_reverse_Bang_return_type face = create_face result = face.reverse! assert_kind_of(Sketchup::Face, result) end def test_reverse_Bang_return_value face = create_face normal = face.normal result = face.reverse! assert_equal(normal, face.normal.reverse!) end def test_reverse_Bang_arity assert_equal(0, Sketchup::Face.instance_method(:reverse!).arity) end def test_reverse_Bang_invalid_arguments face = create_face material = create_material face.material = material assert_raises(TypeError) do face.pushpull("st") end assert_raises(TypeError) do face.pushpull(false) end #assert_raises(ArgumentError) do # face.pushpull(1, 2) #end assert_raises(TypeError) do face.pushpull(nil) end end # ========================================================================== # # method Sketchup::Face.set_texture_projection # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#set_texture_projection def test_set_texture_projection_api_example model = Sketchup.active_model entities = model.active_entities materials = model.materials # Create a face and add it to the model entities pts = [] pts[0] = [0, 0, 1] pts[1] = [10, 0, 1] pts[2] = [10, 10, 1] face = entities.add_face(pts) # Export an image to use as a texture path = Sketchup.temp_dir full_name = File.join(path, "temp_image.jpg") model.active_view.write_image(full_name, 500, 500, false, 0.0) # Create a material and assign the texture to it material = materials.add "Test Material" material.texture = full_name # Assign the new material to our face we created face.material = material # Returns nil if not successful, path if successful result = face.set_texture_projection(face.normal, true) end def test_set_texture_projection_return_type face = create_face material = create_material face.material = material vector = [rand, rand, rand] result = face.set_texture_projection(vector, true) assert_kind_of(TrueClass, result) end def test_set_texture_projection_back_face_return_type face = create_face material = create_material face.back_material = material vector = [rand, rand, rand] result = face.set_texture_projection(vector, false) assert_kind_of(TrueClass, result) end def test_set_texture_projection_overwrite_existing_projection face = create_face material = create_material face.material = material vector = Geom::Vector3d.new(rand, rand, rand).normalize face.set_texture_projection(vector, true) vector2 = Geom::Vector3d.new(rand, rand, rand).normalize face.set_texture_projection(vector2, true) returned_vector = face.get_texture_projection(true) assert_equal(vector2, returned_vector) end def test_set_texture_projection_arity assert_equal(2, Sketchup::Face.instance_method( :set_texture_projection).arity) end def test_set_texture_projection_invalid_arguments face = create_face assert_raises(ArgumentError) do face.set_texture_projection("st", "ri") end assert_raises(ArgumentError) do face.set_texture_projection(false, false) end assert_raises(ArgumentError) do face.set_texture_projection(1, 2) end #assert_raises(TypeError) do # face.set_texture_projection(nil,nil) #end end # ========================================================================== # # method Sketchup::Face.vertices # http://www.sketchup.com/intl/en/developer/docs/ourdoc/face#vertices def test_vertices_api_example depth = 100 width = 100 model = Sketchup.active_model entities = model.active_entities pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # Add the face to the entities in the model face = entities.add_face(pts) vertices = face.vertices end def test_vertices_return_type face = create_face result = face.vertices assert_kind_of(Array, result) end def test_vertices_return_value face = create_face result = face.vertices assert(result.all? { |entity| entity.is_a?(Sketchup::Vertex) }, 'Not all entities returned were vertices.') end def test_vertices_return_array_length face = create_face result = face.vertices assert_equal(result.length, 4) end def test_vertices_arity assert_equal(0, Sketchup::Face.instance_method(:vertices).arity) end def test_vertices_invalid_arguments face = create_face assert_raises(ArgumentError) do face.vertices("Strings are not valid!") end assert_raises(ArgumentError) do face.vertices(["Can't use array"]) end assert_raises(ArgumentError) do face.vertices(12) end assert_raises(ArgumentError) do face.vertices(false) end assert_raises(ArgumentError) do face.vertices(nil) end end end
{'content_hash': 'b2dd043aaf9b71749684985cb7f3bf50', 'timestamp': '', 'source': 'github', 'line_count': 1712, 'max_line_length': 85, 'avg_line_length': 26.511682242990656, 'alnum_prop': 0.632127434564202, 'repo_name': 'economysizegeek/testup-2', 'id': '06f4af9d7d3398143b74b5a96827a67697e6ac8f', 'size': '45511', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'tests/SketchUp Ruby API/TC_Sketchup_Face.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '597986'}, {'name': 'C++', 'bytes': '8756'}, {'name': 'CSS', 'bytes': '7339'}, {'name': 'JavaScript', 'bytes': '35395'}, {'name': 'Ruby', 'bytes': '409503'}]}
// The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.common.utils; import java.math.BigInteger; /** * * @author <a href="mailto:[email protected]">Loc Ha</a> * */ public class MathUtils { public static int inRange(int min, int max, int value) { if (value < min) { return min; } if (value > max) { return max; } return value; } public static int ceil(int n, int base) { AssertUtils.assertTrue(n >= 0); AssertUtils.assertTrue(base > 0); return ((n + base - 1) / base) * base; } public static int pow2(int exponent) { return pow(2, exponent); } public static int pow(int n, int exponent) { AssertUtils.assertTrue(exponent >= 0); BigInteger pow = BigInteger.valueOf(n).pow(exponent); int val = pow.intValue(); if (val != pow.longValue()) { throw new ArithmeticException(); } return val; } public static byte[] toByteArray(long l) { byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte) (l & 0xffL); l >>= 8; } return result; } public static byte[] toByteArray(int begin, int end) { AssertUtils.assertTrue(begin <= end); AssertUtils.assertTrue(begin >= Byte.MIN_VALUE); AssertUtils.assertTrue(end <= Byte.MAX_VALUE); byte[] byteArray = new byte[end - begin + 1]; for (int i = begin; i <= end; i++) { byteArray[i - begin] = (byte) i; } return byteArray; } }
{'content_hash': '57cc176c24fffb40dc34605ce2f7fd73', 'timestamp': '', 'source': 'github', 'line_count': 83, 'max_line_length': 90, 'avg_line_length': 30.012048192771083, 'alnum_prop': 0.6936973103171417, 'repo_name': 'haducloc/appslandia-common', 'id': '70b055b4588742fc872e3f1c7f76ff37537c6291', 'size': '2492', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/appslandia/common/utils/MathUtils.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '798056'}]}
define :user_ulimit, :filehandle_limit => nil, :process_limit => nil, :memory_limit => nil, :stack_soft_limit => nil, :stack_hard_limit => nil, :filename => nil do filename = params[:filename] || "#{params[:name]}_limits" template "/etc/security/limits.d/#{filename}.conf" do source "ulimit.erb" cookbook "ulimit" owner "root" group "root" mode 0644 variables( :ulimit_user => params[:name], :filehandle_limit => params[:filehandle_limit], :filehandle_soft_limit => params[:filehandle_soft_limit], :filehandle_hard_limit => params[:filehandle_hard_limit], :process_limit => params[:process_limit], :process_soft_limit => params[:process_soft_limit], :process_hard_limit => params[:process_hard_limit], :memory_limit => params[:memory_limit], :core_limit => params[:core_limit], :core_soft_limit => params[:core_soft_limit], :core_hard_limit => params[:core_hard_limit], :stack_limit => params[:stack_limit], :stack_soft_limit => params[:stack_soft_limit], :stack_hard_limit => params[:stack_hard_limit] ) end end
{'content_hash': '10df36837d9fb161000b479daec7c879', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 163, 'avg_line_length': 40.464285714285715, 'alnum_prop': 0.6337157987643425, 'repo_name': 'sci-gaia/doi-metadata-search', 'id': '3218858bca69675006b1d9ffebb412702fd60450', 'size': '1305', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'vendor/cookbooks/ulimit/definitions/user_ulimit.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8051'}, {'name': 'HTML', 'bytes': '31413'}, {'name': 'JavaScript', 'bytes': '26284'}, {'name': 'Ruby', 'bytes': '93422'}]}
package jef.database.jdbc.result; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import javax.sql.rowset.CachedRowSet; import jef.common.log.LogUtil; import jef.database.Condition; import jef.database.DbUtils; import jef.database.ORMConfig; import jef.database.Session.PopulateStrategy; import jef.database.dialect.DatabaseDialect; import jef.database.jdbc.JDBCTarget; import jef.database.meta.Reference; import jef.database.routing.sql.InMemoryOperateProvider; import jef.database.wrapper.clause.InMemoryDistinct; import jef.database.wrapper.clause.InMemoryGroupByHaving; import jef.database.wrapper.clause.InMemoryOrderBy; import jef.database.wrapper.clause.InMemoryPaging; import jef.database.wrapper.clause.InMemoryProcessor; import jef.database.wrapper.clause.InMemoryStartWithConnectBy; import jef.database.wrapper.populator.ColumnMeta; /** * 查询时记录的结果集 * * @author Administrator * */ public final class ResultSetContainer extends AbstractResultSet implements IResultSet { private int current = -1; // 重新排序部分 private InMemoryOrderBy inMemoryOrder; // 重新分页逻辑 private InMemoryPaging inMemoryPage; // 重新分组处理逻辑 private List<InMemoryProcessor> mustInMemoryProcessor; // 所有列的元数据记录 private ColumnMeta columns; protected final List<ResultSetHolder> results = new ArrayList<ResultSetHolder>(5); // 是否缓存 private boolean cache; public ResultSetContainer(boolean cache) { this.cache = cache; } public int size() { return results.size(); } public ColumnMeta getColumns() { return columns; } // 级联过滤条件 protected Map<Reference, List<Condition>> filters; public Map<Reference, List<Condition>> getFilters() { return filters; } @Override public ResultSetMetaData getMetaData() throws SQLException { return columns.getMeta(); } public static IResultSet toInMemoryProcessorResultSet(InMemoryOperateProvider context, ResultSetHolder... rs) { ResultSetContainer mrs = new ResultSetContainer(false); for (ResultSetHolder rsh : rs) { mrs.add(rsh); } context.parepareInMemoryProcess(null, mrs); return mrs.toProperResultSet(null); } public boolean next() { try { boolean n = (current > -1) && results.get(current).rs.next(); if (n == false) { current++; if (current < results.size()) { return next(); } else { return false; } } return n; } catch (SQLException e) { LogUtil.exception(e); return false; } } public boolean previous() throws SQLException { boolean b = (current < results.size()) && results.get(current).rs.previous(); if (b == false) { current--; if (current > -1) { return previous(); } else { return false; } } return b; } public void beforeFirst() throws SQLException { for (ResultSetHolder rs : results) { rs.rs.beforeFirst(); } current = -1; } public boolean first() throws SQLException { results.get(0).rs.first(); for (int i = 1; i < results.size(); i++) { ResultSetHolder rs = results.get(i); if (!rs.rs.isBeforeFirst()) { rs.rs.beforeFirst(); } } current = 0; return true; } public void afterLast() throws SQLException { for (ResultSetHolder rs : results) { rs.rs.afterLast(); } current = results.size(); } public void add(ResultSetHolder rsh) { if (columns == null) { try { initMetadata(rsh.rs); } catch (SQLException e) { throw new IllegalStateException(e); } } synchronized (results) { results.add(rsh); } if (cache) { try { rsh.rs = tryCache(rsh.rs, rsh.getProfile()); rsh.close(false); return; } catch (SQLException e) { // 缓存失败 LogUtil.exception(e); } } } /** * 添加一个 * * @param rs * @param statement */ public void add(ResultSet rs, Statement statement, JDBCTarget tx) { if (columns == null) { try { initMetadata(rs); } catch (SQLException e) { throw new IllegalStateException(e); } } ResultSetHolder rsh = new ResultSetHolder(tx, statement, rs); synchronized (results) { results.add(rsh); } if (cache) { try { rsh.rs = tryCache(rs, tx.getProfile()); rsh.close(false); return; } catch (SQLException e) { // 缓存失败 LogUtil.exception(e); } } // rsh.rs = rs; } /** * 关闭全部连接和结果集 * * @throws SQLException */ public void close() throws SQLException { List<SQLException> ex = new ArrayList<SQLException>(); for (ResultSetHolder rsx : results) { rsx.close(true); } results.clear(); if (ex.size() > 0) { throw new SQLException("theres " + ex.size() + " resultSet close error!"); } } /** * 转换为可以用于输出正确的结果集 * * * 1、a 有内存任务,使用内存处理并排序。 * b 无内存任务,有多个结果集且有排序任务,使用混合排序 * c 无内存任务,有多个结果集且无排序任务,使用当前对象作为结果集 * d 无内存内务,无多个结果集,退化为简单结果集 * 2、有分页任务,包装为分页结果集 * * * @return */ @SuppressWarnings("unchecked") public IResultSet toProperResultSet(Map<Reference, List<Condition>> filters, PopulateStrategy... args) { if (filters == null) { filters = Collections.EMPTY_MAP; } if (results.isEmpty()) { return new ResultSetWrapper(); } //最后将要包装的对象 IResultSet result; // 除了Order、Page以外的内存处理任务 if (mustInMemoryProcessor != null) { InMemoryProcessResultSet rw = new InMemoryProcessResultSet(results,columns,filters); rw.addProcessor(mustInMemoryProcessor); rw.addProcessor(inMemoryOrder);// 如果需要处理,排序是第一位的. try { rw.process(); } catch (SQLException e) { throw DbUtils.toRuntimeException(e); } result=rw; }else if(results.size()==1){ ResultSetWrapper rw = new ResultSetWrapper(results.get(0), columns); rw.setFilters(filters); result=rw; }else if(inMemoryOrder!=null){ ReorderResultSet2 rw = new ReorderResultSet2(results, inMemoryOrder, columns, filters); result=rw; }else{ this.filters=filters; result=this; } //分页处理器 if(inMemoryPage!=null){ result=new LimitOffsetResultSet(result, inMemoryPage.getOffset(), inMemoryPage.getLimit()); } return result; } public DatabaseDialect getProfile() { return results.get(current).getProfile(); } @Override protected ResultSet get() { return results.get(current).rs; } public void setInMemoryPage(InMemoryPaging inMemoryPaging) { this.inMemoryPage = inMemoryPaging; } public void setInMemoryOrder(InMemoryOrderBy inMemoryOrder) { this.inMemoryOrder = inMemoryOrder; } public void setInMemoryGroups(InMemoryGroupByHaving inMemoryGroups) { addToInMemprocessor(inMemoryGroups); } public void setInMemoryDistinct(InMemoryDistinct instance) { addToInMemprocessor(instance); } public void setInMemoryConnectBy(InMemoryStartWithConnectBy parseStartWith) { addToInMemprocessor(parseStartWith); } public boolean isClosed() throws SQLException { return results.isEmpty(); } @Override public boolean isFirst() throws SQLException { throw new UnsupportedOperationException("isFirst"); } @Override public boolean isLast() throws SQLException { throw new UnsupportedOperationException("isLast"); } @Override public boolean last() throws SQLException { throw new UnsupportedOperationException("last"); } @Override public boolean isBeforeFirst() throws SQLException { throw new UnsupportedOperationException("isBeforeFirst"); } @Override public boolean isAfterLast() throws SQLException { throw new UnsupportedOperationException("isAfterLast"); } // //////////////////////////// 私有方法 /////////////////////////////////// private void addToInMemprocessor(InMemoryProcessor process) { if (process != null) { if (this.mustInMemoryProcessor == null) { mustInMemoryProcessor = new ArrayList<InMemoryProcessor>(4); } mustInMemoryProcessor.add(process); } } private void initMetadata(ResultSet wrapped) throws SQLException { ResultSetMetaData meta = wrapped.getMetaData(); this.columns = new ColumnMeta(meta); } private ResultSet tryCache(ResultSet set, DatabaseDialect profile) throws SQLException { long start = System.currentTimeMillis(); CachedRowSet rs = profile.newCacheRowSetInstance(); rs.populate(set); if (ORMConfig.getInstance().isDebugMode()) { LogUtil.debug("Caching Results from database. Cost {}ms.", System.currentTimeMillis() - start); } set.close(); return rs; } }
{'content_hash': 'dbe6e46f91ed58023d445fb5c9829663', 'timestamp': '', 'source': 'github', 'line_count': 352, 'max_line_length': 112, 'avg_line_length': 23.806818181818183, 'alnum_prop': 0.7020286396181384, 'repo_name': 'GeeQuery/ef-orm', 'id': '34c611175d91c1a26fb624ca71f5f7ffaa21eb3b', 'size': '9471', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'common-orm/src/main/java/jef/database/jdbc/result/ResultSetContainer.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '245'}, {'name': 'Java', 'bytes': '8573985'}, {'name': 'Lua', 'bytes': '30'}, {'name': 'PLSQL', 'bytes': '671'}, {'name': 'PLpgSQL', 'bytes': '185'}, {'name': 'SQLPL', 'bytes': '413'}]}
package org.elasticsearch.discovery.ec2; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.client.builder.AwsClientBuilder; import com.amazonaws.http.IdleConnectionReaper; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2ClientBuilder; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.util.LazyInitializable; import java.util.concurrent.atomic.AtomicReference; class AwsEc2ServiceImpl implements AwsEc2Service { private static final Logger logger = LogManager.getLogger(AwsEc2ServiceImpl.class); private final AtomicReference<LazyInitializable<AmazonEc2Reference, ElasticsearchException>> lazyClientReference = new AtomicReference<>(); private AmazonEC2 buildClient(Ec2ClientSettings clientSettings) { final AWSCredentialsProvider credentials = buildCredentials(logger, clientSettings); final ClientConfiguration configuration = buildConfiguration(clientSettings); return buildClient(credentials, configuration, clientSettings.endpoint); } // proxy for testing AmazonEC2 buildClient(AWSCredentialsProvider credentials, ClientConfiguration configuration, String endpoint) { final AmazonEC2ClientBuilder builder = AmazonEC2ClientBuilder.standard().withCredentials(credentials) .withClientConfiguration(configuration); if (Strings.hasText(endpoint)) { logger.debug("using explicit ec2 endpoint [{}]", endpoint); builder.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endpoint, null)); } return SocketAccess.doPrivileged(builder::build); } // pkg private for tests static ClientConfiguration buildConfiguration(Ec2ClientSettings clientSettings) { final ClientConfiguration clientConfiguration = new ClientConfiguration(); // the response metadata cache is only there for diagnostics purposes, // but can force objects from every response to the old generation. clientConfiguration.setResponseMetadataCacheSize(0); clientConfiguration.setProtocol(clientSettings.protocol); if (Strings.hasText(clientSettings.proxyHost)) { // TODO: remove this leniency, these settings should exist together and be validated clientConfiguration.setProxyHost(clientSettings.proxyHost); clientConfiguration.setProxyPort(clientSettings.proxyPort); clientConfiguration.setProxyUsername(clientSettings.proxyUsername); clientConfiguration.setProxyPassword(clientSettings.proxyPassword); } // Increase the number of retries in case of 5xx API responses clientConfiguration.setMaxErrorRetry(10); clientConfiguration.setSocketTimeout(clientSettings.readTimeoutMillis); return clientConfiguration; } // pkg private for tests static AWSCredentialsProvider buildCredentials(Logger logger, Ec2ClientSettings clientSettings) { final AWSCredentials credentials = clientSettings.credentials; if (credentials == null) { logger.debug("Using default provider chain"); return DefaultAWSCredentialsProviderChain.getInstance(); } else { logger.debug("Using basic key/secret credentials"); return new AWSStaticCredentialsProvider(credentials); } } @Override public AmazonEc2Reference client() { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> clientReference = this.lazyClientReference.get(); if (clientReference == null) { throw new IllegalStateException("Missing ec2 client configs"); } return clientReference.getOrCompute(); } /** * Refreshes the settings for the AmazonEC2 client. The new client will be build * using these new settings. The old client is usable until released. On release it * will be destroyed instead of being returned to the cache. */ @Override public void refreshAndClearCache(Ec2ClientSettings clientSettings) { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> newClient = new LazyInitializable<>( () -> new AmazonEc2Reference(buildClient(clientSettings)), clientReference -> clientReference.incRef(), clientReference -> clientReference.decRef()); final LazyInitializable<AmazonEc2Reference, ElasticsearchException> oldClient = this.lazyClientReference.getAndSet(newClient); if (oldClient != null) { oldClient.reset(); } } @Override public void close() { final LazyInitializable<AmazonEc2Reference, ElasticsearchException> clientReference = this.lazyClientReference.getAndSet(null); if (clientReference != null) { clientReference.reset(); } // shutdown IdleConnectionReaper background thread // it will be restarted on new client usage IdleConnectionReaper.shutdown(); } }
{'content_hash': '76cdf6f78840dfd8e22a0a81ca758a59', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 135, 'avg_line_length': 47.13157894736842, 'alnum_prop': 0.7401823934487252, 'repo_name': 'nknize/elasticsearch', 'id': '1d6f69927ab6d339720cf991885a10068576900d', 'size': '6161', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'plugins/discovery-ec2/src/main/java/org/elasticsearch/discovery/ec2/AwsEc2ServiceImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '12298'}, {'name': 'Batchfile', 'bytes': '16353'}, {'name': 'Emacs Lisp', 'bytes': '3341'}, {'name': 'FreeMarker', 'bytes': '45'}, {'name': 'Groovy', 'bytes': '251795'}, {'name': 'HTML', 'bytes': '5348'}, {'name': 'Java', 'bytes': '36849935'}, {'name': 'Perl', 'bytes': '7116'}, {'name': 'Python', 'bytes': '76127'}, {'name': 'Shell', 'bytes': '102829'}]}
package org.keycloak.forms.login.freemarker.model; import freemarker.template.TemplateMethodModelEx; import freemarker.template.TemplateModelException; import org.keycloak.models.RealmModel; import org.keycloak.services.Urls; import java.net.URI; import java.util.List; /** */ public class RequiredActionUrlFormatterMethod implements TemplateMethodModelEx { private final String realm; private final URI baseUri; public RequiredActionUrlFormatterMethod(RealmModel realm, URI baseUri) { this.realm = realm.getName(); this.baseUri = baseUri; } @Override public Object exec(List list) throws TemplateModelException { String action = list.get(0).toString(); String relativePath = list.get(1).toString(); String url = Urls.requiredActionBase(baseUri).path(relativePath).build(realm, action).toString(); return url; } }
{'content_hash': 'ac9e7728c14054337818b93062c11579', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 105, 'avg_line_length': 28.967741935483872, 'alnum_prop': 0.734966592427617, 'repo_name': 'cfsnyder/keycloak', 'id': 'f7db216dd3d63eaa85231cb42696a798996727f9', 'size': '1572', 'binary': False, 'copies': '55', 'ref': 'refs/heads/master', 'path': 'services/src/main/java/org/keycloak/forms/login/freemarker/model/RequiredActionUrlFormatterMethod.java', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '3104'}, {'name': 'ApacheConf', 'bytes': '22819'}, {'name': 'Batchfile', 'bytes': '2114'}, {'name': 'CSS', 'bytes': '345683'}, {'name': 'FreeMarker', 'bytes': '63890'}, {'name': 'HTML', 'bytes': '453234'}, {'name': 'Java', 'bytes': '11387844'}, {'name': 'JavaScript', 'bytes': '739213'}, {'name': 'Shell', 'bytes': '11085'}, {'name': 'XSLT', 'bytes': '121832'}]}
package io.crate.metadata.view; import io.crate.common.annotations.VisibleForTesting; import io.crate.metadata.ColumnIdent; import io.crate.metadata.Reference; import io.crate.metadata.RelationInfo; import io.crate.metadata.RelationName; import io.crate.metadata.RowGranularity; import io.crate.metadata.table.Operation; import org.elasticsearch.common.settings.Settings; import javax.annotation.Nullable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; public class ViewInfo implements RelationInfo { private final RelationName ident; private final String definition; private final List<Reference> columns; private final String owner; @VisibleForTesting public ViewInfo(RelationName ident, String definition, List<Reference> columns, @Nullable String owner) { this.ident = ident; this.definition = definition; this.columns = columns; this.owner = owner; } @Override public Collection<Reference> columns() { return columns; } @Override public RowGranularity rowGranularity() { return RowGranularity.DOC; } @Override public RelationName ident() { return ident; } @Override public List<ColumnIdent> primaryKey() { return Collections.emptyList(); } @Override public Settings parameters() { return Settings.EMPTY; } @Override public Set<Operation> supportedOperations() { return Operation.READ_ONLY; } @Override public RelationType relationType() { return RelationType.VIEW; } @Override public Iterator<Reference> iterator() { return columns.iterator(); } @Override public String toString() { return ident.fqn(); } public String definition() { return definition; } @Nullable public String owner() { return owner; } }
{'content_hash': 'e51699688c9ec9e126a349f35614bf4c', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 109, 'avg_line_length': 22.359550561797754, 'alnum_prop': 0.6814070351758794, 'repo_name': 'EvilMcJerkface/crate', 'id': '8e9a00730aafeaddca03c4047acd3519bbe1541c', 'size': '2987', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'server/src/main/java/io/crate/metadata/view/ViewInfo.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '29877'}, {'name': 'Batchfile', 'bytes': '4123'}, {'name': 'Java', 'bytes': '24908818'}, {'name': 'Python', 'bytes': '64030'}, {'name': 'Shell', 'bytes': '9028'}]}
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2015, Knut Reinert, FU Berlin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin nor the names of // its contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== #ifndef SEQAN_HEADER_MISC_SKIPLIST_H #define SEQAN_HEADER_MISC_SKIPLIST_H #include <seqan/random.h> namespace SEQAN_NAMESPACE_MAIN { /*! * @class Skiplist * @extends Map * @headerfile <seqan/map.h> * * @brief General purpose map container. * * @signature template <typename TValue, typename TSpec> * class Map<TValue, Skiplist<TSpec> >; * * @tparam TSpec The specializing type. * @tparam TValue The type of value stored in the map. * * The skiplist takes in average an oberhead of only two pointers per value stored in the map. */ ////////////////////////////////////////////////////////////////////////////// // Skiplist ////////////////////////////////////////////////////////////////////////////// //forwards template <typename TValue, typename TSpec> class Map; template <typename TValue, typename TSpec> class SkiplistElement; template <typename TValue, typename TSpec> class SkiplistNext; template <typename TValue, typename TSpec> class SkiplistPath; ////////////////////////////////////////////////////////////////////////////// // Tags struct SkiplistIterator; ////////////////////////////////////////////////////////////////////////////// template <typename T> struct AllocatorType; template <typename TValue, typename TSpec> struct AllocatorType<Map<TValue, Skiplist<TSpec> > > { typedef Allocator<SimpleAlloc<> > Type; }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> struct Value<Map<TValue, Skiplist<TSpec> > > { typedef TValue Type; }; ////////////////////////////////////////////////////////////////////////////// template <typename T> struct SkiplistElement_ { typedef char Type; //dummy implementation for VC++ bug }; template <typename TValue, typename TSpec> struct SkiplistElement_<Map<TValue, Skiplist<TSpec> > > { typedef SkiplistElement<TValue, TSpec> Type; }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> struct Key<Map<TValue, Skiplist<TSpec> > >: Key<typename Value< Map<TValue, Skiplist<TSpec> > >::Type> { }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> struct Cargo<Map<TValue, Skiplist<TSpec> > >: Cargo<typename Value< Map<TValue, Skiplist<TSpec> > >::Type> { }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec, typename TIteratorSpec> struct Iterator<Map<TValue, Skiplist<TSpec> >, TIteratorSpec > { typedef Map<TValue, Skiplist<TSpec> > TSkiplist_; typedef Iter<TSkiplist_, SkiplistIterator> Type; }; ////////////////////////////////////////////////////////////////////////////// // Skiplist Map ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> class Map<TValue, Skiplist<TSpec> > { public: typedef typename AllocatorType<Map>::Type TAllocator; typedef SkiplistElement<TValue, TSpec> TElement; typedef typename Size<Map>::Type TSize; enum { MAX_HEIGHT = 28, //heights are in {0, 1, ..., MAX_HEIGHT-1} BLOCK_SIZE_1_ = sizeof(TElement) * 20, //store min. 20 elements BLOCK_SIZE_2_ = 0x200, //minimal block size BLOCK_SIZE = (BLOCK_SIZE_1_ > BLOCK_SIZE_2_) ? BLOCK_SIZE_1_ : BLOCK_SIZE_2_ //block size is the max out of both values }; Holder<TAllocator> data_allocator; TElement * data_recycle[MAX_HEIGHT]; unsigned char * data_mem_begin; unsigned char * data_mem_end; SkiplistElement<TValue, TSpec> data_border; TSize data_length; unsigned char data_height; Rng<> rng; Map() : data_mem_begin(0) , data_mem_end(0) , data_length(0) , data_height(0) , rng(0) { for (unsigned char i = 0; i < MAX_HEIGHT; ++i) { data_recycle[i] = 0; valueConstruct(data_border.data_next + i, NonMinimalCtor()); } } Map(Map const & other) : data_mem_begin(0) , data_mem_end(0) , data_length(0) , data_height(0) , rng(0) { assign(*this, other); } Map & operator=(Map const & other) { assign(*this, other); return *this; } template <typename TKey> inline typename MapValue<Map>::Type operator [] (TKey const & key) { return mapValue(*this, key); } }; ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> class SkiplistElement { public: typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef SkiplistNext<TValue, TSpec> TNext; enum { MAX_HEIGHT = TSkiplist::MAX_HEIGHT }; TValue data_value; TNext data_next[MAX_HEIGHT]; //note: only parts of this array available //indirect constructor in _skiplistConstructElement //indirect destructor in _skiplistDestructElement }; ////////////////////////////////////////////////////////////////////////////// //representation of "horizontal" pointer in skiplist //can be overloaded if label is needed template <typename TValue, typename TSpec> class SkiplistNext { public: typedef SkiplistElement<TValue, TSpec> TElement; TElement * data_element; SkiplistNext() : data_element(0) {} SkiplistNext(NonMinimalCtor) : data_element(0) {} SkiplistNext(SkiplistNext const & other) : data_element(other.data_element) {} }; ////////////////////////////////////////////////////////////////////////////// //represents a path from the root to the predecessor of a skiplist element template <typename TValue, typename TSpec> class SkiplistPath { public: typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef SkiplistElement<TValue, TSpec> TElement; enum { MAX_HEIGHT = TSkiplist::MAX_HEIGHT }; TElement * data_elements[MAX_HEIGHT]; }; ////////////////////////////////////////////////////////////////////////////// template<typename TValue, typename TSpec> inline void assign(Map<TValue, Skiplist<TSpec> > & target, Map<TValue, Skiplist<TSpec> > const & source) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef SkiplistPath<TValue, TSpec> TPath; typedef SkiplistElement<TValue, TSpec> TElement; typedef typename Iterator<TSkiplist>::Type TIterator; clear(target); TPath path; path.data_elements[0] = & target.data_border; for (TIterator it(source); !atEnd(it); goNext(it)) { unsigned char height = _skiplistCreateHeight(target, path); TElement & el = _skiplistConstructElement(target, height, value(it)); for (int i = 0; i <= height; ++i) { el.data_next[i].data_element = 0; path.data_elements[i]->data_next[i].data_element = & el; path.data_elements[i] = & el; } } target.data_length = length(source); } ////////////////////////////////////////////////////////////////////////////// //create Space for SkiplistElement of given height template <typename TValue, typename TSpec> inline SkiplistElement<TValue, TSpec> & _skiplistAllocateElement(Map<TValue, Skiplist<TSpec> > & me, unsigned char height) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef SkiplistElement<TValue, TSpec> TElement; typedef SkiplistNext<TValue, TSpec> TNext; TElement * ret; if (me.data_recycle[height]) {//use recycled ret = me.data_recycle[height]; me.data_recycle[height] = * reinterpret_cast<TElement **>(me.data_recycle[height]); } else { int const element_base_size = sizeof(TElement) - TSkiplist::MAX_HEIGHT * sizeof(TNext); int need_size = element_base_size + (height+1) * sizeof(TNext); int buf_size = me.data_mem_end - me.data_mem_begin; if (buf_size < need_size) {//need new memory if (buf_size >= (int) (element_base_size + sizeof(TNext))) {//link rest memory in recycle int rest_height = (buf_size - element_base_size) / sizeof(TNext) - 1; //must be < height, because buf_size < need_size * reinterpret_cast<TElement **>(me.data_mem_begin) = me.data_recycle[rest_height]; me.data_recycle[rest_height] = reinterpret_cast<TElement *>(me.data_mem_begin); } //else: a small part of memory is wasted allocate(value(me.data_allocator), me.data_mem_begin, (size_t) TSkiplist::BLOCK_SIZE, TagAllocateStorage()); me.data_mem_end = me.data_mem_begin + TSkiplist::BLOCK_SIZE; } ret = reinterpret_cast<TElement *>(me.data_mem_begin); me.data_mem_begin += need_size; } return *ret; } ////////////////////////////////////////////////////////////////////////////// //Creates New SkiplistElement template <typename TValue, typename TSpec, typename TValue2> inline SkiplistElement<TValue, TSpec> & _skiplistConstructElement(Map<TValue, Skiplist<TSpec> > & me, unsigned char height, TValue2 const & _value) { typedef SkiplistElement<TValue, TSpec> TElement; TElement & el = _skiplistAllocateElement(me, height); valueConstruct(& (el.data_value), _value); //no need to construct the next array return el; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline void _skiplistDeallocateElement(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el, unsigned char height) { typedef SkiplistElement<TValue, TSpec> TElement; * reinterpret_cast<TElement **>(& el) = me.data_recycle[height]; me.data_recycle[height] = reinterpret_cast<TElement *>(&el); //the real deallocation is done by the allocator on destruction } ////////////////////////////////////////////////////////////////////////////// //Destroys New SkiplistElement template <typename TValue, typename TSpec> inline void _skiplistDestructElement(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el, unsigned char height) { valueDestruct(& (el.value) ); //no need to construct the next array _skiplistDeallocateElement(me, el, height); } ////////////////////////////////////////////////////////////////////////////// //creates height for new SkiplistElement. //increases the Skiplist height if necessary template <typename TValue, typename TSpec> inline unsigned char _skiplistCreateHeight(Map<TValue, Skiplist<TSpec> > & me) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; unsigned char height = pickRandomNumber(me.rng, Pdf<GeometricFairCoin>()); if (height >= TSkiplist::MAX_HEIGHT) height = TSkiplist::MAX_HEIGHT-1; if (height > me.data_height) me.data_height = height; return height; } template <typename TValue, typename TSpec> inline unsigned char _skiplistCreateHeight(Map<TValue, Skiplist<TSpec> > & me, SkiplistPath<TValue, TSpec> & path) //extend path if height is increased { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; unsigned char height = pickRandomNumber(me.rng, Pdf<GeometricFairCoin>()); if (height >= TSkiplist::MAX_HEIGHT) height = TSkiplist::MAX_HEIGHT-1; if (height > me.data_height) { for (unsigned char i = me.data_height + 1; i <= height; ++i) { path.data_elements[i] = & me.data_border; } me.data_height = height; } return height; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline unsigned char _skiplistGetHeight(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el, SkiplistPath<TValue, TSpec> & path) { int height = me.data_height; for (; height > 0 ; --height) { if (path.elements[height]->data_next[height] == el) break; } return height; } template <typename TValue, typename TSpec> inline unsigned char _skiplistGetHeight(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el) { typedef SkiplistPath<TValue, TSpec> TPath; TPath path; _skiplistFind(me, el, path); return _skiplistGetHeight(el, path); } ////////////////////////////////////////////////////////////////////////////// //Note: always store paths to the element LEFT of the actually wanted element. //this element will be the predecessor during insertion. //Given a key: find path to the elment that is left to: // - the first element that has the given key, if there is any, or // - the first element that has the smallest key larger than the given key, //or a path to the last element, if all keys are smaller than the given key //Given an element: find path to the element that is left to: // - the given element, or // - the first element that has the smallest key larger than the key of the given element, //or a path to the last element, if all keys are smaller than the key of the given element template <typename TValue, typename TSpec, typename TKey> inline bool _skiplistFindGoNext(SkiplistNext<TValue, TSpec> & next, unsigned char, TKey const & _key) { return (key(next.data_element->data_value) < _key); } template <typename TValue, typename TSpec> inline bool _skiplistFindGoNext(SkiplistNext<TValue, TSpec> & next, unsigned char, SkiplistElement<TValue, TSpec> const & el) { return (key(next.data_element->data_value) <= key(el.data_value)) && (next.data_element != & el); } template <typename TValue, typename TSpec> inline bool _skiplistFindGoNext(SkiplistNext<TValue, TSpec> & next, unsigned char /*height*/, GoEnd) { return next.data_element; // return next.data_element->data_next[height]; } template <typename TValue, typename TSpec, typename TFind> inline void _skiplistFind(Map<TValue, Skiplist<TSpec> > & me, TFind const & find, //can be a key or a SkiplistElement or GoEnd /*OUT*/ SkiplistPath<TValue, TSpec> & path) { typedef SkiplistElement<TValue, TSpec> TElement; typedef SkiplistNext<TValue, TSpec> TNext; TElement * here = & me.data_border; for (int i = me.data_height; i >= 0; --i) { while (true) { TNext & next = here->data_next[i]; if (!next.data_element || !_skiplistFindGoNext(next, i, find)) break; here = next.data_element; } path.data_elements[i] = here; } } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#find * @headerfile <seqan/map.h> * @brief Find a value in a map. * * @signature TIterator find(map, key); * * @param[in] map A map. Types: Map * @param[in] key A key. * * @return TIterator An iterator to the first value in <tt>map</tt> of the given key, if there is any. An iterator * to the fist value in <tt>map</tt> with key &gt; <tt>key</tt>, otherwise. * * @see Map#value * @see Map#cargo */ template <typename TValue, typename TSpec, typename TFind> inline typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type find(Map<TValue, Skiplist<TSpec> > & me, TFind const & _find, //can be a TKey or a SkiplistElement or GoEnd SkiplistPath<TValue, TSpec> & path) { typedef typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type TIterator; _skiplistFind(me, _find, path); return TIterator(path.data_elements[0]->data_next[0].data_element); } template <typename TValue, typename TSpec, typename TFind> inline typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type find(Map<TValue, Skiplist<TSpec> > & me, TFind const & _find) //can be a TKey or a SkiplistElement or GoEnd { typedef SkiplistPath<TValue, TSpec> TPath; TPath path; return find(me, _find, path); } ////////////////////////////////////////////////////////////////////////////// //insert elements after at the position path points to //Requirements: // - height <= height of the skiplist // - next must be filled at least up to height // - el.data_next must have space for at least height many entries template <typename TValue, typename TSpec> inline void _skiplistInsertElement(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el, SkiplistPath<TValue, TSpec> & path, unsigned char height) { for (int i = height; i >= 0; --i) { el.data_next[i].data_element = path.data_elements[i]->data_next[i].data_element; path.data_elements[i]->data_next[i].data_element = & el; } ++me.data_length; } template <typename TValue, typename TSpec> inline void _skiplistInsertElement(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el, unsigned char height) { typedef SkiplistPath<TValue, TSpec> TPath; TPath path; _skiplistFind(me, key(el.data_value), path); _skiplistInsertElement(me, el, path, height); } ////////////////////////////////////////////////////////////////////////////// //creates entry if necessary /*! * @fn Map#value * @brief Returns a value given a key. * * @signature TReference value(map, key); * * @param[in] map A map. * @param[in] key A key. * * @return TReference The first value in <tt>map</tt> of the given key, if there is any. Otherwise, a new value * that is inserted to <tt>map</tt>. * * @note Do not change the key of a value in the map. */ template <typename TValue, typename TSpec, typename TKey2> inline typename Value< Map<TValue, Skiplist<TSpec> > >::Type & value(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef SkiplistPath<TValue, TSpec> TPath; typedef SkiplistElement<TValue, TSpec> TElement; typedef typename Iterator<TSkiplist>::Type TIterator; typedef typename Value<TSkiplist>::Type TValue2; TPath path; TIterator it = find(me, _key, path); if (it && (key(it) == _key)) { return value(it); } else {// insert new value unsigned char height = _skiplistCreateHeight(me, path); TValue2 val_temp; setKey(val_temp, _key); TElement & el = _skiplistConstructElement(me, height, val_temp); _skiplistInsertElement(me, el, path, height); return el.data_value; } } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#cargo * @brief Returns a cargo given a key. * * @signature TCargo find(map, key); * * @param[in,out] map A map. * @param[in] key A key. * * @return TReturn The cargo of the first value in <tt>map</tt> of the given key, if there is any. Otherwise, the * cargo of a new value that is inserted to <tt>map</tt>. */ template <typename TValue, typename TSpec, typename TKey2> inline typename Cargo< Map<TValue, Skiplist<TSpec> > >::Type & cargo(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { return cargo(value(me, _key)); } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#insert * @brief Insert new value into map. * * @signature void insert(map, value); * @signature void insert(map, key, cargo); * * @param[in,out] map A map. * @param[in] value A value that is added to <tt>map</tt>. * @param[in] key A key. * @param[in] cargo A cargo. * * If <tt>key</tt> and <tt>cargo</tt> are specified, a new value of that key and value is added. If there is already a * value of that key in <tt>map</tt>, the value of this element is changed to <tt>cargo</tt>. * * If <tt>value</tt> is specified, and there is already a value in map of that key, than the cargo of this value is * changed to cargo.cargo(value). * * Use Map#add instead to insert multiple values of the same key. */ template <typename TValue, typename TSpec, typename TValue2> inline void insert(Map<TValue, Skiplist<TSpec> > & me, TValue2 const & _value) { value(me, key(_value)) = _value; } template <typename TValue, typename TSpec, typename TKey2, typename TCargo2> inline void insert(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key, TCargo2 const & _cargo) { cargo(me, _key) = _cargo; } ////////////////////////////////////////////////////////////////////////////// //multiple key insert /*! * @fn Map#add * @brief Insert another value into a multi map. * * @signature void add(map, value); * @signature void add(map, key, cargo); * * @param[in,out] map A map. Types: Skiplist * @param[in] value A value that is added to <tt>map</tt>. * @param[in] cargo A cargo. * @param[in] key A key. * * If <tt>key</tt> and <tt>cargo</tt> are specified, a new value of that key and value is added. */ template <typename TValue, typename TSpec, typename TValue2> inline void add(Map<TValue, Skiplist<TSpec> > & me, TValue2 const & _value) { typedef SkiplistElement<TValue, TSpec> TElement; unsigned char height = _skiplistCreateHeight(me); TElement & el = _skiplistConstructElement(me, height, _value); _skiplistInsertElement(me, el, height); } template <typename TValue, typename TSpec, typename TKey2, typename TCargo2> inline void add(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key, TCargo2 const & _cargo) { TValue temp_val; setKey(temp_val, _key); setCargo(temp_val, _cargo); add(me, temp_val); } ////////////////////////////////////////////////////////////////////////////// //extract element from Skiplist template <typename TValue, typename TSpec> inline void _skiplistUnlinkElement(Map<TValue, Skiplist<TSpec> > & me, SkiplistElement<TValue, TSpec> & el) { typedef SkiplistPath<TValue, TSpec> TPath; TPath path; _skiplistFind(me, el, path); for (int i = me.data_height; i >= 0; --i) { if (path.data_elements[i]->data_next[i].data_element == & el) { path.data_elements[i]->data_next[i].data_element = el.data_next[i].data_element; } } } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#erase * @brief Removes a value from a map. * * @signature void erase(map, key); * @signature void erase(map, iterator); * * @param[in] map A map. Types: Map * @param[in] key The key of a value in <tt>map</tt>. * @param[in] iterator An iterator to a value in <tt>map</tt>. * * Removes the first value in <tt>map</tt> of the given key, if there is any. * * Use @link Map#eraseAll @endlink to remove all values of the given key in a multi map. */ template <typename TValue, typename TSpec, typename TMap2> inline void erase(Map<TValue, Skiplist<TSpec> > & me, Iter<TMap2, SkiplistIterator> const & it) { _skiplistUnlinkElement(me, * it.data_pointer); --me.data_length; } template <typename TValue, typename TSpec, typename TToRemove> inline void erase(Map<TValue, Skiplist<TSpec> > & me, TToRemove const & to_remove) { typedef Map<TValue, Skiplist<TSpec> > TMap; typedef typename Iterator<TMap>::Type TIterator; TIterator it = find(me, to_remove); if (it && (key(it) == key(to_remove))) { erase(me, it); } } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#eraseAll * @brief Removes a value from a map. * * @signature void eraseAll(map, key); * * @param[in,out] map A map. Types: Skiplist * @param[in] key The key of a value in <tt>map</tt>. * * Removes all values in <tt>map</tt> of the given key, if there is any. */ template <typename TValue, typename TSpec, typename TToRemove> inline void eraseAll(Map<TValue, Skiplist<TSpec> > & me, TToRemove const & to_remove) { typedef Map<TValue, Skiplist<TSpec> > TMap; typedef typename Iterator<TMap>::Type TIterator; TIterator it = find(me, to_remove); while (it && (key(it) == key(to_remove))) { TIterator it_old = it; ++it; erase(me, it_old); } } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline void clear(Map<TValue, Skiplist<TSpec> > & me) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; me.data_mem_begin = me.data_mem_end = 0; me.data_length = 0; me.data_height = 0; for (unsigned char i = 0; i < TSkiplist::MAX_HEIGHT; ++i) { me.data_recycle[i] = 0; valueConstruct(me.data_border.data_next + i, NonMinimalCtor()); } clear(value(me.data_allocator)); } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec> inline typename Size< Map<TValue, Skiplist<TSpec> > >::Type length(Map<TValue, Skiplist<TSpec> > const & me) { return me.data_length; } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec, typename TIteratorSpec> inline typename Iterator< Map<TValue, Skiplist<TSpec> >, TIteratorSpec>::Type begin(Map<TValue, Skiplist<TSpec> > & me, TIteratorSpec) { typedef typename Iterator< Map<TValue, Skiplist<TSpec> >, TIteratorSpec>::Type TIterator; return TIterator(me); } template <typename TValue, typename TSpec> inline typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type begin(Map<TValue, Skiplist<TSpec> > & me) { typedef typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type TIterator; return TIterator(me); } ////////////////////////////////////////////////////////////////////////////// template <typename TValue, typename TSpec, typename TIteratorSpec> inline typename Iterator< Map<TValue, Skiplist<TSpec> >, TIteratorSpec>::Type end(Map<TValue, Skiplist<TSpec> > &, TIteratorSpec) { typedef typename Iterator< Map<TValue, Skiplist<TSpec> >, TIteratorSpec>::Type TIterator; return TIterator(); } template <typename TValue, typename TSpec> inline typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type end(Map<TValue, Skiplist<TSpec> > &) { typedef typename Iterator< Map<TValue, Skiplist<TSpec> > >::Type TIterator; return TIterator(); } ////////////////////////////////////////////////////////////////////////////// template <typename TCargo> struct SkipListMapValue_ { template <typename TValue, typename TSpec, typename TKey2> static inline TCargo & mapValue_(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { return cargo(me, _key); } }; template <> struct SkipListMapValue_<Nothing> { template <typename TValue, typename TSpec, typename TKey2> static inline bool mapValue_(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { return hasKey(me, _key); } }; template <typename TValue, typename TSpec, typename TKey2> inline typename MapValue< Map<TValue, Skiplist<TSpec> > >::Type mapValue(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef typename Cargo<TSkiplist>::Type TCargo; return SkipListMapValue_<TCargo>::mapValue_(me, _key); } ////////////////////////////////////////////////////////////////////////////// /*! * @fn Map#hasKey * @brief Determines whether a map contains a value given key. * * @signature bool hasKey(map, key); * * @param[in] map A map. Types: Map * @param[in] key A key. * * @return bool <tt>true</tt>, if there is a value in <tt>map</tt> of that key, <tt>false</tt> otherwise. */ template <typename TValue, typename TSpec, typename TKey2> inline bool hasKey(Map<TValue, Skiplist<TSpec> > & me, TKey2 const & _key) { typedef Map<TValue, Skiplist<TSpec> > TSkiplist; typedef typename Iterator<TSkiplist>::Type TIterator; TIterator it = find(me, _key); return (it && (key(it) == _key)); } ////////////////////////////////////////////////////////////////////////////// // SkiplistIterator: Standard Iterator for Skiplist ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> class Iter< TSkiplist, SkiplistIterator> { public: typedef typename SkiplistElement_<TSkiplist>::Type TElement; typedef typename Value<TSkiplist>::Type TValue; TElement * data_pointer; Iter() : data_pointer(0) { } Iter(Iter const & other) : data_pointer(other.data_pointer) { } Iter(TElement * ptr) : data_pointer(ptr) { } Iter(TSkiplist const & sk) : data_pointer(sk.data_border.data_next[0].data_element) { } ~Iter() { } Iter const & operator = (Iter const & other) { data_pointer = other.data_pointer; return *this; } // TODO(holtgrew): Why conversion to boolean? operator bool () const { // Using != 0 instead of implicit/explicit task here to suppress // performance warning C4800 in Visual Studio. return data_pointer != 0; } TValue * operator -> () const { return & data_pointer->data_value; } }; ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline bool atEnd(Iter<TSkiplist, SkiplistIterator> & it) { return (!it.data_pointer); } ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline void goNext(Iter<TSkiplist, SkiplistIterator> & it) { it.data_pointer = it.data_pointer->data_next[0].data_element; } ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline typename Value<TSkiplist>::Type & value(Iter<TSkiplist, SkiplistIterator> & it) { return it.data_pointer->data_value; } template <typename TSkiplist> inline typename Value<TSkiplist>::Type & value(Iter<TSkiplist, SkiplistIterator> const & it) { return it.data_pointer->data_value; } ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline typename Key<TSkiplist>::Type const & key(Iter<TSkiplist, SkiplistIterator> & it) { return key(it.data_pointer->data_value); } template <typename TSkiplist> inline typename Key<TSkiplist>::Type const & key(Iter<TSkiplist, SkiplistIterator> const & it) { return key(it.data_pointer->data_value); } ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline typename Cargo<TSkiplist>::Type & cargo(Iter<TSkiplist, SkiplistIterator> & it) { return cargo(it.data_pointer->data_value); } template <typename TSkiplist> inline typename Cargo<TSkiplist>::Type & cargo(Iter<TSkiplist, SkiplistIterator> const & it) { return cargo(it.data_pointer->data_value); } ////////////////////////////////////////////////////////////////////////////// template <typename TSkiplist> inline bool operator == (Iter<TSkiplist, SkiplistIterator> const & left, Iter<TSkiplist, SkiplistIterator> const & right) { return left.data_pointer == right.data_pointer; } template <typename TSkiplist> inline bool operator != (Iter<TSkiplist, SkiplistIterator> const & left, Iter<TSkiplist, SkiplistIterator> const & right) { return left.data_pointer != right.data_pointer; } //////////////////////////////////////////////////////////////////////////////// //____________________________________________________________________________ ////////////////////////////////////////////////////////////////////////////// } #endif
{'content_hash': '9c61732d0e47b861781d5a6446d4a6d1', 'timestamp': '', 'source': 'github', 'line_count': 1127, 'max_line_length': 134, 'avg_line_length': 30.19254658385093, 'alnum_prop': 0.5805389837482, 'repo_name': 'xp3i4/seqan', 'id': '2f55f0c70ca0115b7a3d8da62cd07cc89f919731', 'size': '34027', 'binary': False, 'copies': '21', 'ref': 'refs/heads/master', 'path': 'include/seqan/map/map_skiplist.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Awk', 'bytes': '6549'}, {'name': 'C', 'bytes': '153286'}, {'name': 'C++', 'bytes': '20543202'}, {'name': 'CMake', 'bytes': '395123'}, {'name': 'CSS', 'bytes': '467535'}, {'name': 'Cuda', 'bytes': '29136'}, {'name': 'GLSL', 'bytes': '1140'}, {'name': 'Groff', 'bytes': '449001'}, {'name': 'HTML', 'bytes': '419485'}, {'name': 'JavaScript', 'bytes': '174233'}, {'name': 'Makefile', 'bytes': '7301'}, {'name': 'Objective-C', 'bytes': '377218'}, {'name': 'PHP', 'bytes': '48846'}, {'name': 'Perl', 'bytes': '6909'}, {'name': 'Python', 'bytes': '1132765'}, {'name': 'R', 'bytes': '34940'}, {'name': 'Shell', 'bytes': '95280'}, {'name': 'Tcl', 'bytes': '3861'}, {'name': 'TeX', 'bytes': '6936'}]}
package com.snowplowanalytics package snowplow package enrich package common package enrichments package registry // Maven Artifact import org.apache.maven.artifact.versioning.DefaultArtifactVersion // Scala import scala.util.control.NonFatal // Scalaz import scalaz._ import Scalaz._ // ua-parser import ua_parser.Parser import ua_parser.Client import ua_parser.Client // json4s import org.json4s._ import org.json4s.JValue import org.json4s.JsonDSL._ import org.json4s.jackson.JsonMethods._ // Iglu import iglu.client.{ SchemaCriterion, SchemaKey } import utils.ScalazJson4sUtils /** * Companion object. Lets us create a UaParserEnrichment * from a JValue. */ object UaParserEnrichmentConfig extends ParseableEnrichment { val supportedSchema = SchemaCriterion("com.snowplowanalytics.snowplow", "ua_parser_config", "jsonschema", 1, 0) def parse(config: JValue, schemaKey: SchemaKey): ValidatedNelMessage[UaParserEnrichment.type] = isParseable(config, schemaKey).map(_ => UaParserEnrichment) } /** * Config for an ua_parser_config enrichment * * Uses uap-java library to parse client attributes */ case object UaParserEnrichment extends Enrichment { val version = new DefaultArtifactVersion("0.1.0") val uaParser = new Parser() /* * Adds a period in front of a not-null version element */ def prependDot(versionElement: String): String = { if (versionElement != null) { "." + versionElement } else { "" } } /* * Prepends space before the versionElement */ def prependSpace(versionElement: String): String = { if (versionElement != null) { " " + versionElement } else { "" } } /* * Checks for null value in versionElement for family parameter */ def checkNull(versionElement: String): String = { if (versionElement == null) { "" } else { versionElement } } /** * Extracts the client attributes * from a useragent string, using * UserAgentEnrichment. * * @param useragent The useragent * String to extract from. * Should be encoded (i.e. * not previously decoded). * @return the json or * the message of the * exception, boxed in a * Scalaz Validation */ def extractUserAgent(useragent: String): Validation[String, JsonAST.JObject] = { val c = try { uaParser.parse(useragent) } catch { case NonFatal(e) => return "Exception parsing useragent [%s]: [%s]".format(useragent, e.getMessage).fail } // To display useragent version val useragentVersion = checkNull(c.userAgent.family) + prependSpace(c.userAgent.major) + prependDot(c.userAgent.minor) + prependDot(c.userAgent.patch) // To display operating system version val osVersion = checkNull(c.os.family) + prependSpace(c.os.major) + prependDot(c.os.minor) + prependDot(c.os.patch) + prependDot(c.os.patchMinor) val json = ( ("schema" -> "iglu:com.snowplowanalytics.snowplow/ua_parser_context/jsonschema/1-0-0") ~ ("data" -> ("useragentFamily" -> c.userAgent.family) ~ ("useragentMajor" -> c.userAgent.major) ~ ("useragentMinor" -> c.userAgent.minor) ~ ("useragentPatch" -> c.userAgent.patch) ~ ("useragentVersion" -> useragentVersion) ~ ("osFamily" -> c.os.family) ~ ("osMajor" -> c.os.major) ~ ("osMinor" -> c.os.minor) ~ ("osPatch" -> c.os.patch) ~ ("osPatchMinor" -> c.os.patchMinor) ~ ("osVersion" -> osVersion) ~ ("deviceFamily" -> c.device.family) ) ) json.success } }
{'content_hash': '6862f3ad9756b4f7df446af8e9eeddc6', 'timestamp': '', 'source': 'github', 'line_count': 139, 'max_line_length': 162, 'avg_line_length': 28.640287769784173, 'alnum_prop': 0.5995980909319266, 'repo_name': 'nakulgan/snowplow', 'id': '738f26b9adcc2df3173eabe8c6ee42dd15a35ee1', 'size': '4681', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': '3-enrich/scala-common-enrich/src/main/scala/com.snowplowanalytics.snowplow.enrich/common/enrichments/registry/UaParserEnrichment.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '119'}, {'name': 'Clojure', 'bytes': '18945'}, {'name': 'HTML', 'bytes': '3654'}, {'name': 'Java', 'bytes': '38516'}, {'name': 'JavaScript', 'bytes': '7677'}, {'name': 'LookML', 'bytes': '71281'}, {'name': 'PLpgSQL', 'bytes': '60494'}, {'name': 'Python', 'bytes': '2960'}, {'name': 'Ruby', 'bytes': '163473'}, {'name': 'Scala', 'bytes': '1713159'}, {'name': 'Shell', 'bytes': '29653'}, {'name': 'Thrift', 'bytes': '3707'}]}
#ifndef OPENCV_OPTIM_HPP #define OPENCV_OPTIM_HPP #include "opencv2/core.hpp" namespace cv { /** @addtogroup core_optim The algorithms in this section minimize or maximize function value within specified constraints or without any constraints. @{ */ /** @brief Basic interface for all solvers */ class CV_EXPORTS MinProblemSolver : public Algorithm { public: /** @brief Represents function being optimized */ class CV_EXPORTS Function { public: virtual ~Function() {} virtual int getDims() const = 0; virtual double getGradientEps() const; virtual double calc(const double* x) const = 0; virtual void getGradient(const double* x,double* grad); }; /** @brief Getter for the optimized function. The optimized function is represented by Function interface, which requires derivatives to implement the calc(double*) and getDim() methods to evaluate the function. @return Smart-pointer to an object that implements Function interface - it represents the function that is being optimized. It can be empty, if no function was given so far. */ virtual Ptr<Function> getFunction() const = 0; /** @brief Setter for the optimized function. *It should be called at least once before the call to* minimize(), as default value is not usable. @param f The new function to optimize. */ virtual void setFunction(const Ptr<Function>& f) = 0; /** @brief Getter for the previously set terminal criteria for this algorithm. @return Deep copy of the terminal criteria used at the moment. */ virtual TermCriteria getTermCriteria() const = 0; /** @brief Set terminal criteria for solver. This method *is not necessary* to be called before the first call to minimize(), as the default value is sensible. Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first. @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. */ virtual void setTermCriteria(const TermCriteria& termcrit) = 0; /** @brief actually runs the algorithm and performs the minimization. The sole input parameter determines the centroid of the starting simplex (roughly, it tells where to start), all the others (terminal criteria, initial step, function to be minimized) are supposed to be set via the setters before the call to this method or the default values (not always sensible) will be used. @param x The initial point, that will become a centroid of an initial simplex. After the algorithm will terminate, it will be setted to the point where the algorithm stops, the point of possible minimum. @return The value of a function at the point found. */ virtual double minimize(InputOutputArray x) = 0; }; /** @brief This class is used to perform the non-linear non-constrained minimization of a function, defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as **downhill simplex method**. The basic idea about the method can be obtained from <http://en.wikipedia.org/wiki/Nelder-Mead_method>. It should be noted, that this method, although deterministic, is rather a heuristic and therefore may converge to a local minima, not necessary a global one. It is iterative optimization technique, which at each step uses an information about the values of a function evaluated only at `n+1` points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At each step new point is chosen to evaluate function at, obtained value is compared with previous ones and based on this information simplex changes it's shape , slowly moving to the local minimum. Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear Conjugate Gradient method (which is also implemented in optim). Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. @note DownhillSolver is a derivative of the abstract interface cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to encapsulate the functionality, common to all non-linear optimization algorithms in the optim module. @note term criteria should meet following condition: @code termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 @endcode */ class CV_EXPORTS DownhillSolver : public MinProblemSolver { public: /** @brief Returns the initial step that will be used in downhill simplex algorithm. @param step Initial step that will be used in algorithm. Note, that although corresponding setter accepts column-vectors as well as row-vectors, this method will return a row-vector. @see DownhillSolver::setInitStep */ virtual void getInitStep(OutputArray step) const=0; /** @brief Sets the initial step that will be used in downhill simplex algorithm. Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional vectors that are used to determine the shape of initial simplex. Roughly said, initial point determines the position of a simplex (it will become simplex's centroid), while step determines the spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are the initial step and initial point respectively, the vertices of a simplex will be: \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes projections of the initial step of *n*-th coordinate (the result of projection is treated to be vector given by \f$s_i:=e_i\cdot\left<e_i\cdot s\right>\f$, where \f$e_i\f$ form canonical basis) @param step Initial step that will be used in algorithm. Roughly said, it determines the spread (size in each dimension) of an initial simplex. */ virtual void setInitStep(InputArray step)=0; /** @brief This function returns the reference to the ready-to-use DownhillSolver object. All the parameters are optional, so this procedure can be called even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() should be called upon the obtained object, if the respective parameters were not given to create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely equivalent (and will drop the same errors in the same way, should invalid input be detected). @param f Pointer to the function that will be minimized, similarly to the one you submit via MinProblemSolver::setFunction. @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one you submit via MinProblemSolver::setInitStep. @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via MinProblemSolver::setTermCriteria. */ static Ptr<DownhillSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<MinProblemSolver::Function>(), InputArray initStep=Mat_<double>(1,1,0.0), TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); }; /** @brief This class is used to perform the non-linear non-constrained minimization of a function with known gradient, defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. The implementation was done based on the beautifully clear explanatory article [An Introduction to the Conjugate Gradient Method Without the Agonizing Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for example <http://en.wikipedia.org/wiki/Conjugate_gradient_method>) for numerically solving the systems of linear equations. It should be noted, that this method, although deterministic, is rather a heuristic method and therefore may converge to a local minima, not necessary a global one. What is even more disastrous, most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may converge to it. Another obvious restriction is that it should be possible to compute the gradient of a function at any point, thus it is preferable to have analytic expression for gradient and computational burden should be born by the user. The latter responsibility is accompilished via the getGradient method of a MinProblemSolver::Function interface (which represents function being optimized). This method takes point a point in *n*-dimensional space (first argument represents the array of coordinates of that point) and comput its gradient (it should be stored in the second argument as an array). @note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. @note term criteria should meet following condition: @code termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 // or termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 @endcode */ class CV_EXPORTS ConjGradSolver : public MinProblemSolver { public: /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. All the parameters are optional, so this procedure can be called even without parameters at all. In this case, the default values will be used. As default value for terminal criteria are the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained object, if the function was not given to create(). Otherwise, the two ways (submit it to create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent (and will drop the same errors in the same way, should invalid input be detected). @param f Pointer to the function that will be minimized, similarly to the one you submit via MinProblemSolver::setFunction. @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via MinProblemSolver::setTermCriteria. */ static Ptr<ConjGradSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<ConjGradSolver::Function>(), TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); }; //! return codes for cv::solveLP() function enum SolveLPResult { SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) SOLVELP_SINGLE = 0, //!< there is only one maximum for target function SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned }; /** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: \f[\mbox{Maximize } c\cdot x\\ \mbox{Subject to:}\\ Ax\leq b\\ x\geq 0\f] Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. Simplex algorithm is one of many algorithms that are designed to handle this sort of problems efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve any problem written as above in polynomial time, while simplex method degenerates to exponential time for some special cases), it is well-studied, easy to implement and is shown to work well for real-life purposes. The particular implementation is taken almost verbatim from **Introduction to Algorithms, third edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the Bland's rule <http://en.wikipedia.org/wiki/Bland%27s_rule> is used to prevent cycling. @param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, in the latter case it is understood to correspond to \f$c^T\f$. @param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers. @param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the formulation above. It will contain 64-bit floating point numbers. @return One of cv::SolveLPResult */ CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z); //! @} }// cv #endif
{'content_hash': '669efb3c63740303fdb2086a5190d144', 'timestamp': '', 'source': 'github', 'line_count': 263, 'max_line_length': 130, 'avg_line_length': 52.361216730038024, 'alnum_prop': 0.7487473676566698, 'repo_name': 'VinesRobotics/VinesRobotics', 'id': '190d54310f0d727cdf1162f28a63f10c44005d01', 'size': '15857', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'OpenCV-android-sdk/sdk/native/jni/include/opencv2/core/optim.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '251635'}, {'name': 'C++', 'bytes': '3536132'}, {'name': 'CMake', 'bytes': '339995'}, {'name': 'Java', 'bytes': '2534949'}, {'name': 'Kotlin', 'bytes': '4556'}, {'name': 'Makefile', 'bytes': '6046'}, {'name': 'Objective-C', 'bytes': '7843'}]}
package org.springframework.ldap.control; import java.util.List; /** * Bean to encapsulate a result List and a {@link PagedResultsCookie} to use for * returning the results when using {@link PagedResultsRequestControl}. * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @deprecated */ public class PagedResult { private List<?> resultList; private PagedResultsCookie cookie; /** * Constructs a PagedResults using the supplied List and * {@link PagedResultsCookie}. * * @param resultList * the result list. * @param cookie * the cookie. */ public PagedResult(List<?> resultList, PagedResultsCookie cookie) { this.resultList = resultList; this.cookie = cookie; } /** * Get the cookie. * * @return the cookie. */ public PagedResultsCookie getCookie() { return cookie; } /** * Get the result list. * * @return the result list. */ public List<?> getResultList() { return resultList; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PagedResult that = (PagedResult) o; if (cookie != null ? !cookie.equals(that.cookie) : that.cookie != null) return false; if (resultList != null ? !resultList.equals(that.resultList) : that.resultList != null) return false; return true; } @Override public int hashCode() { int result = resultList != null ? resultList.hashCode() : 0; result = 31 * result + (cookie != null ? cookie.hashCode() : 0); return result; } }
{'content_hash': 'baa726f23e8db10b478af00775393fc1', 'timestamp': '', 'source': 'github', 'line_count': 71, 'max_line_length': 109, 'avg_line_length': 25.56338028169014, 'alnum_prop': 0.5730027548209367, 'repo_name': 'jaune162/spring-ldap', 'id': '0e53924297da06aeeb0a1e2a33745d8c52c16b76', 'size': '2449', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/org/springframework/ldap/control/PagedResult.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '727'}, {'name': 'HTML', 'bytes': '4289'}, {'name': 'Java', 'bytes': '2235555'}, {'name': 'PHP', 'bytes': '367'}, {'name': 'Python', 'bytes': '2635'}, {'name': 'Ruby', 'bytes': '531'}, {'name': 'Shell', 'bytes': '135'}, {'name': 'XSLT', 'bytes': '1220'}]}
<!DOCTYPE html> <html class="reftest-wait"> <title>WebVTT rendering, repositioning of 9 cues that overlap completely</title> <meta name="timeout" content="long"> <link rel="match" href="9_cues_overlapping_completely-ref.html"> <link rel="stylesheet" type="text/css" href="/fonts/ahem.css" /> <style> html { overflow:hidden } body { margin:0 } ::cue { font-family: Ahem, sans-serif; } ::cue(#cue1) { color: #000 } ::cue(#cue2) { color: #222 } ::cue(#cue3) { color: #444 } ::cue(#cue4) { color: #666 } ::cue(#cue5) { color: #888 } ::cue(#cue6) { color: #aaa } ::cue(#cue7) { color: #ccc } ::cue(#cue8) { color: #eee } ::cue(#cue9) { color: green } </style> <script src="/common/reftest-wait.js"></script> <video width="180" height="180" autoplay ontimeupdate="if (this.currentTime >= 1) { this.ontimeupdate = null; this.pause(); takeScreenshot(); }"> <source src="/media/white.webm" type="video/webm"> <source src="/media/white.mp4" type="video/mp4"> <track src="support/9_cues_overlapping_completely.vtt"> <script> document.getElementsByTagName('track')[0].track.mode = 'showing'; </script> </video> </html>
{'content_hash': '3ebf8a6125b474f066a81acebff587ad', 'timestamp': '', 'source': 'github', 'line_count': 50, 'max_line_length': 145, 'avg_line_length': 23.42, 'alnum_prop': 0.6319385140905209, 'repo_name': 'chromium/chromium', 'id': '606ded5095e1424892002abbda831ca8e9959110', 'size': '1171', 'binary': False, 'copies': '31', 'ref': 'refs/heads/main', 'path': 'third_party/blink/web_tests/external/wpt/webvtt/rendering/cues-with-video/processing-model/evil/9_cues_overlapping_completely.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package common import ( "fmt" "image" "image/color" "image/draw" "io/ioutil" "log" "github.com/EngoEngine/engo" "github.com/EngoEngine/gl" "github.com/golang/freetype" "github.com/golang/freetype/truetype" "golang.org/x/image/font" "golang.org/x/image/math/fixed" ) var ( dpi = float64(72) ) // Font keeps track of a specific Font. Fonts are explicit instances of a font file, // including the Size and Color. A separate font will have to be generated to get // different sizes and colors of the same font file. type Font struct { URL string Size float64 BG color.Color FG color.Color TTF *truetype.Font face font.Face } // Create is for loading fonts from the disk, given a location func (f *Font) Create() error { // Read and parse the font ttfBytes, err := ioutil.ReadFile(f.URL) if err != nil { return err } ttf, err := freetype.ParseFont(ttfBytes) if err != nil { return err } f.TTF = ttf f.face = truetype.NewFace(f.TTF, &truetype.Options{ Size: f.Size, DPI: dpi, Hinting: font.HintingFull, }) return nil } // CreatePreloaded is for loading fonts which have already been defined (and loaded) within Preload func (f *Font) CreatePreloaded() error { fontres, err := engo.Files.Resource(f.URL) if err != nil { return err } fnt, ok := fontres.(FontResource) if !ok { return fmt.Errorf("preloaded font is not of type `*truetype.Font`: %s", f.URL) } f.TTF = fnt.Font f.face = truetype.NewFace(f.TTF, &truetype.Options{ Size: f.Size, DPI: dpi, Hinting: font.HintingFull, }) return nil } // TextDimensions returns the total width, total height and total line size // of the input string written out in the Font. func (f *Font) TextDimensions(text string) (int, int, int) { fnt := f.TTF size := f.Size var ( totalWidth = fixed.Int26_6(0) totalHeight = fixed.Int26_6(size) maxYBearing = fixed.Int26_6(0) ) fupe := fixed.Int26_6(fnt.FUnitsPerEm()) for _, char := range text { idx := fnt.Index(char) hm := fnt.HMetric(fupe, idx) vm := fnt.VMetric(fupe, idx) g := truetype.GlyphBuf{} err := g.Load(fnt, fupe, idx, font.HintingNone) if err != nil { log.Println(err) return 0, 0, 0 } totalWidth += hm.AdvanceWidth yB := (vm.TopSideBearing * fixed.Int26_6(size)) / fupe if yB > maxYBearing { maxYBearing = yB } dY := (vm.AdvanceHeight * fixed.Int26_6(size)) / fupe if dY > totalHeight { totalHeight = dY } } // Scale to actual pixel size totalWidth *= fixed.Int26_6(size) totalWidth /= fupe return int(totalWidth), int(totalHeight), int(maxYBearing) } // RenderNRGBA returns an *image.NRGBA in the Font based on the input string. func (f *Font) RenderNRGBA(text string) *image.NRGBA { width, height, yBearing := f.TextDimensions(text) font := f.TTF size := f.Size if size <= 0 { panic("Font size cannot be <= 0") } // Default colors if f.FG == nil { f.FG = color.NRGBA{0, 0, 0, 0} } if f.BG == nil { f.BG = color.NRGBA{0, 0, 0, 0} } // Colors fg := image.NewUniform(f.FG) bg := image.NewUniform(f.BG) // Create the font context c := freetype.NewContext() nrgba := image.NewNRGBA(image.Rect(0, 0, width, height)) draw.Draw(nrgba, nrgba.Bounds(), bg, image.ZP, draw.Src) c.SetDPI(dpi) c.SetFont(font) c.SetFontSize(size) c.SetClip(nrgba.Bounds()) c.SetDst(nrgba) c.SetSrc(fg) // Draw the text. pt := fixed.P(0, yBearing) _, err := c.DrawString(text, pt) if err != nil { log.Println(err) return nil } return nrgba } // Render returns a Texture in the Font based on the input string. func (f *Font) Render(text string) Texture { nrgba := f.RenderNRGBA(text) // Create texture imObj := NewImageObject(nrgba) return NewTextureSingle(imObj) } // generateFontAtlas generates the font atlas for this given font, using the first `c` Unicode characters. func (f *Font) generateFontAtlas(c int) FontAtlas { atlas := FontAtlas{ XLocation: make([]float32, c), YLocation: make([]float32, c), Width: make([]float32, c), Height: make([]float32, c), OffsetX: make([]float32, c), RightSide: make([]float32, c), OffsetY: make([]float32, c), } currentX := float32(0) currentY := float32(0) // Default colors if f.FG == nil { f.FG = color.NRGBA{0, 0, 0, 0} } if f.BG == nil { f.BG = color.NRGBA{0, 0, 0, 0} } d := &font.Drawer{} d.Src = image.NewUniform(f.FG) d.Face = truetype.NewFace(f.TTF, &truetype.Options{ Size: f.Size, DPI: dpi, Hinting: font.HintingNone, }) lineHeight := d.Face.Metrics().Height ascent := d.Face.Metrics().Ascent prev := 0 for i := 0; i < c; i++ { bounds, adv, ok := d.Face.GlyphBounds(rune(i)) if !ok { continue } advance := float32(adv.Ceil()) atlas.Width[i] = float32((bounds.Max.X - bounds.Min.X).Ceil()) atlas.Height[i] = float32((bounds.Max.Y - bounds.Min.Y).Ceil()) atlas.OffsetX[i] = float32(bounds.Min.X.Ceil()) atlas.OffsetY[i] = float32((ascent + bounds.Min.Y).Ceil()) atlas.RightSide[i] = advance - float32(bounds.Max.X.Ceil()) if prev > 0 { currentX += float32(f.face.Kern(rune(prev), rune(i)).Ceil()) } //overlapping characters if atlas.Width[i] > advance { if atlas.OffsetX[i] < 0 { advance -= atlas.OffsetX[i] } else if advance < float32(bounds.Max.X.Ceil()) { advance = float32(bounds.Max.X.Ceil()) } } // position correction of overlapped characters if atlas.OffsetX[i] < 0 { currentX -= atlas.OffsetX[i] } if currentX+advance > 1024 { currentX = 0 currentY += float32(lineHeight.Ceil()) atlas.TotalHeight += float32(lineHeight.Ceil()) prev = 0 } if currentX+advance > atlas.TotalWidth { atlas.TotalWidth = currentX + advance } atlas.XLocation[i] = currentX atlas.YLocation[i] = currentY currentX += advance prev = i } // Create texture actual := image.NewNRGBA(image.Rect(0, 0, int(atlas.TotalWidth), int(atlas.TotalHeight))) draw.Draw(actual, actual.Bounds(), image.NewUniform(f.BG), image.ZP, draw.Src) d.Dst = actual for i := 0; i < c; i++ { _, _, ok := d.Face.GlyphBounds(rune(i)) if !ok { continue } d.Dot = fixed.P(int(atlas.XLocation[i]), int(atlas.YLocation[i]+float32(ascent.Ceil()))) d.DrawBytes([]byte{byte(i)}) // position correction atlas.XLocation[i] += atlas.OffsetX[i] atlas.YLocation[i] += atlas.OffsetY[i] } imObj := NewImageObject(actual) atlas.Texture = NewTextureSingle(imObj).id return atlas } // GenerateFontAtlas generates the font atlas for this given font, using the first `c` Unicode characters. // This should only be used if you are writing your own custom text shader. func (f *Font) GenerateFontAtlas(c int) FontAtlas { return f.generateFontAtlas(c) } // A FontAtlas is a representation of some of the Font characters, as an image type FontAtlas struct { Texture *gl.Texture // XLocation contains the X-coordinate of the starting position of all characters XLocation []float32 // YLocation contains the Y-coordinate of the starting position of all characters YLocation []float32 // Width contains the width in pixels of all the characters, including the spacing between characters Width []float32 // Height contains the height in pixels of all the characters Height []float32 // OffsetX is the offset of the glyph and the x-coordinate OffsetX []float32 // RightSide is the space left to the right of the glyph RightSide []float32 // OffsetY is the offset of the glyph and the y-coordinate OffsetY []float32 // TotalWidth is the total amount of pixels the `FontAtlas` is wide; useful for determining the `Viewport`, // which is relative to this value. TotalWidth float32 // TotalHeight is the total amount of pixels the `FontAtlas` is high; useful for determining the `Viewport`, // which is relative to this value. TotalHeight float32 } // Text represents a string drawn onto the screen, as used by the `TextShader`. type Text struct { // Font is the reference to the font you're using to render this. This includes the color, as well as the font size. Font *Font // Text is the actual text you want to draw. This may include newlines (\n). Text string // LineSpacing is the amount of additional spacing there is between the lines (when `Text` consists of multiple lines), // relative to the `Size` of the `Font`. LineSpacing float32 // LetterSpacing is the amount of additional spacing there is between the characters, relative to the `Size` of // the `Font`. LetterSpacing float32 // RightToLeft is an experimental variable used to indicate that subsequent characters come to the left of the // previous character. RightToLeft bool } // Texture returns nil because the Text is generated from a FontAtlas. This implements the common.Drawable interface. func (t Text) Texture() *gl.Texture { return nil } // Width returns the width of the Text generated from a FontAtlas. This implements the common.Drawable interface. func (t Text) Width() float32 { atlas, ok := atlasCache[*t.Font] if !ok { // Generate texture first atlas = t.Font.generateFontAtlas(200) atlasCache[*t.Font] = atlas } var currentX float32 var greatestX float32 for _, char := range t.Text { // TODO: this might not work for all characters switch { case char == '\n': if currentX > greatestX { greatestX = currentX } currentX = 0 continue case char < 32: // all system stuff should be ignored continue } currentX += atlas.Width[char] + float32(t.Font.Size)*t.LetterSpacing } if currentX > greatestX { return currentX } return greatestX } // Height returns the height the Text generated from a FontAtlas. This implements the common.Drawable interface. func (t Text) Height() float32 { atlas, ok := atlasCache[*t.Font] if !ok { // Generate texture first atlas = t.Font.generateFontAtlas(200) atlasCache[*t.Font] = atlas } var currentY float32 var totalY float32 var tallest float32 for _, char := range t.Text { // TODO: this might not work for all characters switch { case char == '\n': totalY += tallest tallest = float32(0) continue case char < 32: // all system stuff should be ignored continue } currentY = atlas.Height[char] + t.LineSpacing*atlas.Height[char] if currentY > tallest { tallest = currentY } } return totalY + tallest } // View returns 0, 0, 1, 1 because the Text is generated from a FontAtlas. This implements the common.Drawable interface. func (t Text) View() (float32, float32, float32, float32) { return 0, 0, 1, 1 } // Close does nothing because the Text is generated from a FontAtlas. There is no underlying texture to close. // This implements the common.Drawable interface. func (t Text) Close() {}
{'content_hash': 'e03d557c40c4ea1138bc0a43fe49c12e', 'timestamp': '', 'source': 'github', 'line_count': 400, 'max_line_length': 121, 'avg_line_length': 26.705, 'alnum_prop': 0.6857330087998502, 'repo_name': 'paked/engi', 'id': 'd9cf7502951571709c21cf126c66f0cd3301da9e', 'size': '10682', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'common/font.go', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Go', 'bytes': '155963'}]}
<?php namespace Elcodi\Component\Sitemap\Dumper; use Elcodi\Component\Sitemap\Dumper\Interfaces\SitemapDumperInterface; /** * Class FilesystemDumper. */ class FilesystemDumper implements SitemapDumperInterface { /** * Dumps a sitemap given a path. * * @param string $path Path * @param string $sitemap Sitemap * * @return $this Self object */ public function dump($path, $sitemap) { file_put_contents( $path, $sitemap ); return $this; } }
{'content_hash': '2eb900c3eab8d2181beb10e7b671eca6', 'timestamp': '', 'source': 'github', 'line_count': 31, 'max_line_length': 70, 'avg_line_length': 17.70967741935484, 'alnum_prop': 0.599271402550091, 'repo_name': 'elcodi/elcodi', 'id': 'fff3c55e3191dc55ac0a4b0ffab9411eb35180ee', 'size': '966', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/Elcodi/Component/Sitemap/Dumper/FilesystemDumper.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '963'}, {'name': 'PHP', 'bytes': '2297580'}, {'name': 'Shell', 'bytes': '480'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '42285ef5f357ab789762b7ad295239ae', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '842b0daa3f6d8fcee47adffc655688b3fa571936', 'size': '188', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Rhodophyta/Florideophyceae/Ceramiales/Rhodomelaceae/Polysiphonia/Polysiphonia elongata/ Syn. Polysiphonia schuebeleri/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Async; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Async { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddAwait), Shared] internal class CSharpAddAwaitCodeFixProvider : AbstractAddAwaitCodeFixProvider { /// <summary> /// Because this call is not awaited, execution of the current method continues before the call is completed. /// </summary> private const string CS4014 = nameof(CS4014); /// <summary> /// Since this is an async method, the return expression must be of type 'blah' rather than 'baz' /// </summary> private const string CS4016 = nameof(CS4016); /// <summary> /// cannot implicitly convert from 'X' to 'Y'. /// </summary> private const string CS0029 = nameof(CS0029); public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS0029, CS4014, CS4016); protected override async Task<DescriptionAndNode> GetDescriptionAndNodeAsync( SyntaxNode root, SyntaxNode oldNode, SemanticModel semanticModel, Diagnostic diagnostic, Document document, CancellationToken cancellationToken) { var newRoot = await GetNewRootAsync( root, oldNode, semanticModel, diagnostic, document, cancellationToken).ConfigureAwait(false); if (newRoot == null) { return default(DescriptionAndNode); } return new DescriptionAndNode(CSharpFeaturesResources.Insert_await, newRoot); } private Task<SyntaxNode> GetNewRootAsync( SyntaxNode root, SyntaxNode oldNode, SemanticModel semanticModel, Diagnostic diagnostic, Document document, CancellationToken cancellationToken) { var expression = oldNode as ExpressionSyntax; if (expression == null) { return SpecializedTasks.Default<SyntaxNode>(); } switch (diagnostic.Id) { case CS4014: return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression))); case CS4016: if (!DoesExpressionReturnTask(expression, semanticModel)) { return SpecializedTasks.Default<SyntaxNode>(); } return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression))); case CS0029: if (!DoesExpressionReturnGenericTaskWhoseArgumentsMatchLeftSide(expression, semanticModel, document.Project, cancellationToken)) { return SpecializedTasks.Default<SyntaxNode>(); } return Task.FromResult(root.ReplaceNode(oldNode, ConvertToAwaitExpression(expression))); default: return SpecializedTasks.Default<SyntaxNode>(); } } private static bool DoesExpressionReturnTask(ExpressionSyntax expression, SemanticModel semanticModel) { if (!TryGetTaskType(semanticModel, out var taskType)) { return false; } return TryGetExpressionType(expression, semanticModel, out var returnType) && semanticModel.Compilation.ClassifyConversion(taskType, returnType).Exists; } private static bool DoesExpressionReturnGenericTaskWhoseArgumentsMatchLeftSide(ExpressionSyntax expression, SemanticModel semanticModel, Project project, CancellationToken cancellationToken) { if (!IsInAsyncFunction(expression)) { return false; } if (!TryGetTaskType(semanticModel, out var taskType) || !TryGetExpressionType(expression, semanticModel, out var rightSideType)) { return false; } var compilation = semanticModel.Compilation; if (!compilation.ClassifyConversion(taskType, rightSideType).Exists) { return false; } if (!rightSideType.IsGenericType) { return false; } var typeArguments = rightSideType.TypeArguments; var typeInferer = project.LanguageServices.GetService<ITypeInferenceService>(); var inferredTypes = typeInferer.InferTypes(semanticModel, expression, cancellationToken); return typeArguments.Any(ta => inferredTypes.Any(it => compilation.ClassifyConversion(it, ta).Exists)); } private static bool IsInAsyncFunction(ExpressionSyntax expression) { foreach (var node in expression.Ancestors()) { switch (node.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: return (node as AnonymousFunctionExpressionSyntax)?.AsyncKeyword.IsMissing == false; case SyntaxKind.MethodDeclaration: return (node as MethodDeclarationSyntax)?.Modifiers.Any(SyntaxKind.AsyncKeyword) == true; default: continue; } } return false; } private static SyntaxNode ConvertToAwaitExpression(ExpressionSyntax expression) { if ((expression is BinaryExpressionSyntax || expression is ConditionalExpressionSyntax) && expression.HasTrailingTrivia) { var expWithTrailing = expression.WithoutLeadingTrivia(); var span = expWithTrailing.GetLocation().GetLineSpan().Span; if (span.Start.Line == span.End.Line && !expWithTrailing.DescendantTrivia().Any(trivia => trivia.IsKind(SyntaxKind.SingleLineCommentTrivia))) { return SyntaxFactory.AwaitExpression(SyntaxFactory.ParenthesizedExpression(expWithTrailing)) .WithLeadingTrivia(expression.GetLeadingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation); } } return SyntaxFactory.AwaitExpression(expression.WithoutTrivia().Parenthesize()) .WithTriviaFrom(expression) .WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation); } } }
{'content_hash': '49f69d12cf1a390cdc3b3def5685ce54', 'timestamp': '', 'source': 'github', 'line_count': 171, 'max_line_length': 198, 'avg_line_length': 42.30994152046784, 'alnum_prop': 0.6205943331029716, 'repo_name': 'a-ctor/roslyn', 'id': '6bfa6680ca873578f6aa0258014f467893818c1a', 'size': '7397', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'src/Features/CSharp/Portable/CodeFixes/Async/CSharpAddAwaitCodeFixProvider.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '20688'}, {'name': 'C#', 'bytes': '85699636'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'F#', 'bytes': '3632'}, {'name': 'Groovy', 'bytes': '9673'}, {'name': 'Makefile', 'bytes': '3339'}, {'name': 'PowerShell', 'bytes': '66445'}, {'name': 'Shell', 'bytes': '7465'}, {'name': 'Visual Basic', 'bytes': '63276193'}]}
export CFLAGS="-I$INCLUDE_PATH" export LDFLAGS="-L$LIBRARY_PATH" "$PYTHON" setup.py install --single-version-externally-managed --record=/tmp/record.txt
{'content_hash': 'f7966828ef12f65cad0164efa720a6c6', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 87, 'avg_line_length': 38.5, 'alnum_prop': 0.7597402597402597, 'repo_name': 'menpo/conda-recipes', 'id': 'ce687e457dfcf5b52d067590ddf72940f0be3145', 'size': '154', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'scikits-sparse/build.sh', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '16089'}, {'name': 'Python', 'bytes': '4302'}, {'name': 'Shell', 'bytes': '20599'}]}
module.exports = { description: 'Generate config for ember-cli-deploy lightning pack', normalizeEntityName: function() { // this prevents an error when the entityName is // not specified (since that doesn't actually matter // to us } };
{'content_hash': '00493e425cb34a5daf662106b1720a1a', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 69, 'avg_line_length': 31.875, 'alnum_prop': 0.6980392156862745, 'repo_name': 'ember-cli-deploy/ember-cli-deploy-lightning-pack', 'id': 'd5c58cc588f4a5b56fe839183ca978e198dc6a91', 'size': '255', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'blueprints/lightning-deploy-config/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '3372'}]}
package com.uppidy.android.sdk.connect; import java.util.Collections; import org.springframework.http.MediaType; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.social.oauth2.AccessGrant; import org.springframework.social.oauth2.OAuth2Template; import org.springframework.social.support.ClientHttpRequestFactorySelector; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; /** * Uppidy-specific extension of OAuth2Template to use a RestTemplate that recognizes form-encoded responses as "text/plain". * Uppidy token responses are form-encoded results with a content type of "text/plain", which prevents the FormHttpMessageConverter * registered by default from parsing the results. * @author [email protected] */ public class UppidyOAuth2Template extends OAuth2Template { public UppidyOAuth2Template(String clientId, String baseUrl) { super(clientId, "", baseUrl + "/oauth/authorize", baseUrl + "/oauth/token"); } /* @Override protected RestTemplate createRestTemplate() { RestTemplate restTemplate = new RestTemplate(ClientHttpRequestFactorySelector.getRequestFactory()); FormHttpMessageConverter messageConverter = new FormHttpMessageConverter() { public boolean canRead(Class<?> clazz, MediaType mediaType) { // always read as x-www-url-formencoded even though Uppidy sets contentType to text/plain return true; } }; restTemplate.setMessageConverters(Collections.<HttpMessageConverter<?>>singletonList(messageConverter)); return restTemplate; } @Override @SuppressWarnings("unchecked") protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) { MultiValueMap<String, String> response = getRestTemplate().postForObject(accessTokenUrl, parameters, MultiValueMap.class); String expires = response.getFirst("expires"); return new AccessGrant(response.getFirst("access_token"), null, null, expires != null ? Integer.valueOf(expires) : null); } */ /* public AccessGrant exchangeForAccess(String username, String password, MultiValueMap<String, String> additionalParameters) { MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.set("client_id", clientId); params.set("username", username); params.set("password", password); params.set("grant_type", "password"); if (additionalParameters != null) { params.putAll(additionalParameters); } return postForAccessGrant(accessTokenUrl, params); } */ }
{'content_hash': '9cbd9c7dc943555b7a48f3ea7b5e471f', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 131, 'avg_line_length': 43.11290322580645, 'alnum_prop': 0.790497568275346, 'repo_name': 'uppidy/uppidy-android-sdk', 'id': 'e664cdc87313f2c5681ef810dab778f5398c831c', 'size': '2673', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/uppidy/android/sdk/connect/UppidyOAuth2Template.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '69186'}]}
package ptr //go:generate go run -tags codegen generate.go //go:generate gofmt -w -s .
{'content_hash': '7311069b78cb5705cadc289b3212bc2f', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 46, 'avg_line_length': 22.0, 'alnum_prop': 0.7159090909090909, 'repo_name': 'tonistiigi/buildkit_poc', 'id': 'bc1f6996161a3fce23ddb54e5506e76574cba96f', 'size': '193', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/aws/smithy-go/ptr/doc.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '98756'}, {'name': 'Makefile', 'bytes': '928'}, {'name': 'Protocol Buffer', 'bytes': '2995'}, {'name': 'Shell', 'bytes': '2032'}]}
#include <sys/queue.h> #include <stdlib.h> #include <inttypes.h> #include <kernel/tee_common_unpg.h> #include <kernel/tee_common.h> #include <kernel/thread_defs.h> #include <kernel/panic.h> #include <mm/tee_mmu_defs.h> #include <kernel/tee_ta_manager.h> #include <kernel/tee_kta_trace.h> #include <kernel/misc.h> #include <kernel/tee_misc.h> #include <kernel/tz_proc.h> #include <mm/tee_pager.h> #include <mm/tee_mm.h> #include <mm/core_mmu.h> #include <tee/arch_svc.h> #include <arm.h> #include <tee/tee_cryp_provider.h> #include <tee_api_defines.h> #include <utee_defines.h> #include <trace.h> #include <util.h> struct tee_pager_abort_info { uint32_t abort_type; uint32_t fault_descr; vaddr_t va; uint32_t pc; struct thread_abort_regs *regs; }; enum tee_pager_fault_type { TEE_PAGER_FAULT_TYPE_USER_TA_PANIC, TEE_PAGER_FAULT_TYPE_PAGEABLE, TEE_PAGER_FAULT_TYPE_IGNORE, }; #ifdef CFG_WITH_PAGER struct tee_pager_area { const uint8_t *hashes; const uint8_t *store; uint32_t flags; tee_mm_entry_t *mm; TAILQ_ENTRY(tee_pager_area) link; }; static TAILQ_HEAD(tee_pager_area_head, tee_pager_area) tee_pager_area_head = TAILQ_HEAD_INITIALIZER(tee_pager_area_head); /* * struct tee_pager_pmem - Represents a physical page used for paging. * * @pgidx an index of the entry in tbl_info. The actual physical * address is stored here so even if the page isn't mapped, * there's always an MMU entry holding the physical address. * * @va_alias Virtual address where the physical page always is aliased. * Used during remapping of the page when the content need to * be updated before it's available at the new location. * * @area a pointer to the pager area */ struct tee_pager_pmem { unsigned pgidx; void *va_alias; struct tee_pager_area *area; TAILQ_ENTRY(tee_pager_pmem) link; }; /* The list of physical pages. The first page in the list is the oldest */ TAILQ_HEAD(tee_pager_pmem_head, tee_pager_pmem); static struct tee_pager_pmem_head tee_pager_pmem_head = TAILQ_HEAD_INITIALIZER(tee_pager_pmem_head); static struct tee_pager_pmem_head tee_pager_rw_pmem_head = TAILQ_HEAD_INITIALIZER(tee_pager_rw_pmem_head); /* number of pages hidden */ #define TEE_PAGER_NHIDE (tee_pager_npages / 3) /* Number of registered physical pages, used hiding pages. */ static size_t tee_pager_npages; #ifdef CFG_WITH_STATS static struct tee_pager_stats pager_stats; static inline void incr_ro_hits(void) { pager_stats.ro_hits++; } static inline void incr_rw_hits(void) { pager_stats.rw_hits++; } static inline void incr_hidden_hits(void) { pager_stats.hidden_hits++; } static inline void incr_zi_released(void) { pager_stats.zi_released++; } static inline void incr_npages_all(void) { pager_stats.npages_all++; } static inline void set_npages(void) { pager_stats.npages = tee_pager_npages; } void tee_pager_get_stats(struct tee_pager_stats *stats) { *stats = pager_stats; pager_stats.hidden_hits = 0; pager_stats.ro_hits = 0; pager_stats.rw_hits = 0; pager_stats.zi_released = 0; } #else /* CFG_WITH_STATS */ static inline void incr_ro_hits(void) { } static inline void incr_rw_hits(void) { } static inline void incr_hidden_hits(void) { } static inline void incr_zi_released(void) { } static inline void incr_npages_all(void) { } static inline void set_npages(void) { } void tee_pager_get_stats(struct tee_pager_stats *stats) { memset(stats, 0, sizeof(struct tee_pager_stats)); } #endif /* CFG_WITH_STATS */ /* * Reference to translation table used to map the virtual memory range * covered by the pager. */ static struct core_mmu_table_info tbl_info; static unsigned pager_lock = SPINLOCK_UNLOCK; /* Defines the range of the alias area */ static tee_mm_entry_t *pager_alias_area; /* * Physical pages are added in a stack like fashion to the alias area, * @pager_alias_next_free gives the address of next free entry if * @pager_alias_next_free is != 0 */ static uintptr_t pager_alias_next_free; void tee_pager_set_alias_area(tee_mm_entry_t *mm) { struct core_mmu_table_info ti; size_t tbl_va_size; unsigned idx; unsigned last_idx; vaddr_t smem = tee_mm_get_smem(mm); size_t nbytes = tee_mm_get_bytes(mm); DMSG("0x%" PRIxVA " - 0x%" PRIxVA, smem, smem + nbytes); TEE_ASSERT(!pager_alias_area); if (!core_mmu_find_table(smem, UINT_MAX, &ti)) { DMSG("Can't find translation table"); panic(); } if ((1 << ti.shift) != SMALL_PAGE_SIZE) { DMSG("Unsupported page size in translation table %u", 1 << ti.shift); panic(); } tbl_va_size = (1 << ti.shift) * ti.num_entries; if (!core_is_buffer_inside(smem, nbytes, ti.va_base, tbl_va_size)) { DMSG("area 0x%" PRIxVA " len 0x%zx doesn't fit it translation table 0x%" PRIxVA " len 0x%zx", smem, nbytes, ti.va_base, tbl_va_size); panic(); } TEE_ASSERT(!(smem & SMALL_PAGE_MASK)); TEE_ASSERT(!(nbytes & SMALL_PAGE_MASK)); pager_alias_area = mm; pager_alias_next_free = smem; /* Clear all mapping in the alias area */ idx = core_mmu_va2idx(&ti, smem); last_idx = core_mmu_va2idx(&ti, smem + nbytes); for (; idx < last_idx; idx++) core_mmu_set_entry(&ti, idx, 0, 0); } static void *pager_add_alias_page(paddr_t pa) { unsigned idx; struct core_mmu_table_info ti; uint32_t attr = TEE_MATTR_VALID_BLOCK | TEE_MATTR_GLOBAL | TEE_MATTR_CACHE_DEFAULT | TEE_MATTR_SECURE | TEE_MATTR_PRW; DMSG("0x%" PRIxPA, pa); TEE_ASSERT(pager_alias_next_free); if (!core_mmu_find_table(pager_alias_next_free, UINT_MAX, &ti)) panic(); idx = core_mmu_va2idx(&ti, pager_alias_next_free); core_mmu_set_entry(&ti, idx, pa, attr); pager_alias_next_free += SMALL_PAGE_SIZE; if (pager_alias_next_free >= (tee_mm_get_smem(pager_alias_area) + tee_mm_get_bytes(pager_alias_area))) pager_alias_next_free = 0; return (void *)core_mmu_idx2va(&ti, idx); } bool tee_pager_add_area(tee_mm_entry_t *mm, uint32_t flags, const void *store, const void *hashes) { struct tee_pager_area *area; size_t tbl_va_size; DMSG("0x%" PRIxPTR " - 0x%" PRIxPTR " : flags 0x%x, store %p, hashes %p", tee_mm_get_smem(mm), tee_mm_get_smem(mm) + (mm->size << mm->pool->shift), flags, store, hashes); if (flags & TEE_PAGER_AREA_RO) TEE_ASSERT(store && hashes); else if (flags & TEE_PAGER_AREA_RW) TEE_ASSERT(!store && !hashes); else panic(); if (!tbl_info.num_entries) { if (!core_mmu_find_table(tee_mm_get_smem(mm), UINT_MAX, &tbl_info)) return false; if ((1 << tbl_info.shift) != SMALL_PAGE_SIZE) { DMSG("Unsupported page size in translation table %u", 1 << tbl_info.shift); return false; } } tbl_va_size = (1 << tbl_info.shift) * tbl_info.num_entries; if (!core_is_buffer_inside(tee_mm_get_smem(mm), tee_mm_get_bytes(mm), tbl_info.va_base, tbl_va_size)) { DMSG("area 0x%" PRIxPTR " len 0x%zx doesn't fit it translation table 0x%" PRIxVA " len 0x%zx", tee_mm_get_smem(mm), tee_mm_get_bytes(mm), tbl_info.va_base, tbl_va_size); return false; } area = malloc(sizeof(struct tee_pager_area)); if (!area) return false; area->mm = mm; area->flags = flags; area->store = store; area->hashes = hashes; TAILQ_INSERT_TAIL(&tee_pager_area_head, area, link); return true; } static struct tee_pager_area *tee_pager_find_area(vaddr_t va) { struct tee_pager_area *area; TAILQ_FOREACH(area, &tee_pager_area_head, link) { tee_mm_entry_t *mm = area->mm; size_t offset = (va - mm->pool->lo) >> mm->pool->shift; if (offset >= mm->offset && offset < (mm->offset + mm->size)) return area; } return NULL; } static uint32_t get_area_mattr(struct tee_pager_area *area) { uint32_t attr = TEE_MATTR_VALID_BLOCK | TEE_MATTR_GLOBAL | TEE_MATTR_CACHE_DEFAULT | TEE_MATTR_SECURE | TEE_MATTR_PR; if (!(area->flags & TEE_PAGER_AREA_RO)) attr |= TEE_MATTR_PW; if (area->flags & TEE_PAGER_AREA_X) attr |= TEE_MATTR_PX; return attr; } static void tee_pager_load_page(struct tee_pager_area *area, vaddr_t page_va, void *va_alias) { size_t pg_idx = (page_va - area->mm->pool->lo) >> SMALL_PAGE_SHIFT; if (area->store) { size_t rel_pg_idx = pg_idx - area->mm->offset; const void *stored_page = area->store + rel_pg_idx * SMALL_PAGE_SIZE; memcpy(va_alias, stored_page, SMALL_PAGE_SIZE); incr_ro_hits(); } else { memset(va_alias, 0, SMALL_PAGE_SIZE); incr_rw_hits(); } } static void tee_pager_verify_page(struct tee_pager_area *area, vaddr_t page_va, void *va_alias) { size_t pg_idx = (page_va - area->mm->pool->lo) >> SMALL_PAGE_SHIFT; if (area->store) { size_t rel_pg_idx = pg_idx - area->mm->offset; const void *hash = area->hashes + rel_pg_idx * TEE_SHA256_HASH_SIZE; if (hash_sha256_check(hash, va_alias, SMALL_PAGE_SIZE) != TEE_SUCCESS) { EMSG("PH 0x%" PRIxVA " failed", page_va); panic(); } } } static bool tee_pager_unhide_page(vaddr_t page_va) { struct tee_pager_pmem *pmem; TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) { paddr_t pa; uint32_t attr; core_mmu_get_entry(&tbl_info, pmem->pgidx, &pa, &attr); if (!(attr & TEE_MATTR_HIDDEN_BLOCK)) continue; if (core_mmu_va2idx(&tbl_info, page_va) == pmem->pgidx) { /* page is hidden, show and move to back */ core_mmu_set_entry(&tbl_info, pmem->pgidx, pa, get_area_mattr(pmem->area)); TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link); TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link); /* TODO only invalidate entry touched above */ core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0); incr_hidden_hits(); return true; } } return false; } static void tee_pager_hide_pages(void) { struct tee_pager_pmem *pmem; size_t n = 0; TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) { paddr_t pa; uint32_t attr; if (n >= TEE_PAGER_NHIDE) break; n++; /* * we cannot hide pages when pmem->area is not defined as * unhide requires pmem->area to be defined */ if (!pmem->area) continue; core_mmu_get_entry(&tbl_info, pmem->pgidx, &pa, &attr); if (!(attr & TEE_MATTR_VALID_BLOCK)) continue; core_mmu_set_entry(&tbl_info, pmem->pgidx, pa, TEE_MATTR_HIDDEN_BLOCK); } /* TODO only invalidate entries touched above */ core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0); } /* * Find mapped pmem, hide and move to pageble pmem. * Return false if page was not mapped, and true if page was mapped. */ static bool tee_pager_release_one_zi(vaddr_t page_va) { struct tee_pager_pmem *pmem; unsigned pgidx; paddr_t pa; uint32_t attr; pgidx = core_mmu_va2idx(&tbl_info, page_va); core_mmu_get_entry(&tbl_info, pgidx, &pa, &attr); #ifdef TEE_PAGER_DEBUG_PRINT DMSG("%" PRIxVA " : %" PRIxPA "|%x", page_va, pa, attr); #endif TAILQ_FOREACH(pmem, &tee_pager_rw_pmem_head, link) { if (pmem->pgidx != pgidx) continue; core_mmu_set_entry(&tbl_info, pgidx, pa, TEE_MATTR_PHYS_BLOCK); TAILQ_REMOVE(&tee_pager_rw_pmem_head, pmem, link); tee_pager_npages++; set_npages(); TAILQ_INSERT_HEAD(&tee_pager_pmem_head, pmem, link); incr_zi_released(); return true; } return false; } #endif /*CFG_WITH_PAGER*/ #ifdef ARM32 /* Returns true if the exception originated from user mode */ static bool tee_pager_is_user_exception(struct tee_pager_abort_info *ai) { return (ai->regs->spsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_USR; } #endif /*ARM32*/ #ifdef ARM64 /* Returns true if the exception originated from user mode */ static bool tee_pager_is_user_exception(struct tee_pager_abort_info *ai) { uint32_t spsr = ai->regs->spsr; if (spsr & (SPSR_MODE_RW_32 << SPSR_MODE_RW_SHIFT)) return true; if (((spsr >> SPSR_64_MODE_EL_SHIFT) & SPSR_64_MODE_EL_MASK) == SPSR_64_MODE_EL0) return true; return false; } #endif /*ARM64*/ #ifdef ARM32 /* Returns true if the exception originated from abort mode */ static bool tee_pager_is_abort_in_abort_handler(struct tee_pager_abort_info *ai) { return (ai->regs->spsr & ARM32_CPSR_MODE_MASK) == ARM32_CPSR_MODE_ABT; } #endif /*ARM32*/ #ifdef ARM64 /* Returns true if the exception originated from abort mode */ static bool tee_pager_is_abort_in_abort_handler( struct tee_pager_abort_info *ai __unused) { return false; } #endif /*ARM64*/ static __unused const char *abort_type_to_str(uint32_t abort_type) { if (abort_type == THREAD_ABORT_DATA) return "data"; if (abort_type == THREAD_ABORT_PREFETCH) return "prefetch"; return "undef"; } static __unused void tee_pager_print_detailed_abort( struct tee_pager_abort_info *ai __unused, const char *ctx __unused) { EMSG_RAW("\n"); EMSG_RAW("%s %s-abort at address 0x%" PRIxVA "\n", ctx, abort_type_to_str(ai->abort_type), ai->va); #ifdef ARM32 EMSG_RAW(" fsr 0x%08x ttbr0 0x%08x ttbr1 0x%08x cidr 0x%X\n", ai->fault_descr, read_ttbr0(), read_ttbr1(), read_contextidr()); EMSG_RAW(" cpu #%zu cpsr 0x%08x\n", get_core_pos(), ai->regs->spsr); EMSG_RAW(" r0 0x%08x r4 0x%08x r8 0x%08x r12 0x%08x\n", ai->regs->r0, ai->regs->r4, ai->regs->r8, ai->regs->ip); EMSG_RAW(" r1 0x%08x r5 0x%08x r9 0x%08x sp 0x%08x\n", ai->regs->r1, ai->regs->r5, ai->regs->r9, read_mode_sp(ai->regs->spsr & CPSR_MODE_MASK)); EMSG_RAW(" r2 0x%08x r6 0x%08x r10 0x%08x lr 0x%08x\n", ai->regs->r2, ai->regs->r6, ai->regs->r10, read_mode_lr(ai->regs->spsr & CPSR_MODE_MASK)); EMSG_RAW(" r3 0x%08x r7 0x%08x r11 0x%08x pc 0x%08x\n", ai->regs->r3, ai->regs->r7, ai->regs->r11, ai->pc); #endif /*ARM32*/ #ifdef ARM64 EMSG_RAW(" esr 0x%08x ttbr0 0x%08" PRIx64 " ttbr1 0x%08" PRIx64 " cidr 0x%X\n", ai->fault_descr, read_ttbr0_el1(), read_ttbr1_el1(), read_contextidr_el1()); EMSG_RAW(" cpu #%zu cpsr 0x%08x\n", get_core_pos(), (uint32_t)ai->regs->spsr); EMSG_RAW("x0 %016" PRIx64 " x1 %016" PRIx64, ai->regs->x0, ai->regs->x1); EMSG_RAW("x2 %016" PRIx64 " x3 %016" PRIx64, ai->regs->x2, ai->regs->x3); EMSG_RAW("x4 %016" PRIx64 " x5 %016" PRIx64, ai->regs->x4, ai->regs->x5); EMSG_RAW("x6 %016" PRIx64 " x7 %016" PRIx64, ai->regs->x6, ai->regs->x7); EMSG_RAW("x8 %016" PRIx64 " x9 %016" PRIx64, ai->regs->x8, ai->regs->x9); EMSG_RAW("x10 %016" PRIx64 " x11 %016" PRIx64, ai->regs->x10, ai->regs->x11); EMSG_RAW("x12 %016" PRIx64 " x13 %016" PRIx64, ai->regs->x12, ai->regs->x13); EMSG_RAW("x14 %016" PRIx64 " x15 %016" PRIx64, ai->regs->x14, ai->regs->x15); EMSG_RAW("x16 %016" PRIx64 " x17 %016" PRIx64, ai->regs->x16, ai->regs->x17); EMSG_RAW("x18 %016" PRIx64 " x19 %016" PRIx64, ai->regs->x18, ai->regs->x19); EMSG_RAW("x20 %016" PRIx64 " x21 %016" PRIx64, ai->regs->x20, ai->regs->x21); EMSG_RAW("x22 %016" PRIx64 " x23 %016" PRIx64, ai->regs->x22, ai->regs->x23); EMSG_RAW("x24 %016" PRIx64 " x25 %016" PRIx64, ai->regs->x24, ai->regs->x25); EMSG_RAW("x26 %016" PRIx64 " x27 %016" PRIx64, ai->regs->x26, ai->regs->x27); EMSG_RAW("x28 %016" PRIx64 " x29 %016" PRIx64, ai->regs->x28, ai->regs->x29); EMSG_RAW("x30 %016" PRIx64 " elr %016" PRIx64, ai->regs->x30, ai->regs->elr); EMSG_RAW("sp_el0 %016" PRIx64, ai->regs->sp_el0); #endif /*ARM64*/ } static void tee_pager_print_user_abort(struct tee_pager_abort_info *ai __unused) { #ifdef CFG_TEE_CORE_TA_TRACE tee_pager_print_detailed_abort(ai, "user TA"); tee_ta_dump_current(); #endif } static void tee_pager_print_abort(struct tee_pager_abort_info *ai __unused) { #if (TRACE_LEVEL >= TRACE_INFO) tee_pager_print_detailed_abort(ai, "core"); #endif /*TRACE_LEVEL >= TRACE_DEBUG*/ } static void tee_pager_print_error_abort( struct tee_pager_abort_info *ai __unused) { #if (TRACE_LEVEL >= TRACE_INFO) /* full verbose log at DEBUG level */ tee_pager_print_detailed_abort(ai, "core"); #else #ifdef ARM32 EMSG("%s-abort at 0x%" PRIxVA "\n" "FSR 0x%x PC 0x%x TTBR0 0x%X CONTEXIDR 0x%X\n" "CPUID 0x%x CPSR 0x%x (read from SPSR)", abort_type_to_str(ai->abort_type), ai->va, ai->fault_descr, ai->pc, read_ttbr0(), read_contextidr(), read_mpidr(), read_spsr()); #endif /*ARM32*/ #ifdef ARM64 EMSG("%s-abort at 0x%" PRIxVA "\n" "ESR 0x%x PC 0x%x TTBR0 0x%" PRIx64 " CONTEXIDR 0x%X\n" "CPUID 0x%" PRIx64 " CPSR 0x%x (read from SPSR)", abort_type_to_str(ai->abort_type), ai->va, ai->fault_descr, ai->pc, read_ttbr0_el1(), read_contextidr_el1(), read_mpidr_el1(), (uint32_t)ai->regs->spsr); #endif /*ARM64*/ #endif /*TRACE_LEVEL >= TRACE_DEBUG*/ } static enum tee_pager_fault_type tee_pager_get_fault_type( struct tee_pager_abort_info *ai) { if (tee_pager_is_user_exception(ai)) { tee_pager_print_user_abort(ai); DMSG("[TEE_PAGER] abort in User mode (TA will panic)"); return TEE_PAGER_FAULT_TYPE_USER_TA_PANIC; } if (tee_pager_is_abort_in_abort_handler(ai)) { tee_pager_print_error_abort(ai); EMSG("[PAGER] abort in abort handler (trap CPU)"); panic(); } if (ai->abort_type == THREAD_ABORT_UNDEF) { tee_pager_print_error_abort(ai); EMSG("[TEE_PAGER] undefined abort (trap CPU)"); panic(); } switch (core_mmu_get_fault_type(ai->fault_descr)) { case CORE_MMU_FAULT_ALIGNMENT: tee_pager_print_error_abort(ai); EMSG("[TEE_PAGER] alignement fault! (trap CPU)"); panic(); break; case CORE_MMU_FAULT_ACCESS_BIT: tee_pager_print_error_abort(ai); EMSG("[TEE_PAGER] access bit fault! (trap CPU)"); panic(); break; case CORE_MMU_FAULT_DEBUG_EVENT: tee_pager_print_abort(ai); DMSG("[TEE_PAGER] Ignoring debug event!"); return TEE_PAGER_FAULT_TYPE_IGNORE; case CORE_MMU_FAULT_TRANSLATION: case CORE_MMU_FAULT_WRITE_PERMISSION: case CORE_MMU_FAULT_READ_PERMISSION: return TEE_PAGER_FAULT_TYPE_PAGEABLE; case CORE_MMU_FAULT_ASYNC_EXTERNAL: tee_pager_print_abort(ai); DMSG("[TEE_PAGER] Ignoring async external abort!"); return TEE_PAGER_FAULT_TYPE_IGNORE; case CORE_MMU_FAULT_OTHER: default: tee_pager_print_abort(ai); DMSG("[TEE_PAGER] Unhandled fault!"); return TEE_PAGER_FAULT_TYPE_IGNORE; } } #ifdef CFG_WITH_PAGER /* Finds the oldest page and remaps it for the new virtual address */ static bool tee_pager_get_page(struct tee_pager_abort_info *ai, struct tee_pager_area *area, struct tee_pager_pmem **pmem_ret, paddr_t *pa_ret) { unsigned pgidx = core_mmu_va2idx(&tbl_info, ai->va); struct tee_pager_pmem *pmem; paddr_t pa; uint32_t attr; core_mmu_get_entry(&tbl_info, pgidx, &pa, &attr); assert(!(attr & (TEE_MATTR_VALID_BLOCK | TEE_MATTR_HIDDEN_BLOCK))); if (attr & TEE_MATTR_PHYS_BLOCK) { /* * There's an pmem entry using this mmu entry, let's use * that entry in the new mapping. */ TAILQ_FOREACH(pmem, &tee_pager_pmem_head, link) { if (pmem->pgidx == pgidx) break; } if (!pmem) { DMSG("Couldn't find pmem for pgidx %u", pgidx); return false; } } else { pmem = TAILQ_FIRST(&tee_pager_pmem_head); if (!pmem) { DMSG("No pmem entries"); return false; } core_mmu_get_entry(&tbl_info, pmem->pgidx, &pa, &attr); core_mmu_set_entry(&tbl_info, pmem->pgidx, 0, 0); } pmem->pgidx = pgidx; pmem->area = area; core_mmu_set_entry(&tbl_info, pgidx, pa, TEE_MATTR_PHYS_BLOCK); TAILQ_REMOVE(&tee_pager_pmem_head, pmem, link); if (area->store) { /* move page to back */ TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link); } else { /* Move page to rw list */ TEE_ASSERT(tee_pager_npages > 0); tee_pager_npages--; set_npages(); TAILQ_INSERT_TAIL(&tee_pager_rw_pmem_head, pmem, link); } /* TODO only invalidate entries touched above */ core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0); *pmem_ret = pmem; *pa_ret = pa; return true; } static bool pager_check_access(struct tee_pager_abort_info *ai) { unsigned pgidx = core_mmu_va2idx(&tbl_info, ai->va); uint32_t attr; core_mmu_get_entry(&tbl_info, pgidx, NULL, &attr); /* Not mapped */ if (!(attr & TEE_MATTR_VALID_BLOCK)) return false; /* Not readable, should not happen */ if (!(attr & TEE_MATTR_PR)) { tee_pager_print_error_abort(ai); panic(); } switch (core_mmu_get_fault_type(ai->fault_descr)) { case CORE_MMU_FAULT_TRANSLATION: case CORE_MMU_FAULT_READ_PERMISSION: if (ai->abort_type == THREAD_ABORT_PREFETCH && !(attr & TEE_MATTR_PX)) { /* Attempting to execute from an NOX page */ tee_pager_print_error_abort(ai); panic(); } /* Since the page is mapped now it's OK */ return true; case CORE_MMU_FAULT_WRITE_PERMISSION: if (!(attr & TEE_MATTR_PW)) { /* Attempting to write to an RO page */ tee_pager_print_error_abort(ai); panic(); } return true; default: /* Some fault we can't deal with */ tee_pager_print_error_abort(ai); panic(); } } static void tee_pager_handle_fault(struct tee_pager_abort_info *ai) { struct tee_pager_area *area; vaddr_t page_va = ai->va & ~SMALL_PAGE_MASK; uint32_t exceptions; #ifdef TEE_PAGER_DEBUG_PRINT tee_pager_print_abort(ai); #endif /* check if the access is valid */ area = tee_pager_find_area(ai->va); if (!area) { tee_pager_print_abort(ai); DMSG("Invalid addr 0x%" PRIxVA, ai->va); panic(); } /* * We're updating pages that can affect several active CPUs at a * time below. We end up here because a thread tries to access some * memory that isn't available. We have to be careful when making * that memory available as other threads may succeed in accessing * that address the moment after we've made it available. * * That means that we can't just map the memory and populate the * page, instead we use the aliased mapping to populate the page * and once everything is ready we map it. */ exceptions = thread_mask_exceptions(THREAD_EXCP_IRQ); cpu_spin_lock(&pager_lock); if (!tee_pager_unhide_page(page_va)) { struct tee_pager_pmem *pmem = NULL; paddr_t pa = 0; /* * The page wasn't hidden, but some other core may have * updated the table entry before we got here. */ if (pager_check_access(ai)) { /* * Kind of access is OK with the mapping, we're * done here because the fault has already been * dealt with by another core. */ goto out; } if (!tee_pager_get_page(ai, area, &pmem, &pa)) { tee_pager_print_abort(ai); panic(); } /* load page code & data */ tee_pager_load_page(area, page_va, pmem->va_alias); tee_pager_verify_page(area, page_va, pmem->va_alias); /* * We've updated the page using the aliased mapping and * some cache maintenence is now needed if it's an * executable page. * * Since the d-cache is a Physically-indexed, * physically-tagged (PIPT) cache we can clean the aliased * address instead of the real virtual address. * * The i-cache can also be PIPT, but may be something else * to, to keep it simple we invalidate the entire i-cache. * As a future optimization we may invalidate only the * aliased area if it a PIPT cache else the entire cache. */ if (area->flags & TEE_PAGER_AREA_X) { /* * Doing these operations to LoUIS (Level of * unification, Inner Shareable) would be enough */ cache_maintenance_l1(DCACHE_AREA_CLEAN, pmem->va_alias, SMALL_PAGE_SIZE); cache_maintenance_l1(ICACHE_INVALIDATE, NULL, 0); } core_mmu_set_entry(&tbl_info, pmem->pgidx, pa, get_area_mattr(area)); #ifdef TEE_PAGER_DEBUG_PRINT DMSG("Mapped 0x%" PRIxVA " -> 0x%" PRIxPA, core_mmu_idx2va(&tbl_info, pmem->pgidx), pa); #endif } tee_pager_hide_pages(); out: cpu_spin_unlock(&pager_lock); thread_unmask_exceptions(exceptions); } #else /*CFG_WITH_PAGER*/ static void tee_pager_handle_fault(struct tee_pager_abort_info *ai) { /* * Until PAGER is supported, trap CPU here. */ tee_pager_print_error_abort(ai); EMSG("Unexpected page fault! Trap CPU"); panic(); } #endif /*CFG_WITH_PAGER*/ #ifdef ARM32 static void set_abort_info(uint32_t abort_type, struct thread_abort_regs *regs, struct tee_pager_abort_info *ai) { switch (abort_type) { case THREAD_ABORT_DATA: ai->fault_descr = read_dfsr(); ai->va = read_dfar(); break; case THREAD_ABORT_PREFETCH: ai->fault_descr = read_ifsr(); ai->va = read_ifar(); break; default: ai->fault_descr = 0; ai->va = regs->elr; break; } ai->abort_type = abort_type; ai->pc = regs->elr; ai->regs = regs; } #endif /*ARM32*/ #ifdef ARM64 static void set_abort_info(uint32_t abort_type __unused, struct thread_abort_regs *regs, struct tee_pager_abort_info *ai) { ai->fault_descr = read_esr_el1(); switch ((ai->fault_descr >> ESR_EC_SHIFT) & ESR_EC_MASK) { case ESR_EC_IABT_EL0: case ESR_EC_IABT_EL1: ai->abort_type = THREAD_ABORT_PREFETCH; ai->va = read_far_el1(); break; case ESR_EC_DABT_EL0: case ESR_EC_DABT_EL1: case ESR_EC_SP_ALIGN: ai->abort_type = THREAD_ABORT_DATA; ai->va = read_far_el1(); break; default: ai->abort_type = THREAD_ABORT_UNDEF; ai->va = regs->elr; } ai->pc = regs->elr; ai->regs = regs; } #endif /*ARM64*/ #ifdef ARM32 static void handle_user_ta_panic(struct tee_pager_abort_info *ai) { /* * It was a user exception, stop user execution and return * to TEE Core. */ ai->regs->r0 = TEE_ERROR_TARGET_DEAD; ai->regs->r1 = true; ai->regs->r2 = 0xdeadbeef; ai->regs->elr = (uint32_t)thread_unwind_user_mode; ai->regs->spsr = read_cpsr(); ai->regs->spsr &= ~CPSR_MODE_MASK; ai->regs->spsr |= CPSR_MODE_SVC; ai->regs->spsr &= ~CPSR_FIA; ai->regs->spsr |= read_spsr() & CPSR_FIA; /* Select Thumb or ARM mode */ if (ai->regs->elr & 1) ai->regs->spsr |= CPSR_T; else ai->regs->spsr &= ~CPSR_T; } #endif /*ARM32*/ #ifdef ARM64 static void handle_user_ta_panic(struct tee_pager_abort_info *ai) { uint32_t daif; /* * It was a user exception, stop user execution and return * to TEE Core. */ ai->regs->x0 = TEE_ERROR_TARGET_DEAD; ai->regs->x1 = true; ai->regs->x2 = 0xdeadbeef; ai->regs->elr = (vaddr_t)thread_unwind_user_mode; ai->regs->sp_el0 = thread_get_saved_thread_sp(); daif = (ai->regs->spsr >> SPSR_32_AIF_SHIFT) & SPSR_32_AIF_MASK; /* XXX what about DAIF_D? */ ai->regs->spsr = SPSR_64(SPSR_64_MODE_EL1, SPSR_64_MODE_SP_EL0, daif); } #endif /*ARM64*/ void tee_pager_abort_handler(uint32_t abort_type, struct thread_abort_regs *regs) { struct tee_pager_abort_info ai; set_abort_info(abort_type, regs, &ai); switch (tee_pager_get_fault_type(&ai)) { case TEE_PAGER_FAULT_TYPE_IGNORE: break; case TEE_PAGER_FAULT_TYPE_USER_TA_PANIC: handle_user_ta_panic(&ai); break; case TEE_PAGER_FAULT_TYPE_PAGEABLE: default: tee_pager_handle_fault(&ai); break; } } #ifdef CFG_WITH_PAGER void tee_pager_add_pages(vaddr_t vaddr, size_t npages, bool unmap) { size_t n; DMSG("0x%" PRIxVA " - 0x%" PRIxVA " : %d", vaddr, vaddr + npages * SMALL_PAGE_SIZE, (int)unmap); /* setup memory */ for (n = 0; n < npages; n++) { struct tee_pager_pmem *pmem; tee_vaddr_t va = vaddr + n * SMALL_PAGE_SIZE; unsigned pgidx = core_mmu_va2idx(&tbl_info, va); paddr_t pa; uint32_t attr; core_mmu_get_entry(&tbl_info, pgidx, &pa, &attr); /* Ignore unmapped pages/blocks */ if (!(attr & TEE_MATTR_VALID_BLOCK)) continue; pmem = malloc(sizeof(struct tee_pager_pmem)); if (pmem == NULL) { DMSG("Can't allocate memory"); panic(); } pmem->pgidx = pgidx; pmem->va_alias = pager_add_alias_page(pa); if (unmap) { /* * Note that we're making the page inaccessible * with the TEE_MATTR_PHYS_BLOCK attribute to * indicate that the descriptor still holds a valid * physical address of a page. */ pmem->area = NULL; core_mmu_set_entry(&tbl_info, pgidx, pa, TEE_MATTR_PHYS_BLOCK); } else { /* * The page is still mapped, let's assign the area * and update the protection bits accordingly. */ pmem->area = tee_pager_find_area(va); core_mmu_set_entry(&tbl_info, pgidx, pa, get_area_mattr(pmem->area)); } tee_pager_npages++; incr_npages_all(); set_npages(); TAILQ_INSERT_TAIL(&tee_pager_pmem_head, pmem, link); } /* Invalidate secure TLB */ core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0); } void tee_pager_release_zi(vaddr_t vaddr, size_t size) { bool unmaped = false; uint32_t exceptions = thread_mask_exceptions(THREAD_EXCP_ALL); if ((vaddr & SMALL_PAGE_MASK) || (size & SMALL_PAGE_MASK)) panic(); for (; size; vaddr += SMALL_PAGE_SIZE, size -= SMALL_PAGE_SIZE) unmaped |= tee_pager_release_one_zi(vaddr); /* Invalidate secure TLB */ if (unmaped) core_tlb_maintenance(TLBINV_UNIFIEDTLB, 0); thread_set_exceptions(exceptions); } void *tee_pager_request_zi(size_t size) { tee_mm_entry_t *mm; if (!size) return NULL; mm = tee_mm_alloc(&tee_mm_vcore, ROUNDUP(size, SMALL_PAGE_SIZE)); if (!mm) return NULL; tee_pager_add_area(mm, TEE_PAGER_AREA_RW, NULL, NULL); return (void *)tee_mm_get_smem(mm); } #else /*CFG_WITH_PAGER*/ void tee_pager_get_stats(struct tee_pager_stats *stats) { memset(stats, 0, sizeof(struct tee_pager_stats)); } #endif /*CFG_WITH_PAGER*/
{'content_hash': '1581c88810aba8c2e9be8bd1db856d4e', 'timestamp': '', 'source': 'github', 'line_count': 1095, 'max_line_length': 96, 'avg_line_length': 26.281278538812785, 'alnum_prop': 0.658141635971923, 'repo_name': 'Microsoft/optee_os', 'id': '5f7707563d1c9447d6f3d05df04fba418cd238c7', 'size': '30168', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/arch/arm/mm/tee_pager.c', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '232630'}, {'name': 'Awk', 'bytes': '6649'}, {'name': 'C', 'bytes': '4965473'}, {'name': 'C++', 'bytes': '45693'}, {'name': 'HTML', 'bytes': '75678'}, {'name': 'Makefile', 'bytes': '145467'}, {'name': 'Python', 'bytes': '9500'}, {'name': 'Shell', 'bytes': '13758'}]}
@* * Copyright 2015 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *@ @(analyticsToken: Option[String], analyticsHost: String, assetsPrefix: String, ssoUrl: Option[String], scriptElem: Option[Html], gaCalls: Option[(String,String) => Html], analyticsAnonymizeIp: Boolean = true, analyticsAdditionalJs: Option[Html] = None) @analyticsToken match { case Some(token@_) if !token.equals("N/A") => { <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'); @gaCalls.fold { ga('create', '@token', '@analyticsHost'); ga('send', 'pageview', { 'anonymizeIp': @analyticsAnonymizeIp }); }{f => @f(analyticsHost, token) } @analyticsAdditionalJs </script> } case _ => {} } <script type="text/javascript">var ssoUrl = "@ssoUrl.getOrElse("")";</script> <script src="@assetsPrefix/javascripts/application.min.js" type="text/javascript"></script> @scriptElem
{'content_hash': '4e2b783c3f138e62282530ab70364952', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 91, 'avg_line_length': 38.291666666666664, 'alnum_prop': 0.6485310119695321, 'repo_name': 'alexanderjamesking/play-ui', 'id': '03c08ab727e49280fc48473d7c2d1c5e3a59c814', 'size': '1838', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/main/twirl/uk/gov/hmrc/play/views/layouts/footer.scala.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '44074'}, {'name': 'Scala', 'bytes': '39890'}]}
'use strict'; var path = require('path'); var BinWrapper = require('bin-wrapper'); var pkg = require('../package.json'); var url = 'https://github.com/wellington/wellington/releases/download/v' + pkg.version + '/'; module.exports = new BinWrapper() .src(url + 'wt_darwin_amd64.zip', 'darwin') .src('https://circle-artifacts.com/gh/wellington/wellington/548/artifacts/0/tmp/circle-artifacts.BlQjBpj/v0.8.1/linux_amd64/wt', 'linux') .dest( path.join(__dirname, '../vendor/wellington') ) .use( 'wt') .version('>=' + pkg.version);
{'content_hash': '58c9de8dbd1e86358e898947b74f37fb', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 138, 'avg_line_length': 44.416666666666664, 'alnum_prop': 0.6866791744840526, 'repo_name': 'astalick/wellington-bin', 'id': '3342c745c1477b4bb7c626acd1e1ae83fa7e4cc4', 'size': '533', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '1898'}]}
package libcontainerd import ( "errors" "fmt" "io" "path/filepath" "strings" "syscall" "github.com/Microsoft/hcsshim" "github.com/Sirupsen/logrus" ) type client struct { clientCommon // Platform specific properties below here (none presently on Windows) } // Win32 error codes that are used for various workarounds // These really should be ALL_CAPS to match golangs syscall library and standard // Win32 error conventions, but golint insists on CamelCase. const ( CoEClassstring = syscall.Errno(0x800401F3) // Invalid class string ErrorNoNetwork = syscall.Errno(1222) // The network is not present or not started ErrorBadPathname = syscall.Errno(161) // The specified path is invalid ErrorInvalidObject = syscall.Errno(0x800710D8) // The object identifier does not represent a valid object ) // defaultOwner is a tag passed to HCS to allow it to differentiate between // container creator management stacks. We hard code "docker" in the case // of docker. const defaultOwner = "docker" // Create is the entrypoint to create a container from a spec, and if successfully // created, start it too. func (clnt *client) Create(containerID string, spec Spec, options ...CreateOption) error { logrus.Debugln("LCD client.Create() with spec", spec) configuration := &hcsshim.ContainerConfig{ SystemType: "Container", Name: containerID, Owner: defaultOwner, VolumePath: spec.Root.Path, IgnoreFlushesDuringBoot: spec.Windows.FirstStart, LayerFolderPath: spec.Windows.LayerFolder, HostName: spec.Hostname, } if spec.Windows.Networking != nil { configuration.EndpointList = spec.Windows.Networking.EndpointList } if spec.Windows.Resources != nil { if spec.Windows.Resources.CPU != nil { if spec.Windows.Resources.CPU.Shares != nil { configuration.ProcessorWeight = *spec.Windows.Resources.CPU.Shares } if spec.Windows.Resources.CPU.Percent != nil { configuration.ProcessorMaximum = *spec.Windows.Resources.CPU.Percent * 100 // ProcessorMaximum is a value between 1 and 10000 } } if spec.Windows.Resources.Memory != nil { if spec.Windows.Resources.Memory.Limit != nil { configuration.MemoryMaximumInMB = *spec.Windows.Resources.Memory.Limit / 1024 / 1024 } } if spec.Windows.Resources.Storage != nil { if spec.Windows.Resources.Storage.Bps != nil { configuration.StorageBandwidthMaximum = *spec.Windows.Resources.Storage.Bps } if spec.Windows.Resources.Storage.Iops != nil { configuration.StorageIOPSMaximum = *spec.Windows.Resources.Storage.Iops } if spec.Windows.Resources.Storage.SandboxSize != nil { configuration.StorageSandboxSize = *spec.Windows.Resources.Storage.SandboxSize } } } if spec.Windows.HvRuntime != nil { configuration.VolumePath = "" // Always empty for Hyper-V containers configuration.HvPartition = true configuration.HvRuntime = &hcsshim.HvRuntime{ ImagePath: spec.Windows.HvRuntime.ImagePath, } // Images with build version < 14350 don't support running with clone, but // Windows cannot automatically detect this. Explicitly block cloning in this // case. if build := buildFromVersion(spec.Platform.OSVersion); build > 0 && build < 14350 { configuration.HvRuntime.SkipTemplate = true } } if configuration.HvPartition { configuration.SandboxPath = filepath.Dir(spec.Windows.LayerFolder) } else { configuration.VolumePath = spec.Root.Path configuration.LayerFolderPath = spec.Windows.LayerFolder } for _, option := range options { if s, ok := option.(*ServicingOption); ok { configuration.Servicing = s.IsServicing break } } for _, layerPath := range spec.Windows.LayerPaths { _, filename := filepath.Split(layerPath) g, err := hcsshim.NameToGuid(filename) if err != nil { return err } configuration.Layers = append(configuration.Layers, hcsshim.Layer{ ID: g.ToString(), Path: layerPath, }) } // Add the mounts (volumes, bind mounts etc) to the structure mds := make([]hcsshim.MappedDir, len(spec.Mounts)) for i, mount := range spec.Mounts { mds[i] = hcsshim.MappedDir{ HostPath: mount.Source, ContainerPath: mount.Destination, ReadOnly: mount.Readonly} } configuration.MappedDirectories = mds hcsContainer, err := hcsshim.CreateContainer(containerID, configuration) if err != nil { return err } // Construct a container object for calling start on it. container := &container{ containerCommon: containerCommon{ process: process{ processCommon: processCommon{ containerID: containerID, client: clnt, friendlyName: InitFriendlyName, }, commandLine: strings.Join(spec.Process.Args, " "), }, processes: make(map[string]*process), }, ociSpec: spec, hcsContainer: hcsContainer, } container.options = options for _, option := range options { if err := option.Apply(container); err != nil { logrus.Error(err) } } // Call start, and if it fails, delete the container from our // internal structure, start will keep HCS in sync by deleting the // container there. logrus.Debugf("Create() id=%s, Calling start()", containerID) if err := container.start(); err != nil { clnt.deleteContainer(containerID) return err } logrus.Debugf("Create() id=%s completed successfully", containerID) return nil } // AddProcess is the handler for adding a process to an already running // container. It's called through docker exec. func (clnt *client) AddProcess(containerID, processFriendlyName string, procToAdd Process) error { clnt.lock(containerID) defer clnt.unlock(containerID) container, err := clnt.getContainer(containerID) if err != nil { return err } // Note we always tell HCS to // create stdout as it's required regardless of '-i' or '-t' options, so that // docker can always grab the output through logs. We also tell HCS to always // create stdin, even if it's not used - it will be closed shortly. Stderr // is only created if it we're not -t. createProcessParms := hcsshim.ProcessConfig{ EmulateConsole: procToAdd.Terminal, ConsoleSize: procToAdd.InitialConsoleSize, CreateStdInPipe: true, CreateStdOutPipe: true, CreateStdErrPipe: !procToAdd.Terminal, } // Take working directory from the process to add if it is defined, // otherwise take from the first process. if procToAdd.Cwd != "" { createProcessParms.WorkingDirectory = procToAdd.Cwd } else { createProcessParms.WorkingDirectory = container.ociSpec.Process.Cwd } // Configure the environment for the process createProcessParms.Environment = setupEnvironmentVariables(procToAdd.Env) createProcessParms.CommandLine = strings.Join(procToAdd.Args, " ") logrus.Debugf("commandLine: %s", createProcessParms.CommandLine) // Start the command running in the container. var stdout, stderr io.ReadCloser var stdin io.WriteCloser newProcess, err := container.hcsContainer.CreateProcess(&createProcessParms) if err != nil { logrus.Errorf("AddProcess %s CreateProcess() failed %s", containerID, err) return err } stdin, stdout, stderr, err = newProcess.Stdio() if err != nil { logrus.Errorf("%s getting std pipes failed %s", containerID, err) return err } iopipe := &IOPipe{Terminal: procToAdd.Terminal} iopipe.Stdin = createStdInCloser(stdin, newProcess) // TEMP: Work around Windows BS/DEL behavior. iopipe.Stdin = fixStdinBackspaceBehavior(iopipe.Stdin, container.ociSpec.Platform.OSVersion, procToAdd.Terminal) // Convert io.ReadClosers to io.Readers if stdout != nil { iopipe.Stdout = openReaderFromPipe(stdout) } if stderr != nil { iopipe.Stderr = openReaderFromPipe(stderr) } pid := newProcess.Pid() proc := &process{ processCommon: processCommon{ containerID: containerID, friendlyName: processFriendlyName, client: clnt, systemPid: uint32(pid), }, commandLine: createProcessParms.CommandLine, hcsProcess: newProcess, } // Add the process to the container's list of processes container.processes[processFriendlyName] = proc // Make sure the lock is not held while calling back into the daemon clnt.unlock(containerID) // Tell the engine to attach streams back to the client if err := clnt.backend.AttachStreams(processFriendlyName, *iopipe); err != nil { return err } // Lock again so that the defer unlock doesn't fail. (I really don't like this code) clnt.lock(containerID) // Spin up a go routine waiting for exit to handle cleanup go container.waitExit(proc, false) return nil } // Signal handles `docker stop` on Windows. While Linux has support for // the full range of signals, signals aren't really implemented on Windows. // We fake supporting regular stop and -9 to force kill. func (clnt *client) Signal(containerID string, sig int) error { var ( cont *container err error ) // Get the container as we need it to find the pid of the process. clnt.lock(containerID) defer clnt.unlock(containerID) if cont, err = clnt.getContainer(containerID); err != nil { return err } cont.manualStopRequested = true logrus.Debugf("lcd: Signal() containerID=%s sig=%d pid=%d", containerID, sig, cont.systemPid) if syscall.Signal(sig) == syscall.SIGKILL { // Terminate the compute system if err := cont.hcsContainer.Terminate(); err != nil { if err != hcsshim.ErrVmcomputeOperationPending { logrus.Errorf("Failed to terminate %s - %q", containerID, err) } } } else { // Terminate Process if err := cont.hcsProcess.Kill(); err != nil { // ignore errors logrus.Warnf("Failed to terminate pid %d in %s: %q", cont.systemPid, containerID, err) } } return nil } // While Linux has support for the full range of signals, signals aren't really implemented on Windows. // We try to terminate the specified process whatever signal is requested. func (clnt *client) SignalProcess(containerID string, processFriendlyName string, sig int) error { clnt.lock(containerID) defer clnt.unlock(containerID) cont, err := clnt.getContainer(containerID) if err != nil { return err } for _, p := range cont.processes { if p.friendlyName == processFriendlyName { return hcsshim.TerminateProcessInComputeSystem(containerID, p.systemPid) } } return fmt.Errorf("SignalProcess could not find process %s in %s", processFriendlyName, containerID) } // Resize handles a CLI event to resize an interactive docker run or docker exec // window. func (clnt *client) Resize(containerID, processFriendlyName string, width, height int) error { // Get the libcontainerd container object clnt.lock(containerID) defer clnt.unlock(containerID) cont, err := clnt.getContainer(containerID) if err != nil { return err } h, w := uint16(height), uint16(width) if processFriendlyName == InitFriendlyName { logrus.Debugln("Resizing systemPID in", containerID, cont.process.systemPid) return cont.process.hcsProcess.ResizeConsole(w, h) } for _, p := range cont.processes { if p.friendlyName == processFriendlyName { logrus.Debugln("Resizing exec'd process", containerID, p.systemPid) return p.hcsProcess.ResizeConsole(w, h) } } return fmt.Errorf("Resize could not find containerID %s to resize", containerID) } // Pause handles pause requests for containers func (clnt *client) Pause(containerID string) error { return errors.New("Windows: Containers cannot be paused") } // Resume handles resume requests for containers func (clnt *client) Resume(containerID string) error { return errors.New("Windows: Containers cannot be paused") } // Stats handles stats requests for containers func (clnt *client) Stats(containerID string) (*Stats, error) { return nil, errors.New("Windows: Stats not implemented") } // Restore is the handler for restoring a container func (clnt *client) Restore(containerID string, unusedOnWindows ...CreateOption) error { // TODO Windows: Implement this. For now, just tell the backend the container exited. logrus.Debugf("lcd Restore %s", containerID) return clnt.backend.StateChanged(containerID, StateInfo{ CommonStateInfo: CommonStateInfo{ State: StateExit, ExitCode: 1 << 31, }}) } // GetPidsForContainer returns a list of process IDs running in a container. // Although implemented, this is not used in Windows. func (clnt *client) GetPidsForContainer(containerID string) ([]int, error) { var pids []int clnt.lock(containerID) defer clnt.unlock(containerID) cont, err := clnt.getContainer(containerID) if err != nil { return nil, err } // Add the first process pids = append(pids, int(cont.containerCommon.systemPid)) // And add all the exec'd processes for _, p := range cont.processes { pids = append(pids, int(p.processCommon.systemPid)) } return pids, nil } // Summary returns a summary of the processes running in a container. // This is present in Windows to support docker top. In linux, the // engine shells out to ps to get process information. On Windows, as // the containers could be Hyper-V containers, they would not be // visible on the container host. However, libcontainerd does have // that information. func (clnt *client) Summary(containerID string) ([]Summary, error) { var s []Summary clnt.lock(containerID) defer clnt.unlock(containerID) cont, err := clnt.getContainer(containerID) if err != nil { return nil, err } // Add the first process s = append(s, Summary{ Pid: cont.containerCommon.systemPid, Command: cont.ociSpec.Process.Args[0]}) // And add all the exec'd processes for _, p := range cont.processes { s = append(s, Summary{ Pid: p.processCommon.systemPid, Command: p.commandLine}) } return s, nil } // UpdateResources updates resources for a running container. func (clnt *client) UpdateResources(containerID string, resources Resources) error { // Updating resource isn't supported on Windows // but we should return nil for enabling updating container return nil }
{'content_hash': 'ce29ec6e18d80ad0b049d75582967eac', 'timestamp': '', 'source': 'github', 'line_count': 442, 'max_line_length': 129, 'avg_line_length': 31.56108597285068, 'alnum_prop': 0.7278136200716846, 'repo_name': 'bluebreezecf/docker', 'id': 'efd693a37e0a2b424c79e65948686259f69249c0', 'size': '13950', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'libcontainerd/client_windows.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '3811'}, {'name': 'Go', 'bytes': '5353244'}, {'name': 'Makefile', 'bytes': '7740'}, {'name': 'PowerShell', 'bytes': '5978'}, {'name': 'Shell', 'bytes': '397941'}, {'name': 'VimL', 'bytes': '1350'}]}
/* Snowfall jquery plugin ==================================================================== LICENSE ==================================================================== Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== Version 1.51 Dec 2nd 2012 // fixed bug where snow collection didn't happen if a valid doctype was declared. Version 1.5 Oct 5th 2011 Added collecting snow! Uses the canvas element to collect snow. In order to initialize snow collection use the following $(document).snowfall({collection : 'element'}); element = any valid jquery selector. The plugin then creates a canvas above every element that matches the selector, and collects the snow. If there are a varrying amount of elements the flakes get assigned a random one on start they will collide. Version 1.4 Dec 8th 2010 Fixed issues (I hope) with scroll bars flickering due to snow going over the edge of the screen. Added round snowflakes via css, will not work for any version of IE. - Thanks to Luke Barker of http://www.infinite-eye.com/ Added shadows as an option via css again will not work with IE. The idea behind shadows, is to show flakes on lighter colored web sites - Thanks Yutt Version 1.3.1 Nov 25th 2010 Updated script that caused flakes not to show at all if plugin was initialized with no options, also added the fixes that Han Bongers suggested Developed by Jason Brown for any bugs or questions email me at loktar69@hotmail info on the plugin is located on Somethinghitme.com values for snow options are flakeCount, flakeColor, flakeIndex, minSize, maxSize, minSpeed, maxSpeed, round, true or false, makes the snowflakes rounded if the browser supports it. shadow true or false, gives the snowflakes a shadow if the browser supports it. Example Usage : $(document).snowfall({flakeCount : 100, maxSpeed : 10}); -or- $('#element').snowfall({flakeCount : 800, maxSpeed : 5, maxSize : 5}); -or with defaults- $(document).snowfall(); - To clear - $('#element').snowfall('clear'); */ // requestAnimationFrame polyfill from https://github.com/darius/requestAnimationFrame if (!Date.now) Date.now = function() { return new Date().getTime(); }; (function() { 'use strict'; var vendors = ['webkit', 'moz']; for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) { var vp = vendors[i]; window.requestAnimationFrame = window[vp+'RequestAnimationFrame']; window.cancelAnimationFrame = (window[vp+'CancelAnimationFrame'] || window[vp+'CancelRequestAnimationFrame']); } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) // iOS6 is buggy || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var lastTime = 0; window.requestAnimationFrame = function(callback) { var now = Date.now(); var nextTime = Math.max(lastTime + 16, now); return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); }; window.cancelAnimationFrame = clearTimeout; } }()); (function($){ $.snowfall = function(element, options){ var flakes = [], defaults = { flakeCount : 35, flakeColor : '#ffffff', flakePosition: 'absolute', flakeIndex: 999999, minSize : 1, maxSize : 2, minSpeed : 1, maxSpeed : 5, round : false, shadow : false, collection : false, collectionHeight : 40, deviceorientation : false }, options = $.extend(defaults, options), random = function random(min, max){ return Math.round(min + Math.random()*(max-min)); }; $(element).data("snowfall", this); // Snow flake object function Flake(_x, _y, _size, _speed){ // Flake properties this.x = _x; this.y = _y; this.size = _size; this.speed = _speed; this.step = 0; this.stepSize = random(1,10) / 100; if(options.collection){ this.target = canvasCollection[random(0,canvasCollection.length-1)]; } var flakeMarkup = null; if(options.image){ flakeMarkup = document.createElement("img"); flakeMarkup.src = options.image; }else{ flakeMarkup = document.createElement("div"); $(flakeMarkup).css({'background' : options.flakeColor}); } $(flakeMarkup).attr({ 'class': 'snowfall-flakes', }).css({ 'width' : this.size, 'height' : this.size, 'position' : options.flakePosition, 'top' : this.y, 'left' : this.x, 'fontSize' : 0, 'zIndex' : options.flakeIndex }); if($(element).get(0).tagName === $(document).get(0).tagName){ $('body').append($(flakeMarkup)); element = $('body'); }else{ $(element).append($(flakeMarkup)); } this.element = flakeMarkup; // Update function, used to update the snow flakes, and checks current snowflake against bounds this.update = function(){ this.y += this.speed; if(this.y > (elHeight) - (this.size + 6)){ this.reset(); } this.element.style.top = this.y + 'px'; this.element.style.left = this.x + 'px'; this.step += this.stepSize; if (doRatio === false) { this.x += Math.cos(this.step); } else { this.x += (doRatio + Math.cos(this.step)); } // Pileup check if(options.collection){ if(this.x > this.target.x && this.x < this.target.width + this.target.x && this.y > this.target.y && this.y < this.target.height + this.target.y){ var ctx = this.target.element.getContext("2d"), curX = this.x - this.target.x, curY = this.y - this.target.y, colData = this.target.colData; if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] !== undefined || curY+this.speed+this.size > this.target.height){ if(curY+this.speed+this.size > this.target.height){ while(curY+this.speed+this.size > this.target.height && this.speed > 0){ this.speed *= .5; } ctx.fillStyle = "#fff"; if(colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] == undefined){ colData[parseInt(curX)][parseInt(curY+this.speed+this.size)] = 1; ctx.fillRect(curX, (curY)+this.speed+this.size, this.size, this.size); }else{ colData[parseInt(curX)][parseInt(curY+this.speed)] = 1; ctx.fillRect(curX, curY+this.speed, this.size, this.size); } this.reset(); }else{ // flow to the sides this.speed = 1; this.stepSize = 0; if(parseInt(curX)+1 < this.target.width && colData[parseInt(curX)+1][parseInt(curY)+1] == undefined ){ // go left this.x++; }else if(parseInt(curX)-1 > 0 && colData[parseInt(curX)-1][parseInt(curY)+1] == undefined ){ // go right this.x--; }else{ //stop ctx.fillStyle = "#fff"; ctx.fillRect(curX, curY, this.size, this.size); colData[parseInt(curX)][parseInt(curY)] = 1; this.reset(); } } } } } if(this.x + this.size > (elWidth) - widthOffset || this.x < widthOffset){ this.reset(); } } // Resets the snowflake once it reaches one of the bounds set this.reset = function(){ this.y = 0; this.x = random(widthOffset, elWidth - widthOffset); this.stepSize = random(1,10) / 100; this.size = random((options.minSize * 100), (options.maxSize * 100)) / 100; this.element.style.width = this.size + 'px'; this.element.style.height = this.size + 'px'; this.speed = random(options.minSpeed, options.maxSpeed); } } // local vars var i = 0, elHeight = $(element).height(), elWidth = $(element).width(), widthOffset = 0, snowTimeout = 0; // Collection Piece ****************************** if(options.collection !== false){ var testElem = document.createElement('canvas'); if(!!(testElem.getContext && testElem.getContext('2d'))){ var canvasCollection = [], elements = $(options.collection), collectionHeight = options.collectionHeight; for(var i =0; i < elements.length; i++){ var bounds = elements[i].getBoundingClientRect(), $canvas = $('<canvas/>', { 'class' : 'snowfall-canvas' }), collisionData = []; if(bounds.top-collectionHeight > 0){ $('body').append($canvas); $canvas.css({ 'position' : options.flakePosition, 'left' : bounds.left + 'px', 'top' : bounds.top-collectionHeight + 'px' }) .prop({ width: bounds.width, height: collectionHeight }); for(var w = 0; w < bounds.width; w++){ collisionData[w] = []; } canvasCollection.push({ element : $canvas.get(0), x : bounds.left, y : bounds.top-collectionHeight, width : bounds.width, height: collectionHeight, colData : collisionData }); } } }else{ // Canvas element isnt supported options.collection = false; } } // ************************************************ // This will reduce the horizontal scroll bar from displaying, when the effect is applied to the whole page if($(element).get(0).tagName === $(document).get(0).tagName){ widthOffset = 25; } // Bind the window resize event so we can get the innerHeight again $(window).bind("resize", function(){ elHeight = $(element)[0].clientHeight; elWidth = $(element)[0].offsetWidth; }); // initialize the flakes for(i = 0; i < options.flakeCount; i+=1){ flakes.push(new Flake(random(widthOffset,elWidth - widthOffset), random(0, elHeight), random((options.minSize * 100), (options.maxSize * 100)) / 100, random(options.minSpeed, options.maxSpeed))); } // This adds the style to make the snowflakes round via border radius property if(options.round){ $('.snowfall-flakes').css({'-moz-border-radius' : options.maxSize, '-webkit-border-radius' : options.maxSize, 'border-radius' : options.maxSize}); } // This adds shadows just below the snowflake so they pop a bit on lighter colored web pages if(options.shadow){ $('.snowfall-flakes').css({'-moz-box-shadow' : '1px 1px 1px #555', '-webkit-box-shadow' : '1px 1px 1px #555', 'box-shadow' : '1px 1px 1px #555'}); } // On newer Macbooks Snowflakes will fall based on deviceorientation var doRatio = false; if (options.deviceorientation) { $(window).bind('deviceorientation', function(event) { doRatio = event.originalEvent.gamma * 0.1; }); } // this controls flow of the updating snow function snow(){ for( i = 0; i < flakes.length; i += 1){ flakes[i].update(); } snowTimeout = requestAnimationFrame(function(){snow()}); } snow(); // clears the snowflakes this.clear = function(){ $('.snowfall-canvas').remove(); $(element).children('.snowfall-flakes').remove(); cancelAnimationFrame(snowTimeout); } }; // Initialize the options and the plugin $.fn.snowfall = function(options){ if(typeof(options) == "object" || options == undefined){ return this.each(function(i){ (new $.snowfall(this, options)); }); }else if (typeof(options) == "string") { return this.each(function(i){ var snow = $(this).data('snowfall'); if(snow){ snow.clear(); } }); } }; })(jQuery);
{'content_hash': '5e00b543f144cbb956751f564a6ba89d', 'timestamp': '', 'source': 'github', 'line_count': 376, 'max_line_length': 211, 'avg_line_length': 43.098404255319146, 'alnum_prop': 0.45084850354828754, 'repo_name': 'svzosorio/love', 'id': '1477496954eead01b09c7bb79e83dc9b3a823648', 'size': '16205', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'lib/jquery-snowfall/src/snowfall.jquery.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12309'}, {'name': 'HTML', 'bytes': '20647'}, {'name': 'JavaScript', 'bytes': '424800'}, {'name': 'Makefile', 'bytes': '131'}, {'name': 'PHP', 'bytes': '635'}]}
.. index:: single: World .. highlight:: javascript .. _physics2d_world: ================ The World Object ================ Constructor =========== A World object can be constructed with :ref:`Physics2DDevice.createWorld <physics2ddevice_createworld>`. Methods ======= .. index:: pair: World; step `step` ------ **Summary** Step forwards in simulation time. **Syntax** :: world.step(deltaTime); ``deltaTime`` The amount of time (in seconds) to be simulated. This value must be strictly positive. This methods performs a single simulation step regardless of the input `deltaTime`. To use a fixed time step in your simulations, but remain flexible to differing run-time performance (Assuming physics is not the bottleneck), you would use a system similar to: :: // executed each frame while (world.simulatedTime < realTime) { world.step(fixedTimeStep); } .. index:: pair: World; getGravity `getGravity` ------------ **Summary** Retrieve gravity set on world. **Syntax** :: var gravity = world.getGravity(); // or world.getGravity(gravity); ``gravity`` (Optional) If specified then the gravity of the world will be stored into this array. Otherwise a new array will be created. Modifications to the return value of this function will not effect the space. Setting gravity must be done through the `setGravity` method. .. index:: pair: World; setGravity `setGravity` ------------ **Summary** Set gravity on world. **Syntax** :: world.setGravity(gravity); ``gravity`` New value for gravity of world. .. index:: pair: World; addRigidBody `addRigidBody` -------------- **Summary** Add a :ref:`RigidBody <physics2d_body>` to the simulation world. **Syntax** :: var success = world.addRigidBody(body); ``body`` The RigidBody to add to the world This method will fail if the body is already in a World. .. index:: pair: World; removeRigidBody `removeRigidBody` ----------------- **Summary** Remove a :ref:`RigidBody <physics2d_body>` from the simulation world. Any :ref:`Constraint <physics2d_constraint>` objects in the world which make use of the body will also be removed. **Syntax** :: var success = world.removeRigidBody(body); ``body`` The RigidBody to remove from the world This method will fail if the body is not in this World. .. index:: pair: World; addConstraint `addConstraint` --------------- **Summary** Add a :ref:`Constraint <physics2d_constraint>` to the simulation world. **Syntax** :: var success = world.addConstraint(constraint); ``constraint`` The Constraint to add to the world This method will fail if the constraint is already in a World. .. index:: pair: World; removeConstraint `removeConstraint` ------------------ **Summary** Remove a :ref:`Constraint <physics2d_constraint>` from the simulation world. **Syntax** :: var success = world.removeConstraint(constraint); ``constraint`` The Constraint to remove from the world This method will fail if the constraint is not in this World. .. index:: pair: World; clear `clear` ------- **Summary** Clear the simulation world of all rigid bodies and constraints. **Syntax** :: world.clear(); .. index:: pair: World; shapeRectangleQuery `shapeRectangleQuery` --------------------- **Summary** Sample world to find all :ref:`Shape <physics2d_shape>`'s intersecting the given axis aligned rectangle. **Syntax** :: var store = []; var count = world.shapeRectangleQuery(rectangle, store); ``rectangle`` The rectangle in Physics2D coordinates to sample Shapes. ``store`` The array in which to store intersected shapes. The return value `count` is the number of shapes which were intersected. .. index:: pair: World; bodyRectangleQuery `bodyRectangleQuery` -------------------- **Summary** Sample world to find all :ref:`RigidBody <physics2d_body>`'s intersecting the given axis aligned rectangle. **Syntax** :: var store = []; var count = world.bodyRectangleQuery(rectangle, store); ``rectangle`` The rectangle in Physics2D coordinates to sample rigid bodies. ``store`` The array in which to store intersected bodies. The return value `count` is the number of bodies which were intersected. .. index:: pair: World; shapePointQuery `shapeCircleQuery` ------------------ **Summary** Sample world to find all :ref:`Shape <physics2d_shape>`'s intersecting the given circle. **Syntax** :: var store = []; var count = world.shapeCircleQuery(center, radius, store); ``center`` The point in Physics2D coordinates defining center of the circle. ``radius`` The radius in Physics2D coordinates for sample circle. ``store`` The array in which to store intersected shapes. The return value `count` is the number of shapes which were intersected. .. index:: pair: World; bodyCircleQuery `bodyCircleQuery` ----------------- **Summary** Sample world to find all :ref:`RigidBody <physics2d_body>`'s intersecting the given point. **Syntax** :: var store = []; var count = world.bodyCircleQuery(center, radius, store); ``center`` The point in Physics2D coordinates defining center of the circle. ``radius`` The radius in Physics2D coordinates for sample circle. ``store`` The array in which to store intersected bodies. The return value `count` is the number of bodies which were intersected. .. index:: pair: World; shapePointQuery `shapePointQuery` ----------------- **Summary** Sample world to find all :ref:`Shape <physics2d_shape>`'s intersecting the given point. **Syntax** :: var store = []; var count = world.shapePointQuery(point, store); ``point`` The point in Physics2D coordinates to sample Shapes. ``store`` The array in which to store intersected shapes. The return value `count` is the number of shapes which were intersected. .. index:: pair: World; bodyPointQuery `bodyPointQuery` ---------------- **Summary** Sample world to find all :ref:`RigidBody <physics2d_body>`'s intersecting the given point. **Syntax** :: var store = []; var count = world.bodyPointQuery(point, store); ``point`` The point in Physics2D coordinates to sample rigid bodies. ``store`` The array in which to store intersected bodies. The return value `count` is the number of bodies which were intersected. .. index:: pair: World; rayCast `rayCast` --------- **Summary** Sample world for the first intersection of the given parametric ray. **Syntax** :: var ray = { origin : [-1, 0], direction : [10, 0], maxFactor : 2 }; var callback = { ignored : someShape, filter : function(ray, temporaryResult) { if (this.ignored === temporaryResult.shape) { return false; } if (temporaryResult.hitNormal[1] > 0.5) { return false; } return true; } }; var result = world.rayCast(ray, ignoreInnerSurfaces, callback.filter, callback); if (result !== null) { console.log("Ray intersected!"); console.log("Distance to intersection = " + (result.factor / mathDevice.v2Length(ray.direction))); } ``ray`` Parametric ray to be cast through the world. Ray cast will be limited to a factor of `maxFactor` of the ray direction. ``ignoreInnerSurfaces`` (Optional) If true, then intersections with the `inner` surfaces of Shapes will be ignored. Default value is `false`. ``callback`` (Optional) If supplied, this function will be called after each intersection test with the input `ray` and a temporary results object detailing the intersection. This result object is re-used and you should not keep any references to it. Any intersection for which the callback function returns false, will be ignored. ``thisObject`` (Optional) If supplied, the `callback` function supplied will be called with `thisObject` as its `this` value. The return value of this function is a new results result object detailing the closest intersection to the ray. This results object has the following fields: :: { hitPoint : [x, y], // point of intersection hitNormal : [x, y], // normal at intersection on intersected shape. shape : intersectedShape, factor : // factor corresponding to ray intersection } .. index:: pair: World; convexCast `convexCast` ------------ **Summary** Sample world for the first intersection of the given :ref:`Shape <physics2d_shape>` as determined by its :ref:`RigidBody <physics2d_body>`'s velocities. **Syntax** :: var sweepShape = phys2D.createCircleShape({ radius : 1 }); var sweepBody = phys2D.createRigidBody({ shapes : [circle], position : [-1, 0], velocity : [100, 0], angularVelocity : 20 }); var callback = { ignored : someShape, filter : function(shape, temporaryResult) { if (this.ignored === temporaryResult.shape) { return false; } if (temporaryResult.hitNormal[1] > 0.5) { return false; } return true; } }; var maxTime = 2; // seconds var result = world.convexCast(sweepShape, maxTime, callback.filter, callback); if (result !== null) { console.log("Shape intersected!"); console.log("Time of Impact = " + result.factor); } ``shape`` The :ref:`Shape <physics2d_shape>` to be swept through the world. This shape must belong to a :ref:`RigidBody <physics2d_body>` which defines the sweep start position/rotation and sweep velocities. This shape/body pair is permitted belong to the world, in which case it will ignore itself automatically. ``deltaTime`` The amount of time shape will be swept through before returning failure. ``callback`` (Optional) If supplied, this function will be called after each intersection test with the input `shape` and a temporary results object detailing the intersection. This result object is re-used and you should not keep any references to it. Any intersection for which the callback function returns false, will be ignored. ``thisObject`` (Optional) If supplied, the `callback` function supplied will be called with `thisObject` as its `this` value. The return value of this function is a new results result object detailing the first intersection of swept shape in the world. This results object has the same fields as that of the `rayCast` method. Properties ========== .. index:: pair: World; simulatedTime `simulatedTime` --------------- The amount of time in seconds that has been simulated since world creation. .. note:: Read Only .. index:: pair: World; timeStamp `timeStamp` ----------- The current time stamp for this World: equal to the number of times step() has been executed. .. note:: Read Only .. index:: pair: World; rigidBodies `rigidBodies` ------------- Array of all :ref:`RigidBody <physics2d_body>` that are in the World. Removing, or adding body from the world will modify this array, and should not be performed during iteration. If you wish to remove all rigid bodies from the world you may use the following pattern: :: var rigidBodies = world.rigidBodies; while (rigidBodies.length !== 0) { world.removeRigidBody(rigidBodies[0]); } .. note:: Read Only .. index:: pair: World; constraints `constraints` ------------- Array of all :ref:`Constraint <physics2d_constraint>` that are in the World. Removing, or adding constraint from the world will modify this array, and should not be performed during iteration. If you wish to remove all constraints from the world you may use the following pattern: :: var constraints = world.constraints; while (constraints.length !== 0) { world.removeConstraint(constraints[0]); } .. note:: Read Only .. index:: pair: World; liveDynamics `liveDynamics` -------------- Array of all non-sleeping `dynamic` type Rigid Bodies that are in the World. Dynamic bodies are put to sleep when the island of objects formed by contacts with other dynamic bodies, and constraints are all sufficiently slow moving for a sufficient amount of time. Any operation that causes a :ref:`RigidBody <physics2d_body>` or :ref:`Constraint <physics2d_constraint>` to be woken, or forced to sleep may modify this array, you should be carefully not to perform any such mutation of any such objects in the world during iteration. .. note:: Read Only .. index:: pair: World; liveDynamics `liveKinematics` ---------------- Array of all non-sleeping `kinematic` type Rigid Bodies that are in the World. Kinematic bodies are put to sleep when they have not moved during a world `step()`. Any operation that causes a :ref:`RigidBody <physics2d_body>` or :ref:`Constraint <physics2d_constraint>` to be woken, or forced to sleep may modify this array, you should be carefully not to perform any such mutation of any such objects in the world during iteration. .. note:: Read Only .. index:: pair: World; liveKinematics `liveConstraints` ----------------- Array of all non-sleeping Constraints that are in the World. Constraints are put to sleep when the island of dynamic bodies they are connected to is put to sleep. Any operation that causes a :ref:`RigidBody <physics2d_body>` or :ref:`Constraint <physics2d_constraint>` to be woken, or forced to sleep may modify this array, you should be carefully not to perform any such mutation of any such objects in the world during iteration. .. note:: Read Only .. index:: pair: World; broadphase `broadphase` ------------ The :ref:`Broadphase <broadphase>` object assigned to this World. You should not modify the broadphase object, though you are free to query it. .. note:: Read Only .. index:: pair: World; velocityIterations `velocityIterations` -------------------- The number of iterations used in the physics step when solving errors in velocity constraints. This value must be positive. .. index:: pair: World; positionIterations `positionIterations` -------------------- The number of iterations used in the physics step when solving errors in position constraints. This value must be positive. .. index:: pair: World; dynamicArbiters `dynamicArbiters` ----------------- Set of all non-sleeping :ref:`Arbiter <physics2d_arbiter>` objects between pairs of dynamic rigid bodies. If iterating over this array, you should be careful to ignore any :ref:`Arbiter <physics2d_arbiter>` object whose `active` field is false. Such objects correspond either to an interaction which has recently ended and exists purely to cache values that may shortly be re-used, or that is waiting to be destroyed. :: var arbiters = world.dynamicArbiters; var numArbiters = arbiters.length; var i; for (i = 0; i < numArbiters; i += 1) { var arb = arbiters[i]; if (!arb.active) { continue; } ... } This array may be modified by removing a :ref:`RigidBody <physics2d_body>` object from the World and should be avoided during iteration. .. note:: Read Only .. index:: pair: World; staticArbiters `staticArbiters` ---------------- Set of all non-sleeping :ref:`Arbiter <physics2d_arbiter>` objects between a dynamic, and non-dynamic rigid body. If iterating over this array, you should be careful to ignore any :ref:`Arbiter <physics2d_arbiter>` object whose `active` field is false. Such objects correspond either to an interaction which has recently ended and exists purely to cache values that may shortly be re-used, or that is waiting to be destroyed. :: var arbiters = world.staticArbiters; var numArbiters = arbiters.length; var i; for (i = 0; i < numArbiters; i += 1) { var arb = arbiters[i]; if (!arb.active) { continue; } ... } This array may be modified by removing a :ref:`RigidBody <physics2d_body>` object from the World and should be avoided during iteration. .. note:: Read Only
{'content_hash': '5494bb38ae725185c16b05e1088b691e', 'timestamp': '', 'source': 'github', 'line_count': 672, 'max_line_length': 268, 'avg_line_length': 24.3125, 'alnum_prop': 0.6724201248622842, 'repo_name': 'chkjohn/turbulenz_engine', 'id': 'b679a0ea26e2c47dc070402294526a799df5435f', 'size': '16338', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'docs/source/jslibrary_api/physics2d_world_api.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '5049520'}, {'name': 'CSS', 'bytes': '32997'}, {'name': 'JavaScript', 'bytes': '18244146'}, {'name': 'Python', 'bytes': '91804'}, {'name': 'Shell', 'bytes': '9737'}, {'name': 'TypeScript', 'bytes': '4297113'}]}
The Improviz language is still changing somewhat but should be fairly stable at this point. This reference should keep up with it. The most basic part of writing code with Improviz is calling functions that either draw shapes to the screen, or change those shapes in some way, with each of these functions being on their own separate line. The [reference document](./reference.md) lists all of the available, functions what they do, and what values they can be given. ## Calling Functions To call a function, you need to have its name, followed by a pair of parentheses `()`. Within these you place any values that will change the way the function behaves, separated by commas. A blue rectangle rotating on a red background. ``` background(255, 0, 0) fill(0, 0, 255) rotate() rectangle(2, 1) ``` ## Loops Loops allow you to repeatedly call some lines of code. The piece of code that's repeated is called a *block* and it must be indented with a tab. ``` stroke(0, 0, 0) fill(255, 0, 0) loop 100 times rotate() cube(8, 8, 8) ``` Optional `with` variable can be used as well. ``` stroke(0, 0, 0) fill(255, 0, 0) n = 100 loop n times with i rotate() move(i) cube(8, 8, 8) ``` **NOTE** Previously the `loop` keyword was optional but since version 0.9 of Improviz it is now required. ## Comments Any text that comes after two slashes `//` is considered a comment and won't be run ``` cube() //this is a comment //sphere() this line won't run ``` ## Time *time* is the major global variable and is used for all animation, whether as default variables for commands or used by the user. It is the only value that actually changes between frames. ``` rotate(1, 2, 3) cube() // this cube won't move rotate(time) sphere() // this sphere will move ``` ## Assignment If you want to calculate a value and then use it in multiple places, you can assign it to a variable. ``` a = 3 + 4 cube(a) ``` Variables can have their value re-assigned. ``` a = 3 + 4 cube(a) a = 2 sphere(a) ``` Conditional assignment is also available, and will set a variable only if it currently doesn't have a value. This is mostly useful when defining functions and setting defaults for the arguments that are passed in. ``` a = 3 a := 4 cube(a) // cube will be of size 3 ``` ## If Control flow can be done using `if`, `elif` and `else`. The number 0 is considered False, with anything else being considered True. ``` loop 10 times with x if (x % 3 < 1) fill(255, 0, 0) elif (x % 3 < 2) fill(0, 255, 0) else fill(0, 255, 0) rotate() rectangle(8) ``` ## Function Definition Functions are defined using the `func` keyword, followed by a name, argument list and then either an indented block or an arrow and single line expression ``` func val(a) => a + 1 func draw(r, g, b) rotate() fill(r, g, b) cube(val(1)) draw(255, 0, 0) ``` ## Default Arguments Functions can have default values for their arguments that will be used if a value isn't passed in. ``` func defEx(rot:2, size:3) rotate(rot) cube(size) defEx() ``` ## Function Blocks When a function is called in can be passed an optional block. If the function has a **BlockArg** argument then this block is available to be used within the function body. ``` func myf(x, y, &blk) if (isNull(blk)) sphere() else move(x, y, 0) blk() myf(1, 1) rotate() cube() ``` These blocks can also have arguments defined so that values can be passed from the wrapping function to the block. ``` func gridit(x, y, &blk) loop x times with xVal loop y times with yVal move(xVal, yVal, 0) &blk(xVal, yVal) gridit(3, 3) |x: 0, y: 0| rotate() if ((x + y) % 2 < 1) fill(255, 0, 0) else fill(0, 255, 0) cube() ``` The **BlockArg** must start with an ampersand *(&)* symbol. ## First-Class Functions Functions can be passed as values. ``` func draw(f) rotate() fill(r, g, b) f(3) draw(cube) ``` ## Lists Improviz supports basic lists, though currently they have a fixes size once declared. ``` sizes = [1,2,3,2+2] s = sizes[(time * 4) % length(sizes)] rotate(time) cube(s) ``` They can be created using square brackets and accessed also using the square brackets. The `length` function is available to return the length of a list as a number. ## Function Spread Arguments The spread operator can be used to send multiple values in a list to a function as arguments. ``` lblue = [100, 100, 255] // These two calls to fill will do the same thing fill(...lblue) fill(100, 100, 255) ``` ## Saving and Loading GFX state The built in functions **pushScope** and **popScope** can be used to save and load snapshots of the style and transformation state on a stack. ``` pushScope() rotate() cube() popScope() move(1,0,0) sphere() ``` This state will include the stroke and fill styling, as well as the matrix manipulations. This feature is used in conjuction with the function blocks to allow simplified scoping of some commands. ``` fill(255, 0, 0) cube() rotate() move() fill(0, 255, 0) sphere() ``` ## Symbols A symbol is really just a name and is primarily used for giving the name of textures to the texture function. They can be assigned to variables if desired. ``` texture(:crystal) cube() move() t = :another texture(t) ball() ```
{'content_hash': '47a8343bc5ea618421f822239c4edc5d', 'timestamp': '', 'source': 'github', 'line_count': 253, 'max_line_length': 208, 'avg_line_length': 20.940711462450594, 'alnum_prop': 0.6895054737636844, 'repo_name': 'rumblesan/improviz', 'id': '1d890836689c45bdb885cbdeadbee8a2a8ea3d0e', 'size': '5310', 'binary': False, 'copies': '2', 'ref': 'refs/heads/main', 'path': 'docs/language.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Emacs Lisp', 'bytes': '524'}, {'name': 'GLSL', 'bytes': '2102'}, {'name': 'HTML', 'bytes': '1187'}, {'name': 'Haskell', 'bytes': '253296'}, {'name': 'PowerShell', 'bytes': '1369'}, {'name': 'Shell', 'bytes': '3704'}]}
default.sudoers.conf_dir = Pathname.new '/etc/sudoers.d'
{'content_hash': 'ea2b118afd60d872d2de76c8f9b41417', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 56, 'avg_line_length': 29.0, 'alnum_prop': 0.7413793103448276, 'repo_name': 'dlobue/chef-solo-client', 'id': '72023d7c4c7d9841fa8941e2283dc40210f1974c', 'size': '664', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'cookbooks/sudoers/attributes/default.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '7548'}, {'name': 'Ruby', 'bytes': '137880'}]}
// C++ #include <iostream> // OpenCV #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <opencv2/features2d/features2d.hpp> // PnP Tutorial #include "Mesh.h" #include "Model.h" #include "PnPProblem.h" #include "RobustMatcher.h" #include "ModelRegistration.h" #include "Utils.h" using namespace cv; using namespace std; /** GLOBAL VARIABLES **/ string tutorial_path = "../../samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/"; // path to tutorial string img_path = tutorial_path + "Data/resized_IMG_3875.JPG"; // image to register string ply_read_path = tutorial_path + "Data/box.ply"; // object mesh string write_path = tutorial_path + "Data/cookies_ORB.yml"; // output file // Boolean the know if the registration it's done bool end_registration = false; // Intrinsic camera parameters: UVC WEBCAM double f = 45; // focal length in mm double sx = 22.3, sy = 14.9; double width = 2592, height = 1944; double params_CANON[] = { width*f/sx, // fx height*f/sy, // fy width/2, // cx height/2}; // cy // Setup the points to register in the image // In the order of the *.ply file and starting at 1 int n = 8; int pts[] = {1, 2, 3, 4, 5, 6, 7, 8}; // 3 -> 4 // Some basic colors Scalar red(0, 0, 255); Scalar green(0,255,0); Scalar blue(255,0,0); Scalar yellow(0,255,255); /* * CREATE MODEL REGISTRATION OBJECT * CREATE OBJECT MESH * CREATE OBJECT MODEL * CREATE PNP OBJECT */ ModelRegistration registration; Model model; Mesh mesh; PnPProblem pnp_registration(params_CANON); /** Functions headers **/ void help(); // Mouse events for model registration static void onMouseModelRegistration( int event, int x, int y, int, void* ) { if ( event == EVENT_LBUTTONUP ) { int n_regist = registration.getNumRegist(); int n_vertex = pts[n_regist]; Point2f point_2d = Point2f((float)x,(float)y); Point3f point_3d = mesh.getVertex(n_vertex-1); bool is_registrable = registration.is_registrable(); if (is_registrable) { registration.registerPoint(point_2d, point_3d); if( registration.getNumRegist() == registration.getNumMax() ) end_registration = true; } } } /** Main program **/ int main() { help(); // load a mesh given the *.ply file path mesh.load(ply_read_path); // set parameters int numKeyPoints = 10000; //Instantiate robust matcher: detector, extractor, matcher RobustMatcher rmatcher; Ptr<FeatureDetector> detector = ORB::create(numKeyPoints); rmatcher.setFeatureDetector(detector); /** GROUND TRUTH OF THE FIRST IMAGE **/ // Create & Open Window namedWindow("MODEL REGISTRATION", WINDOW_KEEPRATIO); // Set up the mouse events setMouseCallback("MODEL REGISTRATION", onMouseModelRegistration, 0 ); // Open the image to register Mat img_in = imread(img_path, IMREAD_COLOR); Mat img_vis = img_in.clone(); if (!img_in.data) { cout << "Could not open or find the image" << endl; return -1; } // Set the number of points to register int num_registrations = n; registration.setNumMax(num_registrations); cout << "Click the box corners ..." << endl; cout << "Waiting ..." << endl; // Loop until all the points are registered while ( waitKey(30) < 0 ) { // Refresh debug image img_vis = img_in.clone(); // Current registered points vector<Point2f> list_points2d = registration.get_points2d(); vector<Point3f> list_points3d = registration.get_points3d(); // Draw current registered points drawPoints(img_vis, list_points2d, list_points3d, red); // If the registration is not finished, draw which 3D point we have to register. // If the registration is finished, breaks the loop. if (!end_registration) { // Draw debug text int n_regist = registration.getNumRegist(); int n_vertex = pts[n_regist]; Point3f current_poin3d = mesh.getVertex(n_vertex-1); drawQuestion(img_vis, current_poin3d, green); drawCounter(img_vis, registration.getNumRegist(), registration.getNumMax(), red); } else { // Draw debug text drawText(img_vis, "END REGISTRATION", green); drawCounter(img_vis, registration.getNumRegist(), registration.getNumMax(), green); break; } // Show the image imshow("MODEL REGISTRATION", img_vis); } /** COMPUTE CAMERA POSE **/ cout << "COMPUTING POSE ..." << endl; // The list of registered points vector<Point2f> list_points2d = registration.get_points2d(); vector<Point3f> list_points3d = registration.get_points3d(); // Estimate pose given the registered points bool is_correspondence = pnp_registration.estimatePose(list_points3d, list_points2d, SOLVEPNP_ITERATIVE); if ( is_correspondence ) { cout << "Correspondence found" << endl; // Compute all the 2D points of the mesh to verify the algorithm and draw it vector<Point2f> list_points2d_mesh = pnp_registration.verify_points(&mesh); draw2DPoints(img_vis, list_points2d_mesh, green); } else { cout << "Correspondence not found" << endl << endl; } // Show the image imshow("MODEL REGISTRATION", img_vis); // Show image until ESC pressed waitKey(0); /** COMPUTE 3D of the image Keypoints **/ // Containers for keypoints and descriptors of the model vector<KeyPoint> keypoints_model; Mat descriptors; // Compute keypoints and descriptors rmatcher.computeKeyPoints(img_in, keypoints_model); rmatcher.computeDescriptors(img_in, keypoints_model, descriptors); // Check if keypoints are on the surface of the registration image and add to the model for (unsigned int i = 0; i < keypoints_model.size(); ++i) { Point2f point2d(keypoints_model[i].pt); Point3f point3d; bool on_surface = pnp_registration.backproject2DPoint(&mesh, point2d, point3d); if (on_surface) { model.add_correspondence(point2d, point3d); model.add_descriptor(descriptors.row(i)); model.add_keypoint(keypoints_model[i]); } else { model.add_outlier(point2d); } } // save the model into a *.yaml file model.save(write_path); // Out image img_vis = img_in.clone(); // The list of the points2d of the model vector<Point2f> list_points_in = model.get_points2d_in(); vector<Point2f> list_points_out = model.get_points2d_out(); // Draw some debug text string num = IntToString((int)list_points_in.size()); string text = "There are " + num + " inliers"; drawText(img_vis, text, green); // Draw some debug text num = IntToString((int)list_points_out.size()); text = "There are " + num + " outliers"; drawText2(img_vis, text, red); // Draw the object mesh drawObjectMesh(img_vis, &mesh, &pnp_registration, blue); // Draw found keypoints depending on if are or not on the surface draw2DPoints(img_vis, list_points_in, green); draw2DPoints(img_vis, list_points_out, red); // Show the image imshow("MODEL REGISTRATION", img_vis); // Wait until ESC pressed waitKey(0); // Close and Destroy Window destroyWindow("MODEL REGISTRATION"); cout << "GOODBYE" << endl; } /**********************************************************************************************************/ void help() { cout << "--------------------------------------------------------------------------" << endl << "This program shows how to create your 3D textured model. " << endl << "Usage:" << endl << "./cpp-tutorial-pnp_registration" << endl << "--------------------------------------------------------------------------" << endl << endl; }
{'content_hash': '536f4f3e53dda99421ee5722a1380c6c', 'timestamp': '', 'source': 'github', 'line_count': 268, 'max_line_length': 112, 'avg_line_length': 29.365671641791046, 'alnum_prop': 0.6296060991105463, 'repo_name': 'krips89/opendetection', 'id': 'da775a063ee6fece55c648255ca32995b0bd8015', 'size': '7870', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'detectors/local2D/detection/simple_ransac_detection/main_registration.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C++', 'bytes': '319483'}, {'name': 'CMake', 'bytes': '16040'}]}
package com.facebook.buck.cli; import com.facebook.buck.step.AdbOptions; import com.google.common.annotations.VisibleForTesting; import org.kohsuke.args4j.Option; public class AdbCommandLineOptions { @VisibleForTesting static final String ADB_THREADS_LONG_ARG = "--adb-threads"; @VisibleForTesting static final String ADB_THREADS_SHORT_ARG = "-T"; @Option( name = ADB_THREADS_LONG_ARG, aliases = {ADB_THREADS_SHORT_ARG}, usage = "Number of threads to use for adb operations. " + "Defaults to number of connected devices." ) private int adbThreadCount = 0; @VisibleForTesting static final String MULTI_INSTALL_MODE_SHORT_ARG = "-x"; @VisibleForTesting static final String MULTI_INSTALL_MODE_LONG_ARG = "-all"; @Option( name = MULTI_INSTALL_MODE_LONG_ARG, aliases = {MULTI_INSTALL_MODE_SHORT_ARG}, usage = "Install .apk on all connected devices and/or emulators (multi-install mode)" ) private boolean multiInstallMode; public AdbOptions getAdbOptions(BuckConfig buckConfig) { if (buckConfig.getMultiInstallMode()) { multiInstallMode = true; } return new AdbOptions(adbThreadCount, multiInstallMode); } }
{'content_hash': 'a4adeda8c4c94b66e34fa42744ad4fa1', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 100, 'avg_line_length': 31.210526315789473, 'alnum_prop': 0.7276559865092749, 'repo_name': 'robbertvanginkel/buck', 'id': 'fa4cec189e436f534f6df27e3b06bc54057e3c50', 'size': '1791', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/com/facebook/buck/cli/AdbCommandLineOptions.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '793'}, {'name': 'Batchfile', 'bytes': '2093'}, {'name': 'C', 'bytes': '257167'}, {'name': 'C#', 'bytes': '237'}, {'name': 'C++', 'bytes': '11280'}, {'name': 'CSS', 'bytes': '54863'}, {'name': 'D', 'bytes': '1017'}, {'name': 'Go', 'bytes': '16819'}, {'name': 'Groovy', 'bytes': '3362'}, {'name': 'HTML', 'bytes': '9146'}, {'name': 'Haskell', 'bytes': '971'}, {'name': 'IDL', 'bytes': '385'}, {'name': 'Java', 'bytes': '20717327'}, {'name': 'JavaScript', 'bytes': '934020'}, {'name': 'Kotlin', 'bytes': '2396'}, {'name': 'Lex', 'bytes': '2731'}, {'name': 'Makefile', 'bytes': '1816'}, {'name': 'Matlab', 'bytes': '47'}, {'name': 'OCaml', 'bytes': '4384'}, {'name': 'Objective-C', 'bytes': '138399'}, {'name': 'Objective-C++', 'bytes': '34'}, {'name': 'PowerShell', 'bytes': '244'}, {'name': 'Prolog', 'bytes': '858'}, {'name': 'Python', 'bytes': '1830515'}, {'name': 'Roff', 'bytes': '1207'}, {'name': 'Rust', 'bytes': '3618'}, {'name': 'Scala', 'bytes': '4906'}, {'name': 'Shell', 'bytes': '52110'}, {'name': 'Smalltalk', 'bytes': '3495'}, {'name': 'Standard ML', 'bytes': '15'}, {'name': 'Swift', 'bytes': '6947'}, {'name': 'Thrift', 'bytes': '29644'}, {'name': 'Yacc', 'bytes': '323'}]}
<!DOCTYPE html> <title>document.embeds and document.plugins</title> <link rel="author" title="Ms2ger" href="mailto:[email protected]"> <link rel="help" href="https://html.spec.whatwg.org/multipage/#dom-document-embeds"> <link rel="help" href="https://html.spec.whatwg.org/multipage/#dom-document-plugins"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <div id="log"></div> <script> test(function() { assert_equals(document.embeds, document.embeds, "embeds should be constant"); assert_equals(document.plugins, document.plugins, "plugins should be constant"); assert_equals(document.embeds, document.plugins, "embeds should be the same as plugins"); assert_equals(document.embeds.length, 0); assert_equals(document.plugins.length, 0); }, "No plugins"); test(function() { var embed = document.body.appendChild(document.createElement("embed")); this.add_cleanup(function() { document.body.removeChild(embed) }); assert_array_equals(document.embeds, [embed]); assert_array_equals(document.plugins, [embed]); assert_equals(document.embeds, document.embeds, "embeds should be constant"); assert_equals(document.plugins, document.plugins, "plugins should be constant"); assert_equals(document.embeds, document.plugins, "embeds should be the same as plugins"); }, "One plugin"); test(function() { var embed1 = document.createElement("embed"), embed2 = document.createElement("embed"); document.body.appendChild(embed2); this.add_cleanup(function() { document.body.removeChild(embed2) }); document.body.insertBefore(embed1, embed2); this.add_cleanup(function() { document.body.removeChild(embed1) }); assert_array_equals(document.embeds, [embed1, embed2]); assert_array_equals(document.plugins, [embed1, embed2]); assert_equals(document.embeds, document.embeds, "embeds should be constant"); assert_equals(document.plugins, document.plugins, "plugins should be constant"); assert_equals(document.embeds, document.plugins, "embeds should be the same as plugins"); }, "Two plugins"); test(function() { var embed1 = document.createElement("embed"), embed2 = document.createElement("embed"); document.body.appendChild(embed1); this.add_cleanup(function() { document.body.removeChild(embed1) }); var embeds = document.embeds; assert_true(embeds instanceof HTMLCollection); assert_equals(embeds.length, 1); document.body.appendChild(embed2); assert_equals(embeds.length, 2); document.body.removeChild(embed2); assert_equals(embeds.length, 1); }, "Document.embeds should be a live collection"); test(function() { var embed1 = document.createElement("embed"), embed2 = document.createElement("embed"); document.body.appendChild(embed1); this.add_cleanup(function() { document.body.removeChild(embed1) }); var pls = document.plugins; assert_true(pls instanceof HTMLCollection); assert_equals(pls.length, 1); document.body.appendChild(embed2); assert_equals(pls.length, 2); document.body.removeChild(embed2); assert_equals(pls.length, 1); }, "Document.plugins should be a live collection"); </script>
{'content_hash': '71c55eff76f5616f948631c488328422', 'timestamp': '', 'source': 'github', 'line_count': 87, 'max_line_length': 85, 'avg_line_length': 37.93103448275862, 'alnum_prop': 0.7054545454545454, 'repo_name': 'ric2b/Vivaldi-browser', 'id': 'e710798915dd7f2cad90148f91f4e0f658bf133d', 'size': '3300', 'binary': False, 'copies': '50', 'ref': 'refs/heads/master', 'path': 'chromium/third_party/blink/web_tests/external/wpt/html/dom/documents/dom-tree-accessors/document.embeds-document.plugins-01.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
/** * Firebase libraries for browser - npm package. * * Usage: * * firebase = require('firebase'); */ require('./firebase'); module.exports = firebase;
{'content_hash': 'ccded213b2baf0c533a01ac94b5b06df', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 49, 'avg_line_length': 17.88888888888889, 'alnum_prop': 0.6273291925465838, 'repo_name': 'axreid/Contact-Application', 'id': '01bcbf17452f67978c14c278ecd711b63d6b961e', 'size': '161', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'node_modules/firebase/firebase-browser.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '588'}, {'name': 'HTML', 'bytes': '10610'}, {'name': 'JavaScript', 'bytes': '13796'}]}
package com.alibaba.dubbo.common.serialize.support.json; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import com.alibaba.dubbo.common.json.JSON; import com.alibaba.dubbo.common.serialize.ObjectOutput; /** * JsonObjectOutput * * @author william.liangf */ public class JsonObjectOutput implements ObjectOutput { private final PrintWriter writer; private final boolean writeClass; public JsonObjectOutput(OutputStream out) { this(new OutputStreamWriter(out), false); } public JsonObjectOutput(Writer writer) { this(writer, false); } public JsonObjectOutput(OutputStream out, boolean writeClass) { this(new OutputStreamWriter(out), writeClass); } public JsonObjectOutput(Writer writer, boolean writeClass) { this.writer = new PrintWriter(writer); this.writeClass = writeClass; } public void writeBool(boolean v) throws IOException { writeObject(v); } public void writeByte(byte v) throws IOException { writeObject(v); } public void writeShort(short v) throws IOException { writeObject(v); } public void writeInt(int v) throws IOException { writeObject(v); } public void writeLong(long v) throws IOException { writeObject(v); } public void writeFloat(float v) throws IOException { writeObject(v); } public void writeDouble(double v) throws IOException { writeObject(v); } public void writeUTF(String v) throws IOException { writeObject(v); } public void writeBytes(byte[] b) throws IOException { writer.println(new String(b)); } public void writeBytes(byte[] b, int off, int len) throws IOException { writer.println(new String(b, off, len)); } public void writeObject(Object obj) throws IOException { JSON.json(obj, writer, writeClass); writer.println(); writer.flush(); } public void flushBuffer() throws IOException { writer.flush(); } }
{'content_hash': 'a04744f78fd0b54cd0025e7c2a9c147e', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 75, 'avg_line_length': 23.86813186813187, 'alnum_prop': 0.6611418047882136, 'repo_name': 'fengshao0907/dubbox-1', 'id': '4616a128d1c78d4f857ce9fea8bdd0e1dee54d1e', 'size': '2781', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'dubbo-common/src/main/java/com/alibaba/dubbo/common/serialize/support/json/JsonObjectOutput.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '3649'}, {'name': 'CSS', 'bytes': '18582'}, {'name': 'Java', 'bytes': '5515221'}, {'name': 'JavaScript', 'bytes': '63148'}, {'name': 'Lex', 'bytes': '2077'}, {'name': 'Shell', 'bytes': '7337'}, {'name': 'Thrift', 'bytes': '668'}]}
package org.springframework.boot.loader.tools.layer; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.boot.loader.tools.Layer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link IncludeExcludeContentSelector}. * * @author Madhura Bhave * @author Phillip Webb */ class IncludeExcludeContentSelectorTests { private static final Layer LAYER = new Layer("test"); @Test void createWhenLayerIsNullThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> new IncludeExcludeContentSelector<>(null, Collections.emptyList(), Collections.emptyList())) .withMessage("Layer must not be null"); } @Test void createWhenFactoryIsNullThrowsException() { assertThatIllegalArgumentException() .isThrownBy(() -> new IncludeExcludeContentSelector<>(LAYER, null, null, null)) .withMessage("FilterFactory must not be null"); } @Test void getLayerReturnsLayer() { IncludeExcludeContentSelector<?> selector = new IncludeExcludeContentSelector<>(LAYER, null, null); assertThat(selector.getLayer()).isEqualTo(LAYER); } @Test void containsWhenEmptyIncludesAndEmptyExcludesReturnsTrue() { List<String> includes = Arrays.asList(); List<String> excludes = Arrays.asList(); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("A")).isTrue(); } @Test void containsWhenNullIncludesAndEmptyExcludesReturnsTrue() { List<String> includes = null; List<String> excludes = null; IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("A")).isTrue(); } @Test void containsWhenEmptyIncludesAndNotExcludedReturnsTrue() { List<String> includes = Arrays.asList(); List<String> excludes = Arrays.asList("B"); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("A")).isTrue(); } @Test void containsWhenEmptyIncludesAndExcludedReturnsFalse() { List<String> includes = Arrays.asList(); List<String> excludes = Arrays.asList("A"); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("A")).isFalse(); } @Test void containsWhenIncludedAndEmptyExcludesReturnsTrue() { List<String> includes = Arrays.asList("A", "B"); List<String> excludes = Arrays.asList(); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("B")).isTrue(); } @Test void containsWhenIncludedAndNotExcludedReturnsTrue() { List<String> includes = Arrays.asList("A", "B"); List<String> excludes = Arrays.asList("C", "D"); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("B")).isTrue(); } @Test void containsWhenIncludedAndExcludedReturnsFalse() { List<String> includes = Arrays.asList("A", "B"); List<String> excludes = Arrays.asList("C", "D"); IncludeExcludeContentSelector<String> selector = new IncludeExcludeContentSelector<>(LAYER, includes, excludes, TestContentsFilter::new); assertThat(selector.contains("C")).isFalse(); } /** * {@link ContentFilter} used for testing. */ static class TestContentsFilter implements ContentFilter<String> { private final String match; TestContentsFilter(String match) { this.match = match; } @Override public boolean matches(String item) { return this.match.equals(item); } } }
{'content_hash': '6541974d49bee4d20b92870e58a16401', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 113, 'avg_line_length': 31.77952755905512, 'alnum_prop': 0.7566897918731417, 'repo_name': 'vpavic/spring-boot', 'id': 'f5efbfe924494a8447e44bfba5a065f47023c248', 'size': '4657', 'binary': False, 'copies': '19', 'ref': 'refs/heads/main', 'path': 'spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/test/java/org/springframework/boot/loader/tools/layer/IncludeExcludeContentSelectorTests.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '2138'}, {'name': 'CSS', 'bytes': '117'}, {'name': 'Dockerfile', 'bytes': '2309'}, {'name': 'Groovy', 'bytes': '15015'}, {'name': 'HTML', 'bytes': '58426'}, {'name': 'Java', 'bytes': '21554950'}, {'name': 'JavaScript', 'bytes': '33592'}, {'name': 'Kotlin', 'bytes': '432332'}, {'name': 'Mustache', 'bytes': '449'}, {'name': 'Ruby', 'bytes': '7867'}, {'name': 'Shell', 'bytes': '45437'}, {'name': 'Smarty', 'bytes': '2882'}, {'name': 'Vim Snippet', 'bytes': '135'}]}
package edu.stanford.isis.atb.domain.template; import java.util.Collection; /** * @author Vitaliy Semeshko */ public abstract class AbstractRemovableElement extends AbstractElement implements RemovableElement { private RemoveCommand removeCommand; @Override public void setRemoveCommand(RemoveCommand command) { this.removeCommand = command; } @Override public void remove() { if (removeCommand != null) { removeCommand.execute(); } } public void initRemoveCommand(final Collection<?> collection) { // init remove command removeCommand = new RemoveCommand() { @Override public void execute() { collection.remove(AbstractRemovableElement.this); } }; } }
{'content_hash': '0d3357695996fdc88760ede77b6ba278', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 100, 'avg_line_length': 18.55263157894737, 'alnum_prop': 0.7319148936170212, 'repo_name': 'NCIP/annotation-and-image-markup', 'id': '5642502529bb2eb774b7122593144acbb1ecda4d', 'size': '929', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ATB_1.0_src/src/main/java/edu/stanford/isis/atb/domain/template/AbstractRemovableElement.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '31363450'}, {'name': 'C#', 'bytes': '5152916'}, {'name': 'C++', 'bytes': '148605530'}, {'name': 'CSS', 'bytes': '85406'}, {'name': 'Java', 'bytes': '2039090'}, {'name': 'Objective-C', 'bytes': '381107'}, {'name': 'Perl', 'bytes': '502054'}, {'name': 'Shell', 'bytes': '11832'}, {'name': 'Tcl', 'bytes': '30867'}]}
package operationmanager import ( "fmt" "sync" ) // Operation Manager is a thread-safe interface for keeping track of multiple pending async operations. type OperationManager interface { // Called when the operation with the given ID has started. // Creates a new channel with specified buffer size tracked with the specified ID. // Returns a read-only version of the newly created channel. // Returns an error if an entry with the specified ID already exists (previous entry must be removed by calling Close). Start(id string, bufferSize uint) (<-chan interface{}, error) // Called when the operation with the given ID has terminated. // Closes and removes the channel associated with ID. // Returns an error if no associated channel exists. Close(id string) error // Attempts to send msg to the channel associated with ID. // Returns an error if no associated channel exists. Send(id string, msg interface{}) error } // Returns a new instance of a channel manager. func NewOperationManager() OperationManager { return &operationManager{ chanMap: make(map[string]chan interface{}), } } type operationManager struct { sync.RWMutex chanMap map[string]chan interface{} } // Called when the operation with the given ID has started. // Creates a new channel with specified buffer size tracked with the specified ID. // Returns a read-only version of the newly created channel. // Returns an error if an entry with the specified ID already exists (previous entry must be removed by calling Close). func (cm *operationManager) Start(id string, bufferSize uint) (<-chan interface{}, error) { cm.Lock() defer cm.Unlock() if _, exists := cm.chanMap[id]; exists { return nil, fmt.Errorf("id %q already exists", id) } cm.chanMap[id] = make(chan interface{}, bufferSize) return cm.chanMap[id], nil } // Called when the operation with the given ID has terminated. // Closes and removes the channel associated with ID. // Returns an error if no associated channel exists. func (cm *operationManager) Close(id string) error { cm.Lock() defer cm.Unlock() if _, exists := cm.chanMap[id]; !exists { return fmt.Errorf("id %q not found", id) } close(cm.chanMap[id]) delete(cm.chanMap, id) return nil } // Attempts to send msg to the channel associated with ID. // Returns an error if no associated channel exists. func (cm *operationManager) Send(id string, msg interface{}) error { cm.RLock() defer cm.RUnlock() if _, exists := cm.chanMap[id]; !exists { return fmt.Errorf("id %q not found", id) } cm.chanMap[id] <- msg return nil }
{'content_hash': '50b24f60be8fafc4ed5b191f8f6a6fae', 'timestamp': '', 'source': 'github', 'line_count': 78, 'max_line_length': 120, 'avg_line_length': 32.93589743589744, 'alnum_prop': 0.7345270533281433, 'repo_name': 'bfallik/kubernetes', 'id': 'eb8fed88ed0f9f2d653de57ede839b9723354391', 'size': '3158', 'binary': False, 'copies': '41', 'ref': 'refs/heads/master', 'path': 'pkg/util/operationmanager/operationmanager.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '23669'}, {'name': 'Go', 'bytes': '10708303'}, {'name': 'HTML', 'bytes': '72208'}, {'name': 'Java', 'bytes': '5649'}, {'name': 'JavaScript', 'bytes': '199133'}, {'name': 'Makefile', 'bytes': '18793'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'PHP', 'bytes': '736'}, {'name': 'Python', 'bytes': '55847'}, {'name': 'Ruby', 'bytes': '5423'}, {'name': 'SaltStack', 'bytes': '32538'}, {'name': 'Shell', 'bytes': '828304'}]}
This module provides a class with helper methods to optimize components' rendering. ## ifOnce Returns a number if the specified label: `2` -> already exists in the cache; `1` -> just written in the cache; `0` -> does not exist in the cache. This method is used with conditions to provide a logic: if the condition was switched to true, then further, it always returns true. ``` < .content v-if = opt.ifOnce('opened', m.opened === 'true') Very big content ``` ## memoizeLiteral Tries to find a blueprint in the cache to the specified value and returns it, or if the value wasn't found in the cache, it would be frozen, cached, and returned. This method is used to cache raw literals within component templates to avoid redundant re-renders that occurs because links to objects were changed. ``` < b-button :mods = opt.memoizeLiteral({foo: 'bla'}) ``` ## showAnyChanges Shows in a terminal/console any changes of component properties. This method is useful to debug. ```typescript import iBlock, { component } from 'super/i-block/i-block'; @component() export default class bExample extends iBlock { mounted() { this.opt.showAnyChanges(); } } ```
{'content_hash': '44d6927cabcaba26738dab072c4056a2', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 110, 'avg_line_length': 25.955555555555556, 'alnum_prop': 0.7311643835616438, 'repo_name': 'V4Fire/Client', 'id': '2760fe6934f008a9f67b7225dce731885ee3af1d', 'size': '1197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/super/i-block/modules/opt/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '8114'}, {'name': 'JavaScript', 'bytes': '951325'}, {'name': 'Scheme', 'bytes': '64903'}, {'name': 'Shell', 'bytes': '109'}, {'name': 'Stylus', 'bytes': '61221'}, {'name': 'TypeScript', 'bytes': '1272027'}]}
class ForNameDeclaredField { void foo() { Class.forName("Test").getDeclaredField("num1"); } } class Test { public int num; public int num2; int num1; }
{'content_hash': 'fd38ec2bf86d84a2bb497a94d3ea3200', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 51, 'avg_line_length': 13.916666666666666, 'alnum_prop': 0.6526946107784432, 'repo_name': 'mglukhikh/intellij-community', 'id': '616dc81b0b5fce558204da41e515ba8b5a530470', 'size': '767', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'java/java-tests/testData/codeInsight/completion/reflection/ForNameDeclaredField_after.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '60827'}, {'name': 'C', 'bytes': '211435'}, {'name': 'C#', 'bytes': '1264'}, {'name': 'C++', 'bytes': '197674'}, {'name': 'CMake', 'bytes': '1675'}, {'name': 'CSS', 'bytes': '201445'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groovy', 'bytes': '3243028'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1899088'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '165554704'}, {'name': 'JavaScript', 'bytes': '570364'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '4611299'}, {'name': 'Lex', 'bytes': '147047'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '51276'}, {'name': 'Objective-C', 'bytes': '27861'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl 6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6680'}, {'name': 'Python', 'bytes': '25439881'}, {'name': 'Roff', 'bytes': '37534'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '66341'}, {'name': 'Smalltalk', 'bytes': '338'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]}
\documentclass[28pt,landscape,a4paper,footrule]{foils} \usepackage{solido-network-slides} %It is safe to bet that the absolute volumes of IPv6 traffic and IPv4 traffic will fit this growth pattern with the proportion of IPv6 traffic growing at a slow but steady pace. The proportion of inquiries in IPv6 in the Google ranking, currently at 1.1% should reach the 2% mark twelve months from now. Less than that would be a bit disappointing. %http://www.google.com/ipv6/statistics.html % Husk: % RIPE LIR readyness \begin{document} \selectlanguage{english} \mytitlepage{IPv6 status in Denmark\\\vskip 3mm get moving!} \vskip 2cm \centerline{\footnotesize Slides are available as PDF} \slide{Goal} \hlkimage{6cm}{kame-noanime-small.png} \begin{list1} \item Introduce IPv6 - facts and features \item IPv6 Status Denmark \item Enabled providers and sites \item How to get your site on IPv6 \item Why I think we should prioritize IPv6 \end{list1} \slide{Internetworking: history} \begin{list2} \item[1960s] L. Kleinrock, MIT packet-switching theory, J. C. R. Licklider, MIT - notes Paul Baran: On Distributed Communications \item[1969] ARPANET 4 nodes \item[1971] 14 nodes \item[1974] TCP/IP: Cerf/Kahn: A protocol for Packet Network Interconnection \item[1983] {\bf Switching from NCP to IP/TCP} \item[1983] EUUG $\rightarrow$ DKUUG/DIKU forbindelse \item[2010] IANA reserved blocks 7\% (Maj 2010) - \link{http://www.potaroo.net/tools/ipv4/} \item[2011] February 3 IANA pool ran out - last 5 /8 allocated to RIRs \item[2011] April 19 APNIC ran into their last /8 and started a more restrictive policy \item[2012] Sept 14 RIPE NCC ran into their last /8 and started a more restrictive policy \end{list2} \slide{Internetworking: future of IPv4} \hlkimage{14cm}{plotend-ipv4.png} \begin{list2} \item Projected Exhaustion Date \item[2014] June ARIN - September LACNIC \item[2020] AFRINIC - has about 3.8 /8s Source \link{http://www.potaroo.net/tools/ipv4/} \end{list2} \slide{How to use IPv6} \begin{center} \vskip 3 cm \hlkbig www.solidonetworks.com [email protected] ([email protected] is not IPv6 enabled - ooops!) \end{center} \slide{Really how to use IPv6?} \begin{list1} \item Get IPv6 address and routing \item Add AAAA (quad A) records to your DNS \item Done \end{list1} \vskip 1cm \centerline{\Large www.solidonetworks.com} \begin{alltt} \LARGE www IN A 91.102.95.20 IN AAAA 2a02:9d0:10::9 \end{alltt} \slide{IPv6 Status Denmark} \begin{list1} \item Unofficial IPv6 task force at \link{http://www.ipv6tf.dk/} \item Major ISPs are ready in core networks \item Major ISP deliver IPv6 to business customers \item No major providers deliver IPv6 to consumers \item Some smaller internet Providers are working on IPv6 to homes \item A large percentage of the LIRs servicing Denmark has IPv6! \vskip 1cm \item Many hosting and content providers are ready in core networks \item Many hosting and content providers can deliver IPv6 to business customers \end{list1} \slide{IPv6 in the Nordic region - 2011} \hlkimage{14cm}{ipv6-nordic-2011.png} \link{http://v6asns.ripe.net/v/6?s=_ALL;s=DK;s=SE;s=NO;s=NL} \slide{IPv6 in the Nordic region - 2013} \hlkimage{14cm}{ipv6-nordic-2013.png} \link{http://v6asns.ripe.net/v/6?s=SE;s=FI;s=NO;s=DK;s=IS;s=_ALL}\\ \link{https://www.ripe.net/membership/indices/DK.html} \slide{RIPE NCC getting IPv4 in Europe} \begin{quote} On 14th September 2012, the RIPE NCC distributed the final IPv4 address space before reaching the last /8. This means that section 5.6 of IPv4 Address Allocation and Assignment Policies for the RIPE NCC Service Region is now in effect. This section states that, once the RIPE NCC begins to allocate address space from the last /8, {\bf an LIR may receive only a /22 (1,024 IPv4 addresses)}, even if they can justify a larger allocation. This /22 allocation will only be made to LIRs {\bf if they have already received an IPv6 allocation} from an upstream LIR or the RIPE NCC. \vskip 1cm \verb+<blink>+No new IPv4 Provider Independent (PI) space will be assigned.\verb+</blink>+ \end{quote} \vskip 15mm \centerline{\color{titlecolor}\bf \LARGE IPv6 or GTFO} \slide{The price of IPv4} \begin{quote} Hi, thank you for the interesting, sorry for the late reply, but I have got 20-30 interests/ day. I have got two unused ip range 91.135.112.0/21 and 91.135.120.0/22 I'm waiting for offers and the highest offer will become it. I can give it to rent or I can sell it. The best offer for rent is 3,5 eur / month / ip and for buy is 30 eur / ip. Best regards, Zoltan \end{quote} Let me calculate that for you {\bf /22 is 1,024 IPs each 30 EUR = 30,720 EUR} How many do you want? \vskip 2cm Source: private email communication asking about an IPv4 listing on RIPE portal \slide{Current status Denmark} \hlkimage{12cm}{demotivational-poster-Lazy.jpg} \begin{list1} \item Too little interest (upgraded from "no interest" in earlier presentations) \item Some providers are doing testing, Thanks Bolig:net for the native IPv6 in my home! \item Perceived NO NEEED - this is a problem - {\bf WTF people, get real!} \end{list1} \slide{Carrier Grade NAT - an IPv4 solution} \hlkimage{12cm}{ingenuity-720642.jpg} CGN sucks and RFC6598 IANA-Reserved IPv4 Prefix for Shared Address Space extends the life - double NAT whammy - no problems *jediwave* \vskip 8mm \centerline{Join me everyone - {\bf NAT IS BAD}} \slide{Every day is IPv6 day} \hlkimage{6cm}{ipv6-launch-flag.png} \begin{list1} \item Free, a major French ISP rolled-out IPv6 at end of year 2007 \item XS4All As of August 2010 native IPv6 DSL connections became available to almost all their customers. \item Denmark are frontrunners in IT, *sigh* \end{list1} Source: \link{http://en.wikipedia.org/wiki/IPv6_deployment} \slide{Danish ISPs and infrastructure} \begin{list1} \item \link{http://www.tdc.dk} Large ISP \item \link{http://globalconnect.dk} Fiber and internet provider \item \link{http://netgroup.dk} Internet provider \item \link{http://nianet.dk} Internet provider \item \link{http://bolignet.dk/} Internet provider \item \link{http://zensystems.dk} Internet provider \item \link{http://fiberby.dk/} Internet provider \item \link{http://siminn.dk} Internet provider (IPv6 RSN \smiley ) \item \link{http://www.dk-hostmaster.dk} \end{list1} \slide{IPv6 enabled sites} \begin{list1} \item \link{http://www.lynero.dk} \link{www.feriebolig-spanien.dk} \item \link{http://mirrors.dotsrc.org} {\bf \link{http://www.herning.dk}} \item \link{http://www.computerworld.dk} \link{http://www.version2.dk} \item \link{http://www.information.dk} \link{http://kiaklub.dk/} \item \link{http://xstream.dk} \link{http://ssl.isecurity.dk} \item \link{https://bitbureauet.dk/} \link{http://Ugenr.dk} \item \link{http://bingo.wenneberg.net/} \link{http://mirror.dk.freebsd.org} \item \link{http://Pixolink.com} \link{http://coolsms.com} \end{list1} \slide{Personal and other web sites} \begin{list1} \item \link{http://flemmingriis.com} \item \link{http://graffen.dk} \item \link{http://iboserup.dk} \item \link{http://blog.andersen.nu/} \item \link{http://iptv-analyzer.org} \item \link{http://web.gratisdns.dk} Larsen Data\\ + approx 51313 hosts via URL forwarder service! \end{list1} \vskip 1cm \centerline{\Large \color{titlecolor}Quick conclusion - there is danish content on IPv6} \vskip 15mm See more at: \link{http://world-ipv6-day.dk/danske-ipv6-sites} \slide{Telenor} \hlkimage{22cm}{telenor-ipv6-2013.png} \slide{TDC Yousee} \hlkimage{12cm}{yousee-ipv6-2013.png} aha, de har ellers tidligere meldt mere aggressivt ud. \slide{3.dk} \hlkimage{20cm}{3-dk-ipv6-2013.png} Mkay, kort tid ... \slide{Non-IPv6 sites in Denmark} \hlkimage{13cm}{lazy-cat.jpg} but no DR.dk, folketinget.dk, ministerier, offentlige myndigheder, no KMD, no web sites with CSC, IBM, ...? \vskip 10mm \centerline{\LARGE it's not hard - get moving} \slide{How to get your site on IPv6} Practical information for your network \begin{list1} \item Strategy and actions points \begin{list2} \item Collect information about IPv6 \item Collect information about your network \item Collect information about your hosts and services \item Ask your providers for IPv6 plans \item Experiment with IPv6 - today \item Implement small proof of concept, in production! \item Expand coverage \end{list2} \end{list1} \vskip 2cm \centerline{Process for LIRs: apply for IPv6 space, announce with BGP - 2 days work!} \slide{Ripeness} \begin{list1} \item First star: IPv6 address space \item One more star: route6 object \item Another star: reverse DNS \item Yet another star: prefix visible in RIS \end{list1} \link{http://ipv6ripeness.ripe.net/4star/DK.html} \slide{Security Implications - take control} \hlkimage{2cm}{IPv6ready.png} \begin{list1} \item For an IPv4 enterprise network, the existence of an IPv6 overlay network has several of implications: \begin{list2} \item The IPv4 firewalls can be bypassed by the IPv6 traffic, and leave the security door wide open. \item Intrusion detection mechanisms not expecting IPv6 traffic may be confused and allow intrusion \item In some cases (for example, with the IPv6 transition technology known as 6to4), an internal PC can communicate directly with another internal PC and evade all intrusion protection and detection systems (IPS/IDS). Botnet command and control channels are known to use these kind of tunnels. \end{list2} \end{list1} Kilde:\\ {\footnotesize\link{http://www.cisco.com/en/US/prod/collateral/iosswrel/ps6537/ps6553/white_paper_c11-629391.html}} \slide{Collect information about IPv6} \begin{list1} \item \emph{Guidelines for the Secure Deployment of IPv6}, SP800-119, NIST\\ \link{http://csrc.nist.gov/publications/nistpubs/800-119/sp800-119.pdf} \item \emph{The Second Internet: Reinventing Computer Networks with IPv6}, Lawrence E. Hughes, October 2010,\\ \link{http://www.secondinternet.org/} \item \emph{IPv6 Network Administration} af David Malone og Niall Richard Murphy \item \link{http://www.ripe.net} \item This presentation \smiley \end{list1} \slide{Allocating IPv6 addresses} \begin{list1} \item You have plenty! \item Providers and LIRs will typically get /32 \item Providers will typically give organisations /48 or /56 \item Your /48 can be used for: \begin{list2} \item 65536 subnets - all host subnets are /64 \item Each subnet has $2^{64}$ addresses \end{list2} \end{list1} \slide{Preparing an IPv6 Addressing Plan} \hlkimage{20cm}{ipv6-address-plan-ripe.png} {\footnotesize \link{http://www.ripe.net/training/material/IPv6-for-LIRs-Training-Course/IPv6_addr_plan4.pdf}} \slide{Example adress plan input} \hlkimage{22cm}{ipv6-linked-to-ipv4.png} \centerline{Easy and coupled with VLAN IDs it will work \smiley} \slide{Run IPv6 in production} \begin{list1} \item Make sure you establish IPv6 in {\bf production} \item Enabling service on IPv6 without production - bad experience for users \item Start by enabling your DNS servers for IPv6 - and DNSSEC - and DNS over TCP\\ Remember that your firewall might have problems with large DNS packets \item Add a production IPv6 router - hardware device or generic server \item Tunnels are OK, and SixXS consider their service production \end{list1} \slide{Up and running with IPv6} \begin{list1} %\item Join the fun - join the wireless network \item \link{https://www.sixxs.net/} Apply for IPv6 tunnel \item \link{http://www.tunnelbroker.net/} Apply for IPv6 tunnel \item Use ping/ping6 and traceroute to test connectivity - Done enjoy \smiley \item Try in your browser: \begin{list2} \item \link{http://www.kame.net} Dancing turtle \item \link{http://www.ripe.net} RIPE, look for address up right corner \item \link{http://loopsofzen.co.uk/} Play a game \item \link{https://www.sixxs.net/} Apply for IPv6 tunnel \item \link{http://ipv6.he.net/certification/} Join the Hurricane Electric IPv6 Certification Project \end{list2} \end{list1} \slide{F5 load balancer example} \hlkimage{\linewidth-3cm}{f5-load-balancer.png} \slide{Why prioritize IPv6 IPv6 - the business case} \begin{list2} \item An almost unlimited scalability with a very large IPv6 address space ($2^{128}$ addresses), enabling IP addresses to each and every device. \item Address self-configuration mechanisms, easing the deployment. Router advertisements are simple \item Improved security and authentication features, such as mandatory IPSec capacities and direct connections \item Peer-to-peer connectivity, solving the NAT barrier with specific and permanent IP addresses for any device and/or user of the Internet. \item Mobility features, enabling a seamless connexion when moving from one access point to another access point on the Internet. \item Multi cast and any cast functionalities. \item IPv6 will provide an easier remote interaction with each and every device with a {\bfseries direct integration to the Internet.} In other words, IPv6 will make possible to move from a network of servers, to a network of things. \end{list2} \centerline{ Business case for IPv6 is {\bf continuity}} {\footnotesize Partially inspired by \link{http://www.smartipv6building.org/index.php/en/ipv6-potential}} \slide{Conclusion} \begin{center} \vskip 5mm {\color{titlecolor}\LARGE \bf IPv6 is here already - use it} \vskip 5mm \hlkimage{7cm}{taskforce-logo.jpg} \link{http://www.ipv6tf.dk} \vskip 1cm \centerline{ Danish IPv6 task force - unofficial - not very active} \end{center} \myquestionspage \slide{Ressources} \begin{list1} \item \emph{Guidelines for the Secure Deployment of IPv6}, SP800-119, NIST\\ \link{http://csrc.nist.gov/publications/nistpubs/800-119/sp800-119.pdf} \item \emph{The Second Internet: Reinventing Computer Networks with IPv6}, Lawrence E. Hughes, October 2010,\\ \link{http://www.secondinternet.org/} \end{list1} \slide{VikingScan.org - free portscanning} \hlkimage{18cm}{vikingscan.png} %\vskip 1cm %\centerline{\link{http://www.vikingscan.org}} \hlkprofiluk \end{document}
{'content_hash': 'c611d14f367dde61ee27a1bd96482ec7', 'timestamp': '', 'source': 'github', 'line_count': 464, 'max_line_length': 348, 'avg_line_length': 30.295258620689655, 'alnum_prop': 0.753859287187878, 'repo_name': 'kramshoej/security-courses', 'id': '618af20cf6856d1ea60fe1328c7b68108afb5c1c', 'size': '14057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'presentations/network/osd-2013-ipv6-status/osd-2013-ipv6-status.tex', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '1058741'}, {'name': 'CSS', 'bytes': '2225'}, {'name': 'Emacs Lisp', 'bytes': '1699'}, {'name': 'HTML', 'bytes': '19166'}, {'name': 'Makefile', 'bytes': '44210'}, {'name': 'Perl', 'bytes': '188055'}, {'name': 'PostScript', 'bytes': '3776026'}, {'name': 'Python', 'bytes': '171'}, {'name': 'Roff', 'bytes': '8853'}, {'name': 'Shell', 'bytes': '27158'}, {'name': 'TeX', 'bytes': '3755003'}]}
//--------------------------------------------------------------------- // <copyright file="WrappedIQueryable.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- // this code has been generated using WrapperGenerator // Do not modify the file, but instead modify and re-run the generator. // disable warnings about 'new' keyword being required/not needed #pragma warning disable 108, 109 namespace Microsoft.Test.Taupo.Contracts.Wrappers { using System; using System.Collections.Generic; using System.Reflection; using Microsoft.Test.Taupo.Contracts; /// <summary> /// Wraps the 'System.Linq.IQueryable' type. /// </summary> public partial class WrappedIQueryable : WrappedIEnumerable { private static readonly Type WrappedObjectType; private static readonly IDictionary<string, MethodInfo> MethodInfoCache = new Dictionary<string, MethodInfo>(); /// <summary> /// Initializes static members of the WrappedIQueryable class. /// </summary> static WrappedIQueryable() { WrappedObjectType = WrapperUtilities.GetTypeFromAssembly("System.Linq.IQueryable", "System.Core"); } /// <summary> /// Initializes a new instance of the WrappedIQueryable class. /// </summary> /// <param name="wrapperScope">The wrapper scope.</param> /// <param name="wrappedInstance">The wrapped instance.</param> public WrappedIQueryable(IWrapperScope wrapperScope, object wrappedInstance) : base(wrapperScope, wrappedInstance) { } /// <summary> /// Gets a value of the 'ElementType' property on 'System.Linq.IQueryable' /// </summary> public virtual Type ElementType { get { return WrapperUtilities.InvokeMethodAndCast<Type>(this, WrapperUtilities.GetMethodInfo(WrappedObjectType, MethodInfoCache, "System.Type get_ElementType()"), new object[] { }); } } /// <summary> /// Gets a value of the 'Expression' property on 'System.Linq.IQueryable' /// </summary> public virtual WrappedObject Expression { get { return WrapperUtilities.InvokeMethodAndWrap<WrappedObject>(this, WrapperUtilities.GetMethodInfo(WrappedObjectType, MethodInfoCache, "System.Linq.Expressions.Expression get_Expression()"), new object[] { }); } } /// <summary> /// Gets a value of the 'Provider' property on 'System.Linq.IQueryable' /// </summary> public virtual WrappedIQueryProvider Provider { get { return WrapperUtilities.InvokeMethodAndWrap<WrappedIQueryProvider>(this, WrapperUtilities.GetMethodInfo(WrappedObjectType, MethodInfoCache, "System.Linq.IQueryProvider get_Provider()"), new object[] { }); } } } }
{'content_hash': '6826ac2ee6cc9225e445aaa09c3061b6', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 222, 'avg_line_length': 41.379746835443036, 'alnum_prop': 0.5903946160905476, 'repo_name': 'abkmr/odata.net', 'id': 'be97cf4f5c9b1ac7eaccb8b780afcdbd87b5197a', 'size': '3271', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'test/FunctionalTests/Taupo/Source/Taupo/Contracts/Wrappers/WrappedIQueryable.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '6954'}, {'name': 'Batchfile', 'bytes': '1588'}, {'name': 'C#', 'bytes': '77144154'}, {'name': 'HTML', 'bytes': '9302'}, {'name': 'Visual Basic', 'bytes': '7824314'}, {'name': 'XSLT', 'bytes': '19962'}]}
package org.springframework.data.neo4j.annotation; /** * @author mh * @since 25.07.11 */ public enum QueryType { Cypher, Gremlin }
{'content_hash': '5d2e6b62c50b3c8a86bf659b6f67fb64', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 50, 'avg_line_length': 12.818181818181818, 'alnum_prop': 0.6737588652482269, 'repo_name': 'spring-projects/spring-data-graph', 'id': 'bcadbd84e654e26c402fa4e39e872d0670135915', 'size': '758', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spring-data-neo4j/src/main/java/org/springframework/data/neo4j/annotation/QueryType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '20804'}, {'name': 'CSS', 'bytes': '6676'}, {'name': 'Java', 'bytes': '877310'}, {'name': 'XSLT', 'bytes': '60211'}]}
package org.apache.camel.zipkin.scribe; import org.apache.camel.CamelContext; import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.apache.camel.zipkin.ZipkinTracer; import org.junit.Test; /** * Integration test requires running Zipkin/Scribe running * * <p>The easiest way to run is locally: * <pre>{@code * curl -sSL https://zipkin.io/quickstart.sh | bash -s * SCRIBE_ENABLED=true java -jar zipkin.jar * }</pre> * * <p>This test has to be run with environment variables set. For example: * <pre>{@code * ZIPKIN_COLLECTOR_THRIFT_SERVICE_HOST=localhost * ZIPKIN_COLLECTOR_THRIFT_SERVICE_PORT=9410 * }</pre> */ public class ZipkinAutoConfigureScribe extends CamelTestSupport { private ZipkinTracer zipkin; @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); zipkin = new ZipkinTracer(); // we have one route as service zipkin.addClientServiceMapping("seda:cat", "cat"); zipkin.addServerServiceMapping("seda:cat", "cat"); // should auto configure as we have not setup a span reporter // attaching ourself to CamelContext zipkin.init(context); return context; } @Test public void testZipkinRoute() throws Exception { template.requestBody("direct:start", "Hello Cat"); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").to("seda:cat"); from("seda:cat").routeId("cat") .log("routing at ${routeId}") .delay(simple("${random(1000,2000)}")); } }; } }
{'content_hash': '2d28ea9230f8320db42fec24731abc93', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 74, 'avg_line_length': 29.921875, 'alnum_prop': 0.6548302872062663, 'repo_name': 'onders86/camel', 'id': 'a7ce5ea6f31835e0002fdba0a96baaf0f2b60518', 'size': '2718', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'components/camel-zipkin/src/test/java/org/apache/camel/zipkin/scribe/ZipkinAutoConfigureScribe.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Apex', 'bytes': '6519'}, {'name': 'Batchfile', 'bytes': '6512'}, {'name': 'CSS', 'bytes': '30373'}, {'name': 'Elm', 'bytes': '10852'}, {'name': 'FreeMarker', 'bytes': '11410'}, {'name': 'Groovy', 'bytes': '54390'}, {'name': 'HTML', 'bytes': '190929'}, {'name': 'Java', 'bytes': '69972191'}, {'name': 'JavaScript', 'bytes': '90399'}, {'name': 'Makefile', 'bytes': '513'}, {'name': 'Python', 'bytes': '36'}, {'name': 'Ruby', 'bytes': '4802'}, {'name': 'Scala', 'bytes': '323702'}, {'name': 'Shell', 'bytes': '23616'}, {'name': 'Tcl', 'bytes': '4974'}, {'name': 'Thrift', 'bytes': '6979'}, {'name': 'XQuery', 'bytes': '546'}, {'name': 'XSLT', 'bytes': '285105'}]}
<html> <head> <title>Nina Sebastiane's panel show appearances</title> <script type="text/javascript" src="../common.js"></script> <link rel="stylesheet" media="all" href="../style.css" type="text/css"/> <script type="text/javascript" src="../people.js"></script> <!--#include virtual="head.txt" --> </head> <body> <!--#include virtual="nav.txt" --> <div class="page"> <h1>Nina Sebastiane's panel show appearances</h1> <p>Nina Sebastiane has appeared in <span class="total">9</span> episodes between 2003-2003. <a href="http://www.imdb.com/name/nm1433123">Nina Sebastiane on IMDB</a>. <a href="https://en.wikipedia.org/wiki/Nina_Sebastiane">Nina Sebastiane on Wikipedia</a>.</p> <div class="performerholder"> <table class="performer"> <tr style="vertical-align:bottom;"> <td><div style="height:100px;" class="performances female" title="9"></div><span class="year">2003</span></td> </tr> </table> </div> <ol class="episodes"> <li><strong>2003-09-04</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-09-01</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-28</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-26</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-18</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-13</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-11</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-06</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> <li><strong>2003-08-04</strong> / <a href="../shows/loosewomen.html">Loose Women</a></li> </ol> </div> </body> </html>
{'content_hash': 'b0554eabf732af5617c76d8930c6b9f6', 'timestamp': '', 'source': 'github', 'line_count': 38, 'max_line_length': 261, 'avg_line_length': 47.31578947368421, 'alnum_prop': 0.660734149054505, 'repo_name': 'slowe/panelshows', 'id': 'b0eec940743b7305afeb37aecf06b0535e5135d9', 'size': '1798', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'people/5110uwv5.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8431'}, {'name': 'HTML', 'bytes': '25483901'}, {'name': 'JavaScript', 'bytes': '95028'}, {'name': 'Perl', 'bytes': '19899'}]}
var connect = require('connect'); var http = require('http'); var app = connect(); // require request-ip and register it as middleware var requestIp = require('request-ip'); app.use(requestIp.mw()) app.use(function(req, res) { // by default, the ip address will be set on the `clientIp` attribute var ip = req.clientIp; res.end(ip + '\n'); }); //create node.js http server and listen on port http.createServer(app).listen(3000); // test it locally from the command line // > curl -X GET localhost:3000 # Hello, your ip address is ::1 and is of type IPv6
{'content_hash': '10f8ee086d3e91bf0ff7846105deffb8', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 83, 'avg_line_length': 29.94736842105263, 'alnum_prop': 0.6889279437609842, 'repo_name': 'pbojinov/request-ip', 'id': 'c9af979cef8614030139100d63870a6b80dcfedf', 'size': '569', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'examples/connect-middleware-simple.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '36416'}]}
@interface KSURLTest : SenTestCase { @private NSString *path_; NSString *dlpath_; NSMutableArray *progress_; } @end // Helper function that runs a command and returns the command's exit status. // The command is run through the shell. static int RunCommand(NSString *cmd) { if (cmd == nil) return -1; NSArray *shargs = [NSArray arrayWithObjects:@"-c", cmd, nil]; NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:shargs]; [task waitUntilExit]; return [task terminationStatus]; } @implementation KSURLTest - (void)setUp { NSBundle *bundle = [NSBundle bundleForClass:[self class]]; path_ = [[bundle pathForResource:@"ksurl" ofType:@""] retain]; STAssertNotNil(path_, nil); BOOL isDir = YES; BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path_ isDirectory:&isDir]; STAssertTrue(exists, nil); STAssertFalse(isDir, nil); dlpath_ = [[NSString alloc] initWithFormat:@"/tmp/KSURLTest-%d", geteuid()]; [[NSFileManager defaultManager] removeFileAtPath:dlpath_ handler:nil]; progress_ = [[NSMutableArray array] retain]; } - (void)tearDown { [[NSFileManager defaultManager] removeFileAtPath:dlpath_ handler:nil]; [path_ release]; path_ = nil; [dlpath_ release]; dlpath_ = nil; [progress_ release]; } - (void)testBadArgs { NSString *cmd = nil; int rc = -1; rc = RunCommand(path_); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" "]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" "]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" -blah -foo bar"]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" -url"]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" -path"]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" -url -path foo"]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat:@" -url blah -path "]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); } - (void)testSuccessfulDownload { NSString *cmd = nil; int rc = -1; cmd = [path_ stringByAppendingFormat: @" -url file:///etc/passwd -path %@", dlpath_]; rc = RunCommand(cmd); STAssertTrue(rc == 0, nil); } - (void)testFailedDownload { NSString *cmd = nil; int rc = -1; // This file should not exist. cmd = [path_ stringByAppendingFormat: @" -url file:///qwdf23qf2e4f11wedzxerqwlka.test/ -path %@", dlpath_]; rc = RunCommand(cmd); STAssertTrue(rc != 0, nil); cmd = [path_ stringByAppendingFormat: @" -url file:///etc/passwd -path %@ -uid -2", dlpath_]; rc = RunCommand(cmd); STAssertTrue(rc == 0, nil); } // Called when progress happens in our download. - (void)progressNotification:(NSNotification *)notification { [progress_ addObject:[[notification userInfo] objectForKey:KSURLProgressKey]]; } - (void)testProgress { NSString *cmd = nil; int rc = -1; // To avoid network issues screwing up the tests, we'll use file: URLs. // Find a file we know we can read without issue. Some continuous build // systems throw errors when trying to read from system files. NSBundle *me = [NSBundle bundleForClass:[self class]]; NSString *file = [me executablePath]; NSDictionary *attr = [[NSFileManager defaultManager] fileAttributesAtPath:file traverseLink:YES]; STAssertNotNil(attr, nil); NSNumber *fileSize = [attr objectForKey:NSFileSize]; STAssertNotNil(fileSize, nil); NSURL *fileURL = [NSURL fileURLWithPath:file]; cmd = [path_ stringByAppendingFormat:@" -url %@ -path %@ -size %@", fileURL, dlpath_, fileSize]; [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(progressNotification:) name:KSURLProgressNotification object:dlpath_]; STAssertTrue([progress_ count] == 0, nil); rc = RunCommand(cmd); STAssertTrue(rc == 0, nil); [[NSDistributedNotificationCenter defaultCenter] removeObserver:self name:KSURLProgressNotification object:dlpath_]; // confirm stuff happened STAssertTrue([progress_ count] >= 1, nil); // No incremental progress on 10.4 for file:// URLs :-( // 10.4.11: release is 8.11; 10.5.3: release is 9.3 struct utsname name; if ((uname(&name) == 0) && (name.release[0] != '8')) { // We can't compare the progress count to a known value, since it // depends on the size of the file, but the last one should be a // one-value indicating completion. STAssertEquals([[progress_ lastObject] intValue], 1, nil); } // confirm it's always increasing and within range NSNumber *num; NSEnumerator *penum = [progress_ objectEnumerator]; float last = 0.0; while ((num = [penum nextObject])) { STAssertTrue([num floatValue] >= last, nil); last = [num floatValue]; } STAssertTrue(last <= 1.0, nil); } @end
{'content_hash': '2b8e71c14ef2fbe6345016be83df2d6a', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 81, 'avg_line_length': 28.65, 'alnum_prop': 0.6536746170254024, 'repo_name': 'V2ga/update-engine', 'id': '9658e60ed1194739f5f3b92594374d59708421ed', 'size': '5861', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'Core/Support/KSURLTest.m', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '801'}, {'name': 'Objective-C', 'bytes': '1016600'}, {'name': 'Shell', 'bytes': '3409'}]}
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>calculate_offset (ScrollPaginate::Helpers::ViewHelpers)</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre><span class="ruby-comment cmt"># File lib/scroll_paginate/helpers/view_helpers.rb, line 58</span> <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">calculate_offset</span>(<span class="ruby-identifier">num</span>, <span class="ruby-identifier">page</span>=<span class="ruby-keyword kw">nil</span>) <span class="ruby-identifier">page</span> <span class="ruby-value">? </span><span class="ruby-identifier">page</span>.<span class="ruby-identifier">to_i</span> <span class="ruby-operator">*</span> <span class="ruby-identifier">num</span> <span class="ruby-operator">:</span> <span class="ruby-value">0</span> <span class="ruby-keyword kw">end</span></pre> </body> </html>
{'content_hash': '6f7bea72308b9f44caff8e31684302d5', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 316, 'avg_line_length': 66.27777777777777, 'alnum_prop': 0.680637049455155, 'repo_name': 'rajib/scroll_paginate', 'id': '53c6bd8b0a2298fe017fc2e98e21d2b87f76cc93', 'size': '1193', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/classes/ScrollPaginate/Helpers/ViewHelpers.src/M000004.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '4176'}, {'name': 'Ruby', 'bytes': '8582'}]}
''' A testing suite for ICA. This will run some Python code to build the data, then calls the ICA testing script that contains BIDMach commands, then comes back to this Python code to plot the data. This code should be in the BIDMach/scripts folder. (c) February 2015 by Daniel Seita ''' import matplotlib.pyplot as plt import numpy as np import pylab import sys from scipy import signal from sklearn.decomposition import FastICA,PCA from subprocess import call ''' Returns a matrix where each row corresponds to one signal. Each row has been standardized to have zero mean and unit variance (I think), and they also have additive Gaussian noise. In order to ensure that we actually see enough variation in a small time stamp, the "first" and "second" variables (and possibly others) are used to increase/decrease the "density" of the data. For instance a high "first" value pushes the sine waves close together. > group is an integer that represents the group selection, useful for running many tests > time is from numpy and controls the density of the data > num_samples is the number of total samples to use for each row ''' def get_source(group, time, num_samples): S = None first = max(2, int(num_samples/4000)) second = max(3, int(num_samples/3000)) third = max(2, first/10) if group == 1: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) S = np.c_[s1, s2, s3] elif group == 2: s1 = np.sin(first * time) s2 = np.sign(np.sin(second * time)) s3 = signal.sawtooth(first * np.pi * time) s4 = signal.sweep_poly(third * time, [1,2]) S = np.c_[s1, s2, s3, s4] elif group == 3: s1 = np.cos(second * time) # Signal 1: cosineusoidal signal s2 = np.sign(np.sin(second * time)) # Signal 2: square signal s3 = signal.sawtooth(first * np.pi * time) # Signal 3: saw tooth signal s4 = signal.sweep_poly(third * time, [1,2]) # Signal 4: sweeping polynomial signal s5 = np.sin(first * time) # Signal 5: sinusoidal signal S = np.c_[s1, s2, s3, s4, s5] elif group == 4: s1 = np.sin(first * time) s2 = signal.sawtooth(float(first/2.55) * np.pi * time) s3 = np.sign(np.sin(second * time)) s4 = signal.sawtooth(first * np.pi * time) s5 = signal.sweep_poly(third * time, [1,2]) S = np.c_[s1, s2, s3, s4, s5] S += 0.2 * np.random.normal(size=S.shape) S /= S.std(axis=0) return S.T ''' Generates mixed data. Note that if whitened = True, this picks a pre-whitened matrix to analyze... Takes in the group number and returns a mixing matrix of the appropriate size. If the data needs to be pre-whitened, then we should pick an orthogonal mixing matrix. There are three orthogonal matrices and three non-orthogonal matrices. ''' def get_mixing_matrix(group, pre_whitened): A = None if group == 1: if pre_whitened: A = np.array([[ 0, -.8, -.6], [.8, -.36, .48], [.6, .48, -.64]]) else: A = np.array([[ 1, 1, 1], [0.5, 2, 1], [1.5, 1, 2]]) elif group == 2: if pre_whitened: A = np.array([[-0.040037, 0.24263, -0.015820, 0.96916], [ -0.54019, 0.29635, 0.78318, -0.083724], [ 0.84003, 0.23492, 0.48878, -0.016133], [ 0.030827, -0.89337, 0.38403, 0.23120]]) else: A = np.array([[ 1, 2, -1, 2.5], [-.1, -.1, 3, -.9], [8, 1, 7, 1], [1.5, -2, 3, -1]]) elif group == 3 or group == 4: if pre_whitened: A = np.array([[ 0.31571, 0.45390, -0.59557, 0.12972, 0.56837], [-0.32657, 0.47508, 0.43818, -0.56815, 0.39129], [ 0.82671, 0.11176, 0.54879, 0.05170, 0.01480], [-0.12123, -0.56812, 0.25204, 0.28505, 0.71969], [-0.30915, 0.48299, 0.29782, 0.75955, -0.07568]]) else: A = np.array([[ 1, 2, -1, 2.5, 1], [-.1, -.1, 3, -.9, 2], [8, 1, 7, 1, 3], [1.5, -2, 3, -1, 4], [-.1, 4, -.1, 3, -.2]]) return A ''' Takes in the predicted source from BIDMach and the original source and attempts to change the order and cardinality of the predicted data to match the original one. This is purely for debugging. newS is the list of lists that forms the numpy array, and rows_B_taken ensures a 1-1 correspondence. > B is the predicted source from BIDMach > S is the actual source before mixing ''' def rearrange_data(B, S): newS = [] rows_B_taken = [] for i in range(S.shape[0]): new_row = S[i,:] change_sign = False best_norm = 99999999 best_row_index = -1 for j in range(B.shape[0]): if j in rows_B_taken: continue old_row = B[j,:] norm1 = np.linalg.norm(old_row + new_row) if norm1 < best_norm: best_norm = norm1 best_row_index = j change_sign = True norm2 = np.linalg.norm(old_row - new_row) if norm2 < best_norm: best_norm = norm2 best_row_index = j rows_B_taken.append(best_row_index) if change_sign: newS.append((-B[best_row_index,:]).tolist()) else: newS.append(B[best_row_index,:].tolist()) return np.array(newS) ######## # MAIN # ######## # Some administrative stuff to make it clear how to handle this code. if len(sys.argv) != 5: print "\nUsage: python runICA.py <num_samples> <data_group> <pre_zero_mean> <pre_whitened>" print "<num_samples> should be an integer; recommended to be at least 10000" print "<data_group> should be an integer; currently only {1,2,3,4} are supported" print "<pre_zero_mean> should be \'Y\' or \'y\' if you want the (mixed) data to have zero-mean" print "<pre_whitened> should be \'Y\' or \'y\' if you want the (mixed) data to be pre-whitened" print "You also need to call this code in the directory where you can call \'./bidmach scripts/ica_test.ssc\'\n" sys.exit() n_samples = int(sys.argv[1]) data_group = int(sys.argv[2]) pre_zero_mean = True if sys.argv[3].lower() == "y" else False pre_whitened = True if sys.argv[4].lower() == "y" else False if data_group < 1 or data_group > 4: raise Exception("Data group = " + str(data_group) + " is out of range.") plot_extra_info = False # If true, plot the mixed input data (X) in addition to the real/predicted sources # With parameters in pace, generate source, mixing, and output matrices, and save them to files. np.random.seed(0) time = np.linspace(0, 8, n_samples) # These need to depend on num of samples S = get_source(data_group, time, n_samples) A = get_mixing_matrix(data_group, pre_whitened) X = np.dot(A,S) print "\nMean for the mixed data:" for i in range(X.shape[0]): print "Row {}: {}".format(i+1, np.mean(X[i,:])) print "\nThe covariance matrix for the mixed data is\n{}.".format(np.cov(X)) np.savetxt("ica_source.txt", S, delimiter=" ") np.savetxt("ica_mixing.txt", A, delimiter=" ") np.savetxt("ica_output.txt", X, delimiter=" ") print "\nNow calling ICA in BIDMach...\n" # Call BIDMach. Note that this will exit automatically with sys.exit, without user intervention. call(["./bidmach", "scripts/ica_test.ssc"]) print "\nFinished with BIDMach. Now let us plot the data." # Done with BIDMach. First, for the sake of readability, get distributions in same order. B = pylab.loadtxt('ica_pred_source.txt') newB = rearrange_data(B, S) # Extract data and plot results. Add more colors if needed but 5 is plenty. plt.figure() if plot_extra_info: models = [X.T, S.T, newB.T] names = ['Input to ICA','True Sources Before Mixing','BIDMach\'s FastICA'] else: models = [S.T, newB.T] names = ['True Sources Before Mixing','BIDMach\'s FastICA'] colors = ['darkcyan', 'red', 'blue', 'orange', 'yellow'] plot_xlim = min(n_samples-1, 10000) for ii, (model, name) in enumerate(zip(models, names), 1): if plot_extra_info: plt.subplot(3, 1, ii) else: plt.subplot(2, 1, ii) plt.title(name) plt.xlim([0,plot_xlim]) for sig, color in zip(model.T, colors): plt.plot(sig, color=color) plt.subplots_adjust(0.09, 0.04, 0.94, 0.94, 0.26, 0.46) plt.show()
{'content_hash': '68b910546eda6fd68f127190320a4121', 'timestamp': '', 'source': 'github', 'line_count': 207, 'max_line_length': 116, 'avg_line_length': 42.36231884057971, 'alnum_prop': 0.58170829056905, 'repo_name': 'AnnaZhou/BIDMach', 'id': 'e7edfd1f1f35d4cc31ef7c41192555a0493e62df', 'size': '8769', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'scripts/runICA.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '5891'}, {'name': 'C', 'bytes': '96432'}, {'name': 'C++', 'bytes': '134770'}, {'name': 'CSS', 'bytes': '4650'}, {'name': 'Cuda', 'bytes': '149405'}, {'name': 'HTML', 'bytes': '5906'}, {'name': 'Java', 'bytes': '24947'}, {'name': 'Julia', 'bytes': '200'}, {'name': 'Lex', 'bytes': '5213'}, {'name': 'Makefile', 'bytes': '1556'}, {'name': 'Python', 'bytes': '11445'}, {'name': 'Scala', 'bytes': '369798'}, {'name': 'Shell', 'bytes': '38053'}, {'name': 'XSLT', 'bytes': '21507'}]}
struct ServiceWorkerMsg_ExtendableMessageEvent_Params; namespace base { class SingleThreadTaskRunner; class TaskRunner; } namespace blink { class WebDataSource; struct WebServiceWorkerClientQueryOptions; class WebServiceWorkerContextProxy; class WebServiceWorkerProvider; struct WebSyncRegistration; } namespace IPC { class Message; } namespace content { struct PlatformNotificationData; struct PushEventPayload; struct ServiceWorkerClientInfo; class ServiceWorkerProviderContext; class ServiceWorkerContextClient; class ThreadSafeSender; class WebServiceWorkerRegistrationImpl; // This class provides access to/from an ServiceWorker's WorkerGlobalScope. // Unless otherwise noted, all methods are called on the worker thread. class ServiceWorkerContextClient : public blink::WebServiceWorkerContextClient { public: using SyncCallback = mojo::Callback<void(blink::mojom::ServiceWorkerEventStatus)>; // Returns a thread-specific client instance. This does NOT create a // new instance. static ServiceWorkerContextClient* ThreadSpecificInstance(); // Called on the main thread. ServiceWorkerContextClient(int embedded_worker_id, int64_t service_worker_version_id, const GURL& service_worker_scope, const GURL& script_url, int worker_devtools_agent_route_id); ~ServiceWorkerContextClient() override; void OnMessageReceived(int thread_id, int embedded_worker_id, const IPC::Message& message); // Called some time after the worker has started. Attempts to use the // ServiceRegistry to connect to services before this method is called are // queued up and will resolve after this method is called. void BindServiceRegistry(shell::mojom::InterfaceProviderRequest services, shell::mojom::InterfaceProviderPtr exposed_services); // WebServiceWorkerContextClient overrides. blink::WebURL scope() const override; void getClient(const blink::WebString&, blink::WebServiceWorkerClientCallbacks*) override; void getClients(const blink::WebServiceWorkerClientQueryOptions&, blink::WebServiceWorkerClientsCallbacks*) override; void openWindow(const blink::WebURL&, blink::WebServiceWorkerClientCallbacks*) override; void setCachedMetadata(const blink::WebURL&, const char* data, size_t size) override; void clearCachedMetadata(const blink::WebURL&) override; void workerReadyForInspection() override; // Called on the main thread. void workerContextFailedToStart() override; void workerScriptLoaded() override; bool hasAssociatedRegistration() override; void workerContextStarted( blink::WebServiceWorkerContextProxy* proxy) override; void didEvaluateWorkerScript(bool success) override; void didInitializeWorkerContext(v8::Local<v8::Context> context) override; void willDestroyWorkerContext(v8::Local<v8::Context> context) override; void workerContextDestroyed() override; void reportException(const blink::WebString& error_message, int line_number, int column_number, const blink::WebString& source_url) override; void reportConsoleMessage(int source, int level, const blink::WebString& message, int line_number, const blink::WebString& source_url) override; void sendDevToolsMessage(int session_id, int call_id, const blink::WebString& message, const blink::WebString& state) override; blink::WebDevToolsAgentClient::WebKitClientMessageLoop* createDevToolsMessageLoop() override; void didHandleActivateEvent(int request_id, blink::WebServiceWorkerEventResult) override; void didHandleExtendableMessageEvent( int request_id, blink::WebServiceWorkerEventResult result) override; void didHandleInstallEvent( int request_id, blink::WebServiceWorkerEventResult result) override; void didHandleFetchEvent(int request_id) override; void didHandleFetchEvent( int request_id, const blink::WebServiceWorkerResponse& response) override; void didHandleNotificationClickEvent( int request_id, blink::WebServiceWorkerEventResult result) override; void didHandleNotificationCloseEvent( int request_id, blink::WebServiceWorkerEventResult result) override; void didHandlePushEvent(int request_id, blink::WebServiceWorkerEventResult result) override; void didHandleSyncEvent(int request_id, blink::WebServiceWorkerEventResult result) override; // Called on the main thread. blink::WebServiceWorkerNetworkProvider* createServiceWorkerNetworkProvider( blink::WebDataSource* data_source) override; blink::WebServiceWorkerProvider* createServiceWorkerProvider() override; void postMessageToClient( const blink::WebString& uuid, const blink::WebString& message, blink::WebMessagePortChannelArray* channels) override; void postMessageToCrossOriginClient( const blink::WebCrossOriginServiceWorkerClient&, const blink::WebString&, blink::WebMessagePortChannelArray*) override; void focus(const blink::WebString& uuid, blink::WebServiceWorkerClientCallbacks*) override; void navigate(const blink::WebString& uuid, const blink::WebURL&, blink::WebServiceWorkerClientCallbacks*) override; void skipWaiting( blink::WebServiceWorkerSkipWaitingCallbacks* callbacks) override; void claim(blink::WebServiceWorkerClientsClaimCallbacks* callbacks) override; void registerForeignFetchScopes( const blink::WebVector<blink::WebURL>& sub_scopes, const blink::WebVector<blink::WebSecurityOrigin>& origins) override; virtual void DispatchSyncEvent( const std::string& tag, blink::WebServiceWorkerContextProxy::LastChanceOption last_chance, const SyncCallback& callback); private: struct WorkerContextData; // Get routing_id for sending message to the ServiceWorkerVersion // in the browser process. int GetRoutingID() const { return embedded_worker_id_; } void Send(IPC::Message* message); void SendWorkerStarted(); void SetRegistrationInServiceWorkerGlobalScope( const ServiceWorkerRegistrationObjectInfo& info, const ServiceWorkerVersionAttributes& attrs); void OnActivateEvent(int request_id); void OnExtendableMessageEvent( int request_id, const ServiceWorkerMsg_ExtendableMessageEvent_Params& params); void OnInstallEvent(int request_id); void OnFetchEvent(int request_id, const ServiceWorkerFetchRequest& request); void OnNotificationClickEvent( int request_id, int64_t persistent_notification_id, const PlatformNotificationData& notification_data, int action_index); void OnPushEvent(int request_id, const PushEventPayload& payload); void OnNotificationCloseEvent( int request_id, int64_t persistent_notification_id, const PlatformNotificationData& notification_data); void OnDidGetClient(int request_id, const ServiceWorkerClientInfo& client); void OnDidGetClients( int request_id, const std::vector<ServiceWorkerClientInfo>& clients); void OnOpenWindowResponse(int request_id, const ServiceWorkerClientInfo& client); void OnOpenWindowError(int request_id, const std::string& message); void OnFocusClientResponse(int request_id, const ServiceWorkerClientInfo& client); void OnNavigateClientResponse(int request_id, const ServiceWorkerClientInfo& client); void OnNavigateClientError(int request_id, const GURL& url); void OnDidSkipWaiting(int request_id); void OnDidClaimClients(int request_id); void OnClaimClientsError(int request_id, blink::WebServiceWorkerError::ErrorType error_type, const base::string16& message); void OnPing(); base::WeakPtr<ServiceWorkerContextClient> GetWeakPtr(); const int embedded_worker_id_; const int64_t service_worker_version_id_; const GURL service_worker_scope_; const GURL script_url_; const int worker_devtools_agent_route_id_; scoped_refptr<ThreadSafeSender> sender_; scoped_refptr<base::SingleThreadTaskRunner> main_thread_task_runner_; scoped_refptr<base::TaskRunner> worker_task_runner_; scoped_refptr<ServiceWorkerProviderContext> provider_context_; // Not owned; this object is destroyed when proxy_ becomes invalid. blink::WebServiceWorkerContextProxy* proxy_; // Initialized on the worker thread in workerContextStarted and // destructed on the worker thread in willDestroyWorkerContext. std::unique_ptr<WorkerContextData> context_; DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextClient); }; } // namespace content #endif // CONTENT_RENDERER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CLIENT_H_
{'content_hash': 'cfb40edbc5463e9f25c63e41c87cf87d', 'timestamp': '', 'source': 'github', 'line_count': 226, 'max_line_length': 80, 'avg_line_length': 40.99557522123894, 'alnum_prop': 0.7182946573124662, 'repo_name': 'wuhengzhi/chromium-crosswalk', 'id': '48b4dbd51781268190ed7dfee91f723a78e2847b', 'size': '10541', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'content/renderer/service_worker/service_worker_context_client.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
angular.module("rt.resize", []).factory("resize", function ($window, $timeout) { return function ($scope) { var fns = []; function callAll() { for (var i = 0; i < fns.length; i++) { fns[i](); } } // Bind to window.resize var window = angular.element($window); window.bind("resize", callAll); // Unbind when scope goes away. $scope.$on("$destroy", function () { window.unbind("resize", callAll); }); return { call: function (fn) { fns.push(fn); $timeout(fn); return this; } }; }; });
{'content_hash': 'de214f4c54eea44b1dfedfc107dc97f5', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 80, 'avg_line_length': 25.25, 'alnum_prop': 0.4328147100424328, 'repo_name': 'rubenv/angular-resize', 'id': '74a8345225ad05ee6c28d3de2c5972a69bca8474', 'size': '707', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/resize.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2785'}]}
/* * This software is distributed under BSD 3-clause license (see LICENSE file). * * Authors: Soeren Sonnenburg, Evan Shelhamer, Viktor Gal */ #include <shogun/kernel/TStudentKernel.h> #include <shogun/mathematics/Math.h> #include <utility> using namespace shogun; void TStudentKernel::init() { SG_ADD(&degree, "degree", "Kernel degree.", ParameterProperties::HYPER); SG_ADD(&distance, "distance", "Distance to be used.", ParameterProperties::HYPER); } TStudentKernel::TStudentKernel(): Kernel(0), distance(NULL), degree(1.0) { init(); } TStudentKernel::TStudentKernel(int32_t cache, float64_t d, std::shared_ptr<Distance> dist) : Kernel(cache), distance(std::move(dist)), degree(d) { init(); ASSERT(distance) } TStudentKernel::TStudentKernel(std::shared_ptr<Features >l, std::shared_ptr<Features >r, float64_t d, std::shared_ptr<Distance> dist) : Kernel(10), distance(std::move(dist)), degree(d) { init(); ASSERT(distance) init(std::move(l), std::move(r)); } TStudentKernel::~TStudentKernel() { cleanup(); } bool TStudentKernel::init(std::shared_ptr<Features> l, std::shared_ptr<Features> r) { ASSERT(distance) Kernel::init(l,r); distance->init(l,r); return init_normalizer(); } float64_t TStudentKernel::compute(int32_t idx_a, int32_t idx_b) { float64_t dist = distance->distance(idx_a, idx_b); return 1.0/(1.0+Math::pow(dist, this->degree)); }
{'content_hash': '0bd98166e1c7ab8853b49eb2ee850ee8', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 133, 'avg_line_length': 22.737704918032787, 'alnum_prop': 0.702956020187455, 'repo_name': 'besser82/shogun', 'id': 'ac786055d2dea6b0a28148ea786f6f284406086b', 'size': '1387', 'binary': False, 'copies': '4', 'ref': 'refs/heads/develop', 'path': 'src/shogun/kernel/TStudentKernel.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '64'}, {'name': 'Batchfile', 'bytes': '615'}, {'name': 'C', 'bytes': '12178'}, {'name': 'C++', 'bytes': '10261995'}, {'name': 'CMake', 'bytes': '193647'}, {'name': 'Dockerfile', 'bytes': '2046'}, {'name': 'GDB', 'bytes': '89'}, {'name': 'HTML', 'bytes': '2060'}, {'name': 'MATLAB', 'bytes': '8755'}, {'name': 'Makefile', 'bytes': '244'}, {'name': 'Python', 'bytes': '286724'}, {'name': 'SWIG', 'bytes': '385845'}, {'name': 'Shell', 'bytes': '7267'}]}
<!DOCTYPE html> <html itemscope lang="en-us"> <head><meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta charset="utf-8"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" /> <meta property="og:title" content="Chamada De Trabalhos (CFP)" /> <meta name="twitter:title" content="Chamada de Trabalhos (CFP)"/> <meta itemprop="name" content="Chamada de Trabalhos (CFP)"><meta property="og:description" content="Propose a talk for devopsdays Porto Alegre 2018" /> <meta name="twitter:description" content="Propose a talk for devopsdays Porto Alegre 2018" /> <meta itemprop="description" content="Propose a talk for devopsdays Porto Alegre 2018"><meta name="twitter:site" content="@devopsdays"> <meta property="og:type" content="event" /> <meta property="og:url" content="/events/2018-porto-alegre/cfp/" /><meta name="twitter:creator" content="@poadevopsday" /><meta name="twitter:label1" value="Event" /> <meta name="twitter:data1" value="devopsdays Porto Alegre 2018" /><meta name="twitter:label2" value="Date" /> <meta name="twitter:data2" value="September 15, 2018" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" /> <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" /> <meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" /> <meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="413"> <title>Chamada de Trabalhos (CFP) </title> <script> window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; ga('create', 'UA-9713393-1', 'auto'); ga('send', 'pageview'); ga('create', 'UA-85374985-2', 'auto', 'clientTracker'); ga('clientTracker.send', 'pageview'); </script> <script async src='https://www.google-analytics.com/analytics.js'></script> <link href="/css/site.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png"> <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png"> <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png"> <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png"> <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png"> <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png"> <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png"> <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png"> <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png"> <link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png"> <link rel="icon" type="image/png" sizes="16x16" href="/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"> <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" /> <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" /> <script src=/js/devopsdays-min.js></script></head> <body lang=""> <nav class="navbar navbar-expand-md navbar-light"> <a class="navbar-brand" href="/"> <img src="/img/devopsdays-brain.png" height="30" class="d-inline-block align-top" alt="devopsdays Logo"> DevOpsDays </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"><li class="nav-item global-navigation"><a class = "nav-link" href="/events">events</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/blog">blog</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/sponsor">sponsor</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/speaking">speaking</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/organizing">organizing</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/about">about</a></li></ul> </div> </nav> <nav class="navbar event-navigation navbar-expand-md navbar-light"> <a href="/events/2018-porto-alegre" class="nav-link">Porto Alegre</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse" id="navbar2"> <ul class="navbar-nav"><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/speakers">Palestrantes</a> </li><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/program">Programação</a> </li><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/location">Local</a> </li><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/conduta">Conduta</a> </li><li class="nav-item active"> <a class="nav-link" href="https://devopsdayspoa2018.eventize.com.br/index.php?pagina=4">Inscreva-se</a> </li><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/sponsor">Patrocinio</a> </li><li class="nav-item active"> <a class="nav-link" href="/events/2018-porto-alegre/contato/">Contato</a> </li></ul> </div> </nav> <div class="container-fluid"> <div class="row"> <div class="col-md-12"><div class="row"> <div class="col-md-12 content-text"><h1>devopsdays Porto Alegre - Chamada de Trabalhos (CFP)</h1> <center> <b>Call for proposals opens Saturday, Apr 7, 2018.</b><br> <b>Call for proposals closes Sunday, Jul 15, 2018.</b><br> Selected proposals will be announced on Wednesday, Aug 1, 2018. </center> <p><center><strong>Link para submissões:</strong> <a href="https://www.papercall.io/devopsdayspoa2018">https://www.papercall.io/devopsdayspoa2018</a></center></p> <hr> <h2 id="tipos-de-apresentações">Tipos de apresentações</h2> <p>Há três tipos de apresentações no devopsdays:</p> <ol> <li>Palestras de <strong>15 minutos</strong> apresentadas durante a conferência.</li> <li><strong>Ignite talk</strong> durante a <a href="/pages/ignite-talks-format">seção ignite</a>, são slots de 5 minutos no qual os slides são alterados a cada 15 segundos (20 slides no total).</li> <li><strong>Open Space</strong>: Se você gostaria de coordenar um grupo de discussão durante o evento, poderá fazê-lo numa sessão <a href="/pages/open-space-format">Open Space</a>. Não é necessário propor antes da conferência. Os tópicos são sugeridos durante a conferência. Se você quiser mostrar um produto ou serviço, você poderá fazê-lo como <a href="../sponsor">patrocinador</a> e mostrar uma demo na mesa respectiva dos patrocinadores.</li> </ol> <hr> <h2 id="critérios-de-escolha">Critérios de escolha</h2> <p>A escolha das palestras é parte arte e parte ciência; aqui estão alguns fatores que consideramos quando ter o melhor programa para nossa audiência local:</p> <ul> <li><em>grande apelo</em>: Como a sua apresentação se mostra para pessoas com diferentes experiências e conhecimentos? Apresentações muito técnicas precisam de mais níveis para fornecer valor para todos, os quais podem não ter o conhecimento específico na ferramenta.</li> <li><em>novos palestrantes locais</em>: Você é o único que pode contar sua história. Nós estamos muito interessados nos desafios e experiência de sucessos local. Nós estamos felizes para ajudar/mentorar os novos palestrantes que nos procurarem.</li> <li><em>vozes sub-representadas</em>: Nos gostaríamos de ouvir todas as vozes, incluso aquelas que são menos frequentes em eventos similares. Se você está num campo que não é considerado como um de tecnologia, você está em uma organização grande e tradicional, ou você é a única pessoa em sua organização com seus antecedentes, estamos interessados em sua experiência única.</li> <li><em>não enviar palestras por terceiros</em>: Este é um evento orientado pela comunidade e palestrantes precisam estar diretamente engajados com os organizadores e atendentes. Se uma empresa de relações públicas ou o departamento está propondo uma palestra, você já deve saber como um palestrante estará distante do processo.</li> <li><em>produtos e serviços</em>: Valorizamos muito nossos palestrantes e apoiadores, não iremos aceitar uma palestra que tenda a ser uma apresentação do seu produto.</li> </ul> <hr> <h2 id="mais-informações">Mais informações</h2> <p>Se você faz parte de grupos pouco representados no universo de TI e gostaria de apresentar algo, mas não se sente seguro, <a href="/events/2018-porto-alegre/contato">contate</a> diretamente nossos organizadores para que possamos fornecer subsídios como mentoria, por exemplo, para que faça uma grande palestra com total segurança.</p> <p>Esta página foi adaptada da <a href="https://www.devopsdays.org/events/2018-sao-paulo/cfp/">página de CFP do devopsdays SP 2018</a></p> <br /><div class="row cta-row"> <div class="col-md-12"><h4 class="sponsor-cta">Platina Sponsors</h4><a href = "/events/2018-porto-alegre/sponsor" class="sponsor-cta"><i>Join as Platina Sponsor!</i> </a></div> </div><div class="row sponsor-row"></div><div class="row cta-row"> <div class="col-md-12"><h4 class="sponsor-cta">Ouro Sponsors</h4></div> </div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://www.interop.com.br"><img src = "/img/sponsors/interop.png" alt = "InterOp" title = "InterOp" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://accera.com.br"><img src = "/img/sponsors/accera.png" alt = "Accera" title = "Accera" class="img-fluid"></a> </div></div><div class="row cta-row"> <div class="col-md-12"><h4 class="sponsor-cta">Prata Sponsors</h4></div> </div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.neogrid.com/br"><img src = "/img/sponsors/neogrid.png" alt = "Neogrid" title = "Neogrid" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.thoughtworks.com/"><img src = "/img/sponsors/thoughtworks-services.png" alt = "Thoughtworks" title = "Thoughtworks" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.adp.com.br/"><img src = "/img/sponsors/adp.png" alt = "ADP" title = "ADP" class="img-fluid"></a> </div></div><div class="row cta-row"> <div class="col-md-12"><h4 class="sponsor-cta">Bronze Sponsors</h4><a href = "/events/2018-porto-alegre/sponsor" class="sponsor-cta"><i>Join as Bronze Sponsor!</i> </a></div> </div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.umbler.com/br"><img src = "/img/sponsors/umbler.png" alt = "Hospedagem Cloud por demanda para Agências e Devs | Umbler" title = "Hospedagem Cloud por demanda para Agências e Devs | Umbler" class="img-fluid"></a> </div></div><div class="row cta-row"> <div class="col-md-12"><h4 class="sponsor-cta">Comunidade Sponsors</h4><a href = "/events/2018-porto-alegre/sponsor" class="sponsor-cta"><i>Join as Comunidade Sponsor!</i> </a></div> </div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.arresteddevops.com"><img src = "/img/sponsors/arresteddevops.png" alt = "Arrested DevOps" title = "Arrested DevOps" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://afropython.org/"><img src = "/img/sponsors/afropython.png" alt = "AfroPython" title = "AfroPython" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://events.docker.com/porto-alegre/"><img src = "/img/sponsors/docker-porto-alegre.png" alt = "Docker Porto Alegre" title = "Docker Porto Alegre" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://nodegirlscode.org/"><img src = "/img/sponsors/nodegirlscode.png" alt = "NodeGirls" title = "NodeGirls" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.meetup.com/pt-BR/Node-js-Porto-Alegre-Meetup/"><img src = "/img/sponsors/nodejs-porto-alegre.png" alt = "Node.JS POA" title = "Node.JS POA" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://king.host/"><img src = "/img/sponsors/kinghost.png" alt = "kinghost" title = "kinghost" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.packet.net"><img src = "/img/sponsors/packet.png" alt = "Packet" title = "Packet" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://www.meetup.com/pt-BR/PyData-Porto-Alegre/"><img src = "/img/sponsors/pydata-poa.png" alt = "Meetup PyData Porto Alegre" title = "Meetup PyData Porto Alegre" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "https://linux-for-all.github.io/"><img src = "/img/sponsors/linuxforall.png" alt = "Linux for all" title = "Linux for all" class="img-fluid"></a> </div><div class = "col-lg-1 col-md-2 col-4"> <a href = "http://arqti.org/"><img src = "/img/sponsors/arqti.png" alt = "ArqTI" title = "ArqTI" class="img-fluid"></a> </div></div><br /> </div> </div> </div></div> </div> <nav class="navbar bottom navbar-light footer-nav-row" style="background-color: #bfbfc1;"> <div class = "row"> <div class = "col-md-12 footer-nav-background"> <div class = "row"> <div class = "col-md-6 col-lg-3 footer-nav-col"> <h3 class="footer-nav">@DEVOPSDAYS</h3> <div> <a class="twitter-timeline" data-dnt="true" href="https://twitter.com/devopsdays/lists/devopsdays" data-chrome="noheader" height="440"></a> <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> </div> </div> <div class="col-md-6 col-lg-3 footer-nav-col footer-content"> <h3 class="footer-nav">BLOG</h3><a href = "https://www.devopsdays.org/blog/2019/05/10/10-years-of-devopsdays/"><h1 class = "footer-heading">10 years of devopsdays</h1></a><h2 class="footer-heading">by Kris Buytaert - 10 May, 2019</h2><p class="footer-content">It&rsquo;s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery. Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.</p><a href = "https://www.devopsdays.org/blog/"><h1 class = "footer-heading">Blogs</h1></a><h2 class="footer-heading">10 May, 2019</h2><p class="footer-content"></p><a href="https://www.devopsdays.org/blog/index.xml">Feed</a> </div> <div class="col-md-6 col-lg-3 footer-nav-col"> <h3 class="footer-nav">CFP OPEN</h3><a href = "/events/2019-campinas" class = "footer-content">Campinas</a><br /><a href = "/events/2019-macapa" class = "footer-content">Macapá</a><br /><a href = "/events/2019-shanghai" class = "footer-content">Shanghai</a><br /><a href = "/events/2019-recife" class = "footer-content">Recife</a><br /><a href = "/events/2020-charlotte" class = "footer-content">Charlotte</a><br /><a href = "/events/2020-prague" class = "footer-content">Prague</a><br /><a href = "/events/2020-tokyo" class = "footer-content">Tokyo</a><br /><a href = "/events/2020-salt-lake-city" class = "footer-content">Salt Lake City</a><br /> <br />Propose a talk at an event near you!<br /> </div> <div class="col-md-6 col-lg-3 footer-nav-col"> <h3 class="footer-nav">About</h3> devopsdays is a worldwide community conference series for anyone interested in IT improvement.<br /><br /> <a href="/about/" class = "footer-content">About devopsdays</a><br /> <a href="/privacy/" class = "footer-content">Privacy Policy</a><br /> <a href="/conduct/" class = "footer-content">Code of Conduct</a> <br /> <br /> <a href="https://www.netlify.com"> <img src="/img/netlify-light.png" alt="Deploys by Netlify"> </a> </div> </div> </div> </div> </nav> <script> $(document).ready(function () { $("#share").jsSocials({ shares: ["email", {share: "twitter", via: 'poadevopsday'}, "facebook", "linkedin"], text: 'devopsdays Porto Alegre - 2018', showLabel: false, showCount: false }); }); </script> </body> </html>
{'content_hash': '13161d3c7060b82daf96a2fa3794985b', 'timestamp': '', 'source': 'github', 'line_count': 275, 'max_line_length': 654, 'avg_line_length': 67.48363636363636, 'alnum_prop': 0.6513094083414162, 'repo_name': 'gomex/devopsdays-web', 'id': '4704539d315a041a1559dc442c257bcd97d7d5d6', 'size': '18657', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'static/events/2018-porto-alegre/cfp/index.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1568'}, {'name': 'HTML', 'bytes': '1937025'}, {'name': 'JavaScript', 'bytes': '14313'}, {'name': 'PowerShell', 'bytes': '291'}, {'name': 'Ruby', 'bytes': '650'}, {'name': 'Shell', 'bytes': '12282'}]}
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.Globalization; using System.Text; using Roslyn.Utilities; using Microsoft.Build.Framework; using Microsoft.Build.Tasks.Hosting; using Microsoft.Build.Utilities; using Microsoft.CodeAnalysis.CommandLine; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines the "Csc" XMake task, which enables building assemblies from C# /// source files by invoking the C# compiler. This is the new Roslyn XMake task, /// meaning that the code is compiled by using the Roslyn compiler server, rather /// than csc.exe. The two should be functionally identical, but the compiler server /// should be significantly faster with larger projects and have a smaller memory /// footprint. /// </summary> public class Csc : ManagedCompiler { #region Properties // Please keep these alphabetized. These are the parameters specific to Csc. The // ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is // the base class. public bool AllowUnsafeBlocks { set { _store[nameof(AllowUnsafeBlocks)] = value; } get { return _store.GetOrDefault(nameof(AllowUnsafeBlocks), false); } } public string ApplicationConfiguration { set { _store[nameof(ApplicationConfiguration)] = value; } get { return (string)_store[nameof(ApplicationConfiguration)]; } } public string BaseAddress { set { _store[nameof(BaseAddress)] = value; } get { return (string)_store[nameof(BaseAddress)]; } } public bool CheckForOverflowUnderflow { set { _store[nameof(CheckForOverflowUnderflow)] = value; } get { return _store.GetOrDefault(nameof(CheckForOverflowUnderflow), false); } } public string DocumentationFile { set { _store[nameof(DocumentationFile)] = value; } get { return (string)_store[nameof(DocumentationFile)]; } } public string DisabledWarnings { set { _store[nameof(DisabledWarnings)] = value; } get { return (string)_store[nameof(DisabledWarnings)]; } } public bool DisableSdkPath { set { _store[nameof(DisableSdkPath)] = value; } get { return _store.GetOrDefault(nameof(DisableSdkPath), false); } } public bool ErrorEndLocation { set { _store[nameof(ErrorEndLocation)] = value; } get { return _store.GetOrDefault(nameof(ErrorEndLocation), false); } } public string ErrorReport { set { _store[nameof(ErrorReport)] = value; } get { return (string)_store[nameof(ErrorReport)]; } } public bool GenerateFullPaths { set { _store[nameof(GenerateFullPaths)] = value; } get { return _store.GetOrDefault(nameof(GenerateFullPaths), false); } } public string ModuleAssemblyName { set { _store[nameof(ModuleAssemblyName)] = value; } get { return (string)_store[nameof(ModuleAssemblyName)]; } } public bool NoStandardLib { set { _store[nameof(NoStandardLib)] = value; } get { return _store.GetOrDefault(nameof(NoStandardLib), false); } } public string PdbFile { set { _store[nameof(PdbFile)] = value; } get { return (string)_store[nameof(PdbFile)]; } } /// <summary> /// Name of the language passed to "/preferreduilang" compiler option. /// </summary> /// <remarks> /// If set to null, "/preferreduilang" option is omitted, and csc.exe uses its default setting. /// Otherwise, the value is passed to "/preferreduilang" as is. /// </remarks> public string PreferredUILang { set { _store[nameof(PreferredUILang)] = value; } get { return (string)_store[nameof(PreferredUILang)]; } } public string VsSessionGuid { set { _store[nameof(VsSessionGuid)] = value; } get { return (string)_store[nameof(VsSessionGuid)]; } } public bool UseHostCompilerIfAvailable { set { _store[nameof(UseHostCompilerIfAvailable)] = value; } get { return _store.GetOrDefault(nameof(UseHostCompilerIfAvailable), false); } } public int WarningLevel { set { _store[nameof(WarningLevel)] = value; } get { return _store.GetOrDefault(nameof(WarningLevel), 4); } } public string WarningsAsErrors { set { _store[nameof(WarningsAsErrors)] = value; } get { return (string)_store[nameof(WarningsAsErrors)]; } } public string WarningsNotAsErrors { set { _store[nameof(WarningsNotAsErrors)] = value; } get { return (string)_store[nameof(WarningsNotAsErrors)]; } } public string NullableContextOptions { set { _store[nameof(NullableContextOptions)] = value; } get { return (string)_store[nameof(NullableContextOptions)]; } } #endregion #region Tool Members private static readonly string[] s_separators = { Environment.NewLine }; internal override void LogMessages(string output, MessageImportance messageImportance) { var lines = output.Split(s_separators, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedMessage = line.Trim(); if (trimmedMessage != "") { Log.LogMessageFromText(trimmedMessage, messageImportance); } } } /// <summary> /// Return the name of the tool to execute. /// </summary> override protected string ToolNameWithoutExtension { get { return "csc"; } } /// <summary> /// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file. /// </summary> protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/lib:", AdditionalLibPaths, ","); commandLine.AppendPlusOrMinusSwitch("/unsafe", _store, nameof(AllowUnsafeBlocks)); commandLine.AppendPlusOrMinusSwitch("/checked", _store, nameof(CheckForOverflowUnderflow)); commandLine.AppendSwitchWithSplitting("/nowarn:", DisabledWarnings, ",", ';', ','); commandLine.AppendWhenTrue("/fullpaths", _store, nameof(GenerateFullPaths)); commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", ModuleAssemblyName); commandLine.AppendSwitchIfNotNull("/pdb:", PdbFile); commandLine.AppendPlusOrMinusSwitch("/nostdlib", _store, nameof(NoStandardLib)); commandLine.AppendSwitchIfNotNull("/platform:", PlatformWith32BitPreference); commandLine.AppendSwitchIfNotNull("/errorreport:", ErrorReport); commandLine.AppendSwitchWithInteger("/warn:", _store, nameof(WarningLevel)); commandLine.AppendSwitchIfNotNull("/doc:", DocumentationFile); commandLine.AppendSwitchIfNotNull("/baseaddress:", BaseAddress); commandLine.AppendSwitchUnquotedIfNotNull("/define:", GetDefineConstantsSwitch(DefineConstants, Log)); commandLine.AppendSwitchIfNotNull("/win32res:", Win32Resource); commandLine.AppendSwitchIfNotNull("/main:", MainEntryPoint); commandLine.AppendSwitchIfNotNull("/appconfig:", ApplicationConfiguration); commandLine.AppendWhenTrue("/errorendlocation", _store, nameof(ErrorEndLocation)); commandLine.AppendSwitchIfNotNull("/preferreduilang:", PreferredUILang); commandLine.AppendPlusOrMinusSwitch("/highentropyva", _store, nameof(HighEntropyVA)); commandLine.AppendSwitchIfNotNull("/nullable:", NullableContextOptions); commandLine.AppendWhenTrue("/nosdkpath", _store, nameof(DisableSdkPath)); // If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid> bool designTime = false; if (HostObject is ICscHostObject csHost) { designTime = csHost.IsDesignTime(); } else if (HostObject != null) { throw new InvalidOperationException(string.Format(ErrorString.General_IncorrectHostObject, "Csc", "ICscHostObject")); } if (!designTime) { if (!string.IsNullOrWhiteSpace(VsSessionGuid)) { commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", VsSessionGuid); } } AddReferencesToCommandLine(commandLine, References); base.AddResponseFileCommands(commandLine); // This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs). // Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line, // and then any specific warnings that should be treated as errors should be specified with // /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line // does matter. // // Note that // /warnaserror+ // is just shorthand for: // /warnaserror+:<all possible warnings> // // Similarly, // /warnaserror- // is just shorthand for: // /warnaserror-:<all possible warnings> commandLine.AppendSwitchWithSplitting("/warnaserror+:", WarningsAsErrors, ",", ';', ','); commandLine.AppendSwitchWithSplitting("/warnaserror-:", WarningsNotAsErrors, ",", ';', ','); // It's a good idea for the response file to be the very last switch passed, just // from a predictability perspective. It also solves the problem that a dogfooder // ran into, which is described in an email thread attached to bug VSWhidbey 146883. // See also bugs 177762 and 118307 for additional bugs related to response file position. if (ResponseFiles != null) { foreach (ITaskItem response in ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } } #endregion internal override RequestLanguage Language => RequestLanguage.CSharpCompile; /// <summary> /// The C# compiler (starting with Whidbey) supports assembly aliasing for references. /// See spec at http://devdiv/spectool/Documents/Whidbey/VCSharp/Design%20Time/M3%20DCRs/DCR%20Assembly%20aliases.doc. /// This method handles the necessary work of looking at the "Aliases" attribute on /// the incoming "References" items, and making sure to generate the correct /// command-line on csc.exe. The syntax for aliasing a reference is: /// csc.exe /reference:Goo=System.Xml.dll /// /// The "Aliases" attribute on the "References" items is actually a comma-separated /// list of aliases, and if any of the aliases specified is the string "global", /// then we add that reference to the command-line without an alias. /// </summary> internal static void AddReferencesToCommandLine( CommandLineBuilderExtension commandLine, ITaskItem[] references, bool isInteractive = false) { // If there were no references passed in, don't add any /reference: switches // on the command-line. if (references == null) { return; } // Loop through all the references passed in. We'll be adding separate // /reference: switches for each reference, and in some cases even multiple // /reference: switches per reference. foreach (ITaskItem reference in references) { // See if there was an "Alias" attribute on the reference. string aliasString = reference.GetMetadata("Aliases"); string switchName = "/reference:"; if (!isInteractive) { bool embed = Utilities.TryConvertItemMetadataToBool(reference, "EmbedInteropTypes"); if (embed) { switchName = "/link:"; } } if (string.IsNullOrEmpty(aliasString)) { // If there was no "Alias" attribute, just add this as a global reference. commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // If there was an "Alias" attribute, it contains a comma-separated list // of aliases to use for this reference. For each one of those aliases, // we're going to add a separate /reference: switch to the csc.exe // command-line string[] aliases = aliasString.Split(','); foreach (string alias in aliases) { // Trim whitespace. string trimmedAlias = alias.Trim(); if (alias.Length == 0) { continue; } // The alias should be a valid C# identifier. Therefore it cannot // contain comma, space, semicolon, or double-quote. Let's check for // the existence of those characters right here, and bail immediately // if any are present. There are a whole bunch of other characters // that are not allowed in a C# identifier, but we'll just let csc.exe // error out on those. The ones we're checking for here are the ones // that could seriously screw up the command-line parsing or could // allow parameter injection. if (trimmedAlias.IndexOfAny(new char[] { ',', ' ', ';', '"' }) != -1) { throw Utilities.GetLocalizedArgumentException( ErrorString.Csc_AssemblyAliasContainsIllegalCharacters, reference.ItemSpec, trimmedAlias); } // The alias called "global" is special. It means that we don't // give it an alias on the command-line. if (string.Compare("global", trimmedAlias, StringComparison.OrdinalIgnoreCase) == 0) { commandLine.AppendSwitchIfNotNull(switchName, reference.ItemSpec); } else { // We have a valid (and explicit) alias for this reference. Add // it to the command-line using the syntax: // /reference:Goo=System.Xml.dll commandLine.AppendSwitchAliased(switchName, trimmedAlias, reference.ItemSpec); } } } } } /// <summary> /// Old VS projects had some pretty messed-up looking values for the /// "DefineConstants" property. It worked fine in the IDE, because it /// effectively munged up the string so that it ended up being valid for /// the compiler. We do the equivalent munging here now. /// /// Basically, we take the incoming string, and split it on comma/semicolon/space. /// Then we look at the resulting list of strings, and remove any that are /// illegal identifiers, and pass the remaining ones through to the compiler. /// /// Note that CSharp does support assigning a value to the constants ... in /// other words, a constant is either defined or not defined ... it can't have /// an actual value. /// </summary> internal static string GetDefineConstantsSwitch(string originalDefineConstants, TaskLoggingHelper log) { if (originalDefineConstants == null) { return null; } StringBuilder finalDefineConstants = new StringBuilder(); // Split the incoming string on comma/semicolon/space. string[] allIdentifiers = originalDefineConstants.Split(new char[] { ',', ';', ' ' }); // Loop through all the parts, and for the ones that are legal C# identifiers, // add them to the outgoing string. foreach (string singleIdentifier in allIdentifiers) { if (UnicodeCharacterUtilities.IsValidIdentifier(singleIdentifier)) { // Separate them with a semicolon if there's something already in // the outgoing string. if (finalDefineConstants.Length > 0) { finalDefineConstants.Append(";"); } finalDefineConstants.Append(singleIdentifier); } else if (singleIdentifier.Length > 0) { log.LogWarningWithCodeFromResources("Csc_InvalidParameterWarning", "/define:", singleIdentifier); } } if (finalDefineConstants.Length > 0) { return finalDefineConstants.ToString(); } else { // We wouldn't want to pass in an empty /define: switch on the csc.exe command-line. return null; } } /// <summary> /// This method will initialize the host compiler object with all the switches, /// parameters, resources, references, sources, etc. /// /// It returns true if everything went according to plan. It returns false if the /// host compiler had a problem with one of the parameters that was passed in. /// /// This method also sets the "this.HostCompilerSupportsAllParameters" property /// accordingly. /// /// Example: /// If we attempted to pass in WarningLevel="9876", then this method would /// set HostCompilerSupportsAllParameters=true, but it would give a /// return value of "false". This is because the host compiler fully supports /// the WarningLevel parameter, but 9876 happens to be an illegal value. /// /// Example: /// If we attempted to pass in NoConfig=false, then this method would set /// HostCompilerSupportsAllParameters=false, because while this is a legal /// thing for csc.exe, the IDE compiler cannot support it. In this situation /// the return value will also be false. /// </summary> /// <owner>RGoel</owner> private bool InitializeHostCompiler(ICscHostObject cscHostObject) { bool success; HostCompilerSupportsAllParameters = UseHostCompilerIfAvailable; string param = "Unknown"; try { // Need to set these separately, because they don't require a CommitChanges to the C# compiler in the IDE. CheckHostObjectSupport(param = nameof(LinkResources), cscHostObject.SetLinkResources(LinkResources)); CheckHostObjectSupport(param = nameof(References), cscHostObject.SetReferences(References)); CheckHostObjectSupport(param = nameof(Resources), cscHostObject.SetResources(Resources)); CheckHostObjectSupport(param = nameof(Sources), cscHostObject.SetSources(Sources)); // For host objects which support it, pass the list of analyzers. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers)); } } catch (Exception e) { Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message); return false; } try { param = nameof(cscHostObject.BeginInitialization); cscHostObject.BeginInitialization(); CheckHostObjectSupport(param = nameof(AdditionalLibPaths), cscHostObject.SetAdditionalLibPaths(AdditionalLibPaths)); CheckHostObjectSupport(param = nameof(AddModules), cscHostObject.SetAddModules(AddModules)); CheckHostObjectSupport(param = nameof(AllowUnsafeBlocks), cscHostObject.SetAllowUnsafeBlocks(AllowUnsafeBlocks)); CheckHostObjectSupport(param = nameof(BaseAddress), cscHostObject.SetBaseAddress(BaseAddress)); CheckHostObjectSupport(param = nameof(CheckForOverflowUnderflow), cscHostObject.SetCheckForOverflowUnderflow(CheckForOverflowUnderflow)); CheckHostObjectSupport(param = nameof(CodePage), cscHostObject.SetCodePage(CodePage)); // These two -- EmitDebugInformation and DebugType -- must go together, with DebugType // getting set last, because it is more specific. CheckHostObjectSupport(param = nameof(EmitDebugInformation), cscHostObject.SetEmitDebugInformation(EmitDebugInformation)); CheckHostObjectSupport(param = nameof(DebugType), cscHostObject.SetDebugType(DebugType)); CheckHostObjectSupport(param = nameof(DefineConstants), cscHostObject.SetDefineConstants(GetDefineConstantsSwitch(DefineConstants, Log))); CheckHostObjectSupport(param = nameof(DelaySign), cscHostObject.SetDelaySign((_store["DelaySign"] != null), DelaySign)); CheckHostObjectSupport(param = nameof(DisabledWarnings), cscHostObject.SetDisabledWarnings(DisabledWarnings)); CheckHostObjectSupport(param = nameof(DocumentationFile), cscHostObject.SetDocumentationFile(DocumentationFile)); CheckHostObjectSupport(param = nameof(ErrorReport), cscHostObject.SetErrorReport(ErrorReport)); CheckHostObjectSupport(param = nameof(FileAlignment), cscHostObject.SetFileAlignment(FileAlignment)); CheckHostObjectSupport(param = nameof(GenerateFullPaths), cscHostObject.SetGenerateFullPaths(GenerateFullPaths)); CheckHostObjectSupport(param = nameof(KeyContainer), cscHostObject.SetKeyContainer(KeyContainer)); CheckHostObjectSupport(param = nameof(KeyFile), cscHostObject.SetKeyFile(KeyFile)); CheckHostObjectSupport(param = nameof(LangVersion), cscHostObject.SetLangVersion(LangVersion)); CheckHostObjectSupport(param = nameof(MainEntryPoint), cscHostObject.SetMainEntryPoint(TargetType, MainEntryPoint)); CheckHostObjectSupport(param = nameof(ModuleAssemblyName), cscHostObject.SetModuleAssemblyName(ModuleAssemblyName)); CheckHostObjectSupport(param = nameof(NoConfig), cscHostObject.SetNoConfig(NoConfig)); CheckHostObjectSupport(param = nameof(NoStandardLib), cscHostObject.SetNoStandardLib(NoStandardLib)); CheckHostObjectSupport(param = nameof(Optimize), cscHostObject.SetOptimize(Optimize)); CheckHostObjectSupport(param = nameof(OutputAssembly), cscHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec)); CheckHostObjectSupport(param = nameof(PdbFile), cscHostObject.SetPdbFile(PdbFile)); // For host objects which support it, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion ICscHostObject4 cscHostObject4 = cscHostObject as ICscHostObject4; if (cscHostObject4 != null) { CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), cscHostObject4.SetPlatformWith32BitPreference(PlatformWith32BitPreference)); CheckHostObjectSupport(param = nameof(HighEntropyVA), cscHostObject4.SetHighEntropyVA(HighEntropyVA)); CheckHostObjectSupport(param = nameof(SubsystemVersion), cscHostObject4.SetSubsystemVersion(SubsystemVersion)); } else { CheckHostObjectSupport(param = nameof(Platform), cscHostObject.SetPlatform(Platform)); } // For host objects which support it, set the analyzer ruleset and additional files. IAnalyzerHostObject analyzerHostObject = cscHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet)); CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles)); } ICscHostObject5 cscHostObject5 = cscHostObject as ICscHostObject5; if (cscHostObject5 != null) { CheckHostObjectSupport(param = nameof(ErrorLog), cscHostObject5.SetErrorLog(ErrorLog)); CheckHostObjectSupport(param = nameof(ReportAnalyzer), cscHostObject5.SetReportAnalyzer(ReportAnalyzer)); } CheckHostObjectSupport(param = nameof(ResponseFiles), cscHostObject.SetResponseFiles(ResponseFiles)); CheckHostObjectSupport(param = nameof(TargetType), cscHostObject.SetTargetType(TargetType)); CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), cscHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors)); CheckHostObjectSupport(param = nameof(WarningLevel), cscHostObject.SetWarningLevel(WarningLevel)); // This must come after TreatWarningsAsErrors. CheckHostObjectSupport(param = nameof(WarningsAsErrors), cscHostObject.SetWarningsAsErrors(WarningsAsErrors)); // This must come after TreatWarningsAsErrors. CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), cscHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors)); CheckHostObjectSupport(param = nameof(Win32Icon), cscHostObject.SetWin32Icon(Win32Icon)); // In order to maintain compatibility with previous host compilers, we must // light-up for ICscHostObject2/ICscHostObject3 if (cscHostObject is ICscHostObject2) { ICscHostObject2 cscHostObject2 = (ICscHostObject2)cscHostObject; CheckHostObjectSupport(param = nameof(Win32Manifest), cscHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest))); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!string.IsNullOrEmpty(Win32Manifest)) { CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false); } } // This must come after Win32Manifest CheckHostObjectSupport(param = nameof(Win32Resource), cscHostObject.SetWin32Resource(Win32Resource)); if (cscHostObject is ICscHostObject3) { ICscHostObject3 cscHostObject3 = (ICscHostObject3)cscHostObject; CheckHostObjectSupport(param = nameof(ApplicationConfiguration), cscHostObject3.SetApplicationConfiguration(ApplicationConfiguration)); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!string.IsNullOrEmpty(ApplicationConfiguration)) { CheckHostObjectSupport(nameof(ApplicationConfiguration), resultFromHostObjectSetOperation: false); } } InitializeHostObjectSupportForNewSwitches(cscHostObject, ref param); // If we have been given a property value that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler. // Null is supported because it means that option should be omitted, and compiler default used - obviously always valid. // Explicitly specified name of current locale is also supported, since it is effectively a no-op. // Other options are not supported since in-proc compiler always uses current locale. if (!string.IsNullOrEmpty(PreferredUILang) && !string.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) { CheckHostObjectSupport(nameof(PreferredUILang), resultFromHostObjectSetOperation: false); } } catch (Exception e) { Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message); return false; } finally { int errorCode; string errorMessage; success = cscHostObject.EndInitialization(out errorMessage, out errorCode); if (HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. // If EndInitialization returns false, then there was an error. If EndInitialization was // successful, but there is a valid 'errorMessage,' interpret it as a warning. if (!success) { Log.LogError(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } else if (errorMessage != null && errorMessage.Length > 0) { Log.LogWarning(null, "CS" + errorCode.ToString("D4", CultureInfo.InvariantCulture), null, null, 0, 0, 0, 0, errorMessage); } } } return (success); } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns one of the following values to indicate what the next action should be: /// UseHostObjectToExecute Host compiler exists and was initialized. /// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate. /// NoActionReturnSuccess Host compiler was already up-to-date, and we're done. /// NoActionReturnFailure Bad parameters were passed into the task. /// </summary> /// <owner>RGoel</owner> protected override HostObjectInitializationStatus InitializeHostObject() { if (HostObject != null) { // When the host object was passed into the task, it was passed in as a generic // "Object" (because ITask interface obviously can't have any Csc-specific stuff // in it, and each task is going to want to communicate with its host in a unique // way). Now we cast it to the specific type that the Csc task expects. If the // host object does not match this type, the host passed in an invalid host object // to Csc, and we error out. // NOTE: For compat reasons this must remain ICscHostObject // we can dynamically test for smarter interfaces later.. if (HostObject is ICscHostObject hostObjectCOM) { using (RCWForCurrentContext<ICscHostObject> hostObject = new RCWForCurrentContext<ICscHostObject>(hostObjectCOM)) { ICscHostObject cscHostObject = hostObject.RCW; bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(cscHostObject); // If we're currently only in design-time (as opposed to build-time), // then we're done. We've initialized the host compiler as best we // can, and we certainly don't want to actually do the final compile. // So return true, saying we're done and successful. if (cscHostObject.IsDesignTime()) { // If we are design-time then we do not want to continue the build at // this time. return hostObjectSuccessfullyInitialized ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.NoActionReturnFailure; } if (!this.HostCompilerSupportsAllParameters) { // Since the host compiler has refused to take on the responsibility for this compilation, // we're about to shell out to the command-line compiler to handle it. If some of the // references don't exist on disk, we know the command-line compiler will fail, so save // the trouble, and just throw a consistent error ourselves. This allows us to give // more information than the compiler would, and also make things consistent across // Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3). // This suite behaves differently in localized builds than on English builds because // VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it. if (!CheckAllReferencesExistOnDisk()) { return HostObjectInitializationStatus.NoActionReturnFailure; } // The host compiler doesn't support some of the switches/parameters // being passed to it. Therefore, we resort to using the command-line compiler // in this case. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } // Ok, by now we validated that the host object supports the necessary switches // and parameters. Last thing to check is whether the host object is up to date, // and in that case, we will inform the caller that no further action is necessary. if (hostObjectSuccessfullyInitialized) { return cscHostObject.IsUpToDate() ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.UseHostObjectToExecute; } else { return HostObjectInitializationStatus.NoActionReturnFailure; } } } else { Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Csc", "ICscHostObject"); } } // No appropriate host object was found. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Csc /// task. Returns true if the compilation succeeded, otherwise false. /// </summary> /// <owner>RGoel</owner> protected override bool CallHostObjectToExecute() { Debug.Assert(HostObject != null, "We should not be here if the host object has not been set."); ICscHostObject cscHostObject = HostObject as ICscHostObject; Debug.Assert(cscHostObject != null, "Wrong kind of host object passed in!"); return cscHostObject.Compile(); } } }
{'content_hash': '583557c1ffc31eb08e72def482c45c26', 'timestamp': '', 'source': 'github', 'line_count': 744, 'max_line_length': 186, 'avg_line_length': 51.91935483870968, 'alnum_prop': 0.5919281350315833, 'repo_name': 'MichalStrehovsky/roslyn', 'id': 'b8a250c3528ddc889889cc9842dcbaf135267e85', 'size': '38630', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'src/Compilers/Core/MSBuildTask/Csc.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '8656'}, {'name': 'C#', 'bytes': '117042543'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2102'}, {'name': 'F#', 'bytes': '508'}, {'name': 'PowerShell', 'bytes': '140127'}, {'name': 'Rich Text Format', 'bytes': '14887'}, {'name': 'Shell', 'bytes': '61759'}, {'name': 'Smalltalk', 'bytes': '622'}, {'name': 'Visual Basic', 'bytes': '69098961'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': '814a1e9ac75cd17933c79d9bd060bab7', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': '1d9c789c28b80109eb354918fb836d0693176797', 'size': '197', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Euphorbiaceae/Euphorbia/Euphorbia linguiformis/ Syn. Euphorbia linguiformis acutinadenia/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
**Author:** [Amogh Joshi](https://github.com/amogh7joshi)<br> **Date created:** 2021/06/02<br> **Last modified:** 2021/06/05<br> **Description:** How to build and train a convolutional LSTM model for next-frame video prediction. <img class="k-inline-icon" src="https://colab.research.google.com/img/colab_favicon.ico"/> [**View in Colab**](https://colab.research.google.com/github/keras-team/keras-io/blob/master/examples/vision/ipynb/conv_lstm.ipynb) <span class="k-dot">•</span><img class="k-inline-icon" src="https://github.com/favicon.ico"/> [**GitHub source**](https://github.com/keras-team/keras-io/blob/master/examples/vision/conv_lstm.py) --- ## Introduction The [Convolutional LSTM](https://papers.nips.cc/paper/2015/file/07563a3fe3bbe7e3ba84431ad9d055af-Paper.pdf) architectures bring together time series processing and computer vision by introducing a convolutional recurrent cell in a LSTM layer. In this example, we will explore the Convolutional LSTM model in an application to next-frame prediction, the process of predicting what video frames come next given a series of past frames. --- ## Setup ```python import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import io import imageio from IPython.display import Image, display from ipywidgets import widgets, Layout, HBox ``` --- ## Dataset Construction For this example, we will be using the [Moving MNIST](http://www.cs.toronto.edu/~nitish/unsupervised_video/) dataset. We will download the dataset and then construct and preprocess training and validation sets. For next-frame prediction, our model will be using a previous frame, which we'll call `f_n`, to predict a new frame, called `f_(n + 1)`. To allow the model to create these predictions, we'll need to process the data such that we have "shifted" inputs and outputs, where the input data is frame `x_n`, being used to predict frame `y_(n + 1)`. ```python # Download and load the dataset. fpath = keras.utils.get_file( "moving_mnist.npy", "http://www.cs.toronto.edu/~nitish/unsupervised_video/mnist_test_seq.npy", ) dataset = np.load(fpath) # Swap the axes representing the number of frames and number of data samples. dataset = np.swapaxes(dataset, 0, 1) # We'll pick out 1000 of the 10000 total examples and use those. dataset = dataset[:1000, ...] # Add a channel dimension since the images are grayscale. dataset = np.expand_dims(dataset, axis=-1) # Split into train and validation sets using indexing to optimize memory. indexes = np.arange(dataset.shape[0]) np.random.shuffle(indexes) train_index = indexes[: int(0.9 * dataset.shape[0])] val_index = indexes[int(0.9 * dataset.shape[0]) :] train_dataset = dataset[train_index] val_dataset = dataset[val_index] # Normalize the data to the 0-1 range. train_dataset = train_dataset / 255 val_dataset = val_dataset / 255 # We'll define a helper function to shift the frames, where # `x` is frames 0 to n - 1, and `y` is frames 1 to n. def create_shifted_frames(data): x = data[:, 0 : data.shape[1] - 1, :, :] y = data[:, 1 : data.shape[1], :, :] return x, y # Apply the processing function to the datasets. x_train, y_train = create_shifted_frames(train_dataset) x_val, y_val = create_shifted_frames(val_dataset) # Inspect the dataset. print("Training Dataset Shapes: " + str(x_train.shape) + ", " + str(y_train.shape)) print("Validation Dataset Shapes: " + str(x_val.shape) + ", " + str(y_val.shape)) ``` <div class="k-default-codeblock"> ``` Training Dataset Shapes: (900, 19, 64, 64, 1), (900, 19, 64, 64, 1) Validation Dataset Shapes: (100, 19, 64, 64, 1), (100, 19, 64, 64, 1) ``` </div> --- ## Data Visualization Our data consists of sequences of frames, each of which are used to predict the upcoming frame. Let's take a look at some of these sequential frames. ```python # Construct a figure on which we will visualize the images. fig, axes = plt.subplots(4, 5, figsize=(10, 8)) # Plot each of the sequential images for one random data example. data_choice = np.random.choice(range(len(train_dataset)), size=1)[0] for idx, ax in enumerate(axes.flat): ax.imshow(np.squeeze(train_dataset[data_choice][idx]), cmap="gray") ax.set_title(f"Frame {idx + 1}") ax.axis("off") # Print information and display the figure. print(f"Displaying frames for example {data_choice}.") plt.show() ``` <div class="k-default-codeblock"> ``` Displaying frames for example 130. ``` </div> ![png](/img/examples/vision/conv_lstm/conv_lstm_7_1.png) --- ## Model Construction To build a Convolutional LSTM model, we will use the `ConvLSTM2D` layer, which will accept inputs of shape `(batch_size, num_frames, width, height, channels)`, and return a prediction movie of the same shape. ```python # Construct the input layer with no definite frame size. inp = layers.Input(shape=(None, *x_train.shape[2:])) # We will construct 3 `ConvLSTM2D` layers with batch normalization, # followed by a `Conv3D` layer for the spatiotemporal outputs. x = layers.ConvLSTM2D( filters=64, kernel_size=(5, 5), padding="same", return_sequences=True, activation="relu", )(inp) x = layers.BatchNormalization()(x) x = layers.ConvLSTM2D( filters=64, kernel_size=(3, 3), padding="same", return_sequences=True, activation="relu", )(x) x = layers.BatchNormalization()(x) x = layers.ConvLSTM2D( filters=64, kernel_size=(1, 1), padding="same", return_sequences=True, activation="relu", )(x) x = layers.Conv3D( filters=1, kernel_size=(3, 3, 3), activation="sigmoid", padding="same" )(x) # Next, we will build the complete model and compile it. model = keras.models.Model(inp, x) model.compile( loss=keras.losses.binary_crossentropy, optimizer=keras.optimizers.Adam(), ) ``` --- ## Model Training With our model and data constructed, we can now train the model. ```python # Define some callbacks to improve training. early_stopping = keras.callbacks.EarlyStopping(monitor="val_loss", patience=10) reduce_lr = keras.callbacks.ReduceLROnPlateau(monitor="val_loss", patience=5) # Define modifiable training hyperparameters. epochs = 20 batch_size = 5 # Fit the model to the training data. model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_val, y_val), callbacks=[early_stopping, reduce_lr], ) ``` --- ## Frame Prediction Visualizations With our model now constructed and trained, we can generate some example frame predictions based on a new video. We'll pick a random example from the validation set and then choose the first ten frames from them. From there, we can allow the model to predict 10 new frames, which we can compare to the ground truth frame predictions. ```python # Select a random example from the validation dataset. example = val_dataset[np.random.choice(range(len(val_dataset)), size=1)[0]] # Pick the first/last ten frames from the example. frames = example[:10, ...] original_frames = example[10:, ...] # Predict a new set of 10 frames. for _ in range(10): # Extract the model's prediction and post-process it. new_prediction = model.predict(np.expand_dims(frames, axis=0)) new_prediction = np.squeeze(new_prediction, axis=0) predicted_frame = np.expand_dims(new_prediction[-1, ...], axis=0) # Extend the set of prediction frames. frames = np.concatenate((frames, predicted_frame), axis=0) # Construct a figure for the original and new frames. fig, axes = plt.subplots(2, 10, figsize=(20, 4)) # Plot the original frames. for idx, ax in enumerate(axes[0]): ax.imshow(np.squeeze(original_frames[idx]), cmap="gray") ax.set_title(f"Frame {idx + 11}") ax.axis("off") # Plot the new frames. new_frames = frames[10:, ...] for idx, ax in enumerate(axes[1]): ax.imshow(np.squeeze(new_frames[idx]), cmap="gray") ax.set_title(f"Frame {idx + 11}") ax.axis("off") # Display the figure. plt.show() ``` ![png](/img/examples/vision/conv_lstm/conv_lstm_13_0.png) --- ## Predicted Videos Finally, we'll pick a few examples from the validation set and construct some GIFs with them to see the model's predicted videos. You can use the trained model hosted on [Hugging Face Hub](https://huggingface.co/keras-io/conv-lstm) and try the demo on [Hugging Face Spaces](https://huggingface.co/spaces/keras-io/conv-lstm). ```python # Select a few random examples from the dataset. examples = val_dataset[np.random.choice(range(len(val_dataset)), size=5)] # Iterate over the examples and predict the frames. predicted_videos = [] for example in examples: # Pick the first/last ten frames from the example. frames = example[:10, ...] original_frames = example[10:, ...] new_predictions = np.zeros(shape=(10, *frames[0].shape)) # Predict a new set of 10 frames. for i in range(10): # Extract the model's prediction and post-process it. frames = example[: 10 + i + 1, ...] new_prediction = model.predict(np.expand_dims(frames, axis=0)) new_prediction = np.squeeze(new_prediction, axis=0) predicted_frame = np.expand_dims(new_prediction[-1, ...], axis=0) # Extend the set of prediction frames. new_predictions[i] = predicted_frame # Create and save GIFs for each of the ground truth/prediction images. for frame_set in [original_frames, new_predictions]: # Construct a GIF from the selected video frames. current_frames = np.squeeze(frame_set) current_frames = current_frames[..., np.newaxis] * np.ones(3) current_frames = (current_frames * 255).astype(np.uint8) current_frames = list(current_frames) # Construct a GIF from the frames. with io.BytesIO() as gif: imageio.mimsave(gif, current_frames, "GIF", fps=5) predicted_videos.append(gif.getvalue()) # Display the videos. print(" Truth\tPrediction") for i in range(0, len(predicted_videos), 2): # Construct and display an `HBox` with the ground truth and prediction. box = HBox( [ widgets.Image(value=predicted_videos[i]), widgets.Image(value=predicted_videos[i + 1]), ] ) display(box) ``` <div class="k-default-codeblock"> ``` Truth Prediction ``` </div> ![Imgur](https://i.imgur.com/UYMTsw7.gif)
{'content_hash': '7ee514165346f0ec617fbcafaa2a27b0', 'timestamp': '', 'source': 'github', 'line_count': 339, 'max_line_length': 418, 'avg_line_length': 30.625368731563423, 'alnum_prop': 0.6986129840107879, 'repo_name': 'keras-team/keras-io', 'id': '6fb6a0a99dfce797f7aa9f4f31b6901a9769fcdb', 'size': '10440', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'examples/vision/md/conv_lstm.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '15929'}, {'name': 'Dockerfile', 'bytes': '188'}, {'name': 'HTML', 'bytes': '21968'}, {'name': 'Jupyter Notebook', 'bytes': '718942'}, {'name': 'Makefile', 'bytes': '193'}, {'name': 'Python', 'bytes': '680865'}]}
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /* Program.cs -- программа удаляет у указанных экземпляров отметку об инвентаризации. * Ars Magna project, http://arsmagna.ru * ------------------------------------------------------- * Status: poor */ #region Using directives using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using ManagedIrbis; #endregion // ReSharper disable UseStringInterpolation // ReSharper disable StringLiteralTypo // ReSharper disable LocalizableElement namespace RemoveInventarization { class Program { private static int _index; private static Stopwatch _stopwatch; private static IrbisConnection _connection; /// <summary> /// Форматируем отрезок времени /// в виде ЧЧ:ММ:СС. /// </summary> private static string _FormatTimeSpan ( TimeSpan timeSpan ) { string result = string.Format ( "{0:00}:{1:00}:{2:00}", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds ); return result; } static bool ProcessRecord ( MarcRecord record, string number ) { RecordField field = record.Fields .GetField(910) .GetField('b', number) .FirstOrDefault(); if (ReferenceEquals(field, null)) { Console.WriteLine("{0}: no 910", number); return false; } bool processed = field.HaveSubField('!') || field.HaveSubField('s'); if (processed) { field.RemoveSubField('!'); field.RemoveSubField('s'); Console.Write("[{0}]", record.Mfn); } else { Console.Write("{0} ", record.Mfn); } return processed; } static void ProcessNumber ( string number ) { number = number.Trim(); if (string.IsNullOrEmpty(number)) { return; } Console.Write ( "{0,6}) {1} ", _index++, _FormatTimeSpan(_stopwatch.Elapsed) ); int[] mfns = _connection.Search("\"IN=" + number + "\""); if (mfns.Length == 0) { Console.WriteLine("{0}: not found", number); return; } Console.Write("{0}: ", number); foreach (int mfn in mfns) { MarcRecord record = _connection.ReadRecord(mfn); if (ProcessRecord(record, number)) { _connection.WriteRecord(record); } Console.WriteLine(); } } /// <summary> /// Аргументы: 1) имя файла в формате "одна строчка - один номер", /// 2) строка подключения к серверу. /// </summary> /// <param name="args"></param> static void Main ( string[] args ) { if (args.Length != 2) { Console.WriteLine ("RemoveInventarization <sigla.txt> <connectionString>"); return; } string fileName = args[0]; string connectionString = args[1]; _stopwatch = new Stopwatch(); try { using (var reader = new StreamReader(fileName, Encoding.Default)) using (_connection = new IrbisConnection(connectionString)) { string line; while ((line = reader.ReadLine()) != null) { ProcessNumber(line); } } } catch (Exception exception) { Console.WriteLine(exception); } _stopwatch.Stop(); Console.WriteLine(); Console.WriteLine("Elapsed: {0}", _FormatTimeSpan(_stopwatch.Elapsed)); } } }
{'content_hash': 'dcb7fb85a695bae1809d2b14f081d679', 'timestamp': '', 'source': 'github', 'line_count': 170, 'max_line_length': 85, 'avg_line_length': 26.764705882352942, 'alnum_prop': 0.4487912087912088, 'repo_name': 'amironov73/ManagedIrbis', 'id': '367971e7a8479c5b52db4084efcbe238f1bdbec0', 'size': '4718', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Source/Classic/Apps/RemoveInventarization/Program.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '92910'}, {'name': 'ASP.NET', 'bytes': '413'}, {'name': 'Batchfile', 'bytes': '33021'}, {'name': 'C', 'bytes': '24669'}, {'name': 'C#', 'bytes': '19567730'}, {'name': 'CSS', 'bytes': '170'}, {'name': 'F*', 'bytes': '362819'}, {'name': 'HTML', 'bytes': '5592'}, {'name': 'JavaScript', 'bytes': '5342'}, {'name': 'Pascal', 'bytes': '152697'}, {'name': 'Shell', 'bytes': '524'}, {'name': 'Smalltalk', 'bytes': '29356'}, {'name': 'TeX', 'bytes': '44337'}, {'name': 'VBA', 'bytes': '46543'}, {'name': 'Witcher Script', 'bytes': '40165'}]}
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: > While evaluating "for (ExpressionNoIn; Expression; Expression) Statement", ExpressionNoIn is evaulated first es5id: 12.6.3_A2 description: Using "(function(){throw "NoInExpression"})()" as ExpressionNoIn ---*/ ////////////////////////////////////////////////////////////////////////////// //CHECK#1 try { for((function(){throw "NoInExpression";})(); (function(){throw "FirstExpression";})(); (function(){throw "SecondExpression";})()) { var in_for = "reached"; } $ERROR('#1: (function(){throw "NoInExpression";})() lead to throwing exception'); } catch (e) { if (e !== "NoInExpression") { $ERROR('#1: When for (ExpressionNoIn ; Expression ; Expression) Statement is evaluated ExpressionNoIn evaluates first'); } } // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //CHECK#2 if (in_for !== undefined) { $ERROR('#2: in_for === undefined. Actual: in_for ==='+ in_for ); } // //////////////////////////////////////////////////////////////////////////////
{'content_hash': '85f9ad05ae18f931db1575dd826d9e58', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 132, 'avg_line_length': 37.303030303030305, 'alnum_prop': 0.49471974004874086, 'repo_name': 'baslr/ArangoDB', 'id': '1b0d7d864e0934ef07603fbc1ba07c1bc33c04cf', 'size': '1231', 'binary': False, 'copies': '5', 'ref': 'refs/heads/3.1-silent', 'path': '3rdParty/V8/V8-5.0.71.39/test/test262/data/test/language/statements/for/S12.6.3_A2.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '391227'}, {'name': 'Awk', 'bytes': '4272'}, {'name': 'Batchfile', 'bytes': '62892'}, {'name': 'C', 'bytes': '7932707'}, {'name': 'C#', 'bytes': '96430'}, {'name': 'C++', 'bytes': '284363933'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CMake', 'bytes': '681903'}, {'name': 'CSS', 'bytes': '1036656'}, {'name': 'CWeb', 'bytes': '174166'}, {'name': 'Cuda', 'bytes': '52444'}, {'name': 'DIGITAL Command Language', 'bytes': '259402'}, {'name': 'Emacs Lisp', 'bytes': '14637'}, {'name': 'Fortran', 'bytes': '1856'}, {'name': 'Groovy', 'bytes': '131'}, {'name': 'HTML', 'bytes': '2318016'}, {'name': 'Java', 'bytes': '2325801'}, {'name': 'JavaScript', 'bytes': '67878359'}, {'name': 'LLVM', 'bytes': '24129'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'Lua', 'bytes': '16189'}, {'name': 'M4', 'bytes': '600550'}, {'name': 'Makefile', 'bytes': '509612'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'NSIS', 'bytes': '28404'}, {'name': 'Objective-C', 'bytes': '19321'}, {'name': 'Objective-C++', 'bytes': '2503'}, {'name': 'PHP', 'bytes': '98503'}, {'name': 'Pascal', 'bytes': '145688'}, {'name': 'Perl', 'bytes': '720157'}, {'name': 'Perl 6', 'bytes': '9918'}, {'name': 'Python', 'bytes': '5859911'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'R', 'bytes': '5123'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Roff', 'bytes': '1010686'}, {'name': 'Ruby', 'bytes': '922159'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Scheme', 'bytes': '10604'}, {'name': 'Shell', 'bytes': '511077'}, {'name': 'Swift', 'bytes': '116'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '32117'}, {'name': 'Vim script', 'bytes': '4075'}, {'name': 'Visual Basic', 'bytes': '11568'}, {'name': 'XSLT', 'bytes': '551977'}, {'name': 'Yacc', 'bytes': '53005'}]}
<resources> <string name="app_name">FAU Fablab</string> <string name="appbar_fau">FAU</string> <string name="appbar_fablab">FabLab</string> <string name="appbar_opened">Geöffnet</string> <string name="appbar_opened_since">seit</string> <string name="appbar_closed">Geschlossen</string> <string name="appbar_fablab_closed">Das FabLab war heute noch nicht geöffnet</string> <string name="appbar_orderedby_name">Sortiert nach Name</string> <string name="appbar_orderedby_price">Sortiert nach Preis</string> <string name="appbar_orderby_name">Nach Name sortieren</string> <string name="appbar_orderby_price">Nach Preis sortieren</string> <string name="cart_title">Warenkorb:</string> <string name="cart_price">Gesamtpreis:</string> <string name="cart_total_price_title">Gesamtpreis:</string> <string name="cart_button_checkout">Zur Kasse</string> <string name="cart_article_label">Artikel</string> <string name="cart_product_quantity">Menge in</string> <string name="cart_product_removed">Artikel entfernt</string> <string name="cart_product_undo">Rückgängig</string> <string name="cart_entry_dialog_change_amount">Menge ändern</string> <string name="search_hint">Suche Produkt</string> <string name="title_scan_product">Produkt scannen</string> <string name="action_add_to_cart">In den Warenkorb</string> <string name="action_update">Speichern</string> <string name="add_to_calendar"> Termin in Kalender\neintragen</string> <string name="add_to_cart_amount">Menge:</string> <string name="add_to_cart_rounded_to">gerundet auf</string> <string name="add_to_cart_plus">+</string> <string name="add_to_cart_minus">-</string> <string name="barcode_scanner_invalid_barcode">Ungültiger Barcode</string> <string name="barcode_scanner_product_not_found">Produkt nicht gefunden</string> <string name="product_dialog_location">Standort anzeigen</string> <string name="product_dialog_cart">Zum Warenkorb hinzufügen</string> <string name="product_dialog_report">Ausgegangenes Produkt melden</string> <string name="retrofit_callback_failure">Leider ist bei der Abfrage ein Fehler aufgetreten</string> <string name="no_products_found">Es wurden keine Produkte gefunden</string> <string name="title_scan_qr_code">QR-Code scannen</string> <string name="checkout_pay">Bitte gehen Sie zur Kasse und bezahlen Sie</string> <string name="checkout_error">Fehler beim Übertragen des Warenkorbs</string> <string name="checkout_cancelled">Der Bezahlvorgang wurde abgebrochen</string> <string name="checkout_paid">Ihr Warenkorb wurde bezahlt</string> <string name="checkout_request">Bitte am Kassenterminal \'Warenkorb aus App laden\' auswählen und den angezeigten Code scannen.</string> <string name="retry">Nochmal versuchen</string> <string name="qr_code_scanner_invalid_qr_code">Ungültiger QR-Code</string> <string name="invalid_location">Standort nicht verfügbar</string> <string name="news_preview_image_content_description">Vorschaubild</string> <string name="dates_date">Datum:</string> <string name="dates_time">Uhrzeit:</string> <string name="dates_location">Ort:</string> <string name="action_search">Suche</string> <string name="search_all_hint">Produkt</string> <string name="per">pro</string> <string name="stacktrace_messaging_subject">Fehlermeldung FAU FabLab</string> <string name="stacktrace_messaging_chooser_title">Sende Fehlermeldung mit:</string> <string name="stacktrace_messaging_dialog_title">Fehlermeldung</string> <string name="stacktrace_messaging_dialog_text">Leider ist bei der letzten Benutzung ein Fehler aufgetreten. Wir sind stetig bemüht die Applikation zu verbessern. Deshalb bitten wir Sie die Fehlermeldung an uns weiterzuleiten.</string> <string name="outOfStock_messaging_subject">Ausgegangenes Produkt</string> <string name="outOfStock_messaging_chooser_title">Sende Meldung mit:</string> <string name="alert_messaging_subject">Störmeldung</string> <string name="alert_messaging_chooser_title">Sende Meldung mit:</string> <string name="alert_dialog_title">Störmeldung</string> <string name="alert_dialog_tool">Gerät:</string> <string name="alert_dialog_problem">Problem:</string> <string name="reservation_dialog_title">Maschinenreservierung</string> <string name="reservation_no_machine_available">Zur Zeit ist keine Maschine reservierbar.</string> <string name="reservation_no_usage_available">Es sind noch keine Reservierungen vorhanden.</string> <string name="reservation_button">Reservieren</string> <string name="reservation_button_now">Jetzt reservieren!</string> <string name="reservation_hint_projects">Projekte</string> <string name="reservation_hint_user">User</string> <string name="inventory_fragment_title">Inventur</string> <string name="inventory_fragment_scan_product">Produkt scannen</string> <string name="inventory_fragment_search_product">Produkt suchen</string> <string name="inventory_fragment_search_category">Kategorien suchen</string> <string name="inventory_fragment_delete_inventory">Inventar löschen</string> <string name="inventory_fragment_show_inventory">Inventar anzeigen</string> <string name="show_inventory_fragment_title">Inventar:</string> <string name="inventory_card_product_id">Produkt ID:</string> <string name="inventory_card_user_name">durchgeführt von:</string> <string name="inventory_card_updated_at">durchgeführt am:</string> <string name="inventory_delete_inventory_fail">Fehler beim Inventar löschen aufgetreten</string> <string name="inventory_delete_inventory_success">Inventar gelöscht</string> <string name="inventory_get_inventory_fail">Fehler bei der Abfrage des Inventars aufgetreten</string> <string name="inventory_get_inventory_success">Es sind keine Objekte im Inventar vorhanden</string> <string name="inventory_add_inventory_fail">Objekt konnte nicht hinzugefügt werden</string> <string name="inventory_add_inventory_success">Objekt erfolgreich hinzugefügt</string> <string name="inventory_login_title">Login</string> <string name="inventory_login_login">Login</string> <string name="inventory_login_scanner">Mit QRCode einloggen</string> <string name="inventory_login_hint_username">Benutzername</string> <string name="inventory_login_hint_password">Passwort</string> <string name="inventory_login_unauthorized_user">Anmeldung ist fehlgeschlagen</string> <string name="inventory_login_qr_code_scanner_request">Bitte Inventur QRCode scannen</string> <string name="version_check_update_optional">Optionales Update verfügbar</string> <string name="version_check_update_required">Update verfügbar</string> <string name="version_check_no_update_available">Kein Update verfügbar</string> <string name="category_title">Kategorie:</string> <string name="category_button">Produkte suchen</string> <string name="add_calendar">FabLab Kalender hinzugefügt</string> <string name="existing_calendar">FabLab Kalender existiert bereits</string> <string name="action_add_photo_project">Photo hinzufügen</string> <string name="action_save_project">Projekt speichern</string> <string name="action_delete_project">Projekt löschen</string> <string name="projects_title">Projekte:</string> <string name="action_new_project">neues Projekt</string> <string name="action_create_new_project">neues Projekt erstellen</string> <string name="action_create_project_from_cart">Projekt aus Warenkorb erstellen</string> <string name="no_carts_available">Es liegen keine Warenkörbe vor</string> <string name="choose_cart_title">Warenkörbe:</string> <string name="action_browse_gallery">Gallery durchsuchen</string> <string name="action_take_photo">Photo aufnehmen</string> <string name="edit_project_hint_title">Titel</string> <string name="edit_project_hint_short_description">Kurzbeschreibung</string> <string name="edit_project_hint_description">Beschreibung</string> <string name="save_project_title">Speichern</string> <string name="save_project_local">Entwurf lokal speichern</string> <string name="save_project_github">auf Github hochladen</string> <string name="save_project_success">Projekt wurde gespeichert</string> <string name="save_project_failure">Beim Speichern ist leider ein Fehler aufgetreten</string> <string name="project_photo_image_too_large">das Bild ist zu groß</string> <string name="project_photo_not_yet_uploaded">Bitte das Projekt erst auf Github hochladen, bevor Bilder eingefügt werden können</string> <string name="project_photo_upload_failure">Beim Hochladen ist leider ein Fehler aufgetreten</string> <string name="license_information_ok">Zustimmen</string> <string name="license_information_cancel">Ablehnen</string> <string name="license_information_title"> <![CDATA[ Um Ihr Projekt hochzuladen müssen Sie der <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0-Lizenz</a> für sämtliche Inhalte zustimmen. ]]> </string> <string name="project_photo_image_wrong_format">Die Datei hat das falsche Format</string> <string name="cart_entry_title">Warenkorb</string> <string name="cart_entry_items">Items:</string> <string name="edit_cart_cart">#Warenkorb:</string> <string name="edit_cart_description">#Beschreibung:</string> <string name="confirm_project_delete_message">Möchten Sie das Projekt wirklich löschen?</string> <string name="confirm_project_delete">Ja</string> <string name="confirm_project_not_delete">Nein</string> <string name="delete_project_failure">Leider ist beim löschen ein Fehler aufgetreten</string> <string name="key_show_cart_fab">showcartfab</string> <string name="key_user">user</string> <string name="key_product_search">productsearch</string> <string name="key_project">project</string> <string name="key_cart">cart</string> <string name="key_delete_project_position">delete_position</string> <string name="key_delete_project_project">delete_project</string> <string name="product_map_download_failed">Fehler beim Laden der Karte aufgetreten</string> <!-- Strings for navigation drawer titles --> <string name="news">News</string> <string name="productsearch">Produkt suchen</string> <string name="categorysearch">Kategoriesuche</string> <string name="scanner">Produkt scannen</string> <string name="about">Über</string> <string name="settings">Einstellungen</string> <string name="alert">Störmeldung</string> <string name="logout">Logout</string> <string name="inventory">Inventur</string> <string name="projects">Projekte</string> <string name="reservation">Maschinenreservierung</string> <string name="navdrawer_login_hint_username">Username</string> <string name="navdrawer_login_hint_password">Password</string> <string name="navdrawer_button_login">Login</string> <string name="app_website">fablab.fau.de</string> <!-- Strings for widget --> <string name="small_widget_name">FabLab Widget Small</string> <string name="large_widget_name">FabLab Widget Large</string> <string name="about_license"> <![CDATA[ Copyright 2015 MAD FabLab team <br> <br> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <br> <br> <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> <br> <br> Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]> </string> <string name="about_content"> <![CDATA[ Diese App wurde im Rahmen des <a href="https://www2.informatik.uni-erlangen.de/teaching/SS2015/MAD/index.html">MAD Projekts</a> an der FAU Erlangen-Nürnberg entwickelt.<br> Der Quellcode kann unter <a href="https://github.com/FAU-Inf2/fablab-android">Github</a> gefunden werden.<br> Feedback jederzeit gerne per <a href="mailto:[email protected]">E-Mail</a>.<br> <br> Die Entwickler sind:<br> <br> Emanuel Eimer<br> Stefan Herpich<br> Michael Sandner<br> Julia Schottenhamml<br> Johannes Pfann<br> Max Jalowski<br> Sebastian Haubner<br> Katharina Full<br> Philip Kanhäußer<br> Julian Lorz<br> Daniel Rosenmüller ]]> </string> <string name="about_open_source_licenses">Open Source Lizenzen</string> <string name="about_used_libraries"> <![CDATA[ <b>jackson-databind</b> (Apache License 2.0) <br> <a href="https://github.com/FasterXML/jackson-databind/">Projektseite</a> <br> <br> <b>retrofit</b> (Apache License 2.0) <br> <a href="https://github.com/square/retrofit">Projektseite</a> <br> <br> <b>okhttp</b> (Apache License 2.0) <br> <a href="https://github.com/square/okhttp">Projektseite</a> <br> <br> <b>okio</b> (Apache License 2.0) <br> <a href="https://github.com/square/okio">Projektseite</a> <br> <br> <b>ormlite</b> (ISC license) <br> <a href="http://ormlite.com/">Projektseite</a> <br> <br> <b>barcodescanner</b> (Apache License 2.0) <br> <a href="https://github.com/dm77/barcodescanner">Projektseite</a> <br> <br> <b>AndroidSlidingUpPanel</b> (Apache License 2.0) <br> <a href="https://github.com/umano/AndroidSlidingUpPanel">Projektseite</a> <br> <br> <b>SwipeableRecyclerView</b> (Apache License 2.0) <br> <a href="https://github.com/brnunes/SwipeableRecyclerView">Projektseite</a> <br> <br> <b>CircleImageView</b> (Apache License 2.0 )<br> <a href="https://github.com/hdodenhof/CircleImageView">Projektseite</a> <br> <br> <b>FloatingActionButton</b> (Apache License 2.0) <br> <a href="https://github.com/Clans/FloatingActionButton">Projektseite</a> <br> <br> <b>EventBus</b> (Apache License 2.0) <br> <a href="https://github.com/greenrobot/EventBus">Projektseite</a> <br> <br> <b>Picasso</b> (Apache License 2.0) <br> <a href="https://github.com/square/picasso">Projektseite</a> <br> <br> <b>Renderers</b> (Apache License 2.0) <br> <a href="https://github.com/pedrovgs/Renderers">Projektseite</a> <br> <br> <b>Dagger</b> (Apache License 2.0) <br> <a href="https://github.com/square/dagger">Projektseite</a> <br> <br> <b>Butterknife</b> (Apache License 2.0) <br> <a href="https://github.com/JakeWharton/butterknife">Projektseite</a> <br> <br> <b>Support PreferenceFragment</b> (Apache License 2.0) <br> <a href="https://github.com/Machinarius/PreferenceFragment-Compat">Projektseite</a> <br> <br> <b>RecyclerViewFastScroller</b> (Apache License 2.0) <br> <a href="https://github.com/danoz73/RecyclerViewFastScroller">Projektseite</a> ]]> </string> </resources>
{'content_hash': '8a75df5fe23f4b48e9537653245d8166', 'timestamp': '', 'source': 'github', 'line_count': 320, 'max_line_length': 239, 'avg_line_length': 50.0375, 'alnum_prop': 0.6873594803897077, 'repo_name': 'FAU-Inf2/fablab-android', 'id': '37ce4798db93b220e4adee913d6da4e7b2322911', 'size': '16057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/values/strings.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1690'}, {'name': 'CSS', 'bytes': '353'}, {'name': 'HTML', 'bytes': '28775'}, {'name': 'Java', 'bytes': '505971'}, {'name': 'Shell', 'bytes': '1519'}]}
// Package tests has the unit tests of package messaging. // pubnubDetailedHistory_test.go contains the tests related to the History requests on pubnub Api package tests import ( "encoding/json" "fmt" "github.com/pubnub/go/gae/messaging" "golang.org/x/net/context" "net/http" "strconv" "strings" "testing" "time" //"net/http/httptest" "appengine/aetest" ) // TestDetailedHistoryStart prints a message on the screen to mark the beginning of // detailed history tests. // PrintTestMessage is defined in the common.go file. func TestDetailedHistoryStart(t *testing.T) { PrintTestMessage("==========DetailedHistory tests start==========") } // TestDetailedHistory publish's a message to a pubnub channel and when the sent response is received, // calls the history method of the messaging package to fetch 1 message. This received // message is compared to the message sent and if both match test is successful. /*func TestDetailedHistory(t *testing.T) { pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, "", false, "") r := GenRandom() channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20)) message := "Test Message" returnPublishChannel := make(chan []byte) errorChannel := make(chan []byte) responseChannel := make(chan string) waitChannel := make(chan string) go pubnubInstance.Publish(channel, message, returnPublishChannel, errorChannel) go ParseResponse(returnPublishChannel, pubnubInstance, channel, message, "DetailedHistory", 1, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(responseChannel, waitChannel) ParseWaitResponse(waitChannel, t, "DetailedHistory") } // TestEncryptedDetailedHistory publish's an encrypted message to a pubnub channel and when the // sent response is received, calls the history method of the messaging package to fetch // 1 message. This received message is compared to the message sent and if both match test is successful. func TestEncryptedDetailedHistory(t *testing.T) { pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, "enigma", false, "") r := GenRandom() channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20)) message := "Test Message" returnPublishChannel := make(chan []byte) errorChannel := make(chan []byte) responseChannel := make(chan string) waitChannel := make(chan string) go pubnubInstance.Publish(channel, message, returnPublishChannel, errorChannel) go ParseResponse(returnPublishChannel, pubnubInstance, channel, message, "EncryptedDetailedHistory", 1, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(responseChannel, waitChannel) ParseWaitResponse(waitChannel, t, "EncryptedDetailedHistory") }*/ // TestDetailedHistoryFor10Messages publish's 10 unencrypted messages to a pubnub channel, and after that // calls the history method of the messaging package to fetch last 10 messages. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryFor10Messages(t *testing.T) { testName := "TestDetailedHistoryFor10Messages" DetailedHistoryFor10Messages(t, "", testName) time.Sleep(2 * time.Second) } // TestDetailedHistoryFor10EncryptedMessages publish's 10 encrypted messages to a pubnub channel, and after that // calls the history method of the messaging package to fetch last 10 messages. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryFor10EncryptedMessages(t *testing.T) { testName := "TestDetailedHistoryFor10EncryptedMessages" DetailedHistoryFor10Messages(t, "enigma", testName) time.Sleep(2 * time.Second) } // DetailedHistoryFor10Messages is a common method used by both TestDetailedHistoryFor10EncryptedMessages // and TestDetailedHistoryFor10Messages to publish's 10 messages to a pubnub channel, and after that // call the history method of the messaging package to fetch last 10 messages. These received // messages are compared to the messages sent and if all match test is successful. func DetailedHistoryFor10Messages(t *testing.T, cipherKey string, testName string) { numberOfMessages := 10 startMessagesFrom := 0 /*context, err := aetest.NewContext(nil) if err != nil { t.Fatal(err) } defer context.Close() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/", nil)*/ //context, err := aetest.NewContext(nil) //req, _ := http.NewRequest("GET", "/", nil) inst, err := aetest.NewInstance(&aetest.Options{"", true}) context := CreateContext(inst) if err != nil { t.Fatal(err) } //defer context.Close() defer inst.Close() uuid := "" w, req := InitAppEngineContext(t) //pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, cipherKey, false, "") pubnubInstance := messaging.New(context, uuid, w, req, PubKey, SubKey, SecKey, "", false) message := "Test Message " r := GenRandom() channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20)) messagesSent := PublishMessages(context, w, req, pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) if messagesSent { returnHistoryChannel := make(chan []byte) errorChannel := make(chan []byte) responseChannel := make(chan string) waitChannel := make(chan string) //go pubnubInstance.History(channel, numberOfMessages, 0, 0, false, returnHistoryChannel, errorChannel) go pubnubInstance.History(context, w, req, channel, numberOfMessages, 0, 0, false, returnHistoryChannel, errorChannel) go ParseHistoryResponseForMultipleMessages(returnHistoryChannel, channel, message, testName, startMessagesFrom, numberOfMessages, cipherKey, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(responseChannel, waitChannel) ParseWaitResponse(waitChannel, t, testName) } else { t.Error("Test '" + testName + "': failed.") } } // TestDetailedHistoryParamsFor10MessagesWithSeretKey publish's 10 unencrypted secret keyed messages // to a pubnub channel, and after that calls the history method of the messaging package to fetch // last 10 messages with time parameters between which the messages were sent. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryParamsFor10MessagesWithSeretKey(t *testing.T) { testName := "TestDetailedHistoryFor10MessagesWithSeretKey" DetailedHistoryParamsFor10Messages(t, "", "secret", testName) time.Sleep(2 * time.Second) } // TestDetailedHistoryParamsFor10EncryptedMessagesWithSeretKey publish's 10 encrypted secret keyed messages // to a pubnub channel, and after that calls the history method of the messaging package to fetch // last 10 messages with time parameters between which the messages were sent. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryParamsFor10EncryptedMessagesWithSeretKey(t *testing.T) { testName := "TestDetailedHistoryFor10EncryptedMessagesWithSeretKey" DetailedHistoryParamsFor10Messages(t, "enigma", "secret", testName) time.Sleep(2 * time.Second) } // TestDetailedHistoryParamsFor10Messages publish's 10 unencrypted messages // to a pubnub channel, and after that calls the history method of the messaging package to fetch // last 10 messages with time parameters between which the messages were sent. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryParamsFor10Messages(t *testing.T) { testName := "TestDetailedHistoryFor10Messages" DetailedHistoryParamsFor10Messages(t, "", "", testName) time.Sleep(2 * time.Second) } // TestDetailedHistoryParamsFor10EncryptedMessages publish's 10 encrypted messages // to a pubnub channel, and after that calls the history method of the messaging package to fetch // last 10 messages with time parameters between which the messages were sent. These received // messages are compared to the messages sent and if all match test is successful. func TestDetailedHistoryParamsFor10EncryptedMessages(t *testing.T) { testName := "TestDetailedHistoryParamsFor10EncryptedMessages" DetailedHistoryParamsFor10Messages(t, "enigma", "", testName) time.Sleep(2 * time.Second) } // DetailedHistoryFor10Messages is a common method used by both TestDetailedHistoryFor10EncryptedMessages // and TestDetailedHistoryFor10Messages to publish's 10 messages to a pubnub channel, and after that // call the history method of the messaging package to fetch last 10 messages with time parameters // between which the messages were sent. These received message is compared to the messages sent and // if all match test is successful. func DetailedHistoryParamsFor10Messages(t *testing.T, cipherKey string, secretKey string, testName string) { numberOfMessages := 5 /*context, err := aetest.NewContext(nil) if err != nil { t.Fatal(err) } defer context.Close()*/ //context := CreateContext() inst, err := aetest.NewInstance(&aetest.Options{"", true}) context := CreateContext(inst) if err != nil { t.Fatal(err) } defer inst.Close() uuid := "" w, req := InitAppEngineContext(t) //pubnubInstance := messaging.NewPubnub(PubKey, SubKey, SecKey, cipherKey, false, "") pubnubInstance := messaging.New(context, uuid, w, req, PubKey, SubKey, SecKey, "", false) message := "Test Message " r := GenRandom() channel := fmt.Sprintf("testChannel_dh_%d", r.Intn(20)) startTime := GetServerTime(context, w, req, pubnubInstance, t, testName) startMessagesFrom := 0 //messagesSent := PublishMessages(pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) messagesSent := PublishMessages(context, w, req, pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) midTime := GetServerTime(context, w, req, pubnubInstance, t, testName) startMessagesFrom = 5 //messagesSent2 := PublishMessages(pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) messagesSent2 := PublishMessages(context, w, req, pubnubInstance, channel, t, startMessagesFrom, numberOfMessages, message) endTime := GetServerTime(context, w, req, pubnubInstance, t, testName) startMessagesFrom = 0 if messagesSent { returnHistoryChannel := make(chan []byte) responseChannel := make(chan string) errorChannel := make(chan []byte) waitChannel := make(chan string) //go pubnubInstance.History(channel, numberOfMessages, startTime, midTime, false, returnHistoryChannel, errorChannel) go pubnubInstance.History(context, w, req, channel, numberOfMessages, startTime, midTime, false, returnHistoryChannel, errorChannel) go ParseHistoryResponseForMultipleMessages(returnHistoryChannel, channel, message, testName, startMessagesFrom, numberOfMessages, cipherKey, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(responseChannel, waitChannel) ParseWaitResponse(waitChannel, t, testName) } else { t.Error("Test '" + testName + "': failed.") } startMessagesFrom = 5 if messagesSent2 { returnHistoryChannel2 := make(chan []byte) errorChannel2 := make(chan []byte) responseChannel2 := make(chan string) waitChannel2 := make(chan string) //go pubnubInstance.History(channel, numberOfMessages, midTime, endTime, false, returnHistoryChannel2, errorChannel2) go pubnubInstance.History(context, w, req, channel, numberOfMessages, midTime, endTime, false, returnHistoryChannel2, errorChannel2) go ParseHistoryResponseForMultipleMessages(returnHistoryChannel2, channel, message, testName, startMessagesFrom, numberOfMessages, cipherKey, responseChannel2) go ParseErrorResponse(errorChannel2, responseChannel2) go WaitForCompletion(responseChannel2, waitChannel2) ParseWaitResponse(waitChannel2, t, testName) } else { t.Error("Test '" + testName + "': failed.") } } // GetServerTime calls the GetTime method of the messaging, parses the response to get the // value and return it. func GetServerTime(c context.Context, w http.ResponseWriter, r *http.Request, pubnubInstance *messaging.Pubnub, t *testing.T, testName string) int64 { returnTimeChannel := make(chan []byte) errorChannel := make(chan []byte) //go pubnubInstance.GetTime(returnTimeChannel, errorChannel) go pubnubInstance.GetTime(c, w, r, returnTimeChannel, errorChannel) return ParseServerTimeResponse(returnTimeChannel, t, testName) } // ParseServerTimeResponse unmarshals the time response from the pubnub api and returns the int64 value. // On error the test fails. func ParseServerTimeResponse(returnChannel chan []byte, t *testing.T, testName string) int64 { timeout := make(chan bool, 1) go func() { time.Sleep(15 * time.Second) timeout <- true }() for { select { case value, ok := <-returnChannel: if !ok { break } if string(value) != "[]" { response := string(value) if response != "" { var arr []int64 err2 := json.Unmarshal(value, &arr) if err2 != nil { fmt.Println("err2 time", err2) t.Error("Test '" + testName + "': failed.") break } else { return arr[0] } } else { fmt.Println("response", response) t.Error("Test '" + testName + "': failed.") break } } case <-timeout: fmt.Println("timeout") t.Error("Test '" + testName + "': failed.") break } } //t.Error("Test '" + testName + "': failed.") //return 0 } // PublishMessages calls the publish method of messaging package numberOfMessages times // and appends the count with the message to distinguish from the others. // // Parameters: // pubnubInstance: a reference of *messaging.Pubnub, // channel: the pubnub channel to publish the messages, // t: a reference to *testing.T, // startMessagesFrom: the message identifer, // numberOfMessages: number of messages to send, // message: message to send. // // returns a bool if the publish of all messages is successful. func PublishMessages(context context.Context, w http.ResponseWriter, r *http.Request, pubnubInstance *messaging.Pubnub, channel string, t *testing.T, startMessagesFrom int, numberOfMessages int, message string) bool { messagesReceived := 0 messageToSend := "" tOut := messaging.GetNonSubscribeTimeout() messaging.SetNonSubscribeTimeout(30) for i := startMessagesFrom; i < startMessagesFrom+numberOfMessages; i++ { messageToSend = message + strconv.Itoa(i) returnPublishChannel := make(chan []byte) errorChannel := make(chan []byte) go pubnubInstance.Publish(context, w, r, channel, messageToSend, returnPublishChannel, errorChannel) messagesReceived++ //time.Sleep(500 * time.Millisecond) time.Sleep(1500 * time.Millisecond) } if messagesReceived == numberOfMessages { return true } messaging.SetNonSubscribeTimeout(tOut) return false } // ParseHistoryResponseForMultipleMessages unmarshalls the response of the history call to the // pubnub api and compares the received messages to the sent messages. If the response match the // test is successful. // // Parameters: // returnChannel: channel to read the response from, // t: a reference to *testing.T, // channel: the pubnub channel to publish the messages, // message: message to compare, // testname: the test name form where this method is called, // startMessagesFrom: the message identifer, // numberOfMessages: number of messages to send, // cipherKey: the cipher key if used. Can be empty. func ParseHistoryResponseForMultipleMessages(returnChannel chan []byte, channel string, message string, testName string, startMessagesFrom int, numberOfMessages int, cipherKey string, responseChannel chan string) { for { value, ok := <-returnChannel if !ok { break } if string(value) != "[]" { data, _, _, err := messaging.ParseJSON(value, cipherKey) if err != nil { //t.Error("Test '" + testName + "': failed.") responseChannel <- "Test '" + testName + "': failed. Message: " + err.Error() } else { var arr []string err2 := json.Unmarshal([]byte(data), &arr) if err2 != nil { //t.Error("Test '" + testName + "': failed."); responseChannel <- "Test '" + testName + "': failed. Message: " + err2.Error() } else { messagesReceived := 0 if len(arr) != numberOfMessages { responseChannel <- "Test '" + testName + "': failed." //t.Error("Test '" + testName + "': failed."); break } for i := 0; i < numberOfMessages; i++ { if arr[i] == message+strconv.Itoa(startMessagesFrom+i) { //fmt.Println("data:",arr[i]) messagesReceived++ } } if messagesReceived == numberOfMessages { fmt.Println("Test '" + testName + "': passed.") responseChannel <- "Test '" + testName + "': passed." } else { responseChannel <- "Test '" + testName + "': failed. Returned message mismatch" //t.Error("Test '" + testName + "': failed."); } break } } } } } // ParseHistoryResponse parses the history response from the pubnub api on the returnChannel // and checks if the response contains the message. If true then the test is successful. func ParseHistoryResponse(returnChannel chan []byte, channel string, message string, testName string, responseChannel chan string) { for { value, ok := <-returnChannel if !ok { break } if string(value) != "[]" { response := string(value) //fmt.Println("response", response) if strings.Contains(response, message) { //fmt.Println("Test '" + testName + "': passed.") responseChannel <- "Test '" + testName + "': passed." break } else { responseChannel <- "Test '" + testName + "': failed." } } } } // ParseResponse parses the publish response from the pubnub api on the returnChannel and // when the sent response is received, calls the history method of the messaging // package to fetch 1 message. /*func ParseResponse(returnChannel chan []byte, pubnubInstance *messaging.Pubnub, channel string, message string, testName string, numberOfMessages int, responseChannel chan string) { for { value, ok := <-returnChannel if !ok { break } if string(value) != "[]" { returnHistoryChannel := make(chan []byte) var errorChannel = make(chan []byte) go pubnubInstance.History(channel, 1, 0, 0, false, returnHistoryChannel, errorChannel) go ParseHistoryResponse(returnHistoryChannel, channel, message, testName, responseChannel) go ParseErrorResponse(errorChannel, responseChannel) go WaitForCompletion(returnHistoryChannel, waitChannel) ParseWaitResponse(waitChannel2, t, testName) break } } }*/ // TestDetailedHistoryEnd prints a message on the screen to mark the end of // detailed history tests. // PrintTestMessage is defined in the common.go file. func TestDetailedHistoryEnd(t *testing.T) { PrintTestMessage("==========DetailedHistory tests end==========") }
{'content_hash': '8a99bbb536f52c4b29877bff9aecc05c', 'timestamp': '', 'source': 'github', 'line_count': 455, 'max_line_length': 217, 'avg_line_length': 41.34285714285714, 'alnum_prop': 0.7414810483227898, 'repo_name': 'jack89129/koding', 'id': '40397d3455cb3cb324124902c0d602cd3fc233d9', 'size': '18811', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'go/src/vendor/github.com/pubnub/go/gae/tests/pubnubDetailedHistory_test.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '736295'}, {'name': 'CoffeeScript', 'bytes': '4698645'}, {'name': 'Go', 'bytes': '3993614'}, {'name': 'HTML', 'bytes': '98899'}, {'name': 'JavaScript', 'bytes': '85244'}, {'name': 'Makefile', 'bytes': '9533'}, {'name': 'PHP', 'bytes': '1570'}, {'name': 'PLpgSQL', 'bytes': '12770'}, {'name': 'Perl', 'bytes': '1612'}, {'name': 'Python', 'bytes': '27988'}, {'name': 'Ruby', 'bytes': '4413'}, {'name': 'SQLPL', 'bytes': '5187'}, {'name': 'Shell', 'bytes': '108915'}]}
package com.wangsong.common.model; import java.io.Serializable; import java.util.List; public class JsonTreeData implements Serializable{ public String id; //json id public String pid; // public String text; //json 显示文本 public String state; //json 'open','closed' public Attributes attributes; public List<JsonTreeData> children; // public String getId() { return id; } public void setId(String id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getState() { return state; } public void setState(String state) { this.state = state; } public List<JsonTreeData> getChildren() { return children; } public void setChildren(List<JsonTreeData> children) { this.children = children; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public Attributes getAttributes() { return attributes; } public void setAttributes(Attributes attributes) { this.attributes = attributes; } }
{'content_hash': '243560b590af8078edd615e256df433d', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 58, 'avg_line_length': 23.07547169811321, 'alnum_prop': 0.6099754701553557, 'repo_name': 'chenyiming/learn', 'id': 'c7f5aa92fa7f09194ebee1cd93b85746eaa640d8', 'size': '1231', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'dubbo-app/dubbo-app-common/src/main/java/com/wangsong/common/model/JsonTreeData.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '600676'}, {'name': 'HTML', 'bytes': '330'}, {'name': 'Java', 'bytes': '865690'}, {'name': 'JavaScript', 'bytes': '662816'}, {'name': 'Shell', 'bytes': '85'}]}
package main import ( "math/rand" "os" "time" "github.com/spf13/pflag" cliflag "k8s.io/component-base/cli/flag" "k8s.io/component-base/logs" _ "k8s.io/component-base/metrics/prometheus/clientgo" "k8s.io/kubernetes/cmd/kube-scheduler/app" ) func main() { rand.Seed(time.Now().UnixNano()) command := app.NewSchedulerCommand() // TODO: once we switch everything over to Cobra commands, we can go back to calling // utilflag.InitFlags() (by removing its pflag.Parse() call). For now, we have to set the // normalize func and add the go flag set by hand. pflag.CommandLine.SetNormalizeFunc(cliflag.WordSepNormalizeFunc) // utilflag.InitFlags() logs.InitLogs() defer logs.FlushLogs() if err := command.Execute(); err != nil { os.Exit(1) } }
{'content_hash': '06951425a393988eb3de4659dccf539f', 'timestamp': '', 'source': 'github', 'line_count': 34, 'max_line_length': 90, 'avg_line_length': 22.5, 'alnum_prop': 0.7124183006535948, 'repo_name': 'mboersma/kubernetes', 'id': '3a19f2b5b1ae4b1defdd51f0341a4ede29eca594', 'size': '1334', 'binary': False, 'copies': '31', 'ref': 'refs/heads/master', 'path': 'cmd/kube-scheduler/scheduler.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '22704'}, {'name': 'Go', 'bytes': '13059821'}, {'name': 'HTML', 'bytes': '1264818'}, {'name': 'Java', 'bytes': '5653'}, {'name': 'JavaScript', 'bytes': '196313'}, {'name': 'Makefile', 'bytes': '18170'}, {'name': 'Nginx', 'bytes': '1013'}, {'name': 'PHP', 'bytes': '736'}, {'name': 'Python', 'bytes': '57166'}, {'name': 'Ruby', 'bytes': '8715'}, {'name': 'SaltStack', 'bytes': '32985'}, {'name': 'Shell', 'bytes': '846179'}]}
<?php namespace Konstrui\Logger; interface LoggableInterface { /** * @param LoggerInterface $logger */ public function setLogger(LoggerInterface $logger); /** * @param $log * * @return mixed */ public function log($log); }
{'content_hash': 'e028fded7b3639f1469bfbf010a81440', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 55, 'avg_line_length': 15.11111111111111, 'alnum_prop': 0.5919117647058824, 'repo_name': 'shazarre/konstrui', 'id': '564c9cdc2df82fb4cf924e935b66f267c2ea7315', 'size': '272', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Konstrui/Logger/LoggableInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '13'}, {'name': 'PHP', 'bytes': '109109'}]}
package ch.heigvd.res.samples.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * This simple application shows how to use standard Java IO classes to read, * process and write bytes stored in files. The program first generates a number * of test files (with random byte values). * * It then duplicates one of these files, applying two filters in the process. * Every byte read is counted, so that the number of read bytes (and the number * of read operations) can be queried afterwards. Every byte tentatively written * is checked by another filter stream. If the byte has a value of 13, then it * is NOT written and is ignored. The number of skipped bytes is counted. * * @author Olivier Liechti */ public class FileIOExample { /** * @param args the command line arguments */ public static void main(String[] args) { // We will use two classes to generate, then duplicate test files Generator generator = new Generator(); Duplicator duplicator = new Duplicator(); // Let's generate a number of test files, with different sizes generator.generateTestFile("/tmp/tf200", 200); generator.generateTestFile("/tmp/tf511", 511); generator.generateTestFile("/tmp/tf512", 512); generator.generateTestFile("/tmp/tf513", 513); generator.generateTestFile("/tmp/tf5110", 5110); generator.generateTestFile("/tmp/tf5120", 5120); CountingFilterInputStream is = null; SuperstitiousFilterOutputStream os = null; try { // We want to count the number of bytes read from the file AND we want to make sure that performance is adequate // So, we wrap an instance of our own CountingFilterInputStream around a BufferedInputStream, and wrap this one around // the FileInputStream is = new CountingFilterInputStream(new BufferedInputStream(new FileInputStream("/tmp/tf5120"))); // We want to skip bytes that have a value of '13' during the duplicaiton process, so we use our own SuperstitiousFilterOutputStream os = new SuperstitiousFilterOutputStream(new BufferedOutputStream(new FileOutputStream("/tmp/tf5120-copy"))); // We have our 2 streams, connected to 2 files, so we can ask duplicator to do its job. Note that duplicator does not know that he // is working on files, we could have passed streams connected to network endpoints or to other processes duplicator.duplicate(is, os); Logger.getLogger(FileIOExample.class.getName()).log(Level.INFO, "{0} bytes read in {1} operations.", new Object[]{is.getNumberOfBytesRead(), is.getNumberOfReadOperations()}); Logger.getLogger(FileIOExample.class.getName()).log(Level.INFO, " bytes written, {0} bytes skipped, for a total of {1} bytes evaluated.", new Object[]{os.getNumberOfBytesSkipped(), os.getNumberOfBytesEvaluated()}); System.out.println(); System.out.println(os.getNumberOfBytesWritten()); } catch (IOException ex) { Logger.getLogger(FileIOExample.class.getName()).log(Level.SEVERE, null, ex); } finally { // We are done, so let's close the streams. try { is.close(); } catch (IOException ex) { Logger.getLogger(FileIOExample.class.getName()).log(Level.SEVERE, null, ex); } try { os.close(); } catch (IOException ex) { Logger.getLogger(FileIOExample.class.getName()).log(Level.SEVERE, null, ex); } } } }
{'content_hash': '59902ddfe4a9b714d45c4aa415237667', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 218, 'avg_line_length': 40.976470588235294, 'alnum_prop': 0.737008326155613, 'repo_name': 'wasadigi/Teaching-HEIGVD-RES', 'id': '7489ff8f8920c9f52eec049bae26c18a40300c68', 'size': '3483', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'examples/02-FileIOExample/FileIOExample/src/ch/heigvd/res/samples/io/FileIOExample.java', 'mode': '33188', 'license': 'mit', 'language': []}
// Copyright (c) 2012 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 "chromeos/network/shill_property_handler.h" #include <stddef.h> #include <map> #include <memory> #include <set> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "base/values.h" #include "chromeos/dbus/shill/shill_clients.h" #include "chromeos/dbus/shill/shill_device_client.h" #include "chromeos/dbus/shill/shill_ipconfig_client.h" #include "chromeos/dbus/shill/shill_manager_client.h" #include "chromeos/dbus/shill/shill_profile_client.h" #include "chromeos/dbus/shill/shill_service_client.h" #include "dbus/object_path.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace chromeos { namespace { void ErrorCallbackFunction(const std::string& error_name, const std::string& error_message) { LOG(ERROR) << "Shill Error: " << error_name << " : " << error_message; } class TestListener : public internal::ShillPropertyHandler::Listener { public: TestListener() : technology_list_updates_(0), errors_(0) { } void UpdateManagedList(ManagedState::ManagedType type, const base::ListValue& entries) override { VLOG(1) << "UpdateManagedList[" << ManagedState::TypeToString(type) << "]: " << entries.GetSize(); UpdateEntries(GetTypeString(type), entries); } void UpdateManagedStateProperties(ManagedState::ManagedType type, const std::string& path, const base::Value& properties) override { VLOG(2) << "UpdateManagedStateProperties: " << GetTypeString(type); initial_property_updates(GetTypeString(type))[path] += 1; } void ProfileListChanged() override {} void UpdateNetworkServiceProperty(const std::string& service_path, const std::string& key, const base::Value& value) override { AddPropertyUpdate(shill::kServiceCompleteListProperty, service_path); } void UpdateDeviceProperty(const std::string& device_path, const std::string& key, const base::Value& value) override { AddPropertyUpdate(shill::kDevicesProperty, device_path); } void UpdateIPConfigProperties(ManagedState::ManagedType type, const std::string& path, const std::string& ip_config_path, const base::Value& properties) override { AddPropertyUpdate(shill::kIPConfigsProperty, ip_config_path); } void TechnologyListChanged() override { VLOG(1) << "TechnologyListChanged."; ++technology_list_updates_; } void CheckPortalListChanged(const std::string& check_portal_list) override {} void ManagedStateListChanged(ManagedState::ManagedType type) override { VLOG(1) << "ManagedStateListChanged: " << GetTypeString(type); AddStateListUpdate(GetTypeString(type)); } void DefaultNetworkServiceChanged(const std::string& service_path) override {} std::vector<std::string>& entries(const std::string& type) { return entries_[type]; } std::map<std::string, int>& property_updates(const std::string& type) { return property_updates_[type]; } std::map<std::string, int>& initial_property_updates( const std::string& type) { return initial_property_updates_[type]; } int list_updates(const std::string& type) { return list_updates_[type]; } int technology_list_updates() { return technology_list_updates_; } void reset_list_updates() { VLOG(1) << "=== RESET LIST UPDATES ==="; list_updates_.clear(); technology_list_updates_ = 0; } int errors() { return errors_; } private: std::string GetTypeString(ManagedState::ManagedType type) { if (type == ManagedState::MANAGED_TYPE_NETWORK) return shill::kServiceCompleteListProperty; if (type == ManagedState::MANAGED_TYPE_DEVICE) return shill::kDevicesProperty; NOTREACHED(); return std::string(); } void UpdateEntries(const std::string& type, const base::ListValue& entries) { if (type.empty()) return; entries_[type].clear(); for (base::ListValue::const_iterator iter = entries.begin(); iter != entries.end(); ++iter) { std::string path; if (iter->GetAsString(&path)) entries_[type].push_back(path); } } void AddPropertyUpdate(const std::string& type, const std::string& path) { DCHECK(!type.empty()); VLOG(2) << "AddPropertyUpdate: " << type; property_updates(type)[path] += 1; } void AddStateListUpdate(const std::string& type) { DCHECK(!type.empty()); list_updates_[type] += 1; } // Map of list-type -> paths std::map<std::string, std::vector<std::string>> entries_; // Map of list-type -> map of paths -> update counts std::map<std::string, std::map<std::string, int>> property_updates_; std::map<std::string, std::map<std::string, int>> initial_property_updates_; // Map of list-type -> list update counts std::map<std::string, int > list_updates_; int technology_list_updates_; int errors_; }; } // namespace class ShillPropertyHandlerTest : public testing::Test { public: ShillPropertyHandlerTest() : task_environment_( base::test::SingleThreadTaskEnvironment::MainThreadType::UI), manager_test_(NULL), device_test_(NULL), service_test_(NULL), profile_test_(NULL) {} ~ShillPropertyHandlerTest() override = default; void SetUp() override { shill_clients::InitializeFakes(); // Get the test interface for manager / device / service and clear the // default stub properties. manager_test_ = ShillManagerClient::Get()->GetTestInterface(); ASSERT_TRUE(manager_test_); device_test_ = ShillDeviceClient::Get()->GetTestInterface(); ASSERT_TRUE(device_test_); service_test_ = ShillServiceClient::Get()->GetTestInterface(); ASSERT_TRUE(service_test_); profile_test_ = ShillProfileClient::Get()->GetTestInterface(); ASSERT_TRUE(profile_test_); SetupShillPropertyHandler(); base::RunLoop().RunUntilIdle(); } void TearDown() override { shill_property_handler_.reset(); listener_.reset(); shill_clients::Shutdown(); } void AddDevice(const std::string& type, const std::string& id) { ASSERT_TRUE(IsValidType(type)); device_test_->AddDevice(id, type, id); } void RemoveDevice(const std::string& id) { device_test_->RemoveDevice(id); } void AddService(const std::string& type, const std::string& id, const std::string& state) { VLOG(2) << "AddService: " << type << ": " << id << ": " << state; ASSERT_TRUE(IsValidType(type)); service_test_->AddService(id /* service_path */, id /* guid */, id /* name */, type, state, true /* visible */); } void AddServiceWithIPConfig(const std::string& type, const std::string& id, const std::string& state, const std::string& ipconfig_path) { ASSERT_TRUE(IsValidType(type)); service_test_->AddServiceWithIPConfig(id, /* service_path */ id /* guid */, id /* name */, type, state, ipconfig_path, true /* visible */); } void AddServiceToProfile(const std::string& type, const std::string& id, bool visible) { service_test_->AddService(id /* service_path */, id /* guid */, id /* name */, type, shill::kStateIdle, visible); std::vector<std::string> profiles; profile_test_->GetProfilePaths(&profiles); ASSERT_TRUE(profiles.size() > 0); base::DictionaryValue properties; // Empty entry profile_test_->AddService(profiles[0], id); } void RemoveService(const std::string& id) { service_test_->RemoveService(id); } // Call this after any initial Shill client setup void SetupShillPropertyHandler() { SetupDefaultShillState(); listener_.reset(new TestListener); shill_property_handler_.reset( new internal::ShillPropertyHandler(listener_.get())); shill_property_handler_->Init(); } bool IsValidType(const std::string& type) { return (type == shill::kTypeEthernet || type == shill::kTypeEthernetEap || type == shill::kTypeWifi || type == shill::kTypeCellular || type == shill::kTypeVPN); } protected: void SetupDefaultShillState() { base::RunLoop().RunUntilIdle(); // Process any pending updates device_test_->ClearDevices(); AddDevice(shill::kTypeWifi, "stub_wifi_device1"); AddDevice(shill::kTypeCellular, "stub_cellular_device1"); service_test_->ClearServices(); AddService(shill::kTypeEthernet, "stub_ethernet", shill::kStateOnline); AddService(shill::kTypeWifi, "stub_wifi1", shill::kStateOnline); AddService(shill::kTypeWifi, "stub_wifi2", shill::kStateIdle); AddService(shill::kTypeCellular, "stub_cellular1", shill::kStateIdle); } base::test::SingleThreadTaskEnvironment task_environment_; std::unique_ptr<TestListener> listener_; std::unique_ptr<internal::ShillPropertyHandler> shill_property_handler_; ShillManagerClient::TestInterface* manager_test_; ShillDeviceClient::TestInterface* device_test_; ShillServiceClient::TestInterface* service_test_; ShillProfileClient::TestInterface* profile_test_; private: DISALLOW_COPY_AND_ASSIGN(ShillPropertyHandlerTest); }; TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerStub) { EXPECT_TRUE(shill_property_handler_->IsTechnologyAvailable(shill::kTypeWifi)); EXPECT_TRUE(shill_property_handler_->IsTechnologyEnabled(shill::kTypeWifi)); const size_t kNumShillManagerClientStubImplDevices = 2; EXPECT_EQ(kNumShillManagerClientStubImplDevices, listener_->entries(shill::kDevicesProperty).size()); const size_t kNumShillManagerClientStubImplServices = 4; EXPECT_EQ(kNumShillManagerClientStubImplServices, listener_->entries(shill::kServiceCompleteListProperty).size()); EXPECT_EQ(0, listener_->errors()); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerTechnologyChanged) { const int initial_technology_updates = 2; // Available and Enabled lists EXPECT_EQ(initial_technology_updates, listener_->technology_list_updates()); // Remove an enabled technology. Updates both the Available and Enabled lists. listener_->reset_list_updates(); manager_test_->RemoveTechnology(shill::kTypeWifi); base::RunLoop().RunUntilIdle(); EXPECT_EQ(2, listener_->technology_list_updates()); // Add a disabled technology. listener_->reset_list_updates(); manager_test_->AddTechnology(shill::kTypeWifi, false); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->technology_list_updates()); EXPECT_TRUE(shill_property_handler_->IsTechnologyAvailable( shill::kTypeWifi)); EXPECT_FALSE(shill_property_handler_->IsTechnologyEnabled(shill::kTypeWifi)); // Enable the technology. listener_->reset_list_updates(); ShillManagerClient::Get()->EnableTechnology( shill::kTypeWifi, base::DoNothing(), base::BindOnce(&ErrorCallbackFunction)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->technology_list_updates()); EXPECT_TRUE(shill_property_handler_->IsTechnologyEnabled(shill::kTypeWifi)); EXPECT_EQ(0, listener_->errors()); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerTechnologyChangedTransitions) { listener_->reset_list_updates(); manager_test_->AddTechnology(shill::kTypeWifi, /*enabled=*/true); // Disabling WiFi transitions from Disabling -> Disabled. shill_property_handler_->SetTechnologyEnabled( shill::kTypeWifi, /*enabled=*/false, base::DoNothing()); EXPECT_TRUE(shill_property_handler_->IsTechnologyDisabling(shill::kTypeWifi)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->technology_list_updates()); EXPECT_FALSE( shill_property_handler_->IsTechnologyDisabling(shill::kTypeWifi)); EXPECT_TRUE(shill_property_handler_->IsTechnologyAvailable(shill::kTypeWifi)); // Enable the technology. listener_->reset_list_updates(); shill_property_handler_->SetTechnologyEnabled( shill::kTypeWifi, /*enabled=*/true, base::DoNothing()); EXPECT_TRUE(shill_property_handler_->IsTechnologyEnabling(shill::kTypeWifi)); EXPECT_FALSE( shill_property_handler_->IsTechnologyDisabling(shill::kTypeWifi)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->technology_list_updates()); EXPECT_TRUE(shill_property_handler_->IsTechnologyEnabled(shill::kTypeWifi)); EXPECT_FALSE(shill_property_handler_->IsTechnologyEnabling(shill::kTypeWifi)); EXPECT_EQ(0, listener_->errors()); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerDevicePropertyChanged) { const size_t kNumShillManagerClientStubImplDevices = 2; EXPECT_EQ(kNumShillManagerClientStubImplDevices, listener_->entries(shill::kDevicesProperty).size()); // Add a device. listener_->reset_list_updates(); const std::string kTestDevicePath("test_wifi_device1"); AddDevice(shill::kTypeWifi, kTestDevicePath); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kDevicesProperty)); EXPECT_EQ(kNumShillManagerClientStubImplDevices + 1, listener_->entries(shill::kDevicesProperty).size()); // Remove a device listener_->reset_list_updates(); RemoveDevice(kTestDevicePath); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kDevicesProperty)); EXPECT_EQ(kNumShillManagerClientStubImplDevices, listener_->entries(shill::kDevicesProperty).size()); EXPECT_EQ(0, listener_->errors()); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerServicePropertyChanged) { const size_t kNumShillManagerClientStubImplServices = 4; EXPECT_EQ(kNumShillManagerClientStubImplServices, listener_->entries(shill::kServiceCompleteListProperty).size()); // Add a service. listener_->reset_list_updates(); const std::string kTestServicePath("test_wifi_service1"); AddService(shill::kTypeWifi, kTestServicePath, shill::kStateIdle); base::RunLoop().RunUntilIdle(); // Add should trigger a service list update and update entries. EXPECT_EQ(1, listener_->list_updates(shill::kServiceCompleteListProperty)); EXPECT_EQ(kNumShillManagerClientStubImplServices + 1, listener_->entries(shill::kServiceCompleteListProperty).size()); // Service receives an initial property update. EXPECT_EQ(1, listener_->initial_property_updates( shill::kServiceCompleteListProperty)[kTestServicePath]); // Change a property. base::Value scan_interval(3); ShillServiceClient::Get()->SetProperty( dbus::ObjectPath(kTestServicePath), shill::kScanIntervalProperty, scan_interval, base::DoNothing(), base::BindOnce(&ErrorCallbackFunction)); base::RunLoop().RunUntilIdle(); // Property change triggers an update (but not a service list update). EXPECT_EQ(1, listener_->property_updates( shill::kServiceCompleteListProperty)[kTestServicePath]); // Set the state of the service to Connected. This will trigger a service list // update. listener_->reset_list_updates(); ShillServiceClient::Get()->SetProperty( dbus::ObjectPath(kTestServicePath), shill::kStateProperty, base::Value(shill::kStateReady), base::DoNothing(), base::BindOnce(&ErrorCallbackFunction)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kServiceCompleteListProperty)); // Remove a service. This will update the entries and signal a service list // update. listener_->reset_list_updates(); RemoveService(kTestServicePath); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kServiceCompleteListProperty)); EXPECT_EQ(kNumShillManagerClientStubImplServices, listener_->entries(shill::kServiceCompleteListProperty).size()); EXPECT_EQ(0, listener_->errors()); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerIPConfigPropertyChanged) { // Set the properties for an IP Config object. const std::string kTestIPConfigPath("test_ip_config_path"); base::Value ip_address("192.168.1.1"); ShillIPConfigClient::Get()->SetProperty(dbus::ObjectPath(kTestIPConfigPath), shill::kAddressProperty, ip_address, base::DoNothing()); base::ListValue dns_servers; dns_servers.AppendString("192.168.1.100"); dns_servers.AppendString("192.168.1.101"); ShillIPConfigClient::Get()->SetProperty(dbus::ObjectPath(kTestIPConfigPath), shill::kNameServersProperty, dns_servers, base::DoNothing()); base::Value prefixlen(8); ShillIPConfigClient::Get()->SetProperty(dbus::ObjectPath(kTestIPConfigPath), shill::kPrefixlenProperty, prefixlen, base::DoNothing()); base::Value gateway("192.0.0.1"); ShillIPConfigClient::Get()->SetProperty(dbus::ObjectPath(kTestIPConfigPath), shill::kGatewayProperty, gateway, base::DoNothing()); base::RunLoop().RunUntilIdle(); // Add a service with an empty ipconfig and then update // its ipconfig property. const std::string kTestServicePath1("test_wifi_service1"); AddService(shill::kTypeWifi, kTestServicePath1, shill::kStateIdle); base::RunLoop().RunUntilIdle(); // This is the initial property update. EXPECT_EQ(1, listener_->initial_property_updates( shill::kServiceCompleteListProperty)[kTestServicePath1]); ShillServiceClient::Get()->SetProperty( dbus::ObjectPath(kTestServicePath1), shill::kIPConfigProperty, base::Value(kTestIPConfigPath), base::DoNothing(), base::BindOnce(&ErrorCallbackFunction)); base::RunLoop().RunUntilIdle(); // IPConfig property change on the service should trigger an IPConfigs update. EXPECT_EQ(1, listener_->property_updates( shill::kIPConfigsProperty)[kTestIPConfigPath]); // Now, Add a new service with the IPConfig already set. const std::string kTestServicePath2("test_wifi_service2"); AddServiceWithIPConfig(shill::kTypeWifi, kTestServicePath2, shill::kStateIdle, kTestIPConfigPath); base::RunLoop().RunUntilIdle(); // A service with the IPConfig property already set should trigger an // additional IPConfigs update. EXPECT_EQ(2, listener_->property_updates( shill::kIPConfigsProperty)[kTestIPConfigPath]); } TEST_F(ShillPropertyHandlerTest, ShillPropertyHandlerServiceList) { // Add an entry to the profile only. const std::string kTestServicePath1("stub_wifi_profile_only1"); AddServiceToProfile(shill::kTypeWifi, kTestServicePath1, false /* visible */); base::RunLoop().RunUntilIdle(); // Update the Manager properties. This should trigger a single list update, // an initial property update, and a regular property update. listener_->reset_list_updates(); shill_property_handler_->UpdateManagerProperties(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kServiceCompleteListProperty)); EXPECT_EQ(1, listener_->initial_property_updates( shill::kServiceCompleteListProperty)[kTestServicePath1]); EXPECT_EQ(1, listener_->property_updates( shill::kServiceCompleteListProperty)[kTestServicePath1]); // Add a new entry to the services and the profile; should also trigger a // service list update, and a property update. listener_->reset_list_updates(); const std::string kTestServicePath2("stub_wifi_profile_only2"); AddServiceToProfile(shill::kTypeWifi, kTestServicePath2, true); shill_property_handler_->UpdateManagerProperties(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(1, listener_->list_updates(shill::kServiceCompleteListProperty)); EXPECT_EQ(1, listener_->initial_property_updates( shill::kServiceCompleteListProperty)[kTestServicePath2]); EXPECT_EQ(1, listener_->property_updates( shill::kServiceCompleteListProperty)[kTestServicePath2]); } TEST_F(ShillPropertyHandlerTest, ProhibitedTechnologies) { std::vector<std::string> prohibited_technologies; prohibited_technologies.push_back(shill::kTypeEthernet); EXPECT_TRUE( shill_property_handler_->IsTechnologyEnabled(shill::kTypeEthernet)); shill_property_handler_->SetProhibitedTechnologies( prohibited_technologies, network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); // Disabled EXPECT_FALSE( shill_property_handler_->IsTechnologyEnabled(shill::kTypeEthernet)); // Can not enable it back shill_property_handler_->SetTechnologyEnabled( shill::kTypeEthernet, true, network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_FALSE( shill_property_handler_->IsTechnologyEnabled(shill::kTypeEthernet)); // Can enable it back after policy changes prohibited_technologies.clear(); shill_property_handler_->SetProhibitedTechnologies( prohibited_technologies, network_handler::ErrorCallback()); shill_property_handler_->SetTechnologyEnabled( shill::kTypeEthernet, true, network_handler::ErrorCallback()); base::RunLoop().RunUntilIdle(); EXPECT_TRUE( shill_property_handler_->IsTechnologyEnabled(shill::kTypeEthernet)); } } // namespace chromeos
{'content_hash': 'da91ed2d13877cd8cd11b89023ade98c', 'timestamp': '', 'source': 'github', 'line_count': 550, 'max_line_length': 80, 'avg_line_length': 40.558181818181815, 'alnum_prop': 0.6751692293898777, 'repo_name': 'endlessm/chromium-browser', 'id': '44eb2243d21b540b31f1d4ea87716432130b0c6f', 'size': '22307', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chromeos/network/shill_property_handler_unittest.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
define([ 'aeris/util', 'aeris/events', 'aeris/maps/extensions/mapextensionobject', 'aeris/errors/validationerror', 'aeris/maps/strategy/infobox' ], function(_, Events, MapExtensionObject, ValidationError, InfoBoxStrategy) { /** * Representation of an Info Box. * * @publicApi * @class InfoBox * @namespace aeris.maps * @constructor * @extends aeris.maps.extensions.MapExtensionObject */ var InfoBox = function(opt_attrs, opt_options) { var options = _.extend({ strategy: InfoBoxStrategy }, opt_options); var attrs = _.extend({ /** * The lat/lon position to place the info box. * * @attribute position * @type {aeris.maps.LatLon} */ position: [45, -90], /** * The HTML content to display in the info box. * * @attribute content * @type {string} */ content: '' }, opt_attrs); MapExtensionObject.call(this, attrs, options); Events.call(this); }; _.inherits(InfoBox, MapExtensionObject); _.extend(InfoBox.prototype, Events.prototype); /** * @method validate */ InfoBox.prototype.validate = function(attrs) { if (!_.isArray(attrs.position)) { return new ValidationError(attrs.position + ' is not a valid lat/lon coordinate'); } return MapExtensionObject.prototype.validate.apply(this, arguments); }; /** * Set the lat/lon location of the InfoBox * on the map. * * @param {aeris.maps.LatLon} position * @method setPosition */ InfoBox.prototype.setPosition = function(position) { this.set('position', position, { validate: true }); }; /** * Set the HTML content of the InfoBox * @param {string|HTMLElement} content * @method setContent */ InfoBox.prototype.setContent = function(content) { this.set('content', content, { validate: true }); }; return _.expose(InfoBox, 'aeris.maps.InfoBox'); });
{'content_hash': 'd1f7f67621fb8afb23e8108cd548a8e2', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 88, 'avg_line_length': 22.988235294117647, 'alnum_prop': 0.6218014329580348, 'repo_name': 'MikeLockz/exit-now-mobile', 'id': 'c0c0ec33e92024f26c4db8f7d3faa5b18fb29d0f', 'size': '1954', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'www/lib/aerisjs/examples/amd/bower_components/aerisjs/examples/amd/bower_components/aerisjs/examples/amd/bower_components/aerisjs/src/maps/infobox.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '4623'}, {'name': 'C#', 'bytes': '6407'}, {'name': 'C++', 'bytes': '214507'}, {'name': 'CSS', 'bytes': '1326112'}, {'name': 'Erlang', 'bytes': '326'}, {'name': 'HTML', 'bytes': '654576'}, {'name': 'Handlebars', 'bytes': '552'}, {'name': 'Java', 'bytes': '9481'}, {'name': 'JavaScript', 'bytes': '22743701'}, {'name': 'Objective-C', 'bytes': '279212'}, {'name': 'Shell', 'bytes': '7601'}]}
<?php namespace Symfony\Component\Security\Http\Firewall; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface; /** * BasicAuthenticationListener implements Basic HTTP authentication. * * @author Fabien Potencier <[email protected]> * * @final */ class BasicAuthenticationListener extends AbstractListener { private $tokenStorage; private $authenticationManager; private $providerKey; private $authenticationEntryPoint; private $logger; private $ignoreFailure; private $sessionStrategy; public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, string $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint, LoggerInterface $logger = null) { if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); } $this->tokenStorage = $tokenStorage; $this->authenticationManager = $authenticationManager; $this->providerKey = $providerKey; $this->authenticationEntryPoint = $authenticationEntryPoint; $this->logger = $logger; $this->ignoreFailure = false; } /** * {@inheritdoc} */ public function supports(Request $request): ?bool { return null !== $request->headers->get('PHP_AUTH_USER'); } /** * Handles basic authentication. */ public function authenticate(RequestEvent $event) { $request = $event->getRequest(); if (null === $username = $request->headers->get('PHP_AUTH_USER')) { return; } if (null !== $token = $this->tokenStorage->getToken()) { if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) { return; } } if (null !== $this->logger) { $this->logger->info('Basic authentication Authorization header found for user.', ['username' => $username]); } try { $token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey)); $this->migrateSession($request, $token); $this->tokenStorage->setToken($token); } catch (AuthenticationException $e) { $token = $this->tokenStorage->getToken(); if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) { $this->tokenStorage->setToken(null); } if (null !== $this->logger) { $this->logger->info('Basic authentication failed for user.', ['username' => $username, 'exception' => $e]); } if ($this->ignoreFailure) { return; } $event->setResponse($this->authenticationEntryPoint->start($request, $e)); } } /** * Call this method if your authentication token is stored to a session. * * @final */ public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy) { $this->sessionStrategy = $sessionStrategy; } private function migrateSession(Request $request, TokenInterface $token) { if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) { return; } $this->sessionStrategy->onAuthentication($request, $token); } }
{'content_hash': 'ed859b792d5475d9bf20317e16375800', 'timestamp': '', 'source': 'github', 'line_count': 120, 'max_line_length': 237, 'avg_line_length': 34.84166666666667, 'alnum_prop': 0.6606075101650323, 'repo_name': 'alekitto/symfony', 'id': '0692e055d05399707aaf541d496441f578851445', 'size': '4410', 'binary': False, 'copies': '22', 'ref': 'refs/heads/master', 'path': 'src/Symfony/Component/Security/Http/Firewall/BasicAuthenticationListener.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '49607'}, {'name': 'HTML', 'bytes': '361049'}, {'name': 'Hack', 'bytes': '26'}, {'name': 'JavaScript', 'bytes': '27650'}, {'name': 'PHP', 'bytes': '18997286'}, {'name': 'Shell', 'bytes': '3136'}]}
"use strict"; // TODO: iframes, contenteditable/designMode // Everything is done in functions in this test harness, so we have to declare // all the variables before use to make sure they can be reused. var selection; var testDiv, paras, detachedDiv, detachedPara1, detachedPara2, foreignDoc, foreignPara1, foreignPara2, xmlDoc, xmlElement, detachedXmlElement, detachedTextNode, foreignTextNode, detachedForeignTextNode, xmlTextNode, detachedXmlTextNode, processingInstruction, detachedProcessingInstruction, comment, detachedComment, foreignComment, detachedForeignComment, xmlComment, detachedXmlComment, docfrag, foreignDocfrag, xmlDocfrag, doctype, foreignDoctype, xmlDoctype; var testRanges, testPoints, testNodes; function setupRangeTests() { selection = getSelection(); testDiv = document.querySelector("#test"); if (testDiv) { testDiv.parentNode.removeChild(testDiv); } testDiv = document.createElement("div"); testDiv.id = "test"; document.body.insertBefore(testDiv, document.body.firstChild); // Test some diacritics, to make sure browsers are using code units here // and not something like grapheme clusters. testDiv.innerHTML = "<p id=a>A&#x308;b&#x308;c&#x308;d&#x308;e&#x308;f&#x308;g&#x308;h&#x308;\n" + "<p id=b style=display:none>Ijklmnop\n" + "<p id=c>Qrstuvwx" + "<p id=d style=display:none>Yzabcdef" + "<p id=e style=display:none>Ghijklmn"; paras = testDiv.querySelectorAll("p"); detachedDiv = document.createElement("div"); detachedPara1 = document.createElement("p"); detachedPara1.appendChild(document.createTextNode("Opqrstuv")); detachedPara2 = document.createElement("p"); detachedPara2.appendChild(document.createTextNode("Wxyzabcd")); detachedDiv.appendChild(detachedPara1); detachedDiv.appendChild(detachedPara2); // Opera doesn't automatically create a doctype for a new HTML document, // contrary to spec. It also doesn't let you add doctypes to documents // after the fact through any means I've tried. So foreignDoc in Opera // will have no doctype, foreignDoctype will be null, and Opera will fail // some tests somewhat mysteriously as a result. foreignDoc = document.implementation.createHTMLDocument(""); foreignPara1 = foreignDoc.createElement("p"); foreignPara1.appendChild(foreignDoc.createTextNode("Efghijkl")); foreignPara2 = foreignDoc.createElement("p"); foreignPara2.appendChild(foreignDoc.createTextNode("Mnopqrst")); foreignDoc.body.appendChild(foreignPara1); foreignDoc.body.appendChild(foreignPara2); // Now we get to do really silly stuff, which nobody in the universe is // ever going to actually do, but the spec defines behavior, so too bad. // Testing is fun! xmlDoctype = document.implementation.createDocumentType("qorflesnorf", "abcde", "x\"'y"); xmlDoc = document.implementation.createDocument(null, null, xmlDoctype); detachedXmlElement = xmlDoc.createElement("everyone-hates-hyphenated-element-names"); detachedTextNode = document.createTextNode("Uvwxyzab"); detachedForeignTextNode = foreignDoc.createTextNode("Cdefghij"); detachedXmlTextNode = xmlDoc.createTextNode("Klmnopqr"); // PIs only exist in XML documents, so don't bother with document or // foreignDoc. detachedProcessingInstruction = xmlDoc.createProcessingInstruction("whippoorwill", "chirp chirp chirp"); detachedComment = document.createComment("Stuvwxyz"); // Hurrah, we finally got to "z" at the end! detachedForeignComment = foreignDoc.createComment("אריה יהודה"); detachedXmlComment = xmlDoc.createComment("בן חיים אליעזר"); // We should also test with document fragments that actually contain stuff // . . . but, maybe later. docfrag = document.createDocumentFragment(); foreignDocfrag = foreignDoc.createDocumentFragment(); xmlDocfrag = xmlDoc.createDocumentFragment(); xmlElement = xmlDoc.createElement("igiveuponcreativenames"); xmlTextNode = xmlDoc.createTextNode("do re mi fa so la ti"); xmlElement.appendChild(xmlTextNode); processingInstruction = xmlDoc.createProcessingInstruction("somePI", 'Did you know that ":syn sync fromstart" is very useful when using vim to edit large amounts of JavaScript embedded in HTML?'); xmlDoc.appendChild(xmlElement); xmlDoc.appendChild(processingInstruction); xmlComment = xmlDoc.createComment("I maliciously created a comment that will break incautious XML serializers, but Firefox threw an exception, so all I got was this lousy T-shirt"); xmlDoc.appendChild(xmlComment); comment = document.createComment("Alphabet soup?"); testDiv.appendChild(comment); foreignComment = foreignDoc.createComment('"Commenter" and "commentator" mean different things. I\'ve seen non-native speakers trip up on this.'); foreignDoc.appendChild(foreignComment); foreignTextNode = foreignDoc.createTextNode("I admit that I harbor doubts about whether we really need so many things to test, but it's too late to stop now."); foreignDoc.body.appendChild(foreignTextNode); doctype = document.doctype; foreignDoctype = foreignDoc.doctype; testRanges = [ // Various ranges within the text node children of different // paragraphs. All should be valid. "[paras[0].firstChild, 0, paras[0].firstChild, 0]", "[paras[0].firstChild, 0, paras[0].firstChild, 1]", "[paras[0].firstChild, 2, paras[0].firstChild, 8]", "[paras[0].firstChild, 2, paras[0].firstChild, 9]", "[paras[1].firstChild, 0, paras[1].firstChild, 0]", "[paras[1].firstChild, 0, paras[1].firstChild, 1]", "[paras[1].firstChild, 2, paras[1].firstChild, 8]", "[paras[1].firstChild, 2, paras[1].firstChild, 9]", "[detachedPara1.firstChild, 0, detachedPara1.firstChild, 0]", "[detachedPara1.firstChild, 0, detachedPara1.firstChild, 1]", "[detachedPara1.firstChild, 2, detachedPara1.firstChild, 8]", "[foreignPara1.firstChild, 0, foreignPara1.firstChild, 0]", "[foreignPara1.firstChild, 0, foreignPara1.firstChild, 1]", "[foreignPara1.firstChild, 2, foreignPara1.firstChild, 8]", // Now try testing some elements, not just text nodes. "[document.documentElement, 0, document.documentElement, 1]", "[document.documentElement, 0, document.documentElement, 2]", "[document.documentElement, 1, document.documentElement, 2]", "[document.head, 1, document.head, 1]", "[document.body, 0, document.body, 1]", "[foreignDoc.documentElement, 0, foreignDoc.documentElement, 1]", "[foreignDoc.head, 1, foreignDoc.head, 1]", "[foreignDoc.body, 0, foreignDoc.body, 0]", "[paras[0], 0, paras[0], 0]", "[paras[0], 0, paras[0], 1]", "[detachedPara1, 0, detachedPara1, 0]", "[detachedPara1, 0, detachedPara1, 1]", // Now try some ranges that span elements. "[paras[0].firstChild, 0, paras[1].firstChild, 0]", "[paras[0].firstChild, 0, paras[1].firstChild, 8]", "[paras[0].firstChild, 3, paras[3], 1]", // How about something that spans a node and its descendant? "[paras[0], 0, paras[0].firstChild, 7]", "[testDiv, 2, paras[4], 1]", "[testDiv, 1, paras[2].firstChild, 5]", "[document.documentElement, 1, document.body, 0]", "[foreignDoc.documentElement, 1, foreignDoc.body, 0]", // Then a few more interesting things just for good measure. "[document, 0, document, 1]", "[document, 0, document, 2]", "[document, 1, document, 2]", "[testDiv, 0, comment, 5]", "[paras[2].firstChild, 4, comment, 2]", "[paras[3], 1, comment, 8]", "[foreignDoc, 0, foreignDoc, 0]", "[foreignDoc, 1, foreignComment, 2]", "[foreignDoc.body, 0, foreignTextNode, 36]", "[xmlDoc, 0, xmlDoc, 0]", // Opera 11 crashes if you extractContents() a range that ends at offset // zero in a comment. Comment out this line to run the tests successfully. "[xmlDoc, 1, xmlComment, 0]", "[detachedTextNode, 0, detachedTextNode, 8]", "[detachedForeignTextNode, 7, detachedForeignTextNode, 7]", "[detachedForeignTextNode, 0, detachedForeignTextNode, 8]", "[detachedXmlTextNode, 7, detachedXmlTextNode, 7]", "[detachedXmlTextNode, 0, detachedXmlTextNode, 8]", "[detachedComment, 3, detachedComment, 4]", "[detachedComment, 5, detachedComment, 5]", "[detachedForeignComment, 0, detachedForeignComment, 1]", "[detachedForeignComment, 4, detachedForeignComment, 4]", "[detachedXmlComment, 2, detachedXmlComment, 6]", "[docfrag, 0, docfrag, 0]", "[foreignDocfrag, 0, foreignDocfrag, 0]", "[xmlDocfrag, 0, xmlDocfrag, 0]", ]; testPoints = [ // Various positions within the page, some invalid. Remember that // paras[0] is visible, and paras[1] is display: none. "[paras[0].firstChild, -1]", "[paras[0].firstChild, 0]", "[paras[0].firstChild, 1]", "[paras[0].firstChild, 2]", "[paras[0].firstChild, 8]", "[paras[0].firstChild, 9]", "[paras[0].firstChild, 10]", "[paras[0].firstChild, 65535]", "[paras[1].firstChild, -1]", "[paras[1].firstChild, 0]", "[paras[1].firstChild, 1]", "[paras[1].firstChild, 2]", "[paras[1].firstChild, 8]", "[paras[1].firstChild, 9]", "[paras[1].firstChild, 10]", "[paras[1].firstChild, 65535]", "[detachedPara1.firstChild, 0]", "[detachedPara1.firstChild, 1]", "[detachedPara1.firstChild, 8]", "[detachedPara1.firstChild, 9]", "[foreignPara1.firstChild, 0]", "[foreignPara1.firstChild, 1]", "[foreignPara1.firstChild, 8]", "[foreignPara1.firstChild, 9]", // Now try testing some elements, not just text nodes. "[document.documentElement, -1]", "[document.documentElement, 0]", "[document.documentElement, 1]", "[document.documentElement, 2]", "[document.documentElement, 7]", "[document.head, 1]", "[document.body, 3]", "[foreignDoc.documentElement, 0]", "[foreignDoc.documentElement, 1]", "[foreignDoc.head, 0]", "[foreignDoc.body, 1]", "[paras[0], 0]", "[paras[0], 1]", "[paras[0], 2]", "[paras[1], 0]", "[paras[1], 1]", "[paras[1], 2]", "[detachedPara1, 0]", "[detachedPara1, 1]", "[testDiv, 0]", "[testDiv, 3]", // Then a few more interesting things just for good measure. "[document, -1]", "[document, 0]", "[document, 1]", "[document, 2]", "[document, 3]", "[comment, -1]", "[comment, 0]", "[comment, 4]", "[comment, 96]", "[foreignDoc, 0]", "[foreignDoc, 1]", "[foreignComment, 2]", "[foreignTextNode, 0]", "[foreignTextNode, 36]", "[xmlDoc, -1]", "[xmlDoc, 0]", "[xmlDoc, 1]", "[xmlDoc, 5]", "[xmlComment, 0]", "[xmlComment, 4]", "[processingInstruction, 0]", "[processingInstruction, 5]", "[processingInstruction, 9]", "[detachedTextNode, 0]", "[detachedTextNode, 8]", "[detachedForeignTextNode, 0]", "[detachedForeignTextNode, 8]", "[detachedXmlTextNode, 0]", "[detachedXmlTextNode, 8]", "[detachedProcessingInstruction, 12]", "[detachedComment, 3]", "[detachedComment, 5]", "[detachedForeignComment, 0]", "[detachedForeignComment, 4]", "[detachedXmlComment, 2]", "[docfrag, 0]", "[foreignDocfrag, 0]", "[xmlDocfrag, 0]", "[doctype, 0]", "[doctype, -17]", "[doctype, 1]", "[foreignDoctype, 0]", "[xmlDoctype, 0]", ]; testNodes = [ "paras[0]", "paras[0].firstChild", "paras[1]", "paras[1].firstChild", "foreignPara1", "foreignPara1.firstChild", "detachedPara1", "detachedPara1.firstChild", "detachedPara1", "detachedPara1.firstChild", "testDiv", "document", "detachedDiv", "detachedPara2", "foreignDoc", "foreignPara2", "xmlDoc", "xmlElement", "detachedXmlElement", "detachedTextNode", "foreignTextNode", "detachedForeignTextNode", "xmlTextNode", "detachedXmlTextNode", "processingInstruction", "detachedProcessingInstruction", "comment", "detachedComment", "foreignComment", "detachedForeignComment", "xmlComment", "detachedXmlComment", "docfrag", "foreignDocfrag", "xmlDocfrag", "doctype", "foreignDoctype", "xmlDoctype", ]; } if ("setup" in window) { setup(setupRangeTests); } else { // Presumably we're running from within an iframe or something setupRangeTests(); } /** * Return the length of a node as specified in DOM Range. */ function getNodeLength(node) { if (node.nodeType == Node.DOCUMENT_TYPE_NODE) { return 0; } if (node.nodeType == Node.TEXT_NODE || node.nodeType == Node.PROCESSING_INSTRUCTION_NODE || node.nodeType == Node.COMMENT_NODE) { return node.length; } return node.childNodes.length; } /** * Returns the furthest ancestor of a Node as defined by the spec. */ function furthestAncestor(node) { var root = node; while (root.parentNode != null) { root = root.parentNode; } return root; } /** * "The ancestor containers of a Node are the Node itself and all its * ancestors." * * Is node1 an ancestor container of node2? */ function isAncestorContainer(node1, node2) { return node1 == node2 || (node2.compareDocumentPosition(node1) & Node.DOCUMENT_POSITION_CONTAINS); } /** * Returns the first Node that's after node in tree order, or null if node is * the last Node. */ function nextNode(node) { if (node.hasChildNodes()) { return node.firstChild; } return nextNodeDescendants(node); } /** * Returns the last Node that's before node in tree order, or null if node is * the first Node. */ function previousNode(node) { if (node.previousSibling) { node = node.previousSibling; while (node.hasChildNodes()) { node = node.lastChild; } return node; } return node.parentNode; } /** * Returns the next Node that's after node and all its descendants in tree * order, or null if node is the last Node or an ancestor of it. */ function nextNodeDescendants(node) { while (node && !node.nextSibling) { node = node.parentNode; } if (!node) { return null; } return node.nextSibling; } /** * Returns the ownerDocument of the Node, or the Node itself if it's a * Document. */ function ownerDocument(node) { return node.nodeType == Node.DOCUMENT_NODE ? node : node.ownerDocument; } /** * Returns true if ancestor is an ancestor of descendant, false otherwise. */ function isAncestor(ancestor, descendant) { if (!ancestor || !descendant) { return false; } while (descendant && descendant != ancestor) { descendant = descendant.parentNode; } return descendant == ancestor; } /** * Returns true if descendant is a descendant of ancestor, false otherwise. */ function isDescendant(descendant, ancestor) { return isAncestor(ancestor, descendant); } /** * The position of two boundary points relative to one another, as defined by * the spec. */ function getPosition(nodeA, offsetA, nodeB, offsetB) { // "If node A is the same as node B, return equal if offset A equals offset // B, before if offset A is less than offset B, and after if offset A is // greater than offset B." if (nodeA == nodeB) { if (offsetA == offsetB) { return "equal"; } if (offsetA < offsetB) { return "before"; } if (offsetA > offsetB) { return "after"; } } // "If node A is after node B in tree order, compute the position of (node // B, offset B) relative to (node A, offset A). If it is before, return // after. If it is after, return before." if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_FOLLOWING) { var pos = getPosition(nodeB, offsetB, nodeA, offsetA); if (pos == "before") { return "after"; } if (pos == "after") { return "before"; } } // "If node A is an ancestor of node B:" if (nodeB.compareDocumentPosition(nodeA) & Node.DOCUMENT_POSITION_CONTAINS) { // "Let child equal node B." var child = nodeB; // "While child is not a child of node A, set child to its parent." while (child.parentNode != nodeA) { child = child.parentNode; } // "If the index of child is less than offset A, return after." if (indexOf(child) < offsetA) { return "after"; } } // "Return before." return "before"; } /** * "contained" as defined by DOM Range: "A Node node is contained in a range * range if node's furthest ancestor is the same as range's root, and (node, 0) * is after range's start, and (node, length of node) is before range's end." */ function isContained(node, range) { var pos1 = getPosition(node, 0, range.startContainer, range.startOffset); var pos2 = getPosition(node, getNodeLength(node), range.endContainer, range.endOffset); return furthestAncestor(node) == furthestAncestor(range.startContainer) && pos1 == "after" && pos2 == "before"; } /** * "partially contained" as defined by DOM Range: "A Node is partially * contained in a range if it is an ancestor container of the range's start but * not its end, or vice versa." */ function isPartiallyContained(node, range) { var cond1 = isAncestorContainer(node, range.startContainer); var cond2 = isAncestorContainer(node, range.endContainer); return (cond1 && !cond2) || (cond2 && !cond1); } /** * Index of a node as defined by the spec. */ function indexOf(node) { if (!node.parentNode) { // No preceding sibling nodes, right? return 0; } var i = 0; while (node != node.parentNode.childNodes[i]) { i++; } return i; } /** * extractContents() implementation, following the spec. If an exception is * supposed to be thrown, will return a string with the name (e.g., * "HIERARCHY_REQUEST_ERR") instead of a document fragment. It might also * return an arbitrary human-readable string if a condition is hit that implies * a spec bug. */ function myExtractContents(range) { // "If the context object's detached flag is set, raise an // INVALID_STATE_ERR exception and abort these steps." try { range.collapsed; } catch (e) { return "INVALID_STATE_ERR"; } // "Let frag be a new DocumentFragment whose ownerDocument is the same as // the ownerDocument of the context object's start node." var ownerDoc = range.startContainer.nodeType == Node.DOCUMENT_NODE ? range.startContainer : range.startContainer.ownerDocument; var frag = ownerDoc.createDocumentFragment(); // "If the context object's start and end are the same, abort this method, // returning frag." if (range.startContainer == range.endContainer && range.startOffset == range.endOffset) { return frag; } // "Let original start node, original start offset, original end node, and // original end offset be the context object's start and end nodes and // offsets, respectively." var originalStartNode = range.startContainer; var originalStartOffset = range.startOffset; var originalEndNode = range.endContainer; var originalEndOffset = range.endOffset; // "If original start node and original end node are the same, and they are // a Text or Comment node:" if (range.startContainer == range.endContainer && (range.startContainer.nodeType == Node.TEXT_NODE || range.startContainer.nodeType == Node.COMMENT_NODE)) { // "Let clone be the result of calling cloneNode(false) on original // start node." var clone = originalStartNode.cloneNode(false); // "Set the data of clone to the result of calling // substringData(original start offset, original end offset − original // start offset) on original start node." clone.data = originalStartNode.substringData(originalStartOffset, originalEndOffset - originalStartOffset); // "Append clone as the last child of frag." frag.appendChild(clone); // "Call deleteData(original start offset, original end offset − // original start offset) on original start node." originalStartNode.deleteData(originalStartOffset, originalEndOffset - originalStartOffset); // "Abort this method, returning frag." return frag; } // "Let common ancestor equal original start node." var commonAncestor = originalStartNode; // "While common ancestor is not an ancestor container of original end // node, set common ancestor to its own parent." while (!isAncestorContainer(commonAncestor, originalEndNode)) { commonAncestor = commonAncestor.parentNode; } // "If original start node is an ancestor container of original end node, // let first partially contained child be null." var firstPartiallyContainedChild; if (isAncestorContainer(originalStartNode, originalEndNode)) { firstPartiallyContainedChild = null; // "Otherwise, let first partially contained child be the first child of // common ancestor that is partially contained in the context object." } else { for (var i = 0; i < commonAncestor.childNodes.length; i++) { if (isPartiallyContained(commonAncestor.childNodes[i], range)) { firstPartiallyContainedChild = commonAncestor.childNodes[i]; break; } } if (!firstPartiallyContainedChild) { throw "Spec bug: no first partially contained child!"; } } // "If original end node is an ancestor container of original start node, // let last partially contained child be null." var lastPartiallyContainedChild; if (isAncestorContainer(originalEndNode, originalStartNode)) { lastPartiallyContainedChild = null; // "Otherwise, let last partially contained child be the last child of // common ancestor that is partially contained in the context object." } else { for (var i = commonAncestor.childNodes.length - 1; i >= 0; i--) { if (isPartiallyContained(commonAncestor.childNodes[i], range)) { lastPartiallyContainedChild = commonAncestor.childNodes[i]; break; } } if (!lastPartiallyContainedChild) { throw "Spec bug: no last partially contained child!"; } } // "Let contained children be a list of all children of common ancestor // that are contained in the context object, in tree order." // // "If any member of contained children is a DocumentType, raise a // HIERARCHY_REQUEST_ERR exception and abort these steps." var containedChildren = []; for (var i = 0; i < commonAncestor.childNodes.length; i++) { if (isContained(commonAncestor.childNodes[i], range)) { if (commonAncestor.childNodes[i].nodeType == Node.DOCUMENT_TYPE_NODE) { return "HIERARCHY_REQUEST_ERR"; } containedChildren.push(commonAncestor.childNodes[i]); } } // "If original start node is an ancestor container of original end node, // set new node to original start node and new offset to original start // offset." var newNode, newOffset; if (isAncestorContainer(originalStartNode, originalEndNode)) { newNode = originalStartNode; newOffset = originalStartOffset; // "Otherwise:" } else { // "Let reference node equal original start node." var referenceNode = originalStartNode; // "While reference node's parent is not null and is not an ancestor // container of original end node, set reference node to its parent." while (referenceNode.parentNode && !isAncestorContainer(referenceNode.parentNode, originalEndNode)) { referenceNode = referenceNode.parentNode; } // "Set new node to the parent of reference node, and new offset to one // plus the index of reference node." newNode = referenceNode.parentNode; newOffset = 1 + indexOf(referenceNode); } // "If first partially contained child is a Text or Comment node:" if (firstPartiallyContainedChild && (firstPartiallyContainedChild.nodeType == Node.TEXT_NODE || firstPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) { // "Let clone be the result of calling cloneNode(false) on original // start node." var clone = originalStartNode.cloneNode(false); // "Set the data of clone to the result of calling substringData() on // original start node, with original start offset as the first // argument and (length of original start node − original start offset) // as the second." clone.data = originalStartNode.substringData(originalStartOffset, getNodeLength(originalStartNode) - originalStartOffset); // "Append clone as the last child of frag." frag.appendChild(clone); // "Call deleteData() on original start node, with original start // offset as the first argument and (length of original start node − // original start offset) as the second." originalStartNode.deleteData(originalStartOffset, getNodeLength(originalStartNode) - originalStartOffset); // "Otherwise, if first partially contained child is not null:" } else if (firstPartiallyContainedChild) { // "Let clone be the result of calling cloneNode(false) on first // partially contained child." var clone = firstPartiallyContainedChild.cloneNode(false); // "Append clone as the last child of frag." frag.appendChild(clone); // "Let subrange be a new Range whose start is (original start node, // original start offset) and whose end is (first partially contained // child, length of first partially contained child)." var subrange = ownerDoc.createRange(); subrange.setStart(originalStartNode, originalStartOffset); subrange.setEnd(firstPartiallyContainedChild, getNodeLength(firstPartiallyContainedChild)); // "Let subfrag be the result of calling extractContents() on // subrange." var subfrag = myExtractContents(subrange); // "For each child of subfrag, in order, append that child to clone as // its last child." for (var i = 0; i < subfrag.childNodes.length; i++) { clone.appendChild(subfrag.childNodes[i]); } } // "For each contained child in contained children, append contained child // as the last child of frag." for (var i = 0; i < containedChildren.length; i++) { frag.appendChild(containedChildren[i]); } // "If last partially contained child is a Text or Comment node:" if (lastPartiallyContainedChild && (lastPartiallyContainedChild.nodeType == Node.TEXT_NODE || lastPartiallyContainedChild.nodeType == Node.COMMENT_NODE)) { // "Let clone be the result of calling cloneNode(false) on original // end node." var clone = originalEndNode.cloneNode(false); // "Set the data of clone to the result of calling substringData(0, // original end offset) on original end node." clone.data = originalEndNode.substringData(0, originalEndOffset); // "Append clone as the last child of frag." frag.appendChild(clone); // "Call deleteData(0, original end offset) on original end node." originalEndNode.deleteData(0, originalEndOffset); // "Otherwise, if last partially contained child is not null:" } else if (lastPartiallyContainedChild) { // "Let clone be the result of calling cloneNode(false) on last // partially contained child." var clone = lastPartiallyContainedChild.cloneNode(false); // "Append clone as the last child of frag." frag.appendChild(clone); // "Let subrange be a new Range whose start is (last partially // contained child, 0) and whose end is (original end node, original // end offset)." var subrange = ownerDoc.createRange(); subrange.setStart(lastPartiallyContainedChild, 0); subrange.setEnd(originalEndNode, originalEndOffset); // "Let subfrag be the result of calling extractContents() on // subrange." var subfrag = myExtractContents(subrange); // "For each child of subfrag, in order, append that child to clone as // its last child." for (var i = 0; i < subfrag.childNodes.length; i++) { clone.appendChild(subfrag.childNodes[i]); } } // "Set the context object's start and end to (new node, new offset)." range.setStart(newNode, newOffset); range.setEnd(newNode, newOffset); // "Return frag." return frag; } /** * insertNode() implementation, following the spec. If an exception is * supposed to be thrown, will return a string with the name (e.g., * "HIERARCHY_REQUEST_ERR") instead of a document fragment. It might also * return an arbitrary human-readable string if a condition is hit that implies * a spec bug. */ function myInsertNode(range, newNode) { // "If the context object's detached flag is set, raise an // INVALID_STATE_ERR exception and abort these steps." // // Assume that if accessing collapsed throws, it's detached. try { range.collapsed; } catch (e) { return "INVALID_STATE_ERR"; } // "If the context object's start node is a Text or Comment node and its // parent is null, raise an HIERARCHY_REQUEST_ERR exception and abort these // steps." if ((range.startContainer.nodeType == Node.TEXT_NODE || range.startContainer.nodeType == Node.COMMENT_NODE) && !range.startContainer.parentNode) { return "HIERARCHY_REQUEST_ERR"; } // "If the context object's start node is a Text node, run splitText() on // it with the context object's start offset as its argument, and let // reference node be the result." var referenceNode; if (range.startContainer.nodeType == Node.TEXT_NODE) { // We aren't testing how ranges vary under mutations, and browsers vary // in how they mutate for splitText, so let's just force the correct // way. var start = [range.startContainer, range.startOffset]; var end = [range.endContainer, range.endOffset]; referenceNode = range.startContainer.splitText(range.startOffset); if (start[0] == end[0] && end[1] > start[1]) { end[0] = referenceNode; end[1] -= start[1]; } else if (end[0] == start[0].parentNode && end[1] > indexOf(referenceNode)) { end[1]++; } range.setStart(start[0], start[1]); range.setEnd(end[0], end[1]); // "Otherwise, if the context object's start node is a Comment, let // reference node be the context object's start node." } else if (range.startContainer.nodeType == Node.COMMENT_NODE) { referenceNode = range.startContainer; // "Otherwise, let reference node be the child of the context object's // start node with index equal to the context object's start offset, or // null if there is no such child." } else { referenceNode = range.startContainer.childNodes[range.startOffset]; if (typeof referenceNode == "undefined") { referenceNode = null; } } // "If reference node is null, let parent node be the context object's // start node." var parentNode; if (!referenceNode) { parentNode = range.startContainer; // "Otherwise, let parent node be the parent of reference node." } else { parentNode = referenceNode.parentNode; } // "Call insertBefore(newNode, reference node) on parent node, re-raising // any exceptions that call raised." try { parentNode.insertBefore(newNode, referenceNode); } catch (e) { return getDomExceptionName(e); } } /** * Asserts that two nodes are equal, in the sense of isEqualNode(). If they * aren't, tries to print a relatively informative reason why not. TODO: Move * this to testharness.js? */ function assertNodesEqual(actual, expected, msg) { if (!actual.isEqualNode(expected)) { msg = "Actual and expected mismatch for " + msg + ". "; while (actual && expected) { assert_true(actual.nodeType === expected.nodeType && actual.nodeName === expected.nodeName && actual.nodeValue === expected.nodeValue && actual.childNodes.length === expected.childNodes.length, "First differing node: expected " + format_value(expected) + ", got " + format_value(actual)); actual = nextNode(actual); expected = nextNode(expected); } assert_unreached("DOMs were not equal but we couldn't figure out why"); } } /** * Given a DOMException, return the name (e.g., "HIERARCHY_REQUEST_ERR"). In * theory this should be just e.name, but in practice it's not. So I could * legitimately just return e.name, but then every engine but WebKit would fail * every test, since no one seems to care much for standardizing DOMExceptions. * Instead I mangle it to account for browser bugs, so as not to fail * insertNode() tests (for instance) for insertBefore() bugs. Of course, a * standards-compliant browser will work right in any event. * * If the exception has no string property called "name" or "message", we just * re-throw it. */ function getDomExceptionName(e) { if (typeof e.name == "string" && /^[A-Z_]+_ERR$/.test(e.name)) { // Either following the standard, or prefixing NS_ERROR_DOM (I'm // looking at you, Gecko). return e.name.replace(/^NS_ERROR_DOM_/, ""); } if (typeof e.message == "string" && /^[A-Z_]+_ERR$/.test(e.message)) { // Opera return e.message; } if (typeof e.message == "string" && /^DOM Exception:/.test(e.message)) { // IE return /[A-Z_]+_ERR/.exec(e.message)[0]; } throw e; } /** * Given an array of endpoint data [start container, start offset, end * container, end offset], returns a Range with those endpoints. */ function rangeFromEndpoints(endpoints) { // If we just use document instead of the ownerDocument of endpoints[0], // WebKit will throw on setStart/setEnd. This is a WebKit bug, but it's in // range, not selection, so we don't want to fail anything for it. var range = ownerDocument(endpoints[0]).createRange(); range.setStart(endpoints[0], endpoints[1]); range.setEnd(endpoints[2], endpoints[3]); return range; } /** * Given an array of endpoint data [start container, start offset, end * container, end offset], sets the selection to have those endpoints. Uses * addRange, so the range will be forwards. Accepts an empty array for * endpoints, in which case the selection will just be emptied. */ function setSelectionForwards(endpoints) { selection.removeAllRanges(); if (endpoints.length) { selection.addRange(rangeFromEndpoints(endpoints)); } } /** * Given an array of endpoint data [start container, start offset, end * container, end offset], sets the selection to have those endpoints, with the * direction backwards. Uses extend, so it will throw in IE. Accepts an empty * array for endpoints, in which case the selection will just be emptied. */ function setSelectionBackwards(endpoints) { selection.removeAllRanges(); if (endpoints.length) { selection.collapse(endpoints[2], endpoints[3]); selection.extend(endpoints[0], endpoints[1]); } }
{'content_hash': '5e0f559d411ecf0ab09b25c8fcd69e3c', 'timestamp': '', 'source': 'github', 'line_count': 952, 'max_line_length': 200, 'avg_line_length': 38.81827731092437, 'alnum_prop': 0.6416723041537005, 'repo_name': 'youtube/cobalt_sandbox', 'id': 'c0b622f63ccd50657a72782797262aa18051dff7', 'size': '36984', 'binary': False, 'copies': '136', 'ref': 'refs/heads/main', 'path': 'third_party/web_platform_tests/selection/common.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
/** * */ package com.velocity.models.authorize; /** * @author ranjitk * */ public class CVData { private boolean nillable; private String value; public boolean isNillable() { return nillable; } public void setNillable(boolean nillable) { this.nillable = nillable; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
{'content_hash': 'fe21a0cd7ee14bacdc424c631fcd0983', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 44, 'avg_line_length': 13.5625, 'alnum_prop': 0.6221198156682027, 'repo_name': 'nab-velocity/android-sdk', 'id': '66d7cc32d00cb51a8c5c1b337c96b024f298f626', 'size': '434', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'VelocityLibrary/src/com/velocity/models/authorize/CVData.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '888677'}]}
<?php /** * @see Zend_Validate_Abstract */ // require_once 'Zend/Validate/Abstract.php'; /** * @category Zend * @package Zend_Validate * @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_Validate_Callback extends Zend_Validate_Abstract { /** * Invalid callback */ const INVALID_CALLBACK = 'callbackInvalid'; /** * Invalid value */ const INVALID_VALUE = 'callbackValue'; /** * Validation failure message template definitions * * @var array */ protected $_messageTemplates = array( self::INVALID_VALUE => "'%value%' is not valid", self::INVALID_CALLBACK => "An exception has been raised within the callback", ); /** * Callback in a call_user_func format * * @var string|array */ protected $_callback = null; /** * Default options to set for the filter * * @var mixed */ protected $_options = array(); /** * Sets validator options * * @param string|array $callback * @param mixed $max * @param boolean $inclusive * @return void */ public function __construct($callback = null) { if (is_callable($callback)) { $this->setCallback($callback); } elseif (is_array($callback)) { if (isset($callback['callback'])) { $this->setCallback($callback['callback']); } if (isset($callback['options'])) { $this->setOptions($callback['options']); } } if (null === ($initializedCallack = $this->getCallback())) { // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('No callback registered'); } } /** * Returns the set callback * * @return mixed */ public function getCallback() { return $this->_callback; } /** * Sets the callback * * @param string|array $callback * @return Zend_Validate_Callback Provides a fluent interface */ public function setCallback($callback) { if (!is_callable($callback)) { // require_once 'Zend/Validate/Exception.php'; throw new Zend_Validate_Exception('Invalid callback given'); } $this->_callback = $callback; return $this; } /** * Returns the set options for the callback * * @return mixed */ public function getOptions() { return $this->_options; } /** * Sets options for the callback * * @param mixed $max * @return Zend_Validate_Callback Provides a fluent interface */ public function setOptions($options) { $this->_options = (array) $options; return $this; } /** * Defined by Zend_Validate_Interface * * Returns true if and only if the set callback returns * for the provided $value * * @param mixed $value * @return boolean */ public function isValid($value) { $this->_setValue($value); $options = $this->getOptions(); $callback = $this->getCallback(); $args = func_get_args(); $options = array_merge($args, $options); try { if (!call_user_func_array($callback, $options)) { $this->_error(self::INVALID_VALUE); return false; } } catch (Exception $e) { $this->_error(self::INVALID_CALLBACK); return false; } return true; } }
{'content_hash': '89b01c7bdd1aabfa80700314ddc47e2d', 'timestamp': '', 'source': 'github', 'line_count': 156, 'max_line_length': 87, 'avg_line_length': 23.955128205128204, 'alnum_prop': 0.54000535188654, 'repo_name': 'DaveThePianoDude/remotepiano', 'id': 'e2581cd33710ffc640db64a6e94a16df767840bd', 'size': '4479', 'binary': False, 'copies': '35', 'ref': 'refs/heads/master', 'path': 'analytics/libs/Zend/Validate/Callback.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '3370'}, {'name': 'ApacheConf', 'bytes': '35'}, {'name': 'Batchfile', 'bytes': '117'}, {'name': 'C', 'bytes': '31447'}, {'name': 'CSS', 'bytes': '164666'}, {'name': 'HTML', 'bytes': '394739'}, {'name': 'JavaScript', 'bytes': '2167874'}, {'name': 'PHP', 'bytes': '16669633'}, {'name': 'PowerShell', 'bytes': '3456'}, {'name': 'Python', 'bytes': '56979'}, {'name': 'Ruby', 'bytes': '356'}, {'name': 'Shell', 'bytes': '5781'}, {'name': 'Smarty', 'bytes': '395293'}]}
package ott.program.test; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import ott.capstone.MainClass; import ott.image.EdgeEffects; import ott.tictactoe.Board; import ott.tictactoe.Game; import ott.tictactoe.Player; import ott.tictactoe.image.ImageWrapper; import ott.tictactoe.image.TicTacToeBoard; public class GameTest { public static void runTest() throws Exception { // JFileChooser chooser = new JFileChooser(new File("C:/users/caleb/pictures")); // chooser.showOpenDialog(null); // File imgFile = chooser.getSelectedFile(); // if (imgFile == null) // System.exit(0); // BufferedImage img = ImageIO.read(imgFile); // BufferedImage imgLines = EdgeEffects.detectEdges(img, 100, 100); ScreenCapture cap = new ScreenCapture(); TicTacToeBoard board = null; BufferedImage imgLines = null; do { if (cap.getCurrentImage() != null) { imgLines = EdgeEffects.detectEdges(cap.getCurrentImage(), 100, 100); board = TicTacToeBoard.locateBoard(imgLines); } } while (imgLines == null || board == null); assert board != null; System.out.println("Board found"); Game g = new Game(cap, board); g.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("board")) printArray((Board) evt.getNewValue()); // else if (evt.getPropertyName().equals("winner")) // System.out.println("Game over. " + evt.getNewValue() + " won."); } private void printArray(Board value) { Object[][] boardArray = value.getBoard(); for (int i = 0; i < boardArray.length; i++) { for (int j = 0; j < boardArray[0].length; j++) { String name = boardArray[i][j] == Player.Computer ? "Comp" : boardArray[i][j] == Player.Human ? "Human" : "empty"; System.out.print(name + "\t"); } System.out.println(); } System.out.println(); } }); } private static class ImagePuller implements ImageWrapper { private BufferedImage image; public ImagePuller(BufferedImage img) { image = img; } @Override public BufferedImage getCurrentImage() { return image; } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { } } }
{'content_hash': '54823f66c10bf7cb5fb4d1062c0eb5df', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 120, 'avg_line_length': 23.63888888888889, 'alnum_prop': 0.6862514688601645, 'repo_name': 'ottboy4/tictactoe', 'id': 'a38871d209afda08e42a29c4023f03aacfcd02ad', 'size': '2553', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LibraryTests/src/ott/program/test/GameTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '106023'}]}
survey 'GD', :full_title => 'Grenada', :default_mandatory => 'false', :status => 'alpha', :description => '<p><strong>This has been generated based on a default and needs to be localised for Grenada. Please help us! Contact <a href="mailto:[email protected]">[email protected]</a></strong></p><p>This self-assessment questionnaire generates an open data certificate and badge you can publish to tell people all about this open data. We also use your answers to learn how organisations publish open data.</p><p>When you answer these questions it demonstrates your efforts to comply with relevant legislation. You should also check which other laws and policies apply to your sector.</p><p><strong>You do not need to answer all the questions to get a certificate.</strong> Just answer those you can.</p>' do translations :en => :default section_general 'General Information', :description => '', :display_header => false do q_dataTitle 'What\'s this data called?', :discussion_topic => :dataTitle, :help_text => 'People see the name of your open data in a list of similar ones so make this as unambiguous and descriptive as you can in this tiny box so they quickly identify what\'s unique about it.', :required => :required a_1 'Data Title', :string, :placeholder => 'Data Title', :required => :required q_documentationUrl 'Where is it described?', :discussion_topic => :documentationUrl, :display_on_certificate => true, :text_as_statement => 'This data is described at', :help_text => 'Give a URL for people to read about the contents of your open data and find more detail. It can be a page within a bigger catalog like data.gov.uk.' a_1 'Documentation URL', :string, :input_type => :url, :placeholder => 'Documentation URL', :requirement => ['pilot_1', 'basic_1'] label_pilot_1 'You should have a <strong>web page that offers documentation</strong> about the open data you publish so that people can understand its context, content and utility.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_1' dependency :rule => 'A and B' condition_A :q_releaseType, '!=', :a_collection condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} label_basic_1 'You must have a <strong>web page that gives documentation</strong> and access to the open data you publish so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_1' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_collection condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_publisher 'Who publishes this data?', :discussion_topic => :publisher, :display_on_certificate => true, :text_as_statement => 'This data is published by', :help_text => 'Give the name of the organisation who publishes this data. It’s probably who you work for unless you’re doing this on behalf of someone else.', :required => :required a_1 'Data Publisher', :string, :placeholder => 'Data Publisher', :required => :required q_publisherUrl 'What website is the data published on?', :discussion_topic => :publisherUrl, :display_on_certificate => true, :text_as_statement => 'The data is published on', :help_text => 'Give a URL to a website, this helps us to group data from the same organisation even if people give different names.' a_1 'Publisher URL', :string, :input_type => :url, :placeholder => 'Publisher URL' q_releaseType 'What kind of release is this?', :discussion_topic => :releaseType, :pick => :one, :required => :required a_oneoff 'a one-off release of a single dataset', :help_text => 'This is a single file and you don’t currently plan to publish similar files in the future.' a_collection 'a one-off release of a set of related datasets', :help_text => 'This is a collection of related files about the same data and you don’t currently plan to publish similar collections in the future.' a_series 'ongoing release of a series of related datasets', :help_text => 'This is a sequence of datasets with planned periodic updates in the future.' a_service 'a service or API for accessing open data', :help_text => 'This is a live web service that exposes your data to programmers through an interface they can query.' end section_legal 'Legal Information', :description => 'Rights, licensing and privacy' do label_group_2 'Rights', :help_text => 'your right to share this data with people', :customer_renderer => '/partials/fieldset' q_publisherRights 'Do you have the rights to publish this data as open data?', :discussion_topic => :gd_publisherRights, :help_text => 'If your organisation didn\'t originally create or gather this data then you might not have the right to publish it. If you’re not sure, check with the data owner because you will need their permission to publish it.', :requirement => ['basic_2'], :pick => :one, :required => :required a_yes 'yes, you have the rights to publish this data as open data', :requirement => ['standard_1'] a_no 'no, you don\'t have the rights to publish this data as open data' a_unsure 'you\'re not sure if you have the rights to publish this data as open data' a_complicated 'the rights in this data are complicated or unclear' label_standard_1 'You should have a <strong>clear legal right to publish this data</strong>.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_1' dependency :rule => 'A' condition_A :q_publisherRights, '!=', :a_yes label_basic_2 'You must have the <strong>right to publish this data</strong>.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_2' dependency :rule => 'A' condition_A :q_publisherRights, '==', :a_no q_rightsRiskAssessment 'Where do you detail the risks people might encounter if they use this data?', :discussion_topic => :gd_rightsRiskAssessment, :display_on_certificate => true, :text_as_statement => 'Risks in using this data are described at', :help_text => 'It can be risky for people to use data without a clear legal right to do so. For example, the data might be taken down in response to a legal challenge. Give a URL for a page that describes the risk of using this data.' dependency :rule => 'A' condition_A :q_publisherRights, '==', :a_complicated a_1 'Risk Documentation URL', :string, :input_type => :url, :placeholder => 'Risk Documentation URL', :requirement => ['pilot_2'] label_pilot_2 'You should document <strong>risks associated with using this data</strong>, so people can work out how they want to use it.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_2' dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_complicated condition_B :q_rightsRiskAssessment, '==', {:string_value => '', :answer_reference => '1'} q_publisherOrigin 'Was <em>all</em> this data originally created or gathered by you?', :discussion_topic => :gd_publisherOrigin, :display_on_certificate => true, :text_as_statement => 'This data was', :help_text => 'If any part of this data was sourced outside your organisation by other individuals or organisations then you need to give extra information about your right to publish it.', :pick => :one, :required => :required dependency :rule => '(A or B)' condition_A :q_publisherRights, '==', :a_yes condition_B :q_publisherRights, '==', :a_unsure a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'originally created or generated by its curator' q_thirdPartyOrigin 'Was some of this data extracted or calculated from other data?', :discussion_topic => :gd_thirdPartyOrigin, :help_text => 'An extract or smaller part of someone else\'s data still means your rights to use it might be affected. There might also be legal issues if you analysed their data to produce new results from it.', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false a_false 'no' a_true 'yes', :requirement => ['basic_3'] label_basic_3 'You indicated that this data wasn\'t originally created or gathered by you, and wasn\'t crowdsourced, so it must have been extracted or calculated from other data sources.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_3' dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_false condition_D :q_thirdPartyOrigin, '!=', :a_true q_thirdPartyOpen 'Are <em>all</em> sources of this data already published as open data?', :discussion_topic => :gd_thirdPartyOpen, :display_on_certificate => true, :text_as_statement => 'This data is created from', :help_text => 'You\'re allowed to republish someone else\'s data if it\'s already under an open data licence or if their rights have expired or been waived. If any part of this data is not like this then you\'ll need legal advice before you can publish it.', :pick => :one, :required => :required dependency :rule => 'A and B and C' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'open data sources', :requirement => ['basic_4'] label_basic_4 'You should get <strong>legal advice to make sure you have the right to publish this data</strong>.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_4' dependency :rule => 'A and B and C and D and E' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_true condition_D :q_thirdPartyOpen, '==', :a_false condition_E :q_thirdPartyOpen, '==', :a_false q_crowdsourced 'Was some of this data crowdsourced?', :discussion_topic => :gd_crowdsourced, :display_on_certificate => true, :text_as_statement => 'Some of this data is', :help_text => 'If the data includes information contributed by people outside your organisation, you need their permission to publish their contributions as open data.', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'crowdsourced', :requirement => ['basic_5'] label_basic_5 'You indicated that the data wasn\'t originally created or gathered by you, and wasn\'t extracted or calculated from other data, so it must have been crowdsourced.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_5' dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_thirdPartyOrigin, '==', :a_false condition_D :q_crowdsourced, '!=', :a_true q_crowdsourcedContent 'Did contributors to this data use their judgement?', :discussion_topic => :gd_crowdsourcedContent, :help_text => 'If people used their creativity or judgement to contribute data then they have copyright over their work. For example, writing a description or deciding whether or not to include some data in a dataset would require judgement. So contributors must transfer or waive their rights, or license the data to you before you can publish it.', :pick => :one, :required => :required dependency :rule => 'A and B and C' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true a_false 'no' a_true 'yes' q_claUrl 'Where is the Contributor Licence Agreement (CLA)?', :discussion_topic => :gd_claUrl, :display_on_certificate => true, :text_as_statement => 'The Contributor Licence Agreement is at', :help_text => 'Give a link to an agreement that shows contributors allow you to reuse their data. A CLA will either transfer contributor\'s rights to you, waive their rights, or license the data to you so you can publish it.', :help_text_more_url => 'http://en.wikipedia.org/wiki/Contributor_License_Agreement', :required => :required dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true a_1 'Contributor Licence Agreement URL', :string, :input_type => :url, :placeholder => 'Contributor Licence Agreement URL', :required => :required q_cldsRecorded 'Have all contributors agreed to the Contributor Licence Agreement (CLA)?', :discussion_topic => :gd_cldsRecorded, :help_text => 'Check all contributors agree to a CLA before you reuse or republish their contributions. You should keep a record of who gave contributions and whether or not they agree to the CLA.', :pick => :one, :required => :required dependency :rule => 'A and B and C and D' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true a_false 'no' a_true 'yes', :requirement => ['basic_6'] label_basic_6 'You must get <strong>contributors to agree to a Contributor Licence Agreement</strong> (CLA) that gives you the right to publish their work as open data.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_6' dependency :rule => 'A and B and C and D and E' condition_A :q_publisherRights, '==', :a_unsure condition_B :q_publisherOrigin, '==', :a_false condition_C :q_crowdsourced, '==', :a_true condition_D :q_crowdsourcedContent, '==', :a_true condition_E :q_cldsRecorded, '==', :a_false q_sourceDocumentationUrl 'Where do you describe sources of this data?', :discussion_topic => :gd_sourceDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The sources of this data are described at', :help_text => 'Give a URL that documents where the data was sourced from (its provenance) and the rights under which you publish the data. This helps people understand where the data comes from.' dependency :rule => 'A' condition_A :q_publisherOrigin, '==', :a_false a_1 'Data Sources Documentation URL', :string, :input_type => :url, :placeholder => 'Data Sources Documentation URL', :requirement => ['pilot_3'] label_pilot_3 'You should document <strong>where the data came from and the rights under which you publish it</strong>, so people are assured they can use parts which came from third parties.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_3' dependency :rule => 'A and B' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_sourceDocumentationMetadata 'Is documentation about the sources of this data also in machine-readable format?', :discussion_topic => :gd_sourceDocumentationMetadata, :display_on_certificate => true, :text_as_statement => 'The curator has published', :help_text => 'Information about data sources should be human-readable so people can understand it, as well as in a metadata format that computers can process. When everyone does this it helps other people find out how the same open data is being used and justify its ongoing publication.', :pick => :one dependency :rule => 'A and B' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'} a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable data about the sources of this data', :requirement => ['standard_2'] label_standard_2 'You should <strong>include machine-readable data about the sources of this data</strong>.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_2' dependency :rule => 'A and B and C' condition_A :q_publisherOrigin, '==', :a_false condition_B :q_sourceDocumentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_sourceDocumentationMetadata, '==', :a_false label_group_3 'Licensing', :help_text => 'how you give people permission to use this data', :customer_renderer => '/partials/fieldset' q_copyrightURL 'Where have you published the rights statement for this dataset?', :discussion_topic => :gd_copyrightURL, :display_on_certificate => true, :text_as_statement => 'The rights statement is at', :help_text => 'Give the URL to a page that describes the right to re-use this dataset. This should include a reference to its license, attribution requirements, and a statement about relevant copyright. A rights statement helps people understand what they can and can\'t do with the data.' a_1 'Rights Statement URL', :string, :input_type => :url, :placeholder => 'Rights Statement URL', :requirement => ['pilot_4'] label_pilot_4 'You should <strong>publish a rights statement</strong> that details copyright, licensing and how people should give attribution to the data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_4' dependency :rule => 'A' condition_A :q_copyrightURL, '==', {:string_value => '', :answer_reference => '1'} q_dataLicence 'Under which licence can people reuse this data?', :discussion_topic => :gd_dataLicence, :display_on_certificate => true, :text_as_statement => 'This data is available under', :help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it. Creative content includes the organisation and selection of items within data, but does not include facts. So people need a waiver or a licence which proves that they can use the data and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the data, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.', :pick => :one, :required => :required, :display_type => 'dropdown' a_cc_by 'Creative Commons Attribution', :text_as_statement => 'Creative Commons Attribution' a_cc_by_sa 'Creative Commons Attribution Share-Alike', :text_as_statement => 'Creative Commons Attribution Share-Alike' a_cc_zero 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_odc_by 'Open Data Commons Attribution License', :text_as_statement => 'Open Data Commons Attribution License' a_odc_odbl 'Open Data Commons Open Database License (ODbL)', :text_as_statement => 'Open Data Commons Open Database License (ODbL)' a_odc_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)', :text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)' a_na 'Not applicable', :text_as_statement => '' a_other 'Other...', :text_as_statement => '' q_dataNotApplicable 'Why doesn\'t a licence apply to this data?', :discussion_topic => :gd_dataNotApplicable, :display_on_certificate => true, :text_as_statement => 'This data is not licensed because', :pick => :one, :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_na a_norights 'there is no copyright in this data', :text_as_statement => 'there is no copyright in it', :help_text => 'Copyright only applies to data if you spent intellectual effort creating what\'s in it, for example, by writing text that\'s within the data, or deciding whether particular data is included. There\'s no copyright if the data only contains facts where no judgements were made about whether to include them or not.' a_expired 'copyright has expired', :text_as_statement => 'copyright has expired', :help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.' a_waived 'copyright has been waived', :text_as_statement => '', :help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.' q_dataWaiver 'Which waiver do you use to waive copyright in the data?', :discussion_topic => :gd_dataWaiver, :display_on_certificate => true, :text_as_statement => 'Rights in the data have been waived with', :help_text => 'You need a statement to show people copyright has been waived, so they understand that they can do whatever they like with this data. Standard waivers already exist like PDDL and CCZero but you can write your own with legal advice.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A and B' condition_A :q_dataLicence, '==', :a_na condition_B :q_dataNotApplicable, '==', :a_waived a_pddl 'Open Data Commons Public Domain Dedication and Licence (PDDL)', :text_as_statement => 'Open Data Commons Public Domain Dedication and Licence (PDDL)' a_cc0 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_other 'Other...', :text_as_statement => '' q_dataOtherWaiver 'Where is the waiver for the copyright in the data?', :discussion_topic => :gd_dataOtherWaiver, :display_on_certificate => true, :text_as_statement => 'Rights in the data have been waived with', :help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive copyright in the data.', :required => :required dependency :rule => 'A and B and C' condition_A :q_dataLicence, '==', :a_na condition_B :q_dataNotApplicable, '==', :a_waived condition_C :q_dataWaiver, '==', :a_other a_1 'Waiver URL', :string, :input_type => :url, :required => :required, :placeholder => 'Waiver URL' q_otherDataLicenceName 'What is the name of the licence?', :discussion_topic => :gd_otherDataLicenceName, :display_on_certificate => true, :text_as_statement => 'This data is available under', :help_text => 'If you use a different licence, we need the name so people can see it on your Open Data Certificate.', :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_1 'Other Licence Name', :string, :required => :required, :placeholder => 'Other Licence Name' q_otherDataLicenceURL 'Where is the licence?', :discussion_topic => :gd_otherDataLicenceURL, :display_on_certificate => true, :text_as_statement => 'This licence is at', :help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.', :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_1 'Other Licence URL', :string, :input_type => :url, :required => :required, :placeholder => 'Other Licence URL' q_otherDataLicenceOpen 'Is the licence an open licence?', :discussion_topic => :gd_otherDataLicenceOpen, :help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.', :help_text_more_url => 'http://opendefinition.org/', :pick => :one, :required => :required dependency :rule => 'A' condition_A :q_dataLicence, '==', :a_other a_false 'no' a_true 'yes', :requirement => ['basic_7'] label_basic_7 'You must <strong>publish open data under an open licence</strong> so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_7' dependency :rule => 'A and B' condition_A :q_dataLicence, '==', :a_other condition_B :q_otherDataLicenceOpen, '==', :a_false q_contentRights 'Is there any copyright in the content of this data?', :discussion_topic => :gd_contentRights, :display_on_certificate => true, :text_as_statement => 'There are', :pick => :one, :required => :required a_norights 'no, the data only contains facts and numbers', :text_as_statement => 'no rights in the content of the data', :help_text => 'There is no copyright in factual information. If the data does not contain any content that was created through intellectual effort, there are no rights in the content.' a_samerights 'yes, and the rights are all held by the same person or organisation', :text_as_statement => '', :help_text => 'Choose this option if the content in the data was all created by or transferred to the same person or organisation.' a_mixedrights 'yes, and the rights are held by different people or organisations', :text_as_statement => '', :help_text => 'In some data, the rights in different records are held by different people or organisations. Information about rights needs to be kept in the data too.' q_explicitWaiver 'Is the content of the data marked as public domain?', :discussion_topic => :gd_explicitWaiver, :display_on_certificate => true, :text_as_statement => 'The content has been', :help_text => 'Content can be marked as public domain using the <a href="http://creativecommons.org/publicdomain/">Creative Commons Public Domain Mark</a>. This helps people know that it can be freely reused.', :pick => :one dependency :rule => 'A' condition_A :q_contentRights, '==', :a_norights a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'marked as public domain', :requirement => ['standard_3'] label_standard_3 'You should <strong>mark public domain content as public domain</strong> so that people know they can reuse it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_3' dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_norights condition_B :q_explicitWaiver, '==', :a_false q_contentLicence 'Under which licence can others reuse content?', :discussion_topic => :gd_contentLicence, :display_on_certificate => true, :text_as_statement => 'The content is available under', :help_text => 'Remember that whoever spends intellectual effort creating content automatically gets rights over it but creative content does not include facts. So people need a waiver or a licence which proves that they can use the content and explains how they can do that legally. We list the most common licenses here; if there is no copyright in the content, it\'s expired, or you\'ve waived them, choose \'Not applicable\'.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A' condition_A :q_contentRights, '==', :a_samerights a_cc_by 'Creative Commons Attribution', :text_as_statement => 'Creative Commons Attribution' a_cc_by_sa 'Creative Commons Attribution Share-Alike', :text_as_statement => 'Creative Commons Attribution Share-Alike' a_cc_zero 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_na 'Not applicable', :text_as_statement => '' a_other 'Other...', :text_as_statement => '' q_contentNotApplicable 'Why doesn\'t a licence apply to the content of the data?', :discussion_topic => :gd_contentNotApplicable, :display_on_certificate => true, :text_as_statement => 'The content in this data is not licensed because', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na a_norights 'there is no copyright in the content of this data', :text_as_statement => 'there is no copyright', :help_text => 'Copyright only applies to content if you spent intellectual effort creating it, for example, by writing text that\'s within the data. There\'s no copyright if the content only contains facts.' a_expired 'copyright has expired', :text_as_statement => 'copyright has expired', :help_text => 'Copyright lasts for a fixed amount of time, based on either the number of years after the death of its creator or its publication. You should check when the content was created or published because if that was a long time ago, copyright might have expired.' a_waived 'copyright has been waived', :text_as_statement => '', :help_text => 'This means no one owns copyright and anyone can do whatever they want with this data.' q_contentWaiver 'Which waiver do you use to waive copyright?', :discussion_topic => :gd_contentWaiver, :display_on_certificate => true, :text_as_statement => 'Copyright has been waived with', :help_text => 'You need a statement to show people you\'ve done this, so they understand that they can do whatever they like with this data. Standard waivers already exist like CCZero but you can write your own with legal advice.', :pick => :one, :required => :required, :display_type => 'dropdown' dependency :rule => 'A and B and C' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na condition_C :q_contentNotApplicable, '==', :a_waived a_cc0 'Creative Commons CCZero', :text_as_statement => 'Creative Commons CCZero' a_other 'Other...', :text_as_statement => 'Other...' q_contentOtherWaiver 'Where is the waiver for the copyright?', :discussion_topic => :gd_contentOtherWaiver, :display_on_certificate => true, :text_as_statement => 'Copyright has been waived with', :help_text => 'Give a URL to your own publicly available waiver so people can check that it does waive your copyright.', :required => :required dependency :rule => 'A and B and C and D' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_na condition_C :q_contentNotApplicable, '==', :a_waived condition_D :q_contentWaiver, '==', :a_other a_1 'Waiver URL', :string, :input_type => :url, :required => :required, :placeholder => 'Waiver URL' q_otherContentLicenceName 'What\'s the name of the licence?', :discussion_topic => :gd_otherContentLicenceName, :display_on_certificate => true, :text_as_statement => 'The content is available under', :help_text => 'If you use a different licence, we need its name so people can see it on your Open Data Certificate.', :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_1 'Licence Name', :string, :required => :required, :placeholder => 'Licence Name' q_otherContentLicenceURL 'Where is the licence?', :discussion_topic => :gd_otherContentLicenceURL, :display_on_certificate => true, :text_as_statement => 'The content licence is at', :help_text => 'Give a URL to the licence, so people can see it on your Open Data Certificate and check that it\'s publicly available.', :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_1 'Licence URL', :string, :input_type => :url, :required => :required, :placeholder => 'Licence URL' q_otherContentLicenceOpen 'Is the licence an open licence?', :discussion_topic => :gd_otherContentLicenceOpen, :help_text => 'If you aren\'t sure what an open licence is then read the <a href="http://opendefinition.org/">Open Knowledge Definition</a> definition. Next, choose your licence from the <a href="http://licenses.opendefinition.org/">Open Definition Advisory Board open licence list</a>. If a licence isn\'t in their list, it\'s either not open or hasn\'t been assessed yet.', :help_text_more_url => 'http://opendefinition.org/', :pick => :one, :required => :required dependency :rule => 'A and B' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other a_false 'no' a_true 'yes', :requirement => ['basic_8'] label_basic_8 'You must <strong>publish open data under an open licence</strong> so that people can use it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_8' dependency :rule => 'A and B and C' condition_A :q_contentRights, '==', :a_samerights condition_B :q_contentLicence, '==', :a_other condition_C :q_otherContentLicenceOpen, '==', :a_false q_contentRightsURL 'Where are the rights and licensing of the content explained?', :discussion_topic => :gd_contentRightsURL, :display_on_certificate => true, :text_as_statement => 'The rights and licensing of the content are explained at', :help_text => 'Give the URL for a page where you describe how someone can find out the rights and licensing of a piece of content from the data.', :required => :required dependency :rule => 'A' condition_A :q_contentRights, '==', :a_mixedrights a_1 'Content Rights Description URL', :string, :input_type => :url, :required => :required, :placeholder => 'Content Rights Description URL' q_copyrightStatementMetadata 'Does your rights statement include machine-readable versions of', :discussion_topic => :gd_copyrightStatementMetadata, :display_on_certificate => true, :text_as_statement => 'The rights statement includes data about', :help_text => 'It\'s good practice to embed information about rights in machine-readable formats so people can automatically attribute this data back to you when they use it.', :help_text_more_url => 'https://github.com/theodi/open-data-licensing/blob/master/guides/publisher-guide.md', :pick => :any dependency :rule => 'A' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} a_dataLicense 'data licence', :text_as_statement => 'its data licence', :requirement => ['standard_4'] a_contentLicense 'content licence', :text_as_statement => 'its content licence', :requirement => ['standard_5'] a_attribution 'attribution text', :text_as_statement => 'what attribution text to use', :requirement => ['standard_6'] a_attributionURL 'attribution URL', :text_as_statement => 'what attribution link to give', :requirement => ['standard_7'] a_copyrightNotice 'copyright notice or statement', :text_as_statement => 'a copyright notice or statement', :requirement => ['exemplar_1'] a_copyrightYear 'copyright year', :text_as_statement => 'the copyright year', :requirement => ['exemplar_2'] a_copyrightHolder 'copyright holder', :text_as_statement => 'the copyright holder', :requirement => ['exemplar_3'] label_standard_4 'You should provide <strong>machine-readable data in your rights statement about the licence</strong> for this data, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_4' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_dataLicense label_standard_5 'You should provide <strong>machine-readable data in your rights statement about the licence for the content</strong> of this data, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_5' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_contentLicense label_standard_6 'You should provide <strong>machine-readable data in your rights statement about the text to use when citing the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_6' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_attribution label_standard_7 'You should provide <strong>machine-readable data in your rights statement about the URL to link to when citing this data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_7' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_attributionURL label_exemplar_1 'You should provide <strong>machine-readable data in your rights statement about the copyright statement or notice of this data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_1' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightNotice label_exemplar_2 'You should provide <strong>machine-readable data in your rights statement about the copyright year for the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_2' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightYear label_exemplar_3 'You should provide <strong>machine-readable data in your rights statement about the copyright holder for the data</strong>, so automatic tools can use it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_3' dependency :rule => 'A and B' condition_A :q_copyrightURL, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_copyrightStatementMetadata, '!=', :a_copyrightHolder label_group_4 'Privacy', :help_text => 'how you protect people\'s privacy', :customer_renderer => '/partials/fieldset' q_dataPersonal 'Can individuals be identified from this data?', :discussion_topic => :gd_dataPersonal, :display_on_certificate => true, :text_as_statement => 'This data contains', :pick => :one, :required => :pilot a_not_personal 'no, the data is not about people or their activities', :text_as_statement => 'no data about individuals', :help_text => 'Remember that individuals can still be identified even if data isn\'t directly about them. For example, road traffic flow data combined with an individual\'s commuting patterns could reveal information about that person.' a_summarised 'no, the data has been anonymised by aggregating individuals into groups, so they can\'t be distinguished from other people in the group', :text_as_statement => 'aggregated data', :help_text => 'Statistical disclosure controls can help to make sure that individuals are not identifiable within aggregate data.' a_individual 'yes, there is a risk that individuals be identified, for example by third parties with access to extra information', :text_as_statement => 'information that could identify individuals', :help_text => 'Some data is legitimately about individuals like civil service pay or public expenses for example.' q_statisticalAnonAudited 'Has your anonymisation process been independently audited?', :discussion_topic => :gd_statisticalAnonAudited, :display_on_certificate => true, :text_as_statement => 'The anonymisation process has been', :pick => :one dependency :rule => 'A' condition_A :q_dataPersonal, '==', :a_summarised a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_8'] label_standard_8 'You should <strong>have your anonymisation process audited independently</strong> to ensure it reduces the risk of individuals being reidentified.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_8' dependency :rule => 'A and B' condition_A :q_dataPersonal, '==', :a_summarised condition_B :q_statisticalAnonAudited, '==', :a_false q_appliedAnon 'Have you attempted to reduce or remove the possibility of individuals being identified?', :discussion_topic => :gd_appliedAnon, :display_on_certificate => true, :text_as_statement => 'This data about individuals has been', :help_text => 'Anonymisation reduces the risk of individuals being identified from the data you publish. The best technique to use depends on the kind of data you have.', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_dataPersonal, '==', :a_individual a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'anonymised' q_lawfulDisclosure 'Are you required or permitted by law to publish this data about individuals?', :discussion_topic => :gd_lawfulDisclosure, :display_on_certificate => true, :text_as_statement => 'By law, this data about individuals', :help_text => 'The law might require you to publish data about people, such as the names of company directors. Or you might have permission from the affected individuals to publish information about them.', :pick => :one dependency :rule => 'A and B' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'can be published', :requirement => ['pilot_5'] label_pilot_5 'You should <strong>only publish personal data without anonymisation if you are required or permitted to do so by law</strong>.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_5' dependency :rule => 'A and B and C' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_false q_lawfulDisclosureURL 'Where do you document your right to publish data about individuals?', :discussion_topic => :gd_lawfulDisclosureURL, :display_on_certificate => true, :text_as_statement => 'The right to publish this data about individuals is documented at' dependency :rule => 'A and B and C' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_true a_1 'Disclosure Rationale URL', :string, :input_type => :url, :placeholder => 'Disclosure Rationale URL', :requirement => ['standard_9'] label_standard_9 'You should <strong>document your right to publish data about individuals</strong> for people who use your data and for those affected by disclosure.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_9' dependency :rule => 'A and B and C and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_false condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_lawfulDisclosureURL, '==', {:string_value => '', :answer_reference => '1'} q_riskAssessmentExists 'Have you assessed the risks of disclosing personal data?', :discussion_topic => :gd_riskAssessmentExists, :display_on_certificate => true, :text_as_statement => 'The curator has', :help_text => 'A risk assessment measures risks to the privacy of individuals in your data as well as the use and disclosure of that information.', :pick => :one dependency :rule => 'A and (B or C)' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true a_false 'no', :text_as_statement => 'not carried out a privacy risk assessment' a_true 'yes', :text_as_statement => 'carried out a privacy risk assessment', :requirement => ['pilot_6'] label_pilot_6 'You should <strong>assess the risks of disclosing personal data</strong> if you publish data about individuals.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_6' dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_false q_riskAssessmentUrl 'Where is your risk assessment published?', :discussion_topic => :gd_riskAssessmentUrl, :display_on_certificate => true, :text_as_statement => 'The risk assessment is published at', :help_text => 'Give a URL to where people can check how you have assessed the privacy risks to individuals. This may be redacted or summarised if it contains sensitive information.' dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true a_1 'Risk Assessment URL', :string, :input_type => :url, :placeholder => 'Risk Assessment URL', :requirement => ['standard_10'] label_standard_10 'You should <strong>publish your privacy risk assessment</strong> so people can understand how you have assessed the risks of disclosing data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_10' dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '==', {:string_value => '', :answer_reference => '1'} q_riskAssessmentAudited 'Has your risk assessment been independently audited?', :discussion_topic => :gd_riskAssessmentAudited, :display_on_certificate => true, :text_as_statement => 'The risk assessment has been', :help_text => 'It\'s good practice to check your risk assessment was done correctly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.', :pick => :one dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'} a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_11'] label_standard_11 'You should <strong>have your risk assessment audited independently</strong> to ensure it has been carried out correctly.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_11' dependency :rule => 'A and (B or C) and D and E and F' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_riskAssessmentUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_F :q_riskAssessmentAudited, '==', :a_false q_anonymisationAudited 'Has your anonymisation approach been independently audited?', :discussion_topic => :gd_anonymisationAudited, :display_on_certificate => true, :text_as_statement => 'The anonymisation of the data has been', :help_text => 'It is good practice to make sure your process to remove personal identifiable data works properly. Independent audits by specialists or third-parties tend to be more rigorous and impartial.', :pick => :one dependency :rule => 'A and (B or C) and D' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'independently audited', :requirement => ['standard_12'] label_standard_12 'You should <strong>have your anonymisation process audited independently</strong> by an expert to ensure it is appropriate for your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_12' dependency :rule => 'A and (B or C) and D and E' condition_A :q_dataPersonal, '==', :a_individual condition_B :q_appliedAnon, '==', :a_true condition_C :q_lawfulDisclosure, '==', :a_true condition_D :q_riskAssessmentExists, '==', :a_true condition_E :q_anonymisationAudited, '==', :a_false end section_practical 'Practical Information', :description => 'Findability, accuracy, quality and guarantees' do label_group_6 'Findability', :help_text => 'how you help people find your data', :customer_renderer => '/partials/fieldset' q_onWebsite 'Is there a link to your data from your main website?', :discussion_topic => :onWebsite, :help_text => 'Data can be found more easily if it is linked to from your main website.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_13'] label_standard_13 'You should <strong>ensure that people can find the data from your main website</strong> so that people can find it more easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_13' dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_false repeater 'Web Page' do dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_true q_webpage 'Which page on your website links to the data?', :discussion_topic => :webpage, :display_on_certificate => true, :text_as_statement => 'The website links to the data from', :help_text => 'Give a URL on your main website that includes a link to this data.', :required => :required dependency :rule => 'A' condition_A :q_onWebsite, '==', :a_true a_1 'Web page URL', :string, :input_type => :url, :required => :required, :placeholder => 'Web page URL' end q_listed 'Is your data listed within a collection?', :discussion_topic => :listed, :help_text => 'Data is easier for people to find when it\'s in relevant data catalogs like academic, public sector or health for example, or when it turns up in relevant search results.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_14'] label_standard_14 'You should <strong>ensure that people can find your data when they search for it</strong> in locations that list data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_14' dependency :rule => 'A' condition_A :q_listed, '==', :a_false repeater 'Listing' do dependency :rule => 'A' condition_A :q_listed, '==', :a_true q_listing 'Where is it listed?', :discussion_topic => :listing, :display_on_certificate => true, :text_as_statement => 'The data appears in this collection', :help_text => 'Give a URL where this data is listed within a relevant collection. For example, data.gov.uk (if it\'s UK public sector data), hub.data.ac.uk (if it\'s UK academia data) or a URL for search engine results.', :required => :required dependency :rule => 'A' condition_A :q_listed, '==', :a_true a_1 'Listing URL', :string, :input_type => :url, :required => :required, :placeholder => 'Listing URL' end q_referenced 'Is this data referenced from your own publications?', :discussion_topic => :referenced, :help_text => 'When you reference your data within your own publications, such as reports, presentations or blog posts, you give it more context and help people find and understand it better.', :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_15'] label_standard_15 'You should <strong>reference data from your own publications</strong> so that people are aware of its availability and context.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_15' dependency :rule => 'A' condition_A :q_referenced, '==', :a_false repeater 'Reference' do dependency :rule => 'A' condition_A :q_referenced, '==', :a_true q_reference 'Where is your data referenced?', :discussion_topic => :reference, :display_on_certificate => true, :text_as_statement => 'This data is referenced from', :help_text => 'Give a URL to a document that cites or references this data.', :required => :required dependency :rule => 'A' condition_A :q_referenced, '==', :a_true a_1 'Reference URL', :string, :input_type => :url, :required => :required, :placeholder => 'Reference URL' end label_group_7 'Accuracy', :help_text => 'how you keep your data up-to-date', :customer_renderer => '/partials/fieldset' q_serviceType 'Does the data behind your API change?', :discussion_topic => :serviceType, :display_on_certificate => true, :text_as_statement => 'The data behind the API', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_static 'no, the API gives access to unchanging data', :text_as_statement => 'will not change', :help_text => 'Some APIs just make accessing an unchanging dataset easier, particularly when there\'s lots of it.' a_changing 'yes, the API gives access to changing data', :text_as_statement => 'will change', :help_text => 'Some APIs give instant access to more up-to-date and ever-changing data' q_timeSensitive 'Will your data go out of date?', :discussion_topic => :timeSensitive, :display_on_certificate => true, :text_as_statement => 'The accuracy or relevance of this data will', :pick => :one dependency :rule => '(A or B or (C and D))' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static a_true 'yes, this data will go out of date', :text_as_statement => 'go out of date', :help_text => 'For example, a dataset of bus stop locations will go out of date over time as some are moved or new ones created.' a_timestamped 'yes, this data will go out of date over time but it’s time stamped', :text_as_statement => 'go out of date but it is timestamped', :help_text => 'For example, population statistics usually include a fixed timestamp to indicate when the statistics were relevant.', :requirement => ['pilot_7'] a_false 'no, this data does not contain any time-sensitive information', :text_as_statement => 'not go out of date', :help_text => 'For example, the results of an experiment will not go out of date because the data accurately reports observed outcomes.', :requirement => ['standard_16'] label_pilot_7 'You should <strong>put timestamps in your data when you release it</strong> so people know the period it relates to and when it will expire.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_7' dependency :rule => '(A or B or (C and D)) and (E and F)' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static condition_E :q_timeSensitive, '!=', :a_timestamped condition_F :q_timeSensitive, '!=', :a_false label_standard_16 'You should <strong>publish updates to time-sensitive data</strong> so that it does not go stale.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_16' dependency :rule => '(A or B or (C and D)) and (E)' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_releaseType, '==', :a_collection condition_C :q_releaseType, '==', :a_service condition_D :q_serviceType, '==', :a_static condition_E :q_timeSensitive, '!=', :a_false q_frequentChanges 'Does this data change at least daily?', :discussion_topic => :frequentChanges, :display_on_certificate => true, :text_as_statement => 'This data changes', :help_text => 'Tell people if the underlying data changes on most days. When data changes frequently it also goes out of date quickly, so people need to know if you also update it frequently and quickly too.', :pick => :one, :required => :pilot dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'at least daily' q_seriesType 'What type of dataset series is this?', :discussion_topic => :seriesType, :display_on_certificate => true, :text_as_statement => 'This data is a series of', :pick => :one, :required => :exemplar dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true a_dumps 'regular copies of a complete database', :text_as_statement => 'copies of a database', :help_text => 'Choose if you publish new and updated copies of your full database regularly. When you create database dumps, it\'s useful for people to have access to a feed of the changes so they can keep their copies up to date.' a_aggregate 'regular aggregates of changing data', :text_as_statement => 'aggregates of changing data', :help_text => 'Choose if you create new datasets regularly. You might do this if the underlying data can\'t be released as open data or if you only publish data that\'s new since the last publication.' q_changeFeed 'Is a feed of changes available?', :discussion_topic => :changeFeed, :display_on_certificate => true, :text_as_statement => 'A feed of changes to this data', :help_text => 'Tell people if you provide a stream of changes that affect this data, like new entries or amendments to existing entries. Feeds might be in RSS, Atom or custom formats.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_seriesType, '==', :a_dumps a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'is available', :requirement => ['exemplar_4'] label_exemplar_4 'You should <strong>provide a feed of changes to your data</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_4' dependency :rule => 'A and B and C and D' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_seriesType, '==', :a_dumps condition_D :q_changeFeed, '==', :a_false q_frequentSeriesPublication 'How often do you create a new release?', :discussion_topic => :frequentSeriesPublication, :display_on_certificate => true, :text_as_statement => 'New releases of this data are made', :help_text => 'This determines how out of date this data becomes before people can get an update.', :pick => :one dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true a_rarely 'less than once a month', :text_as_statement => 'less than once a month' a_monthly 'at least every month', :text_as_statement => 'at least every month', :requirement => ['pilot_8'] a_weekly 'at least every week', :text_as_statement => 'at least every week', :requirement => ['standard_17'] a_daily 'at least every day', :text_as_statement => 'at least every day', :requirement => ['exemplar_5'] label_pilot_8 'You should <strong>create a new dataset release every month</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_8' dependency :rule => 'A and B and (C and D and E)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_monthly condition_D :q_frequentSeriesPublication, '!=', :a_weekly condition_E :q_frequentSeriesPublication, '!=', :a_daily label_standard_17 'You should <strong>create a new dataset release every week</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_17' dependency :rule => 'A and B and (C and D)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_weekly condition_D :q_frequentSeriesPublication, '!=', :a_daily label_exemplar_5 'You should <strong>create a new dataset release every day</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_5' dependency :rule => 'A and B and (C)' condition_A :q_releaseType, '==', :a_series condition_B :q_frequentChanges, '==', :a_true condition_C :q_frequentSeriesPublication, '!=', :a_daily q_seriesPublicationDelay 'How long is the delay between when you create a dataset and when you publish it?', :discussion_topic => :seriesPublicationDelay, :display_on_certificate => true, :text_as_statement => 'The lag between creation and publication of this data is', :pick => :one dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_extreme 'longer than the gap between releases', :text_as_statement => 'longer than the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes more than a day for it to be published.' a_reasonable 'about the same as the gap between releases', :text_as_statement => 'about the same as the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes about a day for it to be published.', :requirement => ['pilot_9'] a_good 'less than half the gap between releases', :text_as_statement => 'less than half the gap between releases', :help_text => 'For example, if you create a new version of the dataset every day, choose this if it takes less than twelve hours for it to be published.', :requirement => ['standard_18'] a_minimal 'there is minimal or no delay', :text_as_statement => 'minimal', :help_text => 'Choose this if you publish within a few seconds or a few minutes.', :requirement => ['exemplar_6'] label_pilot_9 'You should <strong>have a reasonable delay between when you create and publish a dataset</strong> that is less than the gap between releases so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_9' dependency :rule => 'A and (B and C and D)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_reasonable condition_C :q_seriesPublicationDelay, '!=', :a_good condition_D :q_seriesPublicationDelay, '!=', :a_minimal label_standard_18 'You should <strong>have a short delay between when you create and publish a dataset</strong> that is less than half the gap between releases so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_18' dependency :rule => 'A and (B and C)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_good condition_C :q_seriesPublicationDelay, '!=', :a_minimal label_exemplar_6 'You should <strong>have minimal or no delay between when you create and publish a dataset</strong> so people keep their copies up-to-date and accurate.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_6' dependency :rule => 'A and (B)' condition_A :q_releaseType, '==', :a_series condition_B :q_seriesPublicationDelay, '!=', :a_minimal q_provideDumps 'Do you also publish dumps of this dataset?', :discussion_topic => :provideDumps, :display_on_certificate => true, :text_as_statement => 'The curator publishes', :help_text => 'A dump is an extract of the whole dataset into a file that people can download. This lets people do analysis that\'s different to analysis with API access.', :pick => :one dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'dumps of the data', :requirement => ['standard_19'] label_standard_19 'You should <strong>let people download your entire dataset</strong> so that they can do more complete and accurate analysis with all the data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_19' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_false q_dumpFrequency 'How frequently do you create a new database dump?', :discussion_topic => :dumpFrequency, :display_on_certificate => true, :text_as_statement => 'Database dumps are created', :help_text => 'Faster access to more frequent extracts of the whole dataset means people can get started quicker with the most up-to-date data.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true a_rarely 'less frequently than once a month', :text_as_statement => 'less frequently than once a month' a_monthly 'at least every month', :text_as_statement => 'at least every month', :requirement => ['pilot_10'] a_weekly 'within a week of any change', :text_as_statement => 'within a week of any change', :requirement => ['standard_20'] a_daily 'within a day of any change', :text_as_statement => 'within a day of any change', :requirement => ['exemplar_7'] label_pilot_10 'You should <strong>create a new database dump every month</strong> so that people have the latest data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_10' dependency :rule => 'A and B and C and (D and E and F)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_monthly condition_E :q_dumpFrequency, '!=', :a_weekly condition_F :q_dumpFrequency, '!=', :a_daily label_standard_20 'You should <strong>create a new database dump within a week of any change</strong> so that people have less time to wait for the latest data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_20' dependency :rule => 'A and B and C and (D and E)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_weekly condition_E :q_dumpFrequency, '!=', :a_daily label_exemplar_7 'You should <strong>create a new database dump within a day of any change</strong> so that people find it easier to get the latest data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_7' dependency :rule => 'A and B and C and (D)' condition_A :q_releaseType, '==', :a_service condition_B :q_serviceType, '==', :a_changing condition_C :q_provideDumps, '==', :a_true condition_D :q_dumpFrequency, '!=', :a_daily q_corrected 'Will your data be corrected if it has errors?', :discussion_topic => :corrected, :display_on_certificate => true, :text_as_statement => 'Any errors in this data are', :help_text => 'It\'s good practice to fix errors in your data especially if you use it yourself. When you make corrections, people need to be told about them.', :pick => :one dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_timeSensitive, '!=', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'corrected', :requirement => ['standard_21'] label_standard_21 'You should <strong>correct data when people report errors</strong> so everyone benefits from improvements in accuracy.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_21' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_timeSensitive, '!=', :a_true condition_C :q_corrected, '==', :a_false label_group_8 'Quality', :help_text => 'how much people can rely on your data', :customer_renderer => '/partials/fieldset' q_qualityUrl 'Where do you document issues with the quality of this data?', :discussion_topic => :qualityUrl, :display_on_certificate => true, :text_as_statement => 'Data quality is documented at', :help_text => 'Give a URL where people can find out about the quality of your data. People accept that errors are inevitable, from equipment malfunctions or mistakes that happen in system migrations. You should be open about quality so people can judge how much to rely on this data.' a_1 'Data Quality Documentation URL', :string, :input_type => :url, :placeholder => 'Data Quality Documentation URL', :requirement => ['standard_22'] label_standard_22 'You should <strong>document any known issues with your data quality</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_22' dependency :rule => 'A' condition_A :q_qualityUrl, '==', {:string_value => '', :answer_reference => '1'} q_qualityControlUrl 'Where is your quality control process described?', :discussion_topic => :qualityControlUrl, :display_on_certificate => true, :text_as_statement => 'Quality control processes are described at', :help_text => 'Give a URL for people to learn about ongoing checks on your data, either automatic or manual. This reassures them that you take quality seriously and encourages improvements that benefit everyone.' a_1 'Quality Control Process Description URL', :string, :input_type => :url, :placeholder => 'Quality Control Process Description URL', :requirement => ['exemplar_8'] label_exemplar_8 'You should <strong>document your quality control process</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_8' dependency :rule => 'A' condition_A :q_qualityControlUrl, '==', {:string_value => '', :answer_reference => '1'} label_group_9 'Guarantees', :help_text => 'how much people can depend on your data’s availability', :customer_renderer => '/partials/fieldset' q_backups 'Do you take offsite backups?', :discussion_topic => :backups, :display_on_certificate => true, :text_as_statement => 'The data is', :help_text => 'Taking a regular offsite backup helps ensure that the data won\'t be lost in the case of accident.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'backed up offsite', :requirement => ['standard_23'] label_standard_23 'You should <strong>take a result offsite backup</strong> so that the data won\'t be lost if an accident happens.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_23' dependency :rule => 'A' condition_A :q_backups, '==', :a_false q_slaUrl 'Where do you describe any guarantees about service availability?', :discussion_topic => :slaUrl, :display_on_certificate => true, :text_as_statement => 'Service availability is described at', :help_text => 'Give a URL for a page that describes what guarantees you have about your service being available for people to use. For example you might have a guaranteed uptime of 99.5%, or you might provide no guarantees.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Service Availability Documentation URL', :string, :input_type => :url, :placeholder => 'Service Availability Documentation URL', :requirement => ['standard_24'] label_standard_24 'You should <strong>describe what guarantees you have around service availability</strong> so that people know how much they can rely on it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_24' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_slaUrl, '==', {:string_value => '', :answer_reference => '1'} q_statusUrl 'Where do you give information about the current status of the service?', :discussion_topic => :statusUrl, :display_on_certificate => true, :text_as_statement => 'Service status is given at', :help_text => 'Give a URL for a page that tells people about the current status of your service, including any faults you are aware of.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Service Status URL', :string, :input_type => :url, :placeholder => 'Service Status URL', :requirement => ['exemplar_9'] label_exemplar_9 'You should <strong>have a service status page</strong> that tells people about the current status of your service.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_9' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_statusUrl, '==', {:string_value => '', :answer_reference => '1'} q_onGoingAvailability 'How long will this data be available for?', :discussion_topic => :onGoingAvailability, :display_on_certificate => true, :text_as_statement => 'The data is available', :pick => :one a_experimental 'it might disappear at any time', :text_as_statement => 'experimentally and might disappear at any time' a_short 'it\'s available experimentally but should be around for another year or so', :text_as_statement => 'experimentally for another year or so', :requirement => ['pilot_11'] a_medium 'it\'s in your medium-term plans so should be around for a couple of years', :text_as_statement => 'for at least a couple of years', :requirement => ['standard_25'] a_long 'it\'s part of your day-to-day operations so will stay published for a long time', :text_as_statement => 'for a long time', :requirement => ['exemplar_10'] label_pilot_11 'You should <strong>guarantee that your data will be available in this form for at least a year</strong> so that people can decide how much to rely on your data.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_11' dependency :rule => 'A and B and C' condition_A :q_onGoingAvailability, '!=', :a_short condition_B :q_onGoingAvailability, '!=', :a_medium condition_C :q_onGoingAvailability, '!=', :a_long label_standard_25 'You should <strong>guarantee that your data will be available in this form in the medium-term</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_25' dependency :rule => 'A and B' condition_A :q_onGoingAvailability, '!=', :a_medium condition_B :q_onGoingAvailability, '!=', :a_long label_exemplar_10 'You should <strong>guarantee that your data will be available in this form in the long-term</strong> so that people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_10' dependency :rule => 'A' condition_A :q_onGoingAvailability, '!=', :a_long end section_technical 'Technical Information', :description => 'Locations, formats and trust' do label_group_11 'Locations', :help_text => 'how people can access your data', :customer_renderer => '/partials/fieldset' q_datasetUrl 'Where is your dataset?', :discussion_topic => :datasetUrl, :display_on_certificate => true, :text_as_statement => 'This data is published at', :help_text => 'Give a URL to the dataset itself. Open data should be linked to directly on the web so people can easily find and reuse it.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_oneoff a_1 'Dataset URL', :string, :input_type => :url, :placeholder => 'Dataset URL', :requirement => ['basic_9', 'pilot_12'] label_basic_9 'You must <strong>provide either a URL to your data or a URL to documentation</strong> about it so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_9' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'} label_pilot_12 'You should <strong>have a URL that is a direct link to the data itself</strong> so that people can access it easily.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_12' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_oneoff condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_datasetUrl, '==', {:string_value => '', :answer_reference => '1'} q_versionManagement 'How do you publish a series of the same dataset?', :discussion_topic => :versionManagement, :requirement => ['basic_10'], :pick => :any dependency :rule => 'A' condition_A :q_releaseType, '==', :a_series a_current 'as a single URL that\'s regularly updated', :help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current dataset.', :requirement => ['standard_26'] a_template 'as consistent URLs for each release', :help_text => 'Choose this if your dataset URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['pilot_13'] a_list 'as a list of releases', :help_text => 'Choose this if you have a list of datasets on a web page or a feed (like Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['standard_27'] label_standard_26 'You should <strong>have a single persistent URL to download the current version of your data</strong> so that people can access it easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_26' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_current label_pilot_13 'You should <strong>use a consistent pattern for different release URLs</strong> so that people can download each one automatically.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_13' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_template label_standard_27 'You should <strong>have a document or feed with a list of available releases</strong> so people can create scripts to download them all.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_27' dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '!=', :a_list label_basic_10 'You must <strong>provide access to releases of your data through a URL</strong> that gives the current version, a discoverable series of URLs or through a documentation page so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_10' dependency :rule => 'A and (B and C and D and E)' condition_A :q_releaseType, '==', :a_series condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_versionManagement, '!=', :a_current condition_D :q_versionManagement, '!=', :a_template condition_E :q_versionManagement, '!=', :a_list q_currentDatasetUrl 'Where is your current dataset?', :discussion_topic => :currentDatasetUrl, :display_on_certificate => true, :text_as_statement => 'The current dataset is available at', :help_text => 'Give a single URL to the most recent version of the dataset. The content at this URL should change each time a new version is released.', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_current a_1 'Current Dataset URL', :string, :input_type => :url, :placeholder => 'Current Dataset URL', :required => :required q_versionsTemplateUrl 'What format do dataset release URLs follow?', :discussion_topic => :versionsTemplateUrl, :display_on_certificate => true, :text_as_statement => 'Releases follow this consistent URL pattern', :help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_template a_1 'Version Template URL', :string, :input_type => :text, :placeholder => 'Version Template URL', :required => :required q_versionsUrl 'Where is your list of dataset releases?', :discussion_topic => :versionsUrl, :display_on_certificate => true, :text_as_statement => 'Releases of this data are listed at', :help_text => 'Give a URL to a page or feed with a machine-readable list of datasets. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_series condition_B :q_versionManagement, '==', :a_list a_1 'Version List URL', :string, :input_type => :url, :placeholder => 'Version List URL', :required => :required q_endpointUrl 'Where is the endpoint for your API?', :discussion_topic => :endpointUrl, :display_on_certificate => true, :text_as_statement => 'The API service endpoint is', :help_text => 'Give a URL that\'s a starting point for people\'s scripts to access your API. This should be a service description document that helps the script to work out which services exist.' dependency :rule => 'A' condition_A :q_releaseType, '==', :a_service a_1 'Endpoint URL', :string, :input_type => :url, :placeholder => 'Endpoint URL', :requirement => ['basic_11', 'standard_28'] label_basic_11 'You must <strong>provide either an API endpoint URL or a URL to its documentation</strong> so that people can find it.', :custom_renderer => '/partials/requirement_basic', :requirement => 'basic_11' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_documentationUrl, '==', {:string_value => '', :answer_reference => '1'} condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'} label_standard_28 'You should <strong>have a service description document or single entry point for your API</strong> so that people can access it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_28' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_C :q_endpointUrl, '==', {:string_value => '', :answer_reference => '1'} q_dumpManagement 'How do you publish database dumps?', :discussion_topic => :dumpManagement, :pick => :any dependency :rule => 'A and B' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true a_current 'as a single URL that\'s regularly updated', :help_text => 'Choose this if there\'s one URL for people to download the most recent version of the current database dump.', :requirement => ['standard_29'] a_template 'as consistent URLs for each release', :help_text => 'Choose this if your database dump URLs follow a regular pattern that includes the date of publication, for example, a URL that starts \'2013-04\'. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['exemplar_11'] a_list 'as a list of releases', :help_text => 'Choose this if you have a list of database dumps on a web page or a feed (such as Atom or RSS) with links to each individual release and its details. This helps people to understand how often you release data, and to write scripts that fetch new ones each time they\'re released.', :requirement => ['exemplar_12'] label_standard_29 'You should <strong>have a single persistent URL to download the current dump of your database</strong> so that people can find it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_29' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_current label_exemplar_11 'You should <strong>use a consistent pattern for database dump URLs</strong> so that people can can download each one automatically.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_11' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_template label_exemplar_12 'You should <strong>have a document or feed with a list of available database dumps</strong> so people can create scripts to download them all', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_12' dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '!=', :a_list q_currentDumpUrl 'Where is the current database dump?', :discussion_topic => :currentDumpUrl, :display_on_certificate => true, :text_as_statement => 'The most recent database dump is always available at', :help_text => 'Give a URL to the most recent dump of the database. The content at this URL should change each time a new database dump is created.', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_current a_1 'Current Dump URL', :string, :input_type => :url, :placeholder => 'Current Dump URL', :required => :required q_dumpsTemplateUrl 'What format do database dump URLs follow?', :discussion_topic => :dumpsTemplateUrl, :display_on_certificate => true, :text_as_statement => 'Database dumps follow the consistent URL pattern', :help_text => 'This is the structure of URLs when you publish different releases. Use `{variable}` to indicate parts of the template URL that change, for example, `http://example.com/data/monthly/mydata-{YY}{MM}.csv`', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_template a_1 'Dump Template URL', :string, :input_type => :text, :placeholder => 'Dump Template URL', :required => :required q_dumpsUrl 'Where is your list of available database dumps?', :discussion_topic => :dumpsUrl, :display_on_certificate => true, :text_as_statement => 'A list of database dumps is at', :help_text => 'Give a URL to a page or feed with a machine-readable list of database dumps. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A and B and C' condition_A :q_releaseType, '==', :a_service condition_B :q_provideDumps, '==', :a_true condition_C :q_dumpManagement, '==', :a_list a_1 'Dump List URL', :string, :input_type => :url, :placeholder => 'Dump List URL', :required => :required q_changeFeedUrl 'Where is your feed of changes?', :discussion_topic => :changeFeedUrl, :display_on_certificate => true, :text_as_statement => 'A feed of changes to this data is at', :help_text => 'Give a URL to a page or feed that provides a machine-readable list of the previous versions of the database dumps. Use the URL of the first page which should link to the rest of the pages.', :required => :required dependency :rule => 'A' condition_A :q_changeFeed, '==', :a_true a_1 'Change Feed URL', :string, :input_type => :url, :placeholder => 'Change Feed URL', :required => :required label_group_12 'Formats', :help_text => 'how people can work with your data', :customer_renderer => '/partials/fieldset' q_machineReadable 'Is this data machine-readable?', :discussion_topic => :machineReadable, :display_on_certificate => true, :text_as_statement => 'This data is', :help_text => 'People prefer data formats which are easily processed by a computer, for speed and accuracy. For example, a scanned photocopy of a spreadsheet would not be machine-readable but a CSV file would be.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable', :requirement => ['pilot_14'] label_pilot_14 'You should <strong>provide your data in a machine-readable format</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_14' dependency :rule => 'A' condition_A :q_machineReadable, '==', :a_false q_openStandard 'Is this data in a standard open format?', :discussion_topic => :openStandard, :display_on_certificate => true, :text_as_statement => 'The format of this data is', :help_text => 'Open standards are created through a fair, transparent and collaborative process. Anyone can implement them and there’s lots of support so it’s easier for you to share data with more people. For example, XML, CSV and JSON are open standards.', :help_text_more_url => 'https://www.gov.uk/government/uploads/system/uploads/attachment_data/file/183962/Open-Standards-Principles-FINAL.pdf', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'a standard open format', :requirement => ['standard_30'] label_standard_30 'You should <strong>provide your data in an open standard format</strong> so that people can use widely available tools to process it more easily.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_30' dependency :rule => 'A' condition_A :q_openStandard, '==', :a_false q_dataType 'What kind of data do you publish?', :discussion_topic => :dataType, :pick => :any a_documents 'human-readable documents', :help_text => 'Choose this if your data is meant for human consumption. For example; policy documents, white papers, reports and meeting minutes. These usually have some structure to them but are mostly text.' a_statistical 'statistical data like counts, averages and percentages', :help_text => 'Choose this if your data is statistical or numeric data like counts, averages or percentages. Like census results, traffic flow information or crime statistics for example.' a_geographic 'geographic information, such as points and boundaries', :help_text => 'Choose this if your data can be plotted on a map as points, boundaries or lines.' a_structured 'other kinds of structured data', :help_text => 'Choose this if your data is structured in other ways. Like event details, railway timetables, contact information or anything that can be interpreted as data, and analysed and presented in multiple ways.' q_documentFormat 'Do your human-readable documents include formats that', :discussion_topic => :documentFormat, :display_on_certificate => true, :text_as_statement => 'Documents are published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_documents a_semantic 'describe semantic structure like HTML, Docbook or Markdown', :text_as_statement => 'in a semantic format', :help_text => 'These formats label structures like chapters, headings and tables that make it easy to automatically create summaries like tables of contents and glossaries. They also make it easy to apply different styles to the document so its appearance changes.', :requirement => ['standard_31'] a_format 'describe information on formatting like OOXML or PDF', :text_as_statement => 'in a display format', :help_text => 'These formats emphasise appearance like fonts, colours and positioning of different elements within the page. These are good for human consumption, but aren\'t as easy for people to process automatically and change style.', :requirement => ['pilot_15'] a_unsuitable 'aren\'t meant for documents like Excel, JSON or CSV', :text_as_statement => 'in a format unsuitable for documents', :help_text => 'These formats better suit tabular or structured data.' label_standard_31 'You should <strong>publish documents in a format that exposes semantic structure</strong> so that people can display them in different styles.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_31' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_documents condition_B :q_documentFormat, '!=', :a_semantic label_pilot_15 'You should <strong>publish documents in a format designed specifically for them</strong> so that they\'re easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_15' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_documents condition_B :q_documentFormat, '!=', :a_semantic condition_C :q_documentFormat, '!=', :a_format q_statisticalFormat 'Does your statistical data include formats that', :discussion_topic => :statisticalFormat, :display_on_certificate => true, :text_as_statement => 'Statistical data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_statistical a_statistical 'expose the structure of statistical hypercube data like <a href="http://sdmx.org/">SDMX</a> or <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a>', :text_as_statement => 'in a statistical data format', :help_text => 'Individual observations in hypercubes relate to a particular measure and a set of dimensions. Each observation may also be related to annotations that give extra context. Formats like <a href="http://sdmx.org/">SDMX</a> and <a href="http://www.w3.org/TR/vocab-data-cube/">Data Cube</a> are designed to express this underlying structure.', :requirement => ['exemplar_13'] a_tabular 'treat statistical data as a table like CSV', :text_as_statement => 'in a tabular data format', :help_text => 'These formats arrange statistical data within a table of rows and columns. This lacks extra context about the underlying hypercube but is easy to process.', :requirement => ['standard_32'] a_format 'focus on the format of tabular data like Excel', :text_as_statement => 'in a presentation format', :help_text => 'Spreadsheets use formatting like italic or bold text, and indentation within fields to describe its appearance and underlying structure. This styling helps people to understand the meaning of your data but makes it less suitable for computers to process.', :requirement => ['pilot_16'] a_unsuitable 'aren\'t meant for statistical or tabular data like Word or PDF', :text_as_statement => 'in a format unsuitable for statistical data', :help_text => 'These formats don\'t suit statistical data because they obscure the underlying structure of the data.' label_exemplar_13 'You should <strong>publish statistical data in a format that exposes dimensions and measures</strong> so that it\'s easy to analyse.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_13' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical label_standard_32 'You should <strong>publish tabular data in a format that exposes tables of data</strong> so that it\'s easy to analyse.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_32' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical condition_C :q_statisticalFormat, '!=', :a_tabular label_pilot_16 'You should <strong>publish tabular data in a format designed for that purpose</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_16' dependency :rule => 'A and (B and C and D)' condition_A :q_dataType, '==', :a_statistical condition_B :q_statisticalFormat, '!=', :a_statistical condition_C :q_statisticalFormat, '!=', :a_tabular condition_D :q_statisticalFormat, '!=', :a_format q_geographicFormat 'Does your geographic data include formats that', :discussion_topic => :geographicFormat, :display_on_certificate => true, :text_as_statement => 'Geographic data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_geographic a_specific 'are designed for geographic data like <a href="http://www.opengeospatial.org/standards/kml/">KML</a> or <a href="http://www.geojson.org/">GeoJSON</a>', :text_as_statement => 'in a geographic data format', :help_text => 'These formats describe points, lines and boundaries, and expose structures in the data which make it easier to process automatically.', :requirement => ['exemplar_14'] a_generic 'keeps data structured like JSON, XML or CSV', :text_as_statement => 'in a generic data format', :help_text => 'Any format that stores normal structured data can express geographic data too, particularly if it only holds data about points.', :requirement => ['pilot_17'] a_unsuitable 'aren\'t designed for geographic data like Word or PDF', :text_as_statement => 'in a format unsuitable for geographic data', :help_text => 'These formats don\'t suit geographic data because they obscure the underlying structure of the data.' label_exemplar_14 'You should <strong>publish geographic data in a format designed that purpose</strong> so that people can use widely available tools to process it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_14' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_geographic condition_B :q_geographicFormat, '!=', :a_specific label_pilot_17 'You should <strong>publish geographic data as structured data</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_17' dependency :rule => 'A and (B and C)' condition_A :q_dataType, '==', :a_geographic condition_B :q_geographicFormat, '!=', :a_specific condition_C :q_geographicFormat, '!=', :a_generic q_structuredFormat 'Does your structured data include formats that', :discussion_topic => :structuredFormat, :display_on_certificate => true, :text_as_statement => 'Structured data is published', :pick => :one dependency :rule => 'A' condition_A :q_dataType, '==', :a_structured a_suitable 'are designed for structured data like JSON, XML, Turtle or CSV', :text_as_statement => 'in a structured data format', :help_text => 'These formats organise data into a basic structure of things which have values for a known set of properties. These formats are easy for computers to process automatically.', :requirement => ['pilot_18'] a_unsuitable 'aren\'t designed for structured data like Word or PDF', :text_as_statement => 'in a format unsuitable for structured data', :help_text => 'These formats don\'t suit this kind of data because they obscure its underlying structure.' label_pilot_18 'You should <strong>publish structured data in a format designed that purpose</strong> so that it\'s easy to process.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_18' dependency :rule => 'A and (B)' condition_A :q_dataType, '==', :a_structured condition_B :q_structuredFormat, '!=', :a_suitable q_identifiers 'Does your data use persistent identifiers?', :discussion_topic => :identifiers, :display_on_certificate => true, :text_as_statement => 'The data includes', :help_text => 'Data is usually about real things like schools or roads or uses a coding scheme. If data from different sources use the same persistent and unique identifier to refer to the same things, people can combine sources easily to create more useful data. Identifiers might be GUIDs, DOIs or URLs.', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'persistent identifiers', :requirement => ['standard_33'] label_standard_33 'You should <strong>use identifiers for things in your data</strong> so that they can be easily related with other data about those things.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_33' dependency :rule => 'A' condition_A :q_identifiers, '==', :a_false q_resolvingIds 'Can the identifiers in your data be used to find extra information?', :discussion_topic => :resolvingIds, :display_on_certificate => true, :text_as_statement => 'The persistent identifiers', :pick => :one dependency :rule => 'A' condition_A :q_identifiers, '==', :a_true a_false 'no, the identifiers can\'t be used to find extra information', :text_as_statement => '' a_service 'yes, there is a service that people can use to resolve the identifiers', :text_as_statement => 'resolve using a service', :help_text => 'Online services can be used to give people information about identifiers such as GUIDs or DOIs which can\'t be directly accessed in the way that URLs are.', :requirement => ['standard_34'] a_resolvable 'yes, the identifiers are URLs that resolve to give information', :text_as_statement => 'resolve because they are URLs', :help_text => 'URLs are useful for both people and computers. People can put a URL into their browser and read more information, like <a href="http://opencorporates.com/companies/gb/08030289">companies</a> and <a href="http://data.ordnancesurvey.co.uk/doc/postcodeunit/EC2A4JE">postcodes</a>. Computers can also process this extra information using scripts to access the underlying data.', :requirement => ['exemplar_15'] label_standard_34 'You should <strong>provide a service to resolve the identifiers you use</strong> so that people can find extra information about them.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_34' dependency :rule => 'A and (B and C)' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '!=', :a_service condition_C :q_resolvingIds, '!=', :a_resolvable label_exemplar_15 'You should <strong>link to a web page of information about each of the things in your data</strong> so that people can easily find and share that information.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_15' dependency :rule => 'A and (B)' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '!=', :a_resolvable q_resolutionServiceURL 'Where is the service that is used to resolve the identifiers?', :discussion_topic => :resolutionServiceURL, :display_on_certificate => true, :text_as_statement => 'The identifier resolution service is at', :help_text => 'The resolution service should take an identifier as a query parameter and give back some information about the thing it identifies.' dependency :rule => 'A and B' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '==', :a_service a_1 'Identifier Resolution Service URL', :string, :input_type => :url, :placeholder => 'Identifier Resolution Service URL', :requirement => ['standard_35'] label_standard_35 'You should <strong>have a URL through which identifiers can be resolved</strong> so that more information about them can be found by a computer.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_35' dependency :rule => 'A and B and C' condition_A :q_identifiers, '==', :a_true condition_B :q_resolvingIds, '==', :a_service condition_C :q_resolutionServiceURL, '==', {:string_value => '', :answer_reference => '1'} q_existingExternalUrls 'Is there third-party information about things in your data on the web?', :discussion_topic => :existingExternalUrls, :help_text => 'Sometimes other people outside your control provide URLs to the things your data is about. For example, your data might have postcodes in it that link to the Ordnance Survey website.', :pick => :one, :required => :exemplar dependency :rule => 'A' condition_A :q_identifiers, '==', :a_true a_false 'no' a_true 'yes' q_reliableExternalUrls 'Is that third-party information reliable?', :discussion_topic => :reliableExternalUrls, :help_text => 'If a third-party provides public URLs about things in your data, they probably take steps to ensure data quality and reliability. This is a measure of how much you trust their processes to do that. Look for their open data certificate or similar hallmarks to help make your decision.', :pick => :one, :required => :exemplar dependency :rule => 'A and B' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true a_false 'no' a_true 'yes' q_externalUrls 'Does your data use those third-party URLs?', :discussion_topic => :externalUrls, :display_on_certificate => true, :text_as_statement => 'Third-party URLs are', :help_text => 'You should use third-party URLs that resolve to information about the things your data describes. This reduces duplication and helps people combine data from different sources to make it more useful.', :pick => :one dependency :rule => 'A and B and C' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true condition_C :q_reliableExternalUrls, '==', :a_true a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'referenced in this data', :requirement => ['exemplar_16'] label_exemplar_16 'You should <strong>use URLs to third-party information in your data</strong> so that it\'s easy to combine with other data that uses those URLs.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_16' dependency :rule => 'A and B and C and D' condition_A :q_identifiers, '==', :a_true condition_B :q_existingExternalUrls, '==', :a_true condition_C :q_reliableExternalUrls, '==', :a_true condition_D :q_externalUrls, '==', :a_false label_group_13 'Trust', :help_text => 'how much trust people can put in your data', :customer_renderer => '/partials/fieldset' q_provenance 'Do you provide machine-readable provenance for your data?', :discussion_topic => :provenance, :display_on_certificate => true, :text_as_statement => 'The provenance of this data is', :help_text => 'This about the origins of how your data was created and processed before it was published. It builds trust in the data you publish because people can trace back how it has been handled.', :help_text_more_url => 'http://www.w3.org/TR/prov-primer/', :pick => :one a_false 'no', :text_as_statement => '' a_true 'yes', :text_as_statement => 'machine-readable', :requirement => ['exemplar_17'] label_exemplar_17 'You should <strong>provide a machine-readable provenance trail</strong> about your data so that people can trace how it was processed.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_17' dependency :rule => 'A' condition_A :q_provenance, '==', :a_false q_digitalCertificate 'Where do you describe how people can verify that data they receive comes from you?', :discussion_topic => :digitalCertificate, :display_on_certificate => true, :text_as_statement => 'This data can be verified using', :help_text => 'If you deliver important data to people they should be able to check that what they receive is the same as what you published. For example, you can digitally sign the data you publish, so people can tell if it has been tampered with.' a_1 'Verification Process URL', :string, :input_type => :url, :placeholder => 'Verification Process URL', :requirement => ['exemplar_18'] label_exemplar_18 'You should <strong>describe how people can check that the data they receive is the same as what you published</strong> so that they can trust it.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_18' dependency :rule => 'A' condition_A :q_digitalCertificate, '==', {:string_value => '', :answer_reference => '1'} end section_social 'Social Information', :description => 'Documentation, support and services' do label_group_15 'Documentation', :help_text => 'how you help people understand the context and content of your data', :customer_renderer => '/partials/fieldset' q_documentationMetadata 'Does your data documentation include machine-readable data for:', :discussion_topic => :documentationMetadata, :display_on_certificate => true, :text_as_statement => 'The documentation includes machine-readable data for', :pick => :any dependency :rule => 'A' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} a_title 'title', :text_as_statement => 'title', :requirement => ['standard_36'] a_description 'description', :text_as_statement => 'description', :requirement => ['standard_37'] a_issued 'release date', :text_as_statement => 'release date', :requirement => ['standard_38'] a_modified 'modification date', :text_as_statement => 'modification date', :requirement => ['standard_39'] a_accrualPeriodicity 'frequency of releases', :text_as_statement => 'release frequency', :requirement => ['standard_40'] a_identifier 'identifier', :text_as_statement => 'identifier', :requirement => ['standard_41'] a_landingPage 'landing page', :text_as_statement => 'landing page', :requirement => ['standard_42'] a_language 'language', :text_as_statement => 'language', :requirement => ['standard_43'] a_publisher 'publisher', :text_as_statement => 'publisher', :requirement => ['standard_44'] a_spatial 'spatial/geographical coverage', :text_as_statement => 'spatial/geographical coverage', :requirement => ['standard_45'] a_temporal 'temporal coverage', :text_as_statement => 'temporal coverage', :requirement => ['standard_46'] a_theme 'theme(s)', :text_as_statement => 'theme(s)', :requirement => ['standard_47'] a_keyword 'keyword(s) or tag(s)', :text_as_statement => 'keyword(s) or tag(s)', :requirement => ['standard_48'] a_distribution 'distribution(s)', :text_as_statement => 'distribution(s)' label_standard_36 'You should <strong>include a machine-readable data title in your documentation</strong> so that people know how to refer to it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_36' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_title label_standard_37 'You should <strong>include a machine-readable data description in your documentation</strong> so that people know what it contains.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_37' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_description label_standard_38 'You should <strong>include a machine-readable data release date in your documentation</strong> so that people know how timely it is.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_38' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_issued label_standard_39 'You should <strong>include a machine-readable last modification date in your documentation</strong> so that people know they have the latest data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_39' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_modified label_standard_40 'You should <strong>provide machine-readable metadata about how frequently you release new versions of your data</strong> so people know how often you update it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_40' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_accrualPeriodicity label_standard_41 'You should <strong>include a canonical URL for the data in your machine-readable documentation</strong> so that people know how to access it consistently.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_41' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_identifier label_standard_42 'You should <strong>include a canonical URL to the machine-readable documentation itself</strong> so that people know how to access to it consistently.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_42' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_landingPage label_standard_43 'You should <strong>include the data language in your machine-readable documentation</strong> so that people who search for it will know whether they can understand it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_43' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_language label_standard_44 'You should <strong>indicate the data publisher in your machine-readable documentation</strong> so people can decide how much to trust your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_44' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_publisher label_standard_45 'You should <strong>include the geographic coverage in your machine-readable documentation</strong> so that people understand where your data applies to.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_45' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_spatial label_standard_46 'You should <strong>include the time period in your machine-readable documentation</strong> so that people understand when your data applies to.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_46' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_temporal label_standard_47 'You should <strong>include the subject in your machine-readable documentation</strong> so that people know roughly what your data is about.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_47' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_theme label_standard_48 'You should <strong>include machine-readable keywords or tags in your documentation</strong> to help people search within the data effectively.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_48' dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '!=', :a_keyword q_distributionMetadata 'Does your documentation include machine-readable metadata for each distribution on:', :discussion_topic => :distributionMetadata, :display_on_certificate => true, :text_as_statement => 'The documentation about each distribution includes machine-readable data for', :pick => :any dependency :rule => 'A and B' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution a_title 'title', :text_as_statement => 'title', :requirement => ['standard_49'] a_description 'description', :text_as_statement => 'description', :requirement => ['standard_50'] a_issued 'release date', :text_as_statement => 'release date', :requirement => ['standard_51'] a_modified 'modification date', :text_as_statement => 'modification date', :requirement => ['standard_52'] a_rights 'rights statement', :text_as_statement => 'rights statement', :requirement => ['standard_53'] a_accessURL 'URL to access the data', :text_as_statement => 'a URL to access the data', :help_text => 'This metadata should be used when your data isn\'t available as a download, like an API for example.' a_downloadURL 'URL to download the dataset', :text_as_statement => 'a URL to download the dataset' a_byteSize 'size in bytes', :text_as_statement => 'size in bytes' a_mediaType 'type of download media', :text_as_statement => 'type of download media' label_standard_49 'You should <strong>include machine-readable titles within your documentation</strong> so people know how to refer to each data distribution.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_49' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_title label_standard_50 'You should <strong>include machine-readable descriptions within your documentation</strong> so people know what each data distribution contains.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_50' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_description label_standard_51 'You should <strong>include machine-readable release dates within your documentation</strong> so people know how current each distribution is.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_51' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_issued label_standard_52 'You should <strong>include machine-readable last modification dates within your documentation</strong> so people know whether their copy of a data distribution is up-to-date.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_52' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_modified label_standard_53 'You should <strong>include a machine-readable link to the applicable rights statement</strong> so people can find out what they can do with a data distribution.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_53' dependency :rule => 'A and B and C' condition_A :q_documentationUrl, '!=', {:string_value => '', :answer_reference => '1'} condition_B :q_documentationMetadata, '==', :a_distribution condition_C :q_distributionMetadata, '!=', :a_rights q_technicalDocumentation 'Where is the technical documentation for the data?', :discussion_topic => :technicalDocumentation, :display_on_certificate => true, :text_as_statement => 'The technical documentation for the data is at' a_1 'Technical Documentation URL', :string, :input_type => :url, :placeholder => 'Technical Documentation URL', :requirement => ['pilot_19'] label_pilot_19 'You should <strong>provide technical documentation for the data</strong> so that people understand how to use it.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_19' dependency :rule => 'A' condition_A :q_technicalDocumentation, '==', {:string_value => '', :answer_reference => '1'} q_vocabulary 'Do the data formats use vocabularies or schemas?', :discussion_topic => :vocabulary, :help_text => 'Formats like CSV, JSON, XML or Turtle use custom vocabularies or schemas which say what columns or properties the data contains.', :pick => :one, :required => :standard a_false 'no' a_true 'yes' q_schemaDocumentationUrl 'Where is documentation about your data vocabularies?', :discussion_topic => :schemaDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The vocabularies used by this data are documented at' dependency :rule => 'A' condition_A :q_vocabulary, '==', :a_true a_1 'Schema Documentation URL', :string, :input_type => :url, :placeholder => 'Schema Documentation URL', :requirement => ['standard_54'] label_standard_54 'You should <strong>document any vocabulary you use within your data</strong> so that people know how to interpret it.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_54' dependency :rule => 'A and B' condition_A :q_vocabulary, '==', :a_true condition_B :q_schemaDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} q_codelists 'Are there any codes used in this data?', :discussion_topic => :codelists, :help_text => 'If your data uses codes to refer to things like geographical areas, spending categories or diseases for example, these need to be explained to people.', :pick => :one, :required => :standard a_false 'no' a_true 'yes' q_codelistDocumentationUrl 'Where are any codes in your data documented?', :discussion_topic => :codelistDocumentationUrl, :display_on_certificate => true, :text_as_statement => 'The codes in this data are documented at' dependency :rule => 'A' condition_A :q_codelists, '==', :a_true a_1 'Codelist Documentation URL', :string, :input_type => :url, :placeholder => 'Codelist Documentation URL', :requirement => ['standard_55'] label_standard_55 'You should <strong>document the codes used within your data</strong> so that people know how to interpret them.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_55' dependency :rule => 'A and B' condition_A :q_codelists, '==', :a_true condition_B :q_codelistDocumentationUrl, '==', {:string_value => '', :answer_reference => '1'} label_group_16 'Support', :help_text => 'how you communicate with people who use your data', :customer_renderer => '/partials/fieldset' q_contactUrl 'Where can people find out how to contact someone with questions about this data?', :discussion_topic => :contactUrl, :display_on_certificate => true, :text_as_statement => 'Find out how to contact someone about this data at', :help_text => 'Give a URL for a page that describes how people can contact someone if they have questions about the data.' a_1 'Contact Documentation', :string, :input_type => :url, :placeholder => 'Contact Documentation', :requirement => ['pilot_20'] label_pilot_20 'You should <strong>provide contact information for people to send questions</strong> about your data to.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_20' dependency :rule => 'A' condition_A :q_contactUrl, '==', {:string_value => '', :answer_reference => '1'} q_improvementsContact 'Where can people find out how to improve the way your data is published?', :discussion_topic => :improvementsContact, :display_on_certificate => true, :text_as_statement => 'Find out how to suggest improvements to publication at' a_1 'Improvement Suggestions URL', :string, :input_type => :url, :placeholder => 'Improvement Suggestions URL', :requirement => ['pilot_21'] label_pilot_21 'You should <strong>provide instructions about how suggest improvements</strong> to the way you publish data so you can discover what people need.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_21' dependency :rule => 'A' condition_A :q_improvementsContact, '==', {:string_value => '', :answer_reference => '1'} q_dataProtectionUrl 'Where can people find out how to contact someone with questions about privacy?', :discussion_topic => :dataProtectionUrl, :display_on_certificate => true, :text_as_statement => 'Find out where to send questions about privacy at' a_1 'Confidentiality Contact Documentation', :string, :input_type => :url, :placeholder => 'Confidentiality Contact Documentation', :requirement => ['pilot_22'] label_pilot_22 'You should <strong>provide contact information for people to send questions about privacy</strong> and disclosure of personal details to.', :custom_renderer => '/partials/requirement_pilot', :requirement => 'pilot_22' dependency :rule => 'A' condition_A :q_dataProtectionUrl, '==', {:string_value => '', :answer_reference => '1'} q_socialMedia 'Do you use social media to connect with people who use your data?', :discussion_topic => :socialMedia, :pick => :one a_false 'no' a_true 'yes', :requirement => ['standard_56'] label_standard_56 'You should <strong>use social media to reach people who use your data</strong> and discover how your data is being used', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_56' dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_false repeater 'Account' do dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_true q_account 'Which social media accounts can people reach you on?', :discussion_topic => :account, :display_on_certificate => true, :text_as_statement => 'Contact the curator through these social media accounts', :help_text => 'Give URLs to your social media accounts, like your Twitter or Facebook profile page.', :required => :required dependency :rule => 'A' condition_A :q_socialMedia, '==', :a_true a_1 'Social Media URL', :string, :input_type => :url, :required => :required, :placeholder => 'Social Media URL' end q_forum 'Where should people discuss this dataset?', :discussion_topic => :forum, :display_on_certificate => true, :text_as_statement => 'Discuss this data at', :help_text => 'Give a URL to your forum or mailing list where people can talk about your data.' a_1 'Forum or Mailing List URL', :string, :input_type => :url, :placeholder => 'Forum or Mailing List URL', :requirement => ['standard_57'] label_standard_57 'You should <strong>tell people where they can discuss your data</strong> and support one another.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_57' dependency :rule => 'A' condition_A :q_forum, '==', {:string_value => '', :answer_reference => '1'} q_correctionReporting 'Where can people find out how to request corrections to your data?', :discussion_topic => :correctionReporting, :display_on_certificate => true, :text_as_statement => 'Find out how to request data corrections at', :help_text => 'Give a URL where people can report errors they spot in your data.' dependency :rule => 'A' condition_A :q_corrected, '==', :a_true a_1 'Correction Instructions URL', :string, :input_type => :url, :placeholder => 'Correction Instructions URL', :requirement => ['standard_58'] label_standard_58 'You should <strong>provide instructions about how people can report errors</strong> in your data.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_58' dependency :rule => 'A and B' condition_A :q_corrected, '==', :a_true condition_B :q_correctionReporting, '==', {:string_value => '', :answer_reference => '1'} q_correctionDiscovery 'Where can people find out how to get notifications of corrections to your data?', :discussion_topic => :correctionDiscovery, :display_on_certificate => true, :text_as_statement => 'Find out how to get notifications about data corrections at', :help_text => 'Give a URL where you describe how notifications about corrections are shared with people.' dependency :rule => 'A' condition_A :q_corrected, '==', :a_true a_1 'Correction Notification URL', :string, :input_type => :url, :placeholder => 'Correction Notification URL', :requirement => ['standard_59'] label_standard_59 'You should <strong>provide a mailing list or feed with updates</strong> that people can use to keep their copies of your data up-to-date.', :custom_renderer => '/partials/requirement_standard', :requirement => 'standard_59' dependency :rule => 'A and B' condition_A :q_corrected, '==', :a_true condition_B :q_correctionDiscovery, '==', {:string_value => '', :answer_reference => '1'} q_engagementTeam 'Do you have anyone who actively builds a community around this data?', :discussion_topic => :engagementTeam, :help_text => 'A community engagement team will engage through social media, blogging, and arrange hackdays or competitions to encourage people to use the data.', :help_text_more_url => 'http://theodi.org/guide/engaging-reusers', :pick => :one a_false 'no' a_true 'yes', :requirement => ['exemplar_19'] label_exemplar_19 'You should <strong>build a community of people around your data</strong> to encourage wider use of your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_19' dependency :rule => 'A' condition_A :q_engagementTeam, '==', :a_false q_engagementTeamUrl 'Where is their home page?', :discussion_topic => :engagementTeamUrl, :display_on_certificate => true, :text_as_statement => 'Community engagement is done by', :required => :required dependency :rule => 'A' condition_A :q_engagementTeam, '==', :a_true a_1 'Community Engagement Team Home Page URL', :string, :input_type => :url, :placeholder => 'Community Engagement Team Home Page URL', :required => :required label_group_17 'Services', :help_text => 'how you give people access to tools they need to work with your data', :customer_renderer => '/partials/fieldset' q_libraries 'Where do you list tools to work with your data?', :discussion_topic => :libraries, :display_on_certificate => true, :text_as_statement => 'Tools to help use this data are listed at', :help_text => 'Give a URL that lists the tools you know or recommend people can use when they work with your data.' a_1 'Tool URL', :string, :input_type => :url, :placeholder => 'Tool URL', :requirement => ['exemplar_20'] label_exemplar_20 'You should <strong>provide a list of software libraries and other readily-available tools</strong> so that people can quickly get to work with your data.', :custom_renderer => '/partials/requirement_exemplar', :requirement => 'exemplar_20' dependency :rule => 'A' condition_A :q_libraries, '==', {:string_value => '', :answer_reference => '1'} end end
{'content_hash': '0493d45aebdf1addf24cb6ff15a5d333', 'timestamp': '', 'source': 'github', 'line_count': 2577, 'max_line_length': 727, 'avg_line_length': 54.474970896391156, 'alnum_prop': 0.6664672108959838, 'repo_name': 'zoul/open-data-certificate', 'id': '17edfe5896a6589490b6f69a4d0d0a79f69f44d2', 'size': '140400', 'binary': False, 'copies': '5', 'ref': 'refs/heads/staging', 'path': 'surveys/generated/surveyor/odc_questionnaire.GD.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '127178'}, {'name': 'Cucumber', 'bytes': '15259'}, {'name': 'HTML', 'bytes': '199882'}, {'name': 'JavaScript', 'bytes': '49604'}, {'name': 'Ruby', 'bytes': '35781920'}, {'name': 'Shell', 'bytes': '392'}, {'name': 'XSLT', 'bytes': '82457'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Authentication.Extensions { public static class AzureAdServiceCollectionExtensions { public static IServiceCollection AddAzureAdWebApiAuthentication(this IServiceCollection services) { services.AddWebApiAuthentication(); services.AddSingleton<IConfigureOptions<AzureAdOptions>, AzureAdOptionsSetup>(); services.AddSingleton<IConfigureOptions<JwtBearerOptions>, AzureAdJwtBearerOptionsSetup>(); return services; } } }
{'content_hash': '1cca66875c9d7ff3cbf6431cb898b500', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 105, 'avg_line_length': 36.57142857142857, 'alnum_prop': 0.7682291666666666, 'repo_name': 'lambdakris/templating', 'id': '3fc7ad5cf631ee63a22dcda3731676b1d7865536', 'size': '770', 'binary': False, 'copies': '2', 'ref': 'refs/heads/rel/vs2017/post-rtw', 'path': 'template_feed/Microsoft.DotNet.Web.ProjectTemplates.2.0/content/WebApi-CSharp/Extensions/AzureAd/AzureAdServiceCollectionExtensions.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '4392'}, {'name': 'C#', 'bytes': '1926502'}, {'name': 'CSS', 'bytes': '5966'}, {'name': 'F#', 'bytes': '8374'}, {'name': 'Groovy', 'bytes': '2409'}, {'name': 'JavaScript', 'bytes': '204'}, {'name': 'PowerShell', 'bytes': '3788'}, {'name': 'Shell', 'bytes': '8853'}, {'name': 'Smalltalk', 'bytes': '131'}, {'name': 'Visual Basic', 'bytes': '1160'}]}
import { StyleRules } from '@material-ui/styles/withStyles'; /** * This function doesn't really "do anything" at runtime, it's just the identity * function. Its only purpose is to defeat TypeScript's type widening when providing * style rules to `withStyles` which are a function of the `Theme`. * @param styles a set of style mappings * @returns the same styles that were passed in */ // For TypeScript v3.5 Props has to extend {} instead of object // See https://github.com/mui-org/material-ui/issues/15942 // and https://github.com/microsoft/TypeScript/issues/31735 export default function createStyles<ClassKey extends string, Props extends {}>( styles: StyleRules<Props, ClassKey>, ): StyleRules<Props, ClassKey>;
{'content_hash': '75e6806d4bbfe9704ebbd32a01c72d8e', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 84, 'avg_line_length': 48.53333333333333, 'alnum_prop': 0.75, 'repo_name': 'mbrookes/material-ui', 'id': '958d5ecbcc949d8524d198efcab7abd4a7e7ece2', 'size': '728', 'binary': False, 'copies': '2', 'ref': 'refs/heads/next', 'path': 'packages/material-ui-styles/src/createStyles/createStyles.d.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '2092'}, {'name': 'JavaScript', 'bytes': '16089809'}, {'name': 'TypeScript', 'bytes': '1788737'}]}
package com.orionplatform.math.graph.tasks.query; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import com.orionplatform.core.abstraction.Orion; import com.orionplatform.data.data_structures.list.OrionList; import com.orionplatform.math.graph.Graph; import com.orionplatform.math.graph.GraphRules; import com.orionplatform.math.graph.edge.Edge; import com.orionplatform.math.number.ANumber; public class GetNumberOfMultipleEdgesInGraphTask extends Orion { public static synchronized ANumber run(Graph graph) { GraphRules.isValid(graph); OrionList<Edge> edges = graph.getEdges().getAsOrionList(); AtomicLong numberOfMultipleEdges = new AtomicLong(); Set<Integer> iIndices = new HashSet<Integer>(); edges.forAllPairsCountedOnce((i, j) -> { if(edges.get(i).equals(edges.get(j))) { iIndices.add(i); numberOfMultipleEdges.incrementAndGet(); } }); return ANumber.of(numberOfMultipleEdges.get() + iIndices.size()); } }
{'content_hash': '0a71d41c61a7c679b9e43cd79bc68982', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 73, 'avg_line_length': 34.09090909090909, 'alnum_prop': 0.6862222222222222, 'repo_name': 'orioncode/orionplatform', 'id': 'a1e59fcdd43ef1ff76fdf6c9a55db65fdbbabe12', 'size': '1125', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'orion_math/orion_math_core/src/main/java/com/orionplatform/math/graph/tasks/query/GetNumberOfMultipleEdgesInGraphTask.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '622824'}, {'name': 'HTML', 'bytes': '3108485'}, {'name': 'Java', 'bytes': '8358343'}, {'name': 'JavaScript', 'bytes': '211562'}]}
package rapture.dsl.idef; import java.util.Map; import rapture.common.model.DocumentMetadata; public abstract class FieldLocator { public abstract Object value(String key, Map<String, Object> mappedContent, DocumentMetadata meta); }
{'content_hash': '26499485749593f68188616e4fdbcd2d', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 76, 'avg_line_length': 18.692307692307693, 'alnum_prop': 0.7860082304526749, 'repo_name': 'jonathan-major/Rapture', 'id': 'ca22d127b07fb1bcce09dec859a2b299f243728c', 'size': '1407', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'Libs/RaptureAPI/src/main/java/rapture/dsl/idef/FieldLocator.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '165'}, {'name': 'C++', 'bytes': '352203'}, {'name': 'CMake', 'bytes': '964'}, {'name': 'CSS', 'bytes': '27828'}, {'name': 'GAP', 'bytes': '230464'}, {'name': 'HTML', 'bytes': '122944'}, {'name': 'Java', 'bytes': '8077044'}, {'name': 'JavaScript', 'bytes': '149972'}, {'name': 'PLpgSQL', 'bytes': '1760'}, {'name': 'Python', 'bytes': '50042'}, {'name': 'Ruby', 'bytes': '1150'}, {'name': 'Shell', 'bytes': '14237'}, {'name': 'Smalltalk', 'bytes': '30643'}, {'name': 'TeX', 'bytes': '724064'}, {'name': 'Thrift', 'bytes': '149'}, {'name': 'VimL', 'bytes': '900'}]}
<HTML><HEAD> <TITLE>Review for Yume (1990)</TITLE> <LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css"> </HEAD> <BODY BGCOLOR="#FFFFFF" TEXT="#000000"> <H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0100998">Yume (1990)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Pedro+Sena">Pedro Sena</A></H3><HR WIDTH="40%" SIZE="4"> <PRE>FILM TITLE: DREAMS DIRECTOR: AKIRA KUROSAWA COUNTRY: JAPAN 1990 CAST: Martin Scorcese as Van Gogh SUPER FEATURES: Kurosawa's Short Stories, if you will.</PRE> <PRE> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!</PRE> <P>Akira Kurosawa, has been accused of being a rat, because he will not do a film for the greedy Japanese studios who want him to make them millions of yen. Instead, Akira goes around the world to find funding for whatever work he has finished writing, and gets it done with very little fuss, and with a lot of international good will, for his trully beautiful and colorful work.</P> <P>And while this type of work may not be indicative of the trend of Japanese money making films, it is a love offering for the world of film enthusiasts which Akira Kurosawa has gained over fifty years of film making. His work is staunchly personal, and totally against the 'public' faire, which Hollywood prefers, as does Tokyo. In the process, he makes use of his best friends around the world, who always produce his work, and make sure it gets released, despite the man being blacklisted in his own country as a renegade director. At least he knows he will be remenbered and revered as an artist, something that the money makers never will get. What they get in money, Akira will get in years of being remenbered as a stupendous film maker, who deserves it.</P> <P>DREAMS is a personal set of short stories on film. And while they are unusual, they still stand out. The three best stories ( gosh I don't even remenber if there were more in the film ) were the first one which dealt with a child who sees the spirit of the peach trees ( the deva is the accurate description ) tell him that he should keep these trees alive forever, instead of cutting them down for a development, which seems to be the obvious outcome as Japan grows and prospers into the industrial world. The hint is that all the beauty of these visions will disappear. An odd piece, in that things tend to appear and disappear in a dance ritual that is dazzling, and hipnotic at the same time.</P> <P>The second one has to do with another young man, who is ready for war, in his military outfit. They all march into a tunnel, and on the other end of the tunnel, only the young man shows up, the rest presumably all dead. It is a beautiful metaphor about how war treats people. The young man is scared, and immediatelly lonesome, and having to deal with his own perceptions and emotions.</P> <P>Another story is about Van Gogh, and how he worked, played by the director Martin Scorcese ( a special friend to Akira ), a tribute not so much to the artist, but to Akira himself, who must consider himself a Van Gogh, in an age where they do not appreciate the real art of the spirit, much less the country.</P> <P>As usual, the film is beautifully filmed, with startling color, and so alive as to make us quite a part of it. In the field of flowers, where the painter works, the camera rarely lifts itself above the level of the flowers who touch the camera lovingly. A startling commentary about what art is, rather than what a movie is. While the actual 'copy' is not what Van Gogh does, the camera does the same, by providing us with the real inspiration, rather than money.</P> <P>A MUST SEE FILM FOR AKIRA KUROSAWA FANS. BEAUTIFUL CINEMATOGRAPHY. PERSONAL FILM, IN THAT IT HAS ELEMENTS WHICH COULD BE THOUGHT OF AS FANCIFUL FLIGHTS OF THE IMAGINATION.</P> <PRE>Copyright (c) Pedro Sena 1994 Internet Movie Critics Association Pedro Sena, Reviewer</PRE> <HR><P CLASS=flush><SMALL>The review above was posted to the <A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR> The Internet Movie Database accepts no responsibility for the contents of the review and has no editorial control. Unless stated otherwise, the copyright belongs to the author.<BR> Please direct comments/criticisms of the review to relevant newsgroups.<BR> Broken URLs inthe reviews are the responsibility of the author.<BR> The formatting of the review is likely to differ from the original due to ASCII to HTML conversion. </SMALL></P> <P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P> </P></BODY></HTML>
{'content_hash': 'b64aa83a3853084c58afd9d1f9995a4f', 'timestamp': '', 'source': 'github', 'line_count': 81, 'max_line_length': 186, 'avg_line_length': 60.08641975308642, 'alnum_prop': 0.7318676802958701, 'repo_name': 'xianjunzhengbackup/code', 'id': '47c7bb75a38b4a1731d5714ae24c6eb5b07c90d9', 'size': '4867', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'data science/machine_learning_for_the_web/chapter_4/movie/13531.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'BitBake', 'bytes': '113'}, {'name': 'BlitzBasic', 'bytes': '256'}, {'name': 'CSS', 'bytes': '49827'}, {'name': 'HTML', 'bytes': '157006325'}, {'name': 'JavaScript', 'bytes': '14029'}, {'name': 'Jupyter Notebook', 'bytes': '4875399'}, {'name': 'Mako', 'bytes': '2060'}, {'name': 'Perl', 'bytes': '716'}, {'name': 'Python', 'bytes': '874414'}, {'name': 'R', 'bytes': '454'}, {'name': 'Shell', 'bytes': '3984'}]}
package com.sina.weibo.sdk.demo.openapi; import android.app.Activity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.sina.weibo.sdk.auth.Oauth2AccessToken; import com.sina.weibo.sdk.demo.AccessTokenKeeper; import com.sina.weibo.sdk.demo.Constants; import com.sina.weibo.sdk.demo.R; import com.sina.weibo.sdk.exception.WeiboException; import com.sina.weibo.sdk.net.RequestListener; import com.sina.weibo.sdk.openapi.CommentsAPI; import com.sina.weibo.sdk.openapi.models.CommentList; import com.sina.weibo.sdk.utils.LogUtil; /** * 该类主要演示了如何使用微博 OpenAPI 来获取以下内容: * <li>获取某条微博的评论列表 * <li>... * * @author SINA * @since 2013-11-24 */ public class WBCommentAPIActivity extends Activity implements OnItemClickListener { private static final String TAG = "WBCommentAPIActivity"; /** UI 元素:ListView */ private ListView mFuncListView; /** 功能列表 */ private String[] mFuncList; /** 当前 Token 信息 */ private Oauth2AccessToken mAccessToken; /** 微博评论接口 */ private CommentsAPI mCommentsAPI; /** * @see {@link Activity#onCreate} */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_open_api_base_layout); // 获取功能列表 mFuncList = getResources().getStringArray(R.array.comment_func_list); // 初始化功能列表 ListView mFuncListView = (ListView)findViewById(R.id.api_func_list); mFuncListView.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, mFuncList)); mFuncListView.setOnItemClickListener(this); // 获取当前已保存过的 Token mAccessToken = AccessTokenKeeper.readAccessToken(this); // 获取微博评论信息接口 mCommentsAPI = new CommentsAPI(this, Constants.APP_KEY, mAccessToken); } /** * @see {@link AdapterView.OnItemClickListener#onItemClick} */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view instanceof TextView) { if (mAccessToken != null && mAccessToken.isSessionValid()) { switch (position) { case 0: mCommentsAPI.toME(0L, 0L, 10, 1, CommentsAPI.AUTHOR_FILTER_ALL, CommentsAPI.SRC_FILTER_ALL, mListener); break; case 1: mCommentsAPI.byME(0L, 0L, 10, 1, CommentsAPI.SRC_FILTER_ALL, mListener); break; case 2: mCommentsAPI.timeline(0L, 0L, 10, 1, true, mListener); break; default: break; } } else { Toast.makeText(WBCommentAPIActivity.this, R.string.weibosdk_demo_access_token_is_empty, Toast.LENGTH_LONG).show(); } } } /** * 微博 OpenAPI 回调接口。 */ private RequestListener mListener = new RequestListener() { @Override public void onComplete(String response) { LogUtil.i(TAG, response); if (!TextUtils.isEmpty(response)) { CommentList comments = CommentList.parse(response); if(comments != null && comments.total_number > 0){ Toast.makeText(WBCommentAPIActivity.this, "获取评论成功, 条数: " + comments.commentList.size(), Toast.LENGTH_LONG).show(); } } } @Override public void onWeiboException(WeiboException e) { LogUtil.e(TAG, e.getMessage()); } }; }
{'content_hash': '59c4f1320449cf079076a773a6956a01', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 120, 'avg_line_length': 33.107438016528924, 'alnum_prop': 0.6045931103344983, 'repo_name': '8tory/weibo-android-sdk', 'id': '46bc705fb4e95a4e07bffc9f6996d30ed7499af8', 'size': '4825', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'weibo-android-sdk-demo/src/main/java/com/sina/weibo/sdk/demo/openapi/WBCommentAPIActivity.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'IDL', 'bytes': '44'}, {'name': 'Java', 'bytes': '463011'}]}
{% extends "layout.html" %} {% block page_title %} Support {% endblock %} {% block content %} <main id="content" role="main"> {% include "../includes/phase_banner_beta.html" %} <form action="work-address" method="#" class="form"> <div class="grid-row"> <div class="column-two-thirds"> <a class="link-back" href="work-income">Back</a> {% include "../includes/error-summary.html" %} <header> <h1 class="form-title heading-large"> <!-- <span class="heading-secondary">Section 5 of 23</span> --> Do you get help at work from a professional support worker? </h1> </header> <fieldset class="inline form-group"> <p>A professional support worker is someone whose job is to give you ongoing support to help you stay in work.<p> <label class="block-label" data-target="yes-support" for="radio--3"> <input id="radio--3" type="radio" name="part" value="Yes"> Yes </label> <label class="block-label" for="radio--4"> <input id="radio--4" type="radio" name="part" value="No"> No </label> </fieldset> <div class="panel panel-border-narrow js-hidden" id="yes-support"> <div class="form-group"> <label class="form-label-bold" for="worker-name">Support worker name</label> <input type="text" class="form-control" id="worker-name"> </div> <div class="form-group"> <p class="form-label-bold">Support worker address</p> <div class="form-group" data-required data-error="Enter your company name"> <label for="company" class="form-label">Organisation or company name</label> <input type="text" name="company" id="company" class="form-control" value=""> </div> <div class="form-group"> <label class="form-label" for="address-a">Building number and street</label> <input type="text" name="address" id="address-a" class="form-control" value=""> <input type="text" name="address" id="address-a" class="form-control" value=""> </div> <div class="form-group" data-required data-error="Enter your town or city"> <label for="town" class="form-label">Town or city</label> <input type="text" name="town" id="town" class="form-control" value=""> </div> <div class="form-group" data-required data-error="Enter your postcode"> <label for="postCode" class="form-label">Postcode</label> <input type="text" name="postCode" id="postCode" class="form-control" value=""> </div> </div> </div> <!-- Primary buttons, secondary links --> <div class="form-group"> <input type="submit" class="button" value="Save and continue"> </div> <div class="form-group"> <p><a href="exit">Save and come back later</a></p> </div> </div> <div class="column-one-third"> {% include "../includes/help.html" %} </div> </div> </form> </main> {% endblock %}
{'content_hash': 'c9432ae2017f14295d6f79a0e7cca2b3', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 133, 'avg_line_length': 48.5, 'alnum_prop': 0.4615979381443299, 'repo_name': 'ballzy/apply-for-esa', 'id': '9211b3cb1ed580bf60c8bd5138798a99afd72ff0', 'size': '3880', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/views/beta07/work-support.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '12146'}, {'name': 'HTML', 'bytes': '5333224'}, {'name': 'JavaScript', 'bytes': '28196'}, {'name': 'Shell', 'bytes': '649'}]}
<?xml version="1.0" encoding="utf-8"?> <!-- Copyright (C) 2014 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_enabled="false" android:alpha="?attr/disabledAlpha" android:color="?attr/colorPrimaryDark"/> <item android:color="?attr/colorPrimaryDark"/> </selector>
{'content_hash': '7de5457a5913d3f0f408d9cc650acbaf', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 77, 'avg_line_length': 42.77272727272727, 'alnum_prop': 0.7098831030818279, 'repo_name': 'arsi-apli/NBANDROID-V2', 'id': '68b0eb60b78683803de0bcaccc1e6c1fb30b9aad', 'size': '941', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'nbandroid.layout.lib/src/main/layoutlib_v28_res/data/res/color-watch/btn_watch_default_dark.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'FreeMarker', 'bytes': '747732'}, {'name': 'GAP', 'bytes': '9978'}, {'name': 'GLSL', 'bytes': '632'}, {'name': 'HTML', 'bytes': '51779'}, {'name': 'Java', 'bytes': '3770028'}]}
from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils import timezone from airflow.utils.decorators import apply_defaults class TimeDeltaSensor(BaseSensorOperator): """ Waits for a timedelta after the task's execution_date + schedule_interval. In Airflow, the daily task stamped with ``execution_date`` 2016-01-01 can only start running on 2016-01-02. The timedelta here represents the time after the execution period has closed. :param delta: time length to wait after execution_date before succeeding :type delta: datetime.timedelta """ @apply_defaults def __init__(self, delta, *args, **kwargs): super(TimeDeltaSensor, self).__init__(*args, **kwargs) self.delta = delta def poke(self, context): dag = context['dag'] target_dttm = dag.following_schedule(context['execution_date']) target_dttm += self.delta self.log.info('Checking if the time (%s) has come', target_dttm) return timezone.utcnow() > target_dttm
{'content_hash': 'fadc83ba743693678f51c220ab853f6b', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 78, 'avg_line_length': 38.925925925925924, 'alnum_prop': 0.6974310180780209, 'repo_name': 'wndhydrnt/airflow', 'id': '51c6a7f0349875a4bc18b6874a47383a83fd1a30', 'size': '1865', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'airflow/sensors/time_delta_sensor.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '109698'}, {'name': 'HTML', 'bytes': '270515'}, {'name': 'JavaScript', 'bytes': '1988427'}, {'name': 'Mako', 'bytes': '1284'}, {'name': 'Python', 'bytes': '3580266'}, {'name': 'Shell', 'bytes': '36912'}]}
#ifndef BOOST_IOSTREAMS_DETAIL_EXECUTE_HPP_INCLUDED #define BOOST_IOSTREAMS_DETAIL_EXECUTE_HPP_INCLUDED #if defined(_MSC_VER) # pragma once #endif #include <boost/config.hpp> #include <boost/detail/workaround.hpp> #include <boost/iostreams/detail/config/limits.hpp> // MAX_EXECUTE_ARITY #include <boost/preprocessor/arithmetic/dec.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/iteration/local.hpp> #include <boost/preprocessor/repetition/enum_params.hpp> #include <boost/preprocessor/repetition/enum_binary_params.hpp> #include <boost/preprocessor/punctuation/comma_if.hpp> #include <boost/utility/result_of.hpp> namespace boost { namespace iostreams { namespace detail { // Helper for class template execute_traits. template<typename Result> struct execute_traits_impl { typedef Result result_type; template<typename Op> static Result execute(Op op) { return op(); } }; // Specialization for void return. For simplicity, execute() returns int // for operations returning void. This could be avoided with additional work. template<> struct execute_traits_impl<void> { typedef int result_type; template<typename Op> static int execute(Op op) { op(); return 0; } }; // Deduces the result type of Op and allows uniform treatment of operations // returning void and non-void. template< typename Op, typename Result = // VC6.5 workaround. #if !defined(BOOST_NO_RESULT_OF) && \ !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592)) typename boost::result_of<Op()>::type #else BOOST_DEDUCED_TYPENAME Op::result_type #endif > struct execute_traits : execute_traits_impl<Result> { }; // Implementation with no cleanup operations. template<typename Op> typename execute_traits<Op>::result_type execute_all(Op op) { return execute_traits<Op>::execute(op); } // Implementation with one or more cleanup operations #define BOOST_PP_LOCAL_MACRO(n) \ template<typename Op, BOOST_PP_ENUM_PARAMS(n, typename C)> \ typename execute_traits<Op>::result_type \ execute_all(Op op, BOOST_PP_ENUM_BINARY_PARAMS(n, C, c)) \ { \ typename execute_traits<Op>::result_type r; \ try { \ r = boost::iostreams::detail::execute_all( \ op BOOST_PP_COMMA_IF(BOOST_PP_DEC(n)) \ BOOST_PP_ENUM_PARAMS(BOOST_PP_DEC(n), c) \ ); \ } catch (...) { \ try { \ BOOST_PP_CAT(c, BOOST_PP_DEC(n))(); \ } catch (...) { } \ throw; \ } \ BOOST_PP_CAT(c, BOOST_PP_DEC(n))(); \ return r; \ } \ /**/ #define BOOST_PP_LOCAL_LIMITS (1, BOOST_IOSTREAMS_MAX_EXECUTE_ARITY) #include BOOST_PP_LOCAL_ITERATE() #undef BOOST_PP_LOCAL_MACRO template<class InIt, class Op> Op execute_foreach(InIt first, InIt last, Op op) { if (first == last) return op; try { op(*first); } catch (...) { try { ++first; boost::iostreams::detail::execute_foreach(first, last, op); } catch (...) { } throw; } ++first; return boost::iostreams::detail::execute_foreach(first, last, op); } } } } // End namespaces detail, iostreams, boost. #endif // #ifndef BOOST_IOSTREAMS_DETAIL_EXECUTE_HPP_INCLUDED
{'content_hash': '59df00831c7fdb072148b7eac77e70b1', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 77, 'avg_line_length': 30.7, 'alnum_prop': 0.6357713947290494, 'repo_name': 'PKRoma/poedit', 'id': '28e42172344790955c7228da1db1141f591512b3', 'size': '4526', 'binary': False, 'copies': '135', 'ref': 'refs/heads/master', 'path': 'deps/boost/boost/iostreams/detail/execute.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '48111'}, {'name': 'C++', 'bytes': '1283127'}, {'name': 'Inno Setup', 'bytes': '11178'}, {'name': 'M4', 'bytes': '103956'}, {'name': 'Makefile', 'bytes': '9507'}, {'name': 'Objective-C', 'bytes': '16519'}, {'name': 'Objective-C++', 'bytes': '14681'}, {'name': 'Python', 'bytes': '6594'}, {'name': 'Ruby', 'bytes': '292'}, {'name': 'Shell', 'bytes': '11982'}]}
/*! * # Semantic UI 2.3.3 - Dimmer * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { 'use strict'; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.dimmer = function(parameters) { var $allModules = $(this), time = new Date().getTime(), performance = [], query = arguments[0], methodInvoked = (typeof query == 'string'), queryArguments = [].slice.call(arguments, 1), returnedValue ; $allModules .each(function() { var settings = ( $.isPlainObject(parameters) ) ? $.extend(true, {}, $.fn.dimmer.settings, parameters) : $.extend({}, $.fn.dimmer.settings), selector = settings.selector, namespace = settings.namespace, className = settings.className, error = settings.error, eventNamespace = '.' + namespace, moduleNamespace = 'module-' + namespace, moduleSelector = $allModules.selector || '', clickEvent = ('ontouchstart' in document.documentElement) ? 'touchstart' : 'click', $module = $(this), $dimmer, $dimmable, element = this, instance = $module.data(moduleNamespace), module ; module = { preinitialize: function() { if( module.is.dimmer() ) { $dimmable = $module.parent(); $dimmer = $module; } else { $dimmable = $module; if( module.has.dimmer() ) { if(settings.dimmerName) { $dimmer = $dimmable.find(selector.dimmer).filter('.' + settings.dimmerName); } else { $dimmer = $dimmable.find(selector.dimmer); } } else { $dimmer = module.create(); } module.set.variation(); } }, initialize: function() { module.debug('Initializing dimmer', settings); module.bind.events(); module.set.dimmable(); module.instantiate(); }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module', $dimmer); module.unbind.events(); module.remove.variation(); $dimmable .off(eventNamespace) ; }, bind: { events: function() { if(module.is.page()) { // touch events default to passive, due to changes in chrome to optimize mobile perf $dimmable.get(0).addEventListener('touchmove', module.event.preventScroll, { passive: false }); } if(settings.on == 'hover') { $dimmable .on('mouseenter' + eventNamespace, module.show) .on('mouseleave' + eventNamespace, module.hide) ; } else if(settings.on == 'click') { $dimmable .on(clickEvent + eventNamespace, module.toggle) ; } if( module.is.page() ) { module.debug('Setting as a page dimmer', $dimmable); module.set.pageDimmer(); } if( module.is.closable() ) { module.verbose('Adding dimmer close event', $dimmer); $dimmable .on(clickEvent + eventNamespace, selector.dimmer, module.event.click) ; } } }, unbind: { events: function() { if(module.is.page()) { $dimmable.get(0).removeEventListener('touchmove', module.event.preventScroll, { passive: false }); } $module .removeData(moduleNamespace) ; $dimmable .off(eventNamespace) ; } }, event: { click: function(event) { module.verbose('Determining if event occured on dimmer', event); if( $dimmer.find(event.target).length === 0 || $(event.target).is(selector.content) ) { module.hide(); event.stopImmediatePropagation(); } }, preventScroll: function(event) { event.preventDefault(); } }, addContent: function(element) { var $content = $(element) ; module.debug('Add content to dimmer', $content); if($content.parent()[0] !== $dimmer[0]) { $content.detach().appendTo($dimmer); } }, create: function() { var $element = $( settings.template.dimmer() ) ; if(settings.dimmerName) { module.debug('Creating named dimmer', settings.dimmerName); $element.addClass(settings.dimmerName); } $element .appendTo($dimmable) ; return $element; }, show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; module.debug('Showing dimmer', $dimmer, settings); if( (!module.is.dimmed() || module.is.animating()) && module.is.enabled() ) { module.animate.show(callback); settings.onShow.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is already shown or disabled'); } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if( module.is.dimmed() || module.is.animating() ) { module.debug('Hiding dimmer', $dimmer); module.animate.hide(callback); settings.onHide.call(element); settings.onChange.call(element); } else { module.debug('Dimmer is not visible'); } }, toggle: function() { module.verbose('Toggling dimmer visibility', $dimmer); if( !module.is.dimmed() ) { module.show(); } else { module.hide(); } }, animate: { show: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { if(settings.opacity !== 'auto') { module.set.opacity(); } $dimmer .transition({ displayType : 'flex', animation : settings.transition + ' in', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.set.dimmed(); }, onComplete : function() { module.set.active(); callback(); } }) ; } else { module.verbose('Showing dimmer animation with javascript'); module.set.dimmed(); if(settings.opacity == 'auto') { settings.opacity = 0.8; } $dimmer .stop() .css({ opacity : 0, width : '100%', height : '100%' }) .fadeTo(module.get.duration(), settings.opacity, function() { $dimmer.removeAttr('style'); module.set.active(); callback(); }) ; } }, hide: function(callback) { callback = $.isFunction(callback) ? callback : function(){} ; if(settings.useCSS && $.fn.transition !== undefined && $dimmer.transition('is supported')) { module.verbose('Hiding dimmer with css'); $dimmer .transition({ displayType : 'flex', animation : settings.transition + ' out', queue : false, duration : module.get.duration(), useFailSafe : true, onStart : function() { module.remove.dimmed(); }, onComplete : function() { module.remove.active(); callback(); } }) ; } else { module.verbose('Hiding dimmer with javascript'); module.remove.dimmed(); $dimmer .stop() .fadeOut(module.get.duration(), function() { module.remove.active(); $dimmer.removeAttr('style'); callback(); }) ; } } }, get: { dimmer: function() { return $dimmer; }, duration: function() { if(typeof settings.duration == 'object') { if( module.is.active() ) { return settings.duration.hide; } else { return settings.duration.show; } } return settings.duration; } }, has: { dimmer: function() { if(settings.dimmerName) { return ($module.find(selector.dimmer).filter('.' + settings.dimmerName).length > 0); } else { return ( $module.find(selector.dimmer).length > 0 ); } } }, is: { active: function() { return $dimmer.hasClass(className.active); }, animating: function() { return ( $dimmer.is(':animated') || $dimmer.hasClass(className.animating) ); }, closable: function() { if(settings.closable == 'auto') { if(settings.on == 'hover') { return false; } return true; } return settings.closable; }, dimmer: function() { return $module.hasClass(className.dimmer); }, dimmable: function() { return $module.hasClass(className.dimmable); }, dimmed: function() { return $dimmable.hasClass(className.dimmed); }, disabled: function() { return $dimmable.hasClass(className.disabled); }, enabled: function() { return !module.is.disabled(); }, page: function () { return $dimmable.is('body'); }, pageDimmer: function() { return $dimmer.hasClass(className.pageDimmer); } }, can: { show: function() { return !$dimmer.hasClass(className.disabled); } }, set: { opacity: function(opacity) { var color = $dimmer.css('background-color'), colorArray = color.split(','), isRGB = (colorArray && colorArray.length == 3), isRGBA = (colorArray && colorArray.length == 4) ; opacity = settings.opacity === 0 ? 0 : settings.opacity || opacity; if(isRGB || isRGBA) { colorArray[3] = opacity + ')'; color = colorArray.join(','); } else { color = 'rgba(0, 0, 0, ' + opacity + ')'; } module.debug('Setting opacity to', opacity); $dimmer.css('background-color', color); }, active: function() { $dimmer.addClass(className.active); }, dimmable: function() { $dimmable.addClass(className.dimmable); }, dimmed: function() { $dimmable.addClass(className.dimmed); }, pageDimmer: function() { $dimmer.addClass(className.pageDimmer); }, disabled: function() { $dimmer.addClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.addClass(variation); } } }, remove: { active: function() { $dimmer .removeClass(className.active) ; }, dimmed: function() { $dimmable.removeClass(className.dimmed); }, disabled: function() { $dimmer.removeClass(className.disabled); }, variation: function(variation) { variation = variation || settings.variation; if(variation) { $dimmer.removeClass(variation); } } }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { module.error(error.method, query); return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return found; } }; module.preinitialize(); if(methodInvoked) { if(instance === undefined) { module.initialize(); } module.invoke(query); } else { if(instance !== undefined) { instance.invoke('destroy'); } module.initialize(); } }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; $.fn.dimmer.settings = { name : 'Dimmer', namespace : 'dimmer', silent : false, debug : false, verbose : false, performance : true, // name to distinguish between multiple dimmers in context dimmerName : false, // whether to add a variation type variation : false, // whether to bind close events closable : 'auto', // whether to use css animations useCSS : true, // css animation to use transition : 'fade', // event to bind to on : false, // overriding opacity value opacity : 'auto', // transition durations duration : { show : 500, hide : 500 }, onChange : function(){}, onShow : function(){}, onHide : function(){}, error : { method : 'The method you called is not defined.' }, className : { active : 'active', animating : 'animating', dimmable : 'dimmable', dimmed : 'dimmed', dimmer : 'dimmer', disabled : 'disabled', hide : 'hide', pageDimmer : 'page', show : 'show' }, selector: { dimmer : '> .ui.dimmer', content : '.ui.dimmer > .content, .ui.dimmer > .content > .center' }, template: { dimmer: function() { return $('<div />').attr('class', 'ui dimmer'); } } }; })( jQuery, window, document );
{'content_hash': '4a6111b380ad8a2775b4a148b3af545e', 'timestamp': '', 'source': 'github', 'line_count': 720, 'max_line_length': 112, 'avg_line_length': 29.645833333333332, 'alnum_prop': 0.4531271960646521, 'repo_name': 'extend1994/cdnjs', 'id': 'fa5862d1b8525de9285699ff986f7fb56b19a88d', 'size': '21345', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'ajax/libs/semantic-ui/2.3.3/components/dimmer.js', 'mode': '33188', 'license': 'mit', 'language': []}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_112-google-v7) on Fri Oct 20 16:52:53 PDT 2017 --> <title>ShadowLog.LogItem</title> <meta name="date" content="2017-10-20"> <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="ShadowLog.LogItem"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </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 class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/shadows/ShadowLog.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/shadows/ShadowLooper.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/shadows/ShadowLog.LogItem.html" target="_top">Frames</a></li> <li><a href="ShadowLog.LogItem.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.robolectric.shadows</div> <h2 title="Class ShadowLog.LogItem" class="title">Class ShadowLog.LogItem</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>org.robolectric.shadows.ShadowLog.LogItem</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../org/robolectric/shadows/ShadowLog.html" title="class in org.robolectric.shadows">ShadowLog</a></dd> </dl> <hr> <br> <pre>public static class <span class="typeNameLabel">ShadowLog.LogItem</span> extends java.lang.Object</pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</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> <tr class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#msg">msg</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#tag">tag</a></span></code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>java.lang.Throwable</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#throwable">throwable</a></span></code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#type">type</a></span></code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#LogItem-int-java.lang.String-java.lang.String-java.lang.Throwable-">LogItem</a></span>(int&nbsp;type, java.lang.String&nbsp;tag, java.lang.String&nbsp;msg, java.lang.Throwable&nbsp;throwable)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object&nbsp;o)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../org/robolectric/shadows/ShadowLog.LogItem.html#toString--">toString</a></span>()</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="type"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>type</h4> <pre>public final&nbsp;int type</pre> </li> </ul> <a name="tag"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>tag</h4> <pre>public final&nbsp;java.lang.String tag</pre> </li> </ul> <a name="msg"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>msg</h4> <pre>public final&nbsp;java.lang.String msg</pre> </li> </ul> <a name="throwable"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>throwable</h4> <pre>public final&nbsp;java.lang.Throwable throwable</pre> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="LogItem-int-java.lang.String-java.lang.String-java.lang.Throwable-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>LogItem</h4> <pre>public&nbsp;LogItem(int&nbsp;type, java.lang.String&nbsp;tag, java.lang.String&nbsp;msg, java.lang.Throwable&nbsp;throwable)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;o)</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>equals</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>hashCode</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> <a name="toString--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <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 class="navBarCell1Rev">Class</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 class="aboutLanguage"><script type="text/javascript" src="../../../highlight.pack.js"></script> <script type="text/javascript"><!-- hljs.initHighlightingOnLoad(); //--></script></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../org/robolectric/shadows/ShadowLog.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../org/robolectric/shadows/ShadowLooper.html" title="class in org.robolectric.shadows"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?org/robolectric/shadows/ShadowLog.LogItem.html" target="_top">Frames</a></li> <li><a href="ShadowLog.LogItem.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> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{'content_hash': '7e46e7a0984d1a9293d8a609a4996ca9', 'timestamp': '', 'source': 'github', 'line_count': 396, 'max_line_length': 391, 'avg_line_length': 33.92171717171717, 'alnum_prop': 0.6402888409141666, 'repo_name': 'robolectric/robolectric.github.io', 'id': 'aa90ebf128ac64b3f04e09e5e5ce5a580d53e250', 'size': '13433', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'javadoc/3.5/org/robolectric/shadows/ShadowLog.LogItem.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '132673'}, {'name': 'HTML', 'bytes': '277730'}, {'name': 'JavaScript', 'bytes': '24371'}, {'name': 'Ruby', 'bytes': '1051'}, {'name': 'SCSS', 'bytes': '64100'}, {'name': 'Shell', 'bytes': '481'}]}
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; /** * Created by aheroboy on 19/6/2017. */ /** * Created by aheroboy on 15/6/2017. */ var core_1 = require("@angular/core"); var platform_browser_1 = require("@angular/platform-browser"); var SourceComponent_1 = require("../components/SourceComponent"); var SourceModule = (function () { function SourceModule() { } return SourceModule; }()); SourceModule = __decorate([ core_1.NgModule({ imports: [platform_browser_1.BrowserModule], declarations: [SourceComponent_1.SourceComponent], }) ], SourceModule); exports.SourceModule = SourceModule; //# sourceMappingURL=SourceModule.js.map
{'content_hash': '04b214623b1c4b5f0b212d546fde3ec2', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 150, 'avg_line_length': 41.689655172413794, 'alnum_prop': 0.6451612903225806, 'repo_name': 'SG-Yang/DrawMath', 'id': '4578243f50c5d8fb002aac1420db5136e59bba8a', 'size': '1209', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/app/main/modules/SourceModule.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '28756'}, {'name': 'HTML', 'bytes': '1291'}, {'name': 'JavaScript', 'bytes': '14954'}, {'name': 'TypeScript', 'bytes': '17884'}]}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>compcert: 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.7.1+1 / compcert - 3.10</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> compcert <small> 3.10 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-11-10 23:24:19 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-10 23:24:19 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 2 Virtual package relying on perl coq 8.7.1+1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; authors: &quot;Xavier Leroy &lt;[email protected]&gt;&quot; maintainer: &quot;Jacques-Henri Jourdan &lt;[email protected]&gt;&quot; homepage: &quot;http://compcert.inria.fr/&quot; dev-repo: &quot;git+https://github.com/AbsInt/CompCert.git&quot; bug-reports: &quot;https://github.com/AbsInt/CompCert/issues&quot; license: &quot;INRIA Non-Commercial License Agreement&quot; build: [ [&quot;./configure&quot; &quot;amd64-linux&quot; {os = &quot;linux&quot; &amp; arch = &quot;x86_64&quot;} &quot;amd64-macosx&quot; {os = &quot;macos&quot; &amp; arch = &quot;x86_64&quot;} &quot;arm64-linux&quot; {os = &quot;linux&quot; &amp; (arch = &quot;arm64&quot; | arch = &quot;aarch64&quot;)} &quot;arm64-macosx&quot; {os = &quot;macos&quot; &amp; (arch = &quot;arm64&quot; | arch = &quot;aarch64&quot;)} &quot;amd64-cygwin&quot; {os = &quot;cygwin&quot;} # This is for building a MinGW CompCert with cygwin host and cygwin target &quot;amd64-cygwin&quot; {os = &quot;win32&quot; &amp; os-distribution = &quot;cygwinports&quot;} # This is for building a 64 bit CompCert on 32 bit MinGW with cygwin build host &quot;-toolprefix&quot; {os = &quot;win32&quot; &amp; os-distribution = &quot;cygwinports&quot; &amp; arch = &quot;i686&quot;} &quot;x86_64-pc-cygwin-&quot; {os = &quot;win32&quot; &amp; os-distribution = &quot;cygwinports&quot; &amp; arch = &quot;i686&quot;} &quot;-prefix&quot; &quot;%{prefix}%&quot; &quot;-install-coqdev&quot; &quot;-clightgen&quot; &quot;-use-external-Flocq&quot; &quot;-use-external-MenhirLib&quot; &quot;-coqdevdir&quot; &quot;%{lib}%/coq/user-contrib/compcert&quot; &quot;-ignore-coq-version&quot;] [make &quot;-j%{jobs}%&quot; {ocaml:version &gt;= &quot;4.06&quot;}] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;coq&quot; {&gt;= &quot;8.9.0&quot; &amp; &lt; &quot;8.16~&quot;} &quot;menhir&quot; {&gt;= &quot;20190626&quot; } &quot;ocaml&quot; {&gt;= &quot;4.05.0&quot;} &quot;coq-flocq&quot; {&gt;= &quot;3.1.0&quot; &amp; &lt; &quot;4~&quot;} &quot;coq-menhirlib&quot; {&gt;= &quot;20190626&quot;} ] synopsis: &quot;The CompCert C compiler (64 bit)&quot; tags: [ &quot;category:Computer Science/Semantics and Compilation/Compilation&quot; &quot;category:Computer Science/Semantics and Compilation/Semantics&quot; &quot;keyword:C&quot; &quot;keyword:compiler&quot; &quot;logpath:compcert&quot; &quot;date:2021-11-19&quot; ] url { src: &quot;https://github.com/AbsInt/CompCert/archive/v3.10.tar.gz&quot; checksum: &quot;sha512=93687fb36cdfb247d47404c8d41d84ba96d006dd3a535646337a477fd5517c7487ff1d66e83bccceb47ba2d18b187c1bbdc55b2eff00373a8a120edfc80ef11a&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-compcert.3.10 coq.8.7.1+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.7.1+1). The following dependencies couldn&#39;t be met: - coq-compcert -&gt; ocaml &gt;= 4.05.0 base of this switch (use `--unlock-base&#39; to force) 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-compcert.3.10</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': '77e0c96230b9c4583e189d593a61cced', 'timestamp': '', 'source': 'github', 'line_count': 193, 'max_line_length': 159, 'avg_line_length': 44.27461139896373, 'alnum_prop': 0.5678174370977179, 'repo_name': 'coq-bench/coq-bench.github.io', 'id': '56f6965d6196bb5ea0193ee1587a19fc93e34704', 'size': '8570', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'clean/Linux-x86_64-4.02.3-2.0.6/released/8.7.1+1/compcert/3.10.html', 'mode': '33188', 'license': 'mit', 'language': []}
InspectorTest.log( 'Checks that stepInto nested arrow function doesn\'t produce crash.'); InspectorTest.setupScriptMap(); InspectorTest.addScript(` const rec = (x) => (y) => rec(); //# sourceURL=test.js`); Protocol.Debugger.onPaused(message => { InspectorTest.log("paused"); InspectorTest.logCallFrames(message.params.callFrames); Protocol.Debugger.stepInto(); }) Protocol.Debugger.enable(); Protocol.Debugger.setBreakpointByUrl({ url: 'test.js', lineNumber: 2 }) .then(() => Protocol.Runtime.evaluate({ expression: 'rec(5)(4)' })) .then(InspectorTest.completeTest);
{'content_hash': '4954d7adefcd396cc6dff1273bc03c57', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 74, 'avg_line_length': 30.736842105263158, 'alnum_prop': 0.7208904109589042, 'repo_name': 'RPGOne/Skynet', 'id': '0b0307a5e6319ee290205bbd5a8c5ff113343756', 'size': '752', 'binary': False, 'copies': '2', 'ref': 'refs/heads/Miho', 'path': 'node-master/deps/v8/test/inspector/debugger/step-into-nested-arrow.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': '1C Enterprise', 'bytes': '36'}, {'name': 'Ada', 'bytes': '89079'}, {'name': 'Assembly', 'bytes': '11425802'}, {'name': 'Batchfile', 'bytes': '123467'}, {'name': 'C', 'bytes': '34703955'}, {'name': 'C#', 'bytes': '55955'}, {'name': 'C++', 'bytes': '84647314'}, {'name': 'CMake', 'bytes': '220849'}, {'name': 'CSS', 'bytes': '39257'}, {'name': 'Cuda', 'bytes': '1344541'}, {'name': 'DIGITAL Command Language', 'bytes': '349320'}, {'name': 'DTrace', 'bytes': '37428'}, {'name': 'Emacs Lisp', 'bytes': '19654'}, {'name': 'Erlang', 'bytes': '39438'}, {'name': 'Fortran', 'bytes': '16914'}, {'name': 'HTML', 'bytes': '929759'}, {'name': 'Java', 'bytes': '112658'}, {'name': 'JavaScript', 'bytes': '32806873'}, {'name': 'Jupyter Notebook', 'bytes': '1616334'}, {'name': 'Lua', 'bytes': '22549'}, {'name': 'M4', 'bytes': '64967'}, {'name': 'Makefile', 'bytes': '1046428'}, {'name': 'Matlab', 'bytes': '888'}, {'name': 'Module Management System', 'bytes': '1545'}, {'name': 'NSIS', 'bytes': '2860'}, {'name': 'Objective-C', 'bytes': '131433'}, {'name': 'PHP', 'bytes': '750783'}, {'name': 'Pascal', 'bytes': '75208'}, {'name': 'Perl', 'bytes': '626627'}, {'name': 'Perl 6', 'bytes': '2495926'}, {'name': 'PowerShell', 'bytes': '38374'}, {'name': 'Prolog', 'bytes': '300018'}, {'name': 'Python', 'bytes': '26363074'}, {'name': 'R', 'bytes': '236175'}, {'name': 'Rebol', 'bytes': '217'}, {'name': 'Roff', 'bytes': '328366'}, {'name': 'SAS', 'bytes': '1847'}, {'name': 'Scala', 'bytes': '248902'}, {'name': 'Scheme', 'bytes': '14853'}, {'name': 'Shell', 'bytes': '360815'}, {'name': 'TeX', 'bytes': '105346'}, {'name': 'Vim script', 'bytes': '6101'}, {'name': 'XS', 'bytes': '4319'}, {'name': 'eC', 'bytes': '5158'}]}
package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yarep.core.Repository; import org.wyona.yarep.core.RepositoryFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.parser.Parser; import org.apache.log4j.Category; /** * */ public class AtomEntryResource extends Resource implements ViewableV2, ModifiableV2 { private static Category log = Category.getInstance(AtomEntryResource.class); /** * */ public AtomEntryResource() { } /** * */ public ViewDescriptor[] getViewDescriptors() { return null; } /** * */ public View getView(String viewId) { View defaultView = new View(); String mimeType = getMimeType(viewId); defaultView.setMimeType(mimeType); try { if (mimeType.equals("application/xml")) { defaultView.setInputStream(getContentXML()); return defaultView; } else if (mimeType.equals("application/xhtml+xml") || mimeType.equals("text/html")) { TransformerFactory tf = TransformerFactory.newInstance(); //tf.setURIResolver(null); Transformer transformer = tf.newTransformer(new StreamSource(getRealm().getRepository().getInputStream(new org.wyona.yarep.core.Path(getXSLTPath().toString())))); transformer.setParameter("yanel.path.name", org.wyona.commons.io.PathUtil.getName(getPath())); transformer.setParameter("yanel.path", getPath()); transformer.setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); transformer.setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); // TODO: Is this the best way to generate an InputStream from an OutputStream? java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); org.xml.sax.XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader(); xmlReader.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); transformer.transform(new SAXSource(xmlReader, new org.xml.sax.InputSource(getContentXML())), new StreamResult(baos)); defaultView.setInputStream(new java.io.ByteArrayInputStream(baos.toByteArray())); return defaultView; } else { log.debug("Mime-Type: " + mimeType); defaultView.setInputStream(getContentXML()); //defaultView.setInputStream(rp.getRepo().getInputStream(new org.wyona.yarep.core.Path(rp.getPath().toString()))); } } catch(Exception e) { log.error(e); } return defaultView; } /** * */ private InputStream getContentXML() throws Exception { return getRealm().getRepository().getInputStream(new org.wyona.yarep.core.Path(getPath().toString())); } /** * */ public String getMimeType(String viewId) { String mimeType = getRTI().getProperty("mime-type"); if (mimeType != null) return mimeType; String suffix = org.wyona.commons.io.PathUtil.getSuffix(getPath()); if (suffix != null) { log.debug("SUFFIX: " + suffix); if (suffix.equals("html")) { //mimeType = "text/html"; mimeType = "application/xhtml+xml"; } else if (suffix.equals("xhtml")) { mimeType = "application/xhtml+xml"; } else if (suffix.equals("xml")) { mimeType = "application/xml"; } else { mimeType = "application/xml"; } } else { mimeType = "application/xml"; } return mimeType; } /** * */ public Reader getReader() throws Exception { return getRealm().getRepository().getReader(new org.wyona.yarep.core.Path(getPath())); } /** * */ public InputStream getInputStream() throws Exception { return getRealm().getRepository().getInputStream(new org.wyona.yarep.core.Path(getPath())); } /** * */ public Writer getWriter() { log.error("Not implemented yet!"); return null; } /** * */ public OutputStream getOutputStream() throws Exception { return getRealm().getRepository().getOutputStream(new org.wyona.yarep.core.Path(getPath())); } /** * */ public void write(InputStream in) throws Exception { org.apache.abdera.Abdera abdera = new org.apache.abdera.Abdera(); Parser parser = abdera.getParser(); Document doc = parser.parse(in); Entry entry = (Entry) doc.getRoot(); java.util.Date date = new java.util.Date(); entry.setUpdated(date); java.util.Date publishedDate = entry.getPublished(); if (publishedDate == null) { log.error("No published date!"); entry.setPublished(date); } Repository repo = getRealm().getRepository(); org.wyona.commons.io.Path atomEntryPath = new org.wyona.commons.io.Path(getPath()); if (!repo.existsNode(getPath())) { // TODO: Create node recursively in case parent does not exist! repo.getNode(atomEntryPath.getParent().toString()).addNode(atomEntryPath.getName(), org.wyona.yarep.core.NodeType.RESOURCE); } OutputStream out = repo.getOutputStream(new org.wyona.yarep.core.Path(getPath())); org.apache.abdera.writer.Writer writer = abdera.getWriter(); writer.writeTo(entry, out); log.debug("Atom entry has been written: " + getPath()); } /** * Get last modified */ public long getLastModified() throws Exception { return getRealm().getRepository().getLastModified(new org.wyona.yarep.core.Path(getPath())); } /** * */ private String getXSLTPath() { String xslt = getRTI().getProperty("xslt"); if (xslt != null) { return xslt; } log.error("No XSLT Path within: " + PathUtil.getRTIPath(getPath())); return null; } /** * */ public boolean delete() throws Exception { return getRealm().getRepository().delete(new org.wyona.yarep.core.Path(getPath())); } public boolean exists() throws Exception { log.warn("Not implemented yet!"); return true; } /** * */ public long getSize() throws Exception { return getRealm().getRepository().getSize(new Path(getPath())); } }
{'content_hash': 'be6cc29c5209c65a7d7ef30bdbaf83a5', 'timestamp': '', 'source': 'github', 'line_count': 224, 'max_line_length': 178, 'avg_line_length': 32.892857142857146, 'alnum_prop': 0.620114006514658, 'repo_name': 'baszero/yanel', 'id': '0a67e14580101896706bf21f87fedece1213e23a', 'size': '7971', 'binary': False, 'copies': '2', 'ref': 'refs/heads/upgrade8', 'path': 'src/resources/atom-entry/src/java/org/wyona/yanel/impl/resources/AtomEntryResource.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '29314'}, {'name': 'CSS', 'bytes': '78551'}, {'name': 'HTML', 'bytes': '1333652'}, {'name': 'Java', 'bytes': '2394273'}, {'name': 'JavaScript', 'bytes': '1489720'}, {'name': 'NSIS', 'bytes': '6865'}, {'name': 'Perl', 'bytes': '9821'}, {'name': 'Python', 'bytes': '3285'}, {'name': 'Shell', 'bytes': '48928'}, {'name': 'XSLT', 'bytes': '599717'}]}
"""Support for deCONZ binary sensors.""" from pydeconz.sensor import CarbonMonoxide, Fire, OpenClose, Presence, Vibration, Water from homeassistant.components.binary_sensor import ( DEVICE_CLASS_GAS, DEVICE_CLASS_MOISTURE, DEVICE_CLASS_MOTION, DEVICE_CLASS_OPENING, DEVICE_CLASS_SMOKE, DEVICE_CLASS_VIBRATION, DOMAIN, BinarySensorEntity, ) from homeassistant.const import ATTR_TEMPERATURE from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ATTR_DARK, ATTR_ON, NEW_SENSOR from .deconz_device import DeconzDevice from .gateway import get_gateway_from_config_entry ATTR_ORIENTATION = "orientation" ATTR_TILTANGLE = "tiltangle" ATTR_VIBRATIONSTRENGTH = "vibrationstrength" DEVICE_CLASS = { CarbonMonoxide: DEVICE_CLASS_GAS, Fire: DEVICE_CLASS_SMOKE, OpenClose: DEVICE_CLASS_OPENING, Presence: DEVICE_CLASS_MOTION, Vibration: DEVICE_CLASS_VIBRATION, Water: DEVICE_CLASS_MOISTURE, } async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the deCONZ binary sensor.""" gateway = get_gateway_from_config_entry(hass, config_entry) gateway.entities[DOMAIN] = set() @callback def async_add_sensor(sensors): """Add binary sensor from deCONZ.""" entities = [] for sensor in sensors: if ( sensor.BINARY and sensor.uniqueid not in gateway.entities[DOMAIN] and ( gateway.option_allow_clip_sensor or not sensor.type.startswith("CLIP") ) ): entities.append(DeconzBinarySensor(sensor, gateway)) if entities: async_add_entities(entities) gateway.listeners.append( async_dispatcher_connect( hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_sensor ) ) async_add_sensor( [gateway.api.sensors[key] for key in sorted(gateway.api.sensors, key=int)] ) class DeconzBinarySensor(DeconzDevice, BinarySensorEntity): """Representation of a deCONZ binary sensor.""" TYPE = DOMAIN @callback def async_update_callback(self, force_update=False): """Update the sensor's state.""" keys = {"on", "reachable", "state"} if force_update or self._device.changed_keys.intersection(keys): super().async_update_callback(force_update=force_update) @property def is_on(self): """Return true if sensor is on.""" return self._device.is_tripped @property def device_class(self): """Return the class of the sensor.""" return DEVICE_CLASS.get(type(self._device)) @property def device_state_attributes(self): """Return the state attributes of the sensor.""" attr = {} if self._device.on is not None: attr[ATTR_ON] = self._device.on if self._device.secondary_temperature is not None: attr[ATTR_TEMPERATURE] = self._device.secondary_temperature if self._device.type in Presence.ZHATYPE: if self._device.dark is not None: attr[ATTR_DARK] = self._device.dark elif self._device.type in Vibration.ZHATYPE: attr[ATTR_ORIENTATION] = self._device.orientation attr[ATTR_TILTANGLE] = self._device.tiltangle attr[ATTR_VIBRATIONSTRENGTH] = self._device.vibrationstrength return attr
{'content_hash': 'c4e9293db634fe455ef3a79ab5822300', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 87, 'avg_line_length': 30.62608695652174, 'alnum_prop': 0.6484951731970471, 'repo_name': 'sdague/home-assistant', 'id': '5b536aeb74cdcab73ad16841793fba1673d26669', 'size': '3522', 'binary': False, 'copies': '3', 'ref': 'refs/heads/dev', 'path': 'homeassistant/components/deconz/binary_sensor.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '1488'}, {'name': 'Python', 'bytes': '27869189'}, {'name': 'Shell', 'bytes': '4528'}]}
"""setup -- setuptools setup file for Thomas-aquinas. $Author: shackra $ $Rev: 1 $ $Date: 2012-05-12 02:55:00 -0600 (Sun, 12 March 2013) $ """ __author__ = "Invensible Studios" __author_email__ = "[email protected]" __version__ = "0.0.1" __date__ = "2013 05 12" try: import setuptools except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages with open("README", 'rU') as f: long_description = f.read() setup( name = "thomas-aquinas", version = __version__, author = "Invensible Studios", license="GPL3+", description = "a 2D framework for games and multimedia. Based on Cocos2D", long_description=long_description, url = "http://www.ohloh.net/p/thomas-aquinas", download_url = "https://bitbucket.org/shackra/thomas-aquinas/downloads", classifiers = [ "Development Status :: 3 - Alpha", "Environment :: MacOS X", "Environment :: Win32 (MS Windows)", "Environment :: X11 Applications", "Intended Audience :: Developers", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Natural Language :: Spanish" "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX :: Linux", "Programming Language :: Python", ("Topic :: Software Development :: Libraries :: Python Modules"), ("Topic :: Games/Entertainment"), ], packages = find_packages(), package_data={'summa': ['resources/*']}, install_requires=['pyglet>=1.1.4',], dependency_links=['http://code.google.com/p/pyglet/downloads/list',], include_package_data = True, zip_safe = False, )
{'content_hash': 'cdf222d45ece2800b0bd41bad787740d', 'timestamp': '', 'source': 'github', 'line_count': 59, 'max_line_length': 85, 'avg_line_length': 31.440677966101696, 'alnum_prop': 0.6221024258760108, 'repo_name': 'shackra/thomas-aquinas', 'id': '8ca2fb755afad375aee38510985d81a086e9124b', 'size': '1879', 'binary': False, 'copies': '1', 'ref': 'refs/heads/stable-branch', 'path': 'setup.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '1245155'}]}
var data = require('../people.json'); //var friends = require('../friends.json'); exports.view = function(req, res){ console.log('A testing page'); data.alertTab = false; res.render('index', data); }; exports.viewAlertTab = function(req, res){ console.log('B testing page'); data.alertTab = true; res.render('index', data); } exports.addFriend = function(req, res){ var body = req.body; data.friends.push({name:body.name, imageURL: body.imageURL}); console.log(data); res.render('index', data); };
{'content_hash': '44ac543df25084e47daa904b17c83c45', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 65, 'avg_line_length': 22.375, 'alnum_prop': 0.6443202979515829, 'repo_name': 'tyc007/project_ice', 'id': '51e02ccb05010799f3bf97d2de340f3fa3454039', 'size': '567', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'routes/index.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '248133'}, {'name': 'JavaScript', 'bytes': '74067'}, {'name': 'Perl', 'bytes': '2347'}]}
using System; namespace JoZhTranslit { /// <summary> /// Indicates that provided graphemes map is not in correct format. /// Example: { "б": ["b"], "ё": ["jo", "yo"] } /// </summary> public class MapJsonParseException : Exception { internal MapJsonParseException() { } internal MapJsonParseException(string message) : base(message) { } internal MapJsonParseException(string message, Exception innerException) : base(message, innerException) { } } }
{'content_hash': 'f51b06e45f14d0ab1f338f706591633e', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 80, 'avg_line_length': 23.04, 'alnum_prop': 0.5659722222222222, 'repo_name': 'eealeivan/jozh-translit', 'id': '15c1c454af5f6eddd1bfca0038bdff8dbbbc1633', 'size': '580', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Src/JoZhTranslit/MapJsonParseException.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '30207'}, {'name': 'PowerShell', 'bytes': '41870'}]}