text
stringlengths 4
5.48M
| meta
stringlengths 14
6.54k
|
---|---|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics;
public enum MatrixExpressionType {
Constant,
Parameter,
Transpose,
MatrixMultiply,
ScalarMultiply,
Add,
Subtract
}
public enum MatrixShapeType {
Matrix,
RowVector,
ColumnVector,
Scalar
}
public class SymbolicMatrixExpr {
public MatrixExpressionType exprType;
public MatrixShapeType shapeType;
public Expression dataExp;
public int[] shape;
public bool isConstant;
public string name;
public ParameterExpression[] parameters;
public SymbolicMatrixExpr[] children;
public int treeSize;
private SymbolicMatrixExpr(){
// blank slate matrix for internal use
}
public static SymbolicMatrixExpr constantMatrix(Matrix inputMatrix, string name){
// constant matrix
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
returnMat.isConstant = true;
returnMat.shape = new int[] { inputMatrix.RowCount, inputMatrix.ColumnCount};
//shape calculations
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// data and type calculations
returnMat.dataExp = (ConstantExpression) Expression.Constant(inputMatrix);
returnMat.parameters = new ParameterExpression[] {};
returnMat.exprType = MatrixExpressionType.Constant;
returnMat.name = name;
returnMat.children = new SymbolicMatrixExpr[] {};
returnMat.treeSize = 1;
return returnMat;
}
public static SymbolicMatrixExpr parametricMatrix(int[] shape, string name){
// parametric matrix
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
returnMat.isConstant = false;
returnMat.shape = new int[] {shape[0], shape[1]};
//shape calculations
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// data and type calculations
ParameterExpression expr = Expression.Parameter(typeof(Matrix), name);
returnMat.dataExp = expr;
returnMat.parameters = new ParameterExpression[] {expr};
returnMat.exprType = MatrixExpressionType.Parameter;
returnMat.name = name;
returnMat.children = new SymbolicMatrixExpr[] {};
returnMat.treeSize = 1;
return returnMat;
}
public static SymbolicMatrixExpr transposeMatrix(SymbolicMatrixExpr inputSymbMat){
// transpose the input matrix
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
returnMat.isConstant = inputSymbMat.isConstant;
int[] shape = inputSymbMat.shape;
returnMat.shape = new int[] {shape[1], shape[0]};
//shape calculations
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// data and type calculations
returnMat.dataExp = Symbolic.transpose(inputSymbMat.dataExp);
returnMat.parameters = inputSymbMat.parameters.ToArray();
returnMat.exprType = MatrixExpressionType.Transpose;
returnMat.name = SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMat) + "^T";
returnMat.children = new SymbolicMatrixExpr[] {inputSymbMat};
returnMat.treeSize = inputSymbMat.treeSize + 1;
return returnMat;
}
public static SymbolicMatrixExpr multiply(SymbolicMatrixExpr inputSymbMatLeft, SymbolicMatrixExpr inputSymbMatRight){
// matrix multiply two matrices
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
// calculate return shape and check that it is a valid matrix multiply
int[] shapeLeft = inputSymbMatLeft.shape;
int[] shapeRight = inputSymbMatRight.shape;
if (shapeLeft[1] != shapeRight[0]){
throw new Exception("Shapes are not compatible for matrix multiply");
}
else {
returnMat.shape = new int[] {shapeLeft[0], shapeRight[1]};
}
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// constant calculation
if (inputSymbMatLeft.isConstant && inputSymbMatRight.isConstant){
returnMat.isConstant = true;
returnMat.parameters = new ParameterExpression[] {};
}
else {
returnMat.isConstant = false;
returnMat.parameters = SymbolicMatrixExpr.concatParameters(inputSymbMatLeft, inputSymbMatRight);
}
returnMat.dataExp = Expression.Multiply(inputSymbMatLeft.dataExp, inputSymbMatRight.dataExp);
returnMat.exprType = MatrixExpressionType.MatrixMultiply;
returnMat.name = SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatLeft) + " * "
+ SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatRight);
returnMat.children = new SymbolicMatrixExpr[] {inputSymbMatLeft, inputSymbMatRight};
returnMat.treeSize = inputSymbMatLeft.treeSize + inputSymbMatRight.treeSize + 1;
return returnMat;
}
public static SymbolicMatrixExpr scale(SymbolicMatrixExpr inputSymbScalar, SymbolicMatrixExpr inputSymbMatrix){
// scale the right matrix by the input scalar (left matrix)
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
// check that the scalar input (left symbolic matrix) is a scalar
int[] matShape = inputSymbMatrix.shape;
if (inputSymbScalar.shapeType != MatrixShapeType.Scalar){
throw new Exception("Scalar for scalar multiply does not have the correct shape ([1, 1])");
}
else {
returnMat.shape = new int[] {matShape[0], matShape[1]};
}
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// constant calculation
if (inputSymbScalar.isConstant && inputSymbMatrix.isConstant){
returnMat.isConstant = true;
returnMat.parameters = new ParameterExpression[] {};
}
else {
returnMat.isConstant = false;
returnMat.parameters = SymbolicMatrixExpr.concatParameters(inputSymbScalar, inputSymbMatrix);
}
// TODO: WARNING: does not work when using lambdafy, currently only works for evaluate to evaluate the tree
// still need to figure out how to call non-static members
//returnMat.dataExp = Expression.Multiply(Symbolic.extractScalar(inputSymbScalar.dataExp), inputSymbMatrix.dataExp);
returnMat.dataExp = Expression.Multiply(inputSymbScalar.dataExp, inputSymbMatrix.dataExp);
returnMat.exprType = MatrixExpressionType.ScalarMultiply;
returnMat.name = SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbScalar) + " * "
+ SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatrix);
returnMat.children = new SymbolicMatrixExpr[] {inputSymbScalar, inputSymbMatrix};
returnMat.treeSize = inputSymbScalar.treeSize + inputSymbMatrix.treeSize + 1;
return returnMat;
}
public static SymbolicMatrixExpr add(SymbolicMatrixExpr inputSymbMatLeft, SymbolicMatrixExpr inputSymbMatRight){
// add two symbolic matrices
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
// calculate return shape and check that it is a valid matrix add
int[] shapeLeft = inputSymbMatLeft.shape;
int[] shapeRight = inputSymbMatRight.shape;
if (shapeLeft[0] != shapeRight[0] || shapeLeft[1] != shapeRight[1]){
throw new Exception("Shapes are not compatible for matrix add");
}
else {
returnMat.shape = new int[] {shapeLeft[0], shapeLeft[1]};
}
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// constant calculation
if (inputSymbMatLeft.isConstant && inputSymbMatRight.isConstant){
returnMat.isConstant = true;
returnMat.parameters = new ParameterExpression[] {};
}
else {
returnMat.isConstant = false;
returnMat.parameters = SymbolicMatrixExpr.concatParameters(inputSymbMatLeft, inputSymbMatRight);
}
returnMat.dataExp = Expression.Add(inputSymbMatLeft.dataExp, inputSymbMatRight.dataExp);
returnMat.exprType = MatrixExpressionType.Add;
returnMat.name = SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatLeft) + " + "
+ SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatRight);
returnMat.children = new SymbolicMatrixExpr[] {inputSymbMatLeft, inputSymbMatRight};
returnMat.treeSize = inputSymbMatLeft.treeSize + inputSymbMatRight.treeSize + 1;
return returnMat;
}
public static SymbolicMatrixExpr subtract(SymbolicMatrixExpr inputSymbMatLeft, SymbolicMatrixExpr inputSymbMatRight){
// subtract the right symbolic matrix from the left symbolic matrix
SymbolicMatrixExpr returnMat = new SymbolicMatrixExpr();
// calculate return shape and check that it is a valid matrix add
int[] shapeLeft = inputSymbMatLeft.shape;
int[] shapeRight = inputSymbMatRight.shape;
if (shapeLeft[0] != shapeRight[0] || shapeLeft[1] != shapeRight[1]){
throw new Exception("Shapes are not compatible for matrix subtract");
}
else {
returnMat.shape = new int[] {shapeLeft[0], shapeLeft[1]};
}
returnMat.shapeType = SymbolicMatrixExpr.shapeToMatShapeType(returnMat.shape);
// constant calculation
if (inputSymbMatLeft.isConstant && inputSymbMatRight.isConstant){
returnMat.isConstant = true;
returnMat.parameters = new ParameterExpression[] {};
}
else {
returnMat.isConstant = false;
returnMat.parameters = SymbolicMatrixExpr.concatParameters(inputSymbMatLeft, inputSymbMatRight);
}
returnMat.dataExp = Expression.Subtract(inputSymbMatLeft.dataExp, inputSymbMatRight.dataExp);
returnMat.exprType = MatrixExpressionType.Subtract;
returnMat.name = SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatLeft) + " - "
+ SymbolicMatrixExpr.nameParenthesForNonLeaves(inputSymbMatRight);
returnMat.children = new SymbolicMatrixExpr[] {inputSymbMatLeft, inputSymbMatRight};
returnMat.treeSize = inputSymbMatLeft.treeSize + inputSymbMatRight.treeSize + 1;
return returnMat;
}
public static MatrixShapeType shapeToMatShapeType(int[] shape){
int numRows = shape[0];
int numCols = shape[1];
MatrixShapeType type;
if (numRows == 1 && numCols == 1){
type = MatrixShapeType.Scalar;
}
else if (numRows == 1){
type = MatrixShapeType.RowVector;
}
else if (numCols == 1){
type = MatrixShapeType.ColumnVector;
}
else {
type = MatrixShapeType.Matrix;
}
return type;
}
private static ParameterExpression[] concatParameters(SymbolicMatrixExpr expr1, SymbolicMatrixExpr expr2){
return (expr1.parameters).Concat(expr2.parameters).ToArray();
}
public LambdaExpression lambdafy(){
// might have to condense the parameters into a single parameter of type Matrix[]
// in order to handle variable numbers of parameters
return (LambdaExpression) Expression.Lambda(this.dataExp, this.parameters);
}
public static Func<int[], int[]> shapeIdentity = shape => shape;
// TODO: come back to this when I have internet to figure out how to do polymorphism in c#
//public static Func<T, T> constant(T input){
// return arbitrary => input;
//}
public static SymbolicMatrixExpr[] childrenFirstTopSort(SymbolicMatrixExpr inputMatrix){
List<SymbolicMatrixExpr> returnList = childrenFirstTopSortHelper(inputMatrix);
SymbolicMatrixExpr[] returnSortedExprs = returnList.ToArray();
return returnSortedExprs;
}
private static List<SymbolicMatrixExpr> childrenFirstTopSortHelper(SymbolicMatrixExpr currentExpr){
List<SymbolicMatrixExpr> currentList = new List<SymbolicMatrixExpr>();
if (currentExpr != null){
foreach (SymbolicMatrixExpr child in currentExpr.children){
currentList.AddRange(childrenFirstTopSortHelper(child));
}
currentList.Add (currentExpr);
}
return currentList;
}
public static String nameParenthesForNonLeaves(SymbolicMatrixExpr inputExpression){
String returnMatName;
if (inputExpression.children.GetLength(0) == 0){
returnMatName = inputExpression.name;
}
else {
returnMatName = "(" + inputExpression.name + ")";
}
return returnMatName;
}
public Matrix[] evaluate(Dictionary<string, Matrix> nameDict){
return evaluateRecursive(this, nameDict).ToArray();
}
public static List<Matrix> evaluateRecursive(SymbolicMatrixExpr currentExpr, Dictionary<string, Matrix> nameDict){
List<Matrix> currentResultsList = new List<Matrix>();
List<Matrix> currentChildren = new List<Matrix>();
if (currentExpr != null){
foreach (SymbolicMatrixExpr child in currentExpr.children){
List<Matrix> childList = evaluateRecursive(child, nameDict);
currentChildren.Add ((Matrix) childList.Last());
currentResultsList.AddRange(childList);
}
Matrix currentResult;
switch (currentExpr.exprType){
//TODO: only evaluate unary or binary expressions currently, would like to extend to more general children structures
case MatrixExpressionType.Constant:
currentResult = (Matrix) ((ConstantExpression) currentExpr.dataExp).Value;
break;
case MatrixExpressionType.Parameter:
currentResult = nameDict[((ParameterExpression) currentExpr.dataExp).Name];
break;
case MatrixExpressionType.Transpose:
currentResult = Matrix.Transpose(currentChildren.First());
break;
case MatrixExpressionType.MatrixMultiply:
currentResult = (currentChildren.First() * currentChildren.Last());
break;
case MatrixExpressionType.ScalarMultiply:
Matrix intermediate = currentChildren.Last().Clone();
intermediate.Multiply(((Matrix) currentChildren.First()).GetArray()[0][0]);
currentResult = intermediate;
break;
case MatrixExpressionType.Add:
currentResult = (currentChildren.First() + currentChildren.Last());
break;
case MatrixExpressionType.Subtract:
currentResult = (currentChildren.First() - currentChildren.Last());
break;
default:
currentResult = Matrix.Zeros(1);
break;
}
currentResultsList.Add (currentResult);
}
return currentResultsList;
}
public MatrixExprWithData[] evaluateWithInputsAndType(Dictionary<string, Matrix> nameDict){
List<MatrixExprWithData> resultsList = evaluateRecursiveWithInputsAndType(this, nameDict);
MatrixExprWithData[] returnArray = resultsList.ToArray();
return returnArray;
}
public static List<MatrixExprWithData> evaluateRecursiveWithInputsAndType(SymbolicMatrixExpr currentExpr, Dictionary<string, Matrix> nameDict){
List<MatrixExprWithData> currentResultsList = new List<MatrixExprWithData>();
List<Matrix> currentChildren = new List<Matrix>();
if (currentExpr != null){
foreach (SymbolicMatrixExpr child in currentExpr.children){
List<MatrixExprWithData> childList = evaluateRecursiveWithInputsAndType(child, nameDict);
currentChildren.Add ((Matrix) childList.Last().output);
currentResultsList.AddRange(childList);
}
MatrixExprWithData currentResult;
switch (currentExpr.exprType){
case MatrixExpressionType.Constant:
currentResult = new MatrixExprWithData(new Matrix[] {(Matrix) ((ConstantExpression) currentExpr.dataExp).Value}, currentExpr.exprType);
break;
case MatrixExpressionType.Parameter:
currentResult = new MatrixExprWithData(new Matrix[] {nameDict[((ParameterExpression) currentExpr.dataExp).Name]}, currentExpr.exprType);
break;
default:
currentResult = new MatrixExprWithData(currentChildren.ToArray(), currentExpr.exprType);
break;
}
currentResultsList.Add (currentResult);
}
return currentResultsList;
}
public static SymbolicMatrixExpr identity(int size){
Matrix identityMatrix = Matrix.Identity(size, size);
SymbolicMatrixExpr identityExpr = constantMatrix(identityMatrix, "I");
return identityExpr;
}
}
public class MatrixExprWithData{
public MatrixExpressionType exprType;
public Matrix[] inputs;
public Matrix output;
public MatrixExprWithData(Matrix[] inputs, MatrixExpressionType exprType){
this.inputs = (Matrix[]) inputs.Clone();
this.exprType = exprType;
switch (this.exprType){
//TODO: only evaluate unary or binary expressions currently, would like to extend to more general children structures
case MatrixExpressionType.Constant:
this.output = inputs[0];
break;
case MatrixExpressionType.Parameter:
this.output = inputs[0];
break;
case MatrixExpressionType.Transpose:
this.output = Matrix.Transpose(inputs[0]);
break;
case MatrixExpressionType.MatrixMultiply:
this.output = (inputs[0] * inputs[1]);
break;
case MatrixExpressionType.ScalarMultiply:
Matrix intermediate = inputs[1].Clone();
intermediate.Multiply(inputs[0].GetArray()[0][0]);
this.output = intermediate;
break;
case MatrixExpressionType.Add:
this.output = (inputs[0] + inputs[1]);
break;
case MatrixExpressionType.Subtract:
this.output = (inputs[0] - inputs[1]);
break;
default:
this.output = Matrix.Zeros(1);
break;
}
}
}
| {'content_hash': '0fc007bc2f179ea36be45b345a27d3cf', 'timestamp': '', 'source': 'github', 'line_count': 474, 'max_line_length': 144, 'avg_line_length': 34.675105485232066, 'alnum_prop': 0.7577269408615235, 'repo_name': 'zobot/VRMath', 'id': '74560788f55379955690ab82f40daed8c6477d47', 'size': '16438', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Assets/SymbolicMatrix.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '118649'}, {'name': 'C', 'bytes': '217930'}, {'name': 'C#', 'bytes': '591776'}, {'name': 'JavaScript', 'bytes': '5676'}]} |
package org.treeleaf.common.exception;
/**
* 调用服务逻辑异常
* <p/>
* Created by yaoshuhong on 2015/7/13.
*/
public class ServiceException extends BaseException implements RetCodeSupport {
/**
* 错误码
*/
private String retCode = RetCode.FAIL_LOGIC;
public ServiceException(String message) {
super(message);
}
public ServiceException(String retCode, String message) {
this(message);
this.retCode = retCode;
}
public ServiceException(String message, Throwable throwable) {
super(message, throwable);
}
public ServiceException(String retCode, String message, Throwable throwable) {
this(message, throwable);
this.retCode = retCode;
}
public String getRetCode() {
return retCode;
}
public void setRetCode(String retCode) {
this.retCode = retCode;
}
}
| {'content_hash': 'e643bb6e7a2468ca2e134698be97f538', 'timestamp': '', 'source': 'github', 'line_count': 40, 'max_line_length': 82, 'avg_line_length': 22.0, 'alnum_prop': 0.6454545454545455, 'repo_name': 'treeleafj/treeleaf', 'id': 'f4a1e6f9f4783f6db474367e5a99b4ccc8c155d4', 'size': '902', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'treeleaf-common/src/main/java/org/treeleaf/common/exception/ServiceException.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '245780'}]} |
sidebar_position: 5
---
# Insert
```sql title="SQL"
-- A :result value of :n below will return affected row count:
-- :name insert-character :! :n
-- :doc Insert a single character
insert into characters (name, specialty)
values (:name, :specialty)
-- :name insert-characters :! :n
-- :doc Insert multiple characters with :tuple* parameter type
insert into characters (name, specialty)
values :tuple*:characters
```
```clojure title="Clojure"
(characters/insert-character-sqlvec
{:name "Westley", :specialty "love"}) ;;=>
["insert into characters (name, specialty)
values (?, ?)"
,"Westley"
,"love"]
(characters/insert-character db
{:name "Westley", :specialty "love"}) ;;=>
1
(characters/insert-character db
{:name "Buttercup", :specialty "beauty"}) ;;=>
1
(characters/insert-characters-sqlvec
{:characters
[["Vizzini" "intelligence"]
["Fezzik" "strength"]
["Inigo Montoya" "swordmanship"]]}) ;;=>
["insert into characters (name, specialty)
values (?,?),(?,?),(?,?)"
,"Vizzini"
,"intelligence"
,"Fezzik"
,"strength"
,"Inigo Montoya"
,"swordmanship"]
(characters/insert-characters
db
{:characters
[["Vizzini" "intelligence"]
["Fezzik" "strength"]
["Inigo Montoya" "swordmanship"]]}) ;;=>
3
```
## Retrieving Last Inserted ID or Record
It is often the case that you want to return the record just inserted or at least the auto-generated ID. This functionality varies greatly across databases and JDBC drivers. HugSQL attempts to help where it can. You will need to choose an option that fits your database.
### Option #1: INSERT ... RETURNING
If your database supports the RETURNING clause of INSERT (e.g.,[Postgresql supports this](http://www.postgresql.org/docs/current/static/sql-insert.html)), you can specify your SQL insert statement command type to be `:returning-execute`, or `:<!` for short:
```sql title="SQL"
-- :name insert-into-test-table-returning :<!
-- :doc insert with an sql returning clause
insert into test (id, name) values (:id, :name) returning id
```
### Option #2: Get Generated Keys / Last Insert ID / Inserted Record
HugSQL's `:insert`, or `:i!` command type indicates to the underlying adapter that the insert should be performed, and then `.getGeneratedKeys` called in the jdbc driver. The return value of `.getGeneratedKeys` varies greatly across different databases and jdbc drivers. For example, see the following code from the HugSQL test suite:
```sql title="SQL"
-- :name insert-into-test-table-return-keys :insert :raw
insert into test (id, name) values (:id, :name)
```
```clojure title="Clojure"
(testing "insert w/ return of .getGeneratedKeys"
;; return generated keys, which has varying support and return values
;; clojure.java.jdbc returns a hashmap, clojure.jdbc returns a vector of hashmaps
(when (= adapter-name :clojure.java.jdbc)
(condp = db-name
:postgresql
(is (= {:id 8 :name "H"}
(insert-into-test-table-return-keys db {:id 8 :name "H"} {})))
:mysql
(is (= {:generated_key 9}
(insert-into-test-table-return-keys db {:id 9 :name "I"})))
:sqlite
(is (= {(keyword "last_insert_rowid()") 10}
(insert-into-test-table-return-keys db {:id 10 :name "J"} {})))
:h2
(is (= {(keyword "scope_identity()") 11}
(insert-into-test-table-return-keys db {:id 11 :name "J"} {})))
;; hsql and derby don't seem to support .getGeneratedKeys
nil))
(when (= adapter-name :clojure.jdbc)
(condp = db-name
:postgresql
(is (= [{:id 8 :name "H"}]
(insert-into-test-table-return-keys db {:id 8 :name "H"} {})))
:mysql
(is (= [{:generated_key 9}]
(insert-into-test-table-return-keys db {:id 9 :name "I"})))
:sqlite
(is (= [{(keyword "last_insert_rowid()") 10}]
(insert-into-test-table-return-keys db {:id 10 :name "J"} {})))
:h2
(is (= [{(keyword "scope_identity()") 11}]
(insert-into-test-table-return-keys db {:id 11 :name "J"} {})))
;; hsql and derby don't seem to support .getGeneratedKeys
nil)))
```
| {'content_hash': '37cdad28c2b08a50d6721bee69f5fe71', 'timestamp': '', 'source': 'github', 'line_count': 126, 'max_line_length': 334, 'avg_line_length': 32.666666666666664, 'alnum_prop': 0.6503887269193391, 'repo_name': 'layerware/hugsql', 'id': '93ff8060ab0ab1f7c0c49bf19e8ecf2f30972d35', 'size': '4120', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/hugsql.org/docs/using-hugsql/insert.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Clojure', 'bytes': '81123'}]} |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRolesTable extends Migration {
public function up()
{
Schema::create('roles', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->string('description');
$table->timestamps();
});
}
public function down()
{
Schema::drop('roles');
}
}
| {'content_hash': '179d5073f3848c09dfc02b384d19081e', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 54, 'avg_line_length': 17.958333333333332, 'alnum_prop': 0.6334106728538283, 'repo_name': 'cam-ila/subastayar', 'id': 'b96de68a093a34239a2c0833541edab23520764f', 'size': '431', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/database/migrations/2015_04_20_032633_create_roles_table.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '356'}, {'name': 'JavaScript', 'bytes': '1359'}, {'name': 'PHP', 'bytes': '179314'}, {'name': 'Shell', 'bytes': '252'}]} |
<?php
return [
'dashboard' => 'Panel de Control',
// Incidents
'incidents' => [
'title' => 'Incidencias y horario',
'incidents' => 'Incidentes',
'logged' => '{0} No hay incidencias, ¡buen trabajo!|Has registrado una incidencia.|Has reportado <strong>:count</strong> incidencias.',
'incident-create-template' => 'Crear plantilla',
'incident-templates' => 'Plantillas de incidente',
'add' => [
'title' => 'Reportar incidente',
'success' => 'Incidente agregado.',
'failure' => 'Hubo un error agregando el incidente, por favor intente de nuevo.',
],
'edit' => [
'title' => 'Editar un incidente',
'success' => 'Incidente actualizado.',
'failure' => 'Hubo un error editando el incidente, por favor intente de nuevo.',
],
'delete' => [
'success' => 'El incidente se ha eliminado y no se mostrará en tu página de estado.',
'failure' => 'El incidente no se pudo eliminar, por favor intente de nuevo.',
],
// Incident templates
'templates' => [
'title' => 'Plantillas de incidente',
'add' => [
'title' => 'Crear una plantilla de incidente',
'message' => 'Deberías añadir una plantilla de incidente.',
'success' => 'Su nueva plantilla de incidentes ha sido creada.',
'failure' => 'Algo salió mal con la plantilla de incidente.',
],
'edit' => [
'title' => 'Editar plantilla',
'success' => 'La plantilla de incidente ha sido actualizada.',
'failure' => 'Algo salió mal actualizando la plantilla de incidente',
],
'delete' => [
'success' => 'La plantilla de incidente se ha eliminado.',
'failure' => 'La plantilla de incidente no se pudo eliminar. Por favor, inténtalo de nuevo.',
],
],
],
// Incident Maintenance
'schedule' => [
'schedule' => 'Mantenimiento programado',
'logged' => '{0} No hay planificaciones, buen trabajo.|Has registrado una planificación.|Has registrado <strong>:count</strong> planificaciones.',
'scheduled_at' => 'Programado para :timestamp',
'add' => [
'title' => 'Agregar mantenimiento programado',
'success' => 'Planificación agregada.',
'failure' => 'Algo salió mal agregando la planificación, por favor intente de nuevo.',
],
'edit' => [
'title' => 'Editar Mantenimiento Programado',
'success' => 'La planificación ha sido actualizada!',
'failure' => 'Algo salió mal editando la planificación, por favor intente de nuevo.',
],
'delete' => [
'success' => 'La planificación ha sido eliminada y no será mostrada en su página de estado.',
'failure' => 'El mantenimiento programado no pudo ser eliminado, por favor, inténtelo de nuevo.',
],
],
// Components
'components' => [
'components' => 'Componentes',
'component_statuses' => 'Estatus de los componentes',
'listed_group' => 'Agrupado bajo :nombre',
'add' => [
'title' => 'Agregar componente',
'message' => 'Deberías agregar un componente.',
'success' => 'Componente creado.',
'failure' => 'Algo salió mal con el componente, por favor intente de nuevo.',
],
'edit' => [
'title' => 'Editar componente',
'success' => 'Componente actualizado.',
'failure' => 'Algo salió mal con el componente, por favor intente de nuevo.',
],
'delete' => [
'success' => 'El componente se ha eliminado!',
'failure' => 'El componente no pudo ser eliminado, por favor, inténtelo de nuevo.',
],
// Component groups
'groups' => [
'groups' => 'Grupo de componente|Grupos de componente',
'no_components' => 'Usted debería agregar un grupo de componentes.',
'add' => [
'title' => 'Agregar un grupo de componentes',
'success' => 'Grupo de componentes agregado.',
'failure' => 'Algo salió mal con el grupo de componentes, por favor vuelva a intentarlo.',
],
'edit' => [
'title' => 'Editar un grupo de componentes',
'success' => 'Grupo de componentes actualizado.',
'failure' => 'Algo salió mal con el grupo de componentes, por favor vuelva a intentarlo.',
],
'delete' => [
'success' => 'El grupo de componentes se ha eliminado!',
'failure' => 'El grupo de componentes no pudo ser eliminado, por favor, inténtelo de nuevo.',
],
],
],
// Metrics
'metrics' => [
'metrics' => 'Métricas',
'add' => [
'title' => 'Crear una métrica o indicador',
'message' => 'Deberías añadir una métrica.',
'success' => 'Métrica creada.',
'failure' => 'Algo salió mal con la métrica, por favor, inténtelo de nuevo.',
],
'edit' => [
'title' => 'Editar una métrica',
'success' => 'Métrica actualizada.',
'failure' => 'Algo salió mal con la métrica, por favor, inténtelo de nuevo.',
],
'delete' => [
'success' => 'La métrica se ha eliminado y no se mostrará más en tu página de estado.',
'failure' => 'La métrica no pudo ser eliminada, por favor, inténtelo de nuevo.',
],
],
// Subscribers
'subscribers' => [
'subscribers' => 'Suscriptores',
'description' => 'Los suscriptores recibirán actualizaciones por correo electrónico cuando se creen incidentes o se actualicen componentes.',
'verified' => 'Verificado',
'not_verified' => 'No confirmado',
'subscriber' => ':email, suscrito :date',
'no_subscriptions' => 'Suscrito a todas las actualizaciones',
'add' => [
'title' => 'Agregar un nuevo subscriptor',
'success' => 'Subscriptor agregado.',
'failure' => 'Algo salió mal al agregar el suscriptor, por favor, inténtelo de nuevo.',
'help' => 'Agregue cada subscriptor en una línea nueva.',
],
'edit' => [
'title' => 'Actualizar subscriptor',
'success' => 'Subscriptor actualizado.',
'failure' => 'Algo salió mal al editar el suscriptor, por favor, inténtelo de nuevo.',
],
],
// Team
'team' => [
'team' => 'Equipo',
'member' => 'Miembro',
'profile' => 'Perfil',
'description' => 'Los miembros del equipo será capaces de añadir, modificar y editar componentes e incidentes.',
'add' => [
'title' => 'Añadir a un nuevo miembro de equipo',
'success' => 'Miembro del equipo agregado.',
'failure' => 'No se pudo agregar el miembro del equipo, por favor vuelva a intentarlo.',
],
'edit' => [
'title' => 'Actualizar perfil',
'success' => 'Perfil actualizado.',
'failure' => 'Algo salió mal actualizando el perfil, por favor intente de nuevo.',
],
'delete' => [
'success' => 'El miembro del equipo ha sido eliminado y ya no tendrán acceso al Pane de Control!',
'failure' => 'No se pudo agregar el miembro del equipo, por favor vuelva a intentarlo.',
],
'invite' => [
'title' => 'Invitar a un nuevo miembro al equipo',
'success' => 'Se ha enviado una invitación',
'failure' => 'La invitación no pudo ser enviada, por favor intente de nuevo.',
],
],
// Settings
'settings' => [
'settings' => 'Ajustes',
'app-setup' => [
'app-setup' => 'Configuración de aplicación',
'images-only' => 'Sólo puedes subir imágenes.',
'too-big' => 'El archivo subido es demasiado grande. Sube una imagen con tamaño menor a: tamaño',
],
'analytics' => [
'analytics' => 'Analytics',
],
'localization' => [
'localization' => 'Localización',
],
'customization' => [
'customization' => 'Personalización',
'header' => 'Cabecera HTML personalizada',
'footer' => 'Pie HTML personalizado',
],
'security' => [
'security' => 'Seguridad',
'two-factor' => 'Usuarios sin autenticación de dos factores',
],
'stylesheet' => [
'stylesheet' => 'Hoja de estilo',
],
'theme' => [
'theme' => 'Tema',
],
'edit' => [
'success' => 'Configuración guardada.',
'failure' => 'La configuración no se podido guardar.',
],
'credits' => [
'credits' => 'Créditos',
'contributors' => 'Colaboradores',
'license' => 'Cachet es un proyecto de código libre bajo la licencia BSD-3, liberado por <a href="https://alt-three.com/?utm_source=cachet&utm_medium=credits&utm_campaign=Cachet%20Credit%20Dashboard" target="_blank">Alt Three Services Limited</a>.',
'backers-title' => 'Patrocinadores',
'backers' => 'Si desea apoyar futuros desarrollos, ingrese a la campaña de <a href="https://patreon.com/jbrooksuk" target="_blank">Cachet Patreon</a>.',
'thank-you' => 'Gracias a todos y cada uno de los :count colaboradores.',
],
],
// Login
'login' => [
'login' => 'Iniciar Sesión',
'logged_in' => 'Estás conectado.',
'welcome' => '¡Bienvenido!',
'two-factor' => 'Por favor ingresa tu token.',
],
// Sidebar footer
'help' => 'Ayuda',
'status_page' => 'Página de estado',
'logout' => 'Salir',
// Notifications
'notifications' => [
'notifications' => 'Notificaciones',
'awesome' => 'Excelente.',
'whoops' => 'Whoops.',
],
// Widgets
'widgets' => [
'support' => 'Apoye Cachet',
'support_subtitle' => '¡Visite nuestro proyecto en la página de <strong><a href="https://patreon.com/jbrooksuk" target="_blank">Patreon</a></strong>!',
'news' => 'Últimas noticias',
'news_subtitle' => 'Obtener las actualizaciones más recientes',
],
// Welcome modal
'welcome' => [
'welcome' => 'Bienvenido a tu página de estado!',
'message' => 'La página de estado está casi lista! Tal vez quieras configurar estos ajustes adicionales',
'close' => 'Llévame directamente a mi dashboard',
'steps' => [
'component' => 'Crear componentes',
'incident' => 'Crear incidentes',
'customize' => 'Personalizar',
'team' => 'Agregar Usuarios',
'api' => 'Generar token API',
'two-factor' => 'Autenticación de dos factores',
],
],
];
| {'content_hash': 'b8a13cb6276b6ac39eb9c908a43dc635', 'timestamp': '', 'source': 'github', 'line_count': 268, 'max_line_length': 267, 'avg_line_length': 43.100746268656714, 'alnum_prop': 0.5178772400657952, 'repo_name': 'MatheusRV/Cachet-Sandstorm', 'id': '1e7fb0677b69e940d8d1367b2f7aee0763c9a9fa', 'size': '11844', 'binary': False, 'copies': '13', 'ref': 'refs/heads/2.4', 'path': 'resources/lang/es/dashboard.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '553'}, {'name': "Cap'n Proto", 'bytes': '12139'}, {'name': 'HTML', 'bytes': '208257'}, {'name': 'JavaScript', 'bytes': '17937'}, {'name': 'Nginx', 'bytes': '2520'}, {'name': 'PHP', 'bytes': '3101616'}, {'name': 'Ruby', 'bytes': '4853'}, {'name': 'Shell', 'bytes': '4521'}]} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.spi.type;
import com.facebook.presto.spi.function.OperatorType;
import com.google.common.collect.ImmutableList;
import java.lang.invoke.MethodHandle;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.BooleanType.BOOLEAN;
import static com.facebook.presto.spi.type.DateType.DATE;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static com.facebook.presto.spi.type.HyperLogLogType.HYPER_LOG_LOG;
import static com.facebook.presto.spi.type.TestingIdType.ID;
import static com.facebook.presto.spi.type.TimestampType.TIMESTAMP;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.spi.type.VarcharType.VARCHAR;
public class TestingTypeManager
implements TypeManager
{
@Override
public Type getType(TypeSignature signature)
{
for (Type type : getTypes()) {
if (signature.getBase().equals(type.getTypeSignature().getBase())) {
return type;
}
}
return null;
}
@Override
public Type getParameterizedType(String baseTypeName, List<TypeSignatureParameter> typeParameters)
{
return getType(new TypeSignature(baseTypeName, typeParameters));
}
@Override
public List<Type> getTypes()
{
return ImmutableList.of(BOOLEAN, BIGINT, DOUBLE, VARCHAR, VARBINARY, TIMESTAMP, DATE, ID, HYPER_LOG_LOG);
}
@Override
public Collection<ParametricType> getParametricTypes()
{
return ImmutableList.of();
}
@Override
public Optional<Type> getCommonSuperType(Type firstType, Type secondType)
{
throw new UnsupportedOperationException();
}
@Override
public boolean canCoerce(Type actualType, Type expectedType)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isTypeOnlyCoercion(Type actualType, Type expectedType)
{
return false;
}
@Override
public Optional<Type> coerceTypeBase(Type sourceType, String resultTypeBase)
{
throw new UnsupportedOperationException();
}
@Override
public MethodHandle resolveOperator(OperatorType operatorType, List<? extends Type> argumentTypes)
{
throw new UnsupportedOperationException();
}
}
| {'content_hash': '48c5f5a888db4c87532695cd9b170d98', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 113, 'avg_line_length': 31.57894736842105, 'alnum_prop': 0.724, 'repo_name': 'raghavsethi/presto', 'id': '0dee5926b1dd9adefac52a675b9d563f55660658', 'size': '3000', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'presto-spi/src/test/java/com/facebook/presto/spi/type/TestingTypeManager.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '26997'}, {'name': 'CSS', 'bytes': '13018'}, {'name': 'HTML', 'bytes': '28633'}, {'name': 'Java', 'bytes': '31909074'}, {'name': 'JavaScript', 'bytes': '214692'}, {'name': 'Makefile', 'bytes': '6830'}, {'name': 'PLSQL', 'bytes': '2797'}, {'name': 'PLpgSQL', 'bytes': '11504'}, {'name': 'Python', 'bytes': '7664'}, {'name': 'SQLPL', 'bytes': '926'}, {'name': 'Shell', 'bytes': '29871'}, {'name': 'Thrift', 'bytes': '12631'}]} |
package cloud.orbit.actors.test;
import cloud.orbit.actors.Actor;
import cloud.orbit.actors.Stage;
import cloud.orbit.actors.runtime.AbstractActor;
import cloud.orbit.concurrent.Task;
import org.junit.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.fail;
@SuppressWarnings("unused")
public class ReactivationTest extends ActorBaseTest
{
public interface Hello extends Actor
{
Task<String> sayHello(String greeting);
}
public static class HelloActor extends AbstractActor implements Hello
{
@Override
public Task<String> sayHello(final String greeting)
{
return Task.fromValue(greeting);
}
}
@Test()
public void twoStagesSameActor() throws ExecutionException, InterruptedException, TimeoutException
{
clock.stop();
Stage stage1 = createStage();
Stage stage2 = createStage();
Hello hello = Actor.getReference(Hello.class, "1");
for (int i = 0; i < 100; i++)
{
hello.sayHello("bla " + i).get(5, TimeUnit.SECONDS);
clock.incrementTimeMillis(TimeUnit.HOURS.toMillis(1));
stage1.cleanup().join();
stage2.cleanup().join();
}
dumpMessages();
}
}
| {'content_hash': '648125bc4ed5bd489d4485f8ed95aa53', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 102, 'avg_line_length': 25.92452830188679, 'alnum_prop': 0.6637554585152838, 'repo_name': 'FieldFlux/orbit', 'id': '99ed9c8c01c714e2347c5c50df40b86f3bec8f0e', 'size': '2919', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'actors/test/actor-tests/src/test/java/cloud/orbit/actors/test/ReactivationTest.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '1568309'}]} |
/**
* The `angular2` is the single place to import all of the individual types.
*/
export {commonBootstrap as bootstrap} from 'angular2/src/core/application_common';
// TODO(someone familiar with systemjs): the exports below are copied from
// angular2_exports.ts. Re-exporting from angular2_exports.ts causes systemjs
// to resolve imports very very very slowly. See also a similar notice in
// bootstrap.ts
export * from './annotations';
export * from './change_detection';
export * from './core';
export * from './di';
export * from './directives';
export * from './http';
export * from './forms';
export * from './render';
| {'content_hash': 'bf1adcf00522a4fd02edb737bbf5c173', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 82, 'avg_line_length': 37.05882352941177, 'alnum_prop': 0.719047619047619, 'repo_name': 'Zex/angular', 'id': '08fdd54b1fdc38bcf154af556a4dda100899b3cc', 'size': '630', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'modules/angular2/angular2.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '56049'}, {'name': 'Dart', 'bytes': '431021'}, {'name': 'HTML', 'bytes': '49687'}, {'name': 'JavaScript', 'bytes': '111683'}, {'name': 'Shell', 'bytes': '16735'}, {'name': 'TypeScript', 'bytes': '2336210'}]} |
using Prism.Commands;
using Prism.Events;
using Prism.Windows.AppModel;
using Prism.Windows.Mvvm;
using Prism.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using $safeprojectname$.ViewModels;
// TODO: Sort usings and remove this Code Analysis suppression
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.Analyzers", "SA1210", Justification = "Template can't sort project's using")]
namespace $safeprojectname$.PageViewModels
{
public class MenuViewModel : ViewModelBase
{
private const string CurrentPageTokenKey = "CurrentPageToken";
private Dictionary<PageTokens, bool> _canNavigateLookup;
private PageTokens _currentPageToken;
private INavigationService _navigationService;
private ISessionStateService _sessionStateService;
public MenuViewModel(IEventAggregator eventAggregator, INavigationService navigationService, IResourceLoader resourceLoader, ISessionStateService sessionStateService)
{
eventAggregator.GetEvent<NavigationStateChangedEvent>().Subscribe(OnNavigationStateChanged);
_navigationService = navigationService;
_sessionStateService = sessionStateService;
Commands = new ObservableCollection<MenuItemViewModel>
{
new MenuItemViewModel { DisplayName = resourceLoader.GetString("MainPageMenuItemDisplayName"), FontIcon = "\ue19f", Command = new DelegateCommand(() => NavigateToPage(PageTokens.Main), () => CanNavigateToPage(PageTokens.Main)) },
};
_canNavigateLookup = new Dictionary<PageTokens, bool>();
foreach (PageTokens pageToken in Enum.GetValues(typeof(PageTokens)))
{
_canNavigateLookup.Add(pageToken, true);
}
if (_sessionStateService.SessionState.ContainsKey(CurrentPageTokenKey))
{
// Resuming, so update the menu to reflect the current page correctly
PageTokens currentPageToken;
if (Enum.TryParse(_sessionStateService.SessionState[CurrentPageTokenKey].ToString(), out currentPageToken))
{
UpdateCanNavigateLookup(currentPageToken);
RaiseCanExecuteChanged();
}
}
}
public ObservableCollection<MenuItemViewModel> Commands { get; set; }
private void OnNavigationStateChanged(NavigationStateChangedEventArgs args)
{
PageTokens currentPageToken;
if (Enum.TryParse(args.Sender.Content.GetType().Name.Replace("Page", string.Empty), out currentPageToken))
{
_sessionStateService.SessionState[CurrentPageTokenKey] = currentPageToken.ToString();
UpdateCanNavigateLookup(currentPageToken);
RaiseCanExecuteChanged();
}
}
private void NavigateToPage(PageTokens pageToken)
{
if (CanNavigateToPage(pageToken))
{
_navigationService.Navigate(pageToken.ToString(), null);
}
}
private bool CanNavigateToPage(PageTokens pageToken)
{
return _canNavigateLookup[pageToken];
}
private void UpdateCanNavigateLookup(PageTokens navigatedTo)
{
_canNavigateLookup[_currentPageToken] = true;
_canNavigateLookup[navigatedTo] = false;
_currentPageToken = navigatedTo;
}
private void RaiseCanExecuteChanged()
{
foreach (var item in Commands)
{
(item.Command as DelegateCommand).RaiseCanExecuteChanged();
}
}
}
}
| {'content_hash': '6c5f14dddd4cd4baeb406185d920effa', 'timestamp': '', 'source': 'github', 'line_count': 98, 'max_line_length': 245, 'avg_line_length': 39.08163265306123, 'alnum_prop': 0.6579634464751958, 'repo_name': 'ali-hk/Toolkit', 'id': '3c8f0a0e3540d2fd2fb7247f4f47ad647cdcd391', 'size': '3832', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/ToolkitTemplatePack/ProjectTemplates/PrismToolkitHamburgerMenuApp/PageViewModels/MenuViewModel.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '368352'}, {'name': 'CSS', 'bytes': '1868'}, {'name': 'HTML', 'bytes': '3517'}, {'name': 'PowerShell', 'bytes': '1468'}]} |
#pragma once
#include <aws/events/CloudWatchEvents_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/events/model/RemoveTargetsResultEntry.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace CloudWatchEvents
{
namespace Model
{
class AWS_CLOUDWATCHEVENTS_API RemoveTargetsResult
{
public:
RemoveTargetsResult();
RemoveTargetsResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
RemoveTargetsResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The number of failed entries.</p>
*/
inline int GetFailedEntryCount() const{ return m_failedEntryCount; }
/**
* <p>The number of failed entries.</p>
*/
inline void SetFailedEntryCount(int value) { m_failedEntryCount = value; }
/**
* <p>The number of failed entries.</p>
*/
inline RemoveTargetsResult& WithFailedEntryCount(int value) { SetFailedEntryCount(value); return *this;}
/**
* <p>The failed target entries.</p>
*/
inline const Aws::Vector<RemoveTargetsResultEntry>& GetFailedEntries() const{ return m_failedEntries; }
/**
* <p>The failed target entries.</p>
*/
inline void SetFailedEntries(const Aws::Vector<RemoveTargetsResultEntry>& value) { m_failedEntries = value; }
/**
* <p>The failed target entries.</p>
*/
inline void SetFailedEntries(Aws::Vector<RemoveTargetsResultEntry>&& value) { m_failedEntries = std::move(value); }
/**
* <p>The failed target entries.</p>
*/
inline RemoveTargetsResult& WithFailedEntries(const Aws::Vector<RemoveTargetsResultEntry>& value) { SetFailedEntries(value); return *this;}
/**
* <p>The failed target entries.</p>
*/
inline RemoveTargetsResult& WithFailedEntries(Aws::Vector<RemoveTargetsResultEntry>&& value) { SetFailedEntries(std::move(value)); return *this;}
/**
* <p>The failed target entries.</p>
*/
inline RemoveTargetsResult& AddFailedEntries(const RemoveTargetsResultEntry& value) { m_failedEntries.push_back(value); return *this; }
/**
* <p>The failed target entries.</p>
*/
inline RemoveTargetsResult& AddFailedEntries(RemoveTargetsResultEntry&& value) { m_failedEntries.push_back(std::move(value)); return *this; }
private:
int m_failedEntryCount;
Aws::Vector<RemoveTargetsResultEntry> m_failedEntries;
};
} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws
| {'content_hash': '94b25de8047891c573a25a0572e8641b', 'timestamp': '', 'source': 'github', 'line_count': 93, 'max_line_length': 149, 'avg_line_length': 28.612903225806452, 'alnum_prop': 0.6940999624201428, 'repo_name': 'JoyIfBam5/aws-sdk-cpp', 'id': '2525a15fda647c167a8afffea822ec65da0418a3', 'size': '3234', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'aws-cpp-sdk-events/include/aws/events/model/RemoveTargetsResult.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '11868'}, {'name': 'C++', 'bytes': '167818064'}, {'name': 'CMake', 'bytes': '591577'}, {'name': 'HTML', 'bytes': '4471'}, {'name': 'Java', 'bytes': '271801'}, {'name': 'Python', 'bytes': '85650'}, {'name': 'Shell', 'bytes': '5277'}]} |
package main
import (
"fmt"
"io"
"path/filepath"
"github.com/spf13/cobra"
"k8s.io/helm/pkg/repo"
)
const repoIndexDesc = `
Read the current directory and generate an index file based on the charts found.
This tool is used for creating an 'index.yaml' file for a chart repository. To
set an absolute URL to the charts, use '--url' flag.
To merge the generated index with an existing index file, use the '--merge'
flag. In this case, the charts found in the current directory will be merged
into the existing index, with local charts taking priority over existing charts.
`
type repoIndexCmd struct {
dir string
url string
out io.Writer
merge string
}
func newRepoIndexCmd(out io.Writer) *cobra.Command {
index := &repoIndexCmd{
out: out,
}
cmd := &cobra.Command{
Use: "index [flags] [DIR]",
Short: "generate an index file given a directory containing packaged charts",
Long: repoIndexDesc,
RunE: func(cmd *cobra.Command, args []string) error {
if err := checkArgsLength(len(args), "path to a directory"); err != nil {
return err
}
index.dir = args[0]
return index.run()
},
}
f := cmd.Flags()
f.StringVar(&index.url, "url", "", "url of chart repository")
f.StringVar(&index.merge, "merge", "", "merge the generated index into the given index")
return cmd
}
func (i *repoIndexCmd) run() error {
path, err := filepath.Abs(i.dir)
if err != nil {
return err
}
return index(path, i.url, i.merge)
}
func index(dir, url, mergeTo string) error {
out := filepath.Join(dir, "index.yaml")
i, err := repo.IndexDirectory(dir, url)
if err != nil {
return err
}
if mergeTo != "" {
i2, err := repo.LoadIndexFile(mergeTo)
if err != nil {
return fmt.Errorf("Merge failed: %s", err)
}
i.Merge(i2)
}
i.SortEntries()
return i.WriteFile(out, 0755)
}
| {'content_hash': '5c36e58a779bcf14660cc3e861d3fd1d', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 89, 'avg_line_length': 21.48235294117647, 'alnum_prop': 0.6757940854326396, 'repo_name': 'iamzhout/helm', 'id': 'ad5808946536902b3f7314209586e87907a7a327', 'size': '2415', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'cmd/helm/repo_index.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '788836'}, {'name': 'Makefile', 'bytes': '5942'}, {'name': 'Protocol Buffer', 'bytes': '22507'}, {'name': 'Shell', 'bytes': '53675'}, {'name': 'Smarty', 'bytes': '579'}]} |
/**
* @coreapi
* @module resolve
*/ /** for typedoc */
import { extend, identity } from "../common/common";
import { services } from "../common/coreservices";
import { trace } from "../common/trace";
import { stringify } from "../common/strings";
import { isFunction, isObject } from "../common/predicates";
// TODO: explicitly make this user configurable
export var defaultResolvePolicy = {
when: "LAZY",
async: "WAIT"
};
/**
* The basic building block for the resolve system.
*
* Resolvables encapsulate a state's resolve's resolveFn, the resolveFn's declared dependencies, the wrapped (.promise),
* and the unwrapped-when-complete (.data) result of the resolveFn.
*
* Resolvable.get() either retrieves the Resolvable's existing promise, or else invokes resolve() (which invokes the
* resolveFn) and returns the resulting promise.
*
* Resolvable.get() and Resolvable.resolve() both execute within a context path, which is passed as the first
* parameter to those fns.
*/
var Resolvable = (function () {
function Resolvable(arg1, resolveFn, deps, policy, data) {
this.resolved = false;
this.promise = undefined;
if (arg1 instanceof Resolvable) {
extend(this, arg1);
}
else if (isFunction(resolveFn)) {
if (arg1 == null || arg1 == undefined)
throw new Error("new Resolvable(): token argument is required");
if (!isFunction(resolveFn))
throw new Error("new Resolvable(): resolveFn argument must be a function");
this.token = arg1;
this.policy = policy;
this.resolveFn = resolveFn;
this.deps = deps || [];
this.data = data;
this.resolved = data !== undefined;
this.promise = this.resolved ? services.$q.when(this.data) : undefined;
}
else if (isObject(arg1) && arg1.token && isFunction(arg1.resolveFn)) {
var literal = arg1;
return new Resolvable(literal.token, literal.resolveFn, literal.deps, literal.policy, literal.data);
}
}
Resolvable.prototype.getPolicy = function (state) {
var thisPolicy = this.policy || {};
var statePolicy = state && state.resolvePolicy || {};
return {
when: thisPolicy.when || statePolicy.when || defaultResolvePolicy.when,
async: thisPolicy.async || statePolicy.async || defaultResolvePolicy.async,
};
};
/**
* Asynchronously resolve this Resolvable's data
*
* Given a ResolveContext that this Resolvable is found in:
* Wait for this Resolvable's dependencies, then invoke this Resolvable's function
* and update the Resolvable's state
*/
Resolvable.prototype.resolve = function (resolveContext, trans) {
var _this = this;
var $q = services.$q;
// Gets all dependencies from ResolveContext and wait for them to be resolved
var getResolvableDependencies = function () {
return $q.all(resolveContext.getDependencies(_this).map(function (r) {
return r.get(resolveContext, trans);
}));
};
// Invokes the resolve function passing the resolved dependencies as arguments
var invokeResolveFn = function (resolvedDeps) {
return _this.resolveFn.apply(null, resolvedDeps);
};
/**
* For RXWAIT policy:
*
* Given an observable returned from a resolve function:
* - enables .cache() mode (this allows multicast subscribers)
* - then calls toPromise() (this triggers subscribe() and thus fetches)
* - Waits for the promise, then return the cached observable (not the first emitted value).
*/
var waitForRx = function (observable$) {
var cached = observable$.cache(1);
return cached.take(1).toPromise().then(function () { return cached; });
};
// If the resolve policy is RXWAIT, wait for the observable to emit something. otherwise pass through.
var node = resolveContext.findNode(this);
var state = node && node.state;
var maybeWaitForRx = this.getPolicy(state).async === "RXWAIT" ? waitForRx : identity;
// After the final value has been resolved, update the state of the Resolvable
var applyResolvedValue = function (resolvedValue) {
_this.data = resolvedValue;
_this.resolved = true;
trace.traceResolvableResolved(_this, trans);
return _this.data;
};
// Sets the promise property first, then getsResolvableDependencies in the context of the promise chain. Always waits one tick.
return this.promise = $q.when()
.then(getResolvableDependencies)
.then(invokeResolveFn)
.then(maybeWaitForRx)
.then(applyResolvedValue);
};
/**
* Gets a promise for this Resolvable's data.
*
* Fetches the data and returns a promise.
* Returns the existing promise if it has already been fetched once.
*/
Resolvable.prototype.get = function (resolveContext, trans) {
return this.promise || this.resolve(resolveContext, trans);
};
Resolvable.prototype.toString = function () {
return "Resolvable(token: " + stringify(this.token) + ", requires: [" + this.deps.map(stringify) + "])";
};
Resolvable.prototype.clone = function () {
return new Resolvable(this);
};
return Resolvable;
}());
export { Resolvable };
Resolvable.fromData = function (token, data) {
return new Resolvable(token, function () { return data; }, null, null, data);
};
//# sourceMappingURL=resolvable.js.map | {'content_hash': '7fd8627de1b3dfe6a7a9572e85685f10', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 135, 'avg_line_length': 43.69465648854962, 'alnum_prop': 0.6291055206149546, 'repo_name': 'suryagangula/empower', 'id': 'b03e83e6e8579191db85a234e4f16c6ade32150b', 'size': '5724', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'node_modules/ui-router-visualizer/node_modules/ui-router-core/lib-esm/resolve/resolvable.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5883'}, {'name': 'HTML', 'bytes': '13345'}, {'name': 'JavaScript', 'bytes': '24923'}]} |
<?php
/**
* The "operations" collection of methods.
* Typical usage is:
* <code>
* $appengineService = new Google_Service_Appengine(...);
* $operations = $appengineService->operations;
* </code>
*/
class Google_Service_Appengine_Resource_AppsOperations extends Google_Service_Resource
{
/**
* Gets the latest state of a long-running operation. Clients can use this
* method to poll the operation result at intervals as recommended by the API
* service. (operations.get)
*
* @param string $appsId Part of `name`. The name of the operation resource.
* @param string $operationsId Part of `name`. See documentation of `appsId`.
* @param array $optParams Optional parameters.
* @return Google_Service_Appengine_Operation
*/
public function get($appsId, $operationsId, $optParams = array())
{
$params = array('appsId' => $appsId, 'operationsId' => $operationsId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Appengine_Operation");
}
/**
* Lists operations that match the specified filter in the request. If the
* server doesn't support this method, it returns UNIMPLEMENTED.NOTE: the name
* binding allows API services to override the binding to use different resource
* name schemes, such as users/operations. To override the binding, API services
* can add a binding such as "/v1/{name=users}/operations" to their service
* configuration. For backwards compatibility, the default name includes the
* operations collection id, however overriding users must ensure the name
* binding is the parent resource, without the operations collection id.
* (operations.listAppsOperations)
*
* @param string $appsId Part of `name`. The name of the operation's parent
* resource.
* @param array $optParams Optional parameters.
*
* @opt_param string pageToken The standard list page token.
* @opt_param string filter The standard list filter.
* @opt_param int pageSize The standard list page size.
* @return Google_Service_Appengine_ListOperationsResponse
*/
public function listAppsOperations($appsId, $optParams = array())
{
$params = array('appsId' => $appsId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "Google_Service_Appengine_ListOperationsResponse");
}
}
| {'content_hash': '9cc850e9fffbc7de39033c4c229fd6ae', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 98, 'avg_line_length': 42.642857142857146, 'alnum_prop': 0.7110552763819096, 'repo_name': 'phil-davis/core', 'id': '4995ed0b6eaef32cdc943c8854852e597089a920', 'size': '2978', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'apps/files_external/3rdparty/google/apiclient-services/src/Google/Service/Appengine/Resource/AppsOperations.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dockerfile', 'bytes': '262'}, {'name': 'Makefile', 'bytes': '473'}, {'name': 'Shell', 'bytes': '8644'}]} |
'use strict';
require('itsa-jsext');
const fetch = require('itsa-fetch'),
Classes = require('itsa-classes');
const BaseClass = Classes.createClass(function(config) {
const instance = this;
instance.cookieName = config.cookieName;
instance.router = config.router;
instance.io = fetch.io;
},
{
defineProps(props) {
const instance = this;
if (typeof props==='object') {
return instance.router.reloadView(false, {
'x-cookie': instance.cookieName,
'x-cookieprops': JSON.stringify(props),
'x-action': 'define'
}).then(() => {
if (instance.cookieName==='itsa-bodydata') {
instance.defineBodyAttrs(props);
}
});
}
},
setProps(props) {
const instance = this;
if (typeof props==='object') {
if (instance.cookieName==='itsa-bodydata') {
// immediately set the data-attr --> do not wait for server-response: we want a quick UI
instance.addBodyAttrs(props);
}
return instance.router.reloadView(false, {
'x-cookie': instance.cookieName,
'x-cookieprops': JSON.stringify(props),
'x-action': 'set'
});
}
},
deleteProp(key) {
const instance = this;
if ((typeof key==='string') && (key!=='')) {
return instance.router.reloadView(false, {
'x-cookie': instance.cookieName,
'x-key': key,
'x-action': 'delete'
}).then(() => {
if (instance.cookieName==='itsa-bodydata') {
instance.removeBodyAttrs(key);
}
});
}
},
removeCookie() {
const instance = this;
return instance.router.reloadView(false, {
'x-cookie': instance.cookieName,
'x-action': 'remove'
}).then(() => {
if (instance.cookieName==='itsa-bodydata') {
instance.clearBodyAttrs();
}
});
},
changeTtl(ms) {
const instance = this;
return instance.router.reloadView(false, {
'x-cookie': instance.cookieName,
'x-ms': ms,
'x-action': 'ttl'
});
},
_getAttributeList() {
let list = {};
Array.prototype.forEach.call(document.body.attributes, item => {
if (item.name.itsa_startsWith('data-', true)) {
list[item.name] = item.value;
}
});
return list;
},
defineBodyAttrs(props) {
// make a list of all current attributes and store them in a temp list:
let currentProps = this._getAttributeList();
// add all the attributes that are required
props.itsa_each((value, key) => {
// check is attribute is already defined (and the same). Only take action is there is a difference
if (currentProps['data-'+key]!==value) {
document.body.setAttribute('data-'+key, value);
// remove from the tempPros-list, because whatever this list remains should eventually be removed
delete currentProps['data-'+key];
}
});
// remove whatever is remained inside tempPros-list:
currentProps.itsa_each((value, key) => {
this.removeBodyAttrs(key);
});
},
addBodyAttrs(props) {
let currentProps = this._getAttributeList();
// add all the attributes that are required
props.itsa_each((value, key) => {
// check is attribute is already defined (and the same). Only take action is there is a difference
if (currentProps['data-'+key]!==value) {
document.body.setAttribute('data-'+key, value);
}
});
},
removeBodyAttrs(key) {
document.body.removeAttribute('data-'+key);
},
clearBodyAttrs() {
let currentProps = this._getAttributeList();
currentProps.itsa_each((value, key) => {
this.removeBodyAttrs(key);
});
},
destroy() {
this.io.abortAll();
}
});
module.exports = BaseClass;
| {'content_hash': 'c0893844ee11095cac06e9378cf29d1a', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 113, 'avg_line_length': 33.4296875, 'alnum_prop': 0.5225519981304043, 'repo_name': 'itsa-server/itsa-react-server', 'id': 'e1cd1f7736bf0141b569a153085afb31ea9e5216', 'size': '4448', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/hapi-plugin/cookies/client-cookie-base.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'JavaScript', 'bytes': '232325'}, {'name': 'Shell', 'bytes': '528'}]} |
//
// Copyright (c) 2000-2002
// Joerg Walter, Mathias Koch
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// The authors gratefully acknowledge the support of
// GeNeSys mbH & Co. KG in producing this work.
//
#ifndef BOOST_UBLAS_STORAGE_H
#define BOOST_UBLAS_STORAGE_H
#include <algorithm>
#ifdef BOOST_UBLAS_SHALLOW_ARRAY_ADAPTOR
#include <boost/shared_array.hpp>
#endif
#include <boost/serialization/array.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/numeric/ublas/exception.hpp>
#include <boost/numeric/ublas/traits.hpp>
#include <boost/numeric/ublas/detail/iterator.hpp>
namespace boost { namespace numeric { namespace ublas {
// Base class for Storage Arrays - see the Barton Nackman trick
template<class E>
class storage_array:
private nonassignable {
};
// Unbounded array - with allocator
template<class T, class ALLOC>
class unbounded_array:
public storage_array<unbounded_array<T, ALLOC> > {
typedef unbounded_array<T, ALLOC> self_type;
public:
typedef ALLOC allocator_type;
typedef typename ALLOC::size_type size_type;
typedef typename ALLOC::difference_type difference_type;
typedef T value_type;
typedef const T &const_reference;
typedef T &reference;
typedef const T *const_pointer;
typedef T *pointer;
typedef const_pointer const_iterator;
typedef pointer iterator;
// Construction and destruction
explicit BOOST_UBLAS_INLINE
unbounded_array (const ALLOC &a = ALLOC()):
alloc_ (a), size_ (0) {
data_ = 0;
}
explicit BOOST_UBLAS_INLINE
unbounded_array (size_type size, const ALLOC &a = ALLOC()):
alloc_(a), size_ (size) {
if (size_) {
data_ = alloc_.allocate (size_);
if (! detail::has_trivial_constructor<T>::value) {
for (pointer d = data_; d != data_ + size_; ++d)
alloc_.construct(d, value_type());
}
}
else
data_ = 0;
}
// No value initialised, but still be default constructed
BOOST_UBLAS_INLINE
unbounded_array (size_type size, const value_type &init, const ALLOC &a = ALLOC()):
alloc_ (a), size_ (size) {
if (size_) {
data_ = alloc_.allocate (size_);
std::uninitialized_fill (begin(), end(), init);
}
else
data_ = 0;
}
BOOST_UBLAS_INLINE
unbounded_array (const unbounded_array &c):
storage_array<unbounded_array<T, ALLOC> >(),
alloc_ (c.alloc_), size_ (c.size_) {
if (size_) {
data_ = alloc_.allocate (size_);
std::uninitialized_copy (c.begin(), c.end(), begin());
}
else
data_ = 0;
}
BOOST_UBLAS_INLINE
~unbounded_array () {
if (size_) {
if (! detail::has_trivial_destructor<T>::value) {
// std::_Destroy (begin(), end(), alloc_);
const iterator i_end = end();
for (iterator i = begin (); i != i_end; ++i) {
iterator_destroy (i);
}
}
alloc_.deallocate (data_, size_);
}
}
// Resizing
private:
BOOST_UBLAS_INLINE
void resize_internal (const size_type size, const value_type init, const bool preserve) {
if (size != size_) {
pointer p_data = data_;
if (size) {
data_ = alloc_.allocate (size);
if (preserve) {
pointer si = p_data;
pointer di = data_;
if (size < size_) {
for (; di != data_ + size; ++di) {
alloc_.construct (di, *si);
++si;
}
}
else {
for (; si != p_data + size_; ++si) {
alloc_.construct (di, *si);
++di;
}
for (; di != data_ + size; ++di) {
alloc_.construct (di, init);
}
}
}
else {
if (! detail::has_trivial_constructor<T>::value) {
for (pointer di = data_; di != data_ + size; ++di)
alloc_.construct (di, value_type());
}
}
}
if (size_) {
if (! detail::has_trivial_destructor<T>::value) {
for (pointer si = p_data; si != p_data + size_; ++si)
alloc_.destroy (si);
}
alloc_.deallocate (p_data, size_);
}
if (!size)
data_ = 0;
size_ = size;
}
}
public:
BOOST_UBLAS_INLINE
void resize (size_type size) {
resize_internal (size, value_type (), false);
}
BOOST_UBLAS_INLINE
void resize (size_type size, value_type init) {
resize_internal (size, init, true);
}
// Random Access Container
BOOST_UBLAS_INLINE
size_type max_size () const {
return ALLOC ().max_size();
}
BOOST_UBLAS_INLINE
bool empty () const {
return size_ == 0;
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
reference operator [] (size_type i) {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
// Assignment
BOOST_UBLAS_INLINE
unbounded_array &operator = (const unbounded_array &a) {
if (this != &a) {
resize (a.size_);
std::copy (a.data_, a.data_ + a.size_, data_);
}
return *this;
}
BOOST_UBLAS_INLINE
unbounded_array &assign_temporary (unbounded_array &a) {
swap (a);
return *this;
}
// Swapping
BOOST_UBLAS_INLINE
void swap (unbounded_array &a) {
if (this != &a) {
std::swap (size_, a.size_);
std::swap (data_, a.data_);
}
}
BOOST_UBLAS_INLINE
friend void swap (unbounded_array &a1, unbounded_array &a2) {
a1.swap (a2);
}
BOOST_UBLAS_INLINE
const_iterator begin () const {
return data_;
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return data_ + size_;
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
BOOST_UBLAS_INLINE
iterator begin () {
return data_;
}
BOOST_UBLAS_INLINE
iterator end () {
return data_ + size_;
}
// Reverse iterators
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
reverse_iterator rbegin () {
return reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
reverse_iterator rend () {
return reverse_iterator (begin ());
}
// Allocator
allocator_type get_allocator () {
return alloc_;
}
private:
friend class boost::serialization::access;
// Serialization
template<class Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
serialization::collection_size_type s(size_);
ar & serialization::make_nvp("size",s);
if ( Archive::is_loading::value ) {
resize(s);
}
ar & serialization::make_array(data_, s);
}
private:
// Handle explict destroy on a (possibly indexed) iterator
BOOST_UBLAS_INLINE
static void iterator_destroy (iterator &i) {
(&(*i)) -> ~value_type ();
}
ALLOC alloc_;
size_type size_;
pointer data_;
};
// Bounded array - with allocator for size_type and difference_type
template<class T, std::size_t N, class ALLOC>
class bounded_array:
public storage_array<bounded_array<T, N, ALLOC> > {
typedef bounded_array<T, N, ALLOC> self_type;
public:
// No allocator_type as ALLOC is not used for allocation
typedef typename ALLOC::size_type size_type;
typedef typename ALLOC::difference_type difference_type;
typedef T value_type;
typedef const T &const_reference;
typedef T &reference;
typedef const T *const_pointer;
typedef T *pointer;
typedef const_pointer const_iterator;
typedef pointer iterator;
// Construction and destruction
BOOST_UBLAS_INLINE
bounded_array ():
size_ (0) /*, data_ ()*/ { // size 0 - use bounded_vector to default construct with size N
}
explicit BOOST_UBLAS_INLINE
bounded_array (size_type size):
size_ (size) /*, data_ ()*/ {
BOOST_UBLAS_CHECK (size_ <= N, bad_size ());
// data_ (an array) elements are already default constructed
}
BOOST_UBLAS_INLINE
bounded_array (size_type size, const value_type &init):
size_ (size) /*, data_ ()*/ {
BOOST_UBLAS_CHECK (size_ <= N, bad_size ());
// ISSUE elements should be value constructed here, but we must fill instead as already default constructed
std::fill (begin(), end(), init) ;
}
BOOST_UBLAS_INLINE
bounded_array (const bounded_array &c):
size_ (c.size_) {
// ISSUE elements should be copy constructed here, but we must copy instead as already default constructed
std::copy (c.begin(), c.end(), begin());
}
// Resizing
BOOST_UBLAS_INLINE
void resize (size_type size) {
BOOST_UBLAS_CHECK (size <= N, bad_size ());
size_ = size;
}
BOOST_UBLAS_INLINE
void resize (size_type size, value_type init) {
BOOST_UBLAS_CHECK (size <= N, bad_size ());
if (size > size_)
std::fill (data_ + size_, data_ + size, init);
size_ = size;
}
// Random Access Container
BOOST_UBLAS_INLINE
size_type max_size () const {
return ALLOC ().max_size();
}
BOOST_UBLAS_INLINE
bool empty () const {
return size_ == 0;
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
reference operator [] (size_type i) {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
// Assignment
BOOST_UBLAS_INLINE
bounded_array &operator = (const bounded_array &a) {
if (this != &a) {
resize (a.size_);
std::copy (a.data_, a.data_ + a.size_, data_);
}
return *this;
}
BOOST_UBLAS_INLINE
bounded_array &assign_temporary (bounded_array &a) {
*this = a;
return *this;
}
// Swapping
BOOST_UBLAS_INLINE
void swap (bounded_array &a) {
if (this != &a) {
std::swap (size_, a.size_);
std::swap_ranges (data_, data_ + (std::max) (size_, a.size_), a.data_);
}
}
BOOST_UBLAS_INLINE
friend void swap (bounded_array &a1, bounded_array &a2) {
a1.swap (a2);
}
BOOST_UBLAS_INLINE
const_iterator begin () const {
return data_;
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return data_ + size_;
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
BOOST_UBLAS_INLINE
iterator begin () {
return data_;
}
BOOST_UBLAS_INLINE
iterator end () {
return data_ + size_;
}
// Reverse iterators
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
reverse_iterator rbegin () {
return reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
reverse_iterator rend () {
return reverse_iterator (begin ());
}
private:
// Serialization
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int /*version*/)
{
serialization::collection_size_type s(size_);
ar & serialization::make_nvp("size", s);
if ( Archive::is_loading::value ) {
if (s > N) bad_size("too large size in bounded_array::load()\n").raise();
resize(s);
}
ar & serialization::make_array(data_, s);
}
private:
size_type size_;
// MSVC does not like arrays of size 0 in base classes. Hence, this conditionally changes the size to 1
#ifdef _MSC_VER
BOOST_UBLAS_BOUNDED_ARRAY_ALIGN value_type data_ [(N>0)?N:1];
#else
BOOST_UBLAS_BOUNDED_ARRAY_ALIGN value_type data_ [N];
#endif
};
// Array adaptor with normal deep copy semantics of elements
template<class T>
class array_adaptor:
public storage_array<array_adaptor<T> > {
typedef array_adaptor<T> self_type;
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef const T &const_reference;
typedef T &reference;
typedef const T *const_pointer;
typedef T *pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
array_adaptor ():
size_ (0), own_ (true), data_ (new value_type [0]) {
}
explicit BOOST_UBLAS_INLINE
array_adaptor (size_type size):
size_ (size), own_ (true), data_ (new value_type [size]) {
}
BOOST_UBLAS_INLINE
array_adaptor (size_type size, const value_type &init):
size_ (size), own_ (true), data_ (new value_type [size]) {
std::fill (data_, data_ + size_, init);
}
BOOST_UBLAS_INLINE
array_adaptor (size_type size, pointer data):
size_ (size), own_ (false), data_ (data) {}
BOOST_UBLAS_INLINE
array_adaptor (const array_adaptor &a):
storage_array<self_type> (),
size_ (a.size_), own_ (true), data_ (new value_type [a.size_]) {
*this = a;
}
BOOST_UBLAS_INLINE
~array_adaptor () {
if (own_) {
delete [] data_;
}
}
// Resizing
private:
BOOST_UBLAS_INLINE
void resize_internal (size_type size, value_type init, bool preserve = true) {
if (size != size_) {
pointer data = new value_type [size];
if (preserve) {
std::copy (data_, data_ + (std::min) (size, size_), data);
std::fill (data + (std::min) (size, size_), data + size, init);
}
if (own_)
delete [] data_;
size_ = size;
own_ = true;
data_ = data;
}
}
BOOST_UBLAS_INLINE
void resize_internal (size_type size, pointer data, value_type init, bool preserve = true) {
if (data != data_) {
if (preserve) {
std::copy (data_, data_ + (std::min) (size, size_), data);
std::fill (data + (std::min) (size, size_), data + size, init);
}
if (own_)
delete [] data_;
own_ = false;
data_ = data;
}
else {
std::fill (data + (std::min) (size, size_), data + size, init);
}
size_ = size;
}
public:
BOOST_UBLAS_INLINE
void resize (size_type size) {
resize_internal (size, value_type (), false);
}
BOOST_UBLAS_INLINE
void resize (size_type size, value_type init) {
resize_internal (size, init, true);
}
BOOST_UBLAS_INLINE
void resize (size_type size, pointer data) {
resize_internal (size, data, value_type (), false);
}
BOOST_UBLAS_INLINE
void resize (size_type size, pointer data, value_type init) {
resize_internal (size, data, init, true);
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
reference operator [] (size_type i) {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
// Assignment
BOOST_UBLAS_INLINE
array_adaptor &operator = (const array_adaptor &a) {
if (this != &a) {
resize (a.size_);
std::copy (a.data_, a.data_ + a.size_, data_);
}
return *this;
}
BOOST_UBLAS_INLINE
array_adaptor &assign_temporary (array_adaptor &a) {
if (own_ && a.own_)
swap (a);
else
*this = a;
return *this;
}
// Swapping
BOOST_UBLAS_INLINE
void swap (array_adaptor &a) {
if (this != &a) {
std::swap (size_, a.size_);
std::swap (own_, a.own_);
std::swap (data_, a.data_);
}
}
BOOST_UBLAS_INLINE
friend void swap (array_adaptor &a1, array_adaptor &a2) {
a1.swap (a2);
}
// Iterators simply are pointers.
typedef const_pointer const_iterator;
BOOST_UBLAS_INLINE
const_iterator begin () const {
return data_;
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return data_ + size_;
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
typedef pointer iterator;
BOOST_UBLAS_INLINE
iterator begin () {
return data_;
}
BOOST_UBLAS_INLINE
iterator end () {
return data_ + size_;
}
// Reverse iterators
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
reverse_iterator rbegin () {
return reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
reverse_iterator rend () {
return reverse_iterator (begin ());
}
private:
size_type size_;
bool own_;
pointer data_;
};
#ifdef BOOST_UBLAS_SHALLOW_ARRAY_ADAPTOR
// Array adaptor with shallow (reference) copy semantics of elements.
// shared_array is used to maintain reference counts.
// This class breaks the normal copy semantics for a storage container and is very dangerous!
template<class T>
class shallow_array_adaptor:
public storage_array<shallow_array_adaptor<T> > {
typedef shallow_array_adaptor<T> self_type;
template<class TT>
struct leaker {
typedef void result_type;
typedef TT *argument_type;
BOOST_UBLAS_INLINE
result_type operator () (argument_type x) {}
};
public:
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
typedef T value_type;
typedef const T &const_reference;
typedef T &reference;
typedef const T *const_pointer;
typedef T *pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
shallow_array_adaptor ():
size_ (0), own_ (true), data_ (new value_type [0]) {
}
explicit BOOST_UBLAS_INLINE
shallow_array_adaptor (size_type size):
size_ (size), own_ (true), data_ (new value_type [size]) {
}
BOOST_UBLAS_INLINE
shallow_array_adaptor (size_type size, const value_type &init):
size_ (size), own_ (true), data_ (new value_type [size]) {
std::fill (data_.get (), data_.get () + size_, init);
}
BOOST_UBLAS_INLINE
shallow_array_adaptor (size_type size, pointer data):
size_ (size), own_ (false), data_ (data, leaker<value_type> ()) {}
BOOST_UBLAS_INLINE
shallow_array_adaptor (const shallow_array_adaptor &a):
storage_array<self_type> (),
size_ (a.size_), own_ (a.own_), data_ (a.data_) {}
BOOST_UBLAS_INLINE
~shallow_array_adaptor () {
}
// Resizing
private:
BOOST_UBLAS_INLINE
void resize_internal (size_type size, value_type init, bool preserve = true) {
if (size != size_) {
shared_array<value_type> data (new value_type [size]);
if (preserve) {
std::copy (data_.get (), data_.get () + (std::min) (size, size_), data.get ());
std::fill (data.get () + (std::min) (size, size_), data.get () + size, init);
}
size_ = size;
data_ = data;
}
}
BOOST_UBLAS_INLINE
void resize_internal (size_type size, pointer data, value_type init, bool preserve = true) {
if (preserve) {
std::copy (data_.get (), data_.get () + (std::min) (size, size_), data);
std::fill (data + (std::min) (size, size_), data + size, init);
}
size_ = size;
data_ = data;
}
public:
BOOST_UBLAS_INLINE
void resize (size_type size) {
resize_internal (size, value_type (), false);
}
BOOST_UBLAS_INLINE
void resize (size_type size, value_type init) {
resize_internal (size, init, true);
}
BOOST_UBLAS_INLINE
void resize (size_type size, pointer data) {
resize_internal (size, data, value_type (), false);
}
BOOST_UBLAS_INLINE
void resize (size_type size, pointer data, value_type init) {
resize_internal (size, data, init, true);
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
reference operator [] (size_type i) {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
// Assignment
BOOST_UBLAS_INLINE
shallow_array_adaptor &operator = (const shallow_array_adaptor &a) {
if (this != &a) {
resize (a.size_);
std::copy (a.data_.get (), a.data_.get () + a.size_, data_.get ());
}
return *this;
}
BOOST_UBLAS_INLINE
shallow_array_adaptor &assign_temporary (shallow_array_adaptor &a) {
if (own_ && a.own_)
swap (a);
else
*this = a;
return *this;
}
// Swapping
BOOST_UBLAS_INLINE
void swap (shallow_array_adaptor &a) {
if (this != &a) {
std::swap (size_, a.size_);
std::swap (own_, a.own_);
std::swap (data_, a.data_);
}
}
BOOST_UBLAS_INLINE
friend void swap (shallow_array_adaptor &a1, shallow_array_adaptor &a2) {
a1.swap (a2);
}
// Iterators simply are pointers.
typedef const_pointer const_iterator;
BOOST_UBLAS_INLINE
const_iterator begin () const {
return data_.get ();
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return data_.get () + size_;
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
typedef pointer iterator;
BOOST_UBLAS_INLINE
iterator begin () {
return data_.get ();
}
BOOST_UBLAS_INLINE
iterator end () {
return data_.get () + size_;
}
// Reverse iterators
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
reverse_iterator rbegin () {
return reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
reverse_iterator rend () {
return reverse_iterator (begin ());
}
private:
size_type size_;
bool own_;
shared_array<value_type> data_;
};
#endif
// Range class
template <class Z, class D>
class basic_range {
typedef basic_range<Z, D> self_type;
public:
typedef Z size_type;
typedef D difference_type;
typedef size_type value_type;
typedef value_type const_reference;
typedef const_reference reference;
typedef const value_type *const_pointer;
typedef value_type *pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
basic_range ():
start_ (0), size_ (0) {}
BOOST_UBLAS_INLINE
basic_range (size_type start, size_type stop):
start_ (start), size_ (stop - start) {
BOOST_UBLAS_CHECK (start_ <= stop, bad_index ());
}
BOOST_UBLAS_INLINE
size_type start () const {
return start_;
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Random Access Container
BOOST_UBLAS_INLINE
size_type max_size () const {
return size_;
}
BOOST_UBLAS_INLINE
bool empty () const {
return size_ == 0;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator () (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return start_ + i;
}
// Composition
BOOST_UBLAS_INLINE
basic_range compose (const basic_range &r) const {
return basic_range (start_ + r.start_, start_ + r.start_ + r.size_);
}
// Comparison
BOOST_UBLAS_INLINE
bool operator == (const basic_range &r) const {
return start_ == r.start_ && size_ == r.size_;
}
BOOST_UBLAS_INLINE
bool operator != (const basic_range &r) const {
return ! (*this == r);
}
// Iterator types
private:
// Use and index
typedef size_type const_subiterator_type;
public:
#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR
typedef indexed_const_iterator<self_type, std::random_access_iterator_tag> const_iterator;
#else
class const_iterator:
public container_const_reference<basic_range>,
public random_access_iterator_base<std::random_access_iterator_tag,
const_iterator, value_type> {
public:
typedef typename basic_range::value_type value_type;
typedef typename basic_range::difference_type difference_type;
typedef typename basic_range::const_reference reference;
typedef typename basic_range::const_pointer pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
const_iterator ():
container_const_reference<basic_range> (), it_ () {}
BOOST_UBLAS_INLINE
const_iterator (const basic_range &r, const const_subiterator_type &it):
container_const_reference<basic_range> (r), it_ (it) {}
// Arithmetic
BOOST_UBLAS_INLINE
const_iterator &operator ++ () {
++ it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -- () {
BOOST_UBLAS_CHECK (it_ > 0, bad_index ());
-- it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator += (difference_type n) {
BOOST_UBLAS_CHECK (n >= 0 || it_ >= size_type(-n), bad_index ());
it_ += n;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -= (difference_type n) {
BOOST_UBLAS_CHECK (n <= 0 || it_ >= size_type(n), bad_index ());
it_ -= n;
return *this;
}
BOOST_UBLAS_INLINE
difference_type operator - (const const_iterator &it) const {
return it_ - it.it_;
}
// Dereference
BOOST_UBLAS_INLINE
const_reference operator * () const {
BOOST_UBLAS_CHECK ((*this) ().start () <= it_, bad_index ());
BOOST_UBLAS_CHECK (it_ < (*this) ().start () + (*this) ().size (), bad_index ());
return it_;
}
BOOST_UBLAS_INLINE
const_reference operator [] (difference_type n) const {
return *(*this + n);
}
// Index
BOOST_UBLAS_INLINE
size_type index () const {
BOOST_UBLAS_CHECK ((*this) ().start () <= it_, bad_index ());
BOOST_UBLAS_CHECK (it_ < (*this) ().start () + (*this) ().size (), bad_index ());
return it_ - (*this) ().start ();
}
// Assignment
BOOST_UBLAS_INLINE
const_iterator &operator = (const const_iterator &it) {
// Comeau recommends...
this->assign (&it ());
it_ = it.it_;
return *this;
}
// Comparison
BOOST_UBLAS_INLINE
bool operator == (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ == it.it_;
}
BOOST_UBLAS_INLINE
bool operator < (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ < it.it_;
}
private:
const_subiterator_type it_;
};
#endif
BOOST_UBLAS_INLINE
const_iterator begin () const {
return const_iterator (*this, start_);
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return const_iterator (*this, start_ + size_);
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
// Reverse iterator
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
basic_range preprocess (size_type size) const {
if (this != &all_)
return *this;
return basic_range (0, size);
}
static
BOOST_UBLAS_INLINE
const basic_range &all () {
return all_;
}
private:
size_type start_;
size_type size_;
static const basic_range all_;
};
template <class Z, class D>
const basic_range<Z,D> basic_range<Z,D>::all_ (0, size_type (-1));
// Slice class
template <class Z, class D>
class basic_slice {
typedef basic_slice<Z, D> self_type;
public:
typedef Z size_type;
typedef D difference_type;
typedef size_type value_type;
typedef value_type const_reference;
typedef const_reference reference;
typedef const value_type *const_pointer;
typedef value_type *pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
basic_slice ():
start_ (0), stride_ (0), size_ (0) {}
BOOST_UBLAS_INLINE
basic_slice (size_type start, difference_type stride, size_type size):
start_ (start), stride_ (stride), size_ (size) {}
BOOST_UBLAS_INLINE
size_type start () const {
return start_;
}
BOOST_UBLAS_INLINE
difference_type stride () const {
return stride_;
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
// Random Access Container
BOOST_UBLAS_INLINE
size_type max_size () const {
return size_;
}
BOOST_UBLAS_INLINE
bool empty () const {
return size_ == 0;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator () (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
BOOST_UBLAS_CHECK (stride_ >= 0 || start_ >= i * -stride_, bad_index ());
return start_ + i * stride_;
}
// Composition
BOOST_UBLAS_INLINE
basic_slice compose (const basic_range<size_type, difference_type> &r) const {
BOOST_UBLAS_CHECK (stride_ >=0 || start_ >= -stride_ * r.start(), bad_index ());
return basic_slice (start_ + stride_ * r.start (), stride_, r.size ());
}
BOOST_UBLAS_INLINE
basic_slice compose (const basic_slice &s) const {
BOOST_UBLAS_CHECK (stride_ >=0 || start_ >= -stride_ * s.start_, bad_index ());
return basic_slice (start_ + stride_ * s.start_, stride_ * s.stride_, s.size_);
}
// Comparison
BOOST_UBLAS_INLINE
bool operator == (const basic_slice &s) const {
return start_ == s.start_ && stride_ == s.stride_ && size_ == s.size_;
}
BOOST_UBLAS_INLINE
bool operator != (const basic_slice &s) const {
return ! (*this == s);
}
// Iterator types
private:
// Use and index
typedef size_type const_subiterator_type;
public:
#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR
typedef indexed_const_iterator<self_type, std::random_access_iterator_tag> const_iterator;
#else
class const_iterator:
public container_const_reference<basic_slice>,
public random_access_iterator_base<std::random_access_iterator_tag,
const_iterator, value_type> {
public:
typedef typename basic_slice::value_type value_type;
typedef typename basic_slice::difference_type difference_type;
typedef typename basic_slice::const_reference reference;
typedef typename basic_slice::const_pointer pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
const_iterator ():
container_const_reference<basic_slice> (), it_ () {}
BOOST_UBLAS_INLINE
const_iterator (const basic_slice &s, const const_subiterator_type &it):
container_const_reference<basic_slice> (s), it_ (it) {}
// Arithmetic
BOOST_UBLAS_INLINE
const_iterator &operator ++ () {
++it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -- () {
BOOST_UBLAS_CHECK (it_ > 0, bad_index ());
--it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator += (difference_type n) {
BOOST_UBLAS_CHECK (n >= 0 || it_ >= size_type(-n), bad_index ());
it_ += n;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -= (difference_type n) {
BOOST_UBLAS_CHECK (n <= 0 || it_ >= size_type(n), bad_index ());
it_ -= n;
return *this;
}
BOOST_UBLAS_INLINE
difference_type operator - (const const_iterator &it) const {
return it_ - it.it_;
}
// Dereference
BOOST_UBLAS_INLINE
const_reference operator * () const {
BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());
return (*this) ().start () + it_* (*this) ().stride ();
}
BOOST_UBLAS_INLINE
const_reference operator [] (difference_type n) const {
return *(*this + n);
}
// Index
BOOST_UBLAS_INLINE
size_type index () const {
BOOST_UBLAS_CHECK (it_ < (*this) ().size (), bad_index ());
return it_;
}
// Assignment
BOOST_UBLAS_INLINE
const_iterator &operator = (const const_iterator &it) {
// Comeau recommends...
this->assign (&it ());
it_ = it.it_;
return *this;
}
// Comparison
BOOST_UBLAS_INLINE
bool operator == (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ == it.it_;
}
BOOST_UBLAS_INLINE
bool operator < (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ < it.it_;
}
private:
const_subiterator_type it_;
};
#endif
BOOST_UBLAS_INLINE
const_iterator begin () const {
return const_iterator (*this, 0);
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return const_iterator (*this, size_);
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
// Reverse iterator
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
basic_slice preprocess (size_type size) const {
if (this != &all_)
return *this;
return basic_slice (0, 1, size);
}
static
BOOST_UBLAS_INLINE
const basic_slice &all () {
return all_;
}
private:
size_type start_;
difference_type stride_;
size_type size_;
static const basic_slice all_;
};
template <class Z, class D>
const basic_slice<Z,D> basic_slice<Z,D>::all_ (0, 1, size_type (-1));
// Indirect array class
template<class A>
class indirect_array {
typedef indirect_array<A> self_type;
public:
typedef A array_type;
typedef const A const_array_type;
typedef typename A::size_type size_type;
typedef typename A::difference_type difference_type;
typedef typename A::value_type value_type;
typedef typename A::const_reference const_reference;
typedef typename A::reference reference;
typedef typename A::const_pointer const_pointer;
typedef typename A::pointer pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
indirect_array ():
size_ (), data_ () {}
explicit BOOST_UBLAS_INLINE
indirect_array (size_type size):
size_ (size), data_ (size) {}
BOOST_UBLAS_INLINE
indirect_array (size_type size, const array_type &data):
size_ (size), data_ (data) {}
BOOST_UBLAS_INLINE
indirect_array (pointer start, pointer stop):
size_ (stop - start), data_ (stop - start) {
std::copy (start, stop, data_.begin ());
}
BOOST_UBLAS_INLINE
size_type size () const {
return size_;
}
BOOST_UBLAS_INLINE
const_array_type data () const {
return data_;
}
BOOST_UBLAS_INLINE
array_type data () {
return data_;
}
// Random Access Container
BOOST_UBLAS_INLINE
size_type max_size () const {
return size_;
}
BOOST_UBLAS_INLINE
bool empty () const {
return data_.size () == 0;
}
// Element access
BOOST_UBLAS_INLINE
const_reference operator () (size_type i) const {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
reference operator () (size_type i) {
BOOST_UBLAS_CHECK (i < size_, bad_index ());
return data_ [i];
}
BOOST_UBLAS_INLINE
const_reference operator [] (size_type i) const {
return (*this) (i);
}
BOOST_UBLAS_INLINE
reference operator [] (size_type i) {
return (*this) (i);
}
// Composition
BOOST_UBLAS_INLINE
indirect_array compose (const basic_range<size_type, difference_type> &r) const {
BOOST_UBLAS_CHECK (r.start () + r.size () <= size_, bad_size ());
array_type data (r.size ());
for (size_type i = 0; i < r.size (); ++ i)
data [i] = data_ [r.start () + i];
return indirect_array (r.size (), data);
}
BOOST_UBLAS_INLINE
indirect_array compose (const basic_slice<size_type, difference_type> &s) const {
BOOST_UBLAS_CHECK (s.start () + s.stride () * (s.size () - (s.size () > 0)) <= size (), bad_size ());
array_type data (s.size ());
for (size_type i = 0; i < s.size (); ++ i)
data [i] = data_ [s.start () + s.stride () * i];
return indirect_array (s.size (), data);
}
BOOST_UBLAS_INLINE
indirect_array compose (const indirect_array &ia) const {
array_type data (ia.size_);
for (size_type i = 0; i < ia.size_; ++ i) {
BOOST_UBLAS_CHECK (ia.data_ [i] <= size_, bad_size ());
data [i] = data_ [ia.data_ [i]];
}
return indirect_array (ia.size_, data);
}
// Comparison
template<class OA>
BOOST_UBLAS_INLINE
bool operator == (const indirect_array<OA> &ia) const {
if (size_ != ia.size_)
return false;
for (size_type i = 0; i < BOOST_UBLAS_SAME (size_, ia.size_); ++ i)
if (data_ [i] != ia.data_ [i])
return false;
return true;
}
template<class OA>
BOOST_UBLAS_INLINE
bool operator != (const indirect_array<OA> &ia) const {
return ! (*this == ia);
}
// Iterator types
private:
// Use a index difference
typedef difference_type const_subiterator_type;
public:
#ifdef BOOST_UBLAS_USE_INDEXED_ITERATOR
typedef indexed_const_iterator<indirect_array, std::random_access_iterator_tag> const_iterator;
#else
class const_iterator:
public container_const_reference<indirect_array>,
public random_access_iterator_base<std::random_access_iterator_tag,
const_iterator, value_type> {
public:
typedef typename indirect_array::value_type value_type;
typedef typename indirect_array::difference_type difference_type;
typedef typename indirect_array::const_reference reference;
typedef typename indirect_array::const_pointer pointer;
// Construction and destruction
BOOST_UBLAS_INLINE
const_iterator ():
container_const_reference<indirect_array> (), it_ () {}
BOOST_UBLAS_INLINE
const_iterator (const indirect_array &ia, const const_subiterator_type &it):
container_const_reference<indirect_array> (ia), it_ (it) {}
// Arithmetic
BOOST_UBLAS_INLINE
const_iterator &operator ++ () {
++ it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -- () {
-- it_;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator += (difference_type n) {
it_ += n;
return *this;
}
BOOST_UBLAS_INLINE
const_iterator &operator -= (difference_type n) {
it_ -= n;
return *this;
}
BOOST_UBLAS_INLINE
difference_type operator - (const const_iterator &it) const {
return it_ - it.it_;
}
// Dereference
BOOST_UBLAS_INLINE
const_reference operator * () const {
return (*this) () (it_);
}
BOOST_UBLAS_INLINE
const_reference operator [] (difference_type n) const {
return *(*this + n);
}
// Index
BOOST_UBLAS_INLINE
size_type index () const {
return it_;
}
// Assignment
BOOST_UBLAS_INLINE
const_iterator &operator = (const const_iterator &it) {
// Comeau recommends...
this->assign (&it ());
it_ = it.it_;
return *this;
}
// Comparison
BOOST_UBLAS_INLINE
bool operator == (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ == it.it_;
}
BOOST_UBLAS_INLINE
bool operator < (const const_iterator &it) const {
BOOST_UBLAS_CHECK ((*this) () == it (), external_logic ());
return it_ < it.it_;
}
private:
const_subiterator_type it_;
};
#endif
BOOST_UBLAS_INLINE
const_iterator begin () const {
return const_iterator (*this, 0);
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end () const {
return const_iterator (*this, size_);
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
// Reverse iterator
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
BOOST_UBLAS_INLINE
const_reverse_iterator rbegin () const {
return const_reverse_iterator (end ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crbegin () const {
return rbegin ();
}
BOOST_UBLAS_INLINE
const_reverse_iterator rend () const {
return const_reverse_iterator (begin ());
}
BOOST_UBLAS_INLINE
const_reverse_iterator crend () const {
return rend ();
}
BOOST_UBLAS_INLINE
indirect_array preprocess (size_type size) const {
if (this != &all_)
return *this;
indirect_array ia (size);
for (size_type i = 0; i < size; ++ i)
ia (i) = i;
return ia;
}
static
BOOST_UBLAS_INLINE
const indirect_array &all () {
return all_;
}
private:
size_type size_;
array_type data_;
static const indirect_array all_;
};
template<class A>
const indirect_array<A> indirect_array<A>::all_;
// Gunter Winkler contributed the classes index_pair, index_pair_array,
// index_triple and index_triple_array to enable inplace sort of parallel arrays.
template <class V>
class index_pair :
public container_reference<V> {
typedef index_pair<V> self_type;
public:
typedef typename V::size_type size_type;
BOOST_UBLAS_INLINE
index_pair(V& v, size_type i) :
container_reference<V>(v), i_(i),
v1_(v.data1_[i]), v2_(v.data2_[i]),
dirty_(false), is_copy_(false) {}
BOOST_UBLAS_INLINE
index_pair(const self_type& rhs) :
container_reference<V>(rhs()), i_(0),
v1_(rhs.v1_), v2_(rhs.v2_),
dirty_(false), is_copy_(true) {}
BOOST_UBLAS_INLINE
~index_pair() {
if (dirty_ && (!is_copy_) ) {
(*this)().data1_[i_] = v1_;
(*this)().data2_[i_] = v2_;
}
}
BOOST_UBLAS_INLINE
self_type& operator=(const self_type& rhs) {
v1_ = rhs.v1_;
v2_ = rhs.v2_;
dirty_ = true;
return *this;
}
BOOST_UBLAS_INLINE
void swap(self_type& rhs) {
self_type tmp(rhs);
rhs = *this;
*this = tmp;
}
BOOST_UBLAS_INLINE
friend void swap(self_type& lhs, self_type& rhs) {
lhs.swap(rhs);
}
friend void swap(self_type lhs, self_type rhs) { // For gcc 4.8 and c++11
lhs.swap(rhs);
}
BOOST_UBLAS_INLINE
bool equal(const self_type& rhs) const {
return (v1_ == rhs.v1_);
}
BOOST_UBLAS_INLINE
bool less(const self_type& rhs) const {
return (v1_ < rhs.v1_);
}
BOOST_UBLAS_INLINE
friend bool operator == (const self_type& lhs, const self_type& rhs) {
return lhs.equal(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator != (const self_type& lhs, const self_type& rhs) {
return !lhs.equal(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator < (const self_type& lhs, const self_type& rhs) {
return lhs.less(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator >= (const self_type& lhs, const self_type& rhs) {
return !lhs.less(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator > (const self_type& lhs, const self_type& rhs) {
return rhs.less(lhs);
}
BOOST_UBLAS_INLINE
friend bool operator <= (const self_type& lhs, const self_type& rhs) {
return !rhs.less(lhs);
}
private:
size_type i_;
typename V::value1_type v1_;
typename V::value2_type v2_;
bool dirty_;
bool is_copy_;
};
template <class V1, class V2>
class index_pair_array:
private boost::noncopyable {
typedef index_pair_array<V1, V2> self_type;
public:
typedef typename V1::value_type value1_type;
typedef typename V2::value_type value2_type;
typedef typename V1::size_type size_type;
typedef typename V1::difference_type difference_type;
typedef index_pair<self_type> value_type;
// There is nothing that can be referenced directly. Always return a copy of the index_pair
typedef value_type reference;
typedef const value_type const_reference;
BOOST_UBLAS_INLINE
index_pair_array(size_type size, V1& data1, V2& data2) :
size_(size),data1_(data1),data2_(data2) {}
BOOST_UBLAS_INLINE
size_type size() const {
return size_;
}
BOOST_UBLAS_INLINE
const_reference operator () (size_type i) const {
return value_type((*this), i);
}
BOOST_UBLAS_INLINE
reference operator () (size_type i) {
return value_type((*this), i);
}
typedef indexed_iterator<self_type, std::random_access_iterator_tag> iterator;
typedef indexed_const_iterator<self_type, std::random_access_iterator_tag> const_iterator;
BOOST_UBLAS_INLINE
iterator begin() {
return iterator( (*this), 0);
}
BOOST_UBLAS_INLINE
iterator end() {
return iterator( (*this), size());
}
BOOST_UBLAS_INLINE
const_iterator begin() const {
return const_iterator( (*this), 0);
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end() const {
return const_iterator( (*this), size());
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
// unnecessary function:
BOOST_UBLAS_INLINE
bool equal(size_type i1, size_type i2) const {
return data1_[i1] == data1_[i2];
}
BOOST_UBLAS_INLINE
bool less(size_type i1, size_type i2) const {
return data1_[i1] < data1_[i2];
}
// gives a large speedup
BOOST_UBLAS_INLINE
friend void iter_swap(const iterator& lhs, const iterator& rhs) {
const size_type i1 = lhs.index();
const size_type i2 = rhs.index();
std::swap(lhs().data1_[i1], rhs().data1_[i2]);
std::swap(lhs().data2_[i1], rhs().data2_[i2]);
}
private:
size_type size_;
V1& data1_;
V2& data2_;
// friend class value_type;
friend class index_pair<self_type>;
};
template <class M>
class index_triple :
public container_reference<M> {
typedef index_triple<M> self_type;
public:
typedef typename M::size_type size_type;
BOOST_UBLAS_INLINE
index_triple(M& m, size_type i) :
container_reference<M>(m), i_(i),
v1_(m.data1_[i]), v2_(m.data2_[i]), v3_(m.data3_[i]),
dirty_(false), is_copy_(false) {}
BOOST_UBLAS_INLINE
index_triple(const self_type& rhs) :
container_reference<M>(rhs()), i_(0),
v1_(rhs.v1_), v2_(rhs.v2_), v3_(rhs.v3_),
dirty_(false), is_copy_(true) {}
BOOST_UBLAS_INLINE
~index_triple() {
if (dirty_ && (!is_copy_) ) {
(*this)().data1_[i_] = v1_;
(*this)().data2_[i_] = v2_;
(*this)().data3_[i_] = v3_;
}
}
BOOST_UBLAS_INLINE
self_type& operator=(const self_type& rhs) {
v1_ = rhs.v1_;
v2_ = rhs.v2_;
v3_ = rhs.v3_;
dirty_ = true;
return *this;
}
BOOST_UBLAS_INLINE
void swap(self_type& rhs) {
self_type tmp(rhs);
rhs = *this;
*this = tmp;
}
BOOST_UBLAS_INLINE
friend void swap(self_type& lhs, self_type& rhs) {
lhs.swap(rhs);
}
friend void swap(self_type lhs, self_type rhs) { // For gcc 4.8 and c++11
lhs.swap(rhs);
}
BOOST_UBLAS_INLINE
bool equal(const self_type& rhs) const {
return ((v1_ == rhs.v1_) && (v2_ == rhs.v2_));
}
BOOST_UBLAS_INLINE
bool less(const self_type& rhs) const {
return ((v1_ < rhs.v1_) ||
(v1_ == rhs.v1_ && v2_ < rhs.v2_));
}
BOOST_UBLAS_INLINE
friend bool operator == (const self_type& lhs, const self_type& rhs) {
return lhs.equal(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator != (const self_type& lhs, const self_type& rhs) {
return !lhs.equal(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator < (const self_type& lhs, const self_type& rhs) {
return lhs.less(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator >= (const self_type& lhs, const self_type& rhs) {
return !lhs.less(rhs);
}
BOOST_UBLAS_INLINE
friend bool operator > (const self_type& lhs, const self_type& rhs) {
return rhs.less(lhs);
}
BOOST_UBLAS_INLINE
friend bool operator <= (const self_type& lhs, const self_type& rhs) {
return !rhs.less(lhs);
}
private:
size_type i_;
typename M::value1_type v1_;
typename M::value2_type v2_;
typename M::value3_type v3_;
bool dirty_;
bool is_copy_;
};
template <class V1, class V2, class V3>
class index_triple_array:
private boost::noncopyable {
typedef index_triple_array<V1, V2, V3> self_type;
public:
typedef typename V1::value_type value1_type;
typedef typename V2::value_type value2_type;
typedef typename V3::value_type value3_type;
typedef typename V1::size_type size_type;
typedef typename V1::difference_type difference_type;
typedef index_triple<self_type> value_type;
// There is nothing that can be referenced directly. Always return a copy of the index_triple
typedef value_type reference;
typedef const value_type const_reference;
BOOST_UBLAS_INLINE
index_triple_array(size_type size, V1& data1, V2& data2, V3& data3) :
size_(size),data1_(data1),data2_(data2),data3_(data3) {}
BOOST_UBLAS_INLINE
size_type size() const {
return size_;
}
BOOST_UBLAS_INLINE
const_reference operator () (size_type i) const {
return value_type((*this), i);
}
BOOST_UBLAS_INLINE
reference operator () (size_type i) {
return value_type((*this), i);
}
typedef indexed_iterator<self_type, std::random_access_iterator_tag> iterator;
typedef indexed_const_iterator<self_type, std::random_access_iterator_tag> const_iterator;
BOOST_UBLAS_INLINE
iterator begin() {
return iterator( (*this), 0);
}
BOOST_UBLAS_INLINE
iterator end() {
return iterator( (*this), size());
}
BOOST_UBLAS_INLINE
const_iterator begin() const {
return const_iterator( (*this), 0);
}
BOOST_UBLAS_INLINE
const_iterator cbegin () const {
return begin ();
}
BOOST_UBLAS_INLINE
const_iterator end() const {
return const_iterator( (*this), size());
}
BOOST_UBLAS_INLINE
const_iterator cend () const {
return end ();
}
// unnecessary function:
BOOST_UBLAS_INLINE
bool equal(size_type i1, size_type i2) const {
return ((data1_[i1] == data1_[i2]) && (data2_[i1] == data2_[i2]));
}
BOOST_UBLAS_INLINE
bool less(size_type i1, size_type i2) const {
return ((data1_[i1] < data1_[i2]) ||
(data1_[i1] == data1_[i2] && data2_[i1] < data2_[i2]));
}
// gives a large speedup
BOOST_UBLAS_INLINE
friend void iter_swap(const iterator& lhs, const iterator& rhs) {
const size_type i1 = lhs.index();
const size_type i2 = rhs.index();
std::swap(lhs().data1_[i1], rhs().data1_[i2]);
std::swap(lhs().data2_[i1], rhs().data2_[i2]);
std::swap(lhs().data3_[i1], rhs().data3_[i2]);
}
private:
size_type size_;
V1& data1_;
V2& data2_;
V3& data3_;
// friend class value_type;
friend class index_triple<self_type>;
};
}}}
#endif
| {'content_hash': '936ab814b0c6b1b3b09ab75875fd74f6', 'timestamp': '', 'source': 'github', 'line_count': 2057, 'max_line_length': 119, 'avg_line_length': 32.82887700534759, 'alnum_prop': 0.4848879740555909, 'repo_name': 'viennautils/viennautils-dev', 'id': '310a59af5d5b33ef30bde996016236f9817dea4f', 'size': '67529', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'override/boost/numeric/ublas/storage.hpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '168352'}, {'name': 'C++', 'bytes': '20972064'}, {'name': 'CMake', 'bytes': '7162'}, {'name': 'Perl', 'bytes': '1334'}]} |
package com.zegoggles.smssync.contacts;
import com.zegoggles.smssync.mail.PersonRecord;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import static org.fest.assertions.api.Assertions.assertThat;
@RunWith(RobolectricTestRunner.class)
public class ContactGroupdsTest {
@Test
public void shouldAddIds() throws Exception {
ContactGroupIds ids = new ContactGroupIds();
assertThat(ids.getIds()).isEmpty();
assertThat(ids.getRawIds()).isEmpty();
ids.add(1, 4);
ids.add(3, 4);
assertThat(ids.getIds()).containsExactly(1L, 3L);
assertThat(ids.getRawIds()).containsExactly(4L);
}
@Test
public void shouldCheckForPerson() throws Exception {
ContactGroupIds ids = new ContactGroupIds();
PersonRecord record = new PersonRecord(22, "Test", "[email protected]", "123");
assertThat(ids.contains(record)).isFalse();
ids.add(22L, 44L);
assertThat(ids.contains(record)).isTrue();
}
}
| {'content_hash': '07e8a1ea4e4e435edb81d454067bea48', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 83, 'avg_line_length': 28.2972972972973, 'alnum_prop': 0.6848137535816619, 'repo_name': 'davidfraser/sms-backup-plus', 'id': '5302715754c25cc71944e70e1b6c9e241a2fee80', 'size': '1047', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/test/java/com/zegoggles/smssync/contacts/ContactGroupdsTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '3490'}, {'name': 'Java', 'bytes': '459175'}, {'name': 'Ruby', 'bytes': '3472'}]} |
// memcached 采用 slab 的内存管理方法.
slabs_free(it, ntotal, clsid);
}
bool item_size_ok(const size_t nkey, const int flags, const int nbytes) {
char prefix[40];
uint8_t nsuffix;
size_t ntotal = item_make_header(nkey + 1, flags, nbytes,
| {'content_hash': '02dc13e4f6f7fc7e4e1ae82163cc28a3', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 73, 'avg_line_length': 31.375, 'alnum_prop': 0.6573705179282868, 'repo_name': 'coodoing/piconv', 'id': '014ce7efc72a8c355ab96eee7bc7427b006d91ea', 'size': '270', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'data-set/items.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '618'}, {'name': 'Python', 'bytes': '478938'}]} |
define(['baseTestSetup', 'confirmationServiceMock'], function(baseTestSetup, ConfirmationServiceMock) {
'use strict';
describe('trackr.employee.controllers.vacation-list', function() {
var EmployeeService, VacationRequestListController, scope;
baseTestSetup();
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
EmployeeService = {
getEmployee: function() {
return {
id: 0
};
}
};
spyOn(EmployeeService, 'getEmployee').andCallThrough();
VacationRequestListController = $controller('trackr.employee.controllers.vacation-list', {
$scope: scope,
'trackr.services.employee': EmployeeService,
'base.services.confirmation-dialog': ConfirmationServiceMock
});
}));
it('Must get the employee on load', inject(function($httpBackend) {
expect(EmployeeService.getEmployee).toHaveBeenCalled();
$httpBackend.flush();
}));
it('Must load the vacation requests', inject(function($httpBackend) {
$httpBackend.flush();
expect(scope.vacationRequests).toBeDefined();
expect(scope.vacationRequests.length).toBeGreaterThan(0);
}));
it('Must push a vacation request into the array on $scope event', inject(function($httpBackend) {
$httpBackend.flush();
var length = scope.vacationRequests.length;
scope.$emit('newVacationRequest', {});
expect(scope.vacationRequests.length).toBe(length + 1);
}));
it('Must remove a vacation request from the array if it is cancelled', inject(function($httpBackend) {
$httpBackend.flush();
var length = scope.vacationRequests.length;
scope.cancelVacationRequest(scope.vacationRequests[0]);
$httpBackend.flush();
expect(scope.vacationRequests.length).toBe(length - 1);
}));
});
}); | {'content_hash': '6b7166b36e68c74ad857f949bf2e7306', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 110, 'avg_line_length': 43.16326530612245, 'alnum_prop': 0.5895981087470449, 'repo_name': 'hongyang070/trackr-frontend', 'id': 'b7d5488787acd053ee3509343d042a5e1c7da101', 'size': '2115', 'binary': False, 'copies': '4', 'ref': 'refs/heads/development', 'path': 'test/modules/trackr/employee/vacation/listControllerSpec.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '92310'}, {'name': 'JavaScript', 'bytes': '356700'}]} |
cask "ansible-dk" do
version "1.2.0,3"
sha256 "70fe9e4b8f27e8961c992de3ed1e30bb39c43319af28aae73c177f9530352a49"
url "https://github.com/omniti-labs/ansible-dk/releases/download/#{version.before_comma}/ansible-dk-#{version.before_comma}-#{version.after_comma}.dmg"
appcast "https://github.com/omniti-labs/ansible-dk/releases.atom"
name "Ansible DK"
name "Ansible Development Kit"
homepage "https://github.com/omniti-labs/ansible-dk"
pkg "ansible-dk-#{version.major_minor_patch}-1.pkg"
uninstall pkgutil: "com.omniti.labs.ansible-dk"
end
| {'content_hash': 'e27a4a5bce6e2426979a3a54b9d5f244', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 153, 'avg_line_length': 39.857142857142854, 'alnum_prop': 0.7580645161290323, 'repo_name': 'ericbn/homebrew-cask', 'id': '1384233f8edcb08e8321cc3c6f0b9fc6fb5b79bb', 'size': '558', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'Casks/ansible-dk.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Dockerfile', 'bytes': '249'}, {'name': 'Python', 'bytes': '3630'}, {'name': 'Ruby', 'bytes': '2263313'}, {'name': 'Shell', 'bytes': '32035'}]} |
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/ngrok/rails`. To experiment with that code, run `bin/console` for an interactive prompt.
TODO: Delete this and the text above, and describe your gem
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'ngrok-rails'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install ngrok-rails
## Usage
TODO: Write usage instructions here
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/ngrok-rails.
## License
The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
| {'content_hash': '8c28f8a6a3eb7f0a4958c822604f275e', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 324, 'avg_line_length': 34.23076923076923, 'alnum_prop': 0.7475655430711611, 'repo_name': 'watsonbox/ngrok-rails', 'id': '5eae4d6dbbcb6b38118a4be31e63af1a768cb2e8', 'size': '1351', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '2371'}, {'name': 'Shell', 'bytes': '115'}]} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Patrice.tech</title>
<meta name="description" content="" />
<meta name="HandheldFriendly" content="True" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="https://patricekrakow.github.io/favicon.ico">
<link rel="stylesheet" type="text/css" href="//patricekrakow.github.io/themes/casper/assets/css/screen.css?v=1487944978997" />
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />
<link rel="canonical" href="https://patricekrakow.github.io/" />
<meta name="referrer" content="origin" />
<meta property="og:site_name" content="Patrice.tech" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Patrice.tech" />
<meta property="og:url" content="https://patricekrakow.github.io/" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:title" content="Patrice.tech" />
<meta name="twitter:url" content="https://patricekrakow.github.io/" />
<script type="application/ld+json">
null
</script>
<meta name="generator" content="HubPress" />
<link rel="alternate" type="application/rss+xml" title="Patrice.tech" href="https://patricekrakow.github.io/rss/" />
</head>
<body class="home-template nav-closed">
<div class="site-wrapper">
<header class="main-header no-cover">
<nav class="main-nav overlay clearfix">
</nav>
<div class="vertical">
<div class="main-header-content inner">
<h1 class="page-title">Patrice.tech</h1>
<h2 class="page-description"></h2>
</div>
</div>
<a class="scroll-down icon-arrow-left" href="#content" data-offset="-45"><span class="hidden">Scroll Down</span></a>
</header>
<main id="content" class="content" role="main">
<div class="extra-pagination inner">
<nav class="pagination" role="navigation">
<span class="page-number">Page 1 of 1</span>
</nav>
</div>
<article class="post">
<header class="post-header">
<h2 class="post-title"><a href="https://patricekrakow.github.io/2016/08/10/How-I-installed-Go-on-my-corporate-Windows-laptop-without-administrator-rights.html">How I installed Go on my corporate Windows laptop without administrator rights</a></h2>
</header>
<section class="post-excerpt">
<p>TLDR; The master trick when not having administrator rights is to use C:\Users\username\AppData\Local\Programs !!! I have started by going to https://golang. <a class="read-more" href="https://patricekrakow.github.io/2016/08/10/How-I-installed-Go-on-my-corporate-Windows-laptop-without-administrator-rights.html">»</a></p>
</section>
<footer class="post-meta">
<img class="author-thumb" src="https://avatars.githubusercontent.com/u/12017232?v=3" alt="patricekrakow" nopin="nopin" />
<a href="https://patricekrakow.github.io/author/patricekrakow/">patricekrakow</a>
<time class="post-date" datetime="2016-08-10">10 August 2016</time>
</footer>
</article>
<article class="post">
<header class="post-header">
<h2 class="post-title"><a href="https://patricekrakow.github.io/2016/08/10/Hello-World.html">Hello World!</a></h2>
</header>
<section class="post-excerpt">
<p>This is my first post using HubPress ;-) <a class="read-more" href="https://patricekrakow.github.io/2016/08/10/Hello-World.html">»</a></p>
</section>
<footer class="post-meta">
<img class="author-thumb" src="https://avatars.githubusercontent.com/u/12017232?v=3" alt="patricekrakow" nopin="nopin" />
<a href="https://patricekrakow.github.io/author/patricekrakow/">patricekrakow</a>
<time class="post-date" datetime="2016-08-10">10 August 2016</time>
</footer>
</article>
<nav class="pagination" role="navigation">
<span class="page-number">Page 1 of 1</span>
</nav>
</main>
<footer class="site-footer clearfix">
<section class="copyright"><a href="https://patricekrakow.github.io">Patrice.tech</a> © 2017</section>
<section class="poweredby">Proudly published with <a href="http://hubpress.io">HubPress</a></section>
</footer>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js?v="></script> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js?v="></script>
<script type="text/javascript">
jQuery( document ).ready(function() {
// change date with ago
jQuery('ago.ago').each(function(){
var element = jQuery(this).parent();
element.html( moment(element.text()).fromNow());
});
});
hljs.initHighlightingOnLoad();
</script>
<script type="text/javascript" src="//patricekrakow.github.io/themes/casper/assets/js/jquery.fitvids.js?v=1487944978997"></script>
<script type="text/javascript" src="//patricekrakow.github.io/themes/casper/assets/js/index.js?v=1487944978997"></script>
</body>
</html>
| {'content_hash': '7355bdc5389dab9473149b3ebe98ef7b', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 344, 'avg_line_length': 44.44094488188976, 'alnum_prop': 0.6390857547838412, 'repo_name': 'patricekrakow/patricekrakow.github.io', 'id': '4f02947e4984ed0291c5ce8d6e8f4c08f6f24bdd', 'size': '5644', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'index.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '426759'}, {'name': 'CoffeeScript', 'bytes': '6630'}, {'name': 'HTML', 'bytes': '131109'}, {'name': 'JavaScript', 'bytes': '22599'}, {'name': 'Ruby', 'bytes': '806'}, {'name': 'Shell', 'bytes': '2265'}]} |
var expectedDevices = [{
'vendor': 'Vendor 1',
'model': 'Model 1',
'capacity': 1 << 15,
'removable': true,
}, {
'vendor': 'Vendor 2',
'model': 'Model 2',
'capacity': 1 << 17,
'removable': false,
}];
function testDeviceList() {
chrome.imageWriterPrivate.listRemovableStorageDevices(
chrome.test.callback(listRemovableDevicesCallback));
}
function listRemovableDevicesCallback(deviceList) {
deviceList.sort(function (a, b) {
if (a.storageUnitId > b.storageUnitId) return 1;
if (a.storageUnitId < b.storageUnitId) return -1;
return 0;
});
chrome.test.assertEq(2, deviceList.length);
deviceList.forEach(function (dev, i) {
var expected = expectedDevices[i];
chrome.test.assertEq(expected.vendor, dev.vendor);
chrome.test.assertEq(expected.model, dev.model);
chrome.test.assertEq(expected.capacity, dev.capacity);
chrome.test.assertEq(expected.removable, dev.removable);
});
}
chrome.test.runTests([testDeviceList])
| {'content_hash': '670bbbd17dfdc1dba05b1fe5d6d44ec8', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 62, 'avg_line_length': 26.783783783783782, 'alnum_prop': 0.686175580221998, 'repo_name': 'littlstar/chromium.src', 'id': 'ec7be06b9966fd096f50948cc439a89dbf628c95', 'size': '1245', 'binary': False, 'copies': '57', 'ref': 'refs/heads/nw', 'path': 'chrome/test/data/extensions/api_test/image_writer_private/list_devices/test.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Arduino', 'bytes': '464'}, {'name': 'Assembly', 'bytes': '24741'}, {'name': 'C', 'bytes': '4017880'}, {'name': 'C++', 'bytes': '210335316'}, {'name': 'CSS', 'bytes': '966760'}, {'name': 'Java', 'bytes': '5457985'}, {'name': 'JavaScript', 'bytes': '17809148'}, {'name': 'Makefile', 'bytes': '92563'}, {'name': 'Objective-C', 'bytes': '1154755'}, {'name': 'Objective-C++', 'bytes': '7105145'}, {'name': 'PHP', 'bytes': '97817'}, {'name': 'Perl', 'bytes': '69392'}, {'name': 'Python', 'bytes': '6862570'}, {'name': 'Shell', 'bytes': '478812'}, {'name': 'Standard ML', 'bytes': '4131'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '15206'}]} |
#ifndef __ARCH_ARM_MACH_OMAP2_OMAP_HWMOD_COMMON_DATA_H
#define __ARCH_ARM_MACH_OMAP2_OMAP_HWMOD_COMMON_DATA_H
#include "omap_hwmod.h"
#include "common.h"
#include "display.h"
/* Common address space across OMAP2xxx/3xxx */
extern struct omap_hwmod_addr_space omap2_i2c1_addr_space[];
extern struct omap_hwmod_addr_space omap2_i2c2_addr_space[];
extern struct omap_hwmod_addr_space omap2_dss_addrs[];
extern struct omap_hwmod_addr_space omap2_dss_dispc_addrs[];
extern struct omap_hwmod_addr_space omap2_dss_rfbi_addrs[];
extern struct omap_hwmod_addr_space omap2_dss_venc_addrs[];
extern struct omap_hwmod_addr_space omap2_timer10_addrs[];
extern struct omap_hwmod_addr_space omap2_timer11_addrs[];
extern struct omap_hwmod_addr_space omap2430_mmc1_addr_space[];
extern struct omap_hwmod_addr_space omap2430_mmc2_addr_space[];
extern struct omap_hwmod_addr_space omap2_mcspi1_addr_space[];
extern struct omap_hwmod_addr_space omap2_mcspi2_addr_space[];
extern struct omap_hwmod_addr_space omap2430_mcspi3_addr_space[];
extern struct omap_hwmod_addr_space omap2_dma_system_addrs[];
extern struct omap_hwmod_addr_space omap2_mailbox_addrs[];
extern struct omap_hwmod_addr_space omap2_mcbsp1_addrs[];
extern struct omap_hwmod_addr_space omap2_hdq1w_addr_space[];
/* Common IP block data across OMAP2xxx */
extern struct omap_gpio_dev_attr omap2xxx_gpio_dev_attr;
extern struct omap_hwmod omap2xxx_l3_main_hwmod;
extern struct omap_hwmod omap2xxx_l4_core_hwmod;
extern struct omap_hwmod omap2xxx_l4_wkup_hwmod;
extern struct omap_hwmod omap2xxx_mpu_hwmod;
extern struct omap_hwmod omap2xxx_iva_hwmod;
extern struct omap_hwmod omap2xxx_timer1_hwmod;
extern struct omap_hwmod omap2xxx_timer2_hwmod;
extern struct omap_hwmod omap2xxx_timer3_hwmod;
extern struct omap_hwmod omap2xxx_timer4_hwmod;
extern struct omap_hwmod omap2xxx_timer5_hwmod;
extern struct omap_hwmod omap2xxx_timer6_hwmod;
extern struct omap_hwmod omap2xxx_timer7_hwmod;
extern struct omap_hwmod omap2xxx_timer8_hwmod;
extern struct omap_hwmod omap2xxx_timer9_hwmod;
extern struct omap_hwmod omap2xxx_timer10_hwmod;
extern struct omap_hwmod omap2xxx_timer11_hwmod;
extern struct omap_hwmod omap2xxx_timer12_hwmod;
extern struct omap_hwmod omap2xxx_wd_timer2_hwmod;
extern struct omap_hwmod omap2xxx_uart1_hwmod;
extern struct omap_hwmod omap2xxx_uart2_hwmod;
extern struct omap_hwmod omap2xxx_uart3_hwmod;
extern struct omap_hwmod omap2xxx_dss_core_hwmod;
extern struct omap_hwmod omap2xxx_dss_dispc_hwmod;
extern struct omap_hwmod omap2xxx_dss_rfbi_hwmod;
extern struct omap_hwmod omap2xxx_dss_venc_hwmod;
extern struct omap_hwmod omap2xxx_gpio1_hwmod;
extern struct omap_hwmod omap2xxx_gpio2_hwmod;
extern struct omap_hwmod omap2xxx_gpio3_hwmod;
extern struct omap_hwmod omap2xxx_gpio4_hwmod;
extern struct omap_hwmod omap2xxx_mcspi1_hwmod;
extern struct omap_hwmod omap2xxx_mcspi2_hwmod;
extern struct omap_hwmod omap2xxx_counter_32k_hwmod;
extern struct omap_hwmod omap2xxx_gpmc_hwmod;
extern struct omap_hwmod omap2xxx_rng_hwmod;
extern struct omap_hwmod omap2xxx_sham_hwmod;
extern struct omap_hwmod omap2xxx_aes_hwmod;
/* Common interface data across OMAP2xxx */
extern struct omap_hwmod_ocp_if omap2xxx_l3_main__l4_core;
extern struct omap_hwmod_ocp_if omap2xxx_mpu__l3_main;
extern struct omap_hwmod_ocp_if omap2xxx_dss__l3;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__l4_wkup;
extern struct omap_hwmod_ocp_if omap2_l4_core__uart1;
extern struct omap_hwmod_ocp_if omap2_l4_core__uart2;
extern struct omap_hwmod_ocp_if omap2_l4_core__uart3;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__mcspi1;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__mcspi2;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer2;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer3;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer4;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer5;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer6;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer7;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer8;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer9;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer10;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer11;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__timer12;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__dss;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__dss_dispc;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__dss_rfbi;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__dss_venc;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__rng;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__sham;
extern struct omap_hwmod_ocp_if omap2xxx_l4_core__aes;
/* Common IP block data */
extern struct omap_hwmod_dma_info omap2_uart1_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_uart2_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_uart3_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_i2c1_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_i2c2_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_mcspi1_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_mcspi2_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_mcbsp1_sdma_reqs[];
extern struct omap_hwmod_dma_info omap2_mcbsp2_sdma_reqs[];
/* Common IP block data on OMAP2430/OMAP3 */
extern struct omap_hwmod_dma_info omap2_mcbsp3_sdma_reqs[];
/* Common IP block data across OMAP2/3 */
extern struct omap_hwmod_irq_info omap2_timer1_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer2_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer3_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer4_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer5_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer6_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer7_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer8_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer9_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer10_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_timer11_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_uart1_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_uart2_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_uart3_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_dispc_irqs[];
extern struct omap_hwmod_irq_info omap2_i2c1_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_i2c2_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_gpio1_irqs[];
extern struct omap_hwmod_irq_info omap2_gpio2_irqs[];
extern struct omap_hwmod_irq_info omap2_gpio3_irqs[];
extern struct omap_hwmod_irq_info omap2_gpio4_irqs[];
extern struct omap_hwmod_irq_info omap2_dma_system_irqs[];
extern struct omap_hwmod_irq_info omap2_mcspi1_mpu_irqs[];
extern struct omap_hwmod_irq_info omap2_mcspi2_mpu_irqs[];
extern struct omap_hwmod_addr_space omap2xxx_timer12_addrs[];
extern struct omap_hwmod_irq_info omap2_hdq1w_mpu_irqs[];
/* OMAP hwmod classes - forward declarations */
extern struct omap_hwmod_class l3_hwmod_class;
extern struct omap_hwmod_class l4_hwmod_class;
extern struct omap_hwmod_class mpu_hwmod_class;
extern struct omap_hwmod_class iva_hwmod_class;
extern struct omap_hwmod_class omap2_uart_class;
extern struct omap_hwmod_class omap2_dss_hwmod_class;
extern struct omap_hwmod_class omap2_dispc_hwmod_class;
extern struct omap_hwmod_class omap2_rfbi_hwmod_class;
extern struct omap_hwmod_class omap2_venc_hwmod_class;
extern struct omap_hwmod_class_sysconfig omap2_hdq1w_sysc;
extern struct omap_hwmod_class omap2_hdq1w_class;
extern struct omap_hwmod_class omap2xxx_timer_hwmod_class;
extern struct omap_hwmod_class omap2xxx_wd_timer_hwmod_class;
extern struct omap_hwmod_class omap2xxx_gpio_hwmod_class;
extern struct omap_hwmod_class omap2xxx_dma_hwmod_class;
extern struct omap_hwmod_class omap2xxx_mailbox_hwmod_class;
extern struct omap_hwmod_class omap2xxx_mcspi_class;
extern struct omap_dss_dispc_dev_attr omap2_3_dss_dispc_dev_attr;
#endif
| {'content_hash': '2b596d231c7de11a27c61b8ad5534547', 'timestamp': '', 'source': 'github', 'line_count': 161, 'max_line_length': 65, 'avg_line_length': 49.32298136645963, 'alnum_prop': 0.7939806069764513, 'repo_name': 'lokeshjindal15/pd-gem5', 'id': '2c38c6b0ee034691faf75c1205be0bb6edcbb4e0', 'size': '8344', 'binary': False, 'copies': '344', 'ref': 'refs/heads/master', 'path': 'kernel_dvfs/linux-linaro-tracking-gem5/arch/arm/mach-omap2/omap_hwmod_common_data.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '10138943'}, {'name': 'Awk', 'bytes': '19269'}, {'name': 'C', 'bytes': '469972635'}, {'name': 'C++', 'bytes': '18163034'}, {'name': 'CMake', 'bytes': '2202'}, {'name': 'Clojure', 'bytes': '333'}, {'name': 'Emacs Lisp', 'bytes': '1969'}, {'name': 'Groff', 'bytes': '63956'}, {'name': 'HTML', 'bytes': '136898'}, {'name': 'Hack', 'bytes': '2489'}, {'name': 'Java', 'bytes': '3096'}, {'name': 'Jupyter Notebook', 'bytes': '1231954'}, {'name': 'Lex', 'bytes': '59257'}, {'name': 'M4', 'bytes': '52982'}, {'name': 'Makefile', 'bytes': '1453704'}, {'name': 'Objective-C', 'bytes': '1315749'}, {'name': 'Perl', 'bytes': '716374'}, {'name': 'Perl6', 'bytes': '3727'}, {'name': 'Protocol Buffer', 'bytes': '3246'}, {'name': 'Python', 'bytes': '4102365'}, {'name': 'Scilab', 'bytes': '21433'}, {'name': 'Shell', 'bytes': '512873'}, {'name': 'SourcePawn', 'bytes': '4687'}, {'name': 'UnrealScript', 'bytes': '10556'}, {'name': 'Visual Basic', 'bytes': '2884'}, {'name': 'XS', 'bytes': '1239'}, {'name': 'Yacc', 'bytes': '121715'}]} |
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- From: file:/D:/My%20Projects%231/Android-ObservableScrollView-master/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.0/res/values-lt/values-lt.xml -->
<eat-comment/>
<string msgid="4600421777120114993" name="abc_action_bar_home_description">"Eiti į pagrindinį puslapį"</string>
<string msgid="1594238315039666878" name="abc_action_bar_up_description">"Eiti į viršų"</string>
<string msgid="3588849162933574182" name="abc_action_menu_overflow_description">"Daugiau parinkčių"</string>
<string msgid="4076576682505996667" name="abc_action_mode_done">"Atlikta"</string>
<string msgid="7468859129482906941" name="abc_activity_chooser_view_see_all">"Peržiūrėti viską"</string>
<string msgid="2031811694353399454" name="abc_activitychooserview_choose_application">"Pasirinkti programą"</string>
<string msgid="3691816814315814921" name="abc_searchview_description_clear">"Išvalyti užklausą"</string>
<string msgid="2550479030709304392" name="abc_searchview_description_query">"Paieškos užklausa"</string>
<string msgid="8264924765203268293" name="abc_searchview_description_search">"Paieška"</string>
<string msgid="8928215447528550784" name="abc_searchview_description_submit">"Pateikti užklausą"</string>
<string msgid="893419373245838918" name="abc_searchview_description_voice">"Paieška balsu"</string>
<string msgid="3421042268587513524" name="abc_shareactionprovider_share_with">"Bendrinti naudojant"</string>
<string msgid="7165123711973476752" name="abc_shareactionprovider_share_with_application">"Bendrinti naudojant „%s“"</string>
</resources> | {'content_hash': 'c71cb803c1a7875040d057c2e5b9b67e', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 186, 'avg_line_length': 93.94444444444444, 'alnum_prop': 0.7652276759314015, 'repo_name': 'ZhenisMadiyar/UniversityGuide', 'id': '2088da879d916bc6f266647411822a9c5f79e1cf', 'size': '1717', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/build/intermediates/res/debug/values-lt/values-lt.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '10487'}, {'name': 'CoffeeScript', 'bytes': '1577'}, {'name': 'HTML', 'bytes': '8171'}, {'name': 'Java', 'bytes': '981005'}, {'name': 'JavaScript', 'bytes': '5669'}, {'name': 'Shell', 'bytes': '713'}]} |
<?php
/**
* This class defines the current version of PHPUnit.
*
* @since Class available since Release 2.0.0
*/
class PHPUnit_Runner_Version
{
private static $pharVersion;
private static $version;
/**
* Returns the current version of PHPUnit.
*
* @return string
*/
public static function id()
{
if (self::$pharVersion !== null) {
return self::$pharVersion;
}
if (self::$version === null) {
$version = new SebastianBergmann\Version('4.8.11', dirname(dirname(__DIR__)));
self::$version = $version->getVersion();
}
return self::$version;
}
/**
* @return string
*/
public static function getVersionString()
{
return 'PHPUnit ' . self::id() . ' by Sebastian Bergmann and contributors.';
}
/**
* @return string
* @since Method available since Release 4.0.0
*/
public static function getReleaseChannel()
{
if (strpos(self::$pharVersion, 'alpha') !== false) {
return '-alpha';
}
if (strpos(self::$pharVersion, 'beta') !== false) {
return '-beta';
}
return '';
}
}
| {'content_hash': 'f0909805c4086ea164083140f11c1a8c', 'timestamp': '', 'source': 'github', 'line_count': 57, 'max_line_length': 96, 'avg_line_length': 21.50877192982456, 'alnum_prop': 0.5309951060358891, 'repo_name': 'fian005/asiavia_dev', 'id': '58e339048d23c587aaf896da63a7f1d3cb086e24', 'size': '1447', 'binary': False, 'copies': '246', 'ref': 'refs/heads/master', 'path': 'vendor/phpunit/phpunit/src/Runner/Version.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '34257'}, {'name': 'C++', 'bytes': '50616'}, {'name': 'CSS', 'bytes': '419955'}, {'name': 'HTML', 'bytes': '488556'}, {'name': 'JavaScript', 'bytes': '853618'}, {'name': 'PHP', 'bytes': '28482046'}, {'name': 'Shell', 'bytes': '47922'}]} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '2d2442f95cddcfee0d1ec3016326bdf9', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '5b7f9035e1a0d4334aa8ca2f3db7144fdba6c646', 'size': '181', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Tetramicra/Tetramicra simplex/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
<?php
/* SVN FILE: $Id$ */
/**
* Short description for file.
*
* Long description for file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <https://trac.cakephp.org/wiki/Developement/TestSuite>
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @filesource
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
* @link https://trac.cakephp.org/wiki/Developement/TestSuite CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.fixtures
* @since CakePHP(tm) v 1.2.0.4667
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
/**
* Short description for class.
*
* @package cake
* @subpackage cake.tests.fixtures
*/
class AdvertisementFixture extends CakeTestFixture {
/**
* name property
*
* @var string 'Advertisement'
* @access public
*/
var $name = 'Advertisement';
/**
* fields property
*
* @var array
* @access public
*/
var $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'title' => array('type' => 'string', 'null' => false),
'created' => 'datetime',
'updated' => 'datetime'
);
/**
* records property
*
* @var array
* @access public
*/
var $records = array(
array('title' => 'First Ad', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'),
array('title' => 'Second Ad', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31')
);
}
?> | {'content_hash': '05ee8be81ba1682b9aa02428633b63e7', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 103, 'avg_line_length': 26.784615384615385, 'alnum_prop': 0.6364158529580701, 'repo_name': 'fiuwebteam/Calendar', 'id': '81ad9251ec6c9e236e1e5afc1dd587c02c2ed02e', 'size': '1741', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'vendors/cake/tests/fixtures/advertisement_fixture.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '482997'}, {'name': 'PHP', 'bytes': '21460133'}]} |
<?php
/**
* Parsing PHP with QueryPath
*
* This file contains an example of how QueryPath can be used
* to parse a PHP file. Any well-formed XML or HTML document can be parsed. Since
* PHP tags are contained inside of processor instructions, an XML parser can
* correctly parse such a file into a DOM. Consequently, you can use QueryPath
* to read, modify, and traverse PHP files.
*
* This example illustrates how such a file can be parsed and manipulated.
*
*
* @author M Butcher <[email protected]>
* @license LGPL The GNU Lesser GPL (LGPL) or an MIT-like license.
*/
?>
<html>
<head>
<title>Parse PHP from QueryPath</title>
</head>
<body>
<?php
require '../src/QueryPath/QueryPath.php';
// Parse this file with QueryPath.
print qp(__FILE__, 'title')->text();
?>
</body>
</html> | {'content_hash': '2ee88ad5a51dc9fa9843b59e2dcd69b0', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 81, 'avg_line_length': 26.666666666666668, 'alnum_prop': 0.7, 'repo_name': 'morido/tud_newsscraper', 'id': '5947f0a0cbed64778fdf5d71080f7c24c2cdbc08', 'size': '800', 'binary': False, 'copies': '27', 'ref': 'refs/heads/master', 'path': 'vendor/querypath/querypath/examples/parse_php.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '37963'}]} |
Halcyon::Application.route do |r|
# Sample route for the sample functionality in Application.
# Safe to remove!
# r.match('/time').to(:controller => 'application', :action => 'time')
# RESTful routes
r.resources :questions
# r.match('/questions/random').to(:controller => 'questions', :action => 'random')
# This is the default route for /:controller/:action/:id
# This is fine for most cases. If you're heavily using resource-based
# routes, you may want to comment/remove this line to prevent
# clients from calling your create or destroy actions with a GET
r.default_routes
# Change this for the default route to be available at /
# r.match('/').to(:controller => 'application', :action => 'index')
# It can often be useful to respond with available functionality if the
# application is a public-facing service.
# Default not-found route
{:action => 'not_found'}
end
| {'content_hash': '96d497a842dcfd73ffa36032a7328324', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 84, 'avg_line_length': 36.96, 'alnum_prop': 0.6893939393939394, 'repo_name': 'DouglasAllen/halcyon', 'id': '08f5b29cc4058119af94746c7f2a0d7758bb7d6f', 'size': '1888', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'examples/guesser/config/initialize/routes.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '6757'}, {'name': 'JavaScript', 'bytes': '1160'}, {'name': 'Ruby', 'bytes': '136660'}]} |
declare const _default: import("expo-modules-core").ProxyNativeModule;
export default _default;
//# sourceMappingURL=ExponentSpeech.d.ts.map | {'content_hash': 'fa29ce5eb84cc398a57f0a618cdc9cf8', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 70, 'avg_line_length': 46.666666666666664, 'alnum_prop': 0.8071428571428572, 'repo_name': 'exponentjs/exponent', 'id': '73a5631f31684a69e53adbf9c983b2ec81db2f11', 'size': '140', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'packages/expo-speech/build/ExponentSpeech.d.ts', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '96902'}, {'name': 'Batchfile', 'bytes': '382'}, {'name': 'C', 'bytes': '896724'}, {'name': 'C++', 'bytes': '867983'}, {'name': 'CSS', 'bytes': '6732'}, {'name': 'HTML', 'bytes': '152590'}, {'name': 'IDL', 'bytes': '897'}, {'name': 'Java', 'bytes': '4588748'}, {'name': 'JavaScript', 'bytes': '9343259'}, {'name': 'Makefile', 'bytes': '8790'}, {'name': 'Objective-C', 'bytes': '10675806'}, {'name': 'Objective-C++', 'bytes': '364286'}, {'name': 'Perl', 'bytes': '5860'}, {'name': 'Prolog', 'bytes': '287'}, {'name': 'Python', 'bytes': '97564'}, {'name': 'Ruby', 'bytes': '45432'}, {'name': 'Shell', 'bytes': '6501'}]} |
package com.google.template.soy.jssrc.dsl;
import com.google.auto.value.AutoValue;
import com.google.errorprone.annotations.Immutable;
/** Represents a {@code for} statement. */
@AutoValue
@Immutable
abstract class For extends CodeChunk {
abstract String localVar();
abstract CodeChunk.WithValue initial();
abstract CodeChunk.WithValue limit();
abstract CodeChunk.WithValue increment();
abstract CodeChunk body();
static For create(
String localVar,
CodeChunk.WithValue initial,
CodeChunk.WithValue limit,
CodeChunk.WithValue increment,
CodeChunk body) {
return new AutoValue_For(localVar, initial, limit, increment, body);
}
@Override
public void collectRequires(RequiresCollector collector) {
initial().collectRequires(collector);
limit().collectRequires(collector);
increment().collectRequires(collector);
body().collectRequires(collector);
}
@Override
void doFormatInitialStatements(FormattingContext ctx) {
ctx.appendInitialStatements(initial())
.appendInitialStatements(limit())
.appendInitialStatements(increment());
ctx.append("for (var " + localVar() + " = ")
.appendOutputExpression(initial())
.append("; " + localVar() + " < ")
.appendOutputExpression(limit())
.append("; ");
if ((increment() instanceof Leaf) && "1".equals(((Leaf) increment()).value().getText())) {
ctx.append(localVar() + "++");
} else {
ctx.append(localVar() + " += ").appendOutputExpression(increment());
}
ctx.append(") ");
try (FormattingContext ignored = ctx.enterBlock()) {
ctx.appendAll(body());
}
}
}
| {'content_hash': '3bc60a963690262fecdacb1f3b7c6bf3', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 94, 'avg_line_length': 26.234375, 'alnum_prop': 0.6688505062537224, 'repo_name': 'rpatil26/closure-templates', 'id': '8f7a287b78fdbd50185ee88c2111be51bd291148', 'size': '2273', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'java/src/com/google/template/soy/jssrc/dsl/For.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '23189'}, {'name': 'Java', 'bytes': '5917948'}, {'name': 'JavaScript', 'bytes': '1616706'}, {'name': 'Python', 'bytes': '75015'}]} |
import functools
from .utils import url_for_content
from .formats import get_format
from .paginator import Paginator
from flask import url_for
from flask import current_app as app
from quokka.utils.text import (
slugify, slugify_category, make_social_link,
make_social_name, make_external_url
)
from quokka.utils.dateformat import pretty_date
from quokka.utils.custom_vars import custom_var_dict
DEFAULT_DATE_FORMAT = '%a %d %B %Y'
@functools.total_ordering
class Orderable:
is_content = False # to use in templates
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.slug == other.slug
if isinstance(other, str):
return self.slug == self._normalize_key(other)
return False
def __ne__(self, other):
if isinstance(other, self.__class__):
return self.slug != other.slug
if isinstance(other, str):
return self.slug != self._normalize_key(other)
return True
def __lt__(self, other):
if isinstance(other, self.__class__):
return self.slug < other.slug
if isinstance(other, str):
return self.slug < self._normalize_key(other)
return False
def __hash__(self):
return hash(self.slug)
def _normalize_key(self, key):
return slugify(key)
def __html__(self):
return str(self)
@property
def external_url(self):
return make_external_url(self.url)
class Series(Orderable):
def __init__(self, name, index=1):
self.name = self.slug = name
self._index = index
@property
def index(self):
return self._index
@property
def next(self):
return []
@property
def previous(self):
return []
@property
def all(self):
return []
@property
def all_previous(self):
return []
@property
def all_next(self):
return []
class Category(Orderable):
def __init__(self, category):
self.category = category
self.slug = slugify_category(category)
if category == self.slug:
self.name = category.replace('-', ' ').title()
else:
self.name = category
@property
def url(self):
return self.slug
def __str__(self):
return self.category
class Fixed(Orderable):
"""Fixed pages like /authors/ and /tags/ and /categories/"""
def __init__(self, name):
self.name = name
self.slug = slugify_category(name)
@property
def url(self):
return self.slug
def __str__(self):
return self.name
class Url(Fixed):
"""For compatibility"""
def __init__(self, name):
self.name = name
self.slug = name
class Author(Orderable):
def __init__(self, authors):
self.authors = authors
self._profile_page = 'empty'
@property
def name(self):
if isinstance(self.authors, str):
return self.authors.replace('-', ' ').replace('/', ' & ').title()
elif isinstance(self.authors, (list, tuple)):
return ', '.join(self.authors)
@property
def slug(self):
if isinstance(self.authors, str):
return slugify(self.authors)
if len(self.authors) > 1:
return '/'.join(
slugify(author) for author in self.authors
)
else:
return slugify(self.authors[0])
@property
def social(self):
# twitter: ...
return {}
@property
def url(self):
return f'author/{self.slug}'
def __str__(self):
return self.name
@property
def profile_page(self):
if self._profile_page == 'empty':
profile = app.db.get(
'index',
{'content_type': 'block',
'slug': self.slug,
'published': True}
)
if profile:
self._profile_page = Block(profile)
else:
self._profile_page = None
return self._profile_page
class Tag(Orderable):
def __init__(self, name):
self.name = name
self.slug = slugify(name)
@property
def url(self):
return f'tag/{self.slug}/index.html'
def __str__(self):
return self.name
def __getitem__(self, item):
return self
class Content:
is_content = True # to use in templates
def __init__(self, data):
self.data = data
self.format = get_format(data)
@property
def url(self):
return url_for_content(self)
@property
def external_url(self):
return make_external_url(self.url)
@property
def locale_date(self):
if app.theme_context.get('SHOW_PRETTY_DATES') is True:
return pretty_date(self.data['date'])
date_format = app.theme_context.get(
'DEFAULT_DATE_FORMAT', DEFAULT_DATE_FORMAT
)
return self.data['date'].strftime(date_format)
@property
def locale_modified(self):
if app.theme_context.get('SHOW_PRETTY_DATES') is True:
return pretty_date(self.data['modified'])
date_format = app.theme_context.get(
'DEFAULT_DATE_FORMAT', DEFAULT_DATE_FORMAT
)
return self.data['modified'].strftime(date_format)
@property
def metadata(self):
# TODO: get metadata from database
# TODO: implement libratar/gravatar
# return {
# 'cover': 'foo',
# 'author_gravatar': 'http://i.pravatar.cc/300',
# 'about_author': 'About Author',
# 'translations': ['en'],
# 'og_image': 'foo',
# 'series': 'aa',
# 'asides': 'aaa'
# }
data = {}
data.update(custom_var_dict(self.data.get('custom_vars')))
return data
@property
def author_gravatar(self):
return self.author_avatar
@property
def author_avatar(self):
if self.author.profile_page:
return self.author.profile_page.author_avatar
return self.metadata.get(
'author_avatar',
app.theme_context.get(
'AVATAR',
'https://api.adorable.io/avatars/250/quokkacms.png'
)
)
@property
def summary(self):
# return self.metadata.get('summary') or self.data.get('summary') or ''
return self.get('summary', '')
@property
def header_cover(self):
return None
@property
def header_color(self):
return None
@property
def sidebar(self):
return True
@property
def use_schema_org(self):
return True
@property
def comments(self):
# data = self.data.get('comments', None)
# if data is not None:
# return data or 'closed'
return "closed" if not self.data.get('comments') else "opened"
@property
def status(self):
return "draft" if not self.data.get('published') else "published"
@property
def published(self):
return self.data.get('published')
@property
def lang(self):
return self.data.get('language')
@property
def author(self):
if self.data.get('authors'):
return Author(self.data['authors'])
@property
def related_posts(self):
# TODO: depends on CONTENT_ADD_RELATED_POSTS
return []
@property
def banner(self):
# TODO: get it from model
# return 'http://lorempixel.com/1000/600/abstract/'
return url_for('theme_static', filename='img/island.jpg')
@property
def image(self):
return self.banner
@property
def series(self):
# https://github.com/getpelican/pelican-plugins/tree/master/series
return Series('foo')
@property
def content(self):
return self.format.render(self.data) or ''
@property
def category(self):
return Category(self.data['category'])
@property
def tags(self):
return [Tag(tag) for tag in self.data.get('tags', [])]
@property
def keywords(self):
return self.tags
@property
def description(self):
return self.summary
@property
def menulabel(self):
return self.title
@property
def name(self):
return self.title
def __getattr__(self, attr):
value = self.metadata.get(attr) or self.data.get(attr)
if not value:
raise AttributeError(f'{self} do not have {attr}')
return value
def __getitem__(self, item):
return self.__getattr__(item)
def __str__(self):
for name in ['title', 'name', '_id']:
if self.data.get(name):
return self.data[name]
return str(self.__class__)
def __html__(self):
return str(self)
def get(self, name, *args, **kwargs):
return self.metadata.get(
name
) or self.data.get(
name, *args, **kwargs
)
class Article(Content):
"""Represents dated authored article"""
class Page(Content):
"""Represents a static page"""
class Block(Content):
"""Represents a block of items"""
@property
def block_items(self):
return [
make_model(item) for item in self.data['block_items']
]
@property
def author_avatar(self):
if self.metadata.get('author_avatar'):
# TODO: deal with uploads here
return self.metadata.get('author_avatar')
if self.metadata.get('gravatar_email'):
return f"https://avatars.io/gravatar/{make_social_name(self.metadata.get('gravatar_email'))}" # noqa
if self.metadata.get('twitter'):
return f"https://avatars.io/twitter/{make_social_name(self.metadata.get('twitter'))}" # noqa
if self.metadata.get('facebook'):
return f"https://avatars.io/facebook/{make_social_name(self.metadata.get('facebook'))}" # noqa
if self.metadata.get('instagram'):
return f"https://avatars.io/instagram/{make_social_name(self.metadata.get('instagram'))}" # noqa
return f'https://api.adorable.io/avatars/250/{self.slug}.png'
@property
def social_links(self):
links = []
for social, social_link in app.theme_context.get('SOCIALNETWORKS', []):
link = self.metadata.get(social)
if link:
links.append((social, make_social_link(social_link, link)))
return links
class BlockItem(Content):
"""Represents an item inside a block"""
@property
def is_block(self):
return isinstance(self.item, Block)
@property
def is_dropdown(self):
return self.item_type == 'dropdown'
@property
def item(self):
if self.metadata.get('index_id') or self.data.get('index_id'):
return make_model(app.db.get('index', {'_id': self.index_id}))
for ref in ['author', 'category', 'tag', 'url']:
data = self.data.get(f"{ref}_id")
if data:
return make_model(data, ref)
return self.metadata.get('item') or self.data.get('item')
@property
def name(self):
given_name = self.metadata.get('name') or self.data.get('name')
given_title = self.metadata.get('title')
try:
item_name = self.item.name
except AttributeError:
item_name = self.item
return given_name or given_title or item_name
@property
def url(self):
try:
return self.item.url
except AttributeError:
return self.data['item']
def make_model(content, content_type=None):
if isinstance(content, Content):
return content
content_type = content_type or content.get('content_type', 'content')
words = [word.capitalize() for word in content_type.lower().split('_')]
model_name = ''.join(words)
return globals().get(model_name, Content)(content)
def make_paginator(object_list, *args, **kwargs):
object_list = [
obj if isinstance(obj, Content) else make_model(obj)
for obj
in object_list
]
return Paginator(object_list, *args, **kwargs)
| {'content_hash': '4eda9fa30a5c0d2e826df23e3f7c179c', 'timestamp': '', 'source': 'github', 'line_count': 477, 'max_line_length': 113, 'avg_line_length': 25.77358490566038, 'alnum_prop': 0.5706848869367172, 'repo_name': 'abnerpc/quokka', 'id': '6d2fcc4d97b6a5844564497408939688eb0302c2', 'size': '12294', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'quokka/core/content/models.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '104'}, {'name': 'CSS', 'bytes': '32332'}, {'name': 'HTML', 'bytes': '119354'}, {'name': 'JavaScript', 'bytes': '494398'}, {'name': 'Makefile', 'bytes': '503'}, {'name': 'Python', 'bytes': '199573'}, {'name': 'Shell', 'bytes': '12305'}]} |
#import "ZXBitMatrix.h"
#import "ZXDataMask.h"
#import "ZXErrors.h"
#import "ZXFormatInformation.h"
#import "ZXQRCodeBitMatrixParser.h"
#import "ZXQRCodeVersion.h"
@interface ZXQRCodeBitMatrixParser ()
@property (nonatomic, strong) ZXBitMatrix *bitMatrix;
@property (nonatomic, strong) ZXFormatInformation *parsedFormatInfo;
@property (nonatomic, strong) ZXQRCodeVersion *parsedVersion;
@end
@implementation ZXQRCodeBitMatrixParser
- (id)initWithBitMatrix:(ZXBitMatrix *)bitMatrix error:(NSError **)error {
int dimension = bitMatrix.height;
if (dimension < 21 || (dimension & 0x03) != 1) {
if (error) *error = FormatErrorInstance();
return nil;
}
if (self = [super init]) {
_bitMatrix = bitMatrix;
_parsedFormatInfo = nil;
_parsedVersion = nil;
}
return self;
}
/**
* Reads format information from one of its two locations within the QR Code.
*/
- (ZXFormatInformation *)readFormatInformationWithError:(NSError **)error {
if (self.parsedFormatInfo != nil) {
return self.parsedFormatInfo;
}
int formatInfoBits1 = 0;
for (int i = 0; i < 6; i++) {
formatInfoBits1 = [self copyBit:i j:8 versionBits:formatInfoBits1];
}
formatInfoBits1 = [self copyBit:7 j:8 versionBits:formatInfoBits1];
formatInfoBits1 = [self copyBit:8 j:8 versionBits:formatInfoBits1];
formatInfoBits1 = [self copyBit:8 j:7 versionBits:formatInfoBits1];
for (int j = 5; j >= 0; j--) {
formatInfoBits1 = [self copyBit:8 j:j versionBits:formatInfoBits1];
}
int dimension = self.bitMatrix.height;
int formatInfoBits2 = 0;
int jMin = dimension - 7;
for (int j = dimension - 1; j >= jMin; j--) {
formatInfoBits2 = [self copyBit:8 j:j versionBits:formatInfoBits2];
}
for (int i = dimension - 8; i < dimension; i++) {
formatInfoBits2 = [self copyBit:i j:8 versionBits:formatInfoBits2];
}
self.parsedFormatInfo = [ZXFormatInformation decodeFormatInformation:formatInfoBits1 maskedFormatInfo2:formatInfoBits2];
if (self.parsedFormatInfo != nil) {
return self.parsedFormatInfo;
}
if (error) *error = FormatErrorInstance();
return nil;
}
/**
* Reads version information from one of its two locations within the QR Code.
*/
- (ZXQRCodeVersion *)readVersionWithError:(NSError **)error {
if (self.parsedVersion != nil) {
return self.parsedVersion;
}
int dimension = self.bitMatrix.height;
int provisionalVersion = (dimension - 17) >> 2;
if (provisionalVersion <= 6) {
return [ZXQRCodeVersion versionForNumber:provisionalVersion];
}
int versionBits = 0;
int ijMin = dimension - 11;
for (int j = 5; j >= 0; j--) {
for (int i = dimension - 9; i >= ijMin; i--) {
versionBits = [self copyBit:i j:j versionBits:versionBits];
}
}
ZXQRCodeVersion *theParsedVersion = [ZXQRCodeVersion decodeVersionInformation:versionBits];
if (theParsedVersion != nil && theParsedVersion.dimensionForVersion == dimension) {
self.parsedVersion = theParsedVersion;
return self.parsedVersion;
}
versionBits = 0;
for (int i = 5; i >= 0; i--) {
for (int j = dimension - 9; j >= ijMin; j--) {
versionBits = [self copyBit:i j:j versionBits:versionBits];
}
}
theParsedVersion = [ZXQRCodeVersion decodeVersionInformation:versionBits];
if (theParsedVersion != nil && theParsedVersion.dimensionForVersion == dimension) {
self.parsedVersion = theParsedVersion;
return self.parsedVersion;
}
if (error) *error = FormatErrorInstance();
return nil;
}
- (int)copyBit:(int)i j:(int)j versionBits:(int)versionBits {
return [self.bitMatrix getX:i y:j] ? (versionBits << 1) | 0x1 : versionBits << 1;
}
/**
* Reads the bits in the {@link BitMatrix} representing the finder pattern in the
* correct order in order to reconstitute the codewords bytes contained within the
* QR Code.
*/
- (NSArray *)readCodewordsWithError:(NSError **)error {
ZXFormatInformation *formatInfo = [self readFormatInformationWithError:error];
if (!formatInfo) {
return nil;
}
ZXQRCodeVersion *version = [self readVersionWithError:error];
if (!version) {
return nil;
}
ZXDataMask *dataMask = [ZXDataMask forReference:(int)[formatInfo dataMask]];
int dimension = self.bitMatrix.height;
[dataMask unmaskBitMatrix:self.bitMatrix dimension:dimension];
ZXBitMatrix *functionPattern = [version buildFunctionPattern];
BOOL readingUp = YES;
NSMutableArray *result = [NSMutableArray array];
int resultOffset = 0;
int currentByte = 0;
int bitsRead = 0;
for (int j = dimension - 1; j > 0; j -= 2) {
if (j == 6) {
j--;
}
for (int count = 0; count < dimension; count++) {
int i = readingUp ? dimension - 1 - count : count;
for (int col = 0; col < 2; col++) {
if (![functionPattern getX:j - col y:i]) {
bitsRead++;
currentByte <<= 1;
if ([self.bitMatrix getX:j - col y:i]) {
currentByte |= 1;
}
if (bitsRead == 8) {
[result addObject:@((char)currentByte)];
resultOffset++;
bitsRead = 0;
currentByte = 0;
}
}
}
}
readingUp ^= YES;
}
if (resultOffset != [version totalCodewords]) {
if (error) *error = FormatErrorInstance();
return nil;
}
return result;
}
@end
| {'content_hash': '740b6983d8fd6a322d4271cd27d3d4c9', 'timestamp': '', 'source': 'github', 'line_count': 188, 'max_line_length': 122, 'avg_line_length': 28.18617021276596, 'alnum_prop': 0.6655972825061333, 'repo_name': '611161512/Hiooy', 'id': 'ae42c51ffe1942a9ea533b840a9d0d36d8216037', 'size': '5896', 'binary': False, 'copies': '44', 'ref': 'refs/heads/master', 'path': 'Hiooy/hiooy/hiooy4iOS/Common/ZXingObjC/qrcode/decoder/ZXQRCodeBitMatrixParser.m', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '13209'}, {'name': 'CSS', 'bytes': '25697'}, {'name': 'HTML', 'bytes': '33126'}, {'name': 'JavaScript', 'bytes': '14533'}, {'name': 'Objective-C', 'bytes': '3701432'}]} |
module Travis
module Api
module V2
module Http
class EnvVar < Travis::Api::Serializer
attributes :id, :name, :value, :public, :repository_id
def value
if object.public?
object.value.decrypt
end
end
def serializable_hash
hash = super
hash.delete :value unless object.public?
hash
end
end
end
end
end
end
| {'content_hash': '3936e5365e338649e7bcdb84171ea117', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 64, 'avg_line_length': 20.391304347826086, 'alnum_prop': 0.5053304904051172, 'repo_name': 'Tiger66639/travis-api', 'id': '864392a14ca9d5f91e68a859db3eae257abb98c4', 'size': '469', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/travis/api/v2/http/env_var.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '498801'}, {'name': 'Shell', 'bytes': '318'}]} |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Immutable. Thread-safe.
'''
''' Represents a type substitution, with substitutions of types for a set of type parameters.
''' Each TypeSubstitution object has three pieces of information:
''' - OriginalDefinition of generic symbol the substitution is targeting.
''' - An array of pairs that provide a mapping from symbol's type parameters to type arguments.
''' identity substitutions are omitted.
''' - TypeSubstitution object for containing type to provide mapping for its type
''' parameters, if any.
'''
''' The identity substitution (for the whole type hierarchy) is represented by Nothing. That said,
''' top level parent of non-Nothing instance of TypeSubstitution is guaranteed to be non-identity
''' substitution. The instance may still be an identity substitution just for target generic definition,
''' which will be represented by an empty mapping array.
'''
''' The chain of TypeSubstitution objects is guaranteed to not skip any type in the containership hierarchy,
''' even types with zero arity contained in generic type will have corresponding TypeSubstitution object with
''' empty mapping array.
'''
''' Example:
''' Class A(Of T,S)
''' Class B
''' Class C(Of U)
''' End Class
''' End Class
''' End Class
'''
''' TypeSubstitution for A(Of Integer, S).B.C(Of Byte) is C{U->Byte}=>B{}=>A{T->Integer}
''' TypeSubstitution for A(Of T, S).B.C(Of Byte) is C{U->Byte}
''' TypeSubstitution for A(Of Integer, S).B is B{}=>A{T->Integer}
''' TypeSubstitution for A(Of Integer, S).B.C(Of U) is C{}=>B{}=>A{T->Integer}
'''
''' CONSIDER:
''' An array of KeyValuePair(Of TypeParameterSymbol, TypeSymbol)objects is used to represent type
''' parameter substitution mostly due to historical reasons. It might be more convenient and more
''' efficient to use ordinal based array of TypeSymbol objects instead.
'''
''' There is a Construct method that can be called on original definition with TypeSubstitution object as
''' an argument. The advantage of that method is the ability to substitute type parameters of several types
''' in the containership hierarchy in one call. What type the TypeSubstitution parameter targets makes a
''' difference.
'''
''' For example:
''' C.Construct(C{}=>B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of U)
''' C.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of )
''' B.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B
'''
''' See comment for IsValidToApplyTo method as well.
''' </summary>
Friend Class TypeSubstitution
''' <summary>
''' A map between type parameters of _targetGenericDefinition and corresponding type arguments.
''' Represented by an array of Key-Value pairs. Keys are type parameters of _targetGenericDefinition
''' in no particular order. Identity substitutions are omitted.
''' </summary>
Private ReadOnly _pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
''' <summary>
''' Definition of a symbol which this instance of TypeSubstitution primarily targets.
''' </summary>
Private ReadOnly _targetGenericDefinition As Symbol
''' <summary>
''' An instance of TypeSubstitution describing substitution for containing type.
''' </summary>
Private ReadOnly _parent As TypeSubstitution
Public ReadOnly Property Pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
Return _pairs
End Get
End Property
''' <summary>
''' Get all the pairs of substitutions, including from the parent substitutions. The substitutions
''' are in order from outside-in (parent substitutions before child substitutions).
''' </summary>
Public ReadOnly Property PairsIncludingParent As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
If _parent Is Nothing Then
Return Pairs
Else
Dim pairBuilder = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
AddPairsIncludingParentToBuilder(pairBuilder)
Return pairBuilder.ToImmutableAndFree()
End If
End Get
End Property
'Add pairs (including parent pairs) to the given array builder.
Private Sub AddPairsIncludingParentToBuilder(pairBuilder As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)))
If _parent IsNot Nothing Then
_parent.AddPairsIncludingParentToBuilder(pairBuilder)
End If
pairBuilder.AddRange(_pairs)
End Sub
Public ReadOnly Property Parent As TypeSubstitution
Get
Return _parent
End Get
End Property
Public ReadOnly Property TargetGenericDefinition As Symbol
Get
Return _targetGenericDefinition
End Get
End Property
' If this substitution contains the given type parameter, return the substituted type.
' Otherwise, returns the type parameter itself.
Public Function GetSubstitutionFor(tp As TypeParameterSymbol) As TypeWithModifiers
Debug.Assert(tp IsNot Nothing)
Debug.Assert(tp.IsDefinition OrElse TargetGenericDefinition Is tp.ContainingSymbol)
Dim containingSymbol As Symbol = tp.ContainingSymbol
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is containingSymbol Then
For Each p In current.Pairs
If p.Key.Equals(tp) Then Return p.Value
Next
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End If
current = current.Parent
Loop While current IsNot Nothing
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End Function
Public Function GetTypeArgumentsFor(originalDefinition As NamedTypeSymbol, <Out> ByRef hasTypeArgumentsCustomModifiers As Boolean) As ImmutableArray(Of TypeSymbol)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Dim result = ArrayBuilder(Of TypeSymbol).GetInstance(originalDefinition.Arity, Nothing)
hasTypeArgumentsCustomModifiers = False
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
result(p.Key.Ordinal) = p.Value.Type
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
hasTypeArgumentsCustomModifiers = True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
For i As Integer = 0 To result.Count - 1
If result(i) Is Nothing Then
result(i) = originalDefinition.TypeParameters(i)
End If
Next
Return result.ToImmutableAndFree()
End Function
Public Function GetTypeArgumentsCustomModifiersFor(originalDefinition As NamedTypeSymbol) As ImmutableArray(Of ImmutableArray(Of CustomModifier))
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Dim result = ArrayBuilder(Of ImmutableArray(Of CustomModifier)).GetInstance(originalDefinition.Arity, ImmutableArray(Of CustomModifier).Empty)
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
result(p.Key.Ordinal) = p.Value.CustomModifiers
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return result.ToImmutableAndFree()
End Function
Public Function HasTypeArgumentsCustomModifiersFor(originalDefinition As NamedTypeSymbol) As Boolean
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
Return True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Verify TypeSubstitution to make sure it doesn't map any
''' type parameter to an alpha-renamed type parameter.
''' </summary>
''' <remarks></remarks>
Public Sub ThrowIfSubstitutingToAlphaRenamedTypeParameter()
Dim toCheck As TypeSubstitution = Me
Do
For Each pair In toCheck.Pairs
Dim value As TypeSymbol = pair.Value.Type
If value.IsTypeParameter() AndAlso Not value.IsDefinition Then
Throw New ArgumentException()
End If
Next
toCheck = toCheck.Parent
Loop While toCheck IsNot Nothing
End Sub
''' <summary>
''' Return TypeSubstitution instance that targets particular generic definition.
''' </summary>
Public Function GetSubstitutionForGenericDefinition(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is targetGenericDefinition Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Return TypeSubstitution instance that targets particular
''' generic definition or one of its containers.
''' </summary>
Public Function GetSubstitutionForGenericDefinitionOrContainers(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.IsValidToApplyTo(targetGenericDefinition) Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Does substitution target either genericDefinition or
''' one of its containers?
''' </summary>
Public Function IsValidToApplyTo(genericDefinition As Symbol) As Boolean
Debug.Assert(genericDefinition.IsDefinition)
Dim current As Symbol = genericDefinition
Do
If current Is Me.TargetGenericDefinition Then
Return True
End If
current = current.ContainingType
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Combine two substitutions into one by concatenating.
'''
''' They may not directly or indirectly (through Parent) target the same generic definition.
''' sub2 is expected to target types lower in the containership hierarchy.
''' Either or both can be Nothing.
'''
''' targetGenericDefinition specifies target generic definition for the result.
''' If sub2 is not Nothing, it must target targetGenericDefinition.
''' If sub2 is Nothing, sub1 will be "extended" with identity substitutions to target
''' targetGenericDefinition.
''' </summary>
Public Shared Function Concat(targetGenericDefinition As Symbol, sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
Debug.Assert(sub2 Is Nothing OrElse sub2.TargetGenericDefinition Is targetGenericDefinition)
If sub1 Is Nothing Then
Return sub2
Else
Debug.Assert(sub1.TargetGenericDefinition.IsDefinition)
If sub2 Is Nothing Then
If targetGenericDefinition Is sub1.TargetGenericDefinition Then
Return sub1
End If
Return Concat(sub1, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
Else
Return ConcatNotNulls(sub1, sub2)
End If
End If
End Function
Private Shared Function ConcatNotNulls(sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
If sub2.Parent Is Nothing Then
Return Concat(sub1, sub2.TargetGenericDefinition, sub2.Pairs)
Else
Return Concat(ConcatNotNulls(sub1, sub2.Parent), sub2.TargetGenericDefinition, sub2.Pairs)
End If
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeWithModifiers,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeSymbol,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
If params.Length <> args.Length Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim currentParent As TypeSubstitution = Nothing
Dim currentContainer As Symbol = Nothing
#If DEBUG Then
Dim haveSubstitutionForOrdinal = BitVector.Create(params.Length)
#End If
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Try
For i = 0 To params.Length - 1
Dim param As TypeParameterSymbol = params(i)
Dim arg As TypeWithModifiers = args(i)
Debug.Assert(param.IsDefinition)
If currentContainer IsNot param.ContainingSymbol Then
' starting new segment, finish the current one
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
pairs.Clear()
End If
currentContainer = param.ContainingSymbol
#If DEBUG Then
haveSubstitutionForOrdinal.Clear()
#End If
End If
#If DEBUG Then
Debug.Assert(Not haveSubstitutionForOrdinal(param.Ordinal))
haveSubstitutionForOrdinal(param.Ordinal) = True
#End If
If arg.Is(param) Then
Continue For
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(param, arg))
Next
' finish the current segment
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
End If
Finally
pairs.Free()
End Try
If currentParent IsNot Nothing AndAlso currentParent.TargetGenericDefinition IsNot targetGenericDefinition Then
currentParent = Concat(currentParent, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
#If DEBUG Then
ElseIf currentContainer IsNot Nothing AndAlso currentContainer IsNot targetGenericDefinition Then
' currentContainer must be either targetGenericDefinition or a container of targetGenericDefinition
Dim container As NamedTypeSymbol = targetGenericDefinition.ContainingType
While container IsNot Nothing AndAlso container IsNot currentContainer
container = container.ContainingType
End While
Debug.Assert(container Is currentContainer)
#End If
End If
Return currentParent
End Function
Private Shared ReadOnly _withoutModifiers As Func(Of TypeSymbol, TypeWithModifiers) = Function(arg) New TypeWithModifiers(arg)
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition,
params,
args.SelectAsArray(_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(parent,
targetGenericDefinition,
args.SelectAsArray(_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Private helper to make sure identity substitutions are injected for types between
''' targetGenericDefinition and parent.TargetGenericDefinition.
''' </summary>
Private Shared Function Concat(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
) As TypeSubstitution
If parent Is Nothing OrElse parent.TargetGenericDefinition Is targetGenericDefinition.ContainingType Then
Return New TypeSubstitution(targetGenericDefinition, pairs, parent)
End If
Dim containingType As NamedTypeSymbol = targetGenericDefinition.ContainingType
Debug.Assert(containingType IsNot Nothing)
Return New TypeSubstitution(
targetGenericDefinition,
pairs,
Concat(parent, containingType, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty))
End Function
Public Overrides Function ToString() As String
Dim builder As New StringBuilder()
builder.AppendFormat("{0} : ", TargetGenericDefinition)
ToString(builder)
Return builder.ToString()
End Function
Private Overloads Sub ToString(builder As StringBuilder)
If _parent IsNot Nothing Then
_parent.ToString(builder)
builder.Append(", ")
End If
builder.Append("{"c)
For i = 0 To _pairs.Length - 1
If i <> 0 Then
builder.Append(", ")
End If
builder.AppendFormat("{0}->{1}", _pairs(i).Key.ToString(), _pairs(i).Value.Type.ToString())
Next
builder.Append("}"c)
End Sub
Private Sub New(targetGenericDefinition As Symbol, pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)), parent As TypeSubstitution)
Debug.Assert(Not pairs.IsDefault)
Debug.Assert(pairs.All(Function(p) p.Key IsNot Nothing))
Debug.Assert(pairs.All(Function(p) p.Value.Type IsNot Nothing))
Debug.Assert(pairs.All(Function(p) Not p.Value.CustomModifiers.IsDefault))
Debug.Assert(targetGenericDefinition IsNot Nothing AndAlso
(targetGenericDefinition.IsDefinition OrElse
(targetGenericDefinition.Kind = SymbolKind.Method AndAlso
DirectCast(targetGenericDefinition, MethodSymbol).ConstructedFrom Is targetGenericDefinition AndAlso
parent Is Nothing)))
Debug.Assert((targetGenericDefinition.Kind = SymbolKind.Method AndAlso
(DirectCast(targetGenericDefinition, MethodSymbol).IsGenericMethod OrElse
(targetGenericDefinition.ContainingType.IsOrInGenericType() AndAlso parent IsNot Nothing))) OrElse
((targetGenericDefinition.Kind = SymbolKind.NamedType OrElse targetGenericDefinition.Kind = SymbolKind.ErrorType) AndAlso
DirectCast(targetGenericDefinition, NamedTypeSymbol).IsOrInGenericType()))
Debug.Assert(parent Is Nothing OrElse targetGenericDefinition.ContainingSymbol Is parent.TargetGenericDefinition)
_pairs = pairs
_parent = parent
_targetGenericDefinition = targetGenericDefinition
End Sub
''' <summary>
''' Create substitution to handle alpha-renaming of type parameters.
''' It maps type parameter definition to corresponding alpha-renamed type parameter.
''' </summary>
''' <param name="alphaRenamedTypeParameters">Alpha-renamed type parameters.</param>
Public Shared Function CreateForAlphaRename(
parent As TypeSubstitution,
alphaRenamedTypeParameters As ImmutableArray(Of TypeParameterSymbol)
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(Not alphaRenamedTypeParameters.IsEmpty)
Dim memberDefinition As Symbol = alphaRenamedTypeParameters(0).OriginalDefinition.ContainingSymbol
Debug.Assert(parent.TargetGenericDefinition Is memberDefinition.ContainingSymbol)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If memberDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(memberDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(memberDefinition, NamedTypeSymbol).TypeParameters
End If
Debug.Assert(Not typeParametersDefinitions.IsEmpty AndAlso
alphaRenamedTypeParameters.Length = typeParametersDefinitions.Length)
' Build complete map for memberDefinition's type parameters
Dim pairs(typeParametersDefinitions.Length - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To typeParametersDefinitions.Length - 1 Step 1
Debug.Assert(Not alphaRenamedTypeParameters(i).Equals(typeParametersDefinitions(i)))
Debug.Assert(alphaRenamedTypeParameters(i).OriginalDefinition Is typeParametersDefinitions(i))
pairs(i) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), New TypeWithModifiers(alphaRenamedTypeParameters(i)))
Next
Return Concat(parent, memberDefinition, pairs.AsImmutableOrNull())
End Function
''' <summary>
''' Create TypeSubstitution that can be used to substitute method's type parameters
''' in types involved in method's signature.
'''
''' Unlike for other construction methods in this class, targetMethod doesn't have to be
''' original definition, it is allowed to be specialized unconstructed generic method.
'''
''' An item in typeArguments can be an alpha-renamed type parameter, but it must belong
''' to the targetMethod and can only appear at its ordinal position to represent the lack
''' of substitution for it.
''' </summary>
Public Shared Function CreateAdditionalMethodTypeParameterSubstitution(
targetMethod As MethodSymbol,
typeArguments As ImmutableArray(Of TypeWithModifiers)
) As TypeSubstitution
Debug.Assert(targetMethod.Arity > 0 AndAlso typeArguments.Length = targetMethod.Arity AndAlso
targetMethod.ConstructedFrom Is targetMethod)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol) = targetMethod.TypeParameters
Dim argument As TypeWithModifiers
Dim countOfMeaningfulPairs As Integer = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod Then
Debug.Assert(typeParameter Is typeParametersDefinitions(i))
If argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
Debug.Assert(typeParameter.IsDefinition) ' Can't be an alpha renamed type parameter.
End If
countOfMeaningfulPairs += 1
Next
If countOfMeaningfulPairs = 0 Then
'Identity substitution
Return Nothing
End If
' Build the map
Dim pairs(countOfMeaningfulPairs - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
countOfMeaningfulPairs = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod AndAlso argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
pairs(countOfMeaningfulPairs) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), argument)
countOfMeaningfulPairs += 1
Next
Debug.Assert(countOfMeaningfulPairs = pairs.Length)
Return New TypeSubstitution(targetMethod, pairs.AsImmutableOrNull(), Nothing)
End Function
''' <summary>
''' Adjust substitution for construction.
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
''' 3) Parent substitution in oldConstructSubstitution is replaced with adjustedParent.
'''
''' oldConstructSubstitution can be cancelled out by additionalSubstitution. In this case,
''' if the adjustedParent is Nothing, Nothing is returned.
''' </summary>
Public Shared Function AdjustForConstruct(
adjustedParent As TypeSubstitution,
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As TypeSubstitution
Debug.Assert(oldConstructSubstitution IsNot Nothing AndAlso oldConstructSubstitution.TargetGenericDefinition.IsDefinition)
Debug.Assert(additionalSubstitution IsNot Nothing)
Debug.Assert(adjustedParent Is Nothing OrElse
(adjustedParent.TargetGenericDefinition.IsDefinition AndAlso
(oldConstructSubstitution.Parent Is Nothing OrElse
adjustedParent.TargetGenericDefinition Is oldConstructSubstitution.Parent.TargetGenericDefinition)))
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Dim pairsHaveChanged As Boolean = PrivateAdjustForConstruct(pairs, oldConstructSubstitution, additionalSubstitution)
Dim result As TypeSubstitution
' glue new parts together
If pairsHaveChanged OrElse oldConstructSubstitution.Parent IsNot adjustedParent Then
If pairs.Count = 0 AndAlso adjustedParent Is Nothing Then
result = Nothing
Else
result = Concat(adjustedParent,
oldConstructSubstitution.TargetGenericDefinition,
If(pairsHaveChanged, pairs.ToImmutable(), oldConstructSubstitution.Pairs))
End If
Else
result = oldConstructSubstitution
End If
pairs.Free()
Return result
End Function
''' <summary>
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
'''
''' Result is placed into pairs. Identity substitutions are omitted.
'''
''' Returns True if the set of pairs have changed, False otherwise.
''' </summary>
Private Shared Function PrivateAdjustForConstruct(
pairs As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)),
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As Boolean
' Substitute into target of each existing substitution.
Dim pairsHaveChanged As Boolean = False
Dim oldPairs = oldConstructSubstitution.Pairs
Dim haveSubstitutionForOrdinal As BitVector = Nothing
Dim targetGenericDefinition As Symbol = oldConstructSubstitution.TargetGenericDefinition
If oldPairs.Length > 0 Then
Dim arity As Integer
If targetGenericDefinition.Kind = SymbolKind.Method Then
arity = DirectCast(targetGenericDefinition, MethodSymbol).Arity
Else
arity = DirectCast(targetGenericDefinition, NamedTypeSymbol).Arity
End If
haveSubstitutionForOrdinal = BitVector.Create(arity)
End If
For i = 0 To oldPairs.Length - 1 Step 1
Dim newValue As TypeWithModifiers = oldPairs(i).Value.InternalSubstituteTypeParameters(additionalSubstitution)
' Mark that we had this substitution even if it is going to disappear.
' We still don't want to append substitution for this guy from additionalSubstitution.
haveSubstitutionForOrdinal(oldPairs(i).Key.Ordinal) = True
If Not newValue.Equals(oldPairs(i).Value) Then
pairsHaveChanged = True
End If
' Do not add identity mapping.
If Not newValue.Is(oldPairs(i).Key) Then
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(oldPairs(i).Key, newValue))
End If
Next
Dim append As TypeSubstitution = additionalSubstitution.GetSubstitutionForGenericDefinition(targetGenericDefinition)
' append new pairs
If append IsNot Nothing Then
For Each additionalPair In append.Pairs
If haveSubstitutionForOrdinal.IsNull OrElse Not haveSubstitutionForOrdinal(additionalPair.Key.Ordinal) Then
pairsHaveChanged = True
pairs.Add(additionalPair)
End If
Next
End If
Return pairsHaveChanged
End Function
''' <summary>
''' Create substitution for targetGenericDefinition based on its type
''' arguments (matched to type parameters by position) and TypeSubstitution
''' for direct or indirect container.
''' </summary>
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(targetGenericDefinition.IsDefinition)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If targetGenericDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(targetGenericDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(targetGenericDefinition, NamedTypeSymbol).TypeParameters
End If
Dim n = typeParametersDefinitions.Length
Debug.Assert(n > 0)
If args.Length <> n Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim significantMaps As Integer = 0
For i As Integer = 0 To n - 1 Step 1
Dim arg = args(i)
If Not arg.Is(typeParametersDefinitions(i)) Then
significantMaps += 1
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
Next
If significantMaps = 0 Then
Return Concat(targetGenericDefinition, parent, Nothing)
End If
Dim pairIndex = 0
Dim pairs(significantMaps - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To n - 1 Step 1
If Not args(i).Is(typeParametersDefinitions(i)) Then
pairs(pairIndex) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), args(i))
pairIndex += 1
End If
Next
Debug.Assert(pairIndex = significantMaps)
Return Concat(parent, targetGenericDefinition, pairs.AsImmutableOrNull())
End Function
Function SubstituteCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If type.IsTypeParameter() Then
Return New TypeWithModifiers(type, customModifiers).InternalSubstituteTypeParameters(Me).CustomModifiers
End If
Return customModifiers
End Function
End Class
End Namespace
| {'content_hash': 'ec320a63b853ec48f337393f864b0835', 'timestamp': '', 'source': 'github', 'line_count': 873, 'max_line_length': 171, 'avg_line_length': 45.10423825887744, 'alnum_prop': 0.6308665176757415, 'repo_name': 'zmaruo/roslyn', 'id': '7d1272888a2dedfb2fd01fa8c4d7de425087a349', 'size': '39378', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'src/Compilers/VisualBasic/Portable/Symbols/TypeSubstitution.vb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '9445'}, {'name': 'C#', 'bytes': '72050475'}, {'name': 'C++', 'bytes': '3744'}, {'name': 'F#', 'bytes': '421'}, {'name': 'PowerShell', 'bytes': '7578'}, {'name': 'Shell', 'bytes': '9655'}, {'name': 'Visual Basic', 'bytes': '58801946'}]} |
package net.morimekta.util;
import net.morimekta.util.io.BigEndianBinaryReader;
import net.morimekta.util.io.BigEndianBinaryWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
* Utility class for Binary conversion from and to binary array from Collections.
*/
public class BinaryUtil {
/**
* Method to convert a Collection of Binary to a byte array.
*
* @param binaryList Collection containing Binary elements.
* @throws IOException If unable to write binary to bytes, e.g. on buffer overflow.
* @return Array of bytes.
*/
public static byte[] fromBinaryCollection(Collection<Binary> binaryList) throws IOException {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
BigEndianBinaryWriter writer = new BigEndianBinaryWriter(baos)) {
writer.writeInt(binaryList.size());
for (Binary binary : binaryList) {
writer.writeInt(binary.length());
writer.writeBinary(binary);
}
return baos.toByteArray();
}
}
/**
* Method to convert a byte array to a Collection of Binary.
*
* @param bytes Array of bytes.
* @throws IOException If unable to read the binary collection.
* @return Collection of Binary.
*/
public static Collection<Binary> toBinaryCollection(byte[] bytes) throws IOException {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BigEndianBinaryReader reader = new BigEndianBinaryReader(bais) ) {
final int size = reader.expectInt();
Collection<Binary> result = new ArrayList<>();
for( int i = 0; i < size; i++ ) {
int length = reader.expectInt();
result.add(reader.expectBinary(length));
}
return result;
}
}
}
| {'content_hash': 'aaf24912fdfb685e8eedb5dc62027119', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 97, 'avg_line_length': 36.054545454545455, 'alnum_prop': 0.6495209278870399, 'repo_name': 'morimekta/android-util', 'id': '56855d928ff63d557a8924865b58c0389a734ec5', 'size': '1983', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'io-util/src/main/java/net/morimekta/util/BinaryUtil.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '433706'}]} |
/**
* @ngdoc directive
* @name mdMenuBar
* @module material.components.menu-bar
* @restrict E
* @description
*
* Menu bars are containers that hold multiple menus. They change the behavior and appearence
* of the `md-menu` directive to behave similar to an operating system provided menu.
*
* @usage
* <hljs lang="html">
* <md-menu-bar>
* <md-menu>
* <button ng-click="$mdOpenMenu()">
* File
* </button>
* <md-menu-content>
* <md-menu-item>
* <md-button ng-click="ctrl.sampleAction('share', $event)">
* Share...
* </md-button>
* </md-menu-item>
* <md-menu-divider></md-menu-divider>
* <md-menu-item>
* <md-menu-item>
* <md-menu>
* <md-button ng-click="$mdOpenMenu()">New</md-button>
* <md-menu-content>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-bar>
* </hljs>
*
* ## Menu Bar Controls
*
* You may place `md-menu-items` that function as controls within menu bars.
* There are two modes that are exposed via the `type` attribute of the `md-menu-item`.
* `type="checkbox"` will function as a boolean control for the `ng-model` attribute of the
* `md-menu-item`. `type="radio"` will function like a radio button, setting the `ngModel`
* to the `string` value of the `value` attribute. If you need non-string values, you can use
* `ng-value` to provide an expression (this is similar to how angular's native `input[type=radio]` works.
*
* <hljs lang="html">
* <md-menu-bar>
* <md-menu>
* <button ng-click="$mdOpenMenu()">
* Sample Menu
* </button>
* <md-menu-content>
* <md-menu-item type="checkbox" ng-model="settings.allowChanges">Allow changes</md-menu-item>
* <md-menu-divider></md-menu-divider>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 1</md-menu-item>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 2</md-menu-item>
* <md-menu-item type="radio" ng-model="settings.mode" ng-value="1">Mode 3</md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-bar>
* </hljs>
*
*
* ### Nesting Menus
*
* Menus may be nested within menu bars. This is commonly called cascading menus.
* To nest a menu place the nested menu inside the content of the `md-menu-item`.
* <hljs lang="html">
* <md-menu-item>
* <md-menu>
* <button ng-click="$mdOpenMenu()">New</md-button>
* <md-menu-content>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Document', $event)">Document</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Spreadsheet', $event)">Spreadsheet</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Presentation', $event)">Presentation</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Form', $event)">Form</md-button></md-menu-item>
* <md-menu-item><md-button ng-click="ctrl.sampleAction('New Drawing', $event)">Drawing</md-button></md-menu-item>
* </md-menu-content>
* </md-menu>
* </md-menu-item>
* </hljs>
*
*/
angular
.module('material.components.menuBar')
.directive('mdMenuBar', MenuBarDirective);
/* @ngInject */
function MenuBarDirective($mdUtil, $mdTheming) {
return {
restrict: 'E',
require: 'mdMenuBar',
controller: 'MenuBarController',
compile: function compile(templateEl, templateAttrs) {
if (!templateAttrs.ariaRole) {
templateEl[0].setAttribute('role', 'menubar');
}
angular.forEach(templateEl[0].children, function(menuEl) {
if (menuEl.nodeName == 'MD-MENU') {
if (!menuEl.hasAttribute('md-position-mode')) {
menuEl.setAttribute('md-position-mode', 'left bottom');
// Since we're in the compile function and actual `md-buttons` are not compiled yet,
// we need to query for possible `md-buttons` as well.
menuEl.querySelector('button, a, md-button').setAttribute('role', 'menuitem');
}
var contentEls = $mdUtil.nodesToArray(menuEl.querySelectorAll('md-menu-content'));
angular.forEach(contentEls, function(contentEl) {
contentEl.classList.add('_md-menu-bar-menu');
contentEl.classList.add('md-dense');
if (!contentEl.hasAttribute('width')) {
contentEl.setAttribute('width', 5);
}
});
}
});
return function postLink(scope, el, attr, ctrl) {
el.addClass('_md'); // private md component indicator for styling
$mdTheming(scope, el);
ctrl.init();
};
}
};
}
| {'content_hash': '85ca57f037090d6b098e494795d762df', 'timestamp': '', 'source': 'github', 'line_count': 134, 'max_line_length': 136, 'avg_line_length': 40.53731343283582, 'alnum_prop': 0.6152430044182622, 'repo_name': 'epelc/material', 'id': '93057ffea24df02e048698359a3f3f6daba8e370', 'size': '5432', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/components/menuBar/js/menuBarDirective.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '213172'}, {'name': 'HTML', 'bytes': '140586'}, {'name': 'JavaScript', 'bytes': '1451330'}, {'name': 'PHP', 'bytes': '7211'}, {'name': 'Shell', 'bytes': '8145'}]} |
from __future__ import print_function
import json
import xml.etree.ElementTree as xmlElementTree
import base64
import os
import sys
from os.path import isfile, join
import gzip
import datetime
import random
import traceback
import sys
import features_JSON
import features_XML
VERSION="2018-12-13-Stacktraces"
def extract(path, out_path):
try:
f = gzip.open (path)
fo = open(out_path , 'w')
stacktraces = []
userId = None
version = None
sessionStartMicroTime = 0
# Helper function to export data so far
# TODO: De-nest this function
def writeDataToFile():
print (json.dumps(
{
"StackTraces" : stacktraces,
"UserID": userId,
"WorkspaceVersion": version,
"Date": sessionDate,
}), file=fo)
# Process each line of the session file
for bytes_ln in f:
ln = bytes_ln.decode("utf-8")
# ln = str(ln)
# print (ln)
# print (type(ln))
if ln.startswith("Downloading phase"): # Marker from the download script, ignore
continue
data = json.loads(ln)
# Compute the first day
if sessionStartMicroTime == 0:
sessionStartMicroTime = int(data["MicroTime"])
sessionDate = data["DateTime"].split(" ")[0]
# Data is in base64 to protect against special characters, unpack it
b64decodedData = base64.b64decode(data["Data"]).decode("utf-8")
# Text entered into the search box
if data["Tag"] == "StackTrace":
stackTraces.append(b64decodedData)
# A workspace being reported
if data["Tag"] == "Workspace":
if b64decodedData == '': # An empty workspace, ignore
continue
# Select which feature extraction library to use depending on what version on the file format
feature_lib = None
if b64decodedData.startswith("<"):
feature_lib = features_XML
else:
isJSON = True
feature_lib = features_JSON
# Extract version number (first time only)
if (version == None):
version = feature_lib.getVersion(b64decodedData)
# Extract user ID (first time only)
if userId == None:
userId = data["UserID"]
except Exception as e:
# If there were a problem, get the stack trace for what happeend
exc_type, exc_value, exc_traceback = sys.exc_info()
# Log it
print (e)
print (path)
traceback.print_tb(exc_traceback, file=sys.stdout)
# Remove partial results
fo.flush()
os.remove(out_path)
# Flush any further data to the file
writeDataToFile()
| {'content_hash': '7136fc2948dcfef7b9fc128225e9169d', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 110, 'avg_line_length': 31.652631578947368, 'alnum_prop': 0.5447289657465912, 'repo_name': 'DynamoDS/Coulomb', 'id': '6d3abe562c6dc24a86b731d6071d18c6b8df3378', 'size': '3007', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Pipeline/stacktrace_extractor.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Dart', 'bytes': '2592'}, {'name': 'Python', 'bytes': '91637'}, {'name': 'Shell', 'bytes': '1284'}]} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '44498b2d74a3dbb9f199d04285c2db41', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': '8bacad4a189c01639e3b80cc78488e1156fd244d', 'size': '185', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Chaetanthera minuta/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using System;
using System.Collections.Generic;
namespace Mozu.Api.Contracts.ProductRuntime
{
///
/// The result of a product search.
///
public class ProductSearchResult
{
public List<Facet> Facets { get; set; }
public List<Product> Items { get; set; }
///
///This parameter is associated with deep paging. If you started a deep paged request by specifying , returns an encoded value for the . In your most immediate subsequent request, set to the same value you received for to continue paging. When is null, you've reached the end of paged results.
///
public string NextCursorMark { get; set; }
public int PageCount { get; set; }
public int PageSize { get; set; }
///
///Mozu.ProductRuntime.Contracts.ProductSearchResult solrDebugInfo ApiTypeMember DOCUMENT_HERE
///
public SolrDebugInfo SolrDebugInfo { get; set; }
public int StartIndex { get; set; }
public int TotalCount { get; set; }
}
} | {'content_hash': '4cd86d3f477cdb24b366c672746e90c4', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 300, 'avg_line_length': 26.805555555555557, 'alnum_prop': 0.6963730569948187, 'repo_name': 'rocky0904/mozu-dotnet', 'id': 'ae50cdeace951473f94ab419659ff38f7507524f', 'size': '1329', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Mozu.Api/Contracts/ProductRuntime/ProductSearchResult.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '279'}, {'name': 'C#', 'bytes': '7078214'}, {'name': 'F#', 'bytes': '1750'}, {'name': 'PowerShell', 'bytes': '3311'}]} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text;
using System;
namespace Microsoft.CodeAnalysis.Editor.Undo
{
[ExportWorkspaceService(typeof(ISourceTextUndoService), ServiceLayer.Editor), Shared]
internal sealed class EditorSourceTextUndoService : ISourceTextUndoService
{
private readonly Dictionary<SourceText, SourceTextUndoTransaction> _transactions = new Dictionary<SourceText, SourceTextUndoTransaction>();
private readonly ITextUndoHistoryRegistry _undoHistoryRegistry;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public EditorSourceTextUndoService(ITextUndoHistoryRegistry undoHistoryRegistry)
=> _undoHistoryRegistry = undoHistoryRegistry;
public ISourceTextUndoTransaction RegisterUndoTransaction(SourceText sourceText, string description)
{
if (sourceText != null && !string.IsNullOrWhiteSpace(description))
{
var transaction = new SourceTextUndoTransaction(this, sourceText, description);
_transactions.Add(sourceText, transaction);
return transaction;
}
return null;
}
public bool BeginUndoTransaction(ITextSnapshot snapshot)
{
var sourceText = snapshot?.AsText();
if (sourceText != null)
{
_transactions.TryGetValue(sourceText, out var transaction);
if (transaction != null)
{
return transaction.Begin(_undoHistoryRegistry?.GetHistory(snapshot.TextBuffer));
}
}
return false;
}
public bool EndUndoTransaction(ISourceTextUndoTransaction transaction)
{
if (transaction != null && _transactions.ContainsKey(transaction.SourceText))
{
_transactions.Remove(transaction.SourceText);
return true;
}
return false;
}
private sealed class SourceTextUndoTransaction : ISourceTextUndoTransaction
{
private readonly ISourceTextUndoService _service;
public SourceText SourceText { get; }
public string Description { get; }
private ITextUndoTransaction _transaction;
public SourceTextUndoTransaction(ISourceTextUndoService service, SourceText sourceText, string description)
{
_service = service;
SourceText = sourceText;
Description = description;
}
internal bool Begin(ITextUndoHistory undoHistory)
{
if (undoHistory != null)
{
_transaction = new HACK_TextUndoTransactionThatRollsBackProperly(undoHistory.CreateTransaction(Description));
return true;
}
return false;
}
public void Dispose()
{
if (_transaction != null)
{
_transaction.Complete();
}
_service.EndUndoTransaction(this);
}
}
}
}
| {'content_hash': '16c903340b75f52b78bdc2e6112a25c8', 'timestamp': '', 'source': 'github', 'line_count': 103, 'max_line_length': 147, 'avg_line_length': 35.50485436893204, 'alnum_prop': 0.6210008203445447, 'repo_name': 'genlu/roslyn', 'id': '9bf6ece3ea85e1cf5ebdf6e760fda686e465aa7c', 'size': '3659', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'src/EditorFeatures/Core/Undo/EditorSourceTextUndoService.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': '1C Enterprise', 'bytes': '257760'}, {'name': 'Batchfile', 'bytes': '9059'}, {'name': 'C#', 'bytes': '139228314'}, {'name': 'C++', 'bytes': '5602'}, {'name': 'CMake', 'bytes': '9153'}, {'name': 'Dockerfile', 'bytes': '2450'}, {'name': 'F#', 'bytes': '549'}, {'name': 'PowerShell', 'bytes': '242675'}, {'name': 'Shell', 'bytes': '92965'}, {'name': 'Visual Basic .NET', 'bytes': '71735255'}]} |
package com.intellij.openapi.ui;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.GuiUtils;
import com.intellij.ui.UIBundle;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.accessibility.ScreenReader;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ComponentWithBrowseButton<Comp extends JComponent> extends JPanel implements Disposable {
private static final Logger LOG = Logger.getInstance(ComponentWithBrowseButton.class);
private final Comp myComponent;
private final FixedSizeButton myBrowseButton;
private boolean myButtonEnabled = true;
public ComponentWithBrowseButton(Comp component, @Nullable ActionListener browseActionListener) {
super(new BorderLayout(SystemInfo.isMac ? 0 : 2, 0));
myComponent = component;
// required! otherwise JPanel will occasionally gain focus instead of the component
setFocusable(false);
add(myComponent, BorderLayout.CENTER);
myBrowseButton = new FixedSizeButton(myComponent);
if (browseActionListener != null) {
myBrowseButton.addActionListener(browseActionListener);
}
add(centerComponentVertically(myBrowseButton), BorderLayout.EAST);
myBrowseButton.setToolTipText(UIBundle.message("component.with.browse.button.browse.button.tooltip.text"));
// FixedSizeButton isn't focusable but it should be selectable via keyboard.
if (ApplicationManager.getApplication() != null) { // avoid crash at design time
new MyDoClickAction(myBrowseButton).registerShortcut(myComponent);
}
if (ScreenReader.isActive()) {
myBrowseButton.setFocusable(true);
myBrowseButton.getAccessibleContext().setAccessibleName("Browse");
}
}
@NotNull
private static JPanel centerComponentVertically(@NotNull Component component) {
JPanel panel = new JPanel(new GridBagLayout());
panel.add(component, new GridBagConstraints());
return panel;
}
public final Comp getChildComponent() {
return myComponent;
}
public void setTextFieldPreferredWidth(final int charCount) {
final Comp comp = getChildComponent();
Dimension size = GuiUtils.getSizeByChars(charCount, comp);
comp.setPreferredSize(size);
final Dimension preferredSize = myBrowseButton.getPreferredSize();
setPreferredSize(new Dimension(size.width + preferredSize.width + 2, UIUtil.isUnderAquaLookAndFeel() ? preferredSize.height : preferredSize.height + 2));
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
myBrowseButton.setEnabled(enabled && myButtonEnabled);
myComponent.setEnabled(enabled);
}
public void setButtonEnabled(boolean buttonEnabled) {
myButtonEnabled = buttonEnabled;
setEnabled(isEnabled());
}
public void setButtonIcon(Icon icon) {
myBrowseButton.setIcon(icon);
}
/**
* Adds specified <code>listener</code> to the browse button.
*/
public void addActionListener(ActionListener listener){
myBrowseButton.addActionListener(listener);
}
public void removeActionListener(ActionListener listener) {
myBrowseButton.removeActionListener(listener);
}
public void addBrowseFolderListener(@Nullable @Nls(capitalization = Nls.Capitalization.Title) String title,
@Nullable @Nls(capitalization = Nls.Capitalization.Sentence) String description,
@Nullable Project project,
FileChooserDescriptor fileChooserDescriptor,
TextComponentAccessor<Comp> accessor) {
addActionListener(new BrowseFolderActionListener<>(title, description, this, project, fileChooserDescriptor, accessor));
}
/**
* @deprecated use {@link #addBrowseFolderListener(String, String, Project, FileChooserDescriptor, TextComponentAccessor)} instead
*/
public void addBrowseFolderListener(@Nullable @Nls(capitalization = Nls.Capitalization.Title) String title,
@Nullable @Nls(capitalization = Nls.Capitalization.Sentence) String description,
@Nullable Project project,
FileChooserDescriptor fileChooserDescriptor,
TextComponentAccessor<Comp> accessor, boolean autoRemoveOnHide) {
addBrowseFolderListener(title, description, project, fileChooserDescriptor, accessor);
}
/**
* @deprecated use {@link #addActionListener(ActionListener)} instead
*/
@SuppressWarnings("UnusedParameters")
public void addBrowseFolderListener(@Nullable Project project, final BrowseFolderActionListener<Comp> actionListener) {
addActionListener(actionListener);
}
/**
* @deprecated use {@link #addActionListener(ActionListener)} instead
*/
@SuppressWarnings("UnusedParameters")
public void addBrowseFolderListener(@Nullable Project project, final BrowseFolderActionListener<Comp> actionListener, boolean autoRemoveOnHide) {
addActionListener(actionListener);
}
@Override
public void dispose() {
ActionListener[] listeners = myBrowseButton.getActionListeners();
for (ActionListener listener : listeners) {
myBrowseButton.removeActionListener(listener);
}
}
public FixedSizeButton getButton() {
return myBrowseButton;
}
/**
* Do not use this class directly it is public just to hack other implementation of controls similar to TextFieldWithBrowseButton.
*/
public static final class MyDoClickAction extends DumbAwareAction {
private final FixedSizeButton myBrowseButton;
public MyDoClickAction(FixedSizeButton browseButton) {
myBrowseButton = browseButton;
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(myBrowseButton.isVisible() && myBrowseButton.isEnabled());
}
@Override
public void actionPerformed(AnActionEvent e){
myBrowseButton.doClick();
}
public void registerShortcut(JComponent textField) {
ShortcutSet shiftEnter = new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK));
registerCustomShortcutSet(shiftEnter, textField);
myBrowseButton.setToolTipText(KeymapUtil.getShortcutsText(shiftEnter.getShortcuts()));
}
public static void addTo(FixedSizeButton browseButton, JComponent aComponent) {
new MyDoClickAction(browseButton).registerShortcut(aComponent);
}
}
public static class BrowseFolderActionListener<T extends JComponent> implements ActionListener {
private final String myTitle;
private final String myDescription;
protected ComponentWithBrowseButton<T> myTextComponent;
private final TextComponentAccessor<T> myAccessor;
private Project myProject;
protected final FileChooserDescriptor myFileChooserDescriptor;
public BrowseFolderActionListener(@Nullable @Nls(capitalization = Nls.Capitalization.Title) String title,
@Nullable @Nls(capitalization = Nls.Capitalization.Sentence) String description,
ComponentWithBrowseButton<T> textField,
@Nullable Project project,
FileChooserDescriptor fileChooserDescriptor,
TextComponentAccessor<T> accessor) {
if (fileChooserDescriptor != null && fileChooserDescriptor.isChooseMultiple()) {
LOG.error("multiple selection not supported");
fileChooserDescriptor = new FileChooserDescriptor(fileChooserDescriptor) {
@Override
public boolean isChooseMultiple() {
return false;
}
};
}
myTitle = title;
myDescription = description;
myTextComponent = textField;
myProject = project;
myFileChooserDescriptor = fileChooserDescriptor;
myAccessor = accessor;
}
@Nullable
protected Project getProject() {
return myProject;
}
protected void setProject(@Nullable Project project) {
myProject = project;
}
@Override
public void actionPerformed(ActionEvent e) {
FileChooserDescriptor fileChooserDescriptor = myFileChooserDescriptor;
if (myTitle != null || myDescription != null) {
fileChooserDescriptor = (FileChooserDescriptor)myFileChooserDescriptor.clone();
if (myTitle != null) {
fileChooserDescriptor.setTitle(myTitle);
}
if (myDescription != null) {
fileChooserDescriptor.setDescription(myDescription);
}
}
FileChooser.chooseFile(fileChooserDescriptor, getProject(), myTextComponent, getInitialFile(), this::onFileChosen);
}
@Nullable
protected VirtualFile getInitialFile() {
String directoryName = getComponentText();
if (StringUtil.isEmptyOrSpaces(directoryName)) {
return null;
}
directoryName = FileUtil.toSystemIndependentName(directoryName);
VirtualFile path = LocalFileSystem.getInstance().findFileByPath(expandPath(directoryName));
while (path == null && directoryName.length() > 0) {
int pos = directoryName.lastIndexOf('/');
if (pos <= 0) break;
directoryName = directoryName.substring(0, pos);
path = LocalFileSystem.getInstance().findFileByPath(directoryName);
}
return path;
}
@NotNull
protected String expandPath(@NotNull String path) {
return path;
}
protected String getComponentText() {
return myAccessor.getText(myTextComponent.getChildComponent()).trim();
}
@NotNull
protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) {
return chosenFile.getPresentableUrl();
}
protected void onFileChosen(@NotNull VirtualFile chosenFile) {
myAccessor.setText(myTextComponent.getChildComponent(), chosenFileToResultingText(chosenFile));
}
}
@Override
public final void requestFocus() {
myComponent.requestFocus();
}
@SuppressWarnings("deprecation")
@Override
public final void setNextFocusableComponent(Component aComponent) {
super.setNextFocusableComponent(aComponent);
myComponent.setNextFocusableComponent(aComponent);
}
private KeyEvent myCurrentEvent = null;
@Override
protected final boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
if (condition == WHEN_FOCUSED && myCurrentEvent != e) {
try {
myCurrentEvent = e;
myComponent.dispatchEvent(e);
}
finally {
myCurrentEvent = null;
}
}
if (e.isConsumed()) return true;
return super.processKeyBinding(ks, e, condition, pressed);
}
}
| {'content_hash': '677f14d5b3e0ba8fc31a49e98ccaeb04', 'timestamp': '', 'source': 'github', 'line_count': 312, 'max_line_length': 157, 'avg_line_length': 37.708333333333336, 'alnum_prop': 0.7186570335741607, 'repo_name': 'idea4bsd/idea4bsd', 'id': 'a4a24208b4fc0262ba59c25dce9b87fe19c12898', 'size': '12365', 'binary': False, 'copies': '3', 'ref': 'refs/heads/idea4bsd-master', 'path': 'platform/platform-api/src/com/intellij/openapi/ui/ComponentWithBrowseButton.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '59458'}, {'name': 'C', 'bytes': '224097'}, {'name': 'C#', 'bytes': '1538'}, {'name': 'C++', 'bytes': '197012'}, {'name': 'CSS', 'bytes': '197224'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Cucumber', 'bytes': '14382'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'Groff', 'bytes': '35232'}, {'name': 'Groovy', 'bytes': '2971715'}, {'name': 'HLSL', 'bytes': '57'}, {'name': 'HTML', 'bytes': '1829102'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '158117117'}, {'name': 'JavaScript', 'bytes': '563135'}, {'name': 'Jupyter Notebook', 'bytes': '93222'}, {'name': 'Kotlin', 'bytes': '2208983'}, {'name': 'Lex', 'bytes': '179058'}, {'name': 'Makefile', 'bytes': '3018'}, {'name': 'NSIS', 'bytes': '49952'}, {'name': 'Objective-C', 'bytes': '28750'}, {'name': 'Perl', 'bytes': '903'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6607'}, {'name': 'Python', 'bytes': '23911290'}, {'name': 'Ruby', 'bytes': '1217'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '63460'}, {'name': 'Smalltalk', 'bytes': '64'}, {'name': 'TeX', 'bytes': '25473'}, {'name': 'Thrift', 'bytes': '1846'}, {'name': 'TypeScript', 'bytes': '9469'}, {'name': 'Visual Basic', 'bytes': '77'}, {'name': 'XSLT', 'bytes': '113040'}]} |
Copyright (c) 2015, Mirraz
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 socks-libevent 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| {'content_hash': '4b2e8f7965a2526e179fd8bb3d3c8f13', 'timestamp': '', 'source': 'github', 'line_count': 27, 'max_line_length': 78, 'avg_line_length': 54.74074074074074, 'alnum_prop': 0.8112313937753721, 'repo_name': 'Mirraz/socks-libevent', 'id': '397318652a5a666f8fae97628557574844805beb', 'size': '1478', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LICENSE.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '74387'}, {'name': 'Makefile', 'bytes': '1970'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AntConfiguration">
<buildFile url="file://$PROJECT_DIR$/src/ad-interactive-auth/build.xml" />
<buildFile url="file://$PROJECT_DIR$/build.xml" />
</component>
</project>
| {'content_hash': '6150eb4298aecba052d24fbd3d153949', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 78, 'avg_line_length': 32.5, 'alnum_prop': 0.6615384615384615, 'repo_name': 'akrakovsky/msopentech-tools-for-intellij', 'id': '20cee66e2ef2ebb38fa8c16469706cc8166d5286', 'size': '260', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': '.idea/ant.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '1308383'}, {'name': 'JavaScript', 'bytes': '254'}]} |
package org.apache.flink.api.java.typeutils.runtime;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.common.typeutils.TypeSerializerMatchers;
import org.apache.flink.api.common.typeutils.TypeSerializerSchemaCompatibility;
import org.apache.flink.api.common.typeutils.TypeSerializerUpgradeTestBase;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.DataOutputView;
import org.apache.flink.testutils.migration.MigrationVersion;
import org.apache.flink.types.Value;
import org.hamcrest.Matcher;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import static org.hamcrest.Matchers.is;
/** State migration test for {@link RowSerializer}. */
@RunWith(Parameterized.class)
public class ValueSerializerUpgradeTest
extends TypeSerializerUpgradeTestBase<
ValueSerializerUpgradeTest.NameValue, ValueSerializerUpgradeTest.NameValue> {
public ValueSerializerUpgradeTest(TestSpecification<NameValue, NameValue> testSpecification) {
super(testSpecification);
}
@Parameterized.Parameters(name = "Test Specification = {0}")
public static Collection<TestSpecification<?, ?>> testSpecifications() throws Exception {
ArrayList<TestSpecification<?, ?>> testSpecifications = new ArrayList<>();
for (MigrationVersion migrationVersion : MIGRATION_VERSIONS) {
testSpecifications.add(
new TestSpecification<>(
"value-serializer",
migrationVersion,
ValueSerializerSetup.class,
ValueSerializerVerifier.class));
}
return testSpecifications;
}
public static final class ValueSerializerSetup
implements TypeSerializerUpgradeTestBase.PreUpgradeSetup<NameValue> {
@Override
public TypeSerializer<NameValue> createPriorSerializer() {
return new ValueSerializer<>(NameValue.class);
}
@Override
public NameValue createTestData() {
NameValue value = new NameValue();
value.setName("klion26");
return value;
}
}
public static final class ValueSerializerVerifier
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<NameValue> {
@Override
public TypeSerializer<NameValue> createUpgradedSerializer() {
return new ValueSerializer<>(NameValue.class);
}
@Override
public Matcher<NameValue> testDataMatcher() {
NameValue value = new NameValue();
value.setName("klion26");
return is(value);
}
@Override
public Matcher<TypeSerializerSchemaCompatibility<NameValue>> schemaCompatibilityMatcher(
MigrationVersion version) {
return TypeSerializerMatchers.isCompatibleAsIs();
}
}
/** A dummy class used for this test. */
public static final class NameValue implements Value {
public static final long serialVersionUID = 2277251654485371327L;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void write(DataOutputView out) throws IOException {
out.writeUTF(name);
}
@Override
public void read(DataInputView in) throws IOException {
name = in.readUTF();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof NameValue)) {
return false;
}
NameValue other = (NameValue) obj;
return Objects.equals(this.name, other.name);
}
}
}
| {'content_hash': '891afcf0e8bed7ef9fae36c60acb3643', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 98, 'avg_line_length': 32.86178861788618, 'alnum_prop': 0.6494309747649678, 'repo_name': 'StephanEwen/incubator-flink', 'id': 'eeeeeb31f5cfa1b40e96f8aa99ef200ee794596c', 'size': '4847', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'flink-core/src/test/java/org/apache/flink/api/java/typeutils/runtime/ValueSerializerUpgradeTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4588'}, {'name': 'CSS', 'bytes': '57936'}, {'name': 'Clojure', 'bytes': '90539'}, {'name': 'Dockerfile', 'bytes': '10807'}, {'name': 'FreeMarker', 'bytes': '11924'}, {'name': 'HTML', 'bytes': '224454'}, {'name': 'Java', 'bytes': '48116532'}, {'name': 'JavaScript', 'bytes': '1829'}, {'name': 'Makefile', 'bytes': '5134'}, {'name': 'Python', 'bytes': '747014'}, {'name': 'Scala', 'bytes': '13208937'}, {'name': 'Shell', 'bytes': '461052'}, {'name': 'TypeScript', 'bytes': '243702'}]} |
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"
/** @addtogroup STM32L1xx_HAL_Driver
* @{
*/
/** @defgroup UART UART HAL module driver
* @brief HAL UART module driver
* @{
*/
#ifdef HAL_UART_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup UART_Private_Constants UART Private Constants
* @{
*/
#define UART_TIMEOUT_VALUE 22000
/**
* @}
*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup UART_Private_Functions UART Private Functions
* @{
*/
static void UART_SetConfig (UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart);
static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart);
static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma);
static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma);
static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma);
static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma);
static void UART_DMAError(DMA_HandleTypeDef *hdma);
static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout);
/**
* @}
*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup UART_Exported_Functions UART Exported Functions
* @{
*/
/** @defgroup UART_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and Configuration functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to initialize the USARTx or the UARTy
in asynchronous mode.
(+) For the asynchronous mode only these parameters can be configured:
(++) Baud Rate
(++) Word Length
(++) Stop Bit
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
Depending on the frame length defined by the M bit (8-bits or 9-bits),
the possible UART frame formats are as listed in the following table:
+-------------------------------------------------------------+
| M bit | PCE bit | UART frame |
|---------------------|---------------------------------------|
| 0 | 0 | | SB | 8 bit data | STB | |
|---------|-----------|---------------------------------------|
| 0 | 1 | | SB | 7 bit data | PB | STB | |
|---------|-----------|---------------------------------------|
| 1 | 0 | | SB | 9 bit data | STB | |
|---------|-----------|---------------------------------------|
| 1 | 1 | | SB | 8 bit data | PB | STB | |
+-------------------------------------------------------------+
(++) Hardware flow control
(++) Receiver/transmitter modes
(++) Over Sampling Methode
[..]
The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init() and HAL_MultiProcessor_Init() APIs
follow respectively the UART asynchronous, UART Half duplex, LIN and Multi-Processor
configuration procedures (details for the procedures are available in reference manual (RM0038)).
@endverbatim
* @{
*/
/**
* @brief Initializes the UART mode according to the specified parameters in
* the UART_InitTypeDef and create the associated handle.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if(huart == HAL_NULL)
{
return HAL_ERROR;
}
if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE)
{
/* Check the parameters */
assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
}
else
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
}
if(huart->State == HAL_UART_STATE_RESET)
{
/* Init the low level hardware */
HAL_UART_MspInit(huart);
}
huart->State = HAL_UART_STATE_BUSY;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In asynchronous mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL and IREN bits in the USART_CR3 register.*/
huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state */
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->State= HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the half-duplex mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if(huart == HAL_NULL)
{
return HAL_ERROR;
}
/* Check UART instance */
assert_param(IS_UART_HALFDUPLEX_INSTANCE(huart->Instance));
if(huart->State == HAL_UART_STATE_RESET)
{
/* Init the low level hardware */
HAL_UART_MspInit(huart);
}
huart->State = HAL_UART_STATE_BUSY;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In half-duplex mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN and IREN bits in the USART_CR3 register.*/
huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
huart->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_SCEN);
/* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */
huart->Instance->CR3 |= USART_CR3_HDSEL;
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state*/
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->State= HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the LIN mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param BreakDetectLength: Specifies the LIN break detection length.
* This parameter can be one of the following values:
* @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection
* @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength)
{
/* Check the UART handle allocation */
if(huart == HAL_NULL)
{
return HAL_ERROR;
}
/* Check the LIN UART instance */
assert_param(IS_UART_LIN_INSTANCE(huart->Instance));
/* Check the Break detection length parameter */
assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength));
/* LIN mode limited to 16-bit oversampling only */
if(huart->Init.OverSampling == UART_OVERSAMPLING_8)
{
return HAL_ERROR;
}
if(huart->State == HAL_UART_STATE_RESET)
{
/* Init the low level hardware */
HAL_UART_MspInit(huart);
}
huart->State = HAL_UART_STATE_BUSY;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In LIN mode, the following bits must be kept cleared:
- CLKEN bits in the USART_CR2 register,
- SCEN and IREN bits in the USART_CR3 register.*/
huart->Instance->CR2 &= ~(USART_CR2_CLKEN);
huart->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN | USART_CR3_SCEN);
/* Enable the LIN mode by setting the LINEN bit in the CR2 register */
huart->Instance->CR2 |= USART_CR2_LINEN;
/* Set the USART LIN Break detection length. */
MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state*/
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->State= HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief Initializes the Multi-Processor mode according to the specified
* parameters in the UART_InitTypeDef and create the associated handle.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param Address: UART node address
* @param WakeUpMethod: specifies the UART wakeup method.
* This parameter can be one of the following values:
* @arg UART_WAKEUPMETHOD_IDLELINE: Wakeup by an idle line detection
* @arg UART_WAKEUPMETHOD_ADDRESSMARK: Wakeup by an address mark
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod)
{
/* Check the UART handle allocation */
if(huart == HAL_NULL)
{
return HAL_ERROR;
}
/* Check UART instance capabilities */
assert_param(IS_UART_MULTIPROCESSOR_INSTANCE(huart->Instance));
/* Check the Address & wake up method parameters */
assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod));
assert_param(IS_UART_ADDRESS(Address));
if(huart->State == HAL_UART_STATE_RESET)
{
/* Init the low level hardware */
HAL_UART_MspInit(huart);
}
huart->State = HAL_UART_STATE_BUSY;
/* Disable the peripheral */
__HAL_UART_DISABLE(huart);
/* Set the UART Communication parameters */
UART_SetConfig(huart);
/* In Multi-Processor mode, the following bits must be kept cleared:
- LINEN and CLKEN bits in the USART_CR2 register,
- SCEN, HDSEL and IREN bits in the USART_CR3 register */
huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN);
huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN);
/* Set the USART address node */
MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, Address);
/* Set the wake up method by setting the WAKE bit in the CR1 register */
MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod);
/* Enable the peripheral */
__HAL_UART_ENABLE(huart);
/* Initialize the UART state */
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->State= HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief DeInitializes the UART peripheral.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart)
{
/* Check the UART handle allocation */
if(huart == HAL_NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
huart->State = HAL_UART_STATE_BUSY;
/* Disable the Peripheral */
__HAL_UART_DISABLE(huart);
/* DeInit the low level hardware */
HAL_UART_MspDeInit(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
huart->State = HAL_UART_STATE_RESET;
/* Process Unlock */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief UART MSP Init.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_MspInit(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_MspInit could be implemented in the user file
*/
}
/**
* @brief UART MSP DeInit.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup UART_Exported_Functions_Group2 IO operation functions
* @brief UART Transmit and Receive functions
*
@verbatim
==============================================================================
##### IO operation functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to manage the UART asynchronous
and Half duplex data transfers.
(#) There are two modes of transfer:
(++) Blocking mode: The communication is performed in polling mode.
The HAL status of all data processing is returned by the same function
after finishing transfer.
(++) Non blocking mode: The communication is performed using Interrupts
or DMA, these APIs return the HAL status.
The end of the data processing will be indicated through the
dedicated UART IRQ when using Interrupt mode or the DMA IRQ when
using DMA mode.
The HAL_UART_TxCpltCallback(), HAL_UART_RxCpltCallback() user callbacks
will be executed respectivelly at the end of the transmit or receive process.
The HAL_UART_ErrorCallback() user callback will be executed when
a communication error is detected.
(#) Blocking mode APIs are:
(++) HAL_UART_Transmit()
(++) HAL_UART_Receive()
(#) Non Blocking mode APIs with Interrupt are:
(++) HAL_UART_Transmit_IT()
(++) HAL_UART_Receive_IT()
(++) HAL_UART_IRQHandler()
(#) Non Blocking mode functions with DMA are:
(++) HAL_UART_Transmit_DMA()
(++) HAL_UART_Receive_DMA()
(++) HAL_UART_DMAPause()
(++) HAL_UART_DMAResume()
(++) HAL_UART_DMAStop()
(#) A set of Transfer Complete Callbacks are provided in non blocking mode:
(++) HAL_UART_TxHalfCpltCallback()
(++) HAL_UART_TxCpltCallback()
(++) HAL_UART_RxHalfCpltCallback()
(++) HAL_UART_RxCpltCallback()
(++) HAL_UART_ErrorCallback()
[..]
(@) In the Half duplex communication, it is forbidden to run the transmit
and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX
can't be useful.
@endverbatim
* @{
*/
/**
* @brief Sends an amount of data in blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_RX))
{
if((pData == HAL_NULL) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a non-blocking receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
huart->TxXferSize = Size;
huart->TxXferCount = Size;
while(huart->TxXferCount > 0)
{
huart->TxXferCount--;
if(huart->Init.WordLength == UART_WORDLENGTH_9B)
{
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t*) pData;
huart->Instance->DR = (*tmp & (uint16_t)0x01FF);
if(huart->Init.Parity == UART_PARITY_NONE)
{
pData +=2;
}
else
{
pData +=1;
}
}
else
{
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
huart->Instance->DR = (*pData++ & (uint8_t)0xFF);
}
}
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
/* Check if a non-blocking receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
else
{
huart->State = HAL_UART_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data in blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout)
{
uint16_t* tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_TX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a non-blocking transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
huart->RxXferSize = Size;
huart->RxXferCount = Size;
/* Check the remain data to be received */
while(huart->RxXferCount > 0)
{
huart->RxXferCount--;
if(huart->Init.WordLength == UART_WORDLENGTH_9B)
{
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
tmp = (uint16_t*) pData ;
if(huart->Init.Parity == UART_PARITY_NONE)
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
pData +=2;
}
else
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
pData +=1;
}
}
else
{
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK)
{
return HAL_TIMEOUT;
}
if(huart->Init.Parity == UART_PARITY_NONE)
{
*pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
}
else
{
*pData++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
}
}
}
/* Check if a non-blocking transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
else
{
huart->State = HAL_UART_STATE_READY;
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in non blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t tmp = 0;
tmp = huart->State;
if((tmp == HAL_UART_STATE_READY) || (tmp == HAL_UART_STATE_BUSY_RX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pTxBuffPtr = pData;
huart->TxXferSize = Size;
huart->TxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
/* Enable the UART Parity Error Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_PE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Transmit data register empty Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_TXE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data in non blocking mode
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t tmp = 0;
tmp = huart->State;
if((tmp == HAL_UART_STATE_READY) || (tmp == HAL_UART_STATE_BUSY_TX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->RxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
/* Enable the UART Parity Error Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_PE);
/* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_ENABLE_IT(huart, UART_IT_ERR);
/* Process Unlocked */
__HAL_UNLOCK(huart);
/* Enable the UART Data Register not empty Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_RXNE);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Sends an amount of data in non blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be sent
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_RX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pTxBuffPtr = pData;
huart->TxXferSize = Size;
huart->TxXferCount = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
/* Set the UART DMA transfer complete callback */
huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt;
/* Set the UART DMA Half transfer complete callback */
huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt;
/* Set the DMA error callback */
huart->hdmatx->XferErrorCallback = UART_DMAError;
/* Enable the UART transmit DMA channel */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->DR, Size);
/* Enable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
huart->Instance->CR3 |= USART_CR3_DMAT;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Receives an amount of data in non blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param pData: Pointer to data buffer
* @param Size: Amount of data to be received
* @note When the UART parity is enabled (PCE = 1), the received data contain
* the parity bit (MSB position)
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size)
{
uint32_t *tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_READY) || (tmp1 == HAL_UART_STATE_BUSY_TX))
{
if((pData == HAL_NULL ) || (Size == 0))
{
return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(huart);
huart->pRxBuffPtr = pData;
huart->RxXferSize = Size;
huart->ErrorCode = HAL_UART_ERROR_NONE;
/* Check if a transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
huart->State = HAL_UART_STATE_BUSY_TX_RX;
}
else
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
/* Set the UART DMA transfer complete callback */
huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt;
/* Set the UART DMA Half transfer complete callback */
huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt;
/* Set the DMA error callback */
huart->hdmarx->XferErrorCallback = UART_DMAError;
/* Enable the DMA channel */
tmp = (uint32_t*)&pData;
HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->DR, *(uint32_t*)tmp, Size);
/* Enable the DMA transfer for the receiver request by setting the DMAR bit
in the UART CR3 register */
huart->Instance->CR3 |= USART_CR3_DMAR;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Pauses the DMA Transfer.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart)
{
/* Process Locked */
__HAL_LOCK(huart);
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
/* Disable the UART DMA Tx request */
huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
}
else if(huart->State == HAL_UART_STATE_BUSY_RX)
{
/* Disable the UART DMA Rx request */
huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
}
else if (huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
/* Disable the UART DMA Tx & Rx requests */
huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT);
huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR);
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Resumes the DMA Transfer.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart)
{
/* Process Locked */
__HAL_LOCK(huart);
if(huart->State == HAL_UART_STATE_BUSY_TX)
{
/* Enable the UART DMA Tx request */
huart->Instance->CR3 |= USART_CR3_DMAT;
}
else if(huart->State == HAL_UART_STATE_BUSY_RX)
{
/* Clear the Overrun flag before resumming the Rx transfer*/
__HAL_UART_CLEAR_OREFLAG(huart);
/* Enable the UART DMA Rx request */
huart->Instance->CR3 |= USART_CR3_DMAR;
}
else if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
/* Clear the Overrun flag before resumming the Rx transfer*/
__HAL_UART_CLEAR_OREFLAG(huart);
/* Enable the UART DMA Tx & Rx request */
huart->Instance->CR3 |= USART_CR3_DMAT;
huart->Instance->CR3 |= USART_CR3_DMAR;
}
else
{
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_ERROR;
}
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Stops the DMA Transfer.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart)
{
/* The Lock is not implemented on this API to allow the user application
to call the HAL UART API under callbacks HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback():
when calling HAL_DMA_Abort() API the DMA TX/RX Transfer complete interrupt is generated
and the correspond call back is executed HAL_UART_TxCpltCallback() / HAL_UART_RxCpltCallback()
*/
/* Disable the UART Tx/Rx DMA requests */
huart->Instance->CR3 &= ~USART_CR3_DMAT;
huart->Instance->CR3 &= ~USART_CR3_DMAR;
/* Abort the UART DMA tx channel */
if(huart->hdmatx != HAL_NULL)
{
HAL_DMA_Abort(huart->hdmatx);
}
/* Abort the UART DMA rx channel */
if(huart->hdmarx != HAL_NULL)
{
HAL_DMA_Abort(huart->hdmarx);
}
huart->State = HAL_UART_STATE_READY;
return HAL_OK;
}
/**
* @brief This function handles UART interrupt request.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
void HAL_UART_IRQHandler(UART_HandleTypeDef *huart)
{
uint32_t tmp1 = 0, tmp2 = 0;
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_PE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_PE);
/* UART parity error interrupt occurred ------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
__HAL_UART_CLEAR_PEFLAG(huart);
huart->ErrorCode |= HAL_UART_ERROR_PE;
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_FE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
/* UART frame error interrupt occurred -------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
__HAL_UART_CLEAR_FEFLAG(huart);
huart->ErrorCode |= HAL_UART_ERROR_FE;
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_NE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
/* UART noise error interrupt occurred -------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
__HAL_UART_CLEAR_NEFLAG(huart);
huart->ErrorCode |= HAL_UART_ERROR_NE;
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_ORE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR);
/* UART Over-Run interrupt occurred ----------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
__HAL_UART_CLEAR_OREFLAG(huart);
huart->ErrorCode |= HAL_UART_ERROR_ORE;
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_RXNE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE);
/* UART in mode Receiver ---------------------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
UART_Receive_IT(huart);
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_TXE);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_TXE);
/* UART in mode Transmitter ------------------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
UART_Transmit_IT(huart);
}
tmp1 = __HAL_UART_GET_FLAG(huart, UART_FLAG_TC);
tmp2 = __HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC);
/* UART in mode Transmitter end --------------------------------------------*/
if((tmp1 != RESET) && (tmp2 != RESET))
{
UART_EndTransmit_IT(huart);
}
if(huart->ErrorCode != HAL_UART_ERROR_NONE)
{
/* Set the UART state ready to be able to start again the process */
huart->State = HAL_UART_STATE_READY;
HAL_UART_ErrorCallback(huart);
}
}
/**
* @brief Tx Transfer completed callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_TxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Tx Half Transfer completed callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_TxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Transfer completed callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_RxCpltCallback could be implemented in the user file
*/
}
/**
* @brief Rx Half Transfer completed callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_RxHalfCpltCallback could be implemented in the user file
*/
}
/**
* @brief UART error callbacks.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
__weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
/* NOTE: This function Should not be modified, when the callback is needed,
the HAL_UART_ErrorCallback could be implemented in the user file
*/
}
/**
* @}
*/
/** @defgroup UART_Exported_Functions_Group3 Peripheral Control functions
* @brief UART control functions
*
@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control the UART:
(+) HAL_LIN_SendBreak() API can be helpful to transmit the break character.
(+) HAL_MultiProcessor_EnterMuteMode() API can be helpful to enter the UART in mute mode.
(+) HAL_MultiProcessor_ExitMuteMode() API can be helpful to exit the UART mute mode by software.
(+) HAL_HalfDuplex_EnableTransmitter() API to enable the UART transmitter and disables the UART receiver in Half Duplex mode
(+) HAL_HalfDuplex_EnableReceiver() API to enable the UART receiver and disables the UART transmitter in Half Duplex mode
@endverbatim
* @{
*/
/**
* @brief Transmits break characters.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->State = HAL_UART_STATE_BUSY;
/* Send break characters */
huart->Instance->CR1 |= USART_CR1_SBK;
huart->State = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enters the UART in mute mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->State = HAL_UART_STATE_BUSY;
/* Enable the USART mute mode by setting the RWU bit in the CR1 register */
huart->Instance->CR1 |= USART_CR1_RWU;
huart->State = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Exits the UART mute mode: wake up software.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_MultiProcessor_ExitMuteMode(UART_HandleTypeDef *huart)
{
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
/* Process Locked */
__HAL_LOCK(huart);
huart->State = HAL_UART_STATE_BUSY;
/* Disable the USART mute mode by clearing the RWU bit in the CR1 register */
huart->Instance->CR1 &= (uint32_t)~((uint32_t)USART_CR1_RWU);
huart->State = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enables the UART transmitter and disables the UART receiver.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00;
/* Process Locked */
__HAL_LOCK(huart);
huart->State = HAL_UART_STATE_BUSY;
/*-------------------------- USART CR1 Configuration -----------------------*/
tmpreg = huart->Instance->CR1;
/* Clear TE and RE bits */
tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
/* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */
tmpreg |= (uint32_t)USART_CR1_TE;
/* Write to USART CR1 */
huart->Instance->CR1 = (uint32_t)tmpreg;
huart->State = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @brief Enables the UART receiver and disables the UART transmitter.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00;
/* Process Locked */
__HAL_LOCK(huart);
huart->State = HAL_UART_STATE_BUSY;
/*-------------------------- USART CR1 Configuration -----------------------*/
tmpreg = huart->Instance->CR1;
/* Clear TE and RE bits */
tmpreg &= (uint32_t)~((uint32_t)(USART_CR1_TE | USART_CR1_RE));
/* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */
tmpreg |= (uint32_t)USART_CR1_RE;
/* Write to USART CR1 */
huart->Instance->CR1 = (uint32_t)tmpreg;
huart->State = HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_OK;
}
/**
* @}
*/
/** @defgroup UART_Exported_Functions_Group4 Peripheral State and Errors functions
* @brief UART State and Errors functions
*
@verbatim
==============================================================================
##### Peripheral State and Errors functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to return the State of
UART communication process, return Peripheral Errors occurred during communication
process
(+) HAL_UART_GetState() API can be helpful to check in run-time the state of the UART peripheral.
(+) HAL_UART_GetError() check in run-time errors that could be occurred during communication.
@endverbatim
* @{
*/
/**
* @brief Returns the UART state.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL state
*/
HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart)
{
return huart->State;
}
/**
* @brief Return the UART error code
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART.
* @retval UART Error Code
*/
uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart)
{
return huart->ErrorCode;
}
/**
* @}
*/
/**
* @}
*/
/** @defgroup UART_Private_Functions UART Private Functions
* @brief UART Private functions
* @{
*/
/**
* @brief DMA UART transmit process complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode*/
if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0)
{
huart->TxXferCount = 0;
/* Disable the DMA transfer for transmit request by setting the DMAT bit
in the UART CR3 register */
huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAT);
/* Wait for UART TC Flag */
if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, UART_TIMEOUT_VALUE) != HAL_OK)
{
/* Timeout occurred */
huart->State = HAL_UART_STATE_TIMEOUT;
HAL_UART_ErrorCallback(huart);
}
else
{
/* No Timeout */
/* Check if a receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
else
{
huart->State = HAL_UART_STATE_READY;
}
HAL_UART_TxCpltCallback(huart);
}
}
/* DMA Circular mode */
else
{
HAL_UART_TxCpltCallback(huart);
}
}
/**
* @brief DMA UART transmit process half complete callback
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
HAL_UART_TxHalfCpltCallback(huart);
}
/**
* @brief DMA UART receive process complete callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
/* DMA Normal mode*/
if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0)
{
huart->RxXferCount = 0;
/* Disable the DMA transfer for the receiver request by setting the DMAR bit
in the UART CR3 register */
huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAR);
/* Check if a transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
else
{
huart->State = HAL_UART_STATE_READY;
}
}
HAL_UART_RxCpltCallback(huart);
}
/**
* @brief DMA UART receive process half complete callback
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
HAL_UART_RxHalfCpltCallback(huart);
}
/**
* @brief DMA UART communication error callback.
* @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
* the configuration information for the specified DMA module.
* @retval None
*/
static void UART_DMAError(DMA_HandleTypeDef *hdma)
{
UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
huart->RxXferCount = 0;
huart->TxXferCount = 0;
huart->State= HAL_UART_STATE_READY;
huart->ErrorCode |= HAL_UART_ERROR_DMA;
HAL_UART_ErrorCallback(huart);
}
/**
* @brief This function handles UART Communication Timeout.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @param Flag: specifies the UART flag to check.
* @param Status: The new Flag status (SET or RESET).
* @param Timeout: Timeout duration
* @retval HAL status
*/
static HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout)
{
uint32_t tickstart = 0;
/* Get tick */
tickstart = HAL_GetTick();
/* Wait until flag is set */
if(Status == RESET)
{
while(__HAL_UART_GET_FLAG(huart, Flag) == RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
huart->State= HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_TIMEOUT;
}
}
}
}
else
{
while(__HAL_UART_GET_FLAG(huart, Flag) != RESET)
{
/* Check for the Timeout */
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
{
/* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
huart->State= HAL_UART_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(huart);
return HAL_TIMEOUT;
}
}
}
}
return HAL_OK;
}
/**
* @brief Sends an amount of data in non blocking mode.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart)
{
uint16_t* tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_BUSY_TX) || (tmp1 == HAL_UART_STATE_BUSY_TX_RX))
{
if(huart->Init.WordLength == UART_WORDLENGTH_9B)
{
tmp = (uint16_t*) huart->pTxBuffPtr;
huart->Instance->DR = (uint16_t)(*tmp & (uint16_t)0x01FF);
if(huart->Init.Parity == UART_PARITY_NONE)
{
huart->pTxBuffPtr += 2;
}
else
{
huart->pTxBuffPtr += 1;
}
}
else
{
huart->Instance->DR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0x00FF);
}
if(--huart->TxXferCount == 0)
{
/* Disable the UART Transmit Complete Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_TXE);
/* Enable the UART Transmit Complete Interrupt */
__HAL_UART_ENABLE_IT(huart, UART_IT_TC);
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Wraps up transmission in non blocking mode.
* @param huart: pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_EndTransmit_IT(UART_HandleTypeDef *huart)
{
/* Disable the UART Transmit Complete Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_TC);
/* Check if a receive process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_RX;
}
else
{
/* Disable the UART Parity Error Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
/* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
huart->State = HAL_UART_STATE_READY;
}
HAL_UART_TxCpltCallback(huart);
return HAL_OK;
}
/**
* @brief Receives an amount of data in non blocking mode
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval HAL status
*/
static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart)
{
uint16_t* tmp;
uint32_t tmp1 = 0;
tmp1 = huart->State;
if((tmp1 == HAL_UART_STATE_BUSY_RX) || (tmp1 == HAL_UART_STATE_BUSY_TX_RX))
{
if(huart->Init.WordLength == UART_WORDLENGTH_9B)
{
tmp = (uint16_t*) huart->pRxBuffPtr;
if(huart->Init.Parity == UART_PARITY_NONE)
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x01FF);
huart->pRxBuffPtr += 2;
}
else
{
*tmp = (uint16_t)(huart->Instance->DR & (uint16_t)0x00FF);
huart->pRxBuffPtr += 1;
}
}
else
{
if(huart->Init.Parity == UART_PARITY_NONE)
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x00FF);
}
else
{
*huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->DR & (uint8_t)0x007F);
}
}
if(--huart->RxXferCount == 0)
{
__HAL_UART_DISABLE_IT(huart, UART_IT_RXNE);
/* Check if a transmit process is ongoing or not */
if(huart->State == HAL_UART_STATE_BUSY_TX_RX)
{
huart->State = HAL_UART_STATE_BUSY_TX;
}
else
{
/* Disable the UART Parity Error Interrupt */
__HAL_UART_DISABLE_IT(huart, UART_IT_PE);
/* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */
__HAL_UART_DISABLE_IT(huart, UART_IT_ERR);
huart->State = HAL_UART_STATE_READY;
}
HAL_UART_RxCpltCallback(huart);
return HAL_OK;
}
return HAL_OK;
}
else
{
return HAL_BUSY;
}
}
/**
* @brief Configures the UART peripheral.
* @param huart: Pointer to a UART_HandleTypeDef structure that contains
* the configuration information for the specified UART module.
* @retval None
*/
static void UART_SetConfig(UART_HandleTypeDef *huart)
{
uint32_t tmpreg = 0x00;
/* Check the parameters */
assert_param(IS_UART_INSTANCE(huart->Instance));
assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate));
assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength));
assert_param(IS_UART_STOPBITS(huart->Init.StopBits));
assert_param(IS_UART_PARITY(huart->Init.Parity));
assert_param(IS_UART_MODE(huart->Init.Mode));
assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl));
/* The hardware flow control is available only for USART1, USART2, USART3 and USART6 */
if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE)
{
assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance));
}
/*-------------------------- USART CR2 Configuration -----------------------*/
/* Configure the UART Stop Bits: Set STOP[13:12] bits according
* to huart->Init.StopBits value */
MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits);
/*-------------------------- USART CR1 Configuration -----------------------*/
/* Configure the UART Word Length, Parity and mode:
Set the M bits according to huart->Init.WordLength value
Set PCE and PS bits according to huart->Init.Parity value
Set TE and RE bits according to huart->Init.Mode value
Set OVER8 bit according to huart->Init.OverSampling value */
tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling;
MODIFY_REG(huart->Instance->CR1,
(uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8),
tmpreg);
/*-------------------------- USART CR3 Configuration -----------------------*/
/* Configure the UART HFC: Set CTSE and RTSE bits according to huart->Init.HwFlowCtl value */
MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE), huart->Init.HwFlowCtl);
/* Check the Over Sampling */
if(huart->Init.OverSampling == UART_OVERSAMPLING_8)
{
/*-------------------------- USART BRR Configuration ---------------------*/
if((huart->Instance == USART1))
{
huart->Instance->BRR = UART_BRR_SAMPLING8(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate);
}
else
{
huart->Instance->BRR = UART_BRR_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate);
}
}
else
{
/*-------------------------- USART BRR Configuration ---------------------*/
if((huart->Instance == USART1))
{
huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate);
}
else
{
huart->Instance->BRR = UART_BRR_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate);
}
}
}
/**
* @}
*/
#endif /* HAL_UART_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| {'content_hash': '142e5454015f63ec63bdca0931dd9acd', 'timestamp': '', 'source': 'github', 'line_count': 1819, 'max_line_length': 132, 'avg_line_length': 30.25453545904343, 'alnum_prop': 0.6103973979248815, 'repo_name': 'ban4jp/mbed', 'id': '53ef551f2dc41c68787ae045d63ef05647085684', 'size': '63935', 'binary': False, 'copies': '51', 'ref': 'refs/heads/master', 'path': 'libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32L1/stm32l1xx_hal_uart.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '3482197'}, {'name': 'C', 'bytes': '96792596'}, {'name': 'C++', 'bytes': '6125700'}, {'name': 'CMake', 'bytes': '4724'}, {'name': 'HTML', 'bytes': '572290'}, {'name': 'JavaScript', 'bytes': '1494'}, {'name': 'Makefile', 'bytes': '181'}, {'name': 'Objective-C', 'bytes': '56719'}, {'name': 'Python', 'bytes': '613997'}, {'name': 'Shell', 'bytes': '188'}]} |
namespace rx
{
bool VertexBuffer9::mTranslationsInitialized = false;
VertexBuffer9::FormatConverter VertexBuffer9::mFormatConverters[NUM_GL_VERTEX_ATTRIB_TYPES][2][4];
VertexBuffer9::VertexBuffer9(rx::Renderer9 *const renderer) : mRenderer(renderer)
{
mVertexBuffer = NULL;
mBufferSize = 0;
mDynamicUsage = false;
if (!mTranslationsInitialized)
{
initializeTranslations(renderer->getCapsDeclTypes());
mTranslationsInitialized = true;
}
}
VertexBuffer9::~VertexBuffer9()
{
if (mVertexBuffer)
{
mVertexBuffer->Release();
mVertexBuffer = NULL;
}
}
bool VertexBuffer9::initialize(unsigned int size, bool dynamicUsage)
{
if (mVertexBuffer)
{
mVertexBuffer->Release();
mVertexBuffer = NULL;
}
updateSerial();
if (size > 0)
{
DWORD flags = D3DUSAGE_WRITEONLY;
if (dynamicUsage)
{
flags |= D3DUSAGE_DYNAMIC;
}
HRESULT result = mRenderer->createVertexBuffer(size, flags, &mVertexBuffer);
if (FAILED(result))
{
ERR("Out of memory allocating a vertex buffer of size %lu.", size);
return false;
}
}
mBufferSize = size;
mDynamicUsage = dynamicUsage;
return true;
}
VertexBuffer9 *VertexBuffer9::makeVertexBuffer9(VertexBuffer *vertexBuffer)
{
ASSERT(HAS_DYNAMIC_TYPE(VertexBuffer9*, vertexBuffer));
return static_cast<VertexBuffer9*>(vertexBuffer);
}
bool VertexBuffer9::storeVertexAttributes(const gl::VertexAttribute &attrib, GLint start, GLsizei count,
GLsizei instances, unsigned int offset)
{
if (mVertexBuffer)
{
gl::Buffer *buffer = attrib.mBoundBuffer.get();
int inputStride = attrib.stride();
int elementSize = attrib.typeSize();
const FormatConverter &converter = formatConverter(attrib);
DWORD lockFlags = mDynamicUsage ? D3DLOCK_NOOVERWRITE : 0;
void *mapPtr = NULL;
unsigned int mapSize;
if (!spaceRequired(attrib, count, instances, &mapSize))
{
return false;
}
HRESULT result = mVertexBuffer->Lock(offset, mapSize, &mapPtr, lockFlags);
if (FAILED(result))
{
ERR("Lock failed with error 0x%08x", result);
return false;
}
const char *input = NULL;
if (buffer)
{
BufferStorage *storage = buffer->getStorage();
input = static_cast<const char*>(storage->getData()) + static_cast<int>(attrib.mOffset);
}
else
{
input = static_cast<const char*>(attrib.mPointer);
}
if (instances == 0 || attrib.mDivisor == 0)
{
input += inputStride * start;
}
if (converter.identity && inputStride == elementSize)
{
memcpy(mapPtr, input, count * inputStride);
}
else
{
converter.convertArray(input, inputStride, count, mapPtr);
}
mVertexBuffer->Unlock();
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
bool VertexBuffer9::storeRawData(const void* data, unsigned int size, unsigned int offset)
{
if (mVertexBuffer)
{
DWORD lockFlags = mDynamicUsage ? D3DLOCK_NOOVERWRITE : 0;
void *mapPtr = NULL;
HRESULT result = mVertexBuffer->Lock(offset, size, &mapPtr, lockFlags);
if (FAILED(result))
{
ERR("Lock failed with error 0x%08x", result);
return false;
}
memcpy(mapPtr, data, size);
mVertexBuffer->Unlock();
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
bool VertexBuffer9::getSpaceRequired(const gl::VertexAttribute &attrib, GLsizei count, GLsizei instances,
unsigned int *outSpaceRequired) const
{
return spaceRequired(attrib, count, instances, outSpaceRequired);
}
bool VertexBuffer9::requiresConversion(const gl::VertexAttribute &attrib) const
{
return !formatConverter(attrib).identity;
}
unsigned int VertexBuffer9::getVertexSize(const gl::VertexAttribute &attrib) const
{
unsigned int spaceRequired;
return getSpaceRequired(attrib, 1, 0, &spaceRequired) ? spaceRequired : 0;
}
D3DDECLTYPE VertexBuffer9::getDeclType(const gl::VertexAttribute &attrib) const
{
return formatConverter(attrib).d3dDeclType;
}
unsigned int VertexBuffer9::getBufferSize() const
{
return mBufferSize;
}
bool VertexBuffer9::setBufferSize(unsigned int size)
{
if (size > mBufferSize)
{
return initialize(size, mDynamicUsage);
}
else
{
return true;
}
}
bool VertexBuffer9::discard()
{
if (mVertexBuffer)
{
void *dummy;
HRESULT result;
result = mVertexBuffer->Lock(0, 1, &dummy, D3DLOCK_DISCARD);
if (FAILED(result))
{
ERR("Discard lock failed with error 0x%08x", result);
return false;
}
result = mVertexBuffer->Unlock();
if (FAILED(result))
{
ERR("Discard unlock failed with error 0x%08x", result);
return false;
}
return true;
}
else
{
ERR("Vertex buffer not initialized.");
return false;
}
}
IDirect3DVertexBuffer9 * VertexBuffer9::getBuffer() const
{
return mVertexBuffer;
}
// Mapping from OpenGL-ES vertex attrib type to D3D decl type:
//
// BYTE SHORT (Cast)
// BYTE-norm FLOAT (Normalize) (can't be exactly represented as SHORT-norm)
// UNSIGNED_BYTE UBYTE4 (Identity) or SHORT (Cast)
// UNSIGNED_BYTE-norm UBYTE4N (Identity) or FLOAT (Normalize)
// SHORT SHORT (Identity)
// SHORT-norm SHORT-norm (Identity) or FLOAT (Normalize)
// UNSIGNED_SHORT FLOAT (Cast)
// UNSIGNED_SHORT-norm USHORT-norm (Identity) or FLOAT (Normalize)
// FIXED (not in WebGL) FLOAT (FixedToFloat)
// FLOAT FLOAT (Identity)
// GLToCType maps from GL type (as GLenum) to the C typedef.
template <GLenum GLType> struct GLToCType { };
template <> struct GLToCType<GL_BYTE> { typedef GLbyte type; };
template <> struct GLToCType<GL_UNSIGNED_BYTE> { typedef GLubyte type; };
template <> struct GLToCType<GL_SHORT> { typedef GLshort type; };
template <> struct GLToCType<GL_UNSIGNED_SHORT> { typedef GLushort type; };
template <> struct GLToCType<GL_FIXED> { typedef GLuint type; };
template <> struct GLToCType<GL_FLOAT> { typedef GLfloat type; };
// This differs from D3DDECLTYPE in that it is unsized. (Size expansion is applied last.)
enum D3DVertexType
{
D3DVT_FLOAT,
D3DVT_SHORT,
D3DVT_SHORT_NORM,
D3DVT_UBYTE,
D3DVT_UBYTE_NORM,
D3DVT_USHORT_NORM
};
// D3DToCType maps from D3D vertex type (as enum D3DVertexType) to the corresponding C type.
template <unsigned int D3DType> struct D3DToCType { };
template <> struct D3DToCType<D3DVT_FLOAT> { typedef float type; };
template <> struct D3DToCType<D3DVT_SHORT> { typedef short type; };
template <> struct D3DToCType<D3DVT_SHORT_NORM> { typedef short type; };
template <> struct D3DToCType<D3DVT_UBYTE> { typedef unsigned char type; };
template <> struct D3DToCType<D3DVT_UBYTE_NORM> { typedef unsigned char type; };
template <> struct D3DToCType<D3DVT_USHORT_NORM> { typedef unsigned short type; };
// Encode the type/size combinations that D3D permits. For each type/size it expands to a widener that will provide the appropriate final size.
template <unsigned int type, int size> struct WidenRule { };
template <int size> struct WidenRule<D3DVT_FLOAT, size> : NoWiden<size> { };
template <int size> struct WidenRule<D3DVT_SHORT, size> : WidenToEven<size> { };
template <int size> struct WidenRule<D3DVT_SHORT_NORM, size> : WidenToEven<size> { };
template <int size> struct WidenRule<D3DVT_UBYTE, size> : WidenToFour<size> { };
template <int size> struct WidenRule<D3DVT_UBYTE_NORM, size> : WidenToFour<size> { };
template <int size> struct WidenRule<D3DVT_USHORT_NORM, size> : WidenToEven<size> { };
// VertexTypeFlags encodes the D3DCAPS9::DeclType flag and vertex declaration flag for each D3D vertex type & size combination.
template <unsigned int d3dtype, int size> struct VertexTypeFlags { };
template <unsigned int _capflag, unsigned int _declflag>
struct VertexTypeFlagsHelper
{
enum { capflag = _capflag };
enum { declflag = _declflag };
};
template <> struct VertexTypeFlags<D3DVT_FLOAT, 1> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT1> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 2> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT2> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 3> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT3> { };
template <> struct VertexTypeFlags<D3DVT_FLOAT, 4> : VertexTypeFlagsHelper<0, D3DDECLTYPE_FLOAT4> { };
template <> struct VertexTypeFlags<D3DVT_SHORT, 2> : VertexTypeFlagsHelper<0, D3DDECLTYPE_SHORT2> { };
template <> struct VertexTypeFlags<D3DVT_SHORT, 4> : VertexTypeFlagsHelper<0, D3DDECLTYPE_SHORT4> { };
template <> struct VertexTypeFlags<D3DVT_SHORT_NORM, 2> : VertexTypeFlagsHelper<D3DDTCAPS_SHORT2N, D3DDECLTYPE_SHORT2N> { };
template <> struct VertexTypeFlags<D3DVT_SHORT_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_SHORT4N, D3DDECLTYPE_SHORT4N> { };
template <> struct VertexTypeFlags<D3DVT_UBYTE, 4> : VertexTypeFlagsHelper<D3DDTCAPS_UBYTE4, D3DDECLTYPE_UBYTE4> { };
template <> struct VertexTypeFlags<D3DVT_UBYTE_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_UBYTE4N, D3DDECLTYPE_UBYTE4N> { };
template <> struct VertexTypeFlags<D3DVT_USHORT_NORM, 2> : VertexTypeFlagsHelper<D3DDTCAPS_USHORT2N, D3DDECLTYPE_USHORT2N> { };
template <> struct VertexTypeFlags<D3DVT_USHORT_NORM, 4> : VertexTypeFlagsHelper<D3DDTCAPS_USHORT4N, D3DDECLTYPE_USHORT4N> { };
// VertexTypeMapping maps GL type & normalized flag to preferred and fallback D3D vertex types (as D3DVertexType enums).
template <GLenum GLtype, bool normalized> struct VertexTypeMapping { };
template <D3DVertexType Preferred, D3DVertexType Fallback = Preferred>
struct VertexTypeMappingBase
{
enum { preferred = Preferred };
enum { fallback = Fallback };
};
template <> struct VertexTypeMapping<GL_BYTE, false> : VertexTypeMappingBase<D3DVT_SHORT> { }; // Cast
template <> struct VertexTypeMapping<GL_BYTE, true> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Normalize
template <> struct VertexTypeMapping<GL_UNSIGNED_BYTE, false> : VertexTypeMappingBase<D3DVT_UBYTE, D3DVT_FLOAT> { }; // Identity, Cast
template <> struct VertexTypeMapping<GL_UNSIGNED_BYTE, true> : VertexTypeMappingBase<D3DVT_UBYTE_NORM, D3DVT_FLOAT> { }; // Identity, Normalize
template <> struct VertexTypeMapping<GL_SHORT, false> : VertexTypeMappingBase<D3DVT_SHORT> { }; // Identity
template <> struct VertexTypeMapping<GL_SHORT, true> : VertexTypeMappingBase<D3DVT_SHORT_NORM, D3DVT_FLOAT> { }; // Cast, Normalize
template <> struct VertexTypeMapping<GL_UNSIGNED_SHORT, false> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Cast
template <> struct VertexTypeMapping<GL_UNSIGNED_SHORT, true> : VertexTypeMappingBase<D3DVT_USHORT_NORM, D3DVT_FLOAT> { }; // Cast, Normalize
template <bool normalized> struct VertexTypeMapping<GL_FIXED, normalized> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // FixedToFloat
template <bool normalized> struct VertexTypeMapping<GL_FLOAT, normalized> : VertexTypeMappingBase<D3DVT_FLOAT> { }; // Identity
// Given a GL type & norm flag and a D3D type, ConversionRule provides the type conversion rule (Cast, Normalize, Identity, FixedToFloat).
// The conversion rules themselves are defined in vertexconversion.h.
// Almost all cases are covered by Cast (including those that are actually Identity since Cast<T,T> knows it's an identity mapping).
template <GLenum fromType, bool normalized, unsigned int toType>
struct ConversionRule : Cast<typename GLToCType<fromType>::type, typename D3DToCType<toType>::type> { };
// All conversions from normalized types to float use the Normalize operator.
template <GLenum fromType> struct ConversionRule<fromType, true, D3DVT_FLOAT> : Normalize<typename GLToCType<fromType>::type> { };
// Use a full specialization for this so that it preferentially matches ahead of the generic normalize-to-float rules.
template <> struct ConversionRule<GL_FIXED, true, D3DVT_FLOAT> : FixedToFloat<GLint, 16> { };
template <> struct ConversionRule<GL_FIXED, false, D3DVT_FLOAT> : FixedToFloat<GLint, 16> { };
// A 2-stage construction is used for DefaultVertexValues because float must use SimpleDefaultValues (i.e. 0/1)
// whether it is normalized or not.
template <class T, bool normalized> struct DefaultVertexValuesStage2 { };
template <class T> struct DefaultVertexValuesStage2<T, true> : NormalizedDefaultValues<T> { };
template <class T> struct DefaultVertexValuesStage2<T, false> : SimpleDefaultValues<T> { };
// Work out the default value rule for a D3D type (expressed as the C type) and
template <class T, bool normalized> struct DefaultVertexValues : DefaultVertexValuesStage2<T, normalized> { };
template <bool normalized> struct DefaultVertexValues<float, normalized> : SimpleDefaultValues<float> { };
// Policy rules for use with Converter, to choose whether to use the preferred or fallback conversion.
// The fallback conversion produces an output that all D3D9 devices must support.
template <class T> struct UsePreferred { enum { type = T::preferred }; };
template <class T> struct UseFallback { enum { type = T::fallback }; };
// Converter ties it all together. Given an OpenGL type/norm/size and choice of preferred/fallback conversion,
// it provides all the members of the appropriate VertexDataConverter, the D3DCAPS9::DeclTypes flag in cap flag
// and the D3DDECLTYPE member needed for the vertex declaration in declflag.
template <GLenum fromType, bool normalized, int size, template <class T> class PreferenceRule>
struct Converter
: VertexDataConverter<typename GLToCType<fromType>::type,
WidenRule<PreferenceRule< VertexTypeMapping<fromType, normalized> >::type, size>,
ConversionRule<fromType,
normalized,
PreferenceRule< VertexTypeMapping<fromType, normalized> >::type>,
DefaultVertexValues<typename D3DToCType<PreferenceRule< VertexTypeMapping<fromType, normalized> >::type>::type, normalized > >
{
private:
enum { d3dtype = PreferenceRule< VertexTypeMapping<fromType, normalized> >::type };
enum { d3dsize = WidenRule<d3dtype, size>::finalWidth };
public:
enum { capflag = VertexTypeFlags<d3dtype, d3dsize>::capflag };
enum { declflag = VertexTypeFlags<d3dtype, d3dsize>::declflag };
};
// Initialize a TranslationInfo
#define TRANSLATION(type, norm, size, preferred) \
{ \
Converter<type, norm, size, preferred>::identity, \
Converter<type, norm, size, preferred>::finalSize, \
Converter<type, norm, size, preferred>::convertArray, \
static_cast<D3DDECLTYPE>(Converter<type, norm, size, preferred>::declflag) \
}
#define TRANSLATION_FOR_TYPE_NORM_SIZE(type, norm, size) \
{ \
Converter<type, norm, size, UsePreferred>::capflag, \
TRANSLATION(type, norm, size, UsePreferred), \
TRANSLATION(type, norm, size, UseFallback) \
}
#define TRANSLATIONS_FOR_TYPE(type) \
{ \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, true, 4) }, \
}
#define TRANSLATIONS_FOR_TYPE_NO_NORM(type) \
{ \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
{ TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 1), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 2), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 3), TRANSLATION_FOR_TYPE_NORM_SIZE(type, false, 4) }, \
}
const VertexBuffer9::TranslationDescription VertexBuffer9::mPossibleTranslations[NUM_GL_VERTEX_ATTRIB_TYPES][2][4] = // [GL types as enumerated by typeIndex()][normalized][size-1]
{
TRANSLATIONS_FOR_TYPE(GL_BYTE),
TRANSLATIONS_FOR_TYPE(GL_UNSIGNED_BYTE),
TRANSLATIONS_FOR_TYPE(GL_SHORT),
TRANSLATIONS_FOR_TYPE(GL_UNSIGNED_SHORT),
TRANSLATIONS_FOR_TYPE_NO_NORM(GL_FIXED),
TRANSLATIONS_FOR_TYPE_NO_NORM(GL_FLOAT)
};
void VertexBuffer9::initializeTranslations(DWORD declTypes)
{
for (unsigned int i = 0; i < NUM_GL_VERTEX_ATTRIB_TYPES; i++)
{
for (unsigned int j = 0; j < 2; j++)
{
for (unsigned int k = 0; k < 4; k++)
{
if (mPossibleTranslations[i][j][k].capsFlag == 0 || (declTypes & mPossibleTranslations[i][j][k].capsFlag) != 0)
{
mFormatConverters[i][j][k] = mPossibleTranslations[i][j][k].preferredConversion;
}
else
{
mFormatConverters[i][j][k] = mPossibleTranslations[i][j][k].fallbackConversion;
}
}
}
}
}
unsigned int VertexBuffer9::typeIndex(GLenum type)
{
switch (type)
{
case GL_BYTE: return 0;
case GL_UNSIGNED_BYTE: return 1;
case GL_SHORT: return 2;
case GL_UNSIGNED_SHORT: return 3;
case GL_FIXED: return 4;
case GL_FLOAT: return 5;
default: UNREACHABLE(); return 5;
}
}
const VertexBuffer9::FormatConverter &VertexBuffer9::formatConverter(const gl::VertexAttribute &attribute)
{
return mFormatConverters[typeIndex(attribute.mType)][attribute.mNormalized][attribute.mSize - 1];
}
bool VertexBuffer9::spaceRequired(const gl::VertexAttribute &attrib, std::size_t count, GLsizei instances,
unsigned int *outSpaceRequired)
{
unsigned int elementSize = formatConverter(attrib).outputElementSize;
if (attrib.mArrayEnabled)
{
unsigned int elementCount = 0;
if (instances == 0 || attrib.mDivisor == 0)
{
elementCount = count;
}
else
{
if (static_cast<unsigned int>(instances) < std::numeric_limits<unsigned int>::max() - (attrib.mDivisor - 1))
{
// Round up
elementCount = (static_cast<unsigned int>(instances) + (attrib.mDivisor - 1)) / attrib.mDivisor;
}
else
{
elementCount = static_cast<unsigned int>(instances) / attrib.mDivisor;
}
}
if (elementSize <= std::numeric_limits<unsigned int>::max() / elementCount)
{
if (outSpaceRequired)
{
*outSpaceRequired = elementSize * elementCount;
}
return true;
}
else
{
return false;
}
}
else
{
const unsigned int elementSize = 4;
if (outSpaceRequired)
{
*outSpaceRequired = elementSize * 4;
}
return true;
}
}
}
| {'content_hash': '6d154e9fb705f5cfa196e1199645cba8', 'timestamp': '', 'source': 'github', 'line_count': 513, 'max_line_length': 205, 'avg_line_length': 40.75438596491228, 'alnum_prop': 0.623331898407232, 'repo_name': 'viewdy/phantomjs2', 'id': '57f5bcd256aceb72575aff9a198cc9d0f7d27630', 'size': '21448', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'src/qt/qtbase/src/3rdparty/angle/src/libGLESv2/renderer/d3d9/VertexBuffer9.cpp', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '825'}, {'name': 'Assembly', 'bytes': '268988'}, {'name': 'Bison', 'bytes': '12791'}, {'name': 'C', 'bytes': '8684716'}, {'name': 'C#', 'bytes': '1101'}, {'name': 'C++', 'bytes': '126603481'}, {'name': 'CMake', 'bytes': '554470'}, {'name': 'CSS', 'bytes': '760708'}, {'name': 'DTrace', 'bytes': '1931'}, {'name': 'Emacs Lisp', 'bytes': '393'}, {'name': 'GAP', 'bytes': '194281'}, {'name': 'Groff', 'bytes': '570631'}, {'name': 'HTML', 'bytes': '5465225'}, {'name': 'Java', 'bytes': '339535'}, {'name': 'JavaScript', 'bytes': '9558581'}, {'name': 'Makefile', 'bytes': '21096'}, {'name': 'Objective-C', 'bytes': '2820750'}, {'name': 'Objective-C++', 'bytes': '7474644'}, {'name': 'Perl', 'bytes': '1736748'}, {'name': 'Perl6', 'bytes': '38417'}, {'name': 'Prolog', 'bytes': '14631'}, {'name': 'Protocol Buffer', 'bytes': '8758'}, {'name': 'Python', 'bytes': '5502273'}, {'name': 'QML', 'bytes': '170356'}, {'name': 'QMake', 'bytes': '583682'}, {'name': 'Ruby', 'bytes': '424059'}, {'name': 'Shell', 'bytes': '469013'}, {'name': 'XSLT', 'bytes': '1047'}]} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': 'ebc6e7be757e2c1611f640b676e75e91', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'f01024865bd526ffe797ce95532df0dade367def', 'size': '189', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Gardenia/Gardenia jasminoides/ Syn. Gardenia maruba/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
namespace IPC {
//------------------------------------------------------------------------------
ChannelProxy::MessageFilter::MessageFilter() {}
void ChannelProxy::MessageFilter::OnFilterAdded(Channel* channel) {}
void ChannelProxy::MessageFilter::OnFilterRemoved() {}
void ChannelProxy::MessageFilter::OnChannelConnected(int32 peer_pid) {}
void ChannelProxy::MessageFilter::OnChannelError() {}
void ChannelProxy::MessageFilter::OnChannelClosing() {}
bool ChannelProxy::MessageFilter::OnMessageReceived(const Message& message) {
return false;
}
void ChannelProxy::MessageFilter::OnDestruct() const {
delete this;
}
ChannelProxy::MessageFilter::~MessageFilter() {}
//------------------------------------------------------------------------------
ChannelProxy::Context::Context(Listener* listener,
base::SingleThreadTaskRunner* ipc_task_runner)
: listener_task_runner_(base::ThreadTaskRunnerHandle::Get()),
listener_(listener),
ipc_task_runner_(ipc_task_runner),
channel_connected_called_(false),
peer_pid_(base::kNullProcessId) {
DCHECK(ipc_task_runner_.get());
}
ChannelProxy::Context::~Context() {
}
void ChannelProxy::Context::ClearIPCTaskRunner() {
ipc_task_runner_ = NULL;
}
void ChannelProxy::Context::CreateChannel(const IPC::ChannelHandle& handle,
const Channel::Mode& mode) {
DCHECK(channel_.get() == NULL);
channel_id_ = handle.name;
channel_.reset(new Channel(handle, mode, this));
}
bool ChannelProxy::Context::TryFilters(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i]->OnMessageReceived(message)) {
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
return true;
}
}
return false;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceived(const Message& message) {
// First give a chance to the filters to process this message.
if (!TryFilters(message))
OnMessageReceivedNoFilter(message);
return true;
}
// Called on the IPC::Channel thread
bool ChannelProxy::Context::OnMessageReceivedNoFilter(const Message& message) {
// NOTE: This code relies on the listener's message loop not going away while
// this thread is active. That should be a reasonable assumption, but it
// feels risky. We may want to invent some more indirect way of referring to
// a MessageLoop if this becomes a problem.
listener_task_runner_->PostTask(
FROM_HERE, base::Bind(&Context::OnDispatchMessage, this, message));
return true;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelConnected(int32 peer_pid) {
// Add any pending filters. This avoids a race condition where someone
// creates a ChannelProxy, calls AddFilter, and then right after starts the
// peer process. The IO thread could receive a message before the task to add
// the filter is run on the IO thread.
OnAddFilter();
// We cache off the peer_pid so it can be safely accessed from both threads.
peer_pid_ = channel_->peer_pid();
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelConnected(peer_pid);
// See above comment about using listener_task_runner_ here.
listener_task_runner_->PostTask(
FROM_HERE, base::Bind(&Context::OnDispatchConnected, this));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelError() {
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnChannelError();
// See above comment about using listener_task_runner_ here.
listener_task_runner_->PostTask(
FROM_HERE, base::Bind(&Context::OnDispatchError, this));
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelOpened() {
DCHECK(channel_ != NULL);
// Assume a reference to ourselves on behalf of this thread. This reference
// will be released when we are closed.
AddRef();
if (!channel_->Connect()) {
OnChannelError();
return;
}
for (size_t i = 0; i < filters_.size(); ++i)
filters_[i]->OnFilterAdded(channel_.get());
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnChannelClosed() {
// It's okay for IPC::ChannelProxy::Close to be called more than once, which
// would result in this branch being taken.
if (!channel_.get())
return;
for (size_t i = 0; i < filters_.size(); ++i) {
filters_[i]->OnChannelClosing();
filters_[i]->OnFilterRemoved();
}
// We don't need the filters anymore.
filters_.clear();
channel_.reset();
// Balance with the reference taken during startup. This may result in
// self-destruction.
Release();
}
void ChannelProxy::Context::Clear() {
listener_ = NULL;
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnSendMessage(scoped_ptr<Message> message) {
if (!channel_.get()) {
OnChannelClosed();
return;
}
if (!channel_->Send(message.release()))
OnChannelError();
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnAddFilter() {
std::vector<scoped_refptr<MessageFilter> > new_filters;
{
base::AutoLock auto_lock(pending_filters_lock_);
new_filters.swap(pending_filters_);
}
for (size_t i = 0; i < new_filters.size(); ++i) {
filters_.push_back(new_filters[i]);
// If the channel has already been created, then we need to send this
// message so that the filter gets access to the Channel.
if (channel_.get())
new_filters[i]->OnFilterAdded(channel_.get());
// Ditto for if the channel has been connected.
if (peer_pid_)
new_filters[i]->OnChannelConnected(peer_pid_);
}
}
// Called on the IPC::Channel thread
void ChannelProxy::Context::OnRemoveFilter(MessageFilter* filter) {
if (!channel_.get())
return; // The filters have already been deleted.
for (size_t i = 0; i < filters_.size(); ++i) {
if (filters_[i].get() == filter) {
filter->OnFilterRemoved();
filters_.erase(filters_.begin() + i);
return;
}
}
NOTREACHED() << "filter to be removed not found";
}
// Called on the listener's thread
void ChannelProxy::Context::AddFilter(MessageFilter* filter) {
base::AutoLock auto_lock(pending_filters_lock_);
pending_filters_.push_back(make_scoped_refptr(filter));
ipc_task_runner_->PostTask(
FROM_HERE, base::Bind(&Context::OnAddFilter, this));
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchMessage(const Message& message) {
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging* logger = Logging::GetInstance();
std::string name;
logger->GetMessageText(message.type(), &name, &message, NULL);
TRACE_EVENT1("task", "ChannelProxy::Context::OnDispatchMessage",
"name", name);
#else
TRACE_EVENT2("task", "ChannelProxy::Context::OnDispatchMessage",
"class", IPC_MESSAGE_ID_CLASS(message.type()),
"line", IPC_MESSAGE_ID_LINE(message.type()));
#endif
if (!listener_)
return;
OnDispatchConnected();
#ifdef IPC_MESSAGE_LOG_ENABLED
if (message.type() == IPC_LOGGING_ID) {
logger->OnReceivedLoggingMessage(message);
return;
}
if (logger->Enabled())
logger->OnPreDispatchMessage(message);
#endif
listener_->OnMessageReceived(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
if (logger->Enabled())
logger->OnPostDispatchMessage(message, channel_id_);
#endif
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchConnected() {
if (channel_connected_called_)
return;
channel_connected_called_ = true;
if (listener_)
listener_->OnChannelConnected(peer_pid_);
}
// Called on the listener's thread
void ChannelProxy::Context::OnDispatchError() {
if (listener_)
listener_->OnChannelError();
}
//-----------------------------------------------------------------------------
ChannelProxy::ChannelProxy(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
Listener* listener,
base::SingleThreadTaskRunner* ipc_task_runner)
: context_(new Context(listener, ipc_task_runner)),
outgoing_message_filter_(NULL),
did_init_(false) {
Init(channel_handle, mode, true);
}
ChannelProxy::ChannelProxy(Context* context)
: context_(context),
outgoing_message_filter_(NULL),
did_init_(false) {
}
ChannelProxy::~ChannelProxy() {
DCHECK(CalledOnValidThread());
Close();
}
void ChannelProxy::Init(const IPC::ChannelHandle& channel_handle,
Channel::Mode mode,
bool create_pipe_now) {
DCHECK(CalledOnValidThread());
DCHECK(!did_init_);
#if defined(OS_POSIX)
// When we are creating a server on POSIX, we need its file descriptor
// to be created immediately so that it can be accessed and passed
// to other processes. Forcing it to be created immediately avoids
// race conditions that may otherwise arise.
if (mode & Channel::MODE_SERVER_FLAG) {
create_pipe_now = true;
}
#endif // defined(OS_POSIX)
if (create_pipe_now) {
// Create the channel immediately. This effectively sets up the
// low-level pipe so that the client can connect. Without creating
// the pipe immediately, it is possible for a listener to attempt
// to connect and get an error since the pipe doesn't exist yet.
context_->CreateChannel(channel_handle, mode);
} else {
context_->ipc_task_runner()->PostTask(
FROM_HERE, base::Bind(&Context::CreateChannel, context_.get(),
channel_handle, mode));
}
// complete initialization on the background thread
context_->ipc_task_runner()->PostTask(
FROM_HERE, base::Bind(&Context::OnChannelOpened, context_.get()));
did_init_ = true;
}
void ChannelProxy::Close() {
DCHECK(CalledOnValidThread());
// Clear the backpointer to the listener so that any pending calls to
// Context::OnDispatchMessage or OnDispatchError will be ignored. It is
// possible that the channel could be closed while it is receiving messages!
context_->Clear();
if (context_->ipc_task_runner()) {
context_->ipc_task_runner()->PostTask(
FROM_HERE, base::Bind(&Context::OnChannelClosed, context_.get()));
}
}
bool ChannelProxy::Send(Message* message) {
DCHECK(did_init_);
// TODO(alexeypa): add DCHECK(CalledOnValidThread()) here. Currently there are
// tests that call Send() from a wrong thread. See http://crbug.com/163523.
if (outgoing_message_filter())
message = outgoing_message_filter()->Rewrite(message);
#ifdef IPC_MESSAGE_LOG_ENABLED
Logging::GetInstance()->OnSendMessage(message, context_->channel_id());
#endif
context_->ipc_task_runner()->PostTask(
FROM_HERE,
base::Bind(&ChannelProxy::Context::OnSendMessage,
context_, base::Passed(scoped_ptr<Message>(message))));
return true;
}
void ChannelProxy::AddFilter(MessageFilter* filter) {
DCHECK(CalledOnValidThread());
context_->AddFilter(filter);
}
void ChannelProxy::RemoveFilter(MessageFilter* filter) {
DCHECK(CalledOnValidThread());
context_->ipc_task_runner()->PostTask(
FROM_HERE, base::Bind(&Context::OnRemoveFilter, context_.get(),
make_scoped_refptr(filter)));
}
void ChannelProxy::ClearIPCTaskRunner() {
DCHECK(CalledOnValidThread());
context()->ClearIPCTaskRunner();
}
#if defined(OS_POSIX) && !defined(OS_NACL)
// See the TODO regarding lazy initialization of the channel in
// ChannelProxy::Init().
int ChannelProxy::GetClientFileDescriptor() {
DCHECK(CalledOnValidThread());
Channel* channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetClientFileDescriptor();
}
int ChannelProxy::TakeClientFileDescriptor() {
DCHECK(CalledOnValidThread());
Channel* channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->TakeClientFileDescriptor();
}
bool ChannelProxy::GetPeerEuid(uid_t* peer_euid) const {
DCHECK(CalledOnValidThread());
Channel* channel = context_.get()->channel_.get();
// Channel must have been created first.
DCHECK(channel) << context_.get()->channel_id_;
return channel->GetPeerEuid(peer_euid);
}
#endif
//-----------------------------------------------------------------------------
} // namespace IPC
| {'content_hash': '43ae197baae2cc625c1fee0ecd96dbbf', 'timestamp': '', 'source': 'github', 'line_count': 414, 'max_line_length': 80, 'avg_line_length': 30.608695652173914, 'alnum_prop': 0.6636679292929293, 'repo_name': 'Nu3001/external_chromium_org', 'id': '45512f97e1813e916d54f09fdfaac1279a82fd15', 'size': '13291', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'ipc/ipc_channel_proxy.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '7475'}, {'name': 'AppleScript', 'bytes': '6973'}, {'name': 'Assembly', 'bytes': '26042'}, {'name': 'C', 'bytes': '4184836'}, {'name': 'C++', 'bytes': '164717018'}, {'name': 'CSS', 'bytes': '713383'}, {'name': 'Diff', 'bytes': '13146'}, {'name': 'GLSL', 'bytes': '489'}, {'name': 'HTML', 'bytes': '7334362'}, {'name': 'Java', 'bytes': '3063725'}, {'name': 'JavaScript', 'bytes': '8017222'}, {'name': 'Makefile', 'bytes': '8412632'}, {'name': 'Objective-C', 'bytes': '975091'}, {'name': 'Objective-C++', 'bytes': '6091020'}, {'name': 'PHP', 'bytes': '61320'}, {'name': 'PLpgSQL', 'bytes': '109795'}, {'name': 'Perl', 'bytes': '69277'}, {'name': 'Protocol Buffer', 'bytes': '285221'}, {'name': 'Python', 'bytes': '6225107'}, {'name': 'Rebol', 'bytes': '262'}, {'name': 'Shell', 'bytes': '447183'}, {'name': 'XSLT', 'bytes': '418'}, {'name': 'nesC', 'bytes': '14650'}]} |
SYNONYM
#### According to
Integrated Taxonomic Information System
#### Published in
null
#### Original name
null
### Remarks
null | {'content_hash': '6481a6f3c225b1fba2e354833a2fd413', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.7218045112781954, 'repo_name': 'mdoering/backbone', 'id': '2b6aadb3a724eee7410eaeebac6201219573bb81', 'size': '222', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Bryophyta/Sphagnopsida/Sphagnales/Sphagnaceae/Sphagnum/Sphagnum platyphyllum/ Syn. Sphagnum subsecundum platyphyllum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []} |
using Microsoft.AdaptiveStreaming;
using Microsoft.AdaptiveStreaming.Dash;
using Microsoft.Media.AdaptiveStreaming;
using Microsoft.PlayerFramework.Adaptive;
using Microsoft.PlayerFramework.Xaml.DashDemo.Common;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Split Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234234
namespace Microsoft.PlayerFramework.Xaml.DashDemo
{
/// <summary>
/// A page that displays a group title, a list of items within the group, and details for the
/// currently selected item.
/// </summary>
public sealed partial class SplitPage : Page
{
readonly ObservableCollection<string> RequestCollection = new ObservableCollection<string>();
DashDownloaderPlugin dashDownloaderPlugin;
AdaptivePlugin adaptivePlugin;
StreamState CurrentStreamState = StreamState.Closed;
Uri manifestUri;
NavigationHelper navigationHelper;
/// <summary>
/// NavigationHelper is used on each page to aid in navigation and
/// process lifetime management
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
enum StreamState
{
Closed,
Starting,
Playing,
}
public SplitPage()
{
this.InitializeComponent();
// Setup the navigation helper
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
adaptivePlugin = new AdaptivePlugin();
player.Plugins.Add(adaptivePlugin);
dashDownloaderPlugin = new DashDownloaderPlugin();
adaptivePlugin.DownloaderPlugin = dashDownloaderPlugin;
dashDownloaderPlugin.ChunkRequested += dashDownloaderPlugin_ChunkRequested;
dashDownloaderPlugin.ManifestRequested += dashDownloaderPlugin_ManifestRequested;
adaptivePlugin.Manager.OpenedBackground += manager_Opened;
adaptivePlugin.Manager.ClosedBackground += manager_Closed;
player.IsFullScreenChanged += player_IsFullScreenChanged;
Requests.ItemsSource = RequestCollection;
}
async void dashDownloaderPlugin_ManifestRequested(object sender, ManifestRequestedEventArgs e)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
TextBoxManifest.Text = e.OriginalManifest;
});
}
async void dashDownloaderPlugin_ChunkRequested(object sender, ChunkRequestedEventArgs e)
{
int i = 0;
var manifestUrl = manifestUri.OriginalString.ToCharArray();
var requestUrl = e.Source.OriginalString.ToCharArray();
while (manifestUrl[i] == requestUrl[i])
{
i++;
}
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (RequestCollection.Count > 1000) RequestCollection.RemoveAt(1000);
RequestCollection.Insert(0, e.Source.OriginalString.Substring(i));
});
}
void player_IsFullScreenChanged(object sender, RoutedPropertyChangedEventArgs<bool> e)
{
BottomPanel.Visibility = e.NewValue ? Visibility.Collapsed : Visibility.Visible;
LeftPanel.Visibility = e.NewValue ? Visibility.Collapsed : Visibility.Visible;
titlePanel.Visibility = e.NewValue ? Visibility.Collapsed : Visibility.Visible;
}
void manager_Opened(object sender, object e)
{
var manager = sender as AdaptiveStreamingManager;
manager.AdaptiveSrcManager.ManifestReadyEvent += AdaptiveSrcManager_ManifestReadyEvent;
manager.AdaptiveSrcManager.AdaptiveSourceStatusUpdatedEvent += AdaptiveSrcManager_AdaptiveSourceStatusUpdatedEvent;
}
void manager_Closed(object sender, object e)
{
var manager = sender as AdaptiveStreamingManager;
manager.AdaptiveSrcManager.ManifestReadyEvent -= AdaptiveSrcManager_ManifestReadyEvent;
manager.AdaptiveSrcManager.AdaptiveSourceStatusUpdatedEvent -= AdaptiveSrcManager_AdaptiveSourceStatusUpdatedEvent;
}
async void AdaptiveSrcManager_ManifestReadyEvent(Media.AdaptiveStreaming.AdaptiveSource sender, Media.AdaptiveStreaming.ManifestReadyEventArgs args)
{
CurrentStreamState = StreamState.Starting;
manifestUri = args.AdaptiveSource.Uri;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
var videoStream = args.AdaptiveSource.Manifest.SelectedStreams.Where(i => i.Type == MediaStreamType.Video).FirstOrDefault();
if (videoStream != null)
{
videoTracks.ItemsSource = videoStream.AvailableTracks;
}
var audioStreams = args.AdaptiveSource.Manifest.AvailableStreams.Where(i => i.Type == MediaStreamType.Audio);
if (audioStreams != null)
{
audioStreamsList.ItemsSource = audioStreams;
var selectedAudioStream = audioStreams.FirstOrDefault(a => a.Name == args.AdaptiveSource.Manifest.SelectedStreams.First(i => i.Type == MediaStreamType.Audio).Name);
audioStreamsList.SelectedItem = selectedAudioStream;
}
RequestCollection.Clear();
});
}
async void AdaptiveSrcManager_AdaptiveSourceStatusUpdatedEvent(Media.AdaptiveStreaming.AdaptiveSource sender, Media.AdaptiveStreaming.AdaptiveSourceStatusUpdatedEventArgs args)
{
if (CurrentStreamState == StreamState.Starting)
{
CurrentStreamState = StreamState.Playing;
}
else if (CurrentStreamState == StreamState.Playing)
{
await Task.Delay(6000); // wait 6 seconds because this is actually the time the chunk was downloaded, not the time the chunk was played
}
if (CurrentStreamState == StreamState.Closed) return;
switch (args.UpdateType)
{
case AdaptiveSourceStatusUpdateType.BitrateChanged:
var manifest = args.AdaptiveSource.Manifest;
var videoStream = manifest.SelectedStreams.Where(i => i.Type == MediaStreamType.Video).FirstOrDefault();
if (videoStream != null)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
var bitrateInfo = args.AdditionalInfo.Split(';');
var newBitrate = uint.Parse(bitrateInfo[0]);
videoTracks.SelectedItem = ((IEnumerable<IManifestTrack>)videoTracks.ItemsSource).FirstOrDefault(t => t.Bitrate == newBitrate);
});
}
break;
}
}
void Clear()
{
CurrentStreamState = StreamState.Closed;
videoTracks.ItemsSource = null;
videoTracks.SelectedItem = null;
audioStreamsList.ItemsSource = null;
audioStreamsList.SelectedItem = null;
RequestCollection.Clear();
TextBoxManifest.Text = "";
}
#region Page state management
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="sender">
/// The source of the event; typically <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">Event data that provides both the navigation parameter passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
/// a dictionary of state preserved by this page during an earlier
/// session. The state will be null the first time a page is visited.</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
player.Source = new Uri((string)e.NavigationParameter);
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="sender">The source of the event; typically <see cref="NavigationHelper"/></param>
/// <param name="e">Event data that provides an empty dictionary to be populated with
/// serializable state.</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
Clear();
dashDownloaderPlugin.ChunkRequested -= dashDownloaderPlugin_ChunkRequested;
dashDownloaderPlugin.ManifestRequested -= dashDownloaderPlugin_ManifestRequested;
adaptivePlugin.Manager.OpenedBackground -= manager_Opened;
adaptivePlugin.Manager.ClosedBackground -= manager_Closed;
player.IsFullScreenChanged -= player_IsFullScreenChanged;
player.Dispose();
adaptivePlugin = null;
dashDownloaderPlugin = null;
}
#endregion
#region NavigationHelper registration
/// The methods provided in this section are simply used to allow
/// NavigationHelper to respond to the page's navigation methods.
///
/// Page specific logic should be placed in event handlers for the
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// and <see cref="GridCS.Common.NavigationHelper.SaveState"/>.
/// The navigation parameter is available in the LoadState method
/// in addition to page state preserved during an earlier session.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
}
}
| {'content_hash': 'b1d316d0837226ebde4f8ef96aa532e0', 'timestamp': '', 'source': 'github', 'line_count': 256, 'max_line_length': 184, 'avg_line_length': 43.18359375, 'alnum_prop': 0.636454093170511, 'repo_name': 'bondarenkod/pf-arm-deploy-error', 'id': '82a43f4074791005591f0113648487de82a536b5', 'size': '11057', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'playerframework/Win8.Xaml.DashDemo.Win81/SplitPage.xaml.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '241367'}, {'name': 'C#', 'bytes': '4589698'}, {'name': 'CSS', 'bytes': '669373'}, {'name': 'HTML', 'bytes': '291713'}, {'name': 'JavaScript', 'bytes': '5567351'}]} |
var expect = chai.expect;
describe('datepicker', function(){
describe('datepicker.ex1.html', function(){
var $widgetElement = $("input[avalonctrl]").eq(0),
vmodel = avalon.vmodels[$widgetElement.attr("avalonctrl")],
root = $widgetElement.parent(),
datepickerPanel = root.find(".oni-datepicker");
before(function() {
vmodel.toggle = false;
});
it('#初始化时datepicker的toggle属性为false', function(){
expect(vmodel.toggle).to.equal(false);
});
it('#初始化时datepicker的日历选择框隐藏', function(){
expect(datepickerPanel.is(":visible")).to.equal(false);
});
it('#点击日历框,此时的toggle属性为true', function(){
root.simulate("click");
expect(vmodel.toggle).to.equal(true);
});
it('#点击日历框,展开datepicker,日历选择框显示', function(){
root.simulate("click");
expect(datepickerPanel.is(":visible")).to.equal(true);
});
})
});
| {'content_hash': 'cf7533fe4792375456aea946f6d94339', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 71, 'avg_line_length': 28.742857142857144, 'alnum_prop': 0.5566600397614314, 'repo_name': 'wandergis/avalon-webpack-spa', 'id': '978815e435fb35d8dc8dda3c39ac7110ad114ce8', 'size': '1138', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'src/assets/vendor/oniui/test/datepicker/datepicker.ex1.case.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '61400'}, {'name': 'HTML', 'bytes': '4500'}, {'name': 'JavaScript', 'bytes': '944602'}]} |
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
}
else {
jQuery = require('jquery')(root);
}
}
return factory(jQuery);
};
} else {
// Browser globals
factory(window.jQuery);
}
}(function ($) {
/**
* Dutch
*/
$.FE.LANGUAGE['nl'] = {
translation: {
// Place holder
"Type something": "Typ iets",
// Basic formatting
"Bold": "Vet",
"Italic": "Cursief",
"Underline": "Onderstreept",
"Strikethrough": "Doorhalen",
// Main buttons
"Insert": "Invoegen",
"Delete": "Verwijder",
"Cancel": "Annuleren",
"OK": "Ok\u00e9",
"Back": "Terug",
"Remove": "Verwijderen",
"More": "Meer",
"Update": "Bijwerken",
"Style": "Stijl",
// Font
"Font Family": "Lettertype",
"Font Size": "Lettergrootte",
// Colors
"Colors": "Kleuren",
"Background": "Achtergrond",
"Text": "Tekst",
"HEX Color": "HEX kleur",
// Paragraphs
"Paragraph Format": "Opmaak",
"Normal": "Normaal",
"Code": "Code",
"Heading 1": "Kop 1",
"Heading 2": "Kop 2",
"Heading 3": "Kop 3",
"Heading 4": "Kop 4",
// Style
"Paragraph Style": "Paragraaf stijl",
"Inline Style": "Inline stijl",
// Alignment
"Align": "Uitlijnen",
"Align Left": "Links uitlijnen",
"Align Center": "Centreren",
"Align Right": "Rechts uitlijnen",
"Align Justify": "Uitvullen",
"None": "Geen",
// Lists
"Ordered List": "Geordende lijst",
"Unordered List": "Ongeordende lijst",
// Indent
"Decrease Indent": "Inspringen verkleinen",
"Increase Indent": "Inspringen vergroten",
// Links
"Insert Link": "Link invoegen",
"Open in new tab": "Openen in nieuwe tab",
"Open Link": "Open link",
"Edit Link": "Link bewerken",
"Unlink": "Link verwijderen",
"Choose Link": "Link kiezen",
// Images
"Insert Image": "Afbeelding invoegen",
"Upload Image": "Afbeelding uploaden",
"By URL": "Via URL",
"Browse": "Bladeren",
"Drop image": "Sleep afbeelding",
"or click": "of klik op",
"Manage Images": "Afbeeldingen beheren",
"Loading": "Bezig met laden",
"Deleting": "Verwijderen",
"Tags": "Labels",
"Are you sure? Image will be deleted.": "Weet je het zeker? Afbeelding wordt verwijderd.",
"Replace": "Vervangen",
"Uploading": "Uploaden",
"Loading image": "Afbeelding laden",
"Display": "Tonen",
"Inline": "Inline",
"Break Text": "Tekst afbreken",
"Alternative Text": "Alternatieve tekst",
"Change Size": "Grootte wijzigen",
"Width": "Breedte",
"Height": "Hoogte",
"Something went wrong. Please try again.": "Er is iets fout gegaan. Probeer opnieuw.",
"Image Caption": "Afbeelding caption",
"Advanced Edit": "Geavanceerd bewerken",
// Video
"Insert Video": "Video invoegen",
"Embedded Code": "Ingebedde code",
"Paste in a video URL": "Voeg een video-URL toe",
"Drop video": "Sleep video",
"Your browser does not support HTML5 video.": "Je browser ondersteunt geen html5-video.",
"Upload Video": "Video uploaden",
// Tables
"Insert Table": "Tabel invoegen",
"Table Header": "Tabel hoofd",
"Remove Table": "Verwijder tabel",
"Table Style": "Tabelstijl",
"Horizontal Align": "Horizontale uitlijning",
"Row": "Rij",
"Insert row above": "Voeg rij boven toe",
"Insert row below": "Voeg rij onder toe",
"Delete row": "Verwijder rij",
"Column": "Kolom",
"Insert column before": "Voeg kolom in voor",
"Insert column after": "Voeg kolom in na",
"Delete column": "Verwijder kolom",
"Cell": "Cel",
"Merge cells": "Cellen samenvoegen",
"Horizontal split": "Horizontaal splitsen",
"Vertical split": "Verticaal splitsen",
"Cell Background": "Cel achtergrond",
"Vertical Align": "Verticale uitlijning",
"Top": "Top",
"Middle": "Midden",
"Bottom": "Onder",
"Align Top": "Uitlijnen top",
"Align Middle": "Uitlijnen midden",
"Align Bottom": "Onder uitlijnen",
"Cell Style": "Celstijl",
// Files
"Upload File": "Bestand uploaden",
"Drop file": "Sleep bestand",
// Emoticons
"Emoticons": "Emoticons",
"Grinning face": "Grijnzend gezicht",
"Grinning face with smiling eyes": "Grijnzend gezicht met lachende ogen",
"Face with tears of joy": "Gezicht met tranen van vreugde",
"Smiling face with open mouth": "Lachend gezicht met open mond",
"Smiling face with open mouth and smiling eyes": "Lachend gezicht met open mond en lachende ogen",
"Smiling face with open mouth and cold sweat": "Lachend gezicht met open mond en koud zweet",
"Smiling face with open mouth and tightly-closed eyes": "Lachend gezicht met open mond en strak gesloten ogen",
"Smiling face with halo": "Lachend gezicht met halo",
"Smiling face with horns": "Lachend gezicht met hoorns",
"Winking face": "Knipogend gezicht",
"Smiling face with smiling eyes": "Lachend gezicht met lachende ogen",
"Face savoring delicious food": "Gezicht genietend van heerlijk eten",
"Relieved face": "Opgelucht gezicht",
"Smiling face with heart-shaped eyes": "Glimlachend gezicht met hart-vormige ogen",
"Smiling face with sunglasses": "Lachend gezicht met zonnebril",
"Smirking face": "Grijnzende gezicht",
"Neutral face": "Neutraal gezicht",
"Expressionless face": "Uitdrukkingsloos gezicht",
"Unamused face": "Niet geamuseerd gezicht",
"Face with cold sweat": "Gezicht met koud zweet",
"Pensive face": "Peinzend gezicht",
"Confused face": "Verward gezicht",
"Confounded face": "Beschaamd gezicht",
"Kissing face": "Zoenend gezicht",
"Face throwing a kiss": "Gezicht gooien van een kus",
"Kissing face with smiling eyes": "Zoenend gezicht met lachende ogen",
"Kissing face with closed eyes": "Zoenend gezicht met gesloten ogen",
"Face with stuck out tongue": "Gezicht met uitstekende tong",
"Face with stuck out tongue and winking eye": "Gezicht met uitstekende tong en knipoog",
"Face with stuck out tongue and tightly-closed eyes": "Gezicht met uitstekende tong en strak-gesloten ogen",
"Disappointed face": "Teleurgesteld gezicht",
"Worried face": "Bezorgd gezicht",
"Angry face": "Boos gezicht",
"Pouting face": "Pruilend gezicht",
"Crying face": "Huilend gezicht",
"Persevering face": "Volhardend gezicht",
"Face with look of triumph": "Gezicht met blik van triomf",
"Disappointed but relieved face": "Teleurgesteld, maar opgelucht gezicht",
"Frowning face with open mouth": "Fronsend gezicht met open mond",
"Anguished face": "Gekweld gezicht",
"Fearful face": "Angstig gezicht",
"Weary face": "Vermoeid gezicht",
"Sleepy face": "Slaperig gezicht",
"Tired face": "Moe gezicht",
"Grimacing face": "Grimassen trekkend gezicht",
"Loudly crying face": "Luid schreeuwend gezicht",
"Face with open mouth": "Gezicht met open mond",
"Hushed face": "Tot zwijgen gebracht gezicht",
"Face with open mouth and cold sweat": "Gezicht met open mond en koud zweet",
"Face screaming in fear": "Gezicht schreeuwend van angst",
"Astonished face": "Verbaasd gezicht",
"Flushed face": "Blozend gezicht",
"Sleeping face": "Slapend gezicht",
"Dizzy face": "Duizelig gezicht",
"Face without mouth": "Gezicht zonder mond",
"Face with medical mask": "Gezicht met medisch masker",
// Line breaker
"Break": "Afbreken",
// Math
"Subscript": "Subscript",
"Superscript": "Superscript",
// Full screen
"Fullscreen": "Volledig scherm",
// Horizontal line
"Insert Horizontal Line": "Horizontale lijn invoegen",
// Clear formatting
"Clear Formatting": "Verwijder opmaak",
// Undo, redo
"Undo": "Ongedaan maken",
"Redo": "Opnieuw",
// Select all
"Select All": "Alles selecteren",
// Code view
"Code View": "Codeweergave",
// Quote
"Quote": "Citaat",
"Increase": "Toenemen",
"Decrease": "Afnemen",
// Quick Insert
"Quick Insert": "Snel invoegen",
// Spcial Characters
"Special Characters": "Speciale tekens",
"Latin": "Latijns",
"Greek": "Grieks",
"Cyrillic": "Cyrillisch",
"Punctuation": "Interpunctie",
"Currency": "Valuta",
"Arrows": "Pijlen",
"Math": "Wiskunde",
"Misc": "Misc",
// Print.
"Print": "Afdrukken",
// Spell Checker.
"Spell Checker": "Spellingscontrole",
// Help
"Help": "Hulp",
"Shortcuts": "Snelkoppelingen",
"Inline Editor": "Inline editor",
"Show the editor": "Laat de editor zien",
"Common actions": "Algemene acties",
"Copy": "Kopiëren",
"Cut": "Knippen",
"Paste": "Plakken",
"Basic Formatting": "Basisformattering",
"Increase quote level": "Citaat niveau verhogen",
"Decrease quote level": "Citaatniveau verminderen",
"Image / Video": "Beeld / video",
"Resize larger": "Groter maken",
"Resize smaller": "Kleiner maken",
"Table": "Tabel",
"Select table cell": "Selecteer tabelcel",
"Extend selection one cell": "Selecteer een cel uit",
"Extend selection one row": "Selecteer een rij uit",
"Navigation": "Navigatie",
"Focus popup / toolbar": "Focus pop-up / werkbalk",
"Return focus to previous position": "Focus terug naar vorige positie",
// Embed.ly
"Embed URL": "Embed url",
"Paste in a URL to embed": "Voer een URL in om toe te voegen",
// Word Paste.
"The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?": "De geplakte inhoud komt uit een Microsoft Word-document. wil je het formaat behouden of schoonmaken?",
"Keep": "Opmaak behouden",
"Clean": "Tekst schoonmaken",
"Word Paste Detected": "Word inhoud gedetecteerd"
},
direction: "ltr"
};
}));
| {'content_hash': 'b8819227cfd15cb5db044ad990667416', 'timestamp': '', 'source': 'github', 'line_count': 314, 'max_line_length': 218, 'avg_line_length': 33.92356687898089, 'alnum_prop': 0.6214795343597447, 'repo_name': 'camperjz/trident', 'id': 'cc1d8e14e019153571556bfdfbfae6d6dde0c65e', 'size': '10811', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'modules/boonex/froala/updates/9.0.0_9.0.1/source/plugins/froala/js/languages/nl.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '1763'}, {'name': 'CSS', 'bytes': '1481231'}, {'name': 'HTML', 'bytes': '690596'}, {'name': 'JavaScript', 'bytes': '4916309'}, {'name': 'PHP', 'bytes': '28451148'}, {'name': 'Shell', 'bytes': '1265'}]} |
/**
* generated by Xtext 2.10.0
*/
package com.laegler.stubbr.lang.stubbrLang;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Option</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link com.laegler.stubbr.lang.stubbrLang.Option#isDefault <em>Default</em>}</li>
* <li>{@link com.laegler.stubbr.lang.stubbrLang.Option#getName <em>Name</em>}</li>
* <li>{@link com.laegler.stubbr.lang.stubbrLang.Option#getLabel <em>Label</em>}</li>
* <li>{@link com.laegler.stubbr.lang.stubbrLang.Option#getFlowNodes <em>Flow Nodes</em>}</li>
* </ul>
*
* @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getOption()
* @model
* @generated
*/
public interface Option extends EObject
{
/**
* Returns the value of the '<em><b>Default</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Default</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Default</em>' attribute.
* @see #setDefault(boolean)
* @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getOption_Default()
* @model
* @generated
*/
boolean isDefault();
/**
* Sets the value of the '{@link com.laegler.stubbr.lang.stubbrLang.Option#isDefault <em>Default</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Default</em>' attribute.
* @see #isDefault()
* @generated
*/
void setDefault(boolean value);
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getOption_Name()
* @model
* @generated
*/
String getName();
/**
* Sets the value of the '{@link com.laegler.stubbr.lang.stubbrLang.Option#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Label</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Label</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Label</em>' attribute.
* @see #setLabel(String)
* @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getOption_Label()
* @model
* @generated
*/
String getLabel();
/**
* Sets the value of the '{@link com.laegler.stubbr.lang.stubbrLang.Option#getLabel <em>Label</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Label</em>' attribute.
* @see #getLabel()
* @generated
*/
void setLabel(String value);
/**
* Returns the value of the '<em><b>Flow Nodes</b></em>' containment reference list.
* The list contents are of type {@link com.laegler.stubbr.lang.stubbrLang.OptionFlowNode}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Flow Nodes</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Flow Nodes</em>' containment reference list.
* @see com.laegler.stubbr.lang.stubbrLang.StubbrLangPackage#getOption_FlowNodes()
* @model containment="true"
* @generated
*/
EList<OptionFlowNode> getFlowNodes();
} // Option
| {'content_hash': '03e5e437edd703b299cba7401a791e18', 'timestamp': '', 'source': 'github', 'line_count': 125, 'max_line_length': 116, 'avg_line_length': 33.0, 'alnum_prop': 0.6077575757575757, 'repo_name': 'thlaegler/stubbr', 'id': '0ae978ed217e33d55a6708d80cf5fc48c956cd77', 'size': '4125', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'com.laegler.stubbr.lang/src-gen/com/laegler/stubbr/lang/stubbrLang/Option.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '669'}, {'name': 'Cucumber', 'bytes': '1125'}, {'name': 'GAP', 'bytes': '1507949'}, {'name': 'HTML', 'bytes': '1267'}, {'name': 'Java', 'bytes': '13211265'}, {'name': 'JavaScript', 'bytes': '3177'}, {'name': 'Xtend', 'bytes': '322393'}]} |
<?xml version="1.0" encoding="utf-8"?>
<locale>
<Backend>
<Blog>
<item type="label" name="Add">
<translation language="nl"><![CDATA[artikel toevoegen]]></translation>
<translation language="en"><![CDATA[add article]]></translation>
<translation language="hu"><![CDATA[új cikk]]></translation>
<translation language="it"><![CDATA[aggiungi articolo]]></translation>
<translation language="ru"><![CDATA[Добавить статью]]></translation>
<translation language="zh"><![CDATA[添加文章]]></translation>
<translation language="de"><![CDATA[Artikel hinzufügen]]></translation>
<translation language="fr"><![CDATA[ajouter un article]]></translation>
<translation language="es"><![CDATA[agregar artículo]]></translation>
<translation language="uk"><![CDATA[Додати статтю]]></translation>
<translation language="lt"><![CDATA[naujas įrašas]]></translation>
<translation language="sv"><![CDATA[lägg till artikel]]></translation>
<translation language="el"><![CDATA[Προσθήκη άρθρου]]></translation>
</item>
<item type="label" name="WordpressFilter">
<translation language="nl"><![CDATA[filter]]></translation>
<translation language="en"><![CDATA[filter]]></translation>
</item>
<item type="message" name="Added">
<translation language="nl"><![CDATA[Het artikel "%1$s" werd toegevoegd.]]></translation>
<translation language="en"><![CDATA[The article "%1$s" was added.]]></translation>
<translation language="hu"><![CDATA[A(z) "%1$s" cikk hozzáadva.]]></translation>
<translation language="it"><![CDATA[L'articolo "%1$s" è stato aggiunto.]]></translation>
<translation language="ru"><![CDATA[Статья "%1$s" была добавлена]]></translation>
<translation language="zh"><![CDATA[文章“%1$s”已添加。]]></translation>
<translation language="de"><![CDATA[Der Artikel "%1$s" wurde hinzugefügt.]]></translation>
<translation language="fr"><![CDATA[L'article "%1$s" a été ajouté.]]></translation>
<translation language="es"><![CDATA[El artículo "%1$s" ha sido agregado.]]></translation>
<translation language="uk"><![CDATA[Статтю "%1$s" додано.]]></translation>
<translation language="sv"><![CDATA[Artikeln "%1$s" har lagts till.]]></translation>
<translation language="el"><![CDATA[Το άρθρο "%1$s" έχει προστεθεί.]]></translation>
</item>
<item type="message" name="ArticlesFor">
<translation language="nl"><![CDATA[Artikels in "%1$s"]]></translation>
<translation language="en"><![CDATA[Articles for "%1$s"]]></translation>
<translation language="it"><![CDATA[Articoli per "%1$s"]]></translation>
<translation language="ru"><![CDATA[Статья в "%1$s"]]></translation>
<translation language="zh"><![CDATA[文章“%1$s”。]]></translation>
<translation language="hu"><![CDATA[Cikkek "%1$s"-tól/től]]></translation>
<translation language="de"><![CDATA[Artikel in "%1$s"]]></translation>
<translation language="fr"><![CDATA[Articles pour "%1$s" ]]></translation>
<translation language="es"><![CDATA[Artículos para "%1$s"]]></translation>
<translation language="uk"><![CDATA[Статтю "%1$s" додано.]]></translation>
<translation language="sv"><![CDATA[Artiklar för "%1$s"]]></translation>
<translation language="el"><![CDATA[Άρθρα γιά "%1$s"]]></translation>
</item>
<item type="message" name="CommentOnWithURL">
<translation language="nl"><![CDATA[Reactie op: <a href="%1$s">%2$s</a>]]></translation>
<translation language="en"><![CDATA[Comment on: <a href="%1$s">%2$s</a>]]></translation>
<translation language="it"><![CDATA[Commento su: <a href="%1$s">%2$s</a>]]></translation>
<translation language="ru"><![CDATA[Комментарии для записи <a href="%1$s">%2$s</a>]]></translation>
<translation language="zh"><![CDATA[评论于 <a href="%1$s">%2$s</a>]]></translation>
<translation language="hu"><![CDATA[Hozzászólás: <a href="%1$s">%2$s</a>]]></translation>
<translation language="fr"><![CDATA[Commentaire sur <a href="%1$s">%2$s</a>]]></translation>
<translation language="de"><![CDATA[Kommentare zu: <a href="%1$s">%2$s</a>]]></translation>
<translation language="es"><![CDATA[Comentario en: <a href="%1$s">%2$s</a>]]></translation>
<translation language="sv"><![CDATA[Kommentar på: <en href="%1$s">%2$s</en>]]></translation>
<translation language="el"><![CDATA[Σχολιασμός του: <a href="%1$s">%2$s</a>]]></translation>
</item>
<item type="message" name="ConfirmDelete">
<translation language="nl"><![CDATA[Ben je zeker dat je het artikel "%1$s" wil verwijderen?]]></translation>
<translation language="en"><![CDATA[Are your sure you want to delete the article "%1$s"?]]></translation>
<translation language="it"><![CDATA[Sei sicuro di voler eliminare l'articolo "%1$s"?]]></translation>
<translation language="ru"><![CDATA[Действительно удалить "%1$s"?]]></translation>
<translation language="zh"><![CDATA[你确定要删除这篇文章“%1$s”?]]></translation>
<translation language="de"><![CDATA[Willst du den Artikel "%1$s" wirklich löschen?]]></translation>
<translation language="hu"><![CDATA[Biztos törölni akarod a(z) "%1$s" cikket?]]></translation>
<translation language="fr"><![CDATA[Etes-vous sûr de vouloir effacer l'article "%1$s"?]]></translation>
<translation language="es"><![CDATA[¿Estás seguro de que quieres eliminar el artículo "%1$s"?]]></translation>
<translation language="sv"><![CDATA[Är du säker du vill till ta bort artikeln "%1$s"?]]></translation>
<translation language="el"><![CDATA[Σίγουρα θέλετε να διαγράψετε αυτό το άρθρο "%1$s";]]></translation>
</item>
<item type="message" name="DeleteAllSpam">
<translation language="nl"><![CDATA[Alle spam verwijderen:]]></translation>
<translation language="en"><![CDATA[Delete all spam:]]></translation>
<translation language="it"><![CDATA[Cancella tutto lo spam:]]></translation>
<translation language="ru"><![CDATA[Удалить спам:]]></translation>
<translation language="zh"><![CDATA[清空垃圾箱:]]></translation>
<translation language="hu"><![CDATA[Összes spam törlése:]]></translation>
<translation language="fr"><![CDATA[Effacer tous les spams:]]></translation>
<translation language="de"><![CDATA[Lösche allen Spam:]]></translation>
<translation language="es"><![CDATA[Eliminar todo el Spam:]]></translation>
<translation language="sv"><![CDATA[Ta bort allt skräp:]]></translation>
<translation language="el"><![CDATA[Διαγραφή όλης της ανεπιθύμητης αλληλογραφίας:]]></translation>
</item>
<item type="message" name="Deleted">
<translation language="nl"><![CDATA[De geselecteerde artikels werden verwijderd.]]></translation>
<translation language="en"><![CDATA[The selected articles were deleted.]]></translation>
<translation language="it"><![CDATA[Gli articolo selezionati sono stati eliminati.]]></translation>
<translation language="ru"><![CDATA[Записи были удалены.]]></translation>
<translation language="zh"><![CDATA[所选文章已删除。]]></translation>
<translation language="hu"><![CDATA[A kiválasztott cikkek törlésre kerültek.]]></translation>
<translation language="de"><![CDATA[Die ausgewählten Artikel wurden gelöscht.]]></translation>
<translation language="fr"><![CDATA[Les articles sélectionnées ont été effacés.]]></translation>
<translation language="es"><![CDATA[Los artículos seleccionados fueron eliminados.]]></translation>
<translation language="sv"><![CDATA[Valda artiklar borttagna.]]></translation>
<translation language="el"><![CDATA[Τα επιλεγμένα άρθρα διεγράφησαν.]]></translation>
</item>
<item type="message" name="DeletedSpam">
<translation language="nl"><![CDATA[Alle spamberichten werden verwijderd.]]></translation>
<translation language="en"><![CDATA[All spam-comments were deleted.]]></translation>
<translation language="it"><![CDATA[Tutti i commenti ritenuti spam sono stati eliminati.]]></translation>
<translation language="ru"><![CDATA[Все спам-комментарии были удалены.]]></translation>
<translation language="zh"><![CDATA[所有垃圾评论已删除。]]></translation>
<translation language="de"><![CDATA[Alle als Spam markierten Kommentare wurden gelöscht.]]></translation>
<translation language="hu"><![CDATA[Összes spam-hozzászólás törölve.]]></translation>
<translation language="fr"><![CDATA[Tous les commentaires spams ont été effacés.]]></translation>
<translation language="es"><![CDATA[Todos los comentarios spam fueron eliminados.]]></translation>
<translation language="sv"><![CDATA[Alla skräpkommentarer borttagna.]]></translation>
<translation language="el"><![CDATA[Όλα τα ανεπιθύμητα σχόλια διεγράφησαν.]]></translation>
</item>
<item type="message" name="EditArticle">
<translation language="nl"><![CDATA[bewerk artikel "%1$s"]]></translation>
<translation language="en"><![CDATA[edit article "%1$s"]]></translation>
<translation language="hu"><![CDATA["%1$s" cikk szerkesztése]]></translation>
<translation language="it"><![CDATA[modifica articolo "%1$s"]]></translation>
<translation language="ru"><![CDATA[Редактировать запись "%1$s"]]></translation>
<translation language="zh"><![CDATA[编辑文章“%1$s”]]></translation>
<translation language="de"><![CDATA[bearbeite Artikel "%1$s"]]></translation>
<translation language="fr"><![CDATA[éditer l'article "%1$s"]]></translation>
<translation language="es"><![CDATA[editar artículo "%1$s"]]></translation>
<translation language="sv"><![CDATA[ändra artikel "%1$s"]]></translation>
<translation language="el"><![CDATA[μεταβολή άρθρου "%1$s"]]></translation>
</item>
<item type="message" name="EditCommentOn">
<translation language="nl"><![CDATA[bewerk reactie op "%1$s"]]></translation>
<translation language="en"><![CDATA[edit comment on "%1$s"]]></translation>
<translation language="hu"><![CDATA["%1$s" hozzászólás szerkesztése]]></translation>
<translation language="it"><![CDATA[modifica commento su "%1$s"]]></translation>
<translation language="ru"><![CDATA[Редактировать комментарии записи "%1$s"]]></translation>
<translation language="zh"><![CDATA[编辑“%1$s”上的评论]]></translation>
<translation language="fr"><![CDATA[éditer le commentaire sur "%1$s"]]></translation>
<translation language="de"><![CDATA[bearbeite die Kommentare zu "%1$s"]]></translation>
<translation language="es"><![CDATA[editar comentario en "%1$s"]]></translation>
<translation language="sv"><![CDATA[ändra kommentar på "%1$s"]]></translation>
<translation language="el"><![CDATA[μεταβολή του σχολίου στο "%1$s"]]></translation>
</item>
<item type="message" name="Edited">
<translation language="nl"><![CDATA[Het artikel "%1$s" werd opgeslagen.]]></translation>
<translation language="en"><![CDATA[The article "%1$s" was saved.]]></translation>
<translation language="hu"><![CDATA[A(z) "%1$s" cikk elmentve.]]></translation>
<translation language="it"><![CDATA[L'articolo "%1$s" è stato salvato.]]></translation>
<translation language="ru"><![CDATA[Запись "%1$s" сохранена.]]></translation>
<translation language="zh"><![CDATA[文章“%1$s”已保存。]]></translation>
<translation language="de"><![CDATA[Der Artikel "%1$s" wurde gespeichert.]]></translation>
<translation language="fr"><![CDATA[L'article "%1$s" a été enregistré.]]></translation>
<translation language="es"><![CDATA[El atículo "%1$s" fue guardado.]]></translation>
<translation language="sv"><![CDATA[Artikeln "%1$s" sparades.]]></translation>
<translation language="el"><![CDATA[Το άρθρο "%1$s" αποθηκεύτηκε.]]></translation>
</item>
<item type="message" name="EditedComment">
<translation language="nl"><![CDATA[De reactie werd opgeslagen.]]></translation>
<translation language="en"><![CDATA[The comment was saved.]]></translation>
<translation language="hu"><![CDATA[A hozzászólás elmentve.]]></translation>
<translation language="it"><![CDATA[Il commento è stato salvato.]]></translation>
<translation language="ru"><![CDATA[Комментарий изменен.]]></translation>
<translation language="zh"><![CDATA[评论已保存。]]></translation>
<translation language="de"><![CDATA[Der Kommentar wurde gespeichert.]]></translation>
<translation language="fr"><![CDATA[Le commentaire a été enregistré.]]></translation>
<translation language="es"><![CDATA[El comentario fue guardado.]]></translation>
<translation language="sv"><![CDATA[Kommentar sparades.]]></translation>
<translation language="el"><![CDATA[Το σχόλιο αποθηκεύτηκε.]]></translation>
</item>
<item type="message" name="FollowAllCommentsInRSS">
<translation language="nl"><![CDATA[Volg alle reacties in een RSS feed: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="en"><![CDATA[Follow all comments in a RSS feed: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="it"><![CDATA[Segui tutti i commenti tramite feed RSS: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="ru"><![CDATA[Следить за комментариями по RSS: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="zh"><![CDATA[通过RSS源订阅所有评论: <a href="%1$s">%1$s</a>。]]></translation>
<translation language="hu"><![CDATA[Az összes hozzászólás RSS feed-je: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="de"><![CDATA[Verfolge alle Kommentare in einem RSS-Feed: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="fr"><![CDATA[Faire suivre les commentaires dans un flux RSS <a href="%1$s">%1$s</a>]]></translation>
<translation language="es"><![CDATA[Sigue todos los comentarios en el RSS feed: <a href="%1$s">%1$s</a>.]]></translation>
<translation language="sv"><![CDATA[Följ alla kommentarer i ett RSS-flöde: <en href="%1$s">%1$s</en>.]]></translation>
<translation language="el"><![CDATA[Ακολούθησε όλα τα σχόλια σε μιά ροή RSS: <a href="%1$s">%1$s</a>.]]></translation>
</item>
<item type="message" name="HelpMeta">
<translation language="nl"><![CDATA[Toon de meta informatie van deze blogpost in de RSS feed (categorie)]]></translation>
<translation language="en"><![CDATA[Show the meta information for this blogpost in the RSS feed (category)]]></translation>
<translation language="it"><![CDATA[Mostra le meta informazioni di questo articolo nel feed RSS (categoria)]]></translation>
<translation language="ru"><![CDATA[Показать Мета данные для записей в RSS.]]></translation>
<translation language="zh"><![CDATA[在RSS源(分类)中显示博客文章的所有信息]]></translation>
<translation language="hu"><![CDATA[Mutasd ennek a blogposztnak a meta információit RSS feed-ben (katagória)]]></translation>
<translation language="de"><![CDATA[Zeige die Meta-Informationen für diesen Blogpost im RSS Feed (Kategorie)]]></translation>
<translation language="fr"><![CDATA[Afficher les informations meta pour ce post dans le flux RSS (catégorie)]]></translation>
<translation language="es"><![CDATA[muestra la información meta de este post en el RSS feed (category)]]></translation>
<translation language="sv"><![CDATA[Visa meta information för denna bloggpost i RSS-flöde (kategori)]]></translation>
<translation language="el"><![CDATA[Εμφάνισε τις μετα-πληροφορίες γιά αυτή την ανάρτηση στη ροή RSS (κατηγορία)]]></translation>
</item>
<item type="message" name="HelpPingServices">
<translation language="nl"><![CDATA[Laat verschillende blogservices weten wanneer je een nieuw bericht plaatst.]]></translation>
<translation language="en"><![CDATA[Let various blogservices know when you've posted a new article.]]></translation>
<translation language="it"><![CDATA[Informa diversi blogservices quando pubblichi un nuovo articolo.]]></translation>
<translation language="ru"><![CDATA[Разрешить другим блого-сервисам знать о дате новых записей.]]></translation>
<translation language="zh"><![CDATA[让多个不同的博客服务提供商知道你发布了一篇新文章。]]></translation>
<translation language="de"><![CDATA[Informiere verschiedene Blogging-Dienste sobald du einen neuen Artikel veröffentlicht hast.]]></translation>
<translation language="hu"><![CDATA[Tudj meg több más blogszolgáltatást, mikor új cikket teszel közzé.]]></translation>
<translation language="fr"><![CDATA[Informez plusieurs services de blog que vous avez posté un nouvel article.]]></translation>
<translation language="es"><![CDATA[avisa a varios servicios de blog cuando publicas un nuevo artículo.]]></translation>
<translation language="sv"><![CDATA[Låt olika bloggtjänster veta när du har postat en ny artikel.]]></translation>
<translation language="el"><![CDATA[Ενημέρωσε τις διάφορες υπηρεσίες ιστολογίων όταν έχετε αναρτήσει ένα νέο άρθρο.]]></translation>
</item>
<item type="message" name="HelpSpamFilter">
<translation language="nl"><![CDATA[Schakel de ingebouwde spam-filter (Akismet) in om spam-berichten in reacties te vermijden.]]></translation>
<translation language="en"><![CDATA[Enable the built-in spamfilter (Akismet) to help avoid spam comments.]]></translation>
<translation language="it"><![CDATA[Abilita il filtro antispam (Askimet) per evitare spam nei commenti. ]]></translation>
<translation language="ru"><![CDATA[Включить спам-фильтр Akismet.]]></translation>
<translation language="zh"><![CDATA[开启内置的垃圾评论滤镜(Akismet)过滤垃圾评论。]]></translation>
<translation language="de"><![CDATA[Aktiviere den eingebauten Spamfilter (Akismet) um Spam in den Kommentaren zu vermeiden.]]></translation>
<translation language="hu"><![CDATA[Engedélyezd a beépített spamszűrőt (Akismet) a spam hozzászólások kivédéséhez.]]></translation>
<translation language="fr"><![CDATA[Activez le filtre de spam (Akismet) pour éviter les spams dans les commentaires.]]></translation>
<translation language="es"><![CDATA[Activar el filtro spam incorporado (Akismet) para ayudar a evitar los comentarios spam.]]></translation>
<translation language="sv"><![CDATA[Aktivera det inbyggda skräpfiltret (Akismet) för att undvika skräpkommentarer.]]></translation>
<translation language="el"><![CDATA[Ενεργοποίηση του ενσωματωμένου φίλτρου (Akismet) γιά την παρεμπόδιση ανεπιθύμητων σχολίων.]]></translation>
</item>
<item type="message" name="HelpSummary">
<translation language="nl"><![CDATA[Maak voor lange artikels een inleiding of samenvatting. Die kan getoond worden op de homepage of het artikeloverzicht.]]></translation>
<translation language="en"><![CDATA[Write an introduction or summary for long articles. It will be shown on the homepage or the article overview.]]></translation>
<translation language="it"><![CDATA[Scrivi un'introduzione o un sommario per gli articoli lunghi che verrà mostrato nell'homepage o nella panoramica dell'articolo.]]></translation>
<translation language="ru"><![CDATA[Напишите краткое описание для длинных статей. Это будет показано на главной странице или в обзоре статей.]]></translation>
<translation language="zh"><![CDATA[为长篇文章撰写介绍或概括文字。它将显示在首页和文章概览页。]]></translation>
<translation language="hu"><![CDATA[Írj bevezetőt vagy összegzést a hosszú bejegyzésekhez. Ez megjelenik a kezdőoldalon vagy a cikk áttekintésénél.]]></translation>
<translation language="de"><![CDATA[Schreibe eine kurze Einleitung oder Zusammenfassung für längere Artikel. Sie wird auf der Startseite oder der Artikel-Übersicht angezeigt werden.]]></translation>
<translation language="fr"><![CDATA[Rédigez une introduction pour les articles longs. Elle sera affichée sur la homepage ou sur la vue d'ensemble de l'article.]]></translation>
<translation language="es"><![CDATA[Escribe una introducción o resumen para artículos largos. Esto se mostrará en la página principal o en el resumen del artículo.]]></translation>
<translation language="sv"><![CDATA[Skriv en introduktion eller summering för långa artiklar. Det kommer visas på hemsidan eller artikelöversikten.]]></translation>
<translation language="el"><![CDATA[Γράψτε μιά εισαγωγή ή περίληψη γιά μακροσκελή άρθρα. Θα εμφανίζεται στην αρχική σελίδα ή την προεπισκόπηση του άρθρου.]]></translation>
</item>
<item type="message" name="HelpWordpress">
<translation language="nl"><![CDATA[You can upload an export file from a wordpress site here.]]></translation>
<translation language="en"><![CDATA[Hier kan je een export bestand vanuit een wordpress site uploaden.]]></translation>
</item>
<item type="message" name="HelpWordpressFilter">
<translation language="nl"><![CDATA[The searchterm that identifies links in an existing blogpost so that we can transfer them to active links on the fork blog module.]]></translation>
<translation language="en"><![CDATA[De zoekterm die in bestaande blogposts in een link voor moet komen, alvorens wij de link kunnen omzetten naar een actieve link op de fork blog module.]]></translation>
</item>
<item type="message" name="NoCategoryItems">
<translation language="nl"><![CDATA[Er zijn nog geen categorieën. <a href="%1$s">Maak een eerste categorie</a>.]]></translation>
<translation language="en"><![CDATA[There are no categories yet. <a href="%1$s">Create the first category</a>.]]></translation>
<translation language="it"><![CDATA[Non ci sono ancora categorie. <a href="%1$s">Crea la prima categoria</a>.]]></translation>
<translation language="ru"><![CDATA[Нет категорий.<a href="%1$s">Создайте первую</a>.]]></translation>
<translation language="zh"><![CDATA[尚无分类。There are no articles yet. <a href="%1$s">创建一个分类</a>.]]></translation>
<translation language="de"><![CDATA[Es gibt noch keine Kategorien. <a href="%1$s">Erstelle die erste Kategorie</a>.]]></translation>
<translation language="hu"><![CDATA[Nincsenek még kategóriák. <a href="%1$s">Hozd létre az elsőt</a>.]]></translation>
<translation language="fr"><![CDATA[il n'y a pas encore de catégorie. <a href="%1$s">Créez la première</a>]]></translation>
<translation language="es"><![CDATA[Aún no hay categorias. <a href="%1$s">Crea la primera categoría</a>.]]></translation>
<translation language="sv"><![CDATA[Det finns inga kategorier än. <en href="%1$s">Skapa en första kategori</en>.]]></translation>
<translation language="el"><![CDATA[Δεν υπάρχουν ακόμη κατηγορίες. <a href="%1$s">Δημιουργήστε την πρώτη κατηγορία</a>.]]></translation>
</item>
<item type="message" name="NoItems">
<translation language="nl"><![CDATA[Er zijn nog geen artikels. <a href="%1$s">Schrijf het eerste artikel</a>.]]></translation>
<translation language="en"><![CDATA[There are no articles yet. <a href="%1$s">Write the first article</a>.]]></translation>
<translation language="it"><![CDATA[Non ci sono ancora articoli. <a href="%1$s">Scrivi il primo articolo</a>.]]></translation>
<translation language="ru"><![CDATA[Нет записей. <a href="%1$s">Напишите первый пост</a>.]]></translation>
<translation language="zh"><![CDATA[尚无文章。<a href="%1$s">撰写一篇文章</a>。]]></translation>
<translation language="de"><![CDATA[Es gibt noch keine Artikel. <a href="%1$s">Schreibe den ersten Artikel</a>.]]></translation>
<translation language="hu"><![CDATA[Nincsenek még cikkek. <a href="%1$s">Írd meg az elsőt</a>.]]></translation>
<translation language="fr"><![CDATA[il n'y a pas encore d'article. <a href="%1$s">Ajouter le premier article</a>.]]></translation>
<translation language="es"><![CDATA[Aún no hay artículos. <a href="%1$s">Escribe el primer artículo</a>.]]></translation>
<translation language="sv"><![CDATA[Det finns inga artiklar än. <en href="%1$s">Skriv den första artikeln</en>.]]></translation>
<translation language="el"><![CDATA[Δεν υπάρχουν ακόμη άρθρα. <a href="%1$s">Γράψε το πρώτο άρθρο</a>.]]></translation>
</item>
<item type="message" name="NotifyByEmailOnNewComment">
<translation language="nl"><![CDATA[Verwittig via email als er een nieuwe reactie is.]]></translation>
<translation language="en"><![CDATA[Notify by email when there is a new comment.]]></translation>
<translation language="it"><![CDATA[Invia una mail quando viene aggiunto un commento.]]></translation>
<translation language="ru"><![CDATA[Оповещать по E-Mail о новых комментариях.]]></translation>
<translation language="zh"><![CDATA[有新评论时发邮件提醒我。]]></translation>
<translation language="de"><![CDATA[Benachrichtigung per E-Mail bei neuen Kommentare.]]></translation>
<translation language="hu"><![CDATA[Értesítés e-mailben, ha új hozzászólás érkezik.]]></translation>
<translation language="fr"><![CDATA[Notifier par e-mail quand il y a un nouveau commentaire.]]></translation>
<translation language="es"><![CDATA[Notificar por email cuando haya un nuevo comentario.]]></translation>
<translation language="sv"><![CDATA[Notifiera via e-post när det finns en ny kommentar.]]></translation>
<translation language="el"><![CDATA[Ειδοποίηση με email όταν υπάρχει νέο σχόλιο.]]></translation>
</item>
<item type="message" name="NotifyByEmailOnNewCommentToModerate">
<translation language="nl"><![CDATA[Verwittig via email als er een nieuwe reactie te modereren is.]]></translation>
<translation language="en"><![CDATA[Notify by email when there is a new comment to moderate.]]></translation>
<translation language="it"><![CDATA[Invia una mail quando ci sono nuovi commenti da moderare.]]></translation>
<translation language="ru"><![CDATA[Оповещать по E-Mail о новых комментариях со статусом для модерации.]]></translation>
<translation language="zh"><![CDATA[有新评论待审核时发邮件提醒我。]]></translation>
<translation language="de"><![CDATA[Benachrichtigung per E-Mail bei neuen, freizuschaltenden Kommentaren.]]></translation>
<translation language="hu"><![CDATA[Értesítés e-mailben, ha új hozzászólást moderációra vár.]]></translation>
<translation language="fr"><![CDATA[Notifier par e-mail quand il y a un nouveau commentaire à modérer.]]></translation>
<translation language="es"><![CDATA[Notificar por email cuando haya un nuevo comentario que moderar.]]></translation>
<translation language="sv"><![CDATA[Notifiera via e-post när det finns en ny kommentar till moderera.]]></translation>
<translation language="el"><![CDATA[Ειδοποίηση με email όταν υπάρχει ένα νέο σχόλιο προς έγκριση.]]></translation>
</item>
<item type="message" name="NumItemsInRecentArticlesFull">
<translation language="nl"><![CDATA[Aantal items in recente artikels (volledig) widget]]></translation>
<translation language="en"><![CDATA[Number of articles in the recent articles (full) widget]]></translation>
<translation language="it"><![CDATA[Numero di articoli nel widget (completo) degli articoli recenti]]></translation>
<translation language="ru"><![CDATA[Количество последних записей (все)]]></translation>
<translation language="zh"><![CDATA[最新文章(全文)小工具中的文章数量]]></translation>
<translation language="hu"><![CDATA[A legutóbbi cikkek száma (teljes) widget]]></translation>
<translation language="fr"><![CDATA[Nombre d'articles dans le widget articles récents (complet)]]></translation>
<translation language="de"><![CDATA[Anzahl an Artikeln im neueste Artikel (vollständig) Widget.]]></translation>
<translation language="es"><![CDATA[Número de artículos en los artículos recientes (completo) widget]]></translation>
<translation language="sv"><![CDATA[Antal artiklar bland de senaste artiklarna (fullständig) widget]]></translation>
<translation language="el"><![CDATA[Πλήθος άρθρων στη μικροεφαρμογή Πρόσφατων Άρθρων (πλήρης)]]></translation>
</item>
<item type="message" name="NumItemsInRecentArticlesList">
<translation language="nl"><![CDATA[Aantal items in recente artikels (lijst) widget]]></translation>
<translation language="en"><![CDATA[Number of articles in the recent articles (list) widget]]></translation>
<translation language="it"><![CDATA[Numero di articoli nel widget (lista) degli articoli recenti]]></translation>
<translation language="ru"><![CDATA[Количество последних записей (лист)]]></translation>
<translation language="zh"><![CDATA[最新文章(列表)小工具中的文章数量]]></translation>
<translation language="hu"><![CDATA[A legutóbbi cikkek száma (lista) widget]]></translation>
<translation language="fr"><![CDATA[Nombre d'articles dans le widget articles récents (liste)]]></translation>
<translation language="de"><![CDATA[Anzahl an Artikeln im neueste Artikel (Liste) Widget.]]></translation>
<translation language="es"><![CDATA[Número de artículos en los artículos recientes (lista) widget]]></translation>
<translation language="sv"><![CDATA[Antal artiklar bland de senaste artiklarna (lista) widget]]></translation>
<translation language="el"><![CDATA[Πλήθος άρθρων στη μικροεφαρμογή Πρόσφατων Άρθρων (λίστα).]]></translation>
</item>
<item type="message" name="ShowImageForm">
<translation language="nl"><![CDATA[De gebruiker mag een afbeelding toevoegen.]]></translation>
<translation language="en"><![CDATA[The user can upload a file.]]></translation>
<translation language="ru"><![CDATA[Пользователь может загрузить файл.]]></translation>
<translation language="de"><![CDATA[Der Benutzer kann eine Datei hochladen.]]></translation>
<translation language="es"><![CDATA[El usuario puede subir un archivo.]]></translation>
<translation language="hu"><![CDATA[A felhasználó tölthet fel fájlt.]]></translation>
<translation language="sv"><![CDATA[Användaren kan ladda upp en fil.]]></translation>
<translation language="el"><![CDATA[Ο χρήστης μπορεί να ανεβάσει ένα αρχείο.]]></translation>
<translation language="zh"><![CDATA[用户可以上传一个文件。]]></translation>
</item>
<item type="message" name="ShowOnlyItemsInCategory">
<translation language="nl"><![CDATA[Toon enkel berichten in de categorie:]]></translation>
<translation language="en"><![CDATA[Show only articles for:]]></translation>
<translation language="it"><![CDATA[Mostra solo gli articoli per:]]></translation>
<translation language="ru"><![CDATA[Показаны записи:]]></translation>
<translation language="zh"><![CDATA[只显示分类下的文章:]]></translation>
<translation language="de"><![CDATA[Zeige nur Artikel der Kategorie:]]></translation>
<translation language="hu"><![CDATA[Csak cikkek mutatása:]]></translation>
<translation language="fr"><![CDATA[Montrer seulement les articles pour:]]></translation>
<translation language="es"><![CDATA[Mostrar solamente artículos para:]]></translation>
<translation language="sv"><![CDATA[Visa endast artiklar för:]]></translation>
<translation language="el"><![CDATA[Εμφάνισε άρθρα μόνον γιά:]]></translation>
</item>
<item type="error" name="DeleteCategoryNotAllowed">
<translation language="nl"><![CDATA[Het is niet toegestaan om de categorie "%1$s" te verwijderen.]]></translation>
<translation language="en"><![CDATA[It is not allowed to delete the category "%1$s".]]></translation>
<translation language="it"><![CDATA[Non è consentito eliminare la categoria "%1$s".]]></translation>
<translation language="ru"><![CDATA[Запрещено удаление категории "%1$s".]]></translation>
<translation language="zh"><![CDATA[分类“%1$s”不允许删除。]]></translation>
<translation language="de"><![CDATA[Es ist nicht erlaubt die Kategorie "%1$s" zu löschen.]]></translation>
<translation language="hu"><![CDATA[Nem törölhető a(z) "%1$s" kategória.]]></translation>
<translation language="fr"><![CDATA[Vous ne pouvez pas effacer la catégorie "%1$s".]]></translation>
<translation language="es"><![CDATA[No está permitido eliminar la categoría "%1$s".]]></translation>
<translation language="sv"><![CDATA[Det inte tillåtet att ta bort kategorin "%1$s".]]></translation>
<translation language="el"><![CDATA[Δεν επιτρέπεται να διαγράψετε την κατηγορία "%1$s".]]></translation>
</item>
<item type="error" name="RSSDescription">
<translation language="nl"><![CDATA[Blog RSS beschrijving is nog niet geconfigureerd. <a href="%1$s">Configureer</a>]]></translation>
<translation language="en"><![CDATA[Blog RSS description is not yet provided. <a href="%1$s">Configure</a>]]></translation>
<translation language="it"><![CDATA[Non è stata ancora fornita una descrizione per il feed RSS del Blog. <a href="%1$s">Aggiungila</a>]]></translation>
<translation language="ru"><![CDATA[Не установлен заголовок RSS. <a href="%1$s">Настроить</a>]]></translation>
<translation language="zh"><![CDATA[博客RSS描述尚未提供。<a href="%1$s">设置</a>]]></translation>
<translation language="fr"><![CDATA[La description du blog RSS n'est pas encore founie. <a href="%1$s">Configurer</a>]]></translation>
<translation language="hu"><![CDATA[Blog RSS leírás még nincs megadva. <a href="%1$s">Beállítás</a>]]></translation>
<translation language="de"><![CDATA[Die Blog RSS Beschreibung wurde noch nicht angegeben. <a href="%1$s">Konfigurieren</a>]]></translation>
<translation language="es"><![CDATA[Aún no se ha proporcionado una descripción para la alimentación del blog RSS. <a href="%1$s">Configurar</a>]]></translation>
<translation language="lt"><![CDATA[Tinklaraščio RSS nenustatytas, <a href="%1$s">nustatyti</a>]]></translation>
<translation language="sv"><![CDATA[Blogg RSS beskrivning är ännu inte tillagd. <en href="%1$s">Konfigurera</en>]]></translation>
<translation language="el"><![CDATA[Δεν έχει δοθεί ακόμη η περιγραφή γιά τη ροή RSS του ιστολογίου. <a href="%1$s">Ρυθμίστε την</a>]]></translation>
</item>
<item type="error" name="XMLFilesOnly">
<translation language="nl"><![CDATA[Enkel XML bestanden kunnen worden geupload.]]></translation>
<translation language="en"><![CDATA[Only XML files can be uploaded.]]></translation>
</item>
</Blog>
</Backend>
</locale>
| {'content_hash': '6b7a84f702629783a51265efadd1871e', 'timestamp': '', 'source': 'github', 'line_count': 377, 'max_line_length': 211, 'avg_line_length': 93.52519893899205, 'alnum_prop': 0.6707223687569132, 'repo_name': 'nosnickid/forkcms', 'id': '8472dfe9f39c22ee24eef9fe8fe3f25a6745e395', 'size': '37891', 'binary': False, 'copies': '14', 'ref': 'refs/heads/master', 'path': 'src/Backend/Modules/Blog/Installer/Data/locale.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '4249'}, {'name': 'CSS', 'bytes': '286439'}, {'name': 'HTML', 'bytes': '401712'}, {'name': 'JavaScript', 'bytes': '964756'}, {'name': 'PHP', 'bytes': '3126468'}, {'name': 'Smarty', 'bytes': '382045'}]} |
#pragma once
#include <qrgui/plugins/toolPluginInterface/usedInterfaces/mainWindowInterpretersInterface.h>
#include "blocksFactoryManager.h"
namespace interpreterCore {
/// Updates palette when selected robot model is changed: hides blocks from other kits and disables blocks from current
/// kit that are not supported by selected model.
class PaletteUpdateManager : public QObject
{
Q_OBJECT
public:
/// Constructor.
/// @param paletteProvider - contains methods for working with the palette.
/// @param factoryManager - provides information about currently enabled blocks.
/// @param parent - parent of this object in terms of Qt memory management system.
PaletteUpdateManager(qReal::gui::MainWindowInterpretersInterface &paletteProvider
, const BlocksFactoryManagerInterface &factoryManager
, QObject *parent = 0);
public slots:
/// Called when selected robot model is changed, updates palette.
void updatePalette(kitBase::robotModel::RobotModelInterface ¤tModel);
/// Disables all elements in robots palette.
void disableAll();
private:
qReal::gui::MainWindowInterpretersInterface &mPaletteProvider;
const BlocksFactoryManagerInterface &mFactoryManager;
};
}
| {'content_hash': 'f06ac27ab7e60f9eb001dc7afde33d38', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 119, 'avg_line_length': 32.37837837837838, 'alnum_prop': 0.7929883138564274, 'repo_name': 'danilaml/qreal', 'id': '9fc3b3e2ee4089b0859f36a4e2d992b0a4eb7014', 'size': '1802', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'plugins/robots/interpreters/interpreterCore/include/interpreterCore/managers/paletteUpdateManager.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1181'}, {'name': 'C', 'bytes': '24683'}, {'name': 'C#', 'bytes': '18292'}, {'name': 'C++', 'bytes': '6814750'}, {'name': 'CSS', 'bytes': '13352'}, {'name': 'HTML', 'bytes': '313320'}, {'name': 'IDL', 'bytes': '1877'}, {'name': 'JavaScript', 'bytes': '10959'}, {'name': 'Perl', 'bytes': '5781'}, {'name': 'Perl6', 'bytes': '40542'}, {'name': 'Prolog', 'bytes': '974'}, {'name': 'Python', 'bytes': '26582'}, {'name': 'QMake', 'bytes': '333299'}, {'name': 'Shell', 'bytes': '93422'}, {'name': 'Tcl', 'bytes': '21071'}, {'name': 'Terra', 'bytes': '4370'}, {'name': 'Turing', 'bytes': '257'}]} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>IFieldRefAttrs | fx.sharepoint.lists.jsom</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">fx.sharepoint.lists.jsom</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/fx.html">Fx</a>
</li>
<li>
<a href="../modules/fx.sharepoint.html">SharePoint</a>
</li>
<li>
<a href="../modules/fx.sharepoint.caml.html">Caml</a>
</li>
<li>
<a href="../modules/fx.sharepoint.caml.queries.html">Queries</a>
</li>
<li>
<a href="fx.sharepoint.caml.queries.ifieldrefattrs.html">IFieldRefAttrs</a>
</li>
</ul>
<h1>Interface IFieldRefAttrs</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<a href="fx.sharepoint.caml.ielementattrs.html" class="tsd-signature-type">IElementAttrs</a>
<ul class="tsd-hierarchy">
<li>
<span class="target">IFieldRefAttrs</span>
</li>
</ul>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="fx.sharepoint.caml.queries.ifieldrefattrs.html#ascending" class="tsd-kind-icon">ascending</a></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><a href="fx.sharepoint.caml.queries.ifieldrefattrs.html#name" class="tsd-kind-icon">name</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="ascending" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> ascending</h3>
<div class="tsd-signature tsd-kind-icon">ascending<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">boolean</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in src/caml/query/common/IFieldRefAttrs.ts:13</li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Optional Boolean. This specifies the sort order on a FieldRef element that is defined in a view. The default value is TRUE.</p>
</div>
</div>
</section>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-interface">
<a name="name" class="tsd-anchor"></a>
<h3><span class="tsd-flag ts-flagOptional">Optional</span> name</h3>
<div class="tsd-signature tsd-kind-icon">name<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">string</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in src/caml/query/common/IFieldRefAttrs.ts:8</li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Optional Text. This attribute provides the internal name of the field that is referenced.</p>
</div>
</div>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class=" tsd-kind-module tsd-is-not-exported">
<a href="../modules/fx.html">Fx</a>
</li>
<li class=" tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.html">Fx.<wbr>Share<wbr>Point</a>
</li>
<li class=" tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.caml.html">Fx.<wbr>Share<wbr>Point.<wbr>Caml</a>
</li>
<li class=" tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.caml.lists.html">Fx.<wbr>Share<wbr>Point.<wbr>Caml.<wbr>Lists</a>
</li>
<li class="current tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.caml.queries.html">Fx.<wbr>Share<wbr>Point.<wbr>Caml.<wbr>Queries</a>
</li>
<li class=" tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.caml.views.html">Fx.<wbr>Share<wbr>Point.<wbr>Caml.<wbr>Views</a>
</li>
<li class=" tsd-kind-module tsd-parent-kind-module">
<a href="../modules/fx.sharepoint.client.html">Fx.<wbr>Share<wbr>Point.<wbr>Client</a>
</li>
<li class=" tsd-kind-module tsd-is-not-exported">
<a href="../modules/_.html">_</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-module">
<a href="fx.sharepoint.caml.queries.ifieldrefattrs.html" class="tsd-kind-icon">IField<wbr>Ref<wbr>Attrs</a>
<ul>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="fx.sharepoint.caml.queries.ifieldrefattrs.html#ascending" class="tsd-kind-icon">ascending</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-interface">
<a href="fx.sharepoint.caml.queries.ifieldrefattrs.html#name" class="tsd-kind-icon">name</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {'content_hash': '31c614375aa01ff603728b9fca493d5c', 'timestamp': '', 'source': 'github', 'line_count': 262, 'max_line_length': 171, 'avg_line_length': 47.35114503816794, 'alnum_prop': 0.649363211349347, 'repo_name': 'fanxipan/fx-docs', 'id': '9bb68641ec3c9425d38edd5e5a09caaedbbe0fcc', 'size': '12406', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/_static/other/code-libraries/sp-jsom-list/docs/interfaces/fx.sharepoint.caml.queries.ifieldrefattrs.html', 'mode': '33188', 'license': 'mit', 'language': []} |
import Value from './Value';
import Scope from './Scope';
import Renderer from './Renderer';
//#ifndef PRODUCTION
import { VTypeError, VArgumentError } from '../error_runtime';
//#endif
export function is_str (obj) {
return typeof obj == 'string';
}
/* the poh is an abbreviation for the parent or host */
export function set_parent (parent, children) {
if (children === null) return;
for (let child of children) {
if (is_str(child))
continue;
child.__poh__ = parent;
}
}
export function set_host (host, params) {
if (params === null) return;
for (let k in params) {
if (params[k] instanceof Value) {
params[k].__poh__ = host;
params[k].name = k;
}
}
}
export function check_params (rd) {
if (rd.parameters !== null) {
for (let p in rd.parameters) {
let v = rd.parameters[p];
//#ifndef PRODUCTION
if (p.slice(-4) == '.type') {
let p_base = p.slice(0, -4);
if (!v(rd.parameters[p_base]))
throw VTypeError(rd.name, p_base);
continue;
}
if (v === null)
throw VArgumentError(rd.name, p, true);
//#endif
if (v instanceof Value) v = v.vf();
rd.instance.__argv__[p] = v;
}
}
}
export function set_scope (unit) {
let poh = unit.__poh__;
poh = poh instanceof Scope ? poh.__poh__ : poh;
while (poh !== null) {
if (poh instanceof Scope) {
break;
}
poh = poh.__poh__;
}
unit.scope = poh;
} | {'content_hash': '3fb38d705d810f15e5300aebae2067c0', 'timestamp': '', 'source': 'github', 'line_count': 62, 'max_line_length': 62, 'avg_line_length': 26.112903225806452, 'alnum_prop': 0.5132798023471279, 'repo_name': 'lemoi/vpp', 'id': '945bb3a7b8dfd64bfdfc5df2eb11121b19a2835b', 'size': '1619', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/vm/dom/.old/renderer/helper.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Coq', 'bytes': '161'}, {'name': 'JavaScript', 'bytes': '52564'}, {'name': 'Verilog', 'bytes': '176'}]} |
package org.apache.struts.config.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.config.ActionConfig;
import org.apache.struts.config.ActionConfigMatcher;
import org.apache.struts.config.BaseConfig;
import org.apache.struts.config.ControllerConfig;
import org.apache.struts.config.ExceptionConfig;
import org.apache.struts.config.FormBeanConfig;
import org.apache.struts.config.ForwardConfig;
import org.apache.struts.config.MessageResourcesConfig;
import org.apache.struts.config.ModuleConfig;
import org.apache.struts.config.PlugInConfig;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* <p>
* The collection of static configuration information that describes a
* Struts-based module. Multiple modules are identified by a <em>prefix</em> at
* the beginning of the context relative portion of the request URI. If no
* module prefix can be matched, the default configuration (with a prefix equal
* to a zero-length string) is selected, which is elegantly backwards compatible
* with the previous Struts behavior that only supported one module.
* </p>
*
* @version $Rev: 471754 $ $Date: 2005-12-31 03:57:16 -0500 (Sat, 31 Dec 2005) $
* @since Struts 1.1
*/
public class ModuleConfigImpl extends BaseConfig implements Serializable, ModuleConfig {
/**
* <p>
* Commons Logging instance.
* </p>
*/
protected static Log log = LogFactory.getLog(ModuleConfigImpl.class);
// ----------------------------------------------------- Instance Variables
// Instance Variables at end to make comparing Interface and implementation
// easier.
/**
* <p>
* The set of action configurations for this module, if any, keyed by the
* <code>path</code> property.
* </p>
*/
protected HashMap actionConfigs = null;
/**
* <p>
* The set of action configuration for this module, if any, keyed by the
* <code>actionId</code> property.
* </p>
*/
protected HashMap actionConfigIds = null;
/**
* <p>
* The set of action configurations for this module, if any, listed in the
* order in which they are added.
* </p>
*/
protected List actionConfigList = null;
/**
* <p>
* The set of exception handling configurations for this module, if any,
* keyed by the <code>type</code> property.
* </p>
*/
protected HashMap exceptions = null;
/**
* <p>
* The set of form bean configurations for this module, if any, keyed by the
* <code>name</code> property.
* </p>
*/
protected HashMap formBeans = null;
/**
* <p>
* The set of global forward configurations for this module, if any, keyed
* by the <code>name</code> property.
* </p>
*/
protected HashMap forwards = null;
/**
* <p>
* The set of message resources configurations for this module, if any,
* keyed by the <code>key</code> property.
* </p>
*/
protected HashMap messageResources = null;
/**
* <p>
* The set of configured plug-in Actions for this module, if any, in the
* order they were declared and configured.
* </p>
*/
protected ArrayList plugIns = null;
/**
* <p>
* The controller configuration object for this module.
* </p>
*/
protected ControllerConfig controllerConfig = null;
/**
* <p>
* The prefix of the context-relative portion of the request URI, used to
* select this configuration versus others supported by the controller
* servlet. A configuration with a prefix of a zero-length String is the
* default configuration for this web module.
* </p>
*/
protected String prefix = null;
/**
* <p>
* The default class name to be used when creating action form bean
* instances.
* </p>
*/
protected String actionFormBeanClass = "org.apache.struts.action.ActionFormBean";
/**
* The default class name to be used when creating action mapping instances.
*/
protected String actionMappingClass = "org.apache.struts.action.ActionMapping";
/**
* The default class name to be used when creating action forward instances.
*/
protected String actionForwardClass = "org.apache.struts.action.ActionForward";
/**
* <p>
* Matches action config paths against compiled wildcard patterns
* </p>
*/
protected ActionConfigMatcher matcher = null;
/**
* <p>
* Constructor for ModuleConfigImpl. Assumes default configuration.
* </p>
*
* @since Struts 1.2.8
*/
public ModuleConfigImpl() {
this("");
}
/**
* <p>
* Construct an ModuleConfigImpl object according to the specified parameter
* values.
* </p>
*
* @param prefix
* Context-relative URI prefix for this module
*/
public ModuleConfigImpl(String prefix) {
super();
this.prefix = prefix;
this.actionConfigs = new HashMap();
this.actionConfigIds = new HashMap();
this.actionConfigList = new ArrayList();
this.actionFormBeanClass = "org.apache.struts.action.ActionFormBean";
this.actionMappingClass = "org.apache.struts.action.ActionMapping";
this.actionForwardClass = "org.apache.struts.action.ActionForward";
this.configured = false;
this.controllerConfig = null;
this.exceptions = new HashMap();
this.formBeans = new HashMap();
this.forwards = new HashMap();
this.messageResources = new HashMap();
this.plugIns = new ArrayList();
}
// --------------------------------------------------------- Public Methods
/**
* </p> Has this module been completely configured yet. Once this flag has
* been set, any attempt to modify the configuration will return an
* IllegalStateException.</p>
*/
public boolean getConfigured() {
return (this.configured);
}
/**
* <p>
* The controller configuration object for this module.
* </p>
*/
public ControllerConfig getControllerConfig() {
if (this.controllerConfig == null) {
this.controllerConfig = new ControllerConfig();
}
return (this.controllerConfig);
}
/**
* <p>
* The controller configuration object for this module.
* </p>
*
* @param cc
* The controller configuration object for this module.
*/
public void setControllerConfig(ControllerConfig cc) {
throwIfConfigured();
this.controllerConfig = cc;
}
/**
* <p>
* The prefix of the context-relative portion of the request URI, used to
* select this configuration versus others supported by the controller
* servlet. A configuration with a prefix of a zero-length String is the
* default configuration for this web module.
* </p>
*/
public String getPrefix() {
return (this.prefix);
}
/**
* <p>
* The prefix of the context-relative portion of the request URI, used to
* select this configuration versus others supported by the controller
* servlet. A configuration with a prefix of a zero-length String is the
* default configuration for this web module.
* </p>
*/
public void setPrefix(String prefix) {
throwIfConfigured();
this.prefix = prefix;
}
/**
* <p>
* The default class name to be used when creating action form bean
* instances.
* </p>
*/
public String getActionFormBeanClass() {
return this.actionFormBeanClass;
}
/**
* <p>
* The default class name to be used when creating action form bean
* instances.
* </p>
*
* @param actionFormBeanClass
* default class name to be used when creating action form bean
* instances.
*/
public void setActionFormBeanClass(String actionFormBeanClass) {
this.actionFormBeanClass = actionFormBeanClass;
}
/**
* <p>
* The default class name to be used when creating action mapping instances.
* </p>
*/
public String getActionMappingClass() {
return this.actionMappingClass;
}
/**
* <p>
* The default class name to be used when creating action mapping instances.
* </p>
*
* @param actionMappingClass
* default class name to be used when creating action mapping
* instances.
*/
public void setActionMappingClass(String actionMappingClass) {
this.actionMappingClass = actionMappingClass;
}
/**
* </p> Ad d a new <code>ActionConfig</code> instance to the set associated
* with this module. </p>
*
* @param config
* The new configuration instance to be added
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void addActionConfig(ActionConfig config) {
throwIfConfigured();
config.setModuleConfig(this);
String path = config.getPath();
if (actionConfigs.containsKey(path)) {
log.warn("Overriding ActionConfig of path " + path);
}
String actionId = config.getActionId();
if ((actionId != null) && !actionId.equals("")) {
if (actionConfigIds.containsKey(actionId)) {
if (log.isWarnEnabled()) {
ActionConfig otherConfig = (ActionConfig) actionConfigIds.get(actionId);
StringBuffer msg = new StringBuffer("Overriding actionId[");
msg.append(actionId);
msg.append("] for path[");
msg.append(otherConfig.getPath());
msg.append("] with path[");
msg.append(path);
msg.append("]");
log.warn(msg);
}
}
actionConfigIds.put(actionId, config);
}
actionConfigs.put(path, config);
actionConfigList.add(config);
}
/**
* <p>
* Add a new <code>ExceptionConfig</code> instance to the set associated
* with this module.
* </p>
*
* @param config
* The new configuration instance to be added
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void addExceptionConfig(ExceptionConfig config) {
throwIfConfigured();
String key = config.getType();
if (exceptions.containsKey(key)) {
log.warn("Overriding ExceptionConfig of type " + key);
}
exceptions.put(key, config);
}
/**
* <p>
* Add a new <code>FormBeanConfig</code> instance to the set associated with
* this module.
* </p>
*
* @param config
* The new configuration instance to be added
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void addFormBeanConfig(FormBeanConfig config) {
throwIfConfigured();
String key = config.getName();
if (formBeans.containsKey(key)) {
log.warn("Overriding ActionForm of name " + key);
}
formBeans.put(key, config);
}
/**
* <p>
* The default class name to be used when creating action forward instances.
* </p>
*/
public String getActionForwardClass() {
return this.actionForwardClass;
}
/**
* <p>
* The default class name to be used when creating action forward instances.
* </p>
*
* @param actionForwardClass
* default class name to be used when creating action forward
* instances.
*/
public void setActionForwardClass(String actionForwardClass) {
this.actionForwardClass = actionForwardClass;
}
/**
* <p>
* Add a new <code>ForwardConfig</code> instance to the set of global
* forwards associated with this module.
* </p>
*
* @param config
* The new configuration instance to be added
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void addForwardConfig(ForwardConfig config) {
throwIfConfigured();
String key = config.getName();
if (forwards.containsKey(key)) {
log.warn("Overriding global ActionForward of name " + key);
}
forwards.put(key, config);
}
/**
* <p>
* Add a new <code>MessageResourcesConfig</code> instance to the set
* associated with this module.
* </p>
*
* @param config
* The new configuration instance to be added
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void addMessageResourcesConfig(MessageResourcesConfig config) {
throwIfConfigured();
String key = config.getKey();
if (messageResources.containsKey(key)) {
log.warn("Overriding MessageResources bundle of key " + key);
}
messageResources.put(key, config);
}
/**
* <p>
* Add a newly configured {@link org.apache.struts.config.PlugInConfig}
* instance to the set of plug-in Actions for this module.
* </p>
*
* @param plugInConfig
* The new configuration instance to be added
*/
public void addPlugInConfig(PlugInConfig plugInConfig) {
throwIfConfigured();
plugIns.add(plugInConfig);
}
/**
* <p>
* Return the action configuration for the specified path, first looking a
* direct match, then if none found, a wildcard pattern match; otherwise
* return <code>null</code>.
* </p>
*
* @param path
* Path of the action configuration to return
*/
public ActionConfig findActionConfig(String path) {
ActionConfig config = (ActionConfig) actionConfigs.get(path);
// If a direct match cannot be found, try to match action configs
// containing wildcard patterns only if a matcher exists.
if ((config == null) && (matcher != null)) {
config = matcher.match(path);
}
return config;
}
/**
* <p>
* Returns the action configuration for the specifed action action
* identifier.
* </p>
*
* @param actionId
* the action identifier
* @return the action config if found; otherwise <code>null</code>
* @see ActionConfig#getActionId()
* @since Struts 1.3.6
*/
public ActionConfig findActionConfigId(String actionId) {
if (actionId != null) {
return (ActionConfig) this.actionConfigIds.get(actionId);
}
return null;
}
/**
* <p>
* Return the action configurations for this module. If there are none, a
* zero-length array is returned.
* </p>
*/
public ActionConfig[] findActionConfigs() {
ActionConfig[] results = new ActionConfig[actionConfigList.size()];
return ((ActionConfig[]) actionConfigList.toArray(results));
}
/**
* <p>
* Return the exception configuration for the specified type, if any;
* otherwise return <code>null</code>.
* </p>
*
* @param type
* Exception class name to find a configuration for
*/
public ExceptionConfig findExceptionConfig(String type) {
return ((ExceptionConfig) exceptions.get(type));
}
/**
* <p>
* Find and return the <code>ExceptionConfig</code> instance defining how
* <code>Exceptions</code> of the specified type should be handled.
*
* <p>
* In original Struts usage, this was only available in
* <code>ActionConfig</code>, but there are cases when an exception could be
* thrown before an <code>ActionConfig</code> has been identified, where
* global exception handlers may still be pertinent.
* </p>
*
* <p>
* TODO: Look for a way to share this logic with <code>ActionConfig</code>,
* although there are subtle differences, and it certainly doesn't seem like
* it should be done with inheritance.
* </p>
*
* @param type
* Exception class for which to find a handler
* @since Struts 1.3.0
*/
public ExceptionConfig findException(Class type) {
// Check through the entire superclass hierarchy as needed
ExceptionConfig config = null;
while (true) {
// Check for a locally defined handler
String name = type.getName();
log.debug("findException: look locally for " + name);
config = findExceptionConfig(name);
if (config != null) {
return (config);
}
// Loop again for our superclass (if any)
type = type.getSuperclass();
if (type == null) {
break;
}
}
return (null); // No handler has been configured
}
/**
* <p>
* Return the exception configurations for this module. If there are none, a
* zero-length array is returned.
* </p>
*/
public ExceptionConfig[] findExceptionConfigs() {
ExceptionConfig[] results = new ExceptionConfig[exceptions.size()];
return ((ExceptionConfig[]) exceptions.values().toArray(results));
}
/**
* <p>
* Return the form bean configuration for the specified key, if any;
* otherwise return <code>null</code>.
* </p>
*
* @param name
* Name of the form bean configuration to return
*/
public FormBeanConfig findFormBeanConfig(String name) {
return ((FormBeanConfig) formBeans.get(name));
}
/**
* <p>
* Return the form bean configurations for this module. If there are none, a
* zero-length array is returned.
* </p>
*/
public FormBeanConfig[] findFormBeanConfigs() {
FormBeanConfig[] results = new FormBeanConfig[formBeans.size()];
return ((FormBeanConfig[]) formBeans.values().toArray(results));
}
/**
* <p>
* Return the forward configuration for the specified key, if any; otherwise
* return <code>null</code>.
* </p>
*
* @param name
* Name of the forward configuration to return
*/
public ForwardConfig findForwardConfig(String name) {
return ((ForwardConfig) forwards.get(name));
}
/**
* <p>
* Return the form bean configurations for this module. If there are none, a
* zero-length array is returned.
* </p>
*/
public ForwardConfig[] findForwardConfigs() {
ForwardConfig[] results = new ForwardConfig[forwards.size()];
return ((ForwardConfig[]) forwards.values().toArray(results));
}
/**
* <p>
* Return the message resources configuration for the specified key, if any;
* otherwise return <code>null</code>.
* </p>
*
* @param key
* Key of the data source configuration to return
*/
public MessageResourcesConfig findMessageResourcesConfig(String key) {
return ((MessageResourcesConfig) messageResources.get(key));
}
/**
* <p>
* Return the message resources configurations for this module. If there are
* none, a zero-length array is returned.
* </p>
*/
public MessageResourcesConfig[] findMessageResourcesConfigs() {
MessageResourcesConfig[] results = new MessageResourcesConfig[messageResources.size()];
return ((MessageResourcesConfig[]) messageResources.values().toArray(results));
}
/**
* <p>
* Return the configured plug-in actions for this module. If there are none,
* a zero-length array is returned.
* </p>
*/
public PlugInConfig[] findPlugInConfigs() {
PlugInConfig[] results = new PlugInConfig[plugIns.size()];
return ((PlugInConfig[]) plugIns.toArray(results));
}
/**
* <p>
* Freeze the configuration of this module. After this method returns, any
* attempt to modify the configuration will return an IllegalStateException.
* </p>
*/
public void freeze() {
super.freeze();
ActionConfig[] aconfigs = findActionConfigs();
for (int i = 0; i < aconfigs.length; i++) {
aconfigs[i].freeze();
}
matcher = new ActionConfigMatcher(aconfigs);
getControllerConfig().freeze();
ExceptionConfig[] econfigs = findExceptionConfigs();
for (int i = 0; i < econfigs.length; i++) {
econfigs[i].freeze();
}
FormBeanConfig[] fbconfigs = findFormBeanConfigs();
for (int i = 0; i < fbconfigs.length; i++) {
fbconfigs[i].freeze();
}
ForwardConfig[] fconfigs = findForwardConfigs();
for (int i = 0; i < fconfigs.length; i++) {
fconfigs[i].freeze();
}
MessageResourcesConfig[] mrconfigs = findMessageResourcesConfigs();
for (int i = 0; i < mrconfigs.length; i++) {
mrconfigs[i].freeze();
}
PlugInConfig[] piconfigs = findPlugInConfigs();
for (int i = 0; i < piconfigs.length; i++) {
piconfigs[i].freeze();
}
}
/**
* <p>
* Remove the specified action configuration instance.
* </p>
*
* @param config
* ActionConfig instance to be removed
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void removeActionConfig(ActionConfig config) {
throwIfConfigured();
config.setModuleConfig(null);
actionConfigs.remove(config.getPath());
actionConfigList.remove(config);
}
/**
* <p>
* Remove the specified exception configuration instance.
* </p>
*
* @param config
* ActionConfig instance to be removed
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void removeExceptionConfig(ExceptionConfig config) {
throwIfConfigured();
exceptions.remove(config.getType());
}
/**
* <p>
* Remove the specified form bean configuration instance.
* </p>
*
* @param config
* FormBeanConfig instance to be removed
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void removeFormBeanConfig(FormBeanConfig config) {
throwIfConfigured();
formBeans.remove(config.getName());
}
/**
* <p>
* Remove the specified forward configuration instance.
* </p>
*
* @param config
* ForwardConfig instance to be removed
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void removeForwardConfig(ForwardConfig config) {
throwIfConfigured();
forwards.remove(config.getName());
}
/**
* <p>
* Remove the specified message resources configuration instance.
* </p>
*
* @param config
* MessageResourcesConfig instance to be removed
* @throws IllegalStateException
* if this module configuration has been frozen
*/
public void removeMessageResourcesConfig(MessageResourcesConfig config) {
throwIfConfigured();
messageResources.remove(config.getKey());
}
}
| {'content_hash': '2d58917474ceb2d04471f23b93af2693', 'timestamp': '', 'source': 'github', 'line_count': 807, 'max_line_length': 95, 'avg_line_length': 29.639405204460967, 'alnum_prop': 0.5998578535891969, 'repo_name': 'shuliangtao/struts-1.3.10', 'id': '257eff2128326d07c9093b9adcd59bc9f0f10307', 'size': '24795', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/core/src/main/java/org/apache/struts/config/impl/ModuleConfigImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '28570'}, {'name': 'GAP', 'bytes': '7269'}, {'name': 'Java', 'bytes': '4523136'}]} |
hello: hello.cxx
$(CXX) hello.cxx -o hello
clean:
rm hello
| {'content_hash': '28cceafccb2eb838d9c11ab808039f35', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 26, 'avg_line_length': 12.4, 'alnum_prop': 0.6774193548387096, 'repo_name': 'hans-erickson/hello-world', 'id': '9e6a6f9631f25e931d3d6ee180be6c89fc7c4173', 'size': '63', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'hello-c++/Makefile', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '83'}, {'name': 'C++', 'bytes': '1268'}, {'name': 'CMake', 'bytes': '158'}, {'name': 'Java', 'bytes': '101'}, {'name': 'Makefile', 'bytes': '130'}, {'name': 'QMake', 'bytes': '99'}, {'name': 'Ruby', 'bytes': '42'}]} |
using Tibia.Constants;
namespace Tibia.Packets.Outgoing
{
public class PrivateChannelOpenPacket : OutgoingPacket
{
public string Receiver { get; set; }
public PrivateChannelOpenPacket(Objects.Client c)
: base(c)
{
Type = OutgoingPacketType.PrivateChannelOpen;
Destination = PacketDestination.Server;
}
public override bool ParseMessage(NetworkMessage msg, PacketDestination destination)
{
if (msg.GetByte() != (byte)OutgoingPacketType.PrivateChannelOpen)
return false;
Destination = destination;
Type = OutgoingPacketType.PrivateChannelOpen;
Receiver = msg.GetString();
return true;
}
public override void ToNetworkMessage(NetworkMessage msg)
{
msg.AddByte((byte)Type);
msg.AddString(Receiver);
}
public static bool Send(Objects.Client client, string receiver)
{
PrivateChannelOpenPacket p = new PrivateChannelOpenPacket(client);
p.Receiver = receiver;
return p.Send();
}
}
} | {'content_hash': '2294a2802ce4f3b70b1944a8362cc64e', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 92, 'avg_line_length': 29.536585365853657, 'alnum_prop': 0.5813377374071016, 'repo_name': 'Tiglicia/tibiaapi', 'id': 'b4dbebaad3abe1cb837d8b6a46cdd01f008c0462', 'size': '1213', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'tibiaapi/Packets/Outgoing/PrivateChannelOpenPacket.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '91'}, {'name': 'C#', 'bytes': '2360726'}, {'name': 'C++', 'bytes': '55427'}, {'name': 'Objective-C', 'bytes': '180'}, {'name': 'Visual Basic', 'bytes': '164244'}]} |
package streaming
import (
"crypto/tls"
"errors"
"io"
"net/http"
"net/url"
"path"
"time"
restful "github.com/emicklei/go-restful"
"k8s.io/kubernetes/pkg/api"
runtimeapi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
"k8s.io/kubernetes/pkg/kubelet/server/portforward"
"k8s.io/kubernetes/pkg/kubelet/server/remotecommand"
"k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util/term"
)
// The library interface to serve the stream requests.
type Server interface {
http.Handler
// Get the serving URL for the requests.
// Requests must not be nil. Responses may be nil iff an error is returned.
GetExec(*runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error)
GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error)
GetPortForward(*runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error)
// Start the server.
// addr is the address to serve on (address:port) stayUp indicates whether the server should
// listen until Stop() is called, or automatically stop after all expected connections are
// closed. Calling Get{Exec,Attach,PortForward} increments the expected connection count.
// Function does not return until the server is stopped.
Start(stayUp bool) error
// Stop the server, and terminate any open connections.
Stop() error
}
// The interface to execute the commands and provide the streams.
type Runtime interface {
Exec(containerID string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error
Attach(containerID string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error
PortForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error
}
// Config defines the options used for running the stream server.
type Config struct {
// The host:port address the server will listen on.
Addr string
// The optional base URL for constructing streaming URLs. If empty, the baseURL will be
// constructed from the serve address.
BaseURL *url.URL
// How long to leave idle connections open for.
StreamIdleTimeout time.Duration
// How long to wait for clients to create streams. Only used for SPDY streaming.
StreamCreationTimeout time.Duration
// The streaming protocols the server supports (understands and permits). See
// k8s.io/kubernetes/pkg/kubelet/server/remotecommand/constants.go for available protocols.
// Only used for SPDY streaming.
SupportedProtocols []string
// The config for serving over TLS. If nil, TLS will not be used.
TLSConfig *tls.Config
}
// DefaultConfig provides default values for server Config. The DefaultConfig is partial, so
// some fields like Addr must still be provided.
var DefaultConfig = Config{
StreamIdleTimeout: 4 * time.Hour,
StreamCreationTimeout: remotecommand.DefaultStreamCreationTimeout,
SupportedProtocols: remotecommand.SupportedStreamingProtocols,
}
// TODO(timstclair): Add auth(n/z) interface & handling.
func NewServer(config Config, runtime Runtime) (Server, error) {
s := &server{
config: config,
runtime: &criAdapter{runtime},
}
if s.config.BaseURL == nil {
s.config.BaseURL = &url.URL{
Scheme: "http",
Host: s.config.Addr,
}
if s.config.TLSConfig != nil {
s.config.BaseURL.Scheme = "https"
}
}
ws := &restful.WebService{}
endpoints := []struct {
path string
handler restful.RouteFunction
}{
{"/exec/{containerID}", s.serveExec},
{"/attach/{containerID}", s.serveAttach},
{"/portforward/{podSandboxID}", s.servePortForward},
}
// If serving relative to a base path, set that here.
pathPrefix := path.Dir(s.config.BaseURL.Path)
for _, e := range endpoints {
for _, method := range []string{"GET", "POST"} {
ws.Route(ws.
Method(method).
Path(path.Join(pathPrefix, e.path)).
To(e.handler))
}
}
handler := restful.NewContainer()
handler.Add(ws)
s.handler = handler
return s, nil
}
type server struct {
config Config
runtime *criAdapter
handler http.Handler
}
func (s *server) GetExec(req *runtimeapi.ExecRequest) (*runtimeapi.ExecResponse, error) {
url := s.buildURL("exec", req.GetContainerId(), streamOpts{
stdin: req.GetStdin(),
stdout: true,
stderr: !req.GetTty(), // For TTY connections, both stderr is combined with stdout.
tty: req.GetTty(),
command: req.GetCmd(),
})
return &runtimeapi.ExecResponse{
Url: &url,
}, nil
}
func (s *server) GetAttach(req *runtimeapi.AttachRequest) (*runtimeapi.AttachResponse, error) {
url := s.buildURL("attach", req.GetContainerId(), streamOpts{
stdin: req.GetStdin(),
stdout: true,
stderr: !req.GetTty(), // For TTY connections, both stderr is combined with stdout.
tty: req.GetTty(),
})
return &runtimeapi.AttachResponse{
Url: &url,
}, nil
}
func (s *server) GetPortForward(req *runtimeapi.PortForwardRequest) (*runtimeapi.PortForwardResponse, error) {
url := s.buildURL("portforward", req.GetPodSandboxId(), streamOpts{})
return &runtimeapi.PortForwardResponse{
Url: &url,
}, nil
}
func (s *server) Start(stayUp bool) error {
if !stayUp {
// TODO(timstclair): Implement this.
return errors.New("stayUp=false is not yet implemented")
}
server := &http.Server{
Addr: s.config.Addr,
Handler: s.handler,
TLSConfig: s.config.TLSConfig,
}
if s.config.TLSConfig != nil {
return server.ListenAndServeTLS("", "") // Use certs from TLSConfig.
} else {
return server.ListenAndServe()
}
}
func (s *server) Stop() error {
// TODO(timstclair): Implement this.
return errors.New("not yet implemented")
}
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.handler.ServeHTTP(w, r)
}
type streamOpts struct {
stdin bool
stdout bool
stderr bool
tty bool
command []string
port []int32
}
const (
urlParamStdin = api.ExecStdinParam
urlParamStdout = api.ExecStdoutParam
urlParamStderr = api.ExecStderrParam
urlParamTTY = api.ExecTTYParam
urlParamCommand = api.ExecCommandParamm
)
func (s *server) buildURL(method, id string, opts streamOpts) string {
loc := &url.URL{
Path: path.Join(method, id),
}
query := url.Values{}
if opts.stdin {
query.Add(urlParamStdin, "1")
}
if opts.stdout {
query.Add(urlParamStdout, "1")
}
if opts.stderr {
query.Add(urlParamStderr, "1")
}
if opts.tty {
query.Add(urlParamTTY, "1")
}
for _, c := range opts.command {
query.Add(urlParamCommand, c)
}
loc.RawQuery = query.Encode()
return s.config.BaseURL.ResolveReference(loc).String()
}
func (s *server) serveExec(req *restful.Request, resp *restful.Response) {
containerID := req.PathParameter("containerID")
if containerID == "" {
resp.WriteError(http.StatusBadRequest, errors.New("missing required containerID path parameter"))
return
}
streamOpts, err := remotecommand.NewOptions(req.Request)
if err != nil {
resp.WriteError(http.StatusBadRequest, err)
return
}
cmd := req.Request.URL.Query()[api.ExecCommandParamm]
remotecommand.ServeExec(
resp.ResponseWriter,
req.Request,
s.runtime,
"", // unused: podName
"", // unusued: podUID
containerID,
cmd,
streamOpts,
s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout,
s.config.SupportedProtocols)
}
func (s *server) serveAttach(req *restful.Request, resp *restful.Response) {
containerID := req.PathParameter("containerID")
if containerID == "" {
resp.WriteError(http.StatusBadRequest, errors.New("missing required containerID path parameter"))
return
}
streamOpts, err := remotecommand.NewOptions(req.Request)
if err != nil {
resp.WriteError(http.StatusBadRequest, err)
return
}
remotecommand.ServeAttach(
resp.ResponseWriter,
req.Request,
s.runtime,
"", // unused: podName
"", // unusued: podUID
containerID,
streamOpts,
s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout,
s.config.SupportedProtocols)
}
func (s *server) servePortForward(req *restful.Request, resp *restful.Response) {
podSandboxID := req.PathParameter("podSandboxID")
if podSandboxID == "" {
resp.WriteError(http.StatusBadRequest, errors.New("missing required podSandboxID path parameter"))
return
}
portforward.ServePortForward(
resp.ResponseWriter,
req.Request,
s.runtime,
podSandboxID,
"", // unused: podUID
s.config.StreamIdleTimeout,
s.config.StreamCreationTimeout)
}
// criAdapter wraps the Runtime functions to conform to the remotecommand interfaces.
// The adapter binds the container ID to the container name argument, and the pod sandbox ID to the pod name.
type criAdapter struct {
Runtime
}
var _ remotecommand.Executor = &criAdapter{}
var _ remotecommand.Attacher = &criAdapter{}
var _ portforward.PortForwarder = &criAdapter{}
func (a *criAdapter) ExecInContainer(podName string, podUID types.UID, container string, cmd []string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size, timeout time.Duration) error {
return a.Exec(container, cmd, in, out, err, tty, resize)
}
func (a *criAdapter) AttachContainer(podName string, podUID types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error {
return a.Attach(container, in, out, err, tty, resize)
}
func (a *criAdapter) PortForward(podName string, podUID types.UID, port uint16, stream io.ReadWriteCloser) error {
return a.Runtime.PortForward(podName, int32(port), stream)
}
| {'content_hash': '6ece8589575cb092d164559720f84414', 'timestamp': '', 'source': 'github', 'line_count': 324, 'max_line_length': 207, 'avg_line_length': 28.867283950617285, 'alnum_prop': 0.7270394525820593, 'repo_name': 'luomiao/kops', 'id': 'f1d2d0fa902d64e7d1b9d45f37f073afd7b3b015', 'size': '9922', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'vendor/k8s.io/kubernetes/pkg/kubelet/server/streaming/server.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '2235195'}, {'name': 'HCL', 'bytes': '156037'}, {'name': 'Makefile', 'bytes': '14134'}, {'name': 'Python', 'bytes': '8716'}, {'name': 'Ruby', 'bytes': '1027'}, {'name': 'Shell', 'bytes': '43523'}]} |
export class Point {
constructor(public lat?: number,
public lon?: number) { }
} | {'content_hash': '26b1ad832064975ba45b8ca01f66fab2', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 36, 'avg_line_length': 23.0, 'alnum_prop': 0.6195652173913043, 'repo_name': 'FEMMLille/findYourTrashCan', 'id': '435d6d5041bc1346e5e995545c346c4f12833d60', 'size': '92', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'findyourtrashcan-mobile/src/shared/model/point.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '19389'}, {'name': 'HTML', 'bytes': '45258'}, {'name': 'Java', 'bytes': '92485'}, {'name': 'JavaScript', 'bytes': '2385'}, {'name': 'TypeScript', 'bytes': '159292'}]} |
Ext.define('PP.EnvironmentEditor',{
extend: 'PP.EntityEditorGrid',
alias: 'widget.environmenteditor',
entity: 'service_instance',
startQuery:'*',
hideKeyField:true,
stateful:false,
deleteEnabled: true,
startQuery: "*",
lexicon: PP.lexicon,
store: new Ext.data.Store({
model: "service_instance",
autoLoad: false,
listeners: {
load: function() {
this.filterBy(function(record) {
return (record.get("type") == "environment") ? true: false;
});
}
},
sorters:[ {property: 'name', direction: 'ASC' } ]
}),
rec_template:{
environment_name: PP.config.default_environment,
type: 'environment'
},
listeners:{
destroy: function(){
Ext.StoreManager.get("environment_name_store").load(function() {
this.fireEvent("load");
});
}
},
initComponent: function(){
this.columns=[];
this.columns.push(this.columnConfig('name'));
this.columns[0].header='Name';
this.columns[0].editor.allowBlank=false;
this.columns[0].editor.vtype='alphanum';
this.columns.push(this.columnConfig('note'));
this.columns.push(this.columnConfig('environment_name'));
this.columns[2].header='Parent Environment';
this.columns[2].editor.allowBlank=false;
this.tbar=[{
xtype: 'button',
scope:this,
text: 'Create New Environment',
handler: this.buttonHandler
}];
this.mode='other';
PP.EnvironmentEditor.superclass.initComponent.call(this);
},
deleteRecord: function(id){
if( this.store.getById(id) )
{
var rec=this.store.getById(id);
Ext.Msg.confirm('Confirm','Are you sure you want to delete this record?<br>This cannot be undone',function(btn){
if(btn == 'yes')
{
var rec=this.store.getById(id);
var recname=rec.get('name');
Ext.Msg.show({
msg:'Deleting Env in Puppet Repo<br>(this will take a minute)',
progressText: 'updating...',
width: 200,
wait: true,
waitConfig: {interval: 200}
});
Ext.Ajax.request({
url:'/env/' + recname,
method: 'DELETE',
timeout: 300000,
scope: this,
success: function(){
this.store.remove(rec);
rec.destroy({
success: function(){
Ext.StoreManager.get("environment_name_store").load(function() {
this.fireEvent("load");
});
Ext.Msg.hide();
PP.notify.msg('Deleted','Environment has been deleted.');
},
failure: function(op){
Ext.Msg.alert('Error', 'There was an error deleting the record in the remote store' + "<br>" + op.response.responseText);
}
});
},
failure: function(resp){
Ext.Msg.alert('Error','There was an error when deleting the environment from the puppet repo. Please report this.' + "<br>" + resp.responseText);
}
});
}
},this);
}
},
buttonHandler:function(b){
if(!PP.allowEditing)
{
// return;
}
else
{
var w=new Ext.Window({
title: 'New Environment',
height: 200,
width: 400,
layout: 'border',
modal: true,
plain: true,
closeAction:'destroy',
items:[
{
xtype: 'form',
region: 'center',
bodyStyle:'padding:13px;',
layout: { type: 'vbox'},
fieldDefaults: {
anchor: '100%'
},
items:[
{
xtype: 'hidden',
name: 'type',
value: 'environment'
},
{
xtype: 'textfield',
fieldLabel: 'Name',
name: 'name',
allowBlank: false,
vtype: 'alphanum'
},
{
xtype: 'textfield',
fieldLabel: 'Note',
name: 'note'
},
{
xtype: 'combo',
allowBlank: false,
name: 'environment_name',
store: Ext.StoreManager.get('environment_name_store'),
fieldLabel: 'Parent Environment',
labelWidth: 170,
displayField: 'name',
valueField: 'name',
value: PP.config.default_environment,
emptyText: 'select to filter',
// value:'pic',
listeners:{
'expand': {
scope: this,
fn: function(combo){
combo.store.clearFilter();
}
}
}
}
],
buttons:[
{
text:'Create',
scope: this,
handler:function(b,e){
var env=b.up('form').getForm().getValues();
var p = Ext.ModelManager.create( env ,'service_instance');
Ext.Msg.show({
msg:'Saving Env in Puppet Repo<br>(this will take a minute)',
progressText: 'updating...',
width: 200,
wait: true,
waitConfig: {interval: 200}
});
Ext.Ajax.request({
url: PP.config.env_api_path + env.name,
method: 'PUT',
scope: this,
timeout: 150000,
jsonData: { name: env.name, parent: env.environment_name },
success: function(){
p.save({
success: function(){
PP.notify.msg('Success','Environment has been saved.');
Ext.Msg.hide();
this.store.load();
Ext.StoreManager.get("environment_name_store").load(function() {
this.fireEvent("load");
});
},
failure:function(recs,op,success){
if(!op.success)
{
Ext.Msg.alert("Error",'Server returned ' + op.error.status + ": " + op.error.statusText + "<br>" + op.response.responseText);
}
},
scope: this
});
},
failure: function(resp){
Ext.Msg.alert('Error','There was an error when saving the environment for puppet in repo. Please report this.' + "<br>" + resp.responseText);
}
});
b.up('window').close();
}
},
{
text: 'Cancel',
handler: function(){
this.up('window').close();
}
}
]
}
]
});
w.show();
return;
var p = Ext.ModelManager.create({type:'environment'},this.entity);
if(this.rec_template)
{
PP.log(this.rec_template);
for (i in this.rec_template)
{
if(typeof this.rec_template[i] =='function')
{
p.set(i,this.rec_template[i]());
continue;
}
p.set(i,this.rec_template[i]);
}
}
this.store.insert(0, p);
this.editingPlugin.startEdit(p, this.columns[0]);
}
}
});
| {'content_hash': 'e5bb803072a215e5237f996534145bef', 'timestamp': '', 'source': 'github', 'line_count': 244, 'max_line_length': 153, 'avg_line_length': 26.971311475409838, 'alnum_prop': 0.527427442637897, 'repo_name': 'proofpoint/cmdb-ui', 'id': '1ebf9b8bd449bb05f1bd93d63c4753f4b963e58e', 'size': '7180', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/EnvironmentEditor.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '14983'}, {'name': 'JavaScript', 'bytes': '371594'}]} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome to gum’s documentation! — gum 0 documentation</title>
<link rel="stylesheet" href="_static/default.css" type="text/css" />
<link rel="stylesheet" href="_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: './',
VERSION: '0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="_static/jquery.js"></script>
<script type="text/javascript" src="_static/underscore.js"></script>
<script type="text/javascript" src="_static/doctools.js"></script>
<link rel="top" title="gum 0 documentation" href="#" />
<link rel="next" title="Gum for Python 2.X" href="gum_2_x.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="gum_2_x.html" title="Gum for Python 2.X"
accesskey="N">next</a> |</li>
<li><a href="#">gum 0 documentation</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="welcome-to-gum-s-documentation">
<h1>Welcome to gum’s documentation!<a class="headerlink" href="#welcome-to-gum-s-documentation" title="Permalink to this headline">¶</a></h1>
<p>This is intended primarily as an exercise in setting up and configuring Sphinx, but with the pleasant side effect of producing an API reference of sorts for the <em>Gum</em> module.</p>
<p>Contents:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="gum_2_x.html">Gum for Python 2.X</a></li>
</ul>
</div>
</div>
<div class="section" id="indices-and-tables">
<h1>Indices and tables<a class="headerlink" href="#indices-and-tables" title="Permalink to this headline">¶</a></h1>
<ul class="simple">
<li><a class="reference internal" href="genindex.html"><em>Index</em></a></li>
<li><a class="reference internal" href="py-modindex.html"><em>Module Index</em></a></li>
<li><a class="reference internal" href="search.html"><em>Search Page</em></a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="#">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">Welcome to gum’s documentation!</a></li>
<li><a class="reference internal" href="#indices-and-tables">Indices and tables</a></li>
</ul>
<h4>Next topic</h4>
<p class="topless"><a href="gum_2_x.html"
title="next chapter">Gum for Python 2.X</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="_sources/index.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="gum_2_x.html" title="Gum for Python 2.X"
>next</a> |</li>
<li><a href="#">gum 0 documentation</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2014, Ilia Kurenkov.
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.2.2.
</div>
</body>
</html> | {'content_hash': '1f85de3dfde29cf0de2a6b8701f5dee7', 'timestamp': '', 'source': 'github', 'line_count': 127, 'max_line_length': 188, 'avg_line_length': 37.511811023622045, 'alnum_prop': 0.5910999160369438, 'repo_name': 'Copper-Head/gum', 'id': '65b88c8216eff8380227d928dbebba036eb106de', 'size': '4768', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/_build/html/index.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '16424'}, {'name': 'JavaScript', 'bytes': '54587'}, {'name': 'Perl', 'bytes': '6750'}, {'name': 'Python', 'bytes': '29187'}, {'name': 'Shell', 'bytes': '8659'}, {'name': 'TeX', 'bytes': '72598'}]} |
package com.google.errorprone.refaster;
import com.google.auto.value.AutoValue;
import com.sun.tools.javac.code.Type.ArrayType;
import javax.annotation.Nullable;
/**
* {@link UType} version of {@link ArrayType}, which represents a type {@code T[]} based on the type
* {@code T}.
*
* @author [email protected] (Louis Wasserman)
*/
@AutoValue
abstract class UArrayType extends UType {
public static UArrayType create(UType componentType) {
return new AutoValue_UArrayType(componentType);
}
abstract UType componentType();
@Override
@Nullable
public Choice<Unifier> visitArrayType(ArrayType arrayType, @Nullable Unifier unifier) {
return componentType().unify(arrayType.getComponentType(), unifier);
}
@Override
public ArrayType inline(Inliner inliner) throws CouldNotResolveImportException {
return new ArrayType(componentType().inline(inliner), inliner.symtab().arrayClass);
}
}
| {'content_hash': 'b0e7805a46d29a334a8fbfc550e0da29', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 100, 'avg_line_length': 28.0, 'alnum_prop': 0.7521645021645021, 'repo_name': 'cushon/error-prone', 'id': '1752f0e5143d1d105048b25e3881c4de89ab379f', 'size': '1529', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/google/errorprone/refaster/UArrayType.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '2061'}, {'name': 'Java', 'bytes': '7364383'}, {'name': 'Python', 'bytes': '10499'}, {'name': 'Shell', 'bytes': '1815'}]} |
import _ from 'lodash';
export class InitialReducer {
reduce(json, state) {
let data = _.get(json, 'contact-initial', false);
if (data) {
state.contacts = data;
}
data = _.get(json, 'group-initial', false);
if (data) {
for (let group in data) {
state.groups[group] = new Set(data[group]);
}
}
}
}
| {'content_hash': '8edfb23bc8db2315f7bb63706cd9b876', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 53, 'avg_line_length': 18.68421052631579, 'alnum_prop': 0.5464788732394367, 'repo_name': 'jfranklin9000/urbit', 'id': 'a5b26d772892d6249828c2e862a068248ec495d1', 'size': '355', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'pkg/interface/link/src/js/reducers/initial.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1654339'}, {'name': 'C++', 'bytes': '79020'}, {'name': 'CMake', 'bytes': '4685'}, {'name': 'CSS', 'bytes': '144538'}, {'name': 'Emacs Lisp', 'bytes': '6153'}, {'name': 'HTML', 'bytes': '3566'}, {'name': 'Haskell', 'bytes': '497548'}, {'name': 'JavaScript', 'bytes': '680770'}, {'name': 'Makefile', 'bytes': '3557'}, {'name': 'Nix', 'bytes': '93175'}, {'name': 'Python', 'bytes': '15700'}, {'name': 'Ruby', 'bytes': '34231'}, {'name': 'Shell', 'bytes': '70780'}, {'name': 'Vim script', 'bytes': '15955'}]} |
<?php
/**
* The interface for configurator adapters.
*
* Adapters convert configuration in several formats such as XML, ini and PHP
* file to a PHP array.
*
* @package log4php
* @subpackage configurators
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* @version $Revision$
* @since 2.2
*/
interface LoggerConfigurationAdapter
{
/** Converts the configuration file to PHP format usable by the configurator. */
public function convert($input);
}
| {'content_hash': 'a3d912b5ec49670e3fb7cdbf62e44feb', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 82, 'avg_line_length': 22.772727272727273, 'alnum_prop': 0.716566866267465, 'repo_name': 'jeromechan/brooder', 'id': '6237cddadbe9258a52aa7c844002d9a823b8ae63', 'size': '1325', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'logger/log4php/src/main/php/configurators/LoggerConfigurationAdapter.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '52'}, {'name': 'CSS', 'bytes': '17781'}, {'name': 'HTML', 'bytes': '1893930'}, {'name': 'Java', 'bytes': '356608'}, {'name': 'JavaScript', 'bytes': '88133'}, {'name': 'PHP', 'bytes': '3730013'}, {'name': 'XSLT', 'bytes': '1549'}]} |
namespace Machete.Layouts.Parsers
{
using System.Collections.Generic;
using System.Linq;
public class LayoutParser<TLayout, TSchema> :
IParser<TSchema, TLayout>
where TSchema : Entity
where TLayout : Layout
{
readonly ILayoutFactory<TLayout> _factory;
readonly IParser<TSchema, LayoutMatch<TLayout>>[] _parsers;
public LayoutParser(ILayoutFactory<TLayout> factory, IEnumerable<IParser<TSchema, LayoutMatch<TLayout>>> parsers)
{
_factory = factory;
_parsers = parsers.ToArray();
}
public Result<Cursor<TSchema>, TLayout> Parse(Cursor<TSchema> input)
{
var matches = new List<LayoutMatch<TLayout>>(_parsers.Length);
var next = input;
for (var i = 0; i < _parsers.Length; i++)
{
var result = _parsers[i].Parse(next);
if (result.HasResult == false)
return new Unmatched<Cursor<TSchema>, TLayout>(next);
matches.Add(result.Result);
next = result.Next;
}
var layout = _factory.Create();
for (var i = 0; i < matches.Count; i++)
matches[i].Apply(layout);
return new Success<Cursor<TSchema>, TLayout>(layout, next);
}
}
} | {'content_hash': 'da571cd5362ef833ad96d1e53c95e618', 'timestamp': '', 'source': 'github', 'line_count': 45, 'max_line_length': 121, 'avg_line_length': 30.022222222222222, 'alnum_prop': 0.5588452997779423, 'repo_name': 'phatboyg/Machete', 'id': 'ebff730fa6426c4d9ae5b4d00433530d872bf4b9', 'size': '1353', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/Machete/Layouts/Parsers/LayoutParser.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '284'}, {'name': 'C#', 'bytes': '3394947'}, {'name': 'F#', 'bytes': '2628'}, {'name': 'Smalltalk', 'bytes': '610'}]} |
package org.apache.avro;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.avro.Protocol.Message;
import org.apache.avro.Schema.Parser;
import org.apache.avro.compiler.idl.NameTrackingIdl;
import org.apache.avro.compiler.idl.NameTrackingIdl.NameTrackingMap;
import org.apache.avro.compiler.idl.ParseException;
import org.apache.avro.generic.GenericData.StringType;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.codehaus.jackson.node.TextNode;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
/**
* @author Thomas Feng ([email protected])
*/
public class SchemaProcessor {
public class DependencyComparator implements Comparator<File> {
@Override
public int compare(File file1, File file2) {
Map<String, Boolean> nameStates1 = names.get(file1);
Map<String, Boolean> nameStates2 = names.get(file2);
int result = 0;
for (Entry<String, Boolean> entry : nameStates1.entrySet()) {
Boolean value = nameStates2.get(entry.getKey());
if (!entry.getValue()) {
if (value != null && value) {
if (result == -1) {
throw new RuntimeException("These two files mutually depend on each other: " + file1 + " and " + file2);
} else {
result = 1;
}
}
} else if (entry.getValue()) {
if (value != null && !value) {
if (result == 1) {
throw new RuntimeException("These two files mutually depend on each other: " + file1 + " and " + file2);
} else {
result = -1;
}
}
}
}
return result;
}
}
public static class ParseResult {
private final Map<File, Protocol> protocols;
private final Map<File, Schema> schemas;
private ParseResult(Map<File, Schema> schemas, Map<File, Protocol> protocols) {
this.schemas = schemas;
this.protocols = protocols;
}
public Map<File, Protocol> getProtocols() {
return protocols;
}
public Map<File, Schema> getSchemas() {
return schemas;
}
}
private static final Set<String> PREDEFINED_TYPES = ImmutableSet.<String>builder()
.addAll(Schema.PRIMITIVES.keySet())
.add("array", "enum", "error", "fixed", "map", "record")
.build();
private static final Method PROTOCOL_PARSE_METHOD;
private static String STRING_PROP = "avro.java.string";
static {
try {
PROTOCOL_PARSE_METHOD = Protocol.class.getDeclaredMethod("parse", JsonNode.class);
PROTOCOL_PARSE_METHOD.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException("Unable to get access to Protocol.parse(JsonNode) method", e);
}
}
private final DependencyComparator dependencyComparator = new DependencyComparator();
private final List<File> dependencyOrder = new ArrayList<>();
private List<Schema> extraSchemas = new ArrayList<>();
private final Set<File> idlFiles;
private final Map<File, Map<String, Boolean>> names = new HashMap<>();
private final Set<File> protocolFiles;
private final Set<File> schemaFiles;
private StringType stringType;
public SchemaProcessor(List<File> schemaFiles, List<File> externalSchemas, List<File> protocolFiles,
List<File> idlFiles, StringType stringType, List<String> extraSchemaClasses) throws IOException {
this.schemaFiles = new HashSet<>(schemaFiles);
this.protocolFiles = new HashSet<>(protocolFiles);
this.idlFiles = new HashSet<>(idlFiles);
this.stringType = stringType;
addExtraSchemas(extraSchemaClasses);
parseSchemaFiles(schemaFiles);
parseSchemaFiles(externalSchemas);
parseProtocolFiles(protocolFiles);
parseIdlFiles(idlFiles);
computeDependencyOrder();
}
public Set<String> definedNames(File file) {
Map<String, Boolean> nameStates = names.get(file);
if (nameStates == null) {
return Collections.emptySet();
} else {
return nameStates.entrySet().stream()
.filter(entry -> entry.getValue())
.map(entry -> entry.getKey())
.collect(Collectors.toSet());
}
}
public ParseResult parse() throws IOException {
Map<File, Schema> schemas = new HashMap<>(schemaFiles.size());
Map<File, Protocol> protocols = new HashMap<>(protocolFiles.size() + idlFiles.size());
Map<String, Schema> types = new HashMap<>();
for (File file : dependencyOrder) {
if (protocolFiles.contains(file)) {
Protocol protocol = new Protocol(null, null);
protocol.setTypes(types.values());
JsonParser jsonParser = Schema.FACTORY.createJsonParser(file);
JsonNode json = Schema.MAPPER.readTree(jsonParser);
processImports(json, null, types);
try {
PROTOCOL_PARSE_METHOD.invoke(protocol, json);
} catch (InvocationTargetException e) {
throw new IOException("Unable to parse protocol file " + file, e.getTargetException());
} catch (Exception e) {
throw new RuntimeException("Unable to get access to Protocol.parse(JsonNode) method", e);
}
addStringProperties(protocol);
protocols.put(file, protocol);
for (Schema type : protocol.getTypes()) {
collectSchemas(type, types);
}
} else if (idlFiles.contains(file)) {
NameTrackingIdl idl = new NameTrackingIdl(file);
NameTrackingMap names = idl.getNames();
names.putAll(types);
addExtraSchemasToIdl(idl);
Protocol protocol;
try {
protocol = idl.CompilationUnit();
} catch (ParseException e) {
throw new IOException("Unable to parse IDL file " + file, e);
} finally {
idl.close();
}
addStringProperties(protocol);
protocols.put(file, protocol);
for (Schema type : protocol.getTypes()) {
collectSchemas(type, types);
}
} else {
JsonParser jsonParser = Schema.FACTORY.createJsonParser(file);
JsonNode json = Schema.MAPPER.readTree(jsonParser);
processImports(json, null, types);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jsonGenerator = Schema.FACTORY.createJsonGenerator(outputStream);
Schema.MAPPER.writeTree(jsonGenerator, json);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
Parser parser = new Parser();
parser.addTypes(types);
Schema schema = parser.parse(inputStream);
addStringProperties(schema);
collectSchemas(schema, types);
if (schemaFiles.contains(file)) {
schemas.put(file, schema);
}
}
}
return new ParseResult(schemas, protocols);
}
private void addExtraSchemas(List<String> extraSchemaClasses) throws IOException {
ClassLoader classLoader = SchemaProcessor.class.getClassLoader();
for (String extraSchemaClass : extraSchemaClasses) {
try {
Class<?> clazz = classLoader.loadClass(extraSchemaClass);
Field field = clazz.getField("SCHEMA$");
Schema schema = (Schema) field.get(null);
extraSchemas.add(schema);
} catch (Exception e) {
throw new IOException("Unable to load extra schema class " + extraSchemaClass);
}
}
}
private void addExtraSchemasToIdl(NameTrackingIdl idl) {
NameTrackingMap nameMap = idl.getNames();
for (Schema extraSchema : extraSchemas) {
nameMap.put(extraSchema.getFullName(), extraSchema);
}
}
private void addStringProperties(Protocol protocol) {
for (Schema type : protocol.getTypes()) {
addStringProperties(type);
}
for (Message message : protocol.getMessages().values()) {
addStringProperties(message.getRequest());
addStringProperties(message.getResponse());
addStringProperties(message.getErrors());
}
}
private void addStringProperties(Schema schema) {
switch (schema.getType()) {
case STRING:
if (schema.getProp(STRING_PROP) == null) {
schema.addProp(STRING_PROP, stringType.name());
}
break;
case RECORD:
schema.getFields().forEach(field -> addStringProperties(field.schema()));
break;
case MAP:
addStringProperties(schema.getValueType());
break;
case ARRAY:
addStringProperties(schema.getElementType());
break;
case UNION:
schema.getTypes().forEach(type -> addStringProperties(type));
break;
default:
}
}
private void collectNames(JsonNode schema, String namespace, Map<String, Boolean> nameStates) {
if (schema.isTextual()) {
recordName(nameStates, schema.getTextValue(), namespace, false);
} else if (schema.isObject()) {
String type = getText(schema, "type");
if ("record".equals(type) || "error".equals(type) || "enum".equals(type) || "fixed".equals(type)) {
String newNamespace = getText(schema, "namespace");
if (newNamespace != null) {
namespace = newNamespace;
}
String name = getText(schema, "name");
int lastDotIndex = name.lastIndexOf('.');
if (lastDotIndex >= 0) {
namespace = name.substring(0, lastDotIndex);
}
ArrayNode imports = (ArrayNode) schema.get("imports");
if (imports != null) {
for (Iterator<JsonNode> importNodes = imports.getElements(); importNodes.hasNext();) {
recordName(nameStates, importNodes.next().getTextValue(), namespace, false);
}
}
Boolean defined = null;
if ("record".equals(type) || "error".equals(type)) {
JsonNode fieldsNode = schema.get("fields");
defined = fieldsNode != null;
if (fieldsNode != null) {
for (JsonNode field : fieldsNode) {
JsonNode fieldTypeNode = field.get("type");
collectNames(fieldTypeNode, namespace, nameStates);
}
}
} else if ("enum".equals(type)) {
defined = schema.get("symbols") != null;
} else if ("fixed".equals(type)) {
defined = true;
}
recordName(nameStates, name, namespace, defined);
} else if ("array".equals(type)) {
collectNames(schema.get("items"), namespace, nameStates);
} else if ("map".equals(type)) {
collectNames(schema.get("values"), namespace, nameStates);
}
} else if (schema.isArray()) {
for (JsonNode typeNode : schema) {
collectNames(typeNode, namespace, nameStates);
}
}
}
private void collectNamesForProtocol(JsonNode protocol, Map<String, Boolean> nameStates) {
String namespace = getText(protocol, "namespace");
ArrayNode types = (ArrayNode) protocol.get("types");
if (types != null) {
for (JsonNode type : types) {
collectNames(type, namespace, nameStates);
}
}
JsonNode messages = protocol.get("messages");
if (messages != null) {
for (Iterator<String> i = messages.getFieldNames(); i.hasNext();) {
JsonNode message = messages.get(i.next());
JsonNode request = message.get("request");
for (Iterator<JsonNode> iterator = request.getElements(); iterator.hasNext();) {
JsonNode type = iterator.next().get("type");
collectNames(type, namespace, nameStates);
}
JsonNode response = message.get("response");
collectNames(response, namespace, nameStates);
ArrayNode errors = (ArrayNode) message.get("errors");
if (errors != null) {
for (JsonNode error : errors) {
collectNames(error, namespace, nameStates);
}
}
}
}
}
private void collectSchemas(Schema schema, Map<String, Schema> schemas) {
switch (schema.getType()) {
case RECORD:
schemas.put(schema.getFullName(), schema);
schema.getFields().forEach(field -> collectSchemas(field.schema(), schemas));
break;
case MAP:
collectSchemas(schema.getValueType(), schemas);
break;
case ARRAY:
collectSchemas(schema.getElementType(), schemas);
break;
case UNION:
schema.getTypes().forEach(type -> collectSchemas(type, schemas));
break;
case ENUM:
case FIXED:
schemas.put(schema.getFullName(), schema);
break;
default:
}
}
private void computeDependencyOrder() {
dependencyOrder.clear();
HashMultimap<File, File> dependencies = HashMultimap.create();
Set<File> files = new HashSet<>(names.keySet());
for (File file1 : files) {
for (File file2 : files) {
if (!file1.equals(file2)) {
if (dependencyComparator.compare(file1, file2) > 0) {
dependencies.put(file1, file2); // file1 depends on file2.
}
}
}
}
while (!files.isEmpty()) {
File nextFile = null;
for (File file : files) {
if (dependencies.get(file).isEmpty()) {
nextFile = file;
break;
}
}
if (nextFile == null) {
throw new RuntimeException("Unable to sort schema files topologically; "
+ "remaining files that contain dependency cycle(s) are these: "
+ dependencies.keySet());
}
files.remove(nextFile);
dependencies.removeAll(nextFile);
for (Iterator<Entry<File, File>> iterator = dependencies.entries().iterator(); iterator.hasNext();) {
if (nextFile.equals(iterator.next().getValue())) {
iterator.remove();
}
}
dependencyOrder.add(nextFile);
}
}
private String getFullName(String name, String namespace) {
if (name.indexOf('.') >= 0 || namespace == null) {
return name;
} else {
return namespace + "." + name;
}
}
private String getText(JsonNode node, String key) {
JsonNode child = node.get(key);
return child != null ? child.getTextValue() : null;
}
private void parseIdlFiles(List<File> idlFiles) throws IOException {
for (File idlFile : idlFiles) {
NameTrackingIdl idl = new NameTrackingIdl(idlFile);
addExtraSchemasToIdl(idl);
try {
idl.CompilationUnit();
} catch (ParseException e) {
throw new IOException("Unable to parse IDL file " + idlFile, e);
} finally {
idl.close();
}
NameTrackingMap names = idl.getNames();
Set<String> undefinedNames = names.getUndefinedNames();
Map<String, Boolean> nameStates = new HashMap<>(names.size() + undefinedNames.size());
for (String name : names.keySet()) {
nameStates.put(name, true);
}
for (String undefinedName : undefinedNames) {
nameStates.put(undefinedName, false);
}
this.names.put(idlFile, nameStates);
}
}
private void parseProtocolFiles(List<File> protocolFiles) throws IOException {
for (File protocolFile : protocolFiles) {
JsonParser jsonParser = Schema.FACTORY.createJsonParser(protocolFile);
JsonNode schema = Schema.MAPPER.readTree(jsonParser);
Map<String, Boolean> nameStates = new HashMap<>();
collectNamesForProtocol(schema, nameStates);
names.put(protocolFile, nameStates);
}
}
private void parseSchemaFiles(List<File> schemaFiles) throws IOException {
for (File schemaFile : schemaFiles) {
JsonParser jsonParser = Schema.FACTORY.createJsonParser(schemaFile);
JsonNode schema = Schema.MAPPER.readTree(jsonParser);
Map<String, Boolean> nameStates = new HashMap<>();
collectNames(schema, null, nameStates);
names.put(schemaFile, nameStates);
}
}
private void processImports(JsonNode schema, String namespace, Map<String, Schema> types) throws IOException {
if (schema.isObject()) {
String type = getText(schema, "type");
if ("record".equals(type) || "error".equals(type)) {
String newNamespace = getText(schema, "namespace");
if (newNamespace != null) {
namespace = newNamespace;
}
String name = getText(schema, "name");
int lastDotIndex = name.lastIndexOf('.');
if (lastDotIndex >= 0) {
namespace = name.substring(0, lastDotIndex);
}
String fullName = getFullName(name, namespace);
JsonNode imports = schema.get("imports");
if (imports != null) {
for (JsonNode importNode : imports) {
String importedSchemaName = getFullName(importNode.getTextValue(), namespace);
Schema importedSchema = types.get(importedSchemaName);
if (importedSchema == null) {
throw new IOException("Unable to load imported schema " + importedSchemaName);
}
JsonNode importedSchemaNode = schemaToJson(importedSchema);
removeTypeDefinitions(null, importedSchemaNode);
String importedSchemaType = getText(importedSchemaNode, "type");
if ("record".equals(importedSchemaType) || "error".equals(importedSchemaType)) {
ArrayNode fieldsNode = (ArrayNode) schema.get("fields");
if (fieldsNode == null) {
fieldsNode = Schema.MAPPER.createArrayNode();
((ObjectNode) schema).put("fields", fieldsNode);
}
JsonNode importedFields = importedSchemaNode.get("fields");
if (importedFields != null) {
int i = 0;
for (JsonNode importedField : importedFields) {
fieldsNode.insert(i++, importedField);
}
}
} else {
throw new IOException("Cannot import schema " + importedSchemaName + " of type " + importedSchemaType
+ " into " + fullName + " of type " + type);
}
}
}
JsonNode fieldsNode = schema.get("fields");
if (fieldsNode != null) {
for (JsonNode field : fieldsNode) {
JsonNode fieldTypeNode = field.get("type");
processImports(fieldTypeNode, namespace, types);
}
}
} else if ("array".equals(type)) {
processImports(schema.get("items"), namespace, types);
} else if ("map".equals(type)) {
processImports(schema.get("values"), namespace, types);
}
} else if (schema.isArray()) {
for (JsonNode typeNode : schema) {
processImports(typeNode, namespace, types);
}
}
}
private void recordName(Map<String, Boolean> nameStates, String name, String namespace, Boolean defined) {
if (defined != null) {
if (!PREDEFINED_TYPES.contains(name)) {
String fullName = getFullName(name, namespace);
Boolean value = nameStates.get(fullName);
if (value == null || !value && defined) {
nameStates.put(fullName, defined);
}
}
}
}
private void removeTypeDefinitions(String namespace, JsonNode schema) {
if (schema == null) {
return;
}
String type = getText(schema, "type");
if ("record".equals(type) || "error".equals(type)) {
TextNode namespaceNode = (TextNode) schema.get("namespace");
String newNamespace = namespaceNode == null ? namespace : namespaceNode.getTextValue();
ArrayNode fieldsNode = (ArrayNode) schema.get("fields");
if (fieldsNode != null) {
for (JsonNode fieldNode : fieldsNode) {
JsonNode fieldTypeNode = fieldNode.get("type");
if (fieldTypeNode.isObject()) {
String fieldType = getText(fieldTypeNode, "name");
if (fieldType != null) {
((ObjectNode) fieldNode).put("type", new TextNode(getFullName(fieldType, newNamespace)));
continue;
}
}
removeTypeDefinitions(newNamespace, fieldTypeNode);
}
}
} else if ("array".equals(type)) {
JsonNode itemsNode = schema.get("items");
if (itemsNode != null) {
String itemType = getText(itemsNode, "name");
if (itemType != null) {
((ObjectNode) schema).put("items", new TextNode(itemType));
return;
}
}
removeTypeDefinitions(namespace, itemsNode);
} else if ("map".equals(type)) {
JsonNode valuesNode = schema.get("values");
if (valuesNode != null) {
String valueType = getText(valuesNode, "name");
if (valueType != null) {
((ObjectNode) schema).put("values", new TextNode(valueType));
return;
}
}
removeTypeDefinitions(namespace, valuesNode);
}
}
private JsonNode schemaToJson(Schema schema) throws IOException {
JsonParser jsonParser = Schema.FACTORY.createJsonParser(schema.toString());
return jsonParser.readValueAsTree();
}
}
| {'content_hash': '5e1b042459806785b7471e24927ed9b0', 'timestamp': '', 'source': 'github', 'line_count': 616, 'max_line_length': 118, 'avg_line_length': 34.80681818181818, 'alnum_prop': 0.6288885779581176, 'repo_name': 'tfeng/sbt-plugins', 'id': 'ac152aef8a104cf17f7732a75511808e1c5fa8ee', 'size': '22280', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'avro/src/main/java/org/apache/avro/SchemaProcessor.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '34697'}, {'name': 'Scala', 'bytes': '8900'}]} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Bjd;
using Bjd.mail;
using Bjd.net;
using Bjd.option;
using BjdTest.test;
using NUnit.Framework;
using SmtpServer;
namespace SmtpServerTest {
class PopClientTest : ILife{
private TestServer _testServer;
// ログイン失敗などで、しばらくサーバが使用できないため、TESTごとサーバを立ち上げて試験する必要がある
[SetUp]
public void SetUp() {
//MailBoxは、Pop3ServerTest.iniの中で「c:\tmp2\bjd5\SmtpServerTest\mailbox」に設定されている
//また、上記のMaloBoxには、user1=0件 user2=2件 のメールが着信している
_testServer = new TestServer(TestServerType.Pop, "SmtpServerTest\\Fetch","PopClientTest.ini");
//usrr2のメールボックスへの2通のメールをセット
_testServer.SetMail("user2", "00635026511425888292");
_testServer.SetMail("user2", "00635026511765086924");
}
[TearDown]
public void TearDown() {
_testServer.Dispose();
}
private PopClient CreatePopClient(InetKind inetKind){
if (inetKind == InetKind.V4){
return new PopClient(new Kernel(), new Ip(IpKind.V4Localhost), 9110, 3, this);
}
return new PopClient(new Kernel(),new Ip(IpKind.V6Localhost), 9110, 3, this);
}
[TestCase(InetKind.V4,"127.0.0.1",9112)]
[TestCase(InetKind.V6, "::1", 9112)]
public void 接続失敗_ポート間違い(InetKind inetKind,String addr,int port) {
//setUp
var sut = new PopClient(new Kernel(),new Ip(addr), port, 3, this);
var expected = false;
//exercise
var actual = sut.Connect();
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(sut.GetLastError(), Is.EqualTo("Faild in PopClient Connect()"));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4,"127.0.0.2")]
[TestCase(InetKind.V6, "::2")]
public void 接続失敗_アドレス間違い(InetKind inetKind, String addr) {
//setUp
var sut = new PopClient(new Kernel(),new Ip(addr), 9110, 3, this);
var expected = false;
//exercise
var actual = sut.Connect();
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(sut.GetLastError(), Is.EqualTo("Faild in PopClient Connect()"));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void ログイン成功(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = true;
//exercise
sut.Connect();
var actual = sut.Login("user1", "user1");
//verify
Assert.That(actual, Is.EqualTo(expected));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void ログイン失敗_パスワードの間違い(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = false;
//exercise
sut.Connect();
var actual = sut.Login("user1","xxx");
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(sut.GetLastError(), Is.EqualTo("Timeout in PopClient RecvStatus()"));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void user1のUidl取得(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = true;
//exercise
sut.Connect();
sut.Login("user1", "user1");
var lines = new List<string>();
var actual = sut.Uidl(lines);
//verify
Assert.That(actual,Is.EqualTo(expected));
Assert.That(lines.Count,Is.EqualTo(0));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void user2のUidl取得(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = true;
//exercise
sut.Connect();
sut.Login("user2", "user2");
var lines = new List<string>();
var actual = sut.Uidl(lines);
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(lines[0], Is.EqualTo("1 bjd.00635026511425808252.000"));
Assert.That(lines[1], Is.EqualTo("2 bjd.00635026511765066907.001"));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void RETRによるメール取得(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = true;
//exercise
sut.Connect();
sut.Login("user2", "user2");
var mail = new Mail();
var actual = sut.Retr(0,mail);
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(mail.GetBytes().Length, Is.EqualTo(308));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void RETRによるメール取得_失敗(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = false;
//exercise
sut.Connect();
sut.Login("user1", "user1");
var mail = new Mail();
var actual = sut.Retr(0, mail); //user1は滞留が0通なので、存在しないメールをリクエストしている
//verify
Assert.That(actual, Is.EqualTo(expected));
Assert.That(sut.GetLastError(), Is.EqualTo("Not Found +OK in PopClient RecvStatus()"));
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void DELEによるメール削除(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
//var expected = true;
//exercise
sut.Connect();
sut.Login("user2", "user2");
//verify
sut.Dele(0);//1通削除
Assert.That(CountMail("user2"), Is.EqualTo(2));//QUIT前は2通
sut.Quit();
Assert.That(CountMail("user2"), Is.EqualTo(1));//QUIT後は1通
//tearDown
sut.Dispose();
}
[TestCase(InetKind.V4)]
[TestCase(InetKind.V6)]
public void DELEによるメール削除_失敗(InetKind inetKind) {
//setUp
var sut = CreatePopClient(inetKind);
var expected = false;
//exercise
sut.Connect();
sut.Login("user1", "user1");
//verify
var actual = sut.Dele(0);
Assert.That(actual,Is.EqualTo(expected));
Assert.That(sut.GetLastError(), Is.EqualTo("Not Found +OK in PopClient RecvStatus()"));
//tearDown
sut.Quit();
sut.Dispose();
}
//メール通数の確認
int CountMail(String user){
//メールボックス内に蓄積されたファイル数を検証する
var path = String.Format("c:\\tmp2\\bjd5\\SmtpServerTest\\mailbox\\{0}",user);
var di = new DirectoryInfo(path);
//DF_*がn個存在する
var files = di.GetFiles("DF_*");
return files.Count();
}
public bool IsLife() {
return true;
}
}
}
| {'content_hash': '0d5bfb8a0fef35ff4757174d255d2e1d', 'timestamp': '', 'source': 'github', 'line_count': 271, 'max_line_length': 106, 'avg_line_length': 29.44649446494465, 'alnum_prop': 0.5070175438596491, 'repo_name': 'furuya02/bjd5', 'id': '1a9ec30e70d20f88a2e31a36c49c70ce19689a57', 'size': '8514', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SmtpServerTest/Fetch/PopClientTest.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '2566513'}, {'name': 'CSS', 'bytes': '2112'}, {'name': 'HTML', 'bytes': '2063'}, {'name': 'JavaScript', 'bytes': '2315'}, {'name': 'PHP', 'bytes': '376'}, {'name': 'Perl', 'bytes': '538'}, {'name': 'XSLT', 'bytes': '21839'}]} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeRunConfigurationManager" shouldGenerate="true" shouldDeleteObsolete="true">
<generated>
<config projectName="LongestStringChain" targetName="LongestStringChain" />
</generated>
</component>
<component name="CMakeSettings">
<configurations>
<configuration PROFILE_NAME="Debug" CONFIG_NAME="Debug" />
</configurations>
</component>
<component name="ChangeListManager">
<list default="true" id="5d0dbae2-9c43-4c3c-8afa-dba7978297ac" name="Default Changelist" comment="">
<change afterPath="$PROJECT_DIR$/../FractionToRecurringDecimal/.idea/vcs.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../TimeBasedKey-ValueStore/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/../TimeBasedKey-ValueStore/.idea/workspace.xml" afterDir="false" />
</list>
<ignored path="$PROJECT_DIR$/cmake-build-debug/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="CMakeBuildProfile:Debug" />
<component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../../.." />
</component>
<component name="IdeDocumentHistory">
<option name="CHANGED_PATHS">
<list>
<option value="$PROJECT_DIR$/main.cpp" />
</list>
</option>
</component>
<component name="ProjectFrameBounds">
<option name="y" value="23" />
<option name="width" value="1680" />
<option name="height" value="948" />
</component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="1" id="Add" />
</component>
<component name="ProjectView">
<navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" />
</navigator>
<panes>
<pane id="ProjectPane" />
<pane id="Scope" />
</panes>
</component>
<component name="PropertiesComponent">
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="nodejs_interpreter_path.stuck_in_default_project" value="undefined stuck path" />
<property name="nodejs_npm_path_reset_for_default_project" value="true" />
</component>
<component name="RunDashboard">
<option name="ruleStates">
<list>
<RuleState>
<option name="name" value="ConfigurationTypeDashboardGroupingRule" />
</RuleState>
<RuleState>
<option name="name" value="StatusDashboardGroupingRule" />
</RuleState>
</list>
</option>
</component>
<component name="RunManager">
<configuration name="LongestStringChain" type="CMakeRunConfiguration" factoryName="Application" PASS_PARENT_ENVS_2="true" PROJECT_NAME="LongestStringChain" TARGET_NAME="LongestStringChain" CONFIG_NAME="Debug" RUN_TARGET_PROJECT_NAME="LongestStringChain" RUN_TARGET_NAME="LongestStringChain">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
</component>
<component name="SvnConfiguration">
<configuration />
</component>
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="5d0dbae2-9c43-4c3c-8afa-dba7978297ac" name="Default Changelist" comment="" />
<created>1583701742086</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1583701742086</updated>
<workItem from="1583701743254" duration="6170000" />
<workItem from="1584155036889" duration="498000" />
</task>
<servers />
</component>
<component name="TimeTrackingManager">
<option name="totallyTimeSpent" value="6668000" />
</component>
<component name="ToolWindowManager">
<frame x="0" y="23" width="1680" height="948" extended-state="0" />
<layout>
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.25274727" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info id="Favorites" order="2" side_tool="true" />
<window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" />
<window_info active="true" anchor="bottom" id="Run" order="2" visible="true" weight="0.32943925" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
<window_info anchor="bottom" id="TODO" order="6" />
<window_info anchor="bottom" id="Database Changes" order="7" />
<window_info anchor="bottom" id="Messages" order="8" weight="0.32943925" />
<window_info anchor="bottom" id="Terminal" order="9" />
<window_info anchor="bottom" id="Event Log" order="10" side_tool="true" />
<window_info anchor="bottom" id="Version Control" order="11" />
<window_info anchor="bottom" id="CMake" order="12" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
<window_info anchor="right" id="Database" order="3" />
</layout>
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="1" />
</component>
<component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/CMakeLists.txt">
<provider selected="true" editor-type-id="text-editor" />
</entry>
<entry file="file://$PROJECT_DIR$/main.cpp">
<provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="779">
<caret line="292" column="1" selection-start-line="292" selection-start-column="1" selection-end-line="292" selection-end-column="1" />
<folding>
<element signature="e#0#20#0" expanded="true" />
</folding>
</state>
</provider>
</entry>
</component>
</project> | {'content_hash': 'b1e88384636f8361010a63571fcf6671', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 295, 'avg_line_length': 46.99290780141844, 'alnum_prop': 0.6602776939329913, 'repo_name': 'busebd12/InterviewPreparation', 'id': 'fd019940ac1ba24e7ab77bec6389dcb9614245eb', 'size': '6626', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'LeetCode/C++/General/Medium/LongestStringChain/.idea/workspace.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '9011022'}, {'name': 'C++', 'bytes': '14785379'}, {'name': 'CMake', 'bytes': '10099860'}, {'name': 'Java', 'bytes': '54365'}, {'name': 'Makefile', 'bytes': '5154401'}, {'name': 'TeX', 'bytes': '41241'}]} |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.apache.directory.server.dhcp.options;
import com.google.common.primitives.Bytes;
import java.util.Arrays;
/**
*
* @author shevek
*/
public abstract class NulTerminatedStringOption extends StringOption {
@Override
protected byte[] getStringData() {
byte[] data = super.getStringData();
int length = Bytes.indexOf(data, (byte) 0);
if (length >= 0)
return Arrays.copyOf(data, length);
return data;
}
@Override
protected void setStringData(byte[] data) {
super.setStringData(Arrays.copyOf(data, data.length + 1));
}
}
| {'content_hash': '772305b7b3ee434d72d10dcaf63b3b3b', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 79, 'avg_line_length': 26.466666666666665, 'alnum_prop': 0.672544080604534, 'repo_name': 'shevek/dhcp4j', 'id': 'c44aa5c33414afc022fefb26478952d1224c8200', 'size': '794', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'dhcp-protocol/src/main/java/org/apache/directory/server/dhcp/options/NulTerminatedStringOption.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'HTML', 'bytes': '105'}, {'name': 'Java', 'bytes': '536616'}]} |
<section id="main-content">
<my-pages-header sectionTitle="Edit Page" [isIndex]=true></my-pages-header>
<section class="wrapper site-min-height">
<div class="row">
<div class="col-lg-12">
<my-alerts #alerts></my-alerts>
<div id="loaderAnimation" [class.loading]="loading == true">Loading...</div>
<div class="page-edit-wrapper" *ngIf="page">
<form [formGroup]="form" (ngSubmit)="submit()">
<div id="page-edit-body" class="col-lg-9 content-panel">
<div class="form-group row">
<label class="control-label col-md-12">Page Title <sup>*</sup></label>
<div class="col-md-12">
<input class="form-control" formControlName="title" placeholder="Title"/>
<div [hidden]="form.controls.title.valid" class="validation-error bg-danger">A page name is required</div>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Page url <sup>*</sup></label>
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon">https://www.salocreative.co.uk/</span>
<input class="form-control" formControlName="slug" placeholder="Page url"/>
</div>
<div [hidden]="form.controls.slug.valid" class="validation-error bg-danger">A valid slug is required. e.g. my-page-url</div>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Content</label>
<div class="col-md-12">
<froala [froalaOptions]="froalaOptions" [froalaData]="text" (model)="onFroalaModelChanged($event)"></froala>
<textarea class="form-control wysiwyg-replaced" formControlName="content" placeholder="Page content" rows="8">
{{ page.content }}
</textarea>
</div>
</div>
<div class="row divider-header bg-theme">
<div class="col-lg-12">
<h3><i class="fa fa-angle-right"></i> SEO Details</h3>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">SEO Title</label>
<div class="col-md-12">
<input class="form-control" formControlName="seo_title" placeholder="SEO Title" />
<div [hidden]="form.controls.seo_title.valid" class="validation-error bg-danger">SEO titles should be no more than 60 characters.</div>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">SEO Description</label>
<div class="col-md-12">
<textarea class="form-control" formControlName="seo_description" placeholder="SEO Meta Description" rows="2"></textarea>
<div [hidden]="form.controls.seo_description.valid" class="validation-error bg-danger">Meta descriptions should be no more than 160 characters.</div>
</div>
</div>
</div>
<div id="page-edit-sidebar" class="col-lg-3 content-panel">
<h4>Page attributes</h4>
<div class="checkbox">
<label>
<input type="checkbox" formControlName="online"> Online
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" formControlName="inNav"> Show in navigation
</label>
</div>
<div class="form-group row top-item-in-sidebar">
<label class="control-label col-md-12">Parent page</label>
<div class="col-md-12">
<select class="form-control" formControlName="parent_id">
<option value="0">-- No parent --</option>
<option *ngFor="let parent of pagesFlatTree" [value]="parent.id">
<span *ngIf="parent.real_depth == 1">-</span>
<span *ngIf="parent.real_depth == 2">--</span>
<span *ngIf="parent.real_depth == 3">---</span>
<span *ngIf="parent.real_depth == 4">----</span>
{{ parent.title }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-12">Page template</label>
<div class="col-md-12">
<select class="form-control" formControlName="template">
<option value="1">Default template</option>
</select>
</div>
</div>
<button class="btn btn-theme03 btn-block" type="submit" [disabled]="!form.valid"><i class="fa fa-save"></i> Save changes</button>
</div>
</form>
</div>
</div>
</div>
</section>
</section>
| {'content_hash': 'a5731448d0338402013cd2bbb13895da', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 185, 'avg_line_length': 66.5, 'alnum_prop': 0.3956390977443609, 'repo_name': 'SaloCreative/salo-cms', 'id': '12d66104f10dcde8beeb376a226bb7ebe122dcb5', 'size': '6650', 'binary': False, 'copies': '1', 'ref': 'refs/heads/develop', 'path': 'src/app/pages/edit/pages.edit.component.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ApacheConf', 'bytes': '164'}, {'name': 'CSS', 'bytes': '282504'}, {'name': 'HTML', 'bytes': '146320'}, {'name': 'JavaScript', 'bytes': '13507'}, {'name': 'TypeScript', 'bytes': '204775'}]} |
var binding = require('binding')
.Binding.create('enterprise.platformKeysInternal')
.generate();
exports.$set('getTokens', binding.getTokens);
exports.$set('generateKey', binding.generateKey);
exports.$set('sign', binding.sign);
| {'content_hash': '4d1f495a77c554f3bb59fbc5023eee4a', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 68, 'avg_line_length': 38.0, 'alnum_prop': 0.6541353383458647, 'repo_name': 'was4444/chromium.src', 'id': 'bea9e96b26701e481f54dd24fc64aa7c9e3adec8', 'size': '432', 'binary': False, 'copies': '11', 'ref': 'refs/heads/nw15', 'path': 'chrome/renderer/resources/extensions/enterprise_platform_keys/internal_api.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []} |
package pl.edu.agh.ztis.server.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
/**
* Created by Jakub Sloniec on 10.03.2016.
*/
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* pl.edu.agh.ztis.server.controller..*.*(..))")
public void restControlPointcut() {
}
@Pointcut("execution(* pl.edu.agh.ztis.server.service..*.*(..))")
public void sevicePointcut() {
}
@Pointcut("restControlPointcut() || sevicePointcut()")
public void combinedPointcut() {
}
@Around("combinedPointcut()")
public Object logMethod(ProceedingJoinPoint joinPoint) throws Throwable {
final Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass().getName());
Object retVal;
try {
StringBuffer startMessageStringBuffer = new StringBuffer();
startMessageStringBuffer.append("Start method ");
startMessageStringBuffer.append(joinPoint.getSignature().getName());
startMessageStringBuffer.append("(");
// Object[] args = joinPoint.getArgs();
// for (Object arg : args) {
// startMessageStringBuffer.append(arg).append(",");
// }
// if (args.length > 0) {
// startMessageStringBuffer.deleteCharAt(startMessageStringBuffer.length() - 1);
// }
startMessageStringBuffer.append(")");
logger.info(startMessageStringBuffer.toString());
StopWatch stopWatch = new StopWatch();
stopWatch.start();
retVal = joinPoint.proceed();
stopWatch.stop();
StringBuffer endMessageStringBuffer = new StringBuffer();
endMessageStringBuffer.append("Finish method ");
endMessageStringBuffer.append(joinPoint.getSignature().getName());
endMessageStringBuffer.append("(..); execution time: ");
endMessageStringBuffer.append(stopWatch.getTotalTimeMillis());
endMessageStringBuffer.append(" ms; ");
// if (retVal != null) {
// endMessageStringBuffer.append("returning: ");
// endMessageStringBuffer.append(retVal.toString());
// endMessageStringBuffer.append(";");
// }
logger.info(endMessageStringBuffer.toString());
} catch (Throwable ex) {
StringBuffer errorMessageStringBuffer = new StringBuffer();
// Create error message
logger.error(errorMessageStringBuffer.toString(), ex);
throw ex;
}
return retVal;
}
}
| {'content_hash': 'fbcdeeb7d04bd7b42734ef24024e3493', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 92, 'avg_line_length': 28.522727272727273, 'alnum_prop': 0.7282868525896414, 'repo_name': 'JakubSloniec/ztis', 'id': 'ee96dd8c86d6569099e65dd40edecfcceda1fff2', 'size': '2510', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/pl/edu/agh/ztis/server/aspect/LoggingAspect.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '68648'}]} |
<?xml version='1.0' encoding='utf-8' ?>
<!DOCTYPE section PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
<!ENTITY % BOOK_ENTITIES SYSTEM "cloudstack.ent">
%BOOK_ENTITIES;
]>
<!-- 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.
-->
<section id="about-zones">
<title>About Zones</title>
<para>A zone is the second largest organizational unit within a &PRODUCT; deployment. A zone
typically corresponds to a single datacenter, although it is permissible to have multiple
zones in a datacenter. The benefit of organizing infrastructure into zones is to provide
physical isolation and redundancy. For example, each zone can have its own power supply and
network uplink, and the zones can be widely separated geographically (though this is not
required).</para>
<para>A zone consists of:</para>
<itemizedlist>
<listitem><para>One or more pods. Each pod contains one or more clusters of hosts and one or more primary storage servers.</para></listitem>
<listitem><para>A zone may contain one or more primary storage servers, which are shared by all the pods in the zone.</para></listitem>
<listitem><para>Secondary storage, which is shared by all the pods in the zone.</para></listitem>
</itemizedlist>
<mediaobject>
<imageobject>
<imagedata fileref="./images/zone-overview.png" />
</imageobject>
<textobject><phrase>zone-overview.png: Nested structure of a simple zone.</phrase></textobject>
</mediaobject>
<para>Zones are visible to the end user. When a user starts a guest VM, the user must select a zone for their guest. Users might also be required to copy their private templates to additional zones to enable creation of guest VMs using their templates in those zones.</para>
<para>Zones can be public or private. Public zones are visible to all users. This means that any user may create a guest in that zone. Private zones are reserved for a specific domain. Only users in that domain or its subdomains may create guests in that zone.</para>
<para>Hosts in the same zone are directly accessible to each other without having to go through a firewall. Hosts in different zones can access each other through statically configured VPN tunnels.</para>
<para>For each zone, the administrator must decide the following.</para>
<itemizedlist>
<listitem><para>How many pods to place in each zone.</para></listitem>
<listitem><para>How many clusters to place in each pod.</para></listitem>
<listitem><para>How many hosts to place in each cluster.</para></listitem>
<listitem><para>(Optional) How many primary storage servers to place in each zone and total capacity for these storage servers.</para></listitem>
<listitem><para>How many primary storage servers to place in each cluster and total capacity for these storage servers.</para></listitem>
<listitem><para>How much secondary storage to deploy in a zone.</para></listitem>
</itemizedlist>
<para>When you add a new zone using the &PRODUCT; UI, you will be prompted to configure the zone’s physical network
and add the first pod, cluster, host, primary storage, and secondary storage.</para>
<para>In order to support zone-wide functions for VMware, &PRODUCT; is aware of VMware Datacenters and can map each Datacenter to a
&PRODUCT; zone. To enable features like storage live migration and zone-wide
primary storage for VMware hosts, &PRODUCT; has to make sure that a zone
contains only a single VMware Datacenter. Therefore, when you are creating a new
&PRODUCT; zone, you can select a VMware Datacenter for the zone. If you
are provisioning multiple VMware Datacenters, each one will be set up as a single zone
in &PRODUCT;. </para>
<note>
<para>If you are upgrading from a previous &PRODUCT; version, and your existing
deployment contains a zone with clusters from multiple VMware Datacenters, that zone
will not be forcibly migrated to the new model. It will continue to function as
before. However, any new zone-wide operations, such as zone-wide primary storage
and live storage migration, will
not be available in that zone.</para>
</note>
<para/>
</section>
| {'content_hash': '7e283a8e182634de60836ca8420cada8', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 278, 'avg_line_length': 70.01351351351352, 'alnum_prop': 0.7193591970662034, 'repo_name': 'unodba/cloudstack-docs', 'id': '2a4eeb4659f440862efd21c5c26a9192399be481', 'size': '5183', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'en-US/about-zones.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2780'}, {'name': 'HTML', 'bytes': '16465'}, {'name': 'Java', 'bytes': '1829'}, {'name': 'Makefile', 'bytes': '7592'}, {'name': 'Python', 'bytes': '13916'}, {'name': 'Shell', 'bytes': '2088'}]} |
function Test3dsSffs_LOSubjO_script()
% Created 8/27/13 by DJ.
%% Get features of size X
nFeats = size(bigFeature{1},2);
isInSet = zeros(NumFeatComb,nFeats,numel(subjects));
for iSubj=1:numel(subjects)
thisset = [];
for i=1:NumFeatComb
% if ~isempty(sffs.features{iSubj}{i});
thisset = sffs.features{iSubj}{i};
% end
isInSet(i,thisset,iSubj) = 1;
end
end
%% Get cross-validated AUC by leaving one subject out
bestfeats = cell(nFeats,numel(subjects));
AUC_xval = zeros(nFeats,numel(subjects));
firstmajority = zeros(nFeats,numel(subjects)); % to record any ties
for iSubj = 1:numel(subjects)
fprintf('====== Subject %d ======\n',subjects(iSubj));
% Rank best features from training subjects
trainsubj = [1:iSubj-1, iSubj+1:numel(subjects)];
fracpicked = mean(isInSet(:,:,trainsubj),3);
for i=1:nFeats
firstmajority(i,iSubj) = find(fracpicked(:,i)>0.5,1);
end
[~,featureorder] = sort(firstmajority(:,iSubj),'ascend');
% Record and
for nFeatWinners = 1:nFeats
bestfeats{nFeatWinners,iSubj} = featureorder(1:nFeatWinners);
fprintf('Best %d features: [%s]\n',nFeatWinners,num2str(bestfeats{nFeatWinners,iSubj}'));
% Use to test
AUC_xval(nFeatWinners,iSubj) = ClassifierWrapper_forSFFS(bigFeature{iSubj}(:,bestfeats),bigFeature{iSubj}(:,bestfeats),EEGDATA{iSubj},YDATA{iSubj},offsets(iSubj));
end
end
| {'content_hash': '32553b6bdf1029242f23c4b493576ad5', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 171, 'avg_line_length': 35.90243902439025, 'alnum_prop': 0.6467391304347826, 'repo_name': 'djangraw/EegAndEye', 'id': 'c3c29594d13a8e11f97620136165c31eac111b1b', 'size': '1472', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '3DSearch/FeatureSelection/Test3dsSffs_LOSubjO_script.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'MATLAB', 'bytes': '2146710'}]} |
using namespace llvm;
extern cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration;
AArch64MCInstLower::AArch64MCInstLower(MCContext &ctx, AsmPrinter &printer)
: Ctx(ctx), Printer(printer), TargetTriple(printer.getTargetTriple()) {}
MCSymbol *
AArch64MCInstLower::GetGlobalAddressSymbol(const MachineOperand &MO) const {
return Printer.getSymbol(MO.getGlobal());
}
MCSymbol *
AArch64MCInstLower::GetExternalSymbolSymbol(const MachineOperand &MO) const {
return Printer.GetExternalSymbolSymbol(MO.getSymbolName());
}
MCOperand AArch64MCInstLower::lowerSymbolOperandDarwin(const MachineOperand &MO,
MCSymbol *Sym) const {
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
MCSymbolRefExpr::VariantKind RefKind = MCSymbolRefExpr::VK_None;
if ((MO.getTargetFlags() & AArch64II::MO_GOT) != 0) {
if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_PAGE)
RefKind = MCSymbolRefExpr::VK_GOTPAGE;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) ==
AArch64II::MO_PAGEOFF)
RefKind = MCSymbolRefExpr::VK_GOTPAGEOFF;
else
llvm_unreachable("Unexpected target flags with MO_GOT on GV operand");
} else if ((MO.getTargetFlags() & AArch64II::MO_TLS) != 0) {
if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_PAGE)
RefKind = MCSymbolRefExpr::VK_TLVPPAGE;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) ==
AArch64II::MO_PAGEOFF)
RefKind = MCSymbolRefExpr::VK_TLVPPAGEOFF;
else
llvm_unreachable("Unexpected target flags with MO_TLS on GV operand");
} else {
if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_PAGE)
RefKind = MCSymbolRefExpr::VK_PAGE;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) ==
AArch64II::MO_PAGEOFF)
RefKind = MCSymbolRefExpr::VK_PAGEOFF;
}
const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, RefKind, Ctx);
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(
Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx);
return MCOperand::CreateExpr(Expr);
}
MCOperand AArch64MCInstLower::lowerSymbolOperandELF(const MachineOperand &MO,
MCSymbol *Sym) const {
uint32_t RefFlags = 0;
if (MO.getTargetFlags() & AArch64II::MO_GOT)
RefFlags |= AArch64MCExpr::VK_GOT;
else if (MO.getTargetFlags() & AArch64II::MO_TLS) {
TLSModel::Model Model;
if (MO.isGlobal()) {
const GlobalValue *GV = MO.getGlobal();
Model = Printer.TM.getTLSModel(GV);
if (!EnableAArch64ELFLocalDynamicTLSGeneration &&
Model == TLSModel::LocalDynamic)
Model = TLSModel::GeneralDynamic;
} else {
assert(MO.isSymbol() &&
StringRef(MO.getSymbolName()) == "_TLS_MODULE_BASE_" &&
"unexpected external TLS symbol");
// The general dynamic access sequence is used to get the
// address of _TLS_MODULE_BASE_.
Model = TLSModel::GeneralDynamic;
}
switch (Model) {
case TLSModel::InitialExec:
RefFlags |= AArch64MCExpr::VK_GOTTPREL;
break;
case TLSModel::LocalExec:
RefFlags |= AArch64MCExpr::VK_TPREL;
break;
case TLSModel::LocalDynamic:
RefFlags |= AArch64MCExpr::VK_DTPREL;
break;
case TLSModel::GeneralDynamic:
RefFlags |= AArch64MCExpr::VK_TLSDESC;
break;
}
} else {
// No modifier means this is a generic reference, classified as absolute for
// the cases where it matters (:abs_g0: etc).
RefFlags |= AArch64MCExpr::VK_ABS;
}
if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_PAGE)
RefFlags |= AArch64MCExpr::VK_PAGE;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) ==
AArch64II::MO_PAGEOFF)
RefFlags |= AArch64MCExpr::VK_PAGEOFF;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_G3)
RefFlags |= AArch64MCExpr::VK_G3;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_G2)
RefFlags |= AArch64MCExpr::VK_G2;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_G1)
RefFlags |= AArch64MCExpr::VK_G1;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_G0)
RefFlags |= AArch64MCExpr::VK_G0;
else if ((MO.getTargetFlags() & AArch64II::MO_FRAGMENT) == AArch64II::MO_HI12)
RefFlags |= AArch64MCExpr::VK_HI12;
if (MO.getTargetFlags() & AArch64II::MO_NC)
RefFlags |= AArch64MCExpr::VK_NC;
const MCExpr *Expr =
MCSymbolRefExpr::Create(Sym, MCSymbolRefExpr::VK_None, Ctx);
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(
Expr, MCConstantExpr::Create(MO.getOffset(), Ctx), Ctx);
AArch64MCExpr::VariantKind RefKind;
RefKind = static_cast<AArch64MCExpr::VariantKind>(RefFlags);
Expr = AArch64MCExpr::Create(Expr, RefKind, Ctx);
return MCOperand::CreateExpr(Expr);
}
MCOperand AArch64MCInstLower::LowerSymbolOperand(const MachineOperand &MO,
MCSymbol *Sym) const {
if (TargetTriple.isOSDarwin())
return lowerSymbolOperandDarwin(MO, Sym);
assert(TargetTriple.isOSBinFormatELF() && "Expect Darwin or ELF target");
return lowerSymbolOperandELF(MO, Sym);
}
bool AArch64MCInstLower::lowerOperand(const MachineOperand &MO,
MCOperand &MCOp) const {
switch (MO.getType()) {
default:
llvm_unreachable("unknown operand type");
case MachineOperand::MO_Register:
// Ignore all implicit register operands.
if (MO.isImplicit())
return false;
MCOp = MCOperand::CreateReg(MO.getReg());
break;
case MachineOperand::MO_RegisterMask:
// Regmasks are like implicit defs.
return false;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::CreateImm(MO.getImm());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::CreateExpr(
MCSymbolRefExpr::Create(MO.getMBB()->getSymbol(), Ctx));
break;
case MachineOperand::MO_GlobalAddress:
MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
break;
case MachineOperand::MO_ExternalSymbol:
MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = LowerSymbolOperand(MO, Printer.GetJTISymbol(MO.getIndex()));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = LowerSymbolOperand(MO, Printer.GetCPISymbol(MO.getIndex()));
break;
case MachineOperand::MO_BlockAddress:
MCOp = LowerSymbolOperand(
MO, Printer.GetBlockAddressSymbol(MO.getBlockAddress()));
break;
}
return true;
}
void AArch64MCInstLower::Lower(const MachineInstr *MI, MCInst &OutMI) const {
OutMI.setOpcode(MI->getOpcode());
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MCOperand MCOp;
if (lowerOperand(MI->getOperand(i), MCOp))
OutMI.addOperand(MCOp);
}
}
| {'content_hash': '7b1d28f45d72ded11fab54bdf9123f2b', 'timestamp': '', 'source': 'github', 'line_count': 186, 'max_line_length': 80, 'avg_line_length': 38.08064516129032, 'alnum_prop': 0.6689255964986588, 'repo_name': 'slightperturbation/Cobalt', 'id': 'b82934134d91c6979308aa45adca7e8c58a58bea', 'size': '8035', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ext/emsdk_portable/clang/tag-e1.34.1/src/lib/Target/AArch64/AArch64MCInstLower.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '7942339'}, {'name': 'Batchfile', 'bytes': '27769'}, {'name': 'C', 'bytes': '64431592'}, {'name': 'C++', 'bytes': '192377551'}, {'name': 'CMake', 'bytes': '2563457'}, {'name': 'CSS', 'bytes': '32911'}, {'name': 'DTrace', 'bytes': '12324'}, {'name': 'Emacs Lisp', 'bytes': '11557'}, {'name': 'Go', 'bytes': '132306'}, {'name': 'Groff', 'bytes': '141757'}, {'name': 'HTML', 'bytes': '10597275'}, {'name': 'JavaScript', 'bytes': '7134930'}, {'name': 'LLVM', 'bytes': '37169002'}, {'name': 'Lua', 'bytes': '30196'}, {'name': 'Makefile', 'bytes': '4368336'}, {'name': 'Nix', 'bytes': '17734'}, {'name': 'OCaml', 'bytes': '401898'}, {'name': 'Objective-C', 'bytes': '492807'}, {'name': 'PHP', 'bytes': '324917'}, {'name': 'Perl', 'bytes': '27878'}, {'name': 'Prolog', 'bytes': '1200'}, {'name': 'Python', 'bytes': '3678053'}, {'name': 'Shell', 'bytes': '3047898'}, {'name': 'SourcePawn', 'bytes': '2461'}, {'name': 'Standard ML', 'bytes': '2841'}, {'name': 'TeX', 'bytes': '120660'}, {'name': 'VimL', 'bytes': '13743'}]} |
If you have completed service tests or experience and do not need the BMS, release the BMS to avoid additional expenses.
## Procedure<a name="section16687936134318"></a>
1. Log in to the Cloud Server Console.
2. In the navigation pane, choose **Bare Metal Server**.
3. In the upper left corner, click  and select a region.
4. In the BMS list, locate the created BMS **bms-7676-nginx**. Click **More** in the **Operation** column and select **Delete** from the drop-down list.
5. In the displayed dialog box, confirm the information and click **OK**.
If the BMS has associated resources, such as EVS disks and EIP, you can choose whether to delete these resources.
## Result<a name="section968418435505"></a>
The deleted BMS is not displayed in the BMS list.
| {'content_hash': 'efaccb38d271fdf3b50154111c392b9e', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 160, 'avg_line_length': 47.88235294117647, 'alnum_prop': 0.7235872235872236, 'repo_name': 'OpenTelekomCloud/docs', 'id': 'd0b112a018c29a1f6520e415d54f35daad0bdcc4', 'size': '928', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'doc/source/bms/user-guide/step-4-release-the-bms.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Python', 'bytes': '1088'}]} |
require "set"
require "active_support/core_ext/module/delegation"
require "rails_erd/domain/relationship/cardinality"
module RailsERD
class Domain
# Describes a relationship between two entities. A relationship is detected
# based on Active Record associations. One relationship may represent more
# than one association, however. Related associations are grouped together.
# Associations are related if they share the same foreign key, or the same
# join table in the case of many-to-many associations.
class Relationship
N = Cardinality::N
class << self
def from_associations(domain, associations) # @private :nodoc:
assoc_groups = associations.group_by { |assoc| association_identity(assoc) }
assoc_groups.collect { |_, assoc_group| new(domain, assoc_group.to_a) }
end
private
def association_identity(association)
identifier = association_identifier(association).to_s
Set[identifier, association_owner(association), association_target(association)]
end
def association_identifier(association)
if association.macro == :has_and_belongs_to_many
# Rails 4+ supports the join_table method, and doesn't expose it
# as an option if it's an implicit default.
(association.respond_to?(:join_table) && association.join_table) || association.options[:join_table]
else
association.options[:through] || association.send(Domain.foreign_key_method_name).to_s
end
end
def association_owner(association)
association.options[:as] ? association.options[:as].to_s.classify : association.active_record.name
end
def association_target(association)
association.options[:polymorphic] ? association.class_name : association.klass.name
end
end
extend Inspectable
inspection_attributes :source, :destination
# The domain in which this relationship is defined.
attr_reader :domain
# The source entity. It corresponds to the model that has defined a
# +has_one+ or +has_many+ association with the other model.
attr_reader :source
# The destination entity. It corresponds to the model that has defined
# a +belongs_to+ association with the other model.
attr_reader :destination
delegate :one_to_one?, :one_to_many?, :many_to_many?, :source_optional?,
:destination_optional?, :to => :cardinality
def initialize(domain, associations) # @private :nodoc:
@domain = domain
@reverse_associations, @forward_associations = partition_associations(associations)
assoc = @forward_associations.first || @reverse_associations.first
@source = @domain.entity_by_name(self.class.send(:association_owner, assoc))
@destination = @domain.entity_by_name(self.class.send(:association_target, assoc))
@source, @destination = @destination, @source if assoc.belongs_to?
end
# Returns all Active Record association objects that describe this
# relationship.
def associations
@forward_associations + @reverse_associations
end
# Returns the cardinality of this relationship.
def cardinality
@cardinality ||= begin
reverse_max = any_habtm?(associations) ? N : 1
forward_range = associations_range(@forward_associations, N)
reverse_range = associations_range(@reverse_associations, reverse_max)
Cardinality.new(reverse_range, forward_range)
end
end
# Indicates if a relationship is indirect, that is, if it is defined
# through other relationships. Indirect relationships are created in
# Rails with <tt>has_many :through</tt> or <tt>has_one :through</tt>
# association macros.
def indirect?
!@forward_associations.empty? and @forward_associations.all?(&:through_reflection)
end
# Indicates whether or not the relationship is defined by two inverse
# associations (e.g. a +has_many+ and a corresponding +belongs_to+
# association).
def mutual?
@forward_associations.any? and @reverse_associations.any?
end
# Indicates whether or not this relationship connects an entity with itself.
def recursive?
@source == @destination
end
# Indicates whether the destination cardinality class of this relationship
# is equal to one. This is +true+ for one-to-one relationships only.
def to_one?
cardinality.cardinality_class[1] == 1
end
# Indicates whether the destination cardinality class of this relationship
# is equal to infinity. This is +true+ for one-to-many or
# many-to-many relationships only.
def to_many?
cardinality.cardinality_class[1] != 1
end
# Indicates whether the source cardinality class of this relationship
# is equal to one. This is +true+ for one-to-one or
# one-to-many relationships only.
def one_to?
cardinality.cardinality_class[0] == 1
end
# Indicates whether the source cardinality class of this relationship
# is equal to infinity. This is +true+ for many-to-many relationships only.
def many_to?
cardinality.cardinality_class[0] != 1
end
# The strength of a relationship is equal to the number of associations
# that describe it.
def strength
if source.generalized? then 1 else associations.size end
end
def <=>(other) # @private :nodoc:
(source.name <=> other.source.name).nonzero? or (destination.name <=> other.destination.name)
end
private
def partition_associations(associations)
if any_habtm?(associations)
# Many-to-many associations don't have a clearly defined direction.
# We sort by name and use the first model as the source.
source = associations.map(&:active_record).sort_by(&:name).first
associations.partition { |association| association.active_record != source }
else
associations.partition(&:belongs_to?)
end
end
def associations_range(associations, absolute_max)
# The minimum of the range is the maximum value of each association
# minimum. If there is none, it is zero by definition. The reasoning is
# that from all associations, if only one has a required minimum, then
# this side of the relationship has a cardinality of at least one.
min = associations.map { |assoc| association_minimum(assoc) }.max || 0
# The maximum of the range is the maximum value of each association
# maximum. If there is none, it is equal to the absolute maximum. If
# only one association has a high cardinality on this side, the
# relationship itself has the same maximum cardinality.
max = associations.map { |assoc| association_maximum(assoc) }.max || absolute_max
min..max
end
def association_minimum(association)
minimum = association_validators(:presence, association).any? ||
foreign_key_required?(association) ? 1 : 0
length_validators = association_validators(:length, association)
length_validators.map { |v| v.options[:minimum] }.compact.max or minimum
end
def association_maximum(association)
maximum = association.collection? ? N : 1
length_validators = association_validators(:length, association)
length_validators.map { |v| v.options[:maximum] }.compact.min or maximum
end
def association_validators(kind, association)
association.active_record.validators_on(association.name).select { |v| v.kind == kind }
end
def any_habtm?(associations)
associations.any? { |association| association.macro == :has_and_belongs_to_many }
end
def foreign_key_required?(association)
if !association.active_record.abstract_class? and association.belongs_to?
column = association.active_record.columns_hash[association.send(Domain.foreign_key_method_name)] and !column.null
end
end
end
end
end
| {'content_hash': '218f953a94bf4c1bc580635885f92122', 'timestamp': '', 'source': 'github', 'line_count': 203, 'max_line_length': 124, 'avg_line_length': 40.714285714285715, 'alnum_prop': 0.6673926194797338, 'repo_name': 'Yasu31/TK_1720', 'id': '5c77f6490b5f72ba60a30976a83425be59daf4be', 'size': '8265', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/loverduck_app/vendor/bundle/ruby/2.4.0/gems/rails-erd-1.5.2/lib/rails_erd/domain/relationship.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '7824'}, {'name': 'CSS', 'bytes': '2779'}, {'name': 'CoffeeScript', 'bytes': '633'}, {'name': 'HTML', 'bytes': '16742'}, {'name': 'JavaScript', 'bytes': '69585'}, {'name': 'Jupyter Notebook', 'bytes': '256601'}, {'name': 'Python', 'bytes': '5979'}, {'name': 'Ruby', 'bytes': '60792'}, {'name': 'Vue', 'bytes': '34136'}]} |
package scouter.agent.plugin;
import java.net.HttpURLConnection;
import scouter.agent.proxy.IHttpClient;
import scouter.agent.trace.TraceContext;
public class PluginHttpCallTrace {
static AbstractHttpCall plugIn;
static {
PluginLoader.getInstance();
}
public static void call(TraceContext ctx, HttpURLConnection req) {
if (plugIn != null) {
try {
plugIn.call(new WrContext(ctx), new WrHttpCallRequest(req));
} catch (Throwable t) {
}
}
}
public static void call(TraceContext ctx, Object req) {
if (plugIn != null) {
try {
plugIn.call(new WrContext(ctx), new WrHttpCallRequest(req));
} catch (Throwable t) {
}
}
}
public static void call(TraceContext ctx, IHttpClient httpclient, Object req) {
if (plugIn != null) {
try {
plugIn.call(new WrContext(ctx), new WrHttpCallRequest(httpclient, req));
} catch (Throwable t) {
}
}
}
} | {'content_hash': '5619b5a3de8e032913ca46ed01dc4c6e', 'timestamp': '', 'source': 'github', 'line_count': 44, 'max_line_length': 80, 'avg_line_length': 20.386363636363637, 'alnum_prop': 0.6900780379041248, 'repo_name': 'yuyupapa/OpenSource', 'id': '7c83eaf1b7598c7b1891907db992f2d9689cc996', 'size': '1572', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'scouter.agent.java/src/scouter/agent/plugin/PluginHttpCallTrace.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '71892'}, {'name': 'CSS', 'bytes': '26064'}, {'name': 'Groff', 'bytes': '8383'}, {'name': 'HTML', 'bytes': '3089620'}, {'name': 'Java', 'bytes': '29561111'}, {'name': 'JavaScript', 'bytes': '128607'}, {'name': 'NSIS', 'bytes': '41068'}, {'name': 'Scala', 'bytes': '722545'}, {'name': 'Shell', 'bytes': '90291'}, {'name': 'XSLT', 'bytes': '105761'}]} |
//
// This file is part of - WebExtras
// Copyright (C) 2016 Mihir Mone
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using Newtonsoft.Json;
using WebExtras.Core;
using WebExtras.FontAwesome;
using WebExtras.Html;
namespace WebExtras.Bootstrap.v3
{
/// <summary>
/// Denotes a Bootstrap 3 date time picker component
/// </summary>
[Serializable]
public class DateTimePickerHtmlComponent : HtmlComponent
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="name">HTML field name</param>
/// <param name="id">HTML field id</param>
/// <param name="options">Date time picker options</param>
/// <param name="htmlAttributes">Extra HTML attributes</param>
public DateTimePickerHtmlComponent(string name, string id, PickerOptions options, object htmlAttributes)
: base(EHtmlTag.Div)
{
PickerOptions pickerOptions =
(options ?? BootstrapSettings.DateTimePickerOptions).TryFontAwesomeIcons();
string fieldId = id;
string fieldName = name;
// create the text box
HtmlComponent input = new HtmlComponent(EHtmlTag.Input);
var attribs = WebExtrasUtil.AnonymousObjectToHtmlAttributes(htmlAttributes).ToDictionary();
input.Attributes.Add(attribs);
input.Attributes["type"] = "text";
input.Attributes["name"] = fieldName;
if (input.Attributes.ContainsKey("class"))
input.Attributes["class"] += " form-control";
else
input.Attributes["class"] = "form-control";
// create icon
HtmlComponent icons = new HtmlComponent(EHtmlTag.I);
if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V4)
icons.CssClasses.Add("fa fa-calendar");
else if (WebExtrasSettings.FontAwesomeVersion == EFontAwesomeVersion.V3)
icons.CssClasses.Add("icon-calendar");
else
icons.CssClasses.Add("glyphicon glyphicon-calendar");
// create addon
HtmlComponent addOn = new HtmlComponent(EHtmlTag.Span);
addOn.CssClasses.Add("input-group-addon");
addOn.AppendTags.Add(icons);
// create JSON dictionary of the picker options
string op = pickerOptions.ToJson(new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
HtmlComponent script = new HtmlComponent(EHtmlTag.Script);
script.Attributes["type"] = "text/javascript";
script.InnerHtml = "$(function(){ $('#" + fieldId + "').datetimepicker(" + op + "); });";
// setup up datetime picker
Attributes["id"] = fieldId;
Attributes["class"] = "input-group date";
AppendTags.Add(input);
AppendTags.Add(addOn);
AppendTags.Add(script);
}
}
} | {'content_hash': '81718b938809e3aeb973d5b185b9bf33', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 116, 'avg_line_length': 36.57142857142857, 'alnum_prop': 0.6871995192307693, 'repo_name': 'monemihir/webextras', 'id': '334ddf8dfdf4c16fcd83ee1bb546999c6b9080de', 'size': '3330', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'trunk/WebExtras/Bootstrap/v3/DateTimePickerHtmlComponent.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ASP', 'bytes': '3227'}, {'name': 'Batchfile', 'bytes': '1610'}, {'name': 'C#', 'bytes': '1576559'}, {'name': 'CSS', 'bytes': '577986'}, {'name': 'HTML', 'bytes': '215168'}, {'name': 'JavaScript', 'bytes': '881525'}]} |
#ifndef PORTAL_H
#define PORTAL_H
#include "OgrePortalBase.h"
namespace Ogre
{
/** Portal datastructure for connecting zones.
Portals are special constructs which which are used to connect
two Zones in a PCZScene. Portals are defined by 4 coplanr
corners and a direction. Portals are contained within Zones and
are essentially "one way" connectors. Objects and entities can
use them to travel to other Zones, but to return, there must be
a corresponding Portal which connects back to the original zone
from the new zone.
*/
class _OgrePCZPluginExport Portal : public PortalBase
{
public:
Portal(const String &name, const PORTAL_TYPE type = PORTAL_TYPE_QUAD);
virtual ~Portal();
void setTargetZone(PCZone* zone);
/** Set the target portal pointer */
void setTargetPortal(Portal* portal);
/** Get the Zone the Portal connects to */
PCZone* getTargetZone() {return mTargetZone;}
/** Get the connected portal (if any) */
Portal* getTargetPortal() {return mTargetPortal;}
/** @copydoc MovableObject::getMovableType */
const String& getMovableType() const override;
protected:
///connected Zone
PCZone* mTargetZone;
/** Matching Portal in the target zone (usually in same world space
as this portal, but pointing the opposite direction)
*/
Portal* mTargetPortal;
};
/** Factory object for creating Portal instances */
class _OgrePCZPluginExport PortalFactory : public PortalBaseFactory
{
protected:
MovableObject* createInstanceImpl(const String& name, const NameValuePairList* params) override;
public:
PortalFactory() {}
~PortalFactory() {}
static String FACTORY_TYPE_NAME;
static unsigned long FACTORY_TYPE_FLAG;
const String& getType() const override
{ return FACTORY_TYPE_NAME; }
/** Return true here as we want to get a unique type flag. */
bool requestTypeFlags() const override
{ return true; }
};
}
#endif
| {'content_hash': '30c078ab8a4ee21c8e069fd00b258abb', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 104, 'avg_line_length': 29.602739726027398, 'alnum_prop': 0.6478482184173994, 'repo_name': 'paroj/ogre', 'id': 'a72e10b6274953e343952334bc804f83adcfdeff', 'size': '3520', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'PlugIns/PCZSceneManager/include/OgrePortal.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '623'}, {'name': 'C', 'bytes': '3578310'}, {'name': 'C++', 'bytes': '17844368'}, {'name': 'CMake', 'bytes': '296110'}, {'name': 'Dockerfile', 'bytes': '404'}, {'name': 'GLSL', 'bytes': '83132'}, {'name': 'HLSL', 'bytes': '3051'}, {'name': 'HTML', 'bytes': '26750'}, {'name': 'Lex', 'bytes': '83244'}, {'name': 'Makefile', 'bytes': '413'}, {'name': 'Metal', 'bytes': '796'}, {'name': 'Objective-C', 'bytes': '72847'}, {'name': 'Objective-C++', 'bytes': '309298'}, {'name': 'Python', 'bytes': '51792'}, {'name': 'Rich Text Format', 'bytes': '1380'}, {'name': 'SWIG', 'bytes': '43054'}, {'name': 'Shell', 'bytes': '8749'}, {'name': 'Yacc', 'bytes': '40114'}]} |
module Scale
using Colors
using Compat
using Compose
using DataArrays
using DataStructures
using Gadfly
using Showoff
import Gadfly: element_aesthetics, isconcrete, concrete_length,
nonzero_length
import Distributions: Distribution
include("color_misc.jl")
# Return true if var is categorical.
function iscategorical(scales::Dict{Symbol, Gadfly.ScaleElement}, var::Symbol)
return haskey(scales, var) && isa(scales[var], DiscreteScale)
end
# Apply some scales to data in the given order.
#
# Args:
# scales: An iterable object of ScaleElements.
# aess: Aesthetics (of the same length as datas) to update with scaled data.
# datas: Zero or more data objects. (Yes, I know "datas" is not a real word.)
#
# Returns:
# nothing
#
function apply_scales(scales,
aess::Vector{Gadfly.Aesthetics},
datas::Gadfly.Data...)
for scale in scales
apply_scale(scale, aess, datas...)
end
for (aes, data) in zip(aess, datas)
aes.titles = data.titles
end
end
# Apply some scales to data in the given order.
#
# Args:
# scales: An iterable object of ScaleElements.
# datas: Zero or more data objects.
#
# Returns:
# A vector of Aesthetics of the same length as datas containing scaled data.
#
function apply_scales(scales, datas::Gadfly.Data...)
aess = Gadfly.Aesthetics[Gadfly.Aesthetics() for _ in datas]
apply_scales(scales, aess, datas...)
aess
end
# Transformations on continuous scales
immutable ContinuousScaleTransform
f::Function # transform function
finv::Function # f's inverse
# A function taking one or more values and returning an array of
# strings.
label::Function
end
function identity_formatter(xs::AbstractArray, format=:auto)
return showoff(xs, format)
end
const identity_transform =
ContinuousScaleTransform(identity, identity, identity_formatter)
function log10_formatter(xs::AbstractArray, format=:plain)
[@sprintf("10<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const log10_transform =
ContinuousScaleTransform(log10, x -> 10^x, log10_formatter)
function log2_formatter(xs::AbstractArray, format=:plain)
[@sprintf("2<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const log2_transform =
ContinuousScaleTransform(log2, x -> 2^x, log2_formatter)
function ln_formatter(xs::AbstractArray, format=:plain)
[@sprintf("e<sup>%s</sup>", x) for x in showoff(xs, format)]
end
const ln_transform =
ContinuousScaleTransform(log, exp, ln_formatter)
function asinh_formatter(xs::AbstractArray, format=:plain)
[@sprintf("asinh(%s)", x) for x in showoff(xs, format)]
end
const asinh_transform =
ContinuousScaleTransform(asinh, sinh, asinh_formatter)
function sqrt_formatter(xs::AbstractArray, format=:plain)
[@sprintf("%s<sup>2</sup>", x) for x in showoff(xs, format)]
end
const sqrt_transform = ContinuousScaleTransform(sqrt, x -> x^2, sqrt_formatter)
# Continuous scale maps data on a continuous scale simple by calling
# `convert(Float64, ...)`.
immutable ContinuousScale <: Gadfly.ScaleElement
vars::Vector{Symbol}
trans::ContinuousScaleTransform
minvalue
maxvalue
minticks
maxticks
labels::Union(Nothing, Function)
format
scalable
function ContinuousScale(vars::Vector{Symbol},
trans::ContinuousScaleTransform;
labels=nothing,
minvalue=nothing, maxvalue=nothing,
minticks=2, maxticks=10,
format=nothing,
scalable=true)
if minvalue != nothing && maxvalue != nothing && minvalue > maxvalue
error("Cannot construct a ContinuousScale with minvalue > maxvalue")
end
new(vars, trans, minvalue, maxvalue, minticks, maxticks, labels,
format, scalable)
end
end
function make_labeler(scale::ContinuousScale)
if scale.labels != nothing
function f(xs)
return [scale.labels(x) for x in xs]
end
elseif scale.format == nothing
scale.trans.label
else
function f(xs)
return scale.trans.label(xs, scale.format)
end
end
end
const x_vars = [:x, :xmin, :xmax, :xintercept, :xviewmin, :xviewmax]
const y_vars = [:y, :ymin, :ymax, :yintercept, :middle,
:upper_fence, :lower_fence, :upper_hinge, :lower_hinge,
:yviewmin, :yviewmax]
function continuous_scale_partial(vars::Vector{Symbol},
trans::ContinuousScaleTransform)
function f(; minvalue=nothing, maxvalue=nothing, labels=nothing, format=nothing, minticks=2,
maxticks=10, scalable=true)
ContinuousScale(vars, trans, minvalue=minvalue, maxvalue=maxvalue,
labels=labels, format=format, minticks=minticks,
maxticks=maxticks, scalable=scalable)
end
end
# Commonly used scales.
const x_continuous = continuous_scale_partial(x_vars, identity_transform)
const y_continuous = continuous_scale_partial(y_vars, identity_transform)
const x_log10 = continuous_scale_partial(x_vars, log10_transform)
const y_log10 = continuous_scale_partial(y_vars, log10_transform)
const x_log2 = continuous_scale_partial(x_vars, log2_transform)
const y_log2 = continuous_scale_partial(y_vars, log2_transform)
const x_log = continuous_scale_partial(x_vars, ln_transform)
const y_log = continuous_scale_partial(y_vars, ln_transform)
const x_asinh = continuous_scale_partial(x_vars, asinh_transform)
const y_asinh = continuous_scale_partial(y_vars, asinh_transform)
const x_sqrt = continuous_scale_partial(x_vars, sqrt_transform)
const y_sqrt = continuous_scale_partial(y_vars, sqrt_transform)
const size_continuous = continuous_scale_partial([:size], identity_transform)
function element_aesthetics(scale::ContinuousScale)
return scale.vars
end
# Apply a continuous scale.
#
# Args:
# scale: A continuos scale.
# datas: Zero or more data objects.
# aess: Aesthetics (of the same length as datas) to update with scaled data.
#
# Return:
# nothing
#
function apply_scale(scale::ContinuousScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
for var in scale.vars
vals = getfield(data, var)
if vals === nothing
continue
end
# special case for function arrays bound to :y
# pass the function values through and wait for the scale to
# be reapplied by Stat.func
if var == :y && eltype(vals) == Function
aes.y = vals
continue
end
# special case for Distribution values bound to :x or :y. wait for
# scale to be re-applied by Stat.qq
if in(var, [:x, :y]) && typeof(vals) <: Distribution
setfield!(aes, var, vals)
continue
end
T = Any
for d in vals
if isconcrete(d)
T = typeof(scale.trans.f(d))
break
end
end
ds = Gadfly.hasna(vals) ? DataArray(T, length(vals)) : Array(T, length(vals))
apply_scale_typed!(ds, vals, scale)
if var == :xviewmin || var == :xviewmax ||
var == :yviewmin || var == :yviewmax
setfield!(aes, var, ds[1])
else
setfield!(aes, var, ds)
end
if var in x_vars
label_var = :x_label
elseif var in y_vars
label_var = :y_label
else
label_var = symbol(@sprintf("%s_label", string(var)))
end
if in(label_var, Set(fieldnames(aes)))
setfield!(aes, label_var, make_labeler(scale))
end
end
if scale.minvalue != nothing
if scale.vars === x_vars
aes.xviewmin = scale.trans.f(scale.minvalue)
elseif scale.vars === y_vars
aes.yviewmin = scale.trans.f(scale.minvalue)
end
end
if scale.maxvalue != nothing
if scale.vars === x_vars
aes.xviewmax = scale.trans.f(scale.maxvalue)
elseif scale.vars === y_vars
aes.yviewmax = scale.trans.f(scale.maxvalue)
end
end
end
end
function apply_scale_typed!(ds, field, scale::ContinuousScale)
for i in 1:length(field)
d = field[i]
ds[i] = isconcrete(d) ? scale.trans.f(d) : d
end
end
# Reorder the levels of a pooled data array
function reorder_levels(da::PooledDataArray, order::AbstractVector)
level_values = levels(da)
if length(order) != length(level_values)
error("Discrete scale order is not of the same length as the data's levels.")
end
permute!(level_values, order)
return PooledDataArray(da, level_values)
end
function discretize_make_pda(values::Vector, levels=nothing)
if levels == nothing
return PooledDataArray(values)
else
return PooledDataArray(convert(Vector{eltype(levels)}, values), levels)
end
end
function discretize_make_pda(values::DataArray, levels=nothing)
if levels == nothing
return PooledDataArray(values)
else
return PooledDataArray(convert(DataArray{eltype(levels)}, values), levels)
end
end
function discretize_make_pda(values::Range, levels=nothing)
if levels == nothing
return PooledDataArray(collect(values))
else
return PooledDataArray(collect(values), levels)
end
end
function discretize_make_pda(values::PooledDataArray, levels=nothing)
if levels == nothing
return values
else
return PooledDataArray(values, convert(Vector{eltype(values)}, levels))
end
end
function discretize(values, levels=nothing, order=nothing,
preserve_order=true)
if levels == nothing
if preserve_order
levels = OrderedSet()
for value in values
push!(levels, value)
end
da = discretize_make_pda(values, collect(eltype(values), levels))
else
da = discretize_make_pda(values)
end
else
da = discretize_make_pda(values, levels)
end
if order != nothing
return reorder_levels(da, order)
else
return da
end
end
immutable DiscreteScaleTransform
f::Function
end
immutable DiscreteScale <: Gadfly.ScaleElement
vars::Vector{Symbol}
# Labels are either a function that takes an array of values and returns
# an array of string labels, a vector of string labels of the same length
# as the number of unique values in the discrete data, or nothing to use
# the default labels.
labels::Union(Nothing, Function)
# If non-nothing, give values for the scale. Order will be respected and
# anything in the data that's not represented in values will be set to NA.
levels::Union(Nothing, AbstractVector)
# If non-nothing, a permutation of the pool of values.
order::Union(Nothing, AbstractVector)
function DiscreteScale(vals::Vector{Symbol};
labels=nothing, levels=nothing, order=nothing)
new(vals, labels, levels, order)
end
end
const discrete = DiscreteScale
element_aesthetics(scale::DiscreteScale) = scale.vars
function x_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale(x_vars, labels=labels, levels=levels, order=order)
end
function y_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale(y_vars, labels=labels, levels=levels, order=order)
end
function group_discrete(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:group], labels=labels, levels=levels, order=order)
end
function apply_scale(scale::DiscreteScale, aess::Vector{Gadfly.Aesthetics},
datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
for var in scale.vars
label_var = symbol(@sprintf("%s_label", string(var)))
if getfield(data, var) === nothing
continue
end
disc_data = discretize(getfield(data, var), scale.levels, scale.order)
setfield!(aes, var, PooledDataArray(round(Int64, disc_data.refs)))
# The leveler for discrete scales is a closure over the discretized data.
if scale.labels === nothing
function default_labeler(xs)
lvls = levels(disc_data)
vals = Any[1 <= x <= length(lvls) ? lvls[x] : "" for x in xs]
if all([isa(val, FloatingPoint) for val in vals])
return showoff(vals)
else
return [string(val) for val in vals]
end
end
labeler = default_labeler
else
function explicit_labeler(xs)
lvls = levels(disc_data)
return [string(scale.labels(lvls[x])) for x in xs]
end
labeler = explicit_labeler
end
if in(label_var, Set(fieldnames(aes)))
setfield!(aes, label_var, labeler)
end
end
end
end
immutable NoneColorScale <: Gadfly.ScaleElement
end
const color_none = NoneColorScale
function element_aesthetics(scale::NoneColorScale)
[:color]
end
function apply_scale(scale::NoneColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for aes in aess
aes.color = nothing
end
end
immutable DiscreteColorScale <: Gadfly.ScaleElement
f::Function # A function f(n) that produces a vector of n colors.
# If non-nothing, give values for the scale. Order will be respected and
# anything in the data that's not represented in values will be set to NA.
levels::Union(Nothing, AbstractVector)
# If non-nothing, a permutation of the pool of values.
order::Union(Nothing, AbstractVector)
# If true, order levels as they appear in the data
preserve_order::Bool
function DiscreteColorScale(f::Function; levels=nothing, order=nothing,
preserve_order=true)
new(f, levels, order, preserve_order)
end
end
function element_aesthetics(scale::DiscreteColorScale)
[:color]
end
# Common discrete color scales
function color_discrete_hue(; levels=nothing, order=nothing,
preserve_order=true)
DiscreteColorScale(
h -> convert(Vector{Color},
distinguishable_colors(h, [LCHab(70, 60, 240)],
transform=c -> deuteranopic(c, 0.5),
lchoices=Float64[65, 70, 75, 80],
cchoices=Float64[0, 50, 60, 70],
hchoices=linspace(0, 330, 24))),
levels=levels, order=order, preserve_order=preserve_order)
end
@deprecate discrete_color_hue(; levels=nothing, order=nothing, preserve_order=true) color_discrete_hue(; levels=levels, order=order, preserve_order=preserve_order)
const color_discrete = color_discrete_hue
@deprecate discrete_color(; levels=nothing, order=nothing, preserve_order=true) color_discrete(; levels=levels, order=order, preserve_order=preserve_order)
color_discrete_manual(colors...; levels=nothing, order=nothing) = color_discrete_manual(map(Gadfly.parse_color, colors)...; levels=levels, order=order)
function color_discrete_manual(colors::Color...; levels=nothing, order=nothing)
cs = [colors...]
function f(n)
distinguishable_colors(n, cs)
end
DiscreteColorScale(f, levels=levels, order=order)
end
@deprecate discrete_color_manual(colors...; levels=nothing, order=nothing) color_discrete_manual(colors...; levels=levels, order=order)
function apply_scale(scale::DiscreteColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
levelset = OrderedSet()
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
for d in data.color
if !isna(d)
push!(levelset, d)
end
end
end
if scale.levels == nothing
scale_levels = [levelset...]
if !scale.preserve_order
sort!(scale_levels)
end
else
scale_levels = scale.levels
end
if scale.order != nothing
permute!(scale_levels, scale.order)
end
colors = convert(Vector{RGB{Float32}}, scale.f(length(scale_levels)))
color_map = @compat Dict([color => string(label)
for (label, color) in zip(scale_levels, colors)])
function labeler(xs)
[color_map[x] for x in xs]
end
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
ds = discretize(data.color, scale_levels)
colorvals = Array(RGB{Float32}, nonzero_length(ds.refs))
i = 1
for k in ds.refs
if k != 0
colorvals[i] = colors[k]
i += 1
end
end
colored_ds = PooledDataArray(colorvals, colors)
aes.color = colored_ds
aes.color_label = labeler
aes.color_key_colors = OrderedDict()
for (i, c) in enumerate(colors)
aes.color_key_colors[c] = i
end
end
end
immutable ContinuousColorScale <: Gadfly.ScaleElement
# A function of the form f(p) where 0 <= p <= 1, that returns a color.
f::Function
minvalue
maxvalue
function ContinuousColorScale(f::Function; minvalue=nothing, maxvalue=nothing)
new(f, minvalue, maxvalue)
end
end
element_aesthetics(::ContinuousColorScale) = [:color]
function color_continuous_gradient(;minvalue=nothing, maxvalue=nothing)
# TODO: this should be made more general purpose. I.e. define some
# more color scales.
function lch_diverge2(l0=30, l1=100, c=40, h0=260, h1=10, hmid=20, power=1.5)
lspan = l1 - l0
hspan1 = hmid - h0
hspan0 = h1 - hmid
function f(r)
r2 = 2r - 1
return LCHab(min(80, l1 - lspan * abs(r2)^power), max(10, c * abs(r2)),
(1-r)*h0 + r * h1)
end
end
ContinuousColorScale(
lch_diverge2(),
minvalue=minvalue, maxvalue=maxvalue)
end
@deprecate continuous_color_gradient(;minvalue=nothing, maxvalue=nothing) color_continuous_gradient(;minvalue=minvalue, maxvalue=maxvalue)
const color_continuous = color_continuous_gradient
@deprecate continuous_color(;minvalue=nothing, maxvalue=nothing) color_continuous(;minvalue=nothing, maxvalue=nothing)
function apply_scale(scale::ContinuousColorScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
cmin = Inf
cmax = -Inf
for data in datas
if data.color === nothing
continue
end
for c in data.color
if c === NA
continue
end
c = convert(Float64, c)
if c < cmin
cmin = c
end
if c > cmax
cmax = c
end
end
end
if cmin == Inf || cmax == -Inf
return nothing
end
if scale.minvalue != nothing
cmin = scale.minvalue
end
if scale.maxvalue != nothing
cmax = scale.maxvalue
end
cmin, cmax = promote(cmin, cmax)
ticks, viewmin, viewmax = Gadfly.optimize_ticks(cmin, cmax)
if ticks[1] == 0 && cmin >= 1
ticks[1] = 1
end
cmin = ticks[1]
cmax = ticks[end]
cspan = cmax != cmin ? cmax - cmin : 1.0
for (aes, data) in zip(aess, datas)
if data.color === nothing
continue
end
aes.color = DataArray(RGB{Float32}, length(data.color))
apply_scale_typed!(aes.color, data.color, scale, cmin, cspan)
color_key_colors = Dict{Color, Float64}()
color_key_labels = Dict{Color, String}()
tick_labels = identity_formatter(ticks)
for (i, j, label) in zip(ticks, ticks[2:end], tick_labels)
r = (i - cmin) / cspan
c = scale.f(r)
color_key_colors[c] = r
color_key_labels[c] = label
end
c = scale.f((ticks[end] - cmin) / cspan)
color_key_colors[c] = (ticks[end] - cmin) / cspan
color_key_labels[c] = tick_labels[end]
function labeler(xs)
[get(color_key_labels, x, "") for x in xs]
end
aes.color_function = scale.f
aes.color_label = labeler
aes.color_key_colors = color_key_colors
aes.color_key_continuous = true
end
end
function apply_scale_typed!(ds, field, scale::ContinuousColorScale,
cmin::Float64, cspan::Float64)
for (i, d) in enumerate(field)
if isconcrete(d)
ds[i] = convert(RGB{Float32}, scale.f((convert(Float64, d) - cmin) / cspan))
else
ds[i] = NA
end
end
end
# Label scale is always discrete, hence we call it 'label' rather
# 'label_discrete'.
immutable LabelScale <: Gadfly.ScaleElement
end
function apply_scale(scale::LabelScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
if data.label === nothing
continue
end
aes.label = discretize(data.label)
end
end
element_aesthetics(::LabelScale) = [:label]
const label = LabelScale
# Scale applied to grouping aesthetics.
immutable GroupingScale <: Gadfly.ScaleElement
var::Symbol
end
function xgroup(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:xgroup], labels=labels, levels=levels, order=order)
end
function ygroup(; labels=nothing, levels=nothing, order=nothing)
return DiscreteScale([:ygroup], labels=labels, levels=levels, order=order)
end
# Catchall scale for when no transformation of the data is necessary
immutable IdentityScale <: Gadfly.ScaleElement
var::Symbol
end
function element_aesthetics(scale::IdentityScale)
return [scale.var]
end
function apply_scale(scale::IdentityScale,
aess::Vector{Gadfly.Aesthetics}, datas::Gadfly.Data...)
for (aes, data) in zip(aess, datas)
if getfield(data, scale.var) === nothing
continue
end
setfield!(aes, scale.var, getfield(data, scale.var))
end
end
function z_func()
return IdentityScale(:z)
end
function y_func()
return IdentityScale(:y)
end
function x_distribution()
return IdentityScale(:x)
end
function y_distribution()
return IdentityScale(:y)
end
end # module Scale
| {'content_hash': '7c000d5464d3458dc94c082cae622ad7', 'timestamp': '', 'source': 'github', 'line_count': 814, 'max_line_length': 163, 'avg_line_length': 28.423832923832922, 'alnum_prop': 0.6151618619527164, 'repo_name': 'kshramt/Gadfly.jl', 'id': 'af2dd349369557e2f42fb4362c52c8d241c5b62d', 'size': '23138', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/scale.jl', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '24572'}, {'name': 'Julia', 'bytes': '324407'}]} |
<div class="pages">
<div data-page="index" class="page homepage">
<div class="page-content">
<div class="page_content_menu">
<nav class="main-nav">
<ul>
<li><a href="#" onclick="window.plugins.videoPlayer.play('http://stream01.m4u.com.pk:8081/tv/geonews/playlist.m3u8');"><img src="images/icons/tv/Masala Tv.png" alt="" title="" /><span>Masala Tv</span></a></li>
</ul>
</nav>
<div class="close_popup_button"><a href="#" class="backbutton"><img src="images/icons/white/menu_close.png" alt="" title="" /></a></div>
</div>
</div>
</div>
</div> | {'content_hash': '3a004a23c2143310e9cf20d0d5075478', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 219, 'avg_line_length': 37.64705882352941, 'alnum_prop': 0.55625, 'repo_name': 'aftabhabib/multilive', 'id': 'e33f9b69b912596df3d8f28e04f24e11127f0210', 'size': '640', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'cook.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '486773'}, {'name': 'HTML', 'bytes': '31280'}, {'name': 'JavaScript', 'bytes': '746762'}, {'name': 'PHP', 'bytes': '1649'}]} |
package atomic
import "unsafe"
//go:noescape
func Cas(ptr *uint32, old, new uint32) bool
// NO go:noescape annotation; see atomic_pointer.go.
func Casp1(ptr *unsafe.Pointer, old, new unsafe.Pointer) bool
//go:noescape
func Casint32(ptr *int32, old, new int32) bool
//go:noescape
func Casint64(ptr *int64, old, new int64) bool
//go:noescape
func Casuintptr(ptr *uintptr, old, new uintptr) bool
//go:noescape
func Storeint32(ptr *int32, new int32)
//go:noescape
func Storeint64(ptr *int64, new int64)
//go:noescape
func Storeuintptr(ptr *uintptr, new uintptr)
//go:noescape
func Loaduintptr(ptr *uintptr) uintptr
//go:noescape
func Loaduint(ptr *uint) uint
// TODO(matloob): Should these functions have the go:noescape annotation?
//go:noescape
func Loadint32(ptr *int32) int32
//go:noescape
func Loadint64(ptr *int64) int64
//go:noescape
func Xaddint32(ptr *int32, delta int32) int32
//go:noescape
func Xaddint64(ptr *int64, delta int64) int64
//go:noescape
func Xchgint32(ptr *int32, new int32) int32
//go:noescape
func Xchgint64(ptr *int64, new int64) int64
| {'content_hash': 'c31d65ff09ff1ff1873bb4056f2143d2', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 73, 'avg_line_length': 20.32075471698113, 'alnum_prop': 0.7493036211699164, 'repo_name': 'golang/go', 'id': '7df8d9c86329ee49a3abd1f069d66608cb4ebd6d', 'size': '1255', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'src/runtime/internal/atomic/stubs.go', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '2705689'}, {'name': 'Awk', 'bytes': '450'}, {'name': 'Batchfile', 'bytes': '8497'}, {'name': 'C', 'bytes': '127970'}, {'name': 'C++', 'bytes': '917'}, {'name': 'Dockerfile', 'bytes': '2789'}, {'name': 'Fortran', 'bytes': '100'}, {'name': 'Go', 'bytes': '41103717'}, {'name': 'HTML', 'bytes': '2621340'}, {'name': 'JavaScript', 'bytes': '20492'}, {'name': 'Makefile', 'bytes': '748'}, {'name': 'Perl', 'bytes': '31365'}, {'name': 'Python', 'bytes': '15738'}, {'name': 'Shell', 'bytes': '62900'}]} |
clifunzone
==========
.. testsetup::
from clifunzone import *
.. automodule:: clifunzone
:members:
| {'content_hash': '4b5d4b71518f4d064ef743c1c8a984f7', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 28, 'avg_line_length': 12.222222222222221, 'alnum_prop': 0.6, 'repo_name': 'Justin-W/clifunland', 'id': '0d0299346ce14b66361ef45fa8559002db1a6fab', 'size': '110', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/reference/clifunzone.rst', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '1598'}, {'name': 'Gherkin', 'bytes': '348'}, {'name': 'Python', 'bytes': '252891'}, {'name': 'Shell', 'bytes': '8436'}]} |
enum
{
PLATFORM_ERR,
PLATFORM_OK,
PLATFORM_UNDERFLOW = -1
};
// Platform initialization
int platform_init(void);
void platform_int_init(void);
// *****************************************************************************
// PIO subsection
// "Virtual ports": 16 ports (PA...PF), 32-bits each for a total of 512 I/O pins.
// They are coded within a single integer, where the high part encodes the port
// number, while the lower part encodes the pin number
typedef u32 pio_type;
typedef u32 pio_code;
#define PLATFORM_IO_PORTS 16
#define PLATFORM_IO_PORTS_BITS 4
#define PLATFORM_IO_PINS 32
#define PLATFORM_IO_PINS_BITS 5
#define PLATFORM_IO_FULL_PORT_BIT 14
#define PLATFORM_IO_FULL_PORT_MASK ( 1 << PLATFORM_IO_FULL_PORT_BIT )
#define PLATFORM_IO_ENCODE( port, pin, full ) ( ( ( port ) << PLATFORM_IO_PINS_BITS ) | ( pin ) | ( ( full ) ? PLATFORM_IO_FULL_PORT_MASK : 0 ) )
#define PLATFORM_IO_GET_PORT( code ) ( ( ( code ) >> PLATFORM_IO_PINS_BITS ) & ( ( 1 << PLATFORM_IO_PORTS_BITS ) - 1 ) )
#define PLATFORM_IO_GET_PIN( code ) ( ( code ) & ( ( 1 << PLATFORM_IO_PINS_BITS ) - 1 ) )
#define PLATFORM_IO_IS_PORT( code ) ( ( ( code ) & PLATFORM_IO_FULL_PORT_MASK ) != 0 )
#define PLATFORM_IO_ALL_PINS 0xFFFFFFFFUL
#define PLATFORM_IO_ENC_PORT 1
#define PLATFORM_IO_ENC_PIN 0
#define PLATFORM_IO_READ_IN_MASK 0
#define PLATFORM_IO_READ_OUT_MASK 1
enum
{
// Pin operations
PLATFORM_IO_PIN_SET,
PLATFORM_IO_PIN_CLEAR,
PLATFORM_IO_PIN_GET,
PLATFORM_IO_PIN_DIR_INPUT,
PLATFORM_IO_PIN_DIR_OUTPUT,
PLATFORM_IO_PIN_PULLUP,
PLATFORM_IO_PIN_PULLDOWN,
PLATFORM_IO_PIN_NOPULL,
// Port operations
PLATFORM_IO_PORT_SET_VALUE,
PLATFORM_IO_PORT_GET_VALUE,
PLATFORM_IO_PORT_DIR_INPUT,
PLATFORM_IO_PORT_DIR_OUTPUT
};
// The platform I/O functions
int platform_pio_has_port( unsigned port );
const char* platform_pio_get_prefix( unsigned port );
int platform_pio_has_pin( unsigned port, unsigned pin );
int platform_pio_get_num_pins( unsigned port );
pio_type platform_pio_op( unsigned port, pio_type pinmask, int op );
// *****************************************************************************
// Timer subsection
// The ID of the system timer
#define PLATFORM_TIMER_SYS_ID 0x100
#if defined( LUA_NUMBER_INTEGRAL ) && !defined( LUA_INTEGRAL_LONGLONG )
// Maximum values of the system timer
#define PLATFORM_TIMER_SYS_MAX ( ( 1LL << 32 ) - 2 )
// Timer data type
typedef u32 timer_data_type;
#else
// Maximum values of the system timer
#define PLATFORM_TIMER_SYS_MAX ( ( 1LL << 52 ) - 2 )
// Timer data type
typedef u64 timer_data_type;
#endif // #if defined( LUA_NUMBER_INTEGRAL ) && !defined( LUA_INTEGRAL_LONGLONG )
// This constant means 'infinite timeout'
#define PLATFORM_TIMER_INF_TIMEOUT ( PLATFORM_TIMER_SYS_MAX + 1 )
// System timer frequency
#define PLATFORM_TIMER_SYS_FREQ 1000000
// Interrupt types
#define PLATFORM_TIMER_INT_ONESHOT 1
#define PLATFORM_TIMER_INT_CYCLIC 2
// Match interrupt error codes
#define PLATFORM_TIMER_INT_OK 0
#define PLATFORM_TIMER_INT_TOO_SHORT 1
#define PLATFORM_TIMER_INT_TOO_LONG 2
#define PLATFORM_TIMER_INT_INVALID_ID 3
// Timer operations
enum
{
PLATFORM_TIMER_OP_START,
PLATFORM_TIMER_OP_READ,
PLATFORM_TIMER_OP_SET_CLOCK,
PLATFORM_TIMER_OP_GET_CLOCK,
PLATFORM_TIMER_OP_GET_MAX_DELAY,
PLATFORM_TIMER_OP_GET_MIN_DELAY,
PLATFORM_TIMER_OP_GET_MAX_CNT
};
// The platform timer functions
int platform_timer_exists( unsigned id );
void platform_timer_delay( unsigned id, timer_data_type delay_us );
void platform_s_timer_delay( unsigned id, timer_data_type delay_us );
timer_data_type platform_timer_op( unsigned id, int op, timer_data_type data );
timer_data_type platform_s_timer_op( unsigned id, int op, timer_data_type data );
int platform_timer_set_match_int( unsigned id, timer_data_type period_us, int type );
int platform_s_timer_set_match_int( unsigned id, timer_data_type period_us, int type );
timer_data_type platform_timer_get_diff_us( unsigned id, timer_data_type start, timer_data_type end );
// System timer functions
timer_data_type platform_timer_read_sys(void);
int platform_timer_sys_available(void);
// The next 3 functions need to be implemented only if the generic system timer mechanism
// (src/common.c:cmn_systimer*) is used by the backend
u64 platform_timer_sys_raw_read(void);
void platform_timer_sys_enable_int(void);
void platform_timer_sys_disable_int(void);
// Convenience macros
#define platform_timer_read( id ) platform_timer_op( id, PLATFORM_TIMER_OP_READ, 0 )
#define platform_timer_start( id ) platform_timer_op( id, PLATFORM_TIMER_OP_START, 0 )
#define platform_timer_get_diff_crt( id, v ) platform_timer_get_diff_us( id, v, platform_timer_read( id ) )
#define platform_timer_sys_delay( us ) platform_timer_delay( PLATFORM_TIMER_SYS_ID, us )
#define platform_timer_get_max_cnt( id ) platform_timer_op( id, PLATFORM_TIMER_OP_GET_MAX_CNT, 0 )
// *****************************************************************************
// CAN subsection
// Maximum length for any CAN message
#define PLATFORM_CAN_MAXLEN 8
// eLua CAN ID types
enum
{
ELUA_CAN_ID_STD = 0,
ELUA_CAN_ID_EXT
};
int platform_can_exists( unsigned id );
u32 platform_can_setup( unsigned id, u32 clock );
int platform_can_send( unsigned id, u32 canid, u8 idtype, u8 len, const u8 *data );
int platform_can_recv( unsigned id, u32 *canid, u8 *idtype, u8 *len, u8 *data );
// *****************************************************************************
// SPI subsection
// There are 4 "virtual" SPI ports (SPI0...SPI3).
#define PLATFORM_SPI_TOTAL 4
// TODO: PLATFORM_SPI_TOTAL is not used - figure out purpose, or remove?
// SPI mode
#define PLATFORM_SPI_MASTER 1
#define PLATFORM_SPI_SLAVE 0
// SS values
#define PLATFORM_SPI_SELECT_ON 1
#define PLATFORM_SPI_SELECT_OFF 0
// SPI enable/disable
#define PLATFORM_SPI_ENABLE 1
#define PLATFORM_SPI_DISABLE 0
// Data types
typedef u32 spi_data_type;
// The platform SPI functions
int platform_spi_exists( unsigned id );
u32 platform_spi_setup( unsigned id, int mode, u32 clock, unsigned cpol, unsigned cpha, unsigned databits );
spi_data_type platform_spi_send_recv( unsigned id, spi_data_type data );
void platform_spi_select( unsigned id, int is_select );
// *****************************************************************************
// UART subsection
// There are 4 "virtual" UART ports (UART0...UART3).
#define PLATFORM_UART_TOTAL 4
// TODO: PLATFORM_UART_TOTAL is not used - figure out purpose, or remove?
// Note: Some CPUs (e.g. LM4F/TM4C) have more than 4 hardware UARTs
// Pseudo ID of UART over CDC
#define CDC_UART_ID 0xB0
// Parity
enum
{
PLATFORM_UART_PARITY_EVEN,
PLATFORM_UART_PARITY_ODD,
PLATFORM_UART_PARITY_NONE,
PLATFORM_UART_PARITY_MARK,
PLATFORM_UART_PARITY_SPACE
};
// Stop bits
enum
{
PLATFORM_UART_STOPBITS_1,
PLATFORM_UART_STOPBITS_1_5,
PLATFORM_UART_STOPBITS_2
};
// Flow control types (this is a bit mask, one can specify PLATFORM_UART_FLOW_RTS | PLATFORM_UART_FLOW_CTS )
#define PLATFORM_UART_FLOW_NONE 0
#define PLATFORM_UART_FLOW_RTS 1
#define PLATFORM_UART_FLOW_CTS 2
// The platform UART functions
int platform_uart_exists( unsigned id );
u32 platform_uart_setup( unsigned id, u32 baud, int databits, int parity, int stopbits );
int platform_uart_set_buffer( unsigned id, unsigned size );
void platform_uart_send( unsigned id, u8 data );
void platform_s_uart_send( unsigned id, u8 data );
int platform_uart_recv( unsigned id, unsigned timer_id, timer_data_type timeout );
int platform_s_uart_recv( unsigned id, timer_data_type timeout );
int platform_uart_set_flow_control( unsigned id, int type );
int platform_s_uart_set_flow_control( unsigned id, int type );
// *****************************************************************************
// PWM subsection
// There are 16 "virtual" PWM channels (PWM0...PWM15)
#define PLATFORM_PWM_TOTAL 16
// TODO: PLATFORM_PWM_TOTAL is not used - figure out purpose, or remove?
// The platform PWM functions
int platform_pwm_exists( unsigned id );
u32 platform_pwm_setup( unsigned id, u32 frequency, unsigned duty );
void platform_pwm_start( unsigned id );
void platform_pwm_stop( unsigned id );
u32 platform_pwm_set_clock( unsigned id, u32 data );
u32 platform_pwm_get_clock( unsigned id );
// *****************************************************************************
// CPU specific functions
#define PLATFORM_CPU_DISABLE 0
#define PLATFORM_CPU_ENABLE 1
// Interrupt functions return status
#define PLATFORM_INT_OK 0
#define PLATFORM_INT_GENERIC_ERROR ( -1 )
#define PLATFORM_INT_INVALID ( -2 )
#define PLATFORM_INT_NOT_HANDLED ( -3 )
#define PLATFORM_INT_BAD_RESNUM ( -4 )
int platform_cpu_set_global_interrupts( int status );
int platform_cpu_get_global_interrupts(void);
int platform_cpu_set_interrupt( elua_int_id id, elua_int_resnum resnum, int status );
int platform_cpu_get_interrupt( elua_int_id id, elua_int_resnum resnum );
int platform_cpu_get_interrupt_flag( elua_int_id id, elua_int_resnum resnum, int clear );
u32 platform_cpu_get_frequency(void);
// *****************************************************************************
// The platform ADC functions
// Functions requiring platform-specific implementation
int platform_adc_update_sequence(void);
int platform_adc_start_sequence(void);
void platform_adc_stop( unsigned id );
u32 platform_adc_set_clock( unsigned id, u32 frequency);
int platform_adc_check_timer_id( unsigned id, unsigned timer_id );
// ADC Common Functions
int platform_adc_exists( unsigned id );
u32 platform_adc_get_maxval( unsigned id );
u32 platform_adc_set_smoothing( unsigned id, u32 length );
void platform_adc_set_blocking( unsigned id, u32 mode );
void platform_adc_set_freerunning( unsigned id, u32 mode );
u32 platform_adc_is_done( unsigned id );
void platform_adc_set_timer( unsigned id, u32 timer );
// *****************************************************************************
// I2C platform interface
// I2C speed
enum
{
PLATFORM_I2C_SPEED_SLOW = 100000,
PLATFORM_I2C_SPEED_FAST = 400000
};
// I2C direction
enum
{
PLATFORM_I2C_DIRECTION_TRANSMITTER,
PLATFORM_I2C_DIRECTION_RECEIVER
};
int platform_i2c_exists( unsigned id );
u32 platform_i2c_setup( unsigned id, u32 speed );
void platform_i2c_send_start( unsigned id );
void platform_i2c_send_stop( unsigned id );
int platform_i2c_send_address( unsigned id, u16 address, int direction );
int platform_i2c_send_byte( unsigned id, u8 data );
int platform_i2c_recv_byte( unsigned id, int ack );
// *****************************************************************************
// Ethernet specific functions
void platform_eth_send_packet( const void* src, u32 size );
u32 platform_eth_get_packet_nb( void* buf, u32 maxlen );
void platform_eth_force_interrupt(void);
u32 platform_eth_get_elapsed_time(void);
// *****************************************************************************
// Internal flash erase/write functions
// Currently used by WOFS
u32 platform_flash_get_first_free_block_address( u32 *psect );
u32 platform_flash_get_sector_of_address( u32 addr );
u32 platform_flash_write( const void *from, u32 toaddr, u32 size );
u32 platform_s_flash_write( const void *from, u32 toaddr, u32 size );
u32 platform_flash_get_num_sectors(void);
int platform_flash_erase_sector( u32 sector_id );
// *****************************************************************************
// Allocator support
void* platform_get_first_free_ram( unsigned id );
void* platform_get_last_free_ram( unsigned id );
#endif
| {'content_hash': 'b9a6b4c33ad5a2c14da024947c752dc4', 'timestamp': '', 'source': 'github', 'line_count': 326, 'max_line_length': 145, 'avg_line_length': 37.352760736196316, 'alnum_prop': 0.635870904163587, 'repo_name': 'www220/esp-idf', 'id': 'efabdbee9dd238416fe5360c8770c6004d61dc79', 'size': '12323', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/rtt_plug/lua/inc/platform.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '142861'}, {'name': 'C', 'bytes': '24407396'}, {'name': 'C++', 'bytes': '1427370'}, {'name': 'CMake', 'bytes': '139521'}, {'name': 'Inno Setup', 'bytes': '10241'}, {'name': 'Lex', 'bytes': '7270'}, {'name': 'Makefile', 'bytes': '132288'}, {'name': 'Objective-C', 'bytes': '44648'}, {'name': 'Perl', 'bytes': '15204'}, {'name': 'Python', 'bytes': '748019'}, {'name': 'Shell', 'bytes': '67825'}, {'name': 'Yacc', 'bytes': '15875'}]} |
<?xml version="1.0" encoding="utf-8"?>
<Response xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
<Copyright>Copyright © 2014 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.</Copyright>
<BrandLogoUri>http://dev.virtualearth.net/Branding/logo_powered_by.png</BrandLogoUri>
<StatusCode>200</StatusCode>
<StatusDescription>OK</StatusDescription>
<AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
<TraceId>082fe60377aa4b97882c330c72dce07c|DB30012733|02.00.162.2400|</TraceId>
<ResourceSets>
<ResourceSet>
<EstimatedTotal>0</EstimatedTotal>
<Resources/>
</ResourceSet>
</ResourceSets>
</Response>
| {'content_hash': '0184499ba96aee2cf134617a9bc023e9', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 271, 'avg_line_length': 62.8, 'alnum_prop': 0.7717622080679406, 'repo_name': 'datarc/aurora', 'id': '1255da9acb8dac7f40828e2efb6279ccf890394d', 'size': '943', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'serviceAPI v2/old/log_traffic/2014-09-04 13:27:33_traffic.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '372040'}, {'name': 'C', 'bytes': '5383839'}, {'name': 'C++', 'bytes': '360225'}, {'name': 'CSS', 'bytes': '32236'}, {'name': 'HTML', 'bytes': '105369'}, {'name': 'JavaScript', 'bytes': '297557'}, {'name': 'Objective-C', 'bytes': '91'}, {'name': 'Processing', 'bytes': '22461'}, {'name': 'Ruby', 'bytes': '2254'}, {'name': 'Shell', 'bytes': '490'}]} |
package org.apache.flink.streaming.api.environment;
import org.apache.flink.annotation.Public;
import org.apache.flink.api.common.InvalidProgramException;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.client.program.ClusterClient;
import org.apache.flink.client.program.JobWithJars;
import org.apache.flink.client.program.ProgramInvocationException;
import org.apache.flink.client.program.rest.RestClusterClient;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.JobManagerOptions;
import org.apache.flink.configuration.RestOptions;
import org.apache.flink.streaming.api.graph.StreamGraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* A {@link StreamExecutionEnvironment} for executing on a cluster.
*/
@Public
public class RemoteStreamEnvironment extends StreamExecutionEnvironment {
private static final Logger LOG = LoggerFactory.getLogger(RemoteStreamEnvironment.class);
/** The hostname of the JobManager. */
private final String host;
/** The port of the JobManager main actor system. */
private final int port;
/** The configuration used to parametrize the client that connects to the remote cluster. */
private final Configuration clientConfiguration;
/** The jar files that need to be attached to each job. */
private final List<URL> jarFiles;
/** The classpaths that need to be attached to each job. */
private final List<URL> globalClasspaths;
/**
* Creates a new RemoteStreamEnvironment that points to the master
* (JobManager) described by the given host name and port.
*
* @param host
* The host name or address of the master (JobManager), where the
* program should be executed.
* @param port
* The port of the master (JobManager), where the program should
* be executed.
* @param jarFiles
* The JAR files with code that needs to be shipped to the
* cluster. If the program uses user-defined functions,
* user-defined input formats, or any libraries, those must be
* provided in the JAR files.
*/
public RemoteStreamEnvironment(String host, int port, String... jarFiles) {
this(host, port, null, jarFiles);
}
/**
* Creates a new RemoteStreamEnvironment that points to the master
* (JobManager) described by the given host name and port.
*
* @param host
* The host name or address of the master (JobManager), where the
* program should be executed.
* @param port
* The port of the master (JobManager), where the program should
* be executed.
* @param clientConfiguration
* The configuration used to parametrize the client that connects to the
* remote cluster.
* @param jarFiles
* The JAR files with code that needs to be shipped to the
* cluster. If the program uses user-defined functions,
* user-defined input formats, or any libraries, those must be
* provided in the JAR files.
*/
public RemoteStreamEnvironment(String host, int port, Configuration clientConfiguration, String... jarFiles) {
this(host, port, clientConfiguration, jarFiles, null);
}
/**
* Creates a new RemoteStreamEnvironment that points to the master
* (JobManager) described by the given host name and port.
*
* @param host
* The host name or address of the master (JobManager), where the
* program should be executed.
* @param port
* The port of the master (JobManager), where the program should
* be executed.
* @param clientConfiguration
* The configuration used to parametrize the client that connects to the
* remote cluster.
* @param jarFiles
* The JAR files with code that needs to be shipped to the
* cluster. If the program uses user-defined functions,
* user-defined input formats, or any libraries, those must be
* provided in the JAR files.
* @param globalClasspaths
* The paths of directories and JAR files that are added to each user code
* classloader on all nodes in the cluster. Note that the paths must specify a
* protocol (e.g. file://) and be accessible on all nodes (e.g. by means of a NFS share).
* The protocol must be supported by the {@link java.net.URLClassLoader}.
*/
public RemoteStreamEnvironment(String host, int port, Configuration clientConfiguration, String[] jarFiles, URL[] globalClasspaths) {
if (!ExecutionEnvironment.areExplicitEnvironmentsAllowed()) {
throw new InvalidProgramException(
"The RemoteEnvironment cannot be used when submitting a program through a client, " +
"or running in a TestEnvironment context.");
}
if (host == null) {
throw new NullPointerException("Host must not be null.");
}
if (port < 1 || port >= 0xffff) {
throw new IllegalArgumentException("Port out of range");
}
this.host = host;
this.port = port;
this.clientConfiguration = clientConfiguration == null ? new Configuration() : clientConfiguration;
this.jarFiles = new ArrayList<>(jarFiles.length);
for (String jarFile : jarFiles) {
try {
URL jarFileUrl = new File(jarFile).getAbsoluteFile().toURI().toURL();
this.jarFiles.add(jarFileUrl);
JobWithJars.checkJarFile(jarFileUrl);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("JAR file path is invalid '" + jarFile + "'", e);
} catch (IOException e) {
throw new RuntimeException("Problem with jar file " + jarFile, e);
}
}
if (globalClasspaths == null) {
this.globalClasspaths = Collections.emptyList();
}
else {
this.globalClasspaths = Arrays.asList(globalClasspaths);
}
}
@Override
public JobExecutionResult execute(String jobName) throws ProgramInvocationException {
StreamGraph streamGraph = getStreamGraph();
streamGraph.setJobName(jobName);
transformations.clear();
return executeRemotely(streamGraph, jarFiles);
}
/**
* Executes the remote job.
*
* @param streamGraph
* Stream Graph to execute
* @param jarFiles
* List of jar file URLs to ship to the cluster
* @return The result of the job execution, containing elapsed time and accumulators.
*/
protected JobExecutionResult executeRemotely(StreamGraph streamGraph, List<URL> jarFiles) throws ProgramInvocationException {
if (LOG.isInfoEnabled()) {
LOG.info("Running remotely at {}:{}", host, port);
}
ClassLoader usercodeClassLoader = JobWithJars.buildUserCodeClassLoader(jarFiles, globalClasspaths,
getClass().getClassLoader());
Configuration configuration = new Configuration();
configuration.addAll(this.clientConfiguration);
configuration.setString(JobManagerOptions.ADDRESS, host);
configuration.setInteger(JobManagerOptions.PORT, port);
configuration.setInteger(RestOptions.PORT, port);
final ClusterClient<?> client;
try {
client = new RestClusterClient<>(configuration, "RemoteStreamEnvironment");
}
catch (Exception e) {
throw new ProgramInvocationException("Cannot establish connection to JobManager: " + e.getMessage(),
streamGraph.getJobGraph().getJobID(), e);
}
client.setPrintStatusDuringExecution(getConfig().isSysoutLoggingEnabled());
try {
return client.run(streamGraph, jarFiles, globalClasspaths, usercodeClassLoader).getJobExecutionResult();
}
catch (ProgramInvocationException e) {
throw e;
}
catch (Exception e) {
String term = e.getMessage() == null ? "." : (": " + e.getMessage());
throw new ProgramInvocationException("The program execution failed" + term,
streamGraph.getJobGraph().getJobID(), e);
}
finally {
try {
client.shutdown();
} catch (Exception e) {
LOG.warn("Could not properly shut down the cluster client.", e);
}
}
}
@Override
public String toString() {
return "Remote Environment (" + this.host + ":" + this.port + " - parallelism = "
+ (getParallelism() == -1 ? "default" : getParallelism()) + ")";
}
/**
* Gets the hostname of the master (JobManager), where the
* program will be executed.
*
* @return The hostname of the master
*/
public String getHost() {
return host;
}
/**
* Gets the port of the master (JobManager), where the
* program will be executed.
*
* @return The port of the master
*/
public int getPort() {
return port;
}
public Configuration getClientConfiguration() {
return clientConfiguration;
}
}
| {'content_hash': '4d1c401ed393525afd9b47133ce84819', 'timestamp': '', 'source': 'github', 'line_count': 250, 'max_line_length': 134, 'avg_line_length': 35.408, 'alnum_prop': 0.7026660641662901, 'repo_name': 'mylog00/flink', 'id': '0af6d9372940049c5e40311f18e6b031daa9eed0', 'size': '9652', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/RemoteStreamEnvironment.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5666'}, {'name': 'CSS', 'bytes': '18100'}, {'name': 'Clojure', 'bytes': '81015'}, {'name': 'CoffeeScript', 'bytes': '91220'}, {'name': 'Dockerfile', 'bytes': '9788'}, {'name': 'HTML', 'bytes': '86821'}, {'name': 'Java', 'bytes': '40279802'}, {'name': 'JavaScript', 'bytes': '8267'}, {'name': 'Python', 'bytes': '249644'}, {'name': 'Scala', 'bytes': '7501313'}, {'name': 'Shell', 'bytes': '391588'}]} |
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.signals import user_logged_in
from django.contrib.auth.models import User
from django.template.context_processors import csrf
from django.views.generic import UpdateView
from django.contrib.auth import login
from django.contrib import messages
from .forms import *
from .models import *
from django.db.models import Q
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse, HttpResponseRedirect
def signup(request):
"""
This is basically a django form view for registering into the website and creating profile of user.
All relevant fields related to profile are set up by the user.
**Args:**
1. ``user_form``
User form is a django form. It's an instance of UserForm.
**Template:**
:template:`core/signup.html`
"""
if request.method == 'POST':
user_form = UserForm(request.POST)
if user_form.is_valid():
new_user = user_form.save()
login(request, new_user)
messages.success(request, 'Signup successful!')
next = request.POST.get('next', '/')
return redirect(next)
else:
for form_error in user_form.errors:
for e in user_form.errors[form_error].as_data():
if (form_error == 'password2'):
messages.error(request, str(e)[2:-2])
else:
messages.error(request, '{}: {}'.format(form_error, str(e)[2:-2]))
if request.user.is_authenticated():
return redirect('contests_index')
args = {}
args.update(csrf(request))
args['user_form'] = UserForm()
return render(request, 'core/signup.html', args)
def logged_in_message(sender, user, request, **kwargs):
messages.success(request, "Welcome {}!".format(user.username))
user_logged_in.connect(logged_in_message)
def home(request):
"""
This is the homepage of our website. For users not logged in this is set to homepage containing links to signup and login forms and set to profile view for logged in users.
**Template:**
:template:`core/profile.html`
:template:`core/home.html`
"""
if request.user.is_authenticated():
return redirect('/profile/')
return render(request, 'core/home.html')
def profile(request):
"""
This is the profile view of users. This further either redirects to other_profile view or the login view.
"""
if request.user.is_authenticated():
return redirect('other_profile', username=request.user.username)
else:
return HttpResponseRedirect(reverse('login') + "?{}".format(request.path))
def other_profile(request, username):
"""
This view is the detailed view of user. It shows all details about a particular user. Any valid regex matching the URL pattern allows you to see the profile of user. If the request.user is the one whose profile has been visited then it allows to edit details through update profile link.
**Args:**
1. ``user``
user is an instance of :model:`auth.User`.
**Template:**
:template:`core/detail.html`
"""
try:
user = User.objects.get(username=username)
except User.DoesNotExist:
return render(request, 'warning.html', {'warning': 'No such user found. Please verify.'})
if user.is_superuser:
return redirect('contests_index')
return render(request, 'core/detail.html', {'user': user})
class ProfileUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView):
"""
This is the update profile option for user, where user can update his old setting and change them. He can change his city, country, institute, and profile picture.
"""
model = Profile
form_class = ProfileUpdateForm
template_name = 'core/update.html'
success_message = 'Updated Succesfully'
def get_success_url(self):
return self.request.POST.get('next', '/profile')
def get_initial(self):
initial = super(ProfileUpdateView, self).get_initial()
habit_object = self.get_object()
initial['city'] = habit_object.city
initial['country'] = habit_object.country
initial['institute'] = habit_object.institute
initial['picture'] = habit_object.picture
return initial
def get_object(self, queryset=None):
return get_object_or_404(self.model, user=self.request.user)
def validate_username(request):
"""
This view is used in the dynamic asynchronous AJAX verification of username in the signup form.
When user types in the username and shifts focus from the usernamr box, a post request is created which calls this view and checks whether the username is available or not.
This views is a JSONdata file consisting of usernames
"""
username = request.GET.get('username', None)
data = {
'is_taken': User.objects.filter(username__iexact=username).exists()
}
return JsonResponse(data)
| {'content_hash': '6aa345cb415e6d7db88969e2a0104850', 'timestamp': '', 'source': 'github', 'line_count': 137, 'max_line_length': 291, 'avg_line_length': 37.45255474452555, 'alnum_prop': 0.6719937633989476, 'repo_name': 'cs251-eclipse/EclipseOJ', 'id': 'e9e6492125fa9257db35cf181ef44b2fde7e95ef', 'size': '5131', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'EclipseOJ/core/views.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '8073'}, {'name': 'HTML', 'bytes': '46137'}, {'name': 'JavaScript', 'bytes': '2559'}, {'name': 'Python', 'bytes': '94711'}, {'name': 'Shell', 'bytes': '348'}, {'name': 'TeX', 'bytes': '12006'}]} |
from databuild.functional import guess_type
from databuild.operator import Operator
from .importer import Importer
from .exporter import BaseSheetExporter
from databuild import settings as default_settings
class BaseWorkBook(object):
sheet_class = None
importer_class = Importer
echo = False
def __init__(self, name='workbook', settings=None):
if settings is None:
settings = default_settings
self.settings = settings
self.name = name
self.sheets = {}
self.operator = Operator(self, settings=settings)
super(BaseWorkBook, self).__init__()
def __getitem__(self, key):
return self.sheets[key]
def add_sheet(self, name, headers):
assert self.sheet_class is not None
sheet = self.sheet_class(workbook=self, name=name, headers=headers)
self.sheets[name] = sheet
return sheet
def get_or_create_sheet(self, name, headers):
if name in self.sheets:
return self.sheets[name]
else:
return self.add_sheet(name, headers)
def remove_sheet(self, sheet):
self.sheets.pop(sheet.name)
def import_data(self, filename, relative_path=None, format='csv', *args, **kwargs):
importer = self.importer_class(self, relative_path=relative_path)
return importer.import_data(format, filename, *args, **kwargs)
def apply_operations(self, *args, **kwargs):
return self.operator.apply_operations(*args, **kwargs)
def apply_operation(self, operation, build_file=None, *args, **kwargs):
return self.operator.apply_operation(operation, build_file, *args, **kwargs)
class BaseWorkSheet(object):
exporter_class = BaseSheetExporter
def __init__(self, workbook, name, headers):
self.workbook = workbook
self.name = name
self.headers = headers
self.exporter = self.exporter_class(self)
super(BaseWorkSheet, self).__init__()
def __getitem__(self, key):
"""
Returns the nth
"""
raise NotImplementedError
def __len__(self):
"""
Returns the row count
"""
raise NotImplementedError
def guess_column_types(self, sample_size=5, na_class=None):
headers = self.headers[:]
for column in headers:
values = self.get_column(column)[:sample_size]
value_type = guess_type(values)
def transform(x):
try:
return value_type(x[column])
except (ValueError, TypeError):
return na_class
self.update_column(column, transform)
def copy(self, dest, headers=None):
src_headers = self.headers
filter_columns = False
if headers is None:
headers = src_headers
else:
filter_columns = True
excluded_headers = set(src_headers) - set(headers)
dest_sheet = self.workbook.add_sheet(name=dest, headers=headers)
if not filter_columns:
dest_sheet.extend(self.all())
else:
for src_doc in self.all():
dest_doc = src_doc.copy()
[dest_doc.pop(k) for k in excluded_headers]
dest_sheet.append(dest_doc)
return dest_sheet
def destroy(self):
self.workbook.remove_sheet(self)
def append_column(self, column_name, callable_or_values=None):
raise NotImplementedError()
def remove_column(self, column_name):
raise NotImplementedError()
def rename_column(self, old_name, new_name):
raise NotImplementedError()
def copy_column(self, old_name, new_name):
raise NotImplementedError()
def update_column(self, column_name, callable_or_values, filter_fn=None):
raise NotImplementedError()
def get_column(self, column_name):
raise NotImplementedError()
def get(self, **lookup):
raise NotImplementedError()
def all(self):
raise NotImplementedError()
def filter(self, fn):
raise NotImplementedError()
def append(self, doc):
raise NotImplementedError()
def pop_rows(self, rows_count):
raise NotImplementedError()
def extend(self, docs):
raise NotImplementedError()
def update_rows(self, fn, callable_or_doc):
raise NotImplementedError()
def delete(self, fn):
raise NotImplementedError()
def apply_operation(self, operation):
assert operation['params']['sheet'] == self.name
return self.workbook.apply_operation(operation)
def export_data(self, format='csv', headers=None, *args, **kwargs):
return self.exporter.export_data(format=format, headers=headers, *args, **kwargs)
def print_data(self):
raise NotImplementedError()
| {'content_hash': '247907c3799bc2de216d3c4af6a09ac5', 'timestamp': '', 'source': 'github', 'line_count': 164, 'max_line_length': 89, 'avg_line_length': 29.609756097560975, 'alnum_prop': 0.6182042833607908, 'repo_name': 'databuild/databuild', 'id': '4d5c5d9056f4090d1602a453254e8c8f313697be', 'size': '4856', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'databuild/adapters/base/models.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Python', 'bytes': '72938'}, {'name': 'Shell', 'bytes': '6707'}]} |
set CDIR=%~dp0
reg add HKCU\Environment /v HQENGINE_VS2008_X86_LIB_DEB_PATH /t REG_SZ /d %CDIR%\Output\Debug\
reg add HKCU\Environment /v HQENGINE_VS2008_X86_LIB_REL_PATH /t REG_SZ /d %CDIR%\Output\Release\
reg add HKCU\Environment /v HQENGINE_VS2008_X86_LIB_STATIC_CRT_DEB_PATH /t REG_SZ /d "%CDIR%\Output\Debug static CRT\"
reg add HKCU\Environment /v HQENGINE_VS2008_X86_LIB_STATIC_CRT_REL_PATH /t REG_SZ /d "%CDIR%\Output\Release static CRT\" | {'content_hash': '41d9d0b8039a454314cafb46dcada413', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 121, 'avg_line_length': 75.16666666666667, 'alnum_prop': 0.7405764966740577, 'repo_name': 'kakashidinho/HQEngine', 'id': 'eee34402f0913b928335f02f0931f8d3ef24ece1', 'size': '451', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'HQEngine/VS2008/setLibPathEnv.bat', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ada', 'bytes': '89080'}, {'name': 'Assembly', 'bytes': '661970'}, {'name': 'Awk', 'bytes': '32706'}, {'name': 'Batchfile', 'bytes': '14796'}, {'name': 'C', 'bytes': '12872998'}, {'name': 'C#', 'bytes': '76556'}, {'name': 'C++', 'bytes': '25893894'}, {'name': 'CLIPS', 'bytes': '5291'}, {'name': 'CMake', 'bytes': '100966'}, {'name': 'CSS', 'bytes': '23584'}, {'name': 'DIGITAL Command Language', 'bytes': '36015'}, {'name': 'GLSL', 'bytes': '7830'}, {'name': 'HLSL', 'bytes': '20473'}, {'name': 'HTML', 'bytes': '2060539'}, {'name': 'Java', 'bytes': '76190'}, {'name': 'Lex', 'bytes': '13371'}, {'name': 'M4', 'bytes': '236533'}, {'name': 'Makefile', 'bytes': '1169529'}, {'name': 'Module Management System', 'bytes': '17591'}, {'name': 'Objective-C', 'bytes': '1535348'}, {'name': 'Objective-C++', 'bytes': '41381'}, {'name': 'Pascal', 'bytes': '69941'}, {'name': 'Perl', 'bytes': '35354'}, {'name': 'RPC', 'bytes': '3150250'}, {'name': 'Roff', 'bytes': '290354'}, {'name': 'SAS', 'bytes': '16347'}, {'name': 'Shell', 'bytes': '986190'}, {'name': 'Smalltalk', 'bytes': '6052'}, {'name': 'TeX', 'bytes': '144346'}, {'name': 'WebAssembly', 'bytes': '14280'}, {'name': 'XSLT', 'bytes': '75795'}, {'name': 'Yacc', 'bytes': '15640'}]} |
'use strict';
let React;
let ReactNoop;
describe('ReactFragment', () => {
beforeEach(function() {
jest.resetModules();
React = require('react');
ReactNoop = require('react-noop-renderer');
});
function span(prop) {
return {type: 'span', children: [], prop};
}
function text(val) {
return {text: val};
}
function div(...children) {
children = children.map(c => (typeof c === 'string' ? {text: c} : c));
return {type: 'div', children, prop: undefined};
}
it('should render a single child via noop renderer', () => {
const element = (
<React.Fragment>
<span>foo</span>
</React.Fragment>
);
ReactNoop.render(element);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span()]);
});
it('should render zero children via noop renderer', () => {
const element = <React.Fragment />;
ReactNoop.render(element);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([]);
});
it('should render multiple children via noop renderer', () => {
const element = (
<React.Fragment>
hello <span>world</span>
</React.Fragment>
);
ReactNoop.render(element);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([text('hello '), span()]);
});
it('should render an iterable via noop renderer', () => {
const element = (
<React.Fragment>
{new Set([<span key="a">hi</span>, <span key="b">bye</span>])}
</React.Fragment>
);
ReactNoop.render(element);
ReactNoop.flush();
expect(ReactNoop.getChildren()).toEqual([span(), span()]);
});
it('should preserve state of children with 1 level nesting', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<Stateful key="a" />
) : (
<React.Fragment>
<Stateful key="a" />
<div key="b">World</div>
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div(), div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state between top-level fragments', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>
<Stateful />
</React.Fragment>
) : (
<React.Fragment>
<Stateful />
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state of children nested at same level', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
</React.Fragment>
) : (
<React.Fragment>
<React.Fragment>
<React.Fragment>
<div />
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div(), div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state in non-top-level fragment nesting', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
) : (
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state of children if nested 2 levels without siblings', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<Stateful key="a" />
) : (
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state of children if nested 2 levels with siblings', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<Stateful key="a" />
) : (
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
<div />
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div(), div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state between array nested in fragment and fragment', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
) : (
<React.Fragment>{[<Stateful key="a" />]}</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state between top level fragment and array', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
[<Stateful key="a" />]
) : (
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state between array nested in fragment and double nested fragment', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>{[<Stateful key="a" />]}</React.Fragment>
) : (
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state between array nested in fragment and double nested array', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>{[<Stateful key="a" />]}</React.Fragment>
) : (
[[<Stateful key="a" />]]
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state between double nested fragment and double nested array', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment>
<React.Fragment>
<Stateful key="a" />
</React.Fragment>
</React.Fragment>
) : (
[[<Stateful key="a" />]]
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state of children when the keys are different', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment key="a">
<Stateful />
</React.Fragment>
) : (
<React.Fragment key="b">
<Stateful />
<span>World</span>
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div(), span()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should not preserve state between unkeyed and keyed fragment', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<React.Fragment key="a">
<Stateful />
</React.Fragment>
) : (
<React.Fragment>
<Stateful />
</React.Fragment>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div()]);
});
it('should preserve state with reordering in multiple levels', function() {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<div>
<React.Fragment key="c">
<span>foo</span>
<div key="b">
<Stateful key="a" />
</div>
</React.Fragment>
<span>boop</span>
</div>
) : (
<div>
<span>beep</span>
<React.Fragment key="c">
<div key="b">
<Stateful key="a" />
</div>
<span>bar</span>
</React.Fragment>
</div>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div(span(), div(div()), span())]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([div(span(), div(div()), span())]);
});
it('should not preserve state when switching to a keyed fragment to an array', function() {
spyOnDev(console, 'error');
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition ? (
<div>
{
<React.Fragment key="foo">
<Stateful />
</React.Fragment>
}
<span />
</div>
) : (
<div>
{[<Stateful />]}
<span />
</div>
);
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div(div(), span())]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual([]);
expect(ReactNoop.getChildren()).toEqual([div(div(), span())]);
if (__DEV__) {
expect(console.error.calls.count()).toBe(1);
expect(console.error.calls.argsFor(0)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop.',
);
}
});
it('should preserve state when it does not change positions', function() {
spyOnDev(console, 'error');
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
function Foo({condition}) {
return condition
? [
<span />,
<React.Fragment>
<Stateful />
</React.Fragment>,
]
: [
<span />,
<React.Fragment>
<Stateful />
</React.Fragment>,
];
}
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
ReactNoop.render(<Foo condition={false} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([span(), div()]);
ReactNoop.render(<Foo condition={true} />);
ReactNoop.flush();
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop.getChildren()).toEqual([span(), div()]);
if (__DEV__) {
expect(console.error.calls.count()).toBe(3);
for (let errorIndex = 0; errorIndex < 3; ++errorIndex) {
expect(console.error.calls.argsFor(errorIndex)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop.',
);
}
}
});
});
| {'content_hash': '2425d3bdd7756f76e25df2cb2b599bdc', 'timestamp': '', 'source': 'github', 'line_count': 773, 'max_line_length': 106, 'avg_line_length': 23.85510996119017, 'alnum_prop': 0.5541214750542299, 'repo_name': 'aickin/react', 'id': '00ae2aa2e92dceed4a709c35d4990db78fe6e586', 'size': '18647', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'packages/react-reconciler/src/__tests__/ReactFragment-test.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '5219'}, {'name': 'C++', 'bytes': '44242'}, {'name': 'CSS', 'bytes': '4644'}, {'name': 'CoffeeScript', 'bytes': '12487'}, {'name': 'HTML', 'bytes': '24855'}, {'name': 'JavaScript', 'bytes': '1226099'}, {'name': 'Makefile', 'bytes': '189'}, {'name': 'Python', 'bytes': '259'}, {'name': 'Shell', 'bytes': '5356'}, {'name': 'TypeScript', 'bytes': '16266'}]} |
namespace appcache {
// static
AppCacheInterceptor* AppCacheInterceptor::GetInstance() {
return Singleton<AppCacheInterceptor>::get();
}
void AppCacheInterceptor::SetHandler(
net::URLRequest* request, AppCacheRequestHandler* handler) {
request->SetUserData(GetInstance(), handler); // request takes ownership
}
AppCacheRequestHandler* AppCacheInterceptor::GetHandler(
net::URLRequest* request) {
return reinterpret_cast<AppCacheRequestHandler*>(
request->GetUserData(GetInstance()));
}
void AppCacheInterceptor::SetExtraRequestInfo(
net::URLRequest* request, AppCacheService* service, int process_id,
int host_id, ResourceType::Type resource_type) {
if (!service || (host_id == kNoHostId))
return;
AppCacheBackendImpl* backend = service->GetBackend(process_id);
if (!backend)
return;
// TODO(michaeln): An invalid host id is indicative of bad data
// from a child process. How should we handle that here?
AppCacheHost* host = backend->GetHost(host_id);
if (!host)
return;
// Create a handler for this request and associate it with the request.
AppCacheRequestHandler* handler =
host->CreateRequestHandler(request, resource_type);
if (handler)
SetHandler(request, handler);
}
void AppCacheInterceptor::GetExtraResponseInfo(net::URLRequest* request,
int64* cache_id,
GURL* manifest_url) {
DCHECK(*cache_id == kNoCacheId);
DCHECK(manifest_url->is_empty());
AppCacheRequestHandler* handler = GetHandler(request);
if (handler)
handler->GetExtraResponseInfo(cache_id, manifest_url);
}
AppCacheInterceptor::AppCacheInterceptor() {
net::URLRequest::RegisterRequestInterceptor(this);
}
AppCacheInterceptor::~AppCacheInterceptor() {
net::URLRequest::UnregisterRequestInterceptor(this);
}
net::URLRequestJob* AppCacheInterceptor::MaybeIntercept(
net::URLRequest* request) {
AppCacheRequestHandler* handler = GetHandler(request);
if (!handler)
return NULL;
return handler->MaybeLoadResource(request);
}
net::URLRequestJob* AppCacheInterceptor::MaybeInterceptRedirect(
net::URLRequest* request,
const GURL& location) {
AppCacheRequestHandler* handler = GetHandler(request);
if (!handler)
return NULL;
return handler->MaybeLoadFallbackForRedirect(request, location);
}
net::URLRequestJob* AppCacheInterceptor::MaybeInterceptResponse(
net::URLRequest* request) {
AppCacheRequestHandler* handler = GetHandler(request);
if (!handler)
return NULL;
return handler->MaybeLoadFallbackForResponse(request);
}
} // namespace appcache
| {'content_hash': '8e96ad2147b08fb490b5a06f17fe0296', 'timestamp': '', 'source': 'github', 'line_count': 85, 'max_line_length': 75, 'avg_line_length': 31.211764705882352, 'alnum_prop': 0.7214474180173389, 'repo_name': 'wistoch/meego-app-browser', 'id': '1c76df4689c05f8bde566d793cebc27d2f39ba83', 'size': '3172', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'webkit/appcache/appcache_interceptor.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AppleScript', 'bytes': '6772'}, {'name': 'Assembly', 'bytes': '1123040'}, {'name': 'Awk', 'bytes': '9422'}, {'name': 'C', 'bytes': '68482407'}, {'name': 'C++', 'bytes': '95729434'}, {'name': 'F#', 'bytes': '381'}, {'name': 'Go', 'bytes': '3744'}, {'name': 'Java', 'bytes': '11354'}, {'name': 'JavaScript', 'bytes': '5466857'}, {'name': 'Logos', 'bytes': '4517'}, {'name': 'Matlab', 'bytes': '5292'}, {'name': 'Objective-C', 'bytes': '4890308'}, {'name': 'PHP', 'bytes': '97796'}, {'name': 'Perl', 'bytes': '521006'}, {'name': 'Prolog', 'bytes': '435'}, {'name': 'Python', 'bytes': '4833145'}, {'name': 'Shell', 'bytes': '1346070'}, {'name': 'Tcl', 'bytes': '200213'}, {'name': 'XML', 'bytes': '13001'}]} |
HTMLExercises::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
# eager_load ?
config.eager_load = false
end
| {'content_hash': '07e69a37f4218839f7780e2f7c33b4a3', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 84, 'avg_line_length': 36.0, 'alnum_prop': 0.762012012012012, 'repo_name': 'fatbigbright/HTMLExercises', 'id': 'a9e07f801c7b35ba3b9206b0ffac5402498d5d26', 'size': '1332', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'config/environments/development.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6924'}, {'name': 'JavaScript', 'bytes': '43091'}, {'name': 'Ruby', 'bytes': '16221'}]} |
.app-notify-common{width:100%} | {'content_hash': '5c136d9ff608571e70a374be6f792cf6', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 30, 'avg_line_length': 30.0, 'alnum_prop': 0.7666666666666667, 'repo_name': 'odirus/apidoc', 'id': '5fa3fc2925132ad8526d42c0a74201be292bc545', 'size': '30', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/js/apps/notify/css/common.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4379'}, {'name': 'JavaScript', 'bytes': '400870'}, {'name': 'Smarty', 'bytes': '250'}]} |
/* ====================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
namespace Oranikle.Report.Engine
{
///<summary>
/// Collection of matrix cells.
///</summary>
[Serializable]
public class MatrixCells : ReportLink
{
List<MatrixCell> _Items; // list of MatrixCell
public MatrixCells(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
MatrixCell m;
_Items = new List<MatrixCell>();
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "MatrixCell":
m = new MatrixCell(r, this, xNodeLoop);
break;
default:
m=null; // don't know what this is
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown MatrixCells element '" + xNodeLoop.Name + "' ignored.");
break;
}
if (m != null)
_Items.Add(m);
}
if (_Items.Count == 0)
OwnerReport.rl.LogError(8, "For MatrixCells at least one MatrixCell is required.");
else
_Items.TrimExcess();
}
override public void FinalPass()
{
foreach (MatrixCell m in _Items)
{
m.FinalPass();
}
return;
}
public List<MatrixCell> Items
{
get { return _Items; }
}
}
}
| {'content_hash': 'f3a3647e4ead2c9ec73d872726f7feea', 'timestamp': '', 'source': 'github', 'line_count': 80, 'max_line_length': 98, 'avg_line_length': 18.575, 'alnum_prop': 0.5605652759084792, 'repo_name': 'parvbhullar/rdlc.report.engine', 'id': '296ab71f817e693d2a257a43121c89447d45a4fd', 'size': '1486', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Oranikle.Report.Engine/Definition/MatrixCells.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '5297074'}, {'name': 'Smalltalk', 'bytes': '204692'}]} |
package org.springframework.aop.framework;
import org.springframework.core.NamedThreadLocal;
/**
* Class containing static methods used to obtain information about the current AOP invocation.
*
* <p>The {@code currentProxy()} method is usable if the AOP framework is configured to
* expose the current proxy (not the default). It returns the AOP proxy in use. Target objects
* or advice can use this to make advised calls, in the same way as {@code getEJBObject()}
* can be used in EJBs. They can also use it to find advice configuration.
*
* <p>Spring's AOP framework does not expose proxies by default, as there is a performance cost
* in doing so.
*
* <p>The functionality in this class might be used by a target object that needed access
* to resources on the invocation. However, this approach should not be used when there is
* a reasonable alternative, as it makes application code dependent on usage under AOP and
* the Spring AOP framework in particular.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 13.03.2003
*/
public abstract class AopContext {
/**
* ThreadLocal holder for AOP proxy associated with this thread.
* Will contain {@code null} unless the "exposeProxy" property on
* the controlling proxy configuration has been set to "true".
* @see ProxyConfig#setExposeProxy
*/
private static final ThreadLocal<Object> currentProxy = new NamedThreadLocal<Object>("Current AOP proxy");
/**
* Try to return the current AOP proxy. This method is usable only if the
* calling method has been invoked via AOP, and the AOP framework has been set
* to expose proxies. Otherwise, this method will throw an IllegalStateException.
* @return Object the current AOP proxy (never returns {@code null})
* @throws IllegalStateException if the proxy cannot be found, because the
* method was invoked outside an AOP invocation context, or because the
* AOP framework has not been configured to expose the proxy
*/
public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(
"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
}
return proxy;
}
/**
* Make the given proxy available via the {@code currentProxy()} method.
* <p>Note that the caller should be careful to keep the old value as appropriate.
* @param proxy the proxy to expose (or {@code null} to reset it)
* @return the old proxy, which may be {@code null} if none was bound
* @see #currentProxy()
*/
static Object setCurrentProxy(Object proxy) {
Object old = currentProxy.get();
if (proxy != null) {
currentProxy.set(proxy);
}
else {
currentProxy.remove();
}
return old;
}
}
| {'content_hash': '68a481fcab4aa3344c47f8a226339e34', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 107, 'avg_line_length': 37.82432432432432, 'alnum_prop': 0.7320471596998929, 'repo_name': 'qobel/esoguproject', 'id': '13a86ecb899bebbf3acf6b3d17d783123694a7c2', 'size': '3419', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'spring-framework/spring-aop/src/main/java/org/springframework/aop/framework/AopContext.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '48888'}, {'name': 'CSS', 'bytes': '12646'}, {'name': 'GAP', 'bytes': '6137'}, {'name': 'Groovy', 'bytes': '48189'}, {'name': 'HTML', 'bytes': '45255'}, {'name': 'Java', 'bytes': '31552808'}, {'name': 'JavaScript', 'bytes': '144'}, {'name': 'Protocol Buffer', 'bytes': '265'}, {'name': 'Ruby', 'bytes': '1825'}, {'name': 'Shell', 'bytes': '8180'}, {'name': 'Smarty', 'bytes': '702'}, {'name': 'XSLT', 'bytes': '2945'}]} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.