text stringlengths 2 1.04M | meta dict |
|---|---|
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Syntax where
import Prelude hiding (lookup)
import Data.Word(Word64)
import Data.Data(Data, Typeable)
import Data.Text(Text)
import qualified Data.Text as Text
import Data.Char(isUpper, isSymbol)
import Data.Hashable(Hashable, hashWithSalt)
import Data.HashMap.Strict(lookup, keys, foldrWithKey,
filterWithKey, fromListWith, unionWith, keysSet)
import qualified Data.HashSet as Set
import Prettyprinter(Doc, Pretty, pretty, (<+>), hardline,
parens, brackets, layoutPretty, defaultLayoutOptions)
import Prettyprinter.Render.Text(renderStrict)
import Data.Generics.Uniplate.Data(universe, universeBi)
import Data.Foldable(foldMap')
type Line = Word64
type Column = Word64
data Position = Position Line Column
deriving (Show, Eq, Ord, Data, Typeable)
type StartPosition = Position
type EndPosition = Position
data Location = Location StartPosition EndPosition FilePath
deriving (Show, Data, Typeable)
data Id = Id Text Location
deriving (Show, Data, Typeable)
instance Eq Id where
Id t1 _ == Id t2 _ = t1 == t2
instance Hashable Id where
hashWithSalt s (Id t _) = hashWithSalt s t
data Name = Name [Text] Id
deriving (Show, Data, Typeable, Eq)
instance Hashable Name where
hashWithSalt s (Name a b) = hashWithSalt s (a, b)
data ModuleDeclaration =
ModuleDeclaration Name [ImportDeclaration] [Declaration]
deriving (Show, Data, Typeable)
getDecls (ModuleDeclaration _ _ decls) = decls
getName (ModuleDeclaration name _ _) = name
getImports (ModuleDeclaration _ imports _) = imports
{-
Uses a set so that the name of a module appears only once in cases as for example:
```
import Viewer.Obj(getFaces)
import Viewer.Obj as Obj
```
-}
importedModules (ModuleDeclaration _ imports _) =
Set.fromList [name | ImportDeclaration name _ _ <- imports]
data Literal
= Numeral Double
| Text Text
deriving (Show, Data, Typeable)
data Associativity = None | LeftAssociative | RightAssociative
deriving (Show, Data, Typeable)
type Precedence = Double
type OperatorAlias = Name
type Binding = Name
-- The imported Ids in an `import`
type Spec = Maybe [Id]
data ImportDeclaration = ImportDeclaration Name Spec (Maybe Name)
deriving (Show, Data, Typeable)
data Declaration
= TypeDeclaration Binding [Id] [(Binding, [Type])]
| AliasDeclaration Binding Type
| FixityDeclaration Associativity Precedence Binding OperatorAlias
| TypeSignature Binding Type
| ExpressionDeclaration Pattern Expression
-- simplified to an expression declaration
| FunctionDeclaration Binding [Pattern] Expression
deriving (Show, Data, Typeable)
data Type
= TypeArrow Type Type
| TypeInfixOperator Type Name Type
| TypeApplication Type Type
| TypeConstructor Name
| ParenthesizedType Type
| ForAll [Id] Type
| TypeVariable Id
| SkolemConstant Id
deriving (Show, Data, Typeable)
data Pattern
= VariablePattern Binding
| LiteralPattern Literal
| Wildcard Id
| ConstructorPattern Name [Pattern]
| ParenthesizedPattern Pattern
| ArrayPattern [Pattern]
| PatternInfixOperator Pattern Name Pattern
| AliasPattern Binding Pattern
deriving (Show, Data, Typeable)
data Expression
= Variable Name
| LiteralExpression Literal
| ConstructorExpression Name
| FunctionApplication Expression Expression
| LetExpression [Declaration] Expression
-- TODO think about a nicer way to add case lambdas
-- It should have a way to match on more than just a single value
-- Then function declarations could be easily turned into case lambdas as well
-- | CaseLambdaExpression [(Pattern, Expression)]
| ParenthesizedExpression Expression
| ArrayExpression [Expression]
| InfixOperator Expression Name Expression
| PrefixNegation Expression
-- Await expressions are only allowed in the form
-- pat = await expr
| AwaitExpression Expression
| IfExpression Expression Expression Expression
| CaseExpression Expression [(Pattern, Expression)]
| LambdaExpression [Pattern] Expression
-- TODO think about how types could be added to expressions
-- We could define type annotation as a function with type application
-- | TypeAnnotation Expression Type
deriving (Show, Data, Typeable)
commas = mintercalate (text ", ")
mintercalate _ [] = mempty
mintercalate s xs = foldr1 (\x r -> x `mappend` s `mappend` r) xs
qualify (Name modQs modName) (Name [] name) =
Name (modQs ++ [getText modName]) name
qualify _ n = n
instance Pretty Location where
pretty (Location (Position line column) _ filePath) =
pretty filePath
<> text ":" <> pretty line
<> text ":" <> pretty column
instance Pretty Type where
pretty (TypeArrow a b) =
parens (pretty a <+> text "->" <+> pretty b)
pretty (TypeInfixOperator a op b) =
parens (pretty a <+> pretty op <+> pretty b)
pretty (TypeConstructor n) = pretty n
pretty (TypeVariable n) = pretty n
pretty (SkolemConstant s) = text "skolem." <> pretty s
pretty (TypeApplication a b) = parens (pretty a <+> pretty b)
pretty (ParenthesizedType t) = parens (pretty t)
pretty (ForAll ts t) =
text "forall" <+> mintercalate (text " ") (fmap pretty ts)
<> text "." <+> pretty t
instance Pretty Literal where
pretty (Numeral n) = pretty n
pretty (Text t) = prettyEscaped t
instance Pretty Pattern where
pretty (VariablePattern v) = pretty v
pretty (LiteralPattern l) = pretty l
pretty (Wildcard _) = text "_"
pretty (ConstructorPattern name []) =
pretty name
pretty (ConstructorPattern name ps) =
parens (pretty name
<+> mintercalate (text " ") (fmap pretty ps))
pretty (PatternInfixOperator a op b) =
parens (pretty a <+> pretty op <+> pretty b)
pretty (ParenthesizedPattern p) =
parens (pretty p)
pretty (AliasPattern v p) =
pretty v <+> text "as" <+> pretty p
pretty (ArrayPattern ps) =
brackets (commas (fmap pretty ps))
instance Pretty Name where
pretty = intercalateName (text ".") (text ".")
instance Pretty Id where
pretty (Id i _) = text i
{- Rendering Names -}
renderName modName = show (pretty modName)
toPath name =
show (intercalateName (text "/") (text "/") name <> text ".hyp")
-- Join the module name with underscores instead of dots
-- The underscore is used as escape character in file names,
-- because dots cannot be used in Lua due to their special meaning:
-- `local module = require "folder.file"`
-- TODO Disallow/escape underscores in module names or find a better escape character
flatModName = intercalateName (text "_") (text "_")
{-# INLINE flatModName #-}
flatName = intercalateName (text "_") (text ".")
{-# INLINE flatName #-}
intercalateName _ _ (Name [] i) = pretty i
intercalateName qualSep idSep (Name qs i) =
mintercalate qualSep (fmap text qs) <> idSep <> pretty i
{-# INLINE intercalateName #-}
renderError p = show (prettyError p)
renderSetToError p = show (text "Set.fromList" <+> prettyError (Set.toList p))
prettyError p = pretty p <> " at " <> pretty (mergeLocationInfos (locationInfos p))
mergeLocationInfos locations@(Location _ _ filePath:_) =
let positions = mconcat [[startPosition, endPosition] | Location startPosition endPosition _ <- locations] in
Location (minimum positions) (maximum positions) filePath
mergeLocationInfos _ = builtinLocation
text :: Text -> Doc a
text = pretty
prettyNumeral d =
if not (isInfinite d) && d == intToDouble (round d)
then pretty (round d :: Int)
else pretty d
-- `show` escapes and creates double quotes
prettyEscaped = text . Text.pack . show
render d = renderStrict (layoutPretty defaultLayoutOptions d)
renderEnv m = render (foldrWithKey (\k v r ->
pretty k <+> text ":" <+> pretty v <> hardline <> r) mempty m)
{-# INLINE renderEnv #-}
nameToList (Name is i) = is ++ [getText i]
fromText t =
let splitted = Text.split (== '.') t
in Name (init splitted) (Id (last splitted) builtinLocation)
inputToModuleName s =
if Text.isSuffixOf ".hyp" s || Text.elem '/' s || Text.elem '\\' s
then fail "Expected a module name instead of a path"
else return (fromText s)
fromId = Name []
toId (Name [] identifier) = identifier
toId n = error ("Tried to turn name " <> renderError n
<> " into an identifier but it had qualifiers")
isConstructor (Name _ i) = firstIs isUpper (getText i)
isOperator (Name _ i) = firstIs isSym (getText i)
firstIs f = Text.foldr (const . f) False
{-# INLINE firstIs #-}
-- these are not symbols in unicode, but in the language
-- otherwise e.g 2 - 2 would not be lexed as minus
isSym x = isSymbol x || Text.elem x "!%&*/?@\\-:"
{-# INLINE isSym #-}
builtinLocation = Location (Position 0 0) (Position 0 0) "builtin"
prefixedId x = Id ("_v" <> x) builtinLocation
{-# INLINE prefixedId #-}
getQualifiers (Name q _) = q
getText (Id t _) = t
differenceKeys m ks = filterWithKey (const . flip notElem ks) m
{-# INLINE differenceKeys #-}
intersectionKeys m ks = filterWithKey (const . flip elem ks) m
{-# INLINE intersectionKeys #-}
getBindings p =
let
f (VariablePattern v) = [v]
f (AliasPattern i _) = [i]
f _ = []
in foldMap' f (universe p)
nNewVars n = fmap (prefixedId . intToText) [1..n]
makeOp op a b =
FunctionApplication (FunctionApplication
(if isConstructor op then
ConstructorExpression op else Variable op) a) b
makeOpPat op a b =
ConstructorPattern op [a, b]
makeOpTyp op a b =
TypeApplication (TypeApplication (TypeConstructor op) a) b
findEither o m = maybe (Left (notFoundMessage o m)) Right (lookup o m)
mfind o m = maybe (fail (notFoundMessage o m)) return (lookup o m)
{-# INLINE mfind #-}
firstA f (a, b) = fmap (\a' -> (a', b)) (f a)
notFoundMessage o m =
"Unknown " <> renderError o <> " in " <> renderError (keys m)
{-# INLINE notFoundMessage #-}
locationInfos other = [l | Id _ l <- universeBi other]
{-# INLINE locationInfos #-}
-- Functions for sets that error on overwriting a key
unionUnique m1 m2 = sequenceA (unionWith (bind2 shadowingError) (fmap Right m1) (fmap Right m2))
fromListUnique l = sequenceA (fromListWith (bind2 shadowingError) (fmap ((,) <*> Right) l))
toSetUniqueM l = either fail return (fmap keysSet (fromListUnique l))
bind2 f a b = do
a' <- a
b' <- b
f a' b'
shadowingError v1 v2 =
Left (renderError v1 <> " shadows " <> renderError v2)
intToDouble :: Int -> Double
intToDouble = fromIntegral
intToText :: Int -> Text
intToText = Text.pack . show
uintToText :: Word64 -> Text
uintToText = Text.pack . show
| {
"content_hash": "3aaf1004f37a71fc533defabc514e52d",
"timestamp": "",
"source": "github",
"line_count": 359,
"max_line_length": 113,
"avg_line_length": 30.00557103064067,
"alnum_prop": 0.6881730412179725,
"repo_name": "kindl/Hypatia",
"id": "7942d1c64a60f31ff9dfbc182e69582cfb612fd1",
"size": "10772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Syntax.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "79755"
}
],
"symlink_target": ""
} |
import Ember from 'ember';
export default Ember.Route.extend({
model: function(params) {
var store = this.get('store');
var ports;
return store.find('container', params.container_id).then(function(container) {
return container.followLink('ports').then(function(p) {
ports = p;
return container;
});
}).then(function(container) {
var opt = {
include: ['volume'],
filter: {instanceId: container.get('id')}
};
// Find all the mounts for this container
return store.find('mount', null, opt).then(function(containerMounts) {
var mounts = container.get('mounts');
if ( !Ember.isArray(mounts) )
{
mounts = [];
container.set('mounts',mounts);
}
mounts.replace(0,mounts.get('length'), containerMounts.get('content'));
var promises = [];
mounts.forEach(function(mount) {
// And get the volumes for those mounts and all their mounts (for "shared with")
promises.push(mount.get('volume').importLink('mounts'));
});
return Ember.RSVP.all(promises,'Get container mounts');
}).then(function(volumes) {
var promises = [];
volumes.forEach(function(volume) {
volume.get('mounts').forEach(function(mount) {
// Find the related containers, but skip this one
if ( mount.get('instanceId') === container.get('id') )
{
return;
}
if ( ['removed','purged'].indexOf(mount.get('state')) !== -1 )
{
return;
}
var promise = store.find('container',mount.get('instanceId')).then(function(relatedInstance) {
if ( !volume.get('sharedWith') )
{
volume.set('sharedWith',[]);
}
volume.get('sharedWith').pushObject(relatedInstance);
});
promises.push(promise);
});
});
return Ember.RSVP.all(promises).then(function() {
return volumes;
});
}).then(function(volumesWithInstances) {
return Ember.Object.create({
container: container,
relatedVolumes: volumesWithInstances,
ports: ports,
});
}).catch(function(err) {
return Ember.Object.create({
container: container,
mountError: err,
relatedVolumes: [],
ports: [],
});
});
});
},
setupController: function(controller, data) {
this._super(controller, data.get('container'));
controller.setProperties({
mountError: data.get('mountError'),
relatedVolumes: data.get('relatedVolumes'),
ports: data.get('ports'),
});
},
});
| {
"content_hash": "6f10a11f952120099c553f8e201dcf01",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 106,
"avg_line_length": 30.021505376344088,
"alnum_prop": 0.5415472779369628,
"repo_name": "jjperezaguinaga/ui",
"id": "f09b643c197b10d7d9d12e763d4320f886dfd427",
"size": "2792",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/container/route.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "43491"
},
{
"name": "HTML",
"bytes": "220615"
},
{
"name": "JavaScript",
"bytes": "479501"
},
{
"name": "Shell",
"bytes": "6537"
}
],
"symlink_target": ""
} |
Description
-----------
Decompresses configured fields. Multiple fields can be specified to be decompressed using
different decompression algorithms. Plugin supports ``SNAPPY``, ``ZIP``, and ``GZIP`` types of
decompression of fields.
Configuration
-------------
**decompressor:** Specifies the configuration for decompressing fields; in JSON configuration,
this is specified as ``<field>:<decompressor>[,<field>:<decompressor>]*``.
**schema:** Specifies the output schema; the fields that are decompressed will have the same field
name but they will be of type ``BYTES`` or ``STRING``.
| {
"content_hash": "42fe07e1f47bef592a69182531a08ab8",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 99,
"avg_line_length": 42.214285714285715,
"alnum_prop": 0.7343485617597293,
"repo_name": "ananya-bhattacharya/hydrator-plugins",
"id": "f56ce62a160981c7445496a56606fd72da0e369d",
"size": "618",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "transform-plugins/docs/Decompressor-transform.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2133400"
}
],
"symlink_target": ""
} |
/*
Deployment script for ObservationsSACTN
This code was generated by a tool.
Changes to this file may cause incorrect behavior and will be lost if
the code is regenerated.
*/
GO
SET ANSI_NULLS, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CONCAT_NULL_YIELDS_NULL, QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
GO
:setvar DatabaseName "ObservationsSACTN"
:setvar DefaultFilePrefix "ObservationsSACTN"
:setvar DefaultDataPath "D:\Program Files\Microsoft SQL Server\MSSQL15.SAEON2019\MSSQL\DATA\"
:setvar DefaultLogPath "D:\Program Files\Microsoft SQL Server\MSSQL15.SAEON2019\MSSQL\DATA\"
GO
:on error exit
GO
/*
Detect SQLCMD mode and disable script execution if SQLCMD mode is not supported.
To re-enable the script after enabling SQLCMD mode, execute the following:
SET NOEXEC OFF;
*/
:setvar __IsSqlCmdEnabled "True"
GO
IF N'$(__IsSqlCmdEnabled)' NOT LIKE N'True'
BEGIN
PRINT N'SQLCMD mode must be enabled to successfully execute this script.';
SET NOEXEC ON;
END
GO
USE [$(DatabaseName)];
--GO
--IF EXISTS (SELECT 1
-- FROM [master].[dbo].[sysdatabases]
-- WHERE [name] = N'$(DatabaseName)')
-- BEGIN
-- ALTER DATABASE [$(DatabaseName)]
-- SET TEMPORAL_HISTORY_RETENTION ON
-- WITH ROLLBACK IMMEDIATE;
-- END
GO
/*
The column [dbo].[DigitalObjectIdentifiers].[Code] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column [dbo].[DigitalObjectIdentifiers].[DOIType] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column [dbo].[DigitalObjectIdentifiers].[MetadataHtml] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column [dbo].[DigitalObjectIdentifiers].[MetadataJson] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column [dbo].[DigitalObjectIdentifiers].[MetadataJsonSha256] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column [dbo].[DigitalObjectIdentifiers].[MetadataUrl] on table [dbo].[DigitalObjectIdentifiers] must be added, but the column has no default value and does not allow NULL values. If the table contains data, the ALTER script will not work. To avoid this issue you must either: add a default value to the column, mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The column Name on table [dbo].[DigitalObjectIdentifiers] must be changed from NULL to NOT NULL. If the table contains data, the ALTER script may not work. To avoid this issue, you must add values to this column for all rows or mark it as allowing NULL values, or enable the generation of smart-defaults as a deployment option.
The type for column Name in table [dbo].[DigitalObjectIdentifiers] is currently VARCHAR (1000) NULL but is being changed to VARCHAR (500) NOT NULL. Data loss could occur.
*/
--IF EXISTS (select top 1 1 from [dbo].[DigitalObjectIdentifiers])
-- RAISERROR (N'Rows were detected. The schema update is terminating because data loss might occur.', 16, 127) WITH NOWAIT
GO
PRINT N'Dropping [dbo].[DigitalObjectIdentifiers].[IX_DigitalObjectIdentifiers_Name]...';
GO
DROP INDEX [IX_DigitalObjectIdentifiers_Name]
ON [dbo].[DigitalObjectIdentifiers];
GO
PRINT N'Dropping [dbo].[Observation].[IX_Observation_ValueDecade]...';
GO
DROP INDEX [IX_Observation_ValueDecade]
ON [dbo].[Observation];
GO
PRINT N'Dropping [dbo].[Observation].[IX_Observation_ValueYear]...';
GO
DROP INDEX [IX_Observation_ValueYear]
ON [dbo].[Observation];
GO
PRINT N'Dropping [dbo].[Sensor].[IX_Sensor_CodeName]...';
GO
DROP INDEX [IX_Sensor_CodeName]
ON [dbo].[Sensor];
GO
PRINT N'Dropping [dbo].[Observation].[IX_Observation_ValueDateDesc]...';
GO
DROP INDEX [IX_Observation_ValueDateDesc]
ON [dbo].[Observation];
GO
PRINT N'Dropping [dbo].[UX_Sensor_Code]...';
GO
ALTER TABLE [dbo].[Sensor] DROP CONSTRAINT [UX_Sensor_Code];
GO
PRINT N'Altering [dbo].[DigitalObjectIdentifiers]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers] ALTER COLUMN [Name] VARCHAR (500) NOT NULL;
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers]
ADD [AlternateID] UNIQUEIDENTIFIER CONSTRAINT [DF_DigitalObjectIdentifiers_AlternateID] DEFAULT NewId() NULL,
[ParentID] INT NULL,
[DOIType] TINYINT NOT NULL,
[Code] VARCHAR (200) NOT NULL,
[MetadataJson] VARCHAR (MAX) NOT NULL,
[MetadataJsonSha256] BINARY (32) NOT NULL,
[MetadataHtml] VARCHAR (MAX) NOT NULL,
[MetadataUrl] VARCHAR (250) NOT NULL,
[ObjectStoreUrl] VARCHAR (250) NULL,
[QueryUrl] VARCHAR (250) NULL,
[ODPMetadataID] UNIQUEIDENTIFIER NULL,
[ODPMetadataNeedsUpdate] BIT NULL,
[ODPMetadataIsValid] BIT NULL,
[ODPMetadataErrors] VARCHAR (MAX) NULL;
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[UX_DigitalObjectIdentifiers_DOIType_Code]...';
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers]
ADD CONSTRAINT [UX_DigitalObjectIdentifiers_DOIType_Code] UNIQUE NONCLUSTERED ([DOIType] ASC, [Code] ASC);
GO
PRINT N'Creating [dbo].[UX_DigitalObjectIdentifiers_DOIType_Name]...';
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers]
ADD CONSTRAINT [UX_DigitalObjectIdentifiers_DOIType_Name] UNIQUE NONCLUSTERED ([DOIType] ASC, [Name] ASC);
GO
PRINT N'Creating [dbo].[DigitalObjectIdentifiers].[IX_DigitalObjectIdentifiers_DOIType]...';
GO
CREATE NONCLUSTERED INDEX [IX_DigitalObjectIdentifiers_DOIType]
ON [dbo].[DigitalObjectIdentifiers]([DOIType] ASC);
GO
PRINT N'Creating [dbo].[DigitalObjectIdentifiers].[IX_DigitalObjectIdentifiers_ParentID]...';
GO
CREATE NONCLUSTERED INDEX [IX_DigitalObjectIdentifiers_ParentID]
ON [dbo].[DigitalObjectIdentifiers]([ParentID] ASC);
GO
PRINT N'Altering [dbo].[ImportBatchSummary]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER TABLE [dbo].[ImportBatchSummary]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[ImportBatchSummary].[IX_ImportBatchSummary_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_ImportBatchSummary_DigitalObjectIdentifierID]
ON [dbo].[ImportBatchSummary]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Altering [dbo].[Observation]...';
GO
ALTER TABLE [dbo].[Observation] DROP COLUMN [ValueYear], COLUMN [ValueDecade];
GO
ALTER TABLE [dbo].[Observation]
ADD [ValueYear] AS (Year([ValueDate])),
[ValueDecade] AS (Year([ValueDate]) / 10 * 10);
GO
PRINT N'Creating [dbo].[Observation].[IX_Observation_ValueDecade]...';
GO
CREATE NONCLUSTERED INDEX [IX_Observation_ValueDecade]
ON [dbo].[Observation]([ValueDecade] ASC)
ON [Observations];
GO
PRINT N'Creating [dbo].[Observation].[IX_Observation_ValueYear]...';
GO
CREATE NONCLUSTERED INDEX [IX_Observation_ValueYear]
ON [dbo].[Observation]([ValueYear] ASC)
ON [Observations];
GO
PRINT N'Creating [dbo].[Observation].[IX_Observation_SensorID_PhenomenonOfferingID_PhenomenonUOMID_ImportBatchID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Observation_SensorID_PhenomenonOfferingID_PhenomenonUOMID_ImportBatchID]
ON [dbo].[Observation]([SensorID] ASC, [PhenomenonOfferingID] ASC, [PhenomenonUOMID] ASC, [ImportBatchID] ASC)
ON [Observations];
GO
PRINT N'Altering [dbo].[Organisation]...';
GO
ALTER TABLE [dbo].[Organisation]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
PRINT N'Creating [dbo].[Organisation].[IX_Organisation_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Organisation_DigitalObjectIdentifierID]
ON [dbo].[Organisation]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Altering [dbo].[Programme]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER TABLE [dbo].[Programme]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[Programme].[IX_Programme_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Programme_DigitalObjectIdentifierID]
ON [dbo].[Programme]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Altering [dbo].[Project]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER TABLE [dbo].[Project]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[Project].[IX_Project_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Project_DigitalObjectIdentifierID]
ON [dbo].[Project]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Altering [dbo].[Sensor]...';
GO
ALTER TABLE [dbo].[Sensor] ALTER COLUMN [Code] VARCHAR (75) NOT NULL;
GO
PRINT N'Creating [dbo].[UX_Sensor_Code]...';
GO
ALTER TABLE [dbo].[Sensor]
ADD CONSTRAINT [UX_Sensor_Code] UNIQUE NONCLUSTERED ([Code] ASC);
GO
PRINT N'Creating [dbo].[UX_Sensor_Name]...';
GO
ALTER TABLE [dbo].[Sensor]
ADD CONSTRAINT [UX_Sensor_Name] UNIQUE NONCLUSTERED ([Name] ASC);
GO
PRINT N'Creating [dbo].[Sensor].[IX_Sensor_CodeName]...';
GO
CREATE NONCLUSTERED INDEX [IX_Sensor_CodeName]
ON [dbo].[Sensor]([Code] ASC, [Name] ASC);
GO
PRINT N'Altering [dbo].[Site]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER TABLE [dbo].[Site]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[Site].[IX_Site_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Site_DigitalObjectIdentifierID]
ON [dbo].[Site]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Altering [dbo].[Station]...';
GO
ALTER TABLE [dbo].[Station]
ADD [DigitalObjectIdentifierID] INT NULL;
GO
PRINT N'Creating [dbo].[Station].[IX_Station_DigitalObjectIdentifierID]...';
GO
CREATE NONCLUSTERED INDEX [IX_Station_DigitalObjectIdentifierID]
ON [dbo].[Station]([DigitalObjectIdentifierID] ASC);
GO
PRINT N'Creating [dbo].[FK_DigitalObjectIdentifiers_ParentID]...';
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers] WITH NOCHECK
ADD CONSTRAINT [FK_DigitalObjectIdentifiers_ParentID] FOREIGN KEY ([ParentID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_ImportBatchSummary_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[ImportBatchSummary] WITH NOCHECK
ADD CONSTRAINT [FK_ImportBatchSummary_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_Organisation_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[Organisation] WITH NOCHECK
ADD CONSTRAINT [FK_Organisation_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_Programme_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[Programme] WITH NOCHECK
ADD CONSTRAINT [FK_Programme_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_Project_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[Project] WITH NOCHECK
ADD CONSTRAINT [FK_Project_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_Site_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[Site] WITH NOCHECK
ADD CONSTRAINT [FK_Site_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Creating [dbo].[FK_Station_DigitalObjectIdentifierID]...';
GO
ALTER TABLE [dbo].[Station] WITH NOCHECK
ADD CONSTRAINT [FK_Station_DigitalObjectIdentifierID] FOREIGN KEY ([DigitalObjectIdentifierID]) REFERENCES [dbo].[DigitalObjectIdentifiers] ([ID]);
GO
PRINT N'Refreshing [dbo].[vUserDownloads]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vUserDownloads]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vObservationExpansion]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vObservationExpansion]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIObservations]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIObservations]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vObservation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vObservation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vObservationJSON]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vObservationJSON]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vStationObservations]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vStationObservations]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vInstrumentOrganisation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vInstrumentOrganisation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vOrganisationInstrument]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vOrganisationInstrument]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vOrganisationSite]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vOrganisationSite]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vOrganisationStation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vOrganisationStation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSiteOrganisation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSiteOrganisation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vStationOrganisation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vStationOrganisation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vProject]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vProject]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vProjectStation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vProjectStation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vDataLog]...';
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vDataLog]';
GO
PRINT N'Refreshing [dbo].[vInstrumentSensor]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vInstrumentSensor]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensor]...';
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensor]';
GO
PRINT N'Refreshing [dbo].[vSensorDates]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorDates]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorLocation]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorLocation]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vStation]...';
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vStation]';
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIInstrumentDates]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIInstrumentDates]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIStationDates]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIStationDates]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vStationInstrument]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vStationInstrument]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Altering [dbo].[vImportBatchSummary]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER VIEW [dbo].[vImportBatchSummary]
AS
Select
ImportBatchSummary.*,
-- case when Exists(
--Select
-- *
--from
-- Observation
-- inner join Status
-- on (Observation.StatusID = Status.ID)
-- where
-- ((Observation.ImportBatchID = ImportBatchSummary.ImportBatchID) and
-- (Observation.SensorID = ImportBatchSummary.SensorID) and
-- (Observation.PhenomenonOfferingID = ImportBatchSummary.PhenomenonOfferingID) and
-- (Observation.PhenomenonUOMID = ImportBatchSummary.PhenomenonUOMID) and
-- (Status.Name = 'Verified'))
-- ) then 1
-- else 0
-- end HasVerified,
-- (
-- Select
-- Count(*)
-- from
-- Observation
--inner join Status
-- on (Observation.StatusID = Status.ID)
-- where
-- ((Observation.ImportBatchID = ImportBatchSummary.ImportBatchID) and
-- (Observation.SensorID = ImportBatchSummary.SensorID) and
-- (Observation.PhenomenonOfferingID = ImportBatchSummary.PhenomenonOfferingID) and
-- (Observation.PhenomenonUOMID = ImportBatchSummary.PhenomenonUOMID) and
-- (Status.Name = 'Verified'))
-- ) Verifed,
Phenomenon.ID PhenomenonID, Phenomenon.Code PhenomenonCode, Phenomenon.Name PhenomenonName, Phenomenon.Description PhenomenonDescription, Phenomenon.Url PhenomenonUrl,
OfferingID OfferingID, Offering.Code OfferingCode, Offering.Name OfferingName, Offering.Description OfferingDescription,
UnitOfMeasureID, UnitOfMeasure.Code UnitOfMeasureCode, UnitOfMeasure.Unit UnitOfMeasureUnit, UnitOfMeasure.UnitSymbol UnitOfMeasureSymbol,
Sensor.Code SensorCode, Sensor.Name SensorName, Sensor.Description SensorDescription, Sensor.Url SensorUrl,
Instrument.Code InstrumentCode, Instrument.Name InstrumentName, Instrument.Description InstrumentDescription, Instrument.Url InstrumentUrl,
Station.Code StationCode, Station.Name StationName, Station.Description StationDescription, Station.Url StationUrl,
Site.Code SiteCode, Site.Name SiteName, Site.Description SiteDescription, Site.Url SiteUrl,
Project.ID ProjectID, Project.Code ProjectCode, Project.Name ProjectName, Project.Description ProjectDescription, Project.Url ProjectUrl,
Programme.ID ProgrammeID, Programme.Code ProgrammeCode, Programme.Name ProgrammeName, Programme.Description ProgrammeDescription, Programme.Url ProgrammeUrl,
Organisation.ID OrganisationID, Organisation.Code OrganisationCode, Organisation.Name OrganisationName, Organisation.Description OrganisationDescription, Organisation.Url OrganisationUrl
From
ImportBatchSummary
inner join Sensor
on (ImportBatchSummary.SensorID = Sensor.ID)
inner join Instrument
on (ImportBatchSummary.InstrumentID = Instrument.ID)
inner join Station
on (ImportBatchSummary.StationID = Station.ID)
inner join Site
on (ImportBatchSummary.SiteID = Site.ID)
inner join PhenomenonOffering
on (ImportBatchSummary.PhenomenonOfferingID = PhenomenonOffering.ID)
inner join Phenomenon
on (PhenomenonOffering.PhenomenonID = Phenomenon.ID)
inner join Offering
on (PhenomenonOffering.OfferingID = Offering.ID)
inner join PhenomenonUOM
on (ImportBatchSummary.PhenomenonUOMID = PhenomenonUOM.ID)
inner join UnitOfMeasure
on (PhenomenonUOM.UnitOfMeasureID = UnitOfMeasure.ID)
left join Project_Station
on (Project_Station.StationID = Station.ID)
left join Project
on (Project_Station.ProjectID = Project.ID)
left join Programme
on (Project.ProgrammeID = Programme.ID)
left join vStationOrganisation
on (vStationOrganisation.StationID = Station.ID)
left join Organisation
on (vStationOrganisation.OrganisationID = Organisation.ID)
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Altering [dbo].[vLocations]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER VIEW [dbo].[vLocations]
AS
Select distinct
OrganisationID, OrganisationName, OrganisationUrl,
ProgrammeID, ProgrammeName, ProgrammeUrl,
ProjectID, ProjectName, ProjectUrl,
SiteID, SiteName, SiteUrl,
StationID, StationName, StationUrl,
(LatitudeNorth + LatitudeSouth) / 2 Latitude,
(LongitudeWest + LongitudeEast) / 2 Longitude,
(ElevationMaximum + ElevationMinimum) / 2 Elevation
from
vImportBatchSummary
where
(Count > 0) and
(LatitudeNorth is not null) and (LatitudeSouth is not null) and
(LongitudeWest is not null) and (LongitudeEast is not null)
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Altering [dbo].[vInventorySensors]...';
GO
ALTER VIEW [dbo].[vInventorySensors]
AS
Select
Row_Number() over (order by SiteName, StationName, InstrumentName, SensorName, PhenomenonName, OfferingName, UnitOfMeasureUnit) ID, s.*
from
(
Select
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription, SiteUrl,
StationID, StationCode, StationName, StationDescription, StationUrl,
InstrumentID, InstrumentCode, InstrumentName, InstrumentDescription, InstrumentUrl,
SensorID, SensorCode, SensorName, SensorDescription, SensorUrl,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription, PhenomenonUrl,
PhenomenonOfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol,
Sum(Count) Count, Min(StartDate) StartDate, Max(EndDate) EndDate,
Max(LatitudeNorth) LatitudeNorth, Min(LatitudeSouth) LatitudeSouth,
Min(LongitudeWest) LongitudeWest, Max(LongitudeEast) LongitudeEast
from
vImportBatchSummary
group by
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription, SiteUrl,
StationID, StationCode, StationName, StationDescription, StationUrl,
InstrumentID, InstrumentCode, InstrumentName, InstrumentDescription, InstrumentUrl,
SensorID, SensorCode, SensorName, SensorDescription, SensorUrl,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription, PhenomenonUrl,
PhenomenonOfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol
) s
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIDatastreams]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIDatastreams]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPILocations]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPILocations]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIObservedProperties]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIObservedProperties]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPISensors]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPISensors]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIThings]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIThings]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIFeaturesOfInterest]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIFeaturesOfInterest]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Refreshing [dbo].[vSensorThingsAPIHistoricalLocations]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
EXECUTE sp_refreshsqlmodule N'[dbo].[vSensorThingsAPIHistoricalLocations]';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[vInventoryDatasets]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
CREATE VIEW [dbo].[vInventoryDatasets]
AS
Select
Row_Number() over (order by StationCode, PhenomenonCode, OfferingCode, UnitOfMeasureCode) ID, s.*
from
(
Select
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription, SiteUrl,
StationID, StationCode, StationName, StationDescription, StationUrl,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription, PhenomenonUrl,
PhenomenonOfferingID, OfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol,
Sum(Count) Count,
Min(StartDate) StartDate,
Max(EndDate) EndDate,
Max(LatitudeNorth) LatitudeNorth,
Min(LatitudeSouth) LatitudeSouth,
Min(LongitudeWest) LongitudeWest,
Max(LongitudeEast) LongitudeEast,
Min(ElevationMinimum) ElevationMinimum,
Max(ElevationMaximum) ElevationMaximum
from
vImportBatchSummary
group by
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription, SiteUrl,
StationID, StationCode, StationName, StationDescription, StationUrl,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription, PhenomenonUrl,
PhenomenonOfferingID, OfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol
) s
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Creating [dbo].[vStationDatasets]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
CREATE VIEW [dbo].[vStationDatasets]
AS
Select
Row_Number() over (order by StationCode, PhenomenonCode, OfferingCode, UnitOfMeasureCode) ID, s.*
from
(
Select
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription,
StationID, StationCode, StationName, StationDescription,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription,
PhenomenonOfferingID, OfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol,
Sum(Count) Count,
Min(StartDate) StartDate,
Max(EndDate) EndDate,
Max(LatitudeNorth) LatitudeNorth,
Min(LatitudeSouth) LatitudeSouth,
Min(LongitudeWest) LongitudeWest,
Max(LongitudeEast) LongitudeEast,
Min(ElevationMinimum) ElevationMinimum,
Max(ElevationMaximum) ElevationMaximum
from
vImportBatchSummary
group by
OrganisationID, OrganisationCode, OrganisationName, OrganisationDescription, OrganisationUrl,
ProgrammeID, ProgrammeCode, ProgrammeName, ProgrammeDescription, ProgrammeUrl,
ProjectID, ProjectCode, ProjectName, ProjectDescription, ProjectUrl,
SiteID, SiteCode, SiteName, SiteDescription,
StationID, StationCode, StationName, StationDescription,
PhenomenonID, PhenomenonCode, PhenomenonName, PhenomenonDescription,
PhenomenonOfferingID, OfferingID, OfferingCode, OfferingName, OfferingDescription,
PhenomenonUOMID, UnitOfMeasureID, UnitOfMeasureCode, UnitOfMeasureUnit, UnitOfMeasureSymbol
) s
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Altering [dbo].[vFeatures]...';
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER OFF;
GO
ALTER VIEW [dbo].[vFeatures]
AS
Select distinct
PhenomenonID, PhenomenonName, PhenomenonUrl,
PhenomenonOfferingID, OfferingID, OfferingName,
PhenomenonUOMID, UnitOfMeasureID, UnitOfMeasureUnit
from
vImportBatchSummary
where
(Count > 0)
GO
SET ANSI_NULLS, QUOTED_IDENTIFIER ON;
GO
PRINT N'Checking existing data against newly created constraints';
GO
USE [$(DatabaseName)];
GO
ALTER TABLE [dbo].[DigitalObjectIdentifiers] WITH CHECK CHECK CONSTRAINT [FK_DigitalObjectIdentifiers_ParentID];
ALTER TABLE [dbo].[ImportBatchSummary] WITH CHECK CHECK CONSTRAINT [FK_ImportBatchSummary_DigitalObjectIdentifierID];
ALTER TABLE [dbo].[Organisation] WITH CHECK CHECK CONSTRAINT [FK_Organisation_DigitalObjectIdentifierID];
ALTER TABLE [dbo].[Programme] WITH CHECK CHECK CONSTRAINT [FK_Programme_DigitalObjectIdentifierID];
ALTER TABLE [dbo].[Project] WITH CHECK CHECK CONSTRAINT [FK_Project_DigitalObjectIdentifierID];
ALTER TABLE [dbo].[Site] WITH CHECK CHECK CONSTRAINT [FK_Site_DigitalObjectIdentifierID];
ALTER TABLE [dbo].[Station] WITH CHECK CHECK CONSTRAINT [FK_Station_DigitalObjectIdentifierID];
GO
PRINT N'Update complete.';
GO
| {
"content_hash": "0edb0742f24010ef68ea9d666d2b49a6",
"timestamp": "",
"source": "github",
"line_count": 1241,
"max_line_length": 421,
"avg_line_length": 25.02497985495568,
"alnum_prop": 0.7613665636269964,
"repo_name": "SAEONData/SAEON-Observations-Database",
"id": "eb11124ee0b1e6aeabcbfb1da5587bc58f06f58a",
"size": "31058",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "SQL/2.0.63/ObservationsSACTN 2.0.63.publish.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "814481"
},
{
"name": "Batchfile",
"bytes": "766"
},
{
"name": "C#",
"bytes": "7546547"
},
{
"name": "CSS",
"bytes": "13906672"
},
{
"name": "Dockerfile",
"bytes": "1748"
},
{
"name": "HTML",
"bytes": "288820"
},
{
"name": "JavaScript",
"bytes": "295583"
},
{
"name": "Less",
"bytes": "19846829"
},
{
"name": "PowerShell",
"bytes": "652"
},
{
"name": "TSQL",
"bytes": "9070502"
},
{
"name": "TypeScript",
"bytes": "22318"
},
{
"name": "XSLT",
"bytes": "2456"
}
],
"symlink_target": ""
} |
package org.infinispan.configuration;
import static org.infinispan.util.Immutables.immutableTypedProperties;
import org.infinispan.util.TypedProperties;
public abstract class AbstractTypedPropertiesConfiguration {
private final TypedProperties properties;
protected AbstractTypedPropertiesConfiguration(TypedProperties properties) {
this.properties = immutableTypedProperties(properties);
}
public TypedProperties properties() {
return properties;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractTypedPropertiesConfiguration that = (AbstractTypedPropertiesConfiguration) o;
if (properties != null ? !properties.equals(that.properties) : that.properties != null)
return false;
return true;
}
@Override
public int hashCode() {
return properties != null ? properties.hashCode() : 0;
}
} | {
"content_hash": "ad49aa22456b4cf7a296ce7b434309d2",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 93,
"avg_line_length": 25.842105263157894,
"alnum_prop": 0.7158859470468432,
"repo_name": "nmldiegues/stibt",
"id": "1c0f2b6a742899e95dd5a4bd48b3e89f93d270fe",
"size": "1781",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "infinispan/core/src/main/java/org/infinispan/configuration/AbstractTypedPropertiesConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3441"
},
{
"name": "CSS",
"bytes": "6677"
},
{
"name": "GAP",
"bytes": "30552"
},
{
"name": "HTML",
"bytes": "17606"
},
{
"name": "Java",
"bytes": "15496473"
},
{
"name": "JavaScript",
"bytes": "3234"
},
{
"name": "Python",
"bytes": "131164"
},
{
"name": "Ruby",
"bytes": "36919"
},
{
"name": "Scala",
"bytes": "509174"
},
{
"name": "Shell",
"bytes": "146366"
},
{
"name": "XSLT",
"bytes": "52280"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET</title>
<link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="../../../../index.html" title="Chapter 1. Geometry">
<link rel="up" href="../register.html" title="Macro's for adaption">
<link rel="prev" href="boost_geometry_register_point_2d_const.html" title="BOOST_GEOMETRY_REGISTER_POINT_2D_CONST">
<link rel="next" href="boost_geometry_register_point_3d.html" title="BOOST_GEOMETRY_REGISTER_POINT_3D">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost_geometry_register_point_2d_const.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../register.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost_geometry_register_point_3d.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set"></a><a class="link" href="boost_geometry_register_point_2d_get_set.html" title="BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET">BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET</a>
</h5></div></div></div>
<p>
<a class="indexterm" name="idp51481336"></a>
Macro to register a 2D point type (having separate get/set methods)
</p>
<h6>
<a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.h0"></a>
<span class="phrase"><a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.description"></a></span><a class="link" href="boost_geometry_register_point_2d_get_set.html#geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.description">Description</a>
</h6>
<p>
The macro BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET registers a two-dimensional
point type such that it is recognized by Boost.Geometry and that Boost.Geometry
functionality can used with the specified type.. The get/set version
registers get and set methods separately and can be used for classes
with protected member variables and get/set methods to change coordinates
</p>
<h6>
<a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.h1"></a>
<span class="phrase"><a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.synopsis"></a></span><a class="link" href="boost_geometry_register_point_2d_get_set.html#geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.synopsis">Synopsis</a>
</h6>
<p>
</p>
<pre class="programlisting"><span class="preprocessor">#define</span> <span class="identifier">BOOST_GEOMETRY_REGISTER_POINT_2D_GET_SET</span><span class="special">(</span><span class="identifier">Point</span><span class="special">,</span> <span class="identifier">CoordinateType</span><span class="special">,</span> <span class="identifier">CoordinateSystem</span><span class="special">,</span> <span class="identifier">Get0</span><span class="special">,</span> <span class="identifier">Get1</span><span class="special">,</span> <span class="identifier">Set0</span><span class="special">,</span> <span class="identifier">Set1</span><span class="special">)</span></pre>
<p>
</p>
<h6>
<a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.h2"></a>
<span class="phrase"><a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.parameters"></a></span><a class="link" href="boost_geometry_register_point_2d_get_set.html#geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.parameters">Parameters</a>
</h6>
<div class="informaltable"><table class="table">
<colgroup>
<col>
<col>
</colgroup>
<thead><tr>
<th>
<p>
Name
</p>
</th>
<th>
<p>
Description
</p>
</th>
</tr></thead>
<tbody>
<tr>
<td>
<p>
Point
</p>
</td>
<td>
<p>
Point type to be registered
</p>
</td>
</tr>
<tr>
<td>
<p>
CoordinateType
</p>
</td>
<td>
<p>
Type of the coordinates of the point (e.g. double)
</p>
</td>
</tr>
<tr>
<td>
<p>
CoordinateSystem
</p>
</td>
<td>
<p>
Coordinate system (e.g. cs::cartesian)
</p>
</td>
</tr>
<tr>
<td>
<p>
Get0
</p>
</td>
<td>
<p>
Method to get the first (usually x) coordinate
</p>
</td>
</tr>
<tr>
<td>
<p>
Get1
</p>
</td>
<td>
<p>
Method to get the second (usually y) coordinate
</p>
</td>
</tr>
<tr>
<td>
<p>
Set0
</p>
</td>
<td>
<p>
Method to set the first (usually x) coordinate
</p>
</td>
</tr>
<tr>
<td>
<p>
Set1
</p>
</td>
<td>
<p>
Method to set the second (usually y) coordinate
</p>
</td>
</tr>
</tbody>
</table></div>
<h6>
<a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.h3"></a>
<span class="phrase"><a name="geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.header"></a></span><a class="link" href="boost_geometry_register_point_2d_get_set.html#geometry.reference.adapted.register.boost_geometry_register_point_2d_get_set.header">Header</a>
</h6>
<p>
<code class="computeroutput"><span class="preprocessor">#include</span> <span class="special"><</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">geometry</span><span class="special">/</span><span class="identifier">geometries</span><span class="special">/</span><span class="keyword">register</span><span class="special">/</span><span class="identifier">point</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">></span></code>
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2009-2013 Barend Gehrels, Bruno Lalande, Mateusz Loskot, Adam Wulkiewicz<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="boost_geometry_register_point_2d_const.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../register.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="boost_geometry_register_point_3d.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "fa51d446b3f9720270ac8a3589193332",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 669,
"avg_line_length": 49.989010989010985,
"alnum_prop": 0.5628709606506924,
"repo_name": "laborautonomo/poedit",
"id": "af6768a4a513c7f9e2a0ad54865c1b5a686d1ad5",
"size": "9098",
"binary": false,
"copies": "1",
"ref": "refs/heads/stable",
"path": "deps/boost/libs/geometry/doc/html/geometry/reference/adapted/register/boost_geometry_register_point_2d_get_set.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import java.io.FileNotFoundException;
import java.io.IOException;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GL11;
/**
*
* @author Šarūnas Navickas
*/
public class Main
{
private static int _fps = 60;
public static boolean _baigtas = false;
private static Thread _logic;
public static boolean _done = true;
private static void cleanup()
{
Display.destroy();
}
public static void cleanObj()
{
for(int i = 0; i<Duomenys._objektai.size();i++)
{
try
{
Logika.world.remove(Duomenys._objektai.get(i).body);
Duomenys._objektai.remove(i);
}
catch(Exception ex)
{}
}
}
public static void objects() throws IOException
{
_done = false;
System.out.print("Objects..");
//Išvalom viską
while(Duomenys._objektai.size() > 0)
{
try
{
cleanObj();
}
catch(Exception ex)
{
}
}
Logika._rudos = 0;
Duomenys.loadObj("Lygiai/base.txt",true);
try
{
Duomenys.loadObj("Lygiai/"+Logika._lygis+"/boxes.txt",false);
}
catch(Exception ex)
{
Duomenys.loadObj("Lygiai/1/boxes.txt",false);
}
System.out.print("done.\n");
_done = true;
}
private static void init() throws LWJGLException, FileNotFoundException, IOException
{
System.out.println("Initializing:");
System.out.print("Screen..");
Display.setTitle("Kamuoliukų manija");
Display.setFullscreen(true);
Display.setVSyncEnabled(true);
Display.create();
Display.setDisplayMode(new DisplayMode(1024,768));
System.out.print("done.\n");
System.out.print("OpenGL..");
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glOrtho(0.0, Display.getDisplayMode().getWidth(), 0.0, Display.getDisplayMode().getHeight(), -1.0, 1.0);
GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();
GL11.glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);
GL11.glMatrixMode(GL11.GL_PROJECTION);
System.out.print("done.\n");
System.out.print("Textures..");
Duomenys.loadTex("kamuoliukas", "Tekstūros/kamuoliukas.tga");
Duomenys.loadTex("blokelis", "Tekstūros/blokelis.tga");
Duomenys.loadTex("patranka", "Tekstūros/patranka.tga");
Duomenys.loadTex("patranka2", "Tekstūros/patranka2.tga");
Duomenys.loadTex("jėga_pilkas", "Tekstūros/jėga_pilkas.tga");
Duomenys.loadTex("jėga_geltonas", "Tekstūros/jėga_geltonas.tga");
Duomenys.loadTex("jėga_žalias", "Tekstūros/jėga_žalias.tga");
Duomenys.loadTex("jėga_raudonas", "Tekstūros/jėga_raudonas.tga");
Duomenys.loadTex("deze_raudona", "Tekstūros/dėžė_raudona.tga");
Duomenys.loadTex("deze_ruda", "Tekstūros/dėžė_ruda.tga");
Duomenys.loadTex("deze_pilka", "Tekstūros/dėžė_pilka.tga");
Duomenys.loadTex("font", "Tekstūros/font.tga");
System.out.print("done.\n");
_logic = new Thread(new LogicsThread());
}
private static void run() throws LWJGLException, IOException
{
while(!_baigtas)
{
Display.update();
if (Display.isCloseRequested())
{
_baigtas = true;
}
else if (Display.isActive())
{
Grafika.render();
Display.sync(_fps);
}
else
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
}
if (Display.isVisible() || Display.isDirty())
{
Grafika.render();
}
}
}
public static void main(String[] args)
{
try
{
init();
run();
}
catch (Exception ex)
{
System.out.println(ex.toString());
Sys.alert("Kamuoliukų Manija", "Nepavyko paleisti žaidimo.");
}
finally
{
cleanup();
}
System.exit(0);
}
}
| {
"content_hash": "0fbd6c829a5fcc06e68df55d9b085a06",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 117,
"avg_line_length": 31.137254901960784,
"alnum_prop": 0.5411418975650714,
"repo_name": "zaibacu/KManija",
"id": "19cd67a839b799e7be9fccfdcad9736d48ae6358",
"size": "4802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Main.java",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
export { Accessor } from './Accessor';
export { Enhancer } from './Enhancer';
export { Factory, InstanceFactory } from './Factory';
export { ManagedFactory } from './ManagedFactory';
export { EntityFactory } from './EntityFactory';
export { LoginOption, UserFactory, OAuthOptions } from './UserFactory';
export { DeviceFactory } from './DeviceFactory';
export { RootFolderMetadata, FileFactory } from './FileFactory';
export { Managed } from './Managed';
export { Entity } from './Entity';
export { Role } from './Role';
export { User } from './User';
export {
FileMetadata, File, FileOptions, FileData, FileIdentifiers,
} from './File';
| {
"content_hash": "895eb3e1d0fde64d7dff7e51346f2efe",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 71,
"avg_line_length": 42.666666666666664,
"alnum_prop": 0.70625,
"repo_name": "Baqend/js-sdk",
"id": "fb72aa8819f203d1bf32f5925dc350a8a51b1914",
"size": "640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/binding/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "472715"
},
{
"name": "Smarty",
"bytes": "2035"
},
{
"name": "TypeScript",
"bytes": "470906"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
namespace JamLib.Algorithms.Sorting.ExchangeSorts
{
public static class CombSort
{
// TODO: Think about adding additional overloads for IComparable as well as Comparison (so that we can use lambda expressions)
public static void Sort<T>(IList<T> data) { Sort(data, Comparer<T>.Default); }
public static void Sort<T>(IList<T> data, IComparer<T> comparer)
{
int gap = data.Count; //initialize gap size
float shrink = 1.3f; //set the gap shrink factor
bool sorted = false;
while (gap > 1 || !sorted)
{
// Update Gap size
gap = (int)(gap / shrink);
if (gap < 1) { gap = 1; }
// Reset Sort Status
sorted = true;
for (int i = 0; i + gap < data.Count; i++)
{
// if this pair is out of order, swap them and remember something changed
if (comparer.Compare(data[i], data[i + gap]) > 0)
{
SortingUtils.Swap(data, i, i + gap);
sorted = false;
}
}
}
}
}
} | {
"content_hash": "a63bb6d5a10ba6829dbeaa405f43eb6b",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 134,
"avg_line_length": 32.41025641025641,
"alnum_prop": 0.4833860759493671,
"repo_name": "joshimoo/JamLib",
"id": "c8a5cbc253cd1cb573cc55f2645101cba0df8c85",
"size": "1266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JamLib/Algorithms/Sorting/ExchangeSorts/CombSort.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "128796"
}
],
"symlink_target": ""
} |
/*
** Intel/DVI ADPCM coder/decoder.
**
** The algorithm for this coder was taken from the IMA Compatability Project
** proceedings, Vol 2, Number 2; May 1992.
**
** Version 1.2, 18-Dec-92.
*/
#include "snd_local.h"
/* Intel ADPCM step variation table */
static int indexTable[16] = {
-1, -1, -1, -1, 2, 4, 6, 8,
-1, -1, -1, -1, 2, 4, 6, 8,
};
static int stepsizeTable[89] = {
7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};
void S_AdpcmEncode( short indata[], char outdata[], int len, struct adpcm_state *state ) {
short *inp; /* Input buffer pointer */
signed char *outp; /* output buffer pointer */
int val; /* Current input sample value */
int sign; /* Current adpcm sign bit */
int delta; /* Current adpcm output value */
int diff; /* Difference between val and sample */
int step; /* Stepsize */
int valpred; /* Predicted output value */
int vpdiff; /* Current change to valpred */
int index; /* Current step change index */
int outputbuffer; /* place to keep previous 4-bit value */
int bufferstep; /* toggle between outputbuffer/output */
outp = (signed char *)outdata;
inp = indata;
valpred = state->sample;
index = state->index;
step = stepsizeTable[index];
outputbuffer = 0; // quiet a compiler warning
bufferstep = 1;
for ( ; len > 0 ; len-- ) {
val = *inp++;
/* Step 1 - compute difference with previous value */
diff = val - valpred;
sign = (diff < 0) ? 8 : 0;
if ( sign ) diff = (-diff);
/* Step 2 - Divide and clamp */
/* Note:
** This code *approximately* computes:
** delta = diff*4/step;
** vpdiff = (delta+0.5)*step/4;
** but in shift step bits are dropped. The net result of this is
** that even if you have fast mul/div hardware you cannot put it to
** good use since the fixup would be too expensive.
*/
delta = 0;
vpdiff = (step >> 3);
if ( diff >= step ) {
delta = 4;
diff -= step;
vpdiff += step;
}
step >>= 1;
if ( diff >= step ) {
delta |= 2;
diff -= step;
vpdiff += step;
}
step >>= 1;
if ( diff >= step ) {
delta |= 1;
vpdiff += step;
}
/* Step 3 - Update previous value */
if ( sign )
valpred -= vpdiff;
else
valpred += vpdiff;
/* Step 4 - Clamp previous value to 16 bits */
if ( valpred > 32767 )
valpred = 32767;
else if ( valpred < -32768 )
valpred = -32768;
/* Step 5 - Assemble value, update index and step values */
delta |= sign;
index += indexTable[delta];
if ( index < 0 ) index = 0;
if ( index > 88 ) index = 88;
step = stepsizeTable[index];
/* Step 6 - Output value */
if ( bufferstep ) {
outputbuffer = (delta << 4) & 0xf0;
} else {
*outp++ = (delta & 0x0f) | outputbuffer;
}
bufferstep = !bufferstep;
}
/* Output last step, if needed */
if ( !bufferstep )
*outp++ = outputbuffer;
state->sample = valpred;
state->index = index;
}
/* static */ void S_AdpcmDecode( const char indata[], short *outdata, int len, struct adpcm_state *state ) {
signed char *inp; /* Input buffer pointer */
int outp; /* output buffer pointer */
int sign; /* Current adpcm sign bit */
int delta; /* Current adpcm output value */
int step; /* Stepsize */
int valpred; /* Predicted value */
int vpdiff; /* Current change to valpred */
int index; /* Current step change index */
int inputbuffer; /* place to keep next 4-bit value */
int bufferstep; /* toggle between inputbuffer/input */
outp = 0;
inp = (signed char *)indata;
valpred = state->sample;
index = state->index;
step = stepsizeTable[index];
bufferstep = 0;
inputbuffer = 0; // quiet a compiler warning
for ( ; len > 0 ; len-- ) {
/* Step 1 - get the delta value */
if ( bufferstep ) {
delta = inputbuffer & 0xf;
} else {
inputbuffer = *inp++;
delta = (inputbuffer >> 4) & 0xf;
}
bufferstep = !bufferstep;
/* Step 2 - Find new index value (for later) */
index += indexTable[delta];
if ( index < 0 ) index = 0;
if ( index > 88 ) index = 88;
/* Step 3 - Separate sign and magnitude */
sign = delta & 8;
delta = delta & 7;
/* Step 4 - Compute difference and new predicted value */
/*
** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
** in adpcm_coder.
*/
vpdiff = step >> 3;
if ( delta & 4 ) vpdiff += step;
if ( delta & 2 ) vpdiff += step>>1;
if ( delta & 1 ) vpdiff += step>>2;
if ( sign )
valpred -= vpdiff;
else
valpred += vpdiff;
/* Step 5 - clamp output value */
if ( valpred > 32767 )
valpred = 32767;
else if ( valpred < -32768 )
valpred = -32768;
/* Step 6 - Update step value */
step = stepsizeTable[index];
/* Step 7 - Output value */
outdata[outp] = valpred;
outp++;
}
state->sample = valpred;
state->index = index;
}
/*
====================
S_AdpcmMemoryNeeded
Returns the amount of memory (in bytes) needed to store the samples in out internal adpcm format
====================
*/
int S_AdpcmMemoryNeeded( const wavinfo_t *info ) {
float scale;
int scaledSampleCount;
int sampleMemory;
int blockCount;
int headerMemory;
// determine scale to convert from input sampling rate to desired sampling rate
scale = (float)info->rate / dma.speed;
// calc number of samples at playback sampling rate
scaledSampleCount = info->samples / scale;
// calc memory need to store those samples using ADPCM at 4 bits per sample
sampleMemory = scaledSampleCount / 2;
// calc number of sample blocks needed of PAINTBUFFER_SIZE
blockCount = scaledSampleCount / PAINTBUFFER_SIZE;
if( scaledSampleCount % PAINTBUFFER_SIZE ) {
blockCount++;
}
// calc memory needed to store the block headers
headerMemory = blockCount * sizeof(adpcm_state_t);
return sampleMemory + headerMemory;
}
/*
====================
S_AdpcmGetSamples
====================
*/
void S_AdpcmGetSamples(sndBuffer *chunk, short *to) {
adpcm_state_t state;
byte *out;
// get the starting state from the block header
state.index = chunk->adpcm.index;
state.sample = chunk->adpcm.sample;
out = (byte *)chunk->sndChunk;
// get samples
S_AdpcmDecode((char *) out, to, SND_CHUNK_SIZE_BYTE*2, &state );
}
/*
====================
S_AdpcmEncodeSound
====================
*/
void S_AdpcmEncodeSound( sfx_t *sfx, short *samples ) {
adpcm_state_t state;
int inOffset;
int count;
int n;
sndBuffer *newchunk, *chunk;
byte *out;
inOffset = 0;
count = sfx->soundLength;
state.index = 0;
state.sample = samples[0];
chunk = NULL;
while( count ) {
n = count;
if( n > SND_CHUNK_SIZE_BYTE*2 ) {
n = SND_CHUNK_SIZE_BYTE*2;
}
newchunk = SND_malloc();
if (sfx->soundData == NULL) {
sfx->soundData = newchunk;
} else {
chunk->next = newchunk;
}
chunk = newchunk;
// output the header
chunk->adpcm.index = state.index;
chunk->adpcm.sample = state.sample;
out = (byte *)chunk->sndChunk;
// encode the samples
S_AdpcmEncode( samples + inOffset, (char *) out, n, &state );
inOffset += n;
count -= n;
}
}
| {
"content_hash": "4e2932f5bbd76e04a02a025dcddc904e",
"timestamp": "",
"source": "github",
"line_count": 308,
"max_line_length": 108,
"avg_line_length": 24.66883116883117,
"alnum_prop": 0.5983153461437221,
"repo_name": "decolector/localconflict",
"id": "89e68f42d5ec680616700d2792918555ecf09ebd",
"size": "8819",
"binary": false,
"copies": "45",
"ref": "refs/heads/master",
"path": "q3osc/ccrmamod/client/snd_adpcm.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "34527"
},
{
"name": "C",
"bytes": "9052349"
},
{
"name": "C++",
"bytes": "621458"
},
{
"name": "D",
"bytes": "2935"
},
{
"name": "Objective-C",
"bytes": "588656"
},
{
"name": "Python",
"bytes": "8938"
},
{
"name": "R",
"bytes": "11682"
},
{
"name": "Shell",
"bytes": "2389510"
}
],
"symlink_target": ""
} |
package org.achacha.webcardgame.game.dbo;
import com.google.common.base.Preconditions;
import org.achacha.base.db.BaseDbo;
import org.achacha.base.global.Global;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.persistence.Table;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
/**
* Player
*/
@Table(schema="public", name="player")
public class PlayerDbo extends BaseDbo {
transient private static final Logger LOGGER = LogManager.getLogger(PlayerDbo.class);
/** Player id */
protected long id;
/** Login that owns this player */
protected long loginId;
/** Player name */
protected String name;
/** Timestamp of the last processed tick */
protected Timestamp lastTick;
/** Inventory */
protected InventoryDbo inventory;
/** Cards */
protected List<CardDbo> cards;
public static Builder builder(long loginId, String name) {
return new Builder(loginId, name);
}
public static class Builder {
private final PlayerDbo player = new PlayerDbo();
public Builder(long loginId, String name) {
player.loginId = loginId;
player.name = name;
player.cards = new ArrayList<>();
player.inventory = new InventoryDbo();
}
/**
* Add a card
* NOTE: You don't need player id on this card, it will be correctly adjusted on insert
* @param card CardDbo
* @return Builder
*/
public Builder withCard(CardDbo card) {
player.cards.add(card);
return this;
}
public PlayerDbo build() {
return player;
}
}
public PlayerDbo() {
}
@Override
public long getId() {
return this.id;
}
public Timestamp getLastTick() {
return lastTick;
}
public String getName() {
return name;
}
@Override
public void fromResultSet(Connection connection, ResultSet rs) throws SQLException {
this.id = rs.getLong("id");
this.loginId = rs.getLong("login__id");
this.name = rs.getString("name");
this.lastTick = rs.getTimestamp("last_tick");
this.inventory = Global.getInstance().getDatabaseManager().<InventoryDboFactory>getFactory(InventoryDbo.class).getByPlayerId(connection, this.id);
this.cards = Global.getInstance().getDatabaseManager().<CardDboFactory>getFactory(CardDbo.class).getByPlayerId(connection, this.id);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("fromResultSet: this="+this);
}
}
@Override
public void insert(Connection connection) throws SQLException {
Preconditions.checkState(loginId > 0, "Must be associated with a Login");
try (
PreparedStatement pstmt = Global.getInstance().getDatabaseManager().prepareStatement(
connection,
"/sql/Player/Insert.sql",
p-> {
p.setLong(1, loginId);
p.setString(2, name);
}
);
ResultSet rs = pstmt.executeQuery()
) {
if (rs.next()) {
this.id = rs.getLong(1);
this.lastTick = rs.getTimestamp(2);
}
else {
LOGGER.error("Failed to insert player={}", this);
throw new SQLException("Failed to insert player="+this);
}
// Insert inventory
inventory.playerId = this.id;
inventory.insert(connection);
// Insert cards if any
for (CardDbo card : cards) {
card.playerId = this.id;
card.insert(connection);
}
}
}
@Override
public void update(Connection connection) throws SQLException {
Preconditions.checkState(id > 0, "MUst be a valid object to update");
Preconditions.checkState(loginId > 0, "Must be asscoaited with a Login");
// Player doesn't have any updatable data at this time, propagate changes to members
inventory.update(connection);
// Inactivate cards not part of the existing list
Global.getInstance().getDatabaseManager().<CardDboFactory>getFactory(CardDbo.class).inactivateNotIn(connection, id, cards);
for (CardDbo card : cards) {
if (card.id == 0) {
card.playerId = this.id;
card.insert(connection);
}
else {
card.update(connection);
}
}
}
/**
* Set the last tick update to now()
* Commits on update
* @param connection Connection
*/
public void updateLastTickToNow(Connection connection) throws SQLException {
try (
PreparedStatement pstmt = Global.getInstance().getDatabaseManager().prepareStatement(
connection,
"/sql/Player/UpdateLastTickToNow.sql",
p -> {
p.setLong(1, id);
}
);
ResultSet rs = pstmt.executeQuery()
) {
connection.commit();
Preconditions.checkState(rs.next());
lastTick = rs.getTimestamp(1);
}
}
public List<CardDbo> getCards() {
return cards;
}
public void setCards(List<CardDbo> cards) {
this.cards = cards;
}
public InventoryDbo getInventory() {
return inventory;
}
public void setInventory(InventoryDbo inventory) {
this.inventory = inventory;
}
}
| {
"content_hash": "249ceda8edc294e9bf916472739b2591",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 154,
"avg_line_length": 29.762626262626263,
"alnum_prop": 0.575598167317156,
"repo_name": "achacha/SomeWebCardGame",
"id": "014dc3b2dfce3fd69e9ae3358c1e62853747c95d",
"size": "5893",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/achacha/webcardgame/game/dbo/PlayerDbo.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "722"
},
{
"name": "Dockerfile",
"bytes": "111"
},
{
"name": "Java",
"bytes": "470459"
},
{
"name": "JavaScript",
"bytes": "6367"
},
{
"name": "Shell",
"bytes": "629"
}
],
"symlink_target": ""
} |
require "pollett/concerns/mailers/mailer"
| {
"content_hash": "831afd3640616196b513fc7fc3666847",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 41,
"avg_line_length": 42,
"alnum_prop": 0.8333333333333334,
"repo_name": "jasonkriss/pollett",
"id": "88247c41fad4783620cc4a3275d6acb66bc3048b",
"size": "42",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pollett/concerns/mailers.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "686"
},
{
"name": "HTML",
"bytes": "5006"
},
{
"name": "JavaScript",
"bytes": "602"
},
{
"name": "Ruby",
"bytes": "54968"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="de.htw.vs.semaphore.command" />
</beans>
| {
"content_hash": "8a9541d59191496f526425478ab96376",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 128,
"avg_line_length": 61.55555555555556,
"alnum_prop": 0.7490974729241877,
"repo_name": "yveskaufmann/U_VerteilteSysteme",
"id": "3ec2dcbfdfd585e5046b966149e7e86e92a96b45",
"size": "554",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Semaphore/src/main/resources/META-INF/spring/spring-shell-plugin.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "55921"
}
],
"symlink_target": ""
} |
// $Id: auto_event.cpp 84565 2009-02-23 08:20:39Z johnnyw $
// This test shows the use of an ACE_Auto_Event as a signaling
// mechanism. Two threads are created (one a reader, the other a
// writer). The reader waits till the writer has completed
// calculations. Upon waking up the reader prints the data calculated
// by the writer. The writer thread calculates the value and signals
// the reader when the calculation completes.
#include "ace/OS_NS_unistd.h"
#include "ace/OS_main.h"
#include "ace/Service_Config.h"
#include "ace/Auto_Event.h"
#include "ace/Singleton.h"
#include "ace/Thread_Manager.h"
ACE_RCSID(Threads, auto_event, "$Id: auto_event.cpp 84565 2009-02-23 08:20:39Z johnnyw $")
#if defined (ACE_HAS_THREADS)
// Shared event between reader and writer. The ACE_Thread_Mutex is
// necessary to make sure that only one ACE_Auto_Event is created.
// The default constructor for ACE_Auto_Event sets it initially into
// the non-signaled state.
typedef ACE_Singleton <ACE_Auto_Event, ACE_Thread_Mutex> EVENT;
// work time for writer
static int work_time;
// Reader thread.
static void *
reader (void *arg)
{
// Shared data via a reference.
int& data = *(int *) arg;
// Wait for writer to complete.
ACE_DEBUG ((LM_DEBUG, "(%t) reader: waiting......\n"));
if (EVENT::instance ()->wait () == -1)
{
ACE_ERROR ((LM_ERROR, "thread wait failed"));
ACE_OS::exit (0);
}
// Read shared data.
ACE_DEBUG ((LM_DEBUG, "(%t) reader: value of data is: %d\n", data));
return 0;
}
// Writer thread.
static void *
writer (void *arg)
{
int& data = *(int *) arg;
// Calculate (work).
ACE_DEBUG ((LM_DEBUG, "(%t) writer: working for %d secs\n", work_time));
ACE_OS::sleep (work_time);
// Write shared data.
data = 42;
// Wake up reader.
ACE_DEBUG ((LM_DEBUG, "(%t) writer: calculation complete, waking reader\n"));
if (EVENT::instance ()->signal () == -1)
{
ACE_ERROR ((LM_ERROR, "thread signal failed"));
ACE_OS::exit (0);
}
return 0;
}
int
ACE_TMAIN (int argc, ACE_TCHAR **argv)
{
// Shared data: set by writer, read by reader.
int data;
// Work time for writer.
work_time = argc == 2 ? ACE_OS::atoi (argv[1]) : 5;
// threads manager
ACE_Thread_Manager& tm = *ACE_Thread_Manager::instance ();
// Create reader thread.
if (tm.spawn ((ACE_THR_FUNC) reader, (void *) &data) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "thread create for reader failed"), -1);
// Create writer thread.
if (tm.spawn ((ACE_THR_FUNC) writer, (void *) &data) == -1)
ACE_ERROR_RETURN ((LM_ERROR, "thread create for writer failed"), -1);
// Wait for both.
if (tm.wait () == -1)
ACE_ERROR_RETURN ((LM_ERROR, "thread wait failed"), -1);
else
ACE_DEBUG ((LM_ERROR, "graceful exit\n"));
return 0;
}
#if defined (ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION)
template ACE_Singleton<ACE_Auto_Event, ACE_Thread_Mutex> *
ACE_Singleton<ACE_Auto_Event, ACE_Thread_Mutex>::singleton_;
#endif /* ACE_HAS_EXPLICIT_STATIC_TEMPLATE_MEMBER_INSTANTIATION */
#else
int
ACE_TMAIN (int, ACE_TCHAR *[])
{
ACE_ERROR ((LM_ERROR, "threads not supported on this platform\n"));
return 0;
}
#endif /* ACE_HAS_THREADS */
| {
"content_hash": "34b88799cd62f4b8a44e058266c0848e",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 90,
"avg_line_length": 26.783333333333335,
"alnum_prop": 0.6543248288736777,
"repo_name": "binghuo365/BaseLab",
"id": "e8645f5c984b6fb5609dfc3dcbe7abffade9763f",
"size": "3214",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "3rd/ACE-5.7.0/ACE_wrappers/examples/Threads/auto_event.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "4318"
},
{
"name": "C",
"bytes": "568095"
},
{
"name": "C++",
"bytes": "21096884"
},
{
"name": "CSS",
"bytes": "193"
},
{
"name": "Emacs Lisp",
"bytes": "7179"
},
{
"name": "Gnuplot",
"bytes": "85718"
},
{
"name": "Groff",
"bytes": "740"
},
{
"name": "HTML",
"bytes": "2438027"
},
{
"name": "Java",
"bytes": "19583"
},
{
"name": "LLVM",
"bytes": "4067"
},
{
"name": "Logos",
"bytes": "204"
},
{
"name": "Makefile",
"bytes": "3952147"
},
{
"name": "Max",
"bytes": "84490"
},
{
"name": "Objective-C",
"bytes": "420"
},
{
"name": "Perl",
"bytes": "1777795"
},
{
"name": "Perl6",
"bytes": "776"
},
{
"name": "PostScript",
"bytes": "152076"
},
{
"name": "Python",
"bytes": "31245"
},
{
"name": "Shell",
"bytes": "420465"
},
{
"name": "Tcl",
"bytes": "397"
},
{
"name": "Yacc",
"bytes": "15030"
}
],
"symlink_target": ""
} |
require 'spec_helper'
RSpec.describe Qapi do
it 'has a version number' do
expect(Qapi::VERSION).not_to be nil
end
end
| {
"content_hash": "75e470d159ec386998f29b3cfb9bd1f3",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 39,
"avg_line_length": 18.142857142857142,
"alnum_prop": 0.7086614173228346,
"repo_name": "coderdan/qapi",
"id": "46def3cbcf6123866bae8192d58fed7ae1bdf228",
"size": "127",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/qapi_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "6015"
},
{
"name": "Shell",
"bytes": "115"
}
],
"symlink_target": ""
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gst/check/gstcheck.h>
#include <gst/check/gstharness.h>
#include <gst/webrtc/webrtc.h>
#include "../../../ext/webrtc/webrtcsdp.h"
#include "../../../ext/webrtc/webrtcsdp.c"
#include "../../../ext/webrtc/utils.h"
#include "../../../ext/webrtc/utils.c"
#define OPUS_RTP_CAPS(pt) "application/x-rtp,payload=" G_STRINGIFY(pt) ",encoding-name=OPUS,media=audio,clock-rate=48000,ssrc=(uint)3384078950"
#define VP8_RTP_CAPS(pt) "application/x-rtp,payload=" G_STRINGIFY(pt) ",encoding-name=VP8,media=video,clock-rate=90000,ssrc=(uint)3484078950"
typedef enum
{
STATE_NEW,
STATE_NEGOTATION_NEEDED,
STATE_OFFER_CREATED,
STATE_ANSWER_CREATED,
STATE_EOS,
STATE_ERROR,
STATE_CUSTOM,
} TestState;
/* basic premise of this is that webrtc1 and webrtc2 are attempting to connect
* to each other in various configurations */
struct test_webrtc;
struct test_webrtc
{
GList *harnesses;
GThread *thread;
GMainLoop *loop;
GstBus *bus1;
GstBus *bus2;
GstElement *webrtc1;
GstElement *webrtc2;
GMutex lock;
GCond cond;
TestState state;
guint offerror;
gpointer user_data;
GDestroyNotify data_notify;
/* *INDENT-OFF* */
void (*on_negotiation_needed) (struct test_webrtc * t,
GstElement * element,
gpointer user_data);
gpointer negotiation_data;
GDestroyNotify negotiation_notify;
void (*on_ice_candidate) (struct test_webrtc * t,
GstElement * element,
guint mlineindex,
gchar * candidate,
GstElement * other,
gpointer user_data);
gpointer ice_candidate_data;
GDestroyNotify ice_candidate_notify;
GstWebRTCSessionDescription * (*on_offer_created) (struct test_webrtc * t,
GstElement * element,
GstPromise * promise,
gpointer user_data);
gpointer offer_data;
GDestroyNotify offer_notify;
GstWebRTCSessionDescription * (*on_answer_created) (struct test_webrtc * t,
GstElement * element,
GstPromise * promise,
gpointer user_data);
gpointer data_channel_data;
GDestroyNotify data_channel_notify;
void (*on_data_channel) (struct test_webrtc * t,
GstElement * element,
GObject *data_channel,
gpointer user_data);
gpointer answer_data;
GDestroyNotify answer_notify;
void (*on_pad_added) (struct test_webrtc * t,
GstElement * element,
GstPad * pad,
gpointer user_data);
gpointer pad_added_data;
GDestroyNotify pad_added_notify;
void (*bus_message) (struct test_webrtc * t,
GstBus * bus,
GstMessage * msg,
gpointer user_data);
gpointer bus_data;
GDestroyNotify bus_notify;
/* *INDENT-ON* */
};
static void
_on_answer_received (GstPromise * promise, gpointer user_data)
{
struct test_webrtc *t = user_data;
GstElement *offeror = t->offerror == 1 ? t->webrtc1 : t->webrtc2;
GstElement *answerer = t->offerror == 2 ? t->webrtc1 : t->webrtc2;
const GstStructure *reply;
GstWebRTCSessionDescription *answer = NULL;
gchar *desc;
reply = gst_promise_get_reply (promise);
gst_structure_get (reply, "answer",
GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &answer, NULL);
desc = gst_sdp_message_as_text (answer->sdp);
GST_INFO ("Created Answer: %s", desc);
g_free (desc);
g_mutex_lock (&t->lock);
if (t->on_answer_created) {
gst_webrtc_session_description_free (answer);
answer = t->on_answer_created (t, answerer, promise, t->answer_data);
}
gst_promise_unref (promise);
g_signal_emit_by_name (answerer, "set-local-description", answer, NULL);
g_signal_emit_by_name (offeror, "set-remote-description", answer, NULL);
t->state = STATE_ANSWER_CREATED;
g_cond_broadcast (&t->cond);
g_mutex_unlock (&t->lock);
gst_webrtc_session_description_free (answer);
}
static void
_on_offer_received (GstPromise * promise, gpointer user_data)
{
struct test_webrtc *t = user_data;
GstElement *offeror = t->offerror == 1 ? t->webrtc1 : t->webrtc2;
GstElement *answerer = t->offerror == 2 ? t->webrtc1 : t->webrtc2;
const GstStructure *reply;
GstWebRTCSessionDescription *offer = NULL;
gchar *desc;
reply = gst_promise_get_reply (promise);
gst_structure_get (reply, "offer",
GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
desc = gst_sdp_message_as_text (offer->sdp);
GST_INFO ("Created offer: %s", desc);
g_free (desc);
g_mutex_lock (&t->lock);
if (t->on_offer_created) {
gst_webrtc_session_description_free (offer);
offer = t->on_offer_created (t, offeror, promise, t->offer_data);
}
gst_promise_unref (promise);
g_signal_emit_by_name (offeror, "set-local-description", offer, NULL);
g_signal_emit_by_name (answerer, "set-remote-description", offer, NULL);
promise = gst_promise_new_with_change_func (_on_answer_received, t, NULL);
g_signal_emit_by_name (answerer, "create-answer", NULL, promise);
t->state = STATE_OFFER_CREATED;
g_cond_broadcast (&t->cond);
g_mutex_unlock (&t->lock);
gst_webrtc_session_description_free (offer);
}
static gboolean
_bus_watch (GstBus * bus, GstMessage * msg, struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
switch (GST_MESSAGE_TYPE (msg)) {
case GST_MESSAGE_STATE_CHANGED:
if (GST_ELEMENT (msg->src) == t->webrtc1
|| GST_ELEMENT (msg->src) == t->webrtc2) {
GstState old, new, pending;
gst_message_parse_state_changed (msg, &old, &new, &pending);
{
gchar *dump_name = g_strconcat ("%s-state_changed-",
GST_OBJECT_NAME (msg->src), gst_element_state_get_name (old), "_",
gst_element_state_get_name (new), NULL);
GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (msg->src),
GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
g_free (dump_name);
}
}
break;
case GST_MESSAGE_ERROR:{
GError *err = NULL;
gchar *dbg_info = NULL;
{
gchar *dump_name;
dump_name =
g_strconcat ("%s-error", GST_OBJECT_NAME (t->webrtc1), NULL);
GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (t->webrtc1),
GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
g_free (dump_name);
dump_name =
g_strconcat ("%s-error", GST_OBJECT_NAME (t->webrtc2), NULL);
GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (t->webrtc2),
GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
g_free (dump_name);
}
gst_message_parse_error (msg, &err, &dbg_info);
GST_WARNING ("ERROR from element %s: %s\n",
GST_OBJECT_NAME (msg->src), err->message);
GST_WARNING ("Debugging info: %s\n", (dbg_info) ? dbg_info : "none");
g_error_free (err);
g_free (dbg_info);
t->state = STATE_ERROR;
g_cond_broadcast (&t->cond);
break;
}
case GST_MESSAGE_EOS:{
{
gchar *dump_name;
dump_name = g_strconcat ("%s-eos", GST_OBJECT_NAME (t->webrtc1), NULL);
GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (t->webrtc1),
GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
g_free (dump_name);
dump_name = g_strconcat ("%s-eos", GST_OBJECT_NAME (t->webrtc2), NULL);
GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (t->webrtc2),
GST_DEBUG_GRAPH_SHOW_ALL, dump_name);
g_free (dump_name);
}
GST_INFO ("EOS received\n");
t->state = STATE_EOS;
g_cond_broadcast (&t->cond);
break;
}
default:
break;
}
if (t->bus_message)
t->bus_message (t, bus, msg, t->bus_data);
g_mutex_unlock (&t->lock);
return TRUE;
}
static void
_on_negotiation_needed (GstElement * webrtc, struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
if (t->on_negotiation_needed)
t->on_negotiation_needed (t, webrtc, t->negotiation_data);
if (t->state == STATE_NEW)
t->state = STATE_NEGOTATION_NEEDED;
g_cond_broadcast (&t->cond);
g_mutex_unlock (&t->lock);
}
static void
_on_ice_candidate (GstElement * webrtc, guint mlineindex, gchar * candidate,
struct test_webrtc *t)
{
GstElement *other;
g_mutex_lock (&t->lock);
other = webrtc == t->webrtc1 ? t->webrtc2 : t->webrtc1;
if (t->on_ice_candidate)
t->on_ice_candidate (t, webrtc, mlineindex, candidate, other,
t->ice_candidate_data);
g_signal_emit_by_name (other, "add-ice-candidate", mlineindex, candidate);
g_mutex_unlock (&t->lock);
}
static void
_on_pad_added (GstElement * webrtc, GstPad * new_pad, struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
if (t->on_pad_added)
t->on_pad_added (t, webrtc, new_pad, t->pad_added_data);
g_mutex_unlock (&t->lock);
}
static void
_on_data_channel (GstElement * webrtc, GObject * data_channel,
struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
if (t->on_data_channel)
t->on_data_channel (t, webrtc, data_channel, t->data_channel_data);
g_mutex_unlock (&t->lock);
}
static void
_pad_added_not_reached (struct test_webrtc *t, GstElement * element,
GstPad * pad, gpointer user_data)
{
g_assert_not_reached ();
}
static void
_ice_candidate_not_reached (struct test_webrtc *t, GstElement * element,
guint mlineindex, gchar * candidate, GstElement * other, gpointer user_data)
{
g_assert_not_reached ();
}
static void
_negotiation_not_reached (struct test_webrtc *t, GstElement * element,
gpointer user_data)
{
g_assert_not_reached ();
}
static void
_bus_no_errors (struct test_webrtc *t, GstBus * bus, GstMessage * msg,
gpointer user_data)
{
switch (GST_MESSAGE_TYPE (msg)) {
case GST_MESSAGE_ERROR:{
g_assert_not_reached ();
break;
}
default:
break;
}
}
static GstWebRTCSessionDescription *
_offer_answer_not_reached (struct test_webrtc *t, GstElement * element,
GstPromise * promise, gpointer user_data)
{
g_assert_not_reached ();
}
static void
_on_data_channel_not_reached (struct test_webrtc *t, GstElement * element,
GObject * data_channel, gpointer user_data)
{
g_assert_not_reached ();
}
static void
_broadcast (struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
g_cond_broadcast (&t->cond);
g_mutex_unlock (&t->lock);
}
static gboolean
_unlock_create_thread (GMutex * lock)
{
g_mutex_unlock (lock);
return G_SOURCE_REMOVE;
}
static gpointer
_bus_thread (struct test_webrtc *t)
{
g_mutex_lock (&t->lock);
t->loop = g_main_loop_new (NULL, FALSE);
g_idle_add ((GSourceFunc) _unlock_create_thread, &t->lock);
g_cond_broadcast (&t->cond);
g_main_loop_run (t->loop);
g_mutex_lock (&t->lock);
g_main_loop_unref (t->loop);
t->loop = NULL;
g_cond_broadcast (&t->cond);
g_mutex_unlock (&t->lock);
return NULL;
}
static void
element_added_disable_sync (GstBin * bin, GstBin * sub_bin,
GstElement * element, gpointer user_data)
{
GObjectClass *class = G_OBJECT_GET_CLASS (element);
if (g_object_class_find_property (class, "async"))
g_object_set (element, "async", FALSE, NULL);
if (g_object_class_find_property (class, "sync"))
g_object_set (element, "sync", FALSE, NULL);
}
static struct test_webrtc *
test_webrtc_new (void)
{
struct test_webrtc *ret = g_new0 (struct test_webrtc, 1);
ret->on_negotiation_needed = _negotiation_not_reached;
ret->on_ice_candidate = _ice_candidate_not_reached;
ret->on_pad_added = _pad_added_not_reached;
ret->on_offer_created = _offer_answer_not_reached;
ret->on_answer_created = _offer_answer_not_reached;
ret->on_data_channel = _on_data_channel_not_reached;
ret->bus_message = _bus_no_errors;
g_mutex_init (&ret->lock);
g_cond_init (&ret->cond);
ret->bus1 = gst_bus_new ();
ret->bus2 = gst_bus_new ();
gst_bus_add_watch (ret->bus1, (GstBusFunc) _bus_watch, ret);
gst_bus_add_watch (ret->bus2, (GstBusFunc) _bus_watch, ret);
ret->webrtc1 = gst_element_factory_make ("webrtcbin", NULL);
ret->webrtc2 = gst_element_factory_make ("webrtcbin", NULL);
fail_unless (ret->webrtc1 != NULL && ret->webrtc2 != NULL);
gst_element_set_bus (ret->webrtc1, ret->bus1);
gst_element_set_bus (ret->webrtc2, ret->bus2);
g_signal_connect (ret->webrtc1, "deep-element-added",
G_CALLBACK (element_added_disable_sync), NULL);
g_signal_connect (ret->webrtc2, "deep-element-added",
G_CALLBACK (element_added_disable_sync), NULL);
g_signal_connect (ret->webrtc1, "on-negotiation-needed",
G_CALLBACK (_on_negotiation_needed), ret);
g_signal_connect (ret->webrtc2, "on-negotiation-needed",
G_CALLBACK (_on_negotiation_needed), ret);
g_signal_connect (ret->webrtc1, "on-ice-candidate",
G_CALLBACK (_on_ice_candidate), ret);
g_signal_connect (ret->webrtc2, "on-ice-candidate",
G_CALLBACK (_on_ice_candidate), ret);
g_signal_connect (ret->webrtc1, "on-data-channel",
G_CALLBACK (_on_data_channel), ret);
g_signal_connect (ret->webrtc2, "on-data-channel",
G_CALLBACK (_on_data_channel), ret);
g_signal_connect (ret->webrtc1, "pad-added", G_CALLBACK (_on_pad_added), ret);
g_signal_connect (ret->webrtc2, "pad-added", G_CALLBACK (_on_pad_added), ret);
g_signal_connect_swapped (ret->webrtc1, "notify::ice-gathering-state",
G_CALLBACK (_broadcast), ret);
g_signal_connect_swapped (ret->webrtc2, "notify::ice-gathering-state",
G_CALLBACK (_broadcast), ret);
g_signal_connect_swapped (ret->webrtc1, "notify::ice-connection-state",
G_CALLBACK (_broadcast), ret);
g_signal_connect_swapped (ret->webrtc2, "notify::ice-connection-state",
G_CALLBACK (_broadcast), ret);
ret->thread = g_thread_new ("test-webrtc", (GThreadFunc) _bus_thread, ret);
g_mutex_lock (&ret->lock);
while (!ret->loop)
g_cond_wait (&ret->cond, &ret->lock);
g_mutex_unlock (&ret->lock);
return ret;
}
static void
test_webrtc_free (struct test_webrtc *t)
{
/* Otherwise while one webrtcbin is being destroyed, the other could
* generate a signal that calls into the destroyed webrtcbin */
g_signal_handlers_disconnect_by_data (t->webrtc1, t);
g_signal_handlers_disconnect_by_data (t->webrtc2, t);
g_main_loop_quit (t->loop);
g_mutex_lock (&t->lock);
while (t->loop)
g_cond_wait (&t->cond, &t->lock);
g_mutex_unlock (&t->lock);
g_thread_join (t->thread);
gst_bus_remove_watch (t->bus1);
gst_bus_remove_watch (t->bus2);
gst_bus_set_flushing (t->bus1, TRUE);
gst_bus_set_flushing (t->bus2, TRUE);
gst_object_unref (t->bus1);
gst_object_unref (t->bus2);
g_list_free_full (t->harnesses, (GDestroyNotify) gst_harness_teardown);
if (t->data_notify)
t->data_notify (t->user_data);
if (t->negotiation_notify)
t->negotiation_notify (t->negotiation_data);
if (t->ice_candidate_notify)
t->ice_candidate_notify (t->ice_candidate_data);
if (t->offer_notify)
t->offer_notify (t->offer_data);
if (t->answer_notify)
t->answer_notify (t->answer_data);
if (t->pad_added_notify)
t->pad_added_notify (t->pad_added_data);
if (t->data_channel_notify)
t->data_channel_notify (t->data_channel_data);
fail_unless_equals_int (GST_STATE_CHANGE_SUCCESS,
gst_element_set_state (t->webrtc1, GST_STATE_NULL));
fail_unless_equals_int (GST_STATE_CHANGE_SUCCESS,
gst_element_set_state (t->webrtc2, GST_STATE_NULL));
gst_object_unref (t->webrtc1);
gst_object_unref (t->webrtc2);
g_mutex_clear (&t->lock);
g_cond_clear (&t->cond);
g_free (t);
}
static void
test_webrtc_create_offer (struct test_webrtc *t, GstElement * webrtc)
{
GstPromise *promise;
t->offerror = webrtc == t->webrtc1 ? 1 : 2;
promise = gst_promise_new_with_change_func (_on_offer_received, t, NULL);
g_signal_emit_by_name (webrtc, "create-offer", NULL, promise);
}
static void
test_webrtc_wait_for_state_mask (struct test_webrtc *t, TestState state)
{
g_mutex_lock (&t->lock);
while (((1 << t->state) & state) == 0) {
GST_INFO ("test state 0x%x, current 0x%x", state, (1 << t->state));
g_cond_wait (&t->cond, &t->lock);
}
GST_INFO ("have test state 0x%x, current 0x%x", state, 1 << t->state);
g_mutex_unlock (&t->lock);
}
static void
test_webrtc_wait_for_answer_error_eos (struct test_webrtc *t)
{
TestState states = 0;
states |= (1 << STATE_ANSWER_CREATED);
states |= (1 << STATE_EOS);
states |= (1 << STATE_ERROR);
test_webrtc_wait_for_state_mask (t, states);
}
static void
test_webrtc_signal_state_unlocked (struct test_webrtc *t, TestState state)
{
t->state = state;
g_cond_broadcast (&t->cond);
}
static void
test_webrtc_signal_state (struct test_webrtc *t, TestState state)
{
g_mutex_lock (&t->lock);
test_webrtc_signal_state_unlocked (t, state);
g_mutex_unlock (&t->lock);
}
#if 0
static void
test_webrtc_wait_for_ice_gathering_complete (struct test_webrtc *t)
{
GstWebRTCICEGatheringState ice_state1, ice_state2;
g_mutex_lock (&t->lock);
g_object_get (t->webrtc1, "ice-gathering-state", &ice_state1, NULL);
g_object_get (t->webrtc2, "ice-gathering-state", &ice_state2, NULL);
while (ice_state1 != GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE &&
ice_state2 != GST_WEBRTC_ICE_GATHERING_STATE_COMPLETE) {
g_cond_wait (&t->cond, &t->lock);
g_object_get (t->webrtc1, "ice-gathering-state", &ice_state1, NULL);
g_object_get (t->webrtc2, "ice-gathering-state", &ice_state2, NULL);
}
g_mutex_unlock (&t->lock);
}
static void
test_webrtc_wait_for_ice_connection (struct test_webrtc *t,
GstWebRTCICEConnectionState states)
{
GstWebRTCICEConnectionState ice_state1, ice_state2, current;
g_mutex_lock (&t->lock);
g_object_get (t->webrtc1, "ice-connection-state", &ice_state1, NULL);
g_object_get (t->webrtc2, "ice-connection-state", &ice_state2, NULL);
current = (1 << ice_state1) | (1 << ice_state2);
while ((current & states) == 0 || (current & ~states)) {
g_cond_wait (&t->cond, &t->lock);
g_object_get (t->webrtc1, "ice-connection-state", &ice_state1, NULL);
g_object_get (t->webrtc2, "ice-connection-state", &ice_state2, NULL);
current = (1 << ice_state1) | (1 << ice_state2);
}
g_mutex_unlock (&t->lock);
}
#endif
static void
_pad_added_fakesink (struct test_webrtc *t, GstElement * element,
GstPad * pad, gpointer user_data)
{
GstHarness *h;
if (GST_PAD_DIRECTION (pad) != GST_PAD_SRC)
return;
h = gst_harness_new_with_element (element, NULL, "src_%u");
gst_harness_add_sink_parse (h, "fakesink async=false sync=false");
t->harnesses = g_list_prepend (t->harnesses, h);
}
static GstWebRTCSessionDescription *
_count_num_sdp_media (struct test_webrtc *t, GstElement * element,
GstPromise * promise, gpointer user_data)
{
GstWebRTCSessionDescription *offer = NULL;
guint expected = GPOINTER_TO_UINT (user_data);
const GstStructure *reply;
const gchar *field;
field = t->offerror == 1 && t->webrtc1 == element ? "offer" : "answer";
reply = gst_promise_get_reply (promise);
gst_structure_get (reply, field,
GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
fail_unless_equals_int (gst_sdp_message_medias_len (offer->sdp), expected);
return offer;
}
GST_START_TEST (test_sdp_no_media)
{
struct test_webrtc *t = test_webrtc_new ();
/* check that a no stream connection creates 0 media sections */
t->on_negotiation_needed = NULL;
t->offer_data = GUINT_TO_POINTER (0);
t->on_offer_created = _count_num_sdp_media;
t->answer_data = GUINT_TO_POINTER (0);
t->on_answer_created = _count_num_sdp_media;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless (t->state == STATE_ANSWER_CREATED);
test_webrtc_free (t);
}
GST_END_TEST;
static void
add_fake_audio_src_harness (GstHarness * h, gint pt)
{
GstCaps *caps = gst_caps_from_string (OPUS_RTP_CAPS (pt));
GstStructure *s = gst_caps_get_structure (caps, 0);
gst_structure_set (s, "payload", G_TYPE_INT, pt, NULL);
gst_harness_set_src_caps (h, caps);
gst_harness_add_src_parse (h, "fakesrc is-live=true", TRUE);
}
static void
add_fake_video_src_harness (GstHarness * h, gint pt)
{
GstCaps *caps = gst_caps_from_string (VP8_RTP_CAPS (pt));
GstStructure *s = gst_caps_get_structure (caps, 0);
gst_structure_set (s, "payload", G_TYPE_INT, pt, NULL);
gst_harness_set_src_caps (h, caps);
gst_harness_add_src_parse (h, "fakesrc is-live=true", TRUE);
}
static struct test_webrtc *
create_audio_test (void)
{
struct test_webrtc *t = test_webrtc_new ();
GstHarness *h;
t->on_negotiation_needed = NULL;
t->on_pad_added = _pad_added_fakesink;
h = gst_harness_new_with_element (t->webrtc1, "sink_0", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
return t;
}
GST_START_TEST (test_audio)
{
struct test_webrtc *t = create_audio_test ();
/* check that a single stream connection creates the associated number
* of media sections */
t->on_negotiation_needed = NULL;
t->offer_data = GUINT_TO_POINTER (1);
t->on_offer_created = _count_num_sdp_media;
t->answer_data = GUINT_TO_POINTER (1);
t->on_answer_created = _count_num_sdp_media;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
static struct test_webrtc *
create_audio_video_test (void)
{
struct test_webrtc *t = test_webrtc_new ();
GstHarness *h;
t->on_negotiation_needed = NULL;
t->on_pad_added = _pad_added_fakesink;
h = gst_harness_new_with_element (t->webrtc1, "sink_0", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
h = gst_harness_new_with_element (t->webrtc1, "sink_1", NULL);
add_fake_video_src_harness (h, 97);
t->harnesses = g_list_prepend (t->harnesses, h);
return t;
}
GST_START_TEST (test_audio_video)
{
struct test_webrtc *t = create_audio_video_test ();
/* check that a dual stream connection creates the associated number
* of media sections */
t->on_negotiation_needed = NULL;
t->offer_data = GUINT_TO_POINTER (2);
t->on_offer_created = _count_num_sdp_media;
t->answer_data = GUINT_TO_POINTER (2);
t->on_answer_created = _count_num_sdp_media;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
typedef void (*ValidateSDPFunc) (struct test_webrtc * t, GstElement * element,
GstWebRTCSessionDescription * desc, gpointer user_data);
struct validate_sdp
{
ValidateSDPFunc validate;
gpointer user_data;
};
static GstWebRTCSessionDescription *
_check_validate_sdp (struct test_webrtc *t, GstElement * element,
GstPromise * promise, gpointer user_data)
{
struct validate_sdp *validate = user_data;
GstWebRTCSessionDescription *offer = NULL;
const GstStructure *reply;
const gchar *field;
field = t->offerror == 1 && t->webrtc1 == element ? "offer" : "answer";
reply = gst_promise_get_reply (promise);
gst_structure_get (reply, field,
GST_TYPE_WEBRTC_SESSION_DESCRIPTION, &offer, NULL);
validate->validate (t, element, offer, validate->user_data);
return offer;
}
static void
on_sdp_media_direction (struct test_webrtc *t, GstElement * element,
GstWebRTCSessionDescription * desc, gpointer user_data)
{
gchar **expected_directions = user_data;
int i;
for (i = 0; i < gst_sdp_message_medias_len (desc->sdp); i++) {
const GstSDPMedia *media = gst_sdp_message_get_media (desc->sdp, i);
gboolean have_direction = FALSE;
int j;
for (j = 0; j < gst_sdp_media_attributes_len (media); j++) {
const GstSDPAttribute *attr = gst_sdp_media_get_attribute (media, j);
if (g_strcmp0 (attr->key, "inactive") == 0) {
fail_unless (have_direction == FALSE,
"duplicate/multiple directions for media %u", j);
have_direction = TRUE;
fail_unless (g_strcmp0 (attr->key, expected_directions[i]) == 0);
} else if (g_strcmp0 (attr->key, "sendonly") == 0) {
fail_unless (have_direction == FALSE,
"duplicate/multiple directions for media %u", j);
have_direction = TRUE;
fail_unless (g_strcmp0 (attr->key, expected_directions[i]) == 0);
} else if (g_strcmp0 (attr->key, "recvonly") == 0) {
fail_unless (have_direction == FALSE,
"duplicate/multiple directions for media %u", j);
have_direction = TRUE;
fail_unless (g_strcmp0 (attr->key, expected_directions[i]) == 0);
} else if (g_strcmp0 (attr->key, "sendrecv") == 0) {
fail_unless (have_direction == FALSE,
"duplicate/multiple directions for media %u", j);
have_direction = TRUE;
fail_unless (g_strcmp0 (attr->key, expected_directions[i]) == 0);
}
}
fail_unless (have_direction, "no direction attribute in media %u", j);
}
}
GST_START_TEST (test_media_direction)
{
struct test_webrtc *t = create_audio_video_test ();
const gchar *expected_offer[] = { "sendrecv", "sendrecv" };
const gchar *expected_answer[] = { "sendrecv", "recvonly" };
struct validate_sdp offer = { on_sdp_media_direction, expected_offer };
struct validate_sdp answer = { on_sdp_media_direction, expected_answer };
GstHarness *h;
/* check the default media directions for transceivers */
h = gst_harness_new_with_element (t->webrtc2, "sink_0", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
static void
on_sdp_media_payload_types (struct test_webrtc *t, GstElement * element,
GstWebRTCSessionDescription * desc, gpointer user_data)
{
const GstSDPMedia *vmedia;
guint j;
fail_unless_equals_int (gst_sdp_message_medias_len (desc->sdp), 2);
vmedia = gst_sdp_message_get_media (desc->sdp, 1);
for (j = 0; j < gst_sdp_media_attributes_len (vmedia); j++) {
const GstSDPAttribute *attr = gst_sdp_media_get_attribute (vmedia, j);
if (!g_strcmp0 (attr->key, "rtpmap")) {
if (g_str_has_prefix (attr->value, "97")) {
fail_unless_equals_string (attr->value, "97 VP8/90000");
} else if (g_str_has_prefix (attr->value, "96")) {
fail_unless_equals_string (attr->value, "96 red/90000");
} else if (g_str_has_prefix (attr->value, "98")) {
fail_unless_equals_string (attr->value, "98 ulpfec/90000");
} else if (g_str_has_prefix (attr->value, "99")) {
fail_unless_equals_string (attr->value, "99 rtx/90000");
} else if (g_str_has_prefix (attr->value, "100")) {
fail_unless_equals_string (attr->value, "100 rtx/90000");
}
}
}
}
/* In this test we verify that webrtcbin will pick available payload
* types when it needs to, in that example for RTX and FEC */
GST_START_TEST (test_payload_types)
{
struct test_webrtc *t = create_audio_video_test ();
struct validate_sdp offer = { on_sdp_media_payload_types, NULL };
GstWebRTCRTPTransceiver *trans;
GArray *transceivers;
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
/* We don't really care about the answer here */
t->on_answer_created = NULL;
g_signal_emit_by_name (t->webrtc1, "get-transceivers", &transceivers);
fail_unless_equals_int (transceivers->len, 2);
trans = g_array_index (transceivers, GstWebRTCRTPTransceiver *, 1);
g_object_set (trans, "fec-type", GST_WEBRTC_FEC_TYPE_ULP_RED, "do-nack", TRUE,
NULL);
g_array_unref (transceivers);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
static void
on_sdp_media_setup (struct test_webrtc *t, GstElement * element,
GstWebRTCSessionDescription * desc, gpointer user_data)
{
gchar **expected_setup = user_data;
int i;
for (i = 0; i < gst_sdp_message_medias_len (desc->sdp); i++) {
const GstSDPMedia *media = gst_sdp_message_get_media (desc->sdp, i);
gboolean have_setup = FALSE;
int j;
for (j = 0; j < gst_sdp_media_attributes_len (media); j++) {
const GstSDPAttribute *attr = gst_sdp_media_get_attribute (media, j);
if (g_strcmp0 (attr->key, "setup") == 0) {
fail_unless (have_setup == FALSE,
"duplicate/multiple setup for media %u", j);
have_setup = TRUE;
fail_unless (g_strcmp0 (attr->value, expected_setup[i]) == 0);
}
}
fail_unless (have_setup, "no setup attribute in media %u", j);
}
}
GST_START_TEST (test_media_setup)
{
struct test_webrtc *t = create_audio_test ();
const gchar *expected_offer[] = { "actpass" };
const gchar *expected_answer[] = { "active" };
struct validate_sdp offer = { on_sdp_media_setup, expected_offer };
struct validate_sdp answer = { on_sdp_media_setup, expected_answer };
/* check the default dtls setup negotiation values */
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_no_nice_elements_request_pad)
{
struct test_webrtc *t = test_webrtc_new ();
GstPluginFeature *nicesrc, *nicesink;
GstRegistry *registry;
GstPad *pad;
/* check that the absence of libnice elements posts an error on the bus
* when requesting a pad */
registry = gst_registry_get ();
nicesrc = gst_registry_lookup_feature (registry, "nicesrc");
nicesink = gst_registry_lookup_feature (registry, "nicesink");
if (nicesrc)
gst_registry_remove_feature (registry, nicesrc);
if (nicesink)
gst_registry_remove_feature (registry, nicesink);
t->bus_message = NULL;
pad = gst_element_get_request_pad (t->webrtc1, "sink_0");
fail_unless (pad == NULL);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ERROR, t->state);
test_webrtc_free (t);
if (nicesrc)
gst_registry_add_feature (registry, nicesrc);
if (nicesink)
gst_registry_add_feature (registry, nicesink);
}
GST_END_TEST;
GST_START_TEST (test_no_nice_elements_state_change)
{
struct test_webrtc *t = test_webrtc_new ();
GstPluginFeature *nicesrc, *nicesink;
GstRegistry *registry;
/* check that the absence of libnice elements posts an error on the bus */
registry = gst_registry_get ();
nicesrc = gst_registry_lookup_feature (registry, "nicesrc");
nicesink = gst_registry_lookup_feature (registry, "nicesink");
if (nicesrc)
gst_registry_remove_feature (registry, nicesrc);
if (nicesink)
gst_registry_remove_feature (registry, nicesink);
t->bus_message = NULL;
gst_element_set_state (t->webrtc1, GST_STATE_READY);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ERROR, t->state);
test_webrtc_free (t);
if (nicesrc)
gst_registry_add_feature (registry, nicesrc);
if (nicesink)
gst_registry_add_feature (registry, nicesink);
}
GST_END_TEST;
static void
validate_rtc_stats (const GstStructure * s)
{
GstWebRTCStatsType type = 0;
double ts = 0.;
gchar *id = NULL;
fail_unless (gst_structure_get (s, "type", GST_TYPE_WEBRTC_STATS_TYPE, &type,
NULL));
fail_unless (gst_structure_get (s, "id", G_TYPE_STRING, &id, NULL));
fail_unless (gst_structure_get (s, "timestamp", G_TYPE_DOUBLE, &ts, NULL));
fail_unless (type != 0);
fail_unless (ts != 0.);
fail_unless (id != NULL);
g_free (id);
}
static void
validate_codec_stats (const GstStructure * s)
{
guint pt = 0, clock_rate = 0;
fail_unless (gst_structure_get (s, "payload-type", G_TYPE_UINT, &pt, NULL));
fail_unless (gst_structure_get (s, "clock-rate", G_TYPE_UINT, &clock_rate,
NULL));
fail_unless (pt >= 0 && pt <= 127);
fail_unless (clock_rate >= 0);
}
static void
validate_rtc_stream_stats (const GstStructure * s, const GstStructure * stats)
{
gchar *codec_id, *transport_id;
GstStructure *codec, *transport;
fail_unless (gst_structure_get (s, "codec-id", G_TYPE_STRING, &codec_id,
NULL));
fail_unless (gst_structure_get (s, "transport-id", G_TYPE_STRING,
&transport_id, NULL));
fail_unless (gst_structure_get (stats, codec_id, GST_TYPE_STRUCTURE, &codec,
NULL));
fail_unless (gst_structure_get (stats, transport_id, GST_TYPE_STRUCTURE,
&transport, NULL));
fail_unless (codec != NULL);
fail_unless (transport != NULL);
gst_structure_free (transport);
gst_structure_free (codec);
g_free (codec_id);
g_free (transport_id);
}
static void
validate_inbound_rtp_stats (const GstStructure * s, const GstStructure * stats)
{
guint ssrc, fir, pli, nack;
gint packets_lost;
guint64 packets_received, bytes_received;
double jitter;
gchar *remote_id;
GstStructure *remote;
validate_rtc_stream_stats (s, stats);
fail_unless (gst_structure_get (s, "ssrc", G_TYPE_UINT, &ssrc, NULL));
fail_unless (gst_structure_get (s, "fir-count", G_TYPE_UINT, &fir, NULL));
fail_unless (gst_structure_get (s, "pli-count", G_TYPE_UINT, &pli, NULL));
fail_unless (gst_structure_get (s, "nack-count", G_TYPE_UINT, &nack, NULL));
fail_unless (gst_structure_get (s, "packets-received", G_TYPE_UINT64,
&packets_received, NULL));
fail_unless (gst_structure_get (s, "bytes-received", G_TYPE_UINT64,
&bytes_received, NULL));
fail_unless (gst_structure_get (s, "jitter", G_TYPE_DOUBLE, &jitter, NULL));
fail_unless (gst_structure_get (s, "packets-lost", G_TYPE_INT, &packets_lost,
NULL));
fail_unless (gst_structure_get (s, "remote-id", G_TYPE_STRING, &remote_id,
NULL));
fail_unless (gst_structure_get (stats, remote_id, GST_TYPE_STRUCTURE, &remote,
NULL));
fail_unless (remote != NULL);
gst_structure_free (remote);
g_free (remote_id);
}
static void
validate_remote_inbound_rtp_stats (const GstStructure * s,
const GstStructure * stats)
{
guint ssrc;
gint packets_lost;
double jitter, rtt;
gchar *local_id;
GstStructure *local;
validate_rtc_stream_stats (s, stats);
fail_unless (gst_structure_get (s, "ssrc", G_TYPE_UINT, &ssrc, NULL));
fail_unless (gst_structure_get (s, "jitter", G_TYPE_DOUBLE, &jitter, NULL));
fail_unless (gst_structure_get (s, "packets-lost", G_TYPE_INT, &packets_lost,
NULL));
fail_unless (gst_structure_get (s, "round-trip-time", G_TYPE_DOUBLE, &rtt,
NULL));
fail_unless (gst_structure_get (s, "local-id", G_TYPE_STRING, &local_id,
NULL));
fail_unless (gst_structure_get (stats, local_id, GST_TYPE_STRUCTURE, &local,
NULL));
fail_unless (local != NULL);
gst_structure_free (local);
g_free (local_id);
}
static void
validate_outbound_rtp_stats (const GstStructure * s, const GstStructure * stats)
{
guint ssrc, fir, pli, nack;
guint64 packets_sent, bytes_sent;
gchar *remote_id;
GstStructure *remote;
validate_rtc_stream_stats (s, stats);
fail_unless (gst_structure_get (s, "ssrc", G_TYPE_UINT, &ssrc, NULL));
fail_unless (gst_structure_get (s, "fir-count", G_TYPE_UINT, &fir, NULL));
fail_unless (gst_structure_get (s, "pli-count", G_TYPE_UINT, &pli, NULL));
fail_unless (gst_structure_get (s, "nack-count", G_TYPE_UINT, &nack, NULL));
fail_unless (gst_structure_get (s, "packets-sent", G_TYPE_UINT64,
&packets_sent, NULL));
fail_unless (gst_structure_get (s, "bytes-sent", G_TYPE_UINT64, &bytes_sent,
NULL));
fail_unless (gst_structure_get (s, "remote-id", G_TYPE_STRING, &remote_id,
NULL));
fail_unless (gst_structure_get (stats, remote_id, GST_TYPE_STRUCTURE, &remote,
NULL));
fail_unless (remote != NULL);
gst_structure_free (remote);
g_free (remote_id);
}
static void
validate_remote_outbound_rtp_stats (const GstStructure * s,
const GstStructure * stats)
{
guint ssrc;
gchar *local_id;
GstStructure *local;
validate_rtc_stream_stats (s, stats);
fail_unless (gst_structure_get (s, "ssrc", G_TYPE_UINT, &ssrc, NULL));
fail_unless (gst_structure_get (s, "local-id", G_TYPE_STRING, &local_id,
NULL));
fail_unless (gst_structure_get (stats, local_id, GST_TYPE_STRUCTURE, &local,
NULL));
fail_unless (local != NULL);
gst_structure_free (local);
g_free (local_id);
}
static gboolean
validate_stats_foreach (GQuark field_id, const GValue * value,
const GstStructure * stats)
{
const gchar *field = g_quark_to_string (field_id);
GstWebRTCStatsType type;
const GstStructure *s;
fail_unless (GST_VALUE_HOLDS_STRUCTURE (value));
s = gst_value_get_structure (value);
GST_INFO ("validating field %s %" GST_PTR_FORMAT, field, s);
validate_rtc_stats (s);
gst_structure_get (s, "type", GST_TYPE_WEBRTC_STATS_TYPE, &type, NULL);
if (type == GST_WEBRTC_STATS_CODEC) {
validate_codec_stats (s);
} else if (type == GST_WEBRTC_STATS_INBOUND_RTP) {
validate_inbound_rtp_stats (s, stats);
} else if (type == GST_WEBRTC_STATS_OUTBOUND_RTP) {
validate_outbound_rtp_stats (s, stats);
} else if (type == GST_WEBRTC_STATS_REMOTE_INBOUND_RTP) {
validate_remote_inbound_rtp_stats (s, stats);
} else if (type == GST_WEBRTC_STATS_REMOTE_OUTBOUND_RTP) {
validate_remote_outbound_rtp_stats (s, stats);
} else if (type == GST_WEBRTC_STATS_CSRC) {
} else if (type == GST_WEBRTC_STATS_PEER_CONNECTION) {
} else if (type == GST_WEBRTC_STATS_DATA_CHANNEL) {
} else if (type == GST_WEBRTC_STATS_STREAM) {
} else if (type == GST_WEBRTC_STATS_TRANSPORT) {
} else if (type == GST_WEBRTC_STATS_CANDIDATE_PAIR) {
} else if (type == GST_WEBRTC_STATS_LOCAL_CANDIDATE) {
} else if (type == GST_WEBRTC_STATS_REMOTE_CANDIDATE) {
} else if (type == GST_WEBRTC_STATS_CERTIFICATE) {
} else {
g_assert_not_reached ();
}
return TRUE;
}
static void
validate_stats (const GstStructure * stats)
{
gst_structure_foreach (stats,
(GstStructureForeachFunc) validate_stats_foreach, (gpointer) stats);
}
static void
_on_stats (GstPromise * promise, gpointer user_data)
{
struct test_webrtc *t = user_data;
const GstStructure *reply = gst_promise_get_reply (promise);
int i;
validate_stats (reply);
i = GPOINTER_TO_INT (t->user_data);
i++;
t->user_data = GINT_TO_POINTER (i);
if (i >= 2)
test_webrtc_signal_state (t, STATE_CUSTOM);
gst_promise_unref (promise);
}
GST_START_TEST (test_session_stats)
{
struct test_webrtc *t = test_webrtc_new ();
GstPromise *p;
/* test that the stats generated without any streams are sane */
t->on_negotiation_needed = NULL;
t->on_offer_created = NULL;
t->on_answer_created = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
p = gst_promise_new_with_change_func (_on_stats, t, NULL);
g_signal_emit_by_name (t->webrtc1, "get-stats", NULL, p);
p = gst_promise_new_with_change_func (_on_stats, t, NULL);
g_signal_emit_by_name (t->webrtc2, "get-stats", NULL, p);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_add_transceiver)
{
struct test_webrtc *t = test_webrtc_new ();
GstWebRTCRTPTransceiverDirection direction;
GstWebRTCRTPTransceiver *trans;
direction = GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_SENDRECV;
g_signal_emit_by_name (t->webrtc1, "add-transceiver", direction, NULL,
&trans);
fail_unless (trans != NULL);
fail_unless_equals_int (direction, trans->direction);
gst_object_unref (trans);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_get_transceivers)
{
struct test_webrtc *t = create_audio_test ();
GstWebRTCRTPTransceiver *trans;
GArray *transceivers;
g_signal_emit_by_name (t->webrtc1, "get-transceivers", &transceivers);
fail_unless (transceivers != NULL);
fail_unless_equals_int (1, transceivers->len);
trans = g_array_index (transceivers, GstWebRTCRTPTransceiver *, 0);
fail_unless (trans != NULL);
g_array_unref (transceivers);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_add_recvonly_transceiver)
{
struct test_webrtc *t = test_webrtc_new ();
GstWebRTCRTPTransceiverDirection direction;
GstWebRTCRTPTransceiver *trans;
const gchar *expected_offer[] = { "recvonly" };
const gchar *expected_answer[] = { "sendonly" };
struct validate_sdp offer = { on_sdp_media_direction, expected_offer };
struct validate_sdp answer = { on_sdp_media_direction, expected_answer };
GstCaps *caps;
GstHarness *h;
/* add a transceiver that will only receive an opus stream and check that
* the created offer is marked as recvonly */
t->on_negotiation_needed = NULL;
t->on_pad_added = _pad_added_fakesink;
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
/* setup recvonly transceiver */
caps = gst_caps_from_string (OPUS_RTP_CAPS (96));
direction = GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_RECVONLY;
g_signal_emit_by_name (t->webrtc1, "add-transceiver", direction, caps,
&trans);
gst_caps_unref (caps);
fail_unless (trans != NULL);
gst_object_unref (trans);
/* setup sendonly peer */
h = gst_harness_new_with_element (t->webrtc2, "sink_0", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_recvonly_sendonly)
{
struct test_webrtc *t = test_webrtc_new ();
GstWebRTCRTPTransceiverDirection direction;
GstWebRTCRTPTransceiver *trans;
const gchar *expected_offer[] = { "recvonly", "sendonly" };
const gchar *expected_answer[] = { "sendonly", "recvonly" };
struct validate_sdp offer = { on_sdp_media_direction, expected_offer };
struct validate_sdp answer = { on_sdp_media_direction, expected_answer };
GstCaps *caps;
GstHarness *h;
GArray *transceivers;
/* add a transceiver that will only receive an opus stream and check that
* the created offer is marked as recvonly */
t->on_negotiation_needed = NULL;
t->on_pad_added = _pad_added_fakesink;
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
/* setup recvonly transceiver */
caps = gst_caps_from_string (OPUS_RTP_CAPS (96));
direction = GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_RECVONLY;
g_signal_emit_by_name (t->webrtc1, "add-transceiver", direction, caps,
&trans);
gst_caps_unref (caps);
fail_unless (trans != NULL);
gst_object_unref (trans);
/* setup sendonly stream */
h = gst_harness_new_with_element (t->webrtc1, "sink_1", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
g_signal_emit_by_name (t->webrtc1, "get-transceivers", &transceivers);
fail_unless (transceivers != NULL);
trans = g_array_index (transceivers, GstWebRTCRTPTransceiver *, 1);
trans->direction = GST_WEBRTC_RTP_TRANSCEIVER_DIRECTION_SENDONLY;
g_array_unref (transceivers);
/* setup sendonly peer */
h = gst_harness_new_with_element (t->webrtc2, "sink_0", NULL);
add_fake_audio_src_harness (h, 96);
t->harnesses = g_list_prepend (t->harnesses, h);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
static void
on_sdp_has_datachannel (struct test_webrtc *t, GstElement * element,
GstWebRTCSessionDescription * desc, gpointer user_data)
{
gboolean have_data_channel = FALSE;
int i;
for (i = 0; i < gst_sdp_message_medias_len (desc->sdp); i++) {
if (_message_media_is_datachannel (desc->sdp, i)) {
/* there should only be one data channel m= section */
fail_unless_equals_int (FALSE, have_data_channel);
have_data_channel = TRUE;
}
}
fail_unless_equals_int (TRUE, have_data_channel);
}
static void
on_channel_error_not_reached (GObject * channel, GError * error,
gpointer user_data)
{
g_assert_not_reached ();
}
GST_START_TEST (test_data_channel_create)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
gchar *label;
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
g_object_get (channel, "label", &label, NULL);
g_assert_cmpstr (label, ==, "label");
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
g_object_unref (channel);
g_free (label);
test_webrtc_free (t);
}
GST_END_TEST;
static void
have_data_channel (struct test_webrtc *t, GstElement * element,
GObject * our, gpointer user_data)
{
GObject *other = user_data;
gchar *our_label, *other_label;
g_signal_connect (our, "on-error", G_CALLBACK (on_channel_error_not_reached),
NULL);
g_object_get (our, "label", &our_label, NULL);
g_object_get (other, "label", &other_label, NULL);
g_assert_cmpstr (our_label, ==, other_label);
g_free (our_label);
g_free (other_label);
test_webrtc_signal_state_unlocked (t, STATE_CUSTOM);
}
GST_START_TEST (test_data_channel_remote_notify)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static const gchar *test_string = "GStreamer WebRTC is awesome!";
static void
on_message_string (GObject * channel, const gchar * str, struct test_webrtc *t)
{
gchar *expected = g_object_steal_data (channel, "expected");
g_assert_cmpstr (expected, ==, str);
g_free (expected);
test_webrtc_signal_state (t, STATE_CUSTOM);
}
static void
have_data_channel_transfer_string (struct test_webrtc *t, GstElement * element,
GObject * our, gpointer user_data)
{
GObject *other = user_data;
GstWebRTCDataChannelState state;
g_object_get (our, "ready-state", &state, NULL);
fail_unless_equals_int (GST_WEBRTC_DATA_CHANNEL_STATE_OPEN, state);
g_object_get (other, "ready-state", &state, NULL);
fail_unless_equals_int (GST_WEBRTC_DATA_CHANNEL_STATE_OPEN, state);
g_object_set_data_full (our, "expected", g_strdup (test_string), g_free);
g_signal_connect (our, "on-message-string", G_CALLBACK (on_message_string),
t);
g_signal_connect (other, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
g_signal_emit_by_name (other, "send-string", test_string);
}
GST_START_TEST (test_data_channel_transfer_string)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel_transfer_string;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
#define g_assert_cmpbytes(b1, b2) \
G_STMT_START { \
gsize l1, l2; \
const guint8 *d1 = g_bytes_get_data (b1, &l1); \
const guint8 *d2 = g_bytes_get_data (b2, &l2); \
g_assert_cmpmem (d1, l1, d2, l2); \
} G_STMT_END;
static void
on_message_data (GObject * channel, GBytes * data, struct test_webrtc *t)
{
GBytes *expected = g_object_steal_data (channel, "expected");
g_assert_cmpbytes (data, expected);
g_bytes_unref (expected);
test_webrtc_signal_state (t, STATE_CUSTOM);
}
static void
have_data_channel_transfer_data (struct test_webrtc *t, GstElement * element,
GObject * our, gpointer user_data)
{
GObject *other = user_data;
GBytes *data = g_bytes_new_static (test_string, strlen (test_string));
GstWebRTCDataChannelState state;
g_object_get (our, "ready-state", &state, NULL);
fail_unless_equals_int (GST_WEBRTC_DATA_CHANNEL_STATE_OPEN, state);
g_object_get (other, "ready-state", &state, NULL);
fail_unless_equals_int (GST_WEBRTC_DATA_CHANNEL_STATE_OPEN, state);
g_object_set_data_full (our, "expected", g_bytes_ref (data),
(GDestroyNotify) g_bytes_unref);
g_signal_connect (our, "on-message-data", G_CALLBACK (on_message_data), t);
g_signal_connect (other, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
g_signal_emit_by_name (other, "send-data", data);
}
GST_START_TEST (test_data_channel_transfer_data)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel_transfer_data;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static void
have_data_channel_create_data_channel (struct test_webrtc *t,
GstElement * element, GObject * our, gpointer user_data)
{
GObject *another;
t->on_data_channel = have_data_channel_transfer_string;
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&another);
g_assert_nonnull (another);
t->data_channel_data = another;
g_signal_connect (another, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
}
GST_START_TEST (test_data_channel_create_after_negotiate)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel_create_data_channel;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "prev-label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static void
on_buffered_amount_low_emitted (GObject * channel, struct test_webrtc *t)
{
test_webrtc_signal_state (t, STATE_CUSTOM);
}
static void
have_data_channel_check_low_threshold_emitted (struct test_webrtc *t,
GstElement * element, GObject * our, gpointer user_data)
{
g_signal_connect (our, "on-buffered-amount-low",
G_CALLBACK (on_buffered_amount_low_emitted), t);
g_object_set (our, "buffered-amount-low-threshold", 1, NULL);
g_signal_connect (our, "on-error", G_CALLBACK (on_channel_error_not_reached),
NULL);
g_signal_emit_by_name (our, "send-string", "DATA");
}
GST_START_TEST (test_data_channel_low_threshold)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel_check_low_threshold_emitted;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
g_signal_connect (channel, "on-error",
G_CALLBACK (on_channel_error_not_reached), NULL);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static void
on_channel_error (GObject * channel, GError * error, struct test_webrtc *t)
{
g_assert_nonnull (error);
test_webrtc_signal_state (t, STATE_CUSTOM);
}
static void
have_data_channel_transfer_large_data (struct test_webrtc *t,
GstElement * element, GObject * our, gpointer user_data)
{
GObject *other = user_data;
const gsize size = 1024 * 1024;
guint8 *random_data = g_new (guint8, size);
GBytes *data;
gsize i;
for (i = 0; i < size; i++)
random_data[i] = (guint8) (i & 0xff);
data = g_bytes_new_static (random_data, size);
g_object_set_data_full (our, "expected", g_bytes_ref (data),
(GDestroyNotify) g_bytes_unref);
g_signal_connect (our, "on-message-data", G_CALLBACK (on_message_data), t);
g_signal_connect (other, "on-error", G_CALLBACK (on_channel_error), t);
g_signal_emit_by_name (other, "send-data", data);
}
GST_START_TEST (test_data_channel_max_message_size)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
t->on_data_channel = have_data_channel_transfer_large_data;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
g_assert_nonnull (channel);
t->data_channel_data = channel;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static void
_on_ready_state_notify (GObject * channel, GParamSpec * pspec,
struct test_webrtc *t)
{
gint *n_ready = t->data_channel_data;
GstWebRTCDataChannelState ready_state;
g_object_get (channel, "ready-state", &ready_state, NULL);
if (ready_state == GST_WEBRTC_DATA_CHANNEL_STATE_OPEN) {
if (++(*n_ready) >= 2)
test_webrtc_signal_state (t, STATE_CUSTOM);
}
}
GST_START_TEST (test_data_channel_pre_negotiated)
{
struct test_webrtc *t = test_webrtc_new ();
GObject *channel1 = NULL, *channel2 = NULL;
struct validate_sdp offer = { on_sdp_has_datachannel, NULL };
struct validate_sdp answer = { on_sdp_has_datachannel, NULL };
GstStructure *s;
gint n_ready = 0;
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
s = gst_structure_new ("application/data-channel", "negotiated",
G_TYPE_BOOLEAN, TRUE, "id", G_TYPE_INT, 1, NULL);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", s,
&channel1);
g_assert_nonnull (channel1);
g_signal_emit_by_name (t->webrtc2, "create-data-channel", "label", s,
&channel2);
g_assert_nonnull (channel2);
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless (t->state == STATE_ANSWER_CREATED);
t->data_channel_data = &n_ready;
g_signal_connect (channel1, "notify::ready-state",
G_CALLBACK (_on_ready_state_notify), t);
g_signal_connect (channel2, "notify::ready-state",
G_CALLBACK (_on_ready_state_notify), t);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
test_webrtc_signal_state (t, STATE_NEW);
have_data_channel_transfer_string (t, t->webrtc1, channel1, channel2);
test_webrtc_wait_for_state_mask (t, 1 << STATE_CUSTOM);
g_object_unref (channel1);
g_object_unref (channel2);
gst_structure_free (s);
test_webrtc_free (t);
}
GST_END_TEST;
typedef struct
{
guint num_media;
guint num_active_media;
const gchar **bundled;
const gchar **bundled_only;
} BundleCheckData;
static void
_check_bundled_sdp_media (struct test_webrtc *t, GstElement * element,
GstWebRTCSessionDescription * sd, gpointer user_data)
{
gchar **bundled = NULL;
BundleCheckData *data = (BundleCheckData *) user_data;
guint i;
guint active_media;
fail_unless_equals_int (gst_sdp_message_medias_len (sd->sdp),
data->num_media);
fail_unless (_parse_bundle (sd->sdp, &bundled));
if (!bundled) {
fail_unless_equals_int (g_strv_length ((GStrv) data->bundled), 0);
} else {
fail_unless_equals_int (g_strv_length (bundled),
g_strv_length ((GStrv) data->bundled));
}
for (i = 0; data->bundled[i]; i++) {
fail_unless (g_strv_contains ((const gchar **) bundled, data->bundled[i]));
}
active_media = 0;
for (i = 0; i < gst_sdp_message_medias_len (sd->sdp); i++) {
const GstSDPMedia *media = gst_sdp_message_get_media (sd->sdp, i);
const gchar *mid = gst_sdp_media_get_attribute_val (media, "mid");
if (g_strv_contains ((const gchar **) data->bundled_only, mid))
fail_unless (_media_has_attribute_key (media, "bundle-only"));
if (gst_sdp_media_get_port (media) != 0)
active_media += 1;
}
fail_unless_equals_int (active_media, data->num_active_media);
if (bundled)
g_strfreev (bundled);
}
GST_START_TEST (test_bundle_audio_video_max_bundle_max_bundle)
{
struct test_webrtc *t = create_audio_video_test ();
const gchar *bundle[] = { "audio0", "video1", NULL };
const gchar *offer_bundle_only[] = { "video1", NULL };
const gchar *answer_bundle_only[] = { NULL };
/* We set a max-bundle policy on the offering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, and they should be marked
* as bundle-only
*/
BundleCheckData offer_data = {
2,
1,
bundle,
offer_bundle_only,
};
/* We also set a max-bundle policy on the answering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, but need not be marked
* as bundle-only.
*/
BundleCheckData answer_data = {
2,
2,
bundle,
answer_bundle_only,
};
struct validate_sdp offer = { _check_bundled_sdp_media, &offer_data };
struct validate_sdp answer = { _check_bundled_sdp_media, &answer_data };
gst_util_set_object_arg (G_OBJECT (t->webrtc1), "bundle-policy",
"max-bundle");
gst_util_set_object_arg (G_OBJECT (t->webrtc2), "bundle-policy",
"max-bundle");
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_bundle_audio_video_max_compat_max_bundle)
{
struct test_webrtc *t = create_audio_video_test ();
const gchar *bundle[] = { "audio0", "video1", NULL };
const gchar *bundle_only[] = { NULL };
/* We set a max-compat policy on the offering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, and they should *not* be marked
* as bundle-only
*/
BundleCheckData offer_data = {
2,
2,
bundle,
bundle_only,
};
/* We set a max-bundle policy on the answering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, but need not be marked
* as bundle-only.
*/
BundleCheckData answer_data = {
2,
2,
bundle,
bundle_only,
};
struct validate_sdp offer = { _check_bundled_sdp_media, &offer_data };
struct validate_sdp answer = { _check_bundled_sdp_media, &answer_data };
gst_util_set_object_arg (G_OBJECT (t->webrtc1), "bundle-policy",
"max-compat");
gst_util_set_object_arg (G_OBJECT (t->webrtc2), "bundle-policy",
"max-bundle");
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_bundle_audio_video_max_bundle_none)
{
struct test_webrtc *t = create_audio_video_test ();
const gchar *offer_bundle[] = { "audio0", "video1", NULL };
const gchar *offer_bundle_only[] = { "video1", NULL };
const gchar *answer_bundle[] = { NULL };
const gchar *answer_bundle_only[] = { NULL };
/* We set a max-bundle policy on the offering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, and they should be marked
* as bundle-only
*/
BundleCheckData offer_data = {
2,
1,
offer_bundle,
offer_bundle_only,
};
/* We set a none policy on the answering webrtcbin,
* this means that the answer should contain no bundled
* medias, and as the bundle-policy of the offering webrtcbin
* is set to max-bundle, only one media should be active.
*/
BundleCheckData answer_data = {
2,
1,
answer_bundle,
answer_bundle_only,
};
struct validate_sdp offer = { _check_bundled_sdp_media, &offer_data };
struct validate_sdp answer = { _check_bundled_sdp_media, &answer_data };
gst_util_set_object_arg (G_OBJECT (t->webrtc1), "bundle-policy",
"max-bundle");
gst_util_set_object_arg (G_OBJECT (t->webrtc2), "bundle-policy", "none");
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
test_webrtc_free (t);
}
GST_END_TEST;
GST_START_TEST (test_bundle_audio_video_data)
{
struct test_webrtc *t = create_audio_video_test ();
const gchar *bundle[] = { "audio0", "video1", "application2", NULL };
const gchar *offer_bundle_only[] = { "video1", "application2", NULL };
const gchar *answer_bundle_only[] = { NULL };
GObject *channel = NULL;
/* We set a max-bundle policy on the offering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, and they should be marked
* as bundle-only
*/
BundleCheckData offer_data = {
3,
1,
bundle,
offer_bundle_only,
};
/* We also set a max-bundle policy on the answering webrtcbin,
* this means that all the offered medias should be part
* of the group:BUNDLE attribute, but need not be marked
* as bundle-only.
*/
BundleCheckData answer_data = {
3,
3,
bundle,
answer_bundle_only,
};
struct validate_sdp offer = { _check_bundled_sdp_media, &offer_data };
struct validate_sdp answer = { _check_bundled_sdp_media, &answer_data };
gst_util_set_object_arg (G_OBJECT (t->webrtc1), "bundle-policy",
"max-bundle");
gst_util_set_object_arg (G_OBJECT (t->webrtc2), "bundle-policy",
"max-bundle");
t->on_negotiation_needed = NULL;
t->offer_data = &offer;
t->on_offer_created = _check_validate_sdp;
t->answer_data = &answer;
t->on_answer_created = _check_validate_sdp;
t->on_ice_candidate = NULL;
fail_if (gst_element_set_state (t->webrtc1,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
fail_if (gst_element_set_state (t->webrtc2,
GST_STATE_READY) == GST_STATE_CHANGE_FAILURE);
g_signal_emit_by_name (t->webrtc1, "create-data-channel", "label", NULL,
&channel);
test_webrtc_create_offer (t, t->webrtc1);
test_webrtc_wait_for_answer_error_eos (t);
fail_unless_equals_int (STATE_ANSWER_CREATED, t->state);
g_object_unref (channel);
test_webrtc_free (t);
}
GST_END_TEST;
static Suite *
webrtcbin_suite (void)
{
Suite *s = suite_create ("webrtcbin");
TCase *tc = tcase_create ("general");
GstPluginFeature *nicesrc, *nicesink, *dtlssrtpdec, *dtlssrtpenc;
GstPluginFeature *sctpenc, *sctpdec;
GstRegistry *registry;
registry = gst_registry_get ();
nicesrc = gst_registry_lookup_feature (registry, "nicesrc");
nicesink = gst_registry_lookup_feature (registry, "nicesink");
dtlssrtpenc = gst_registry_lookup_feature (registry, "dtlssrtpenc");
dtlssrtpdec = gst_registry_lookup_feature (registry, "dtlssrtpdec");
sctpenc = gst_registry_lookup_feature (registry, "sctpenc");
sctpdec = gst_registry_lookup_feature (registry, "sctpdec");
tcase_add_test (tc, test_no_nice_elements_request_pad);
tcase_add_test (tc, test_no_nice_elements_state_change);
if (nicesrc && nicesink && dtlssrtpenc && dtlssrtpdec) {
tcase_add_test (tc, test_sdp_no_media);
tcase_add_test (tc, test_session_stats);
tcase_add_test (tc, test_audio);
tcase_add_test (tc, test_audio_video);
tcase_add_test (tc, test_media_direction);
tcase_add_test (tc, test_media_setup);
tcase_add_test (tc, test_add_transceiver);
tcase_add_test (tc, test_get_transceivers);
tcase_add_test (tc, test_add_recvonly_transceiver);
tcase_add_test (tc, test_recvonly_sendonly);
tcase_add_test (tc, test_payload_types);
tcase_add_test (tc, test_bundle_audio_video_max_bundle_max_bundle);
tcase_add_test (tc, test_bundle_audio_video_max_bundle_none);
tcase_add_test (tc, test_bundle_audio_video_max_compat_max_bundle);
if (sctpenc && sctpdec) {
tcase_add_test (tc, test_data_channel_create);
tcase_add_test (tc, test_data_channel_remote_notify);
tcase_add_test (tc, test_data_channel_transfer_string);
tcase_add_test (tc, test_data_channel_transfer_data);
tcase_add_test (tc, test_data_channel_create_after_negotiate);
tcase_add_test (tc, test_data_channel_low_threshold);
tcase_add_test (tc, test_data_channel_max_message_size);
tcase_add_test (tc, test_data_channel_pre_negotiated);
tcase_add_test (tc, test_bundle_audio_video_data);
} else {
GST_WARNING ("Some required elements were not found. "
"All datachannel are disabled. sctpenc %p, sctpdec %p", sctpenc,
sctpdec);
}
} else {
GST_WARNING ("Some required elements were not found. "
"All media tests are disabled. nicesrc %p, nicesink %p, "
"dtlssrtpenc %p, dtlssrtpdec %p", nicesrc, nicesink, dtlssrtpenc,
dtlssrtpdec);
}
if (nicesrc)
gst_object_unref (nicesrc);
if (nicesink)
gst_object_unref (nicesink);
if (dtlssrtpdec)
gst_object_unref (dtlssrtpdec);
if (dtlssrtpenc)
gst_object_unref (dtlssrtpenc);
if (sctpenc)
gst_object_unref (sctpenc);
if (sctpdec)
gst_object_unref (sctpdec);
suite_add_tcase (s, tc);
return s;
}
GST_CHECK_MAIN (webrtcbin);
| {
"content_hash": "ab1abf4395712074fc117af8607caae3",
"timestamp": "",
"source": "github",
"line_count": 2393,
"max_line_length": 143,
"avg_line_length": 31.882156289176766,
"alnum_prop": 0.6513356227226257,
"repo_name": "google/aistreams",
"id": "c7b7447d09ffe140ff20fa3799ca91da63482109",
"size": "77151",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "third_party/gst-plugins-bad/tests/check/elements/webrtcbin.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "77741"
},
{
"name": "C++",
"bytes": "626396"
},
{
"name": "Python",
"bytes": "41809"
},
{
"name": "Starlark",
"bytes": "56595"
}
],
"symlink_target": ""
} |
This text is included.
<!-- #include nested 2.inc.md --> | {
"content_hash": "138026916139e07715ca6ebb2ba151af",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 33,
"avg_line_length": 19,
"alnum_prop": 0.6491228070175439,
"repo_name": "mastersign/mdinclude",
"id": "0ba50699d0a510eec6e2be5db4fc8b535210008c",
"size": "57",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/data/includes/nested 1.inc.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "12377"
}
],
"symlink_target": ""
} |
from unfurl.core import Unfurl
import unittest
class TestUrl(unittest.TestCase):
def test_url(self):
""" Test a generic URL with a query string"""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://www.test-example.com/testing/1?2=3&4=5')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 12)
self.assertEqual(test.total_nodes, 12)
# confirm the scheme is parsed
self.assertIn('https', test.nodes[2].label)
# confirm the scheme is parsed
self.assertEqual('/testing/1', test.nodes[4].label)
# confirm the query string params parse
self.assertEqual('4: 5', test.nodes[12].label)
def test_lang_param(self):
""" Test a URL with a language query string param"""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://www.test-example.com/testing/1?2=3&4=5&lang=en')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 14)
self.assertEqual(test.total_nodes, 14)
# confirm the scheme is parsed
self.assertIn('English', test.nodes[14].label)
def test_file_path_url(self):
""" Test a URL that ends with a file path"""
test = Unfurl()
test.add_to_queue(
data_type='url', key=None,
value='https://dfir.blog/content/images/2019/01/logo.png')
test.parse_queue()
# check the number of nodes
self.assertEqual(len(test.nodes.keys()), 13)
self.assertEqual(test.total_nodes, 13)
# confirm the scheme is parsed
self.assertIn('File Extension: .png', test.nodes[13].label)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "b68ee01c9eaf608d6a41c90719990fd3",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 75,
"avg_line_length": 29.6984126984127,
"alnum_prop": 0.5900587920897915,
"repo_name": "obsidianforensics/unfurl",
"id": "778af560b2bf186ab851b290ae8c0f28e4d60794",
"size": "1871",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "unfurl/tests/unit/test_url.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6059"
},
{
"name": "Dockerfile",
"bytes": "648"
},
{
"name": "HTML",
"bytes": "13012"
},
{
"name": "Python",
"bytes": "329420"
}
],
"symlink_target": ""
} |
static PropertyMapper propertyMappings[] = {
"IBUINibName",
"UINibName",
NULL,
"IBUIResizesToFullScreen",
"UIResizesToFullScreen",NULL,
"IBUITitle",
"UITitle",
NULL,
};
static const int numPropertyMappings = sizeof(propertyMappings) / sizeof(PropertyMapper);
viewControllerList UIViewController::_viewControllerNames;
UIViewController::UIViewController() {
_childViewControllers = new XIBArray();
_viewControllers = new XIBArray();
_parentViewController = NULL;
_view = NULL;
_navigationItem = NULL;
_tabBarItem = NULL;
_resizesToFullSize = true;
_storyboardIdentifier = NULL;
}
void UIViewController::InitFromXIB(XIBObject* obj) {
ObjectConverterSwapper::InitFromXIB(obj);
_view = (UIView*)obj->FindMember("IBUIView");
_tabBarItem = (UITabBarItem*)obj->FindMember("IBUITabBarItem");
_navigationItem = (UINavigationItem*)obj->FindMember("IBUINavigationItem");
_resizesToFullSize = obj->GetBool("IBUIAutoresizesArchivedViewToFullSize", true);
XIBArray* viewControllers = (XIBArray*)obj->FindMember("IBUIViewControllers");
if (viewControllers) {
for (int i = 0; i < viewControllers->count(); i++) {
XIBObject* curObj = viewControllers->objectAtIndex(i);
((UIViewController*)curObj)->_parentViewController = this;
_childViewControllers->AddMember(NULL, curObj);
_viewControllers->AddMember(NULL, curObj);
}
}
_outputClassName = "UIViewController";
}
void UIViewController::InitFromStory(XIBObject* obj) {
ObjectConverterSwapper::InitFromStory(obj);
_view = (UIView*)obj->FindMemberAndHandle("view");
_viewControllerNames.push_back(_id);
if (getAttrib("storyboardIdentifier")) {
_storyboardIdentifier = getAttrAndHandle("storyboardIdentifier");
}
if (_connections) {
for (int i = 0; i < _connections->count(); i++) {
XIBObject* curObj = _connections->objectAtIndex(i);
if (strcmp(curObj->_className, "segue") == 0) {
const char* pDest = curObj->getAttrAndHandle("destination");
const char* pKind = curObj->getAttrAndHandle("kind");
XIBObject* newController = findReference(pDest);
if (newController && strcmp(pKind, "relationship") == 0) {
((UIViewController*)newController)->_parentViewController = this;
_childViewControllers->AddMember(NULL, newController);
_viewControllers->AddMember(NULL, newController);
}
}
}
}
_tabBarItem = (UITabBarItem*)FindMemberAndHandle("tabBarItem");
_navigationItem = (UINavigationItem*)obj->FindMemberAndHandle("navigationItem");
_outputClassName = "UIViewController";
}
void UIViewController::Awaken() {
}
void ScanForSegues(XIBArray* out, XIBObject* obj) {
for (memberList::iterator cur = obj->_members.begin(); cur != obj->_members.end(); cur++) {
XIBMember* curMember = *cur;
if (curMember->_obj->_className && strcmp(curMember->_obj->_className, "segue") == 0) {
UIStoryboardSegue* curSegue = (UIStoryboardSegue*)curMember->_obj;
if (curSegue->_type == segueModal || curSegue->_type == seguePush) {
curSegue->_parent = out;
out->AddMember(NULL, curMember->_obj);
}
}
ScanForSegues(out, curMember->_obj);
}
}
void UIViewController::ConvertStaticMappings(NIBWriter* writer, XIBObject* obj) {
Map(writer, obj, propertyMappings, numPropertyMappings);
XIBArray* segueTemplates = new XIBArray();
if (_tabBarItem)
AddOutputMember(writer, "UITabBarItem", _tabBarItem);
if (_navigationItem)
AddOutputMember(writer, "UINavigationItem", _navigationItem);
if (!_resizesToFullSize)
AddBool(writer, "UIAutoresizesArchivedViewToFullSize", _resizesToFullSize);
if (_view) {
if (!_isStory) {
AddOutputMember(writer, "UIView", _view);
} else {
ScanForSegues(segueTemplates, this);
// This would cause a crash if we're not really a storyboard (i.e. input file has extension .storyboard)
// Currently we set both XIB3 and Storyboard with _isStory == true when calling XIBObject::ScanStoryObjects()
// which may trickle down into this control. IsStoryBoardConversion() returns true if we're really a .storyboard input file
if (IsStoryboardConversion()) {
XIBDictionary* externalObjects = new XIBDictionary();
char szNibName[255];
sprintf(szNibName, "%s-view-%s", _id, _view->_id);
AddString(writer, "UINibName", szNibName);
char szOutputName[255];
sprintf(szOutputName, "%s.nib", szNibName);
printf("Writing %s\n", GetOutputFilename(szOutputName).c_str());
FILE* fpOut = fopen(GetOutputFilename(szOutputName).c_str(), "wb");
NIBWriter* viewWriter = new NIBWriter(fpOut, externalObjects, _view);
viewWriter->ExportObject(_view);
XIBObject* ownerProxy = viewWriter->AddProxy("IBFilesOwner");
viewWriter->_topObjects->AddMember(NULL, ownerProxy);
XIBObject* firstResponderProxy = viewWriter->AddProxy("IBFirstResponder");
viewWriter->_topObjects->AddMember(NULL, firstResponderProxy);
// Add view connection
viewWriter->AddOutletConnection(ownerProxy, _view, "view");
viewWriter->WriteObjects();
fclose(fpOut);
if (externalObjects->_members.size() > 1) {
AddOutputMember(writer, "UIExternalObjectsTableForViewLoading", externalObjects);
}
}
}
}
if (_parentViewController) {
AddOutputMember(writer, "UIParentViewController", _parentViewController);
}
if (_isStory) {
XIBObject* storyboard = writer->AddProxy("UIStoryboardPlaceholder");
writer->AddOutletConnection(this, storyboard, "storyboard");
for (int i = 0; i < segueTemplates->count(); i++) {
UIStoryboardSegue* curSegue = (UIStoryboardSegue*)segueTemplates->objectAtIndex(i);
writer->AddOutletConnection(curSegue, this, "viewController");
}
if (segueTemplates->count() > 0) {
AddOutputMember(writer, "UIStoryboardSegueTemplates", segueTemplates);
for (int i = 0; i < segueTemplates->count(); i++) {
UIStoryboardSegue* curSegue = (UIStoryboardSegue*)segueTemplates->objectAtIndex(i);
NIBWriter::ExportController(curSegue->getAttrib("destination"));
}
}
}
if (_childViewControllers->count() > 0) {
AddOutputMember(writer, "UIChildViewControllers", _childViewControllers);
}
if (_viewControllers->count() > 0) {
AddOutputMember(writer, "UIViewControllers", _viewControllers);
}
ObjectConverterSwapper::ConvertStaticMappings(writer, obj);
} | {
"content_hash": "0bd72c6e4bb0606731b4012e83973b19",
"timestamp": "",
"source": "github",
"line_count": 182,
"max_line_length": 135,
"avg_line_length": 39.285714285714285,
"alnum_prop": 0.6290909090909091,
"repo_name": "bSr43/WinObjC",
"id": "8960b61a37fcaa4d05c964a2c90fed1ab33e17bc",
"size": "8065",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tools/vsimporter/xib2nib/UIViewController.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "2091"
},
{
"name": "C",
"bytes": "6815939"
},
{
"name": "C#",
"bytes": "134333"
},
{
"name": "C++",
"bytes": "3352043"
},
{
"name": "Lex",
"bytes": "4667"
},
{
"name": "M",
"bytes": "77709"
},
{
"name": "Objective-C",
"bytes": "8023432"
},
{
"name": "Objective-C++",
"bytes": "9108276"
},
{
"name": "PowerShell",
"bytes": "15625"
},
{
"name": "Python",
"bytes": "7658"
},
{
"name": "Yacc",
"bytes": "9740"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
NUB Generator [autonym]
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b412ce9cf459b82a24fc1265b3d6c161",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 23,
"avg_line_length": 9.076923076923077,
"alnum_prop": 0.6779661016949152,
"repo_name": "mdoering/backbone",
"id": "d7473011dce2296db4896de5e82fb63de1d85280",
"size": "182",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Primulaceae/Ardisia/Ardisia sanguinolenta/Ardisia sanguinolenta sanguinolenta/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>basic_socket::non_blocking (3 of 3 overloads)</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../non_blocking.html" title="basic_socket::non_blocking">
<link rel="prev" href="overload2.html" title="basic_socket::non_blocking (2 of 3 overloads)">
<link rel="next" href="../non_blocking_io.html" title="basic_socket::non_blocking_io">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../non_blocking.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../non_blocking_io.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h5 class="title">
<a name="boost_asio.reference.basic_socket.non_blocking.overload3"></a><a class="link" href="overload3.html" title="basic_socket::non_blocking (3 of 3 overloads)">basic_socket::non_blocking
(3 of 3 overloads)</a>
</h5></div></div></div>
<p>
Sets the non-blocking mode of the socket.
</p>
<pre class="programlisting"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="identifier">non_blocking</span><span class="special">(</span>
<span class="keyword">bool</span> <span class="identifier">mode</span><span class="special">,</span>
<span class="identifier">boost</span><span class="special">::</span><span class="identifier">system</span><span class="special">::</span><span class="identifier">error_code</span> <span class="special">&</span> <span class="identifier">ec</span><span class="special">);</span>
</pre>
<h6>
<a name="boost_asio.reference.basic_socket.non_blocking.overload3.h0"></a>
<span><a name="boost_asio.reference.basic_socket.non_blocking.overload3.parameters"></a></span><a class="link" href="overload3.html#boost_asio.reference.basic_socket.non_blocking.overload3.parameters">Parameters</a>
</h6>
<div class="variablelist">
<p class="title"><b></b></p>
<dl>
<dt><span class="term">mode</span></dt>
<dd><p>
If <code class="computeroutput"><span class="keyword">true</span></code>, the socket's
synchronous operations will fail with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">would_block</span></code>
if they are unable to perform the requested operation immediately.
If <code class="computeroutput"><span class="keyword">false</span></code>, synchronous
operations will block until complete.
</p></dd>
<dt><span class="term">ec</span></dt>
<dd><p>
Set to indicate what error occurred, if any.
</p></dd>
</dl>
</div>
<h6>
<a name="boost_asio.reference.basic_socket.non_blocking.overload3.h1"></a>
<span><a name="boost_asio.reference.basic_socket.non_blocking.overload3.remarks"></a></span><a class="link" href="overload3.html#boost_asio.reference.basic_socket.non_blocking.overload3.remarks">Remarks</a>
</h6>
<p>
The non-blocking mode has no effect on the behaviour of asynchronous
operations. Asynchronous operations will never fail with the error <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">would_block</span></code>.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2012 Christopher M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="overload2.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../non_blocking.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../non_blocking_io.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "20f2707d8e167107cf4b5a3d884e849b",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 452,
"avg_line_length": 73.975,
"alnum_prop": 0.637546468401487,
"repo_name": "goldcoin/gldcoin",
"id": "105df6cee740f1eeb5f1a561a30314764bd015b4",
"size": "5918",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "BuildDeps/deps/boost/doc/html/boost_asio/reference/basic_socket/non_blocking/overload3.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "21289"
},
{
"name": "Assembly",
"bytes": "1152300"
},
{
"name": "Awk",
"bytes": "54072"
},
{
"name": "Batchfile",
"bytes": "95617"
},
{
"name": "C",
"bytes": "30167843"
},
{
"name": "C#",
"bytes": "1801043"
},
{
"name": "C++",
"bytes": "143719415"
},
{
"name": "CMake",
"bytes": "7934"
},
{
"name": "CSS",
"bytes": "369274"
},
{
"name": "Cuda",
"bytes": "26749"
},
{
"name": "DIGITAL Command Language",
"bytes": "320412"
},
{
"name": "Emacs Lisp",
"bytes": "1639"
},
{
"name": "FORTRAN",
"bytes": "1387"
},
{
"name": "Groff",
"bytes": "29119"
},
{
"name": "HTML",
"bytes": "187929099"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "Java",
"bytes": "4131730"
},
{
"name": "JavaScript",
"bytes": "210803"
},
{
"name": "Lex",
"bytes": "1255"
},
{
"name": "Makefile",
"bytes": "1926648"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "NSIS",
"bytes": "5910"
},
{
"name": "Objective-C",
"bytes": "88946"
},
{
"name": "Objective-C++",
"bytes": "11420"
},
{
"name": "OpenEdge ABL",
"bytes": "66157"
},
{
"name": "PHP",
"bytes": "60328"
},
{
"name": "Perl",
"bytes": "3895713"
},
{
"name": "Perl6",
"bytes": "29655"
},
{
"name": "Prolog",
"bytes": "42455"
},
{
"name": "Protocol Buffer",
"bytes": "2764"
},
{
"name": "Python",
"bytes": "1785357"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "55372"
},
{
"name": "R",
"bytes": "4009"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Scheme",
"bytes": "4249"
},
{
"name": "Shell",
"bytes": "1384609"
},
{
"name": "Tcl",
"bytes": "2603631"
},
{
"name": "TeX",
"bytes": "13404"
},
{
"name": "XS",
"bytes": "198495"
},
{
"name": "XSLT",
"bytes": "761090"
},
{
"name": "Yacc",
"bytes": "18910"
},
{
"name": "eC",
"bytes": "5157"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>cucumber.eclipse</groupId>
<artifactId>parent</artifactId>
<version>0.0.15-SNAPSHOT</version>
</parent>
<artifactId>cucumber.eclipse.editor.test</artifactId>
<packaging>eclipse-test-plugin</packaging>
</project> | {
"content_hash": "9d09ff74c56a1e8935752182271f6474",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 104,
"avg_line_length": 34.357142857142854,
"alnum_prop": 0.738045738045738,
"repo_name": "daveychu/cucumber-eclipse",
"id": "6c53930a044a11efcc12e902d0ca313316a70e7e",
"size": "481",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cucumber.eclipse.editor.test/pom.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "201972"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="42">
<CLASSES>
<root url="jar://$PROJECT_DIR$/classes/42.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
</library>
</component> | {
"content_hash": "af5036a5676fd35cd9cc876c49e15937",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 57,
"avg_line_length": 22,
"alnum_prop": 0.5757575757575758,
"repo_name": "TypeUnsafe/golo-tour",
"id": "95822b0453f856621490c91c678b1a4d60ba768f",
"size": "198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "01-Golo.34.MontpellierJUG/01-BASICS/part05/.idea/libraries/42.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7497"
},
{
"name": "Golo",
"bytes": "477865"
},
{
"name": "Java",
"bytes": "67019"
},
{
"name": "JavaScript",
"bytes": "42853"
},
{
"name": "Shell",
"bytes": "14093"
}
],
"symlink_target": ""
} |
'use strict'
var assert = require('assert')
var CodeGenerator = require('../')
var mocha = require('mocha')
var it = mocha.it
var describe = mocha.describe
var beforeEach = mocha.beforeEach
var SymbolNode = require('../lib/node/SymbolNode')
function cleanAssert (a, b) {
a = a.replace(/\s/g, '')
b = b.replace(/\s/g, '')
assert(a === b)
}
function statement (instance, test) {
// console.log('statement:')
// console.log(instance.statements[0])
// console.log(test)
cleanAssert(instance.statements[0], test)
}
function statements (instance, tests) {
var statements = instance.statements
for (var i = 0; i < statements.length; i += 1) {
cleanAssert(statements[i], tests[i])
}
}
function id (name) {
var args = Array.prototype.slice.call(arguments, 1)
/* eslint-disable new-cap */
var identifier = SymbolNode({
name: name
})
/* eslint-enable new-cap */
if (args.length) {
identifier = '$$mathCodegen.functionProxy(' + identifier + ', "' + name + '")'
identifier += '(' + args.join(',') + ')'
}
return identifier
}
describe('math-codegen', function () {
var cg
describe('definitions', function () {
beforeEach(function () {
cg = new CodeGenerator()
})
it('should be sent to the constructor', function () {
cg = new CodeGenerator(null, {ns: 1})
assert(cg.defs.ns === 1)
})
it('should be updated', function () {
cg.setDefs({ns: 1})
assert(cg.defs.ns === 1)
cg.setDefs({ns: null})
assert(!cg.defs.ns)
})
})
describe('parser', function () {
describe('with default options', function () {
beforeEach(function () {
cg = new CodeGenerator()
})
it('should parse a constant', function () {
statement(cg.parse('1'), 'ns.factory(1)')
statement(cg.parse('1e18'), 'ns.factory(1e18)')
})
it('should parse unary expressions', function () {
statement(cg.parse('-1'), id('negative', 'ns.factory(1)'))
statement(cg.parse('+1'), id('positive', 'ns.factory(1)'))
statement(cg.parse('-+1'), id('negative', id('positive', 'ns.factory(1)')))
})
it('should parse an array', function () {
// rawArrayElements is set to true by default
statement(cg.parse('[1,2]'), 'ns.factory([1, 2])')
statement(cg.parse('[+1,-2]'), 'ns.factory([+1, -2])')
})
it('should parse symbols', function () {
statement(cg.parse('PI'), id('PI'))
statement(cg.parse('sin'), id('sin'))
})
it('should parse function calls', function () {
statement(cg.parse('sin()'), id('sin', ''))
statement(cg.parse('sin(1)'), id('sin', 'ns.factory(1)'))
statement(cg.parse('sin(1, 2)'), id('sin', 'ns.factory(1)', 'ns.factory(2)'))
})
it('should parse binary expression calls', function () {
statement(cg.parse('1 + 2'), id('add', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 - 2'), id('sub', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 * 2'), id('mul', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 / 2'), id('div', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 ^ 2'), id('pow', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 % 2'), id('mod', 'ns.factory(1)', 'ns.factory(2)'))
statement(cg.parse('1 < 2'), id('lessThan', 'ns.factory(1)', 'ns.factory(2)'))
statement(
cg.parse('(1 + 2) * (2 + 3)'),
id('mul', id('add', 'ns.factory(1)', 'ns.factory(2)'), id('add', 'ns.factory(2)', 'ns.factory(3)'))
)
statement(cg.parse('1 + 3 ^ 2'), id('add', 'ns.factory(1)', id('pow', 'ns.factory(3)', 'ns.factory(2)')))
statement(cg.parse('x!'), id('factorial', id('x')))
})
it('should parse a conditional expression', function () {
statement(
cg.parse('1 < 2 ? 1 : 2'),
'(!!(' + id('lessThan', 'ns.factory(1)', 'ns.factory(2)') + ') ? ' +
'( ns.factory(1) ) : ( ns.factory(2) ) )'
)
})
it('should parse an assignment expression', function () {
statement(cg.parse('x = 1'), 'scope["x"] = ns.factory(1)')
})
it('should parse multiple statements', function () {
statements(
cg.parse('sin(1);x = 1'),
[id('sin', 'ns.factory(1)'), 'scope["x"] = ns.factory(1)']
)
})
it('should throw on expressions not implemented', function () {
assert.throws(function () {
cg.parse('var y = 1')
})
})
})
describe('with raw set to true', function () {
beforeEach(function () {
cg = new CodeGenerator({
raw: true
})
})
it('should parse a constant', function () {
statement(cg.parse('1'), '1')
statement(cg.parse('1e18'), '1e18')
})
it('should parse unary expressions', function () {
statement(cg.parse('-1'), '-1')
statement(cg.parse('+1'), '+1')
statement(cg.parse('-+1'), '-+1')
})
it('should parse an array', function () {
// rawArrayElements is set to true by default
statement(cg.parse('[1,2]'), '[1, 2]')
statement(cg.parse('[+1,-2]'), '[+1, -2]')
})
it('should parse literals', function () {
statement(cg.parse('PI'), id('PI'))
statement(cg.parse('sin'), id('sin'))
})
it('should parse function calls', function () {
statement(cg.parse('sin()'), id('sin', ''))
statement(cg.parse('sin(1)'), id('sin', '1'))
statement(cg.parse('sin(1, 2)'), id('sin', '1', '2'))
})
it('should parse binary expression calls', function () {
statement(cg.parse('1 + 2'), '(1 + 2)')
statement(cg.parse('1 - 2'), '(1 - 2)')
statement(cg.parse('1 * 2'), '(1 * 2)')
statement(cg.parse('1 / 2'), '(1 / 2)')
statement(cg.parse('1 ^ 2'), '(1 ^ 2)')
statement(cg.parse('1 % 2'), '(1 % 2)')
statement(cg.parse('1 < 2'), '(1 < 2)')
statement(
cg.parse('(1 + 2) * (2 + 3)'),
'((1 + 2) * (2 + 3))'
)
})
it('should not throw on a not implemented binary operator', function () {
statement(cg.parse('1 & 2'), '(1 & 2)')
})
it('should parse a conditional expression', function () {
statement(
cg.parse('1 < 2 ? 1 : 2'),
'(!!((1 < 2)) ? ( 1 ) : ( 2 ) )'
)
})
it('should parse an assignment expression', function () {
statement(cg.parse('x = 1'), 'scope["x"] = 1')
})
it('should parse multiple statements', function () {
statements(
cg.parse('sin(1); x = 1'),
[id('sin', '1'), 'scope["x"] = 1']
)
})
})
describe('with rawArrayExpressionElements set to false', function () {
beforeEach(function () {
cg = new CodeGenerator({
rawArrayExpressionElements: false
})
})
it('should parse an array', function () {
statement(cg.parse('[1,2]'), 'ns.factory([ns.factory(1), ns.factory(2)])')
})
})
describe('with rawCallExpressionElements set to true', function () {
beforeEach(function () {
cg = new CodeGenerator({
rawCallExpressionElements: true
})
})
it('should use raw parameters', function () {
statement(cg.parse('sin()'), id('sin', ''))
statement(cg.parse('sin(1)'), id('sin', '1'))
statement(cg.parse('sin(1, 2)'), id('sin', '1', '2'))
})
})
})
describe('compile', function () {
var ns = { factory: function () {} }
beforeEach(function () {
cg = new CodeGenerator()
})
it('should throw when ns is not defined or it\'s different from an object/function', function () {
cg = new CodeGenerator()
assert.throws(function () {
cg.parse('1 + 2').compile()
})
assert.throws(function () {
cg.parse('1 + 2').compile(1)
})
})
it('should compile successfully when the namespace is a object/function', function () {
var fn = function () { }
fn.factory = function (a) { return a }
fn.add = function (a, b) { return a + b }
assert.doesNotThrow(function () {
cg.parse('1 + x').compile(ns)
cg.parse('1 + x').compile(fn)
})
})
it('should throw when there are no statements', function () {
assert.throws(function () {
cg.compile({})
})
})
it('should have a return statement in the eval method', function () {
var code = cg.parse('1 + 2').compile(ns)
assert(code.eval.toString().indexOf('return ') > 0)
})
it('should compile correctly under a ns', function () {
assert.doesNotThrow(function () {
cg.parse('1 + 2').compile(ns)
cg.parse('x = 1').compile(ns)
cg.parse('x = 1; y = 1').compile(ns)
cg.parse('x = 1; y + 1').compile(ns)
})
})
it('should throw if a method is not defined in the scope or in the ns', function () {
var code = cg.parse('1 + 2').compile(ns)
assert.throws(function () {
// `add` is not defined
code.eval()
}, /symbol "add" is undefined/)
})
it('should throw if a method is expected to be a function in the scope or in the ns', function () {
var code = cg.parse('1 + 2').compile({
factory: function (n) { return n },
add: 3
})
assert.throws(function () {
// `add` is not defined
code.eval()
}, /symbol "add" must be a function/)
})
it('should compile addition if .add is in the namespace', function () {
var code = cg.parse('1 + 2').compile({
factory: function (n) { return n },
add: function (x, y) { return x + y }
})
assert(code.eval() === 3)
})
})
describe('eval', function () {
var ns = {
factory: function (a) { return a },
add: function (a, b) { return a + b },
mul: function (a, b) { return a * b }
}
beforeEach(function () {
cg = new CodeGenerator()
})
it('should eval an operation successfully', function () {
var code = cg.parse('1 + x').compile(ns)
assert(code.eval({ x: 2 }) === 3)
assert(code.eval({ x: 0 }) === 1)
})
it('should make assignment to the scope', function () {
var scope = {x: 2}
var code = cg.parse('y = x; 1 + x').compile(ns)
assert(code.eval(scope) === 3)
assert(scope.y === 2)
})
it('should throw if a variable is not defined in the scope or the namespace', function () {
var code = cg.parse('1 + x').compile(ns)
assert.throws(function () {
code.eval({})
}, /symbol "x" is undefined/)
})
it('should throw if a function is not defined in the scope or the namespace', function () {
var code = cg.parse('1 + x(1)').compile(ns)
assert.throws(function () {
code.eval({
x: 3
})
}, /symbol "x" must be a function/)
})
it('should call the factory on context values', function () {
function Decimal (v) {
this.v = v
}
var decimalNamespace = {
factory: function (v) {
if (typeof v === Decimal) return v
return new Decimal(v)
},
add: function (a, b) {
return a.v + b.v
}
}
const codeGenerator = new CodeGenerator({
applyFactoryToScope: true
})
var code = codeGenerator.parse('x + y')
.compile(decimalNamespace)
assert(code.eval({
x: 1,
y: 2
}) === 3)
})
})
})
| {
"content_hash": "e28b916458be71ac9baad37e490dbf3d",
"timestamp": "",
"source": "github",
"line_count": 383,
"max_line_length": 113,
"avg_line_length": 30.514360313315926,
"alnum_prop": 0.5205784204671857,
"repo_name": "maurizzzio/math-codegen",
"id": "5c4a1d0593c5a9f71e08cb3b70748c48737efbc8",
"size": "11687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "18681"
}
],
"symlink_target": ""
} |
echo "Yum install Development Tools."
# Tool like gcc.
yum groupinstall -y "Development Tools"
# For some python module, ansible plugin.
yum install -y python-devel openssl-devel
| {
"content_hash": "c756156eea350ba2f6e3f8adb8d27474",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 41,
"avg_line_length": 25.857142857142858,
"alnum_prop": 0.7679558011049724,
"repo_name": "djsilenceboy/LearnTest",
"id": "f2cc932c719e8534f6369efc309f4a99c4ebf4cc",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Vagrant_Test/Archived/VagrantServers1/Scripts/Prepare_Development.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "27588"
},
{
"name": "C",
"bytes": "201487"
},
{
"name": "C++",
"bytes": "9459"
},
{
"name": "CSS",
"bytes": "6049"
},
{
"name": "Dockerfile",
"bytes": "5976"
},
{
"name": "HTML",
"bytes": "89155"
},
{
"name": "Java",
"bytes": "3304194"
},
{
"name": "JavaScript",
"bytes": "73886"
},
{
"name": "Jinja",
"bytes": "1150"
},
{
"name": "PHP",
"bytes": "21180"
},
{
"name": "PLSQL",
"bytes": "2080"
},
{
"name": "PowerShell",
"bytes": "19723"
},
{
"name": "Python",
"bytes": "551890"
},
{
"name": "Ruby",
"bytes": "16460"
},
{
"name": "Shell",
"bytes": "142970"
},
{
"name": "TypeScript",
"bytes": "6986"
},
{
"name": "XSLT",
"bytes": "1860"
}
],
"symlink_target": ""
} |
package ws16.tut1.personen_aufgabe;
public interface Gehalt {
//Netto gehalt zur�ckgeben ( Abzug von 33%)
public double nettoGehalt();
}
| {
"content_hash": "6eac4ff64b0ff735365a7e2cca6e07f9",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 44,
"avg_line_length": 17.875,
"alnum_prop": 0.7342657342657343,
"repo_name": "Sebb767/Prog",
"id": "2ff44f074fcf437c7b266fe594e44773512f63f6",
"size": "145",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/tutorium/ws16/tut1/personen_aufgabe/Gehalt.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "200362"
},
{
"name": "Shell",
"bytes": "84"
}
],
"symlink_target": ""
} |
package validation
import (
"errors"
"fmt"
"net"
"syscall"
"golang.org/x/sys/unix"
"istio.io/istio/tools/istio-iptables/pkg/constants"
"istio.io/pkg/log"
)
// Recover the original address from redirect socket. Supposed to work for tcp over ipv4 and ipv6.
func GetOriginalDestination(conn net.Conn) (daddr net.IP, dport uint16, err error) {
// obtain os fd from Conn
tcp, ok := conn.(*net.TCPConn)
if !ok {
err = errors.New("socket is not tcp")
return
}
file, err := tcp.File()
if err != nil {
return
}
defer file.Close()
fd := file.Fd()
// Detect underlying ip is v4 or v6
ip := conn.RemoteAddr().(*net.TCPAddr).IP
isIpv4 := false
if ip.To4() != nil {
isIpv4 = true
} else if ip.To16() != nil {
isIpv4 = false
} else {
err = fmt.Errorf("neither ipv6 nor ipv4 original addr: %s", ip)
return
}
// golang doesn't provide a struct sockaddr_storage
// IPv6MTUInfo is chosen because
// 1. it is no smaller than sockaddr_storage,
// 2. it is provide the port field value
var addr *unix.IPv6MTUInfo
if isIpv4 {
addr, err = unix.GetsockoptIPv6MTUInfo(
int(fd),
unix.IPPROTO_IP,
constants.SoOriginalDst)
if err != nil {
log.Errorf("Error ipv4 getsockopt: %v", err)
return
}
// See struct sockaddr_in
daddr = net.IPv4(
addr.Addr.Addr[0], addr.Addr.Addr[1], addr.Addr.Addr[2], addr.Addr.Addr[3])
} else {
addr, err = unix.GetsockoptIPv6MTUInfo(
int(fd), unix.IPPROTO_IPV6,
constants.SoOriginalDst)
if err != nil {
log.Errorf("Error to ipv6 getsockopt: %v", err)
return
}
// See struct sockaddr_in6
daddr = addr.Addr.Addr[:]
}
// See sockaddr_in6 and sockaddr_in
dport = ntohs(addr.Addr.Port)
log.Infof("Local addr %s", conn.LocalAddr())
log.Infof("Original addr %s: %d", ip, dport)
return
}
// Setup reuse address to run the validation server more robustly
func reuseAddr(network, address string, conn syscall.RawConn) error {
return conn.Control(func(descriptor uintptr) {
err := unix.SetsockoptInt(int(descriptor), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
if err != nil {
log.Errorf("Fail to set fd %d SO_REUSEADDR with error %v", descriptor, err)
}
err = unix.SetsockoptInt(int(descriptor), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
if err != nil {
log.Errorf("Fail to set fd %d SO_REUSEPORT with error %v", descriptor, err)
}
})
}
| {
"content_hash": "c1f0767bd135df4b71f3e6b35cca6590",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 98,
"avg_line_length": 25.791208791208792,
"alnum_prop": 0.674051981252663,
"repo_name": "istio/istio",
"id": "1e12ec20d8fdee5ecba1221621fa9c5d52f8470d",
"size": "3092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/istio-iptables/pkg/validation/vld_unix.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1273"
},
{
"name": "Go",
"bytes": "12352993"
},
{
"name": "Java",
"bytes": "1080"
},
{
"name": "Makefile",
"bytes": "59962"
},
{
"name": "Python",
"bytes": "11895"
},
{
"name": "Ruby",
"bytes": "317"
},
{
"name": "Shell",
"bytes": "149235"
},
{
"name": "Smarty",
"bytes": "7998"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 配置组件扫描 -->
<context:component-scan base-package="dao"/>
<!-- 读取conf.properites -->
<util:properties id="config" location="classpath:mysqlConf.properties"/>
<!-- 配置DataSource数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="#{config.driverName}"/>
<property name="url" value="#{config.url}"/>
<property name="username" value="#{config.username}"/>
<property name="password" value="#{config.password}"/>
<property name="maxActive" value="#{config.maxActive}"/>
<property name="maxWait" value="#{config.maxWait}"/>
</bean>
<!-- session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations"
value="empMapper.xml" />
</bean>
<!-- 扫描指定包下所有的接口 -->
<!--
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
</bean>
-->
<!-- 扫描指定包下带有注解@MyBatisRepository的接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao" />
<property name="annotationClass"
value="annotation.MyBatisRepository"/>
</bean>
</beans>
| {
"content_hash": "47cc782d0caebfe35d8f4d3035ea5dc5",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 116,
"avg_line_length": 41.95890410958904,
"alnum_prop": 0.6937642833823049,
"repo_name": "JesseHu1520/GitDepository",
"id": "590b0264b89f56a318357c29962b0553a67dbc66",
"size": "3141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mybatis02-spring/src/main/resources/appcontext.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1097292"
},
{
"name": "HTML",
"bytes": "123150"
},
{
"name": "Java",
"bytes": "630662"
},
{
"name": "JavaScript",
"bytes": "300964"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_40) on Wed Apr 13 18:09:36 UTC 2016 -->
<title>RefCounted.Tidy (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="RefCounted.Tidy (apache-cassandra API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":6,"i1":6};
var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RefCounted.Tidy.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.html" title="interface in org.apache.cassandra.utils.concurrent"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/utils/concurrent/Refs.html" title="class in org.apache.cassandra.utils.concurrent"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/utils/concurrent/RefCounted.Tidy.html" target="_top">Frames</a></li>
<li><a href="RefCounted.Tidy.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.apache.cassandra.utils.concurrent</div>
<h2 title="Interface RefCounted.Tidy" class="title">Interface RefCounted.Tidy</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../../org/apache/cassandra/io/util/MmappedRegions.Tidier.html" title="class in org.apache.cassandra.io.util">MmappedRegions.Tidier</a>, <a href="../../../../../org/apache/cassandra/io/util/SegmentedFile.Cleanup.html" title="class in org.apache.cassandra.io.util">SegmentedFile.Cleanup</a></dd>
</dl>
<dl>
<dt>Enclosing interface:</dt>
<dd><a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.html" title="interface in org.apache.cassandra.utils.concurrent">RefCounted</a><<a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.html" title="type parameter in RefCounted">T</a>></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="typeNameLabel">RefCounted.Tidy</span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.Tidy.html#name--">name</a></span>()</code> </td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.Tidy.html#tidy--">tidy</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="tidy--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>tidy</h4>
<pre>void tidy()
throws java.lang.Exception</pre>
<dl>
<dt><span class="throwsLabel">Throws:</span></dt>
<dd><code>java.lang.Exception</code></dd>
</dl>
</li>
</ul>
<a name="name--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>name</h4>
<pre>java.lang.String name()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/RefCounted.Tidy.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/apache/cassandra/utils/concurrent/RefCounted.html" title="interface in org.apache.cassandra.utils.concurrent"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/cassandra/utils/concurrent/Refs.html" title="class in org.apache.cassandra.utils.concurrent"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/cassandra/utils/concurrent/RefCounted.Tidy.html" target="_top">Frames</a></li>
<li><a href="RefCounted.Tidy.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016 The Apache Software Foundation</small></p>
</body>
</html>
| {
"content_hash": "c02204a092b10ddbbcd8a9e8b4c3ba9d",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 391,
"avg_line_length": 36.54435483870968,
"alnum_prop": 0.6310272536687631,
"repo_name": "elisska/cloudera-cassandra",
"id": "3081a1ae03887ea166cc2dfc3a869e697f1ad13f",
"size": "9063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DATASTAX_CASSANDRA-3.5.0/javadoc/org/apache/cassandra/utils/concurrent/RefCounted.Tidy.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "75145"
},
{
"name": "CSS",
"bytes": "4112"
},
{
"name": "HTML",
"bytes": "331372"
},
{
"name": "PowerShell",
"bytes": "77673"
},
{
"name": "Python",
"bytes": "979128"
},
{
"name": "Shell",
"bytes": "143685"
},
{
"name": "Thrift",
"bytes": "80564"
}
],
"symlink_target": ""
} |
.. -*- coding: utf-8 -*-
..
.. doc version: 1.10
.. check date: 2016/03/26
.. -----------------------------------------------------------------------------
.. engine userguide toc
.. _engine-userguide-toc:
========================================
Docker Engine ユーザガイド
========================================
.. sidebar:: 目次
.. contents::
:depth: 3
:local:
.. toctree::
:maxdepth: 1
はじめに <intro.rst>
イメージの活用
====================
.. toctree::
:maxdepth: 1
eng-image/dockerfile_best-practice.rst
eng-image/baseimages.rst
eng-image/image_management.rst
Docker ストレージ・ドライバ
==============================
.. toctree::
:maxdepth: 1
storagedriver/index.rst
storagedriver/imagesandcontainers.rst
storagedriver/selectadriver.rst
storagedriver/aufs-driver.rst
storagedriver/btrfs-driver.rst
storagedriver/device-mapper-driver.rst
storagedriver/overlayfs-driver.rst
storagedriver/zfs-driver.rst
ネットワーク設定
==============================
.. toctree::
:maxdepth: 1
networking/index.rst
networking/dockernetworks.rst
networking/work-with-networks.rst
networking/get-started-overlay.rst
networking/configure-dns.rst
default ネットワークを使う
------------------------------
.. toctree::
:maxdepth: 2
networking/default_network/index.rst
その他
====================
.. toctree::
:maxdepth: 1
labels-custom-metadata.rst
.. seealso::
Docker Engine user guide
https://docs.docker.com/engine/userguide/
| {
"content_hash": "fb4a5b6a582ac67d2173b1e999f23f0a",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 80,
"avg_line_length": 17.441860465116278,
"alnum_prop": 0.5546666666666666,
"repo_name": "netmarkjp/docs.docker.jp",
"id": "9796992004d4ea33b3b543b40ce42b148dd2bf0f",
"size": "1598",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "engine/userguide/index.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "104838"
},
{
"name": "HTML",
"bytes": "19821"
},
{
"name": "JavaScript",
"bytes": "5701"
},
{
"name": "Makefile",
"bytes": "1062"
},
{
"name": "Python",
"bytes": "10465"
}
],
"symlink_target": ""
} |
package extruder.metrics.dimensional
import cats.Eq
import cats.instances.int._
import cats.kernel.laws.discipline.MonoidTests
import org.scalacheck.ScalacheckShapeless._
import org.scalatest.FunSuite
import org.typelevel.discipline.scalatest.Discipline
class ResetNamespaceSpec extends FunSuite with Discipline {
import ResetNamespaceSpec._
checkAll("Metric values monoid", MonoidTests[ResetNamespace[Int]].monoid)
}
object ResetNamespaceSpec {
implicit def resetNamespaceEq[A: Eq]: Eq[ResetNamespace[A]] = Eq.by(_.value)
}
| {
"content_hash": "390d84c2476d508460eb2ce04b34deae",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 78,
"avg_line_length": 29.72222222222222,
"alnum_prop": 0.8130841121495327,
"repo_name": "janstenpickle/extruder",
"id": "ff315ffc36af8187c9113a588a14ca095f626c28",
"size": "535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metrics/core/src/test/scala/extruder/metrics/dimensional/ResetNamespaceSpec.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "5594"
},
{
"name": "Scala",
"bytes": "347727"
},
{
"name": "Shell",
"bytes": "1224"
}
],
"symlink_target": ""
} |
BOOST_FIXTURE_TEST_SUITE(evo_specialtx_tests, TestingSetup)
static CKey GetRandomKey()
{
CKey key;
key.MakeNewKey(true);
return key;
}
static CKeyID GetRandomKeyID()
{
return GetRandomKey().GetPubKey().GetID();
}
static CBLSPublicKey GetRandomBLSKey()
{
CBLSSecretKey sk;
sk.MakeNewKey();
return sk.GetPublicKey();
}
static CScript GetRandomScript()
{
return GetScriptForDestination(GetRandomKeyID());
}
static ProRegPL GetRandomProRegPayload()
{
ProRegPL pl;
pl.collateralOutpoint.hash = GetRandHash();
pl.collateralOutpoint.n = InsecureRandBits(2);
BOOST_CHECK(Lookup("57.12.210.11:51472", pl.addr, Params().GetDefaultPort(), false));
pl.keyIDOwner = GetRandomKeyID();
pl.pubKeyOperator = GetRandomBLSKey();
pl.keyIDVoting = GetRandomKeyID();
pl.scriptPayout = GetRandomScript();
pl.nOperatorReward = InsecureRandRange(10000);
pl.scriptOperatorPayout = GetRandomScript();
pl.inputsHash = GetRandHash();
pl.vchSig = InsecureRandBytes(63);
return pl;
}
static ProUpServPL GetRandomProUpServPayload()
{
ProUpServPL pl;
pl.proTxHash = GetRandHash();
BOOST_CHECK(Lookup("127.0.0.1:51472", pl.addr, Params().GetDefaultPort(), false));
pl.scriptOperatorPayout = GetRandomScript();
pl.inputsHash = GetRandHash();
pl.sig.SetByteVector(InsecureRandBytes(BLS_CURVE_SIG_SIZE));
return pl;
}
static ProUpRegPL GetRandomProUpRegPayload()
{
ProUpRegPL pl;
pl.proTxHash = GetRandHash();
pl.pubKeyOperator = GetRandomBLSKey();
pl.keyIDVoting = GetRandomKeyID();
pl.scriptPayout = GetRandomScript();
pl.inputsHash = GetRandHash();
pl.vchSig = InsecureRandBytes(63);
return pl;
}
static ProUpRevPL GetRandomProUpRevPayload()
{
ProUpRevPL pl;
pl.proTxHash = GetRandHash();
pl.nReason = InsecureRand16();
pl.inputsHash = GetRandHash();
pl.sig.SetByteVector(InsecureRandBytes(BLS_CURVE_SIG_SIZE));
return pl;
}
llmq::CFinalCommitment GetRandomLLMQCommitment()
{
llmq::CFinalCommitment fc;
fc.nVersion = InsecureRand16();
fc.llmqType = InsecureRandBits(8);
fc.quorumHash = GetRandHash();
int vecsize = InsecureRandRange(500);
for (int i = 0; i < vecsize; i++) {
fc.signers.emplace_back((bool)InsecureRandBits(1));
fc.validMembers.emplace_back((bool)InsecureRandBits(1));
}
fc.quorumPublicKey.SetByteVector(InsecureRandBytes(BLS_CURVE_PUBKEY_SIZE));
fc.quorumVvecHash = GetRandHash();
fc.quorumSig.SetByteVector(InsecureRandBytes(BLS_CURVE_SIG_SIZE));
fc.membersSig.SetByteVector(InsecureRandBytes(BLS_CURVE_SIG_SIZE));
return fc;
}
static llmq::LLMQCommPL GetRandomLLMQCommPayload()
{
llmq::LLMQCommPL pl;
pl.nHeight = InsecureRand32();
pl.commitment = GetRandomLLMQCommitment();
return pl;
}
static bool EqualCommitments(const llmq::CFinalCommitment& a, const llmq::CFinalCommitment& b)
{
return a.nVersion == b.nVersion &&
a.llmqType == b.llmqType &&
a.quorumHash == b.quorumHash &&
a.signers == b.signers &&
a.quorumPublicKey == b.quorumPublicKey &&
a.quorumVvecHash == b.quorumVvecHash &&
a.quorumSig == b.quorumSig &&
a.membersSig == b.membersSig;
}
BOOST_AUTO_TEST_CASE(protx_validation_test)
{
LOCK(cs_main);
CMutableTransaction mtx;
CValidationState state;
// v1 can only be Type=0
mtx.nType = CTransaction::TxType::PROREG;
mtx.nVersion = CTransaction::TxVersion::LEGACY;
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txns-type-version");
// version >= Sapling, type = 0, payload != null.
mtx.nType = CTransaction::TxType::NORMAL;
mtx.extraPayload = std::vector<uint8_t>(10, 1);
mtx.nVersion = CTransaction::TxVersion::SAPLING;
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txns-type-payload");
// version >= Sapling, type = 0, payload == null --> pass
mtx.extraPayload = nullopt;
BOOST_CHECK(CheckSpecialTxNoContext(CTransaction(mtx), state));
// nVersion>=2 and nType!=0 without extrapayload
mtx.nType = CTransaction::TxType::PROREG;
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK(state.GetRejectReason().find("without extra payload"));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txns-payload-empty");
// Size limits
mtx.extraPayload = std::vector<uint8_t>(MAX_SPECIALTX_EXTRAPAYLOAD + 1, 1);
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txns-payload-oversize");
// Remove one element, so now it passes the size check
mtx.extraPayload->pop_back();
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-protx-payload");
// valid payload but invalid inputs hash
mtx.extraPayload->clear();
ProRegPL pl = GetRandomProRegPayload();
SetTxPayload(mtx, pl);
BOOST_CHECK(!CheckSpecialTxNoContext(CTransaction(mtx), state));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-protx-inputs-hash");
// all good.
mtx.vin.emplace_back(GetRandHash(), 0);
mtx.extraPayload->clear();
pl.inputsHash = CalcTxInputsHash(CTransaction(mtx));
SetTxPayload(mtx, pl);
BOOST_CHECK(CheckSpecialTxNoContext(CTransaction(mtx), state));
}
BOOST_AUTO_TEST_CASE(proreg_setpayload_test)
{
const ProRegPL& pl = GetRandomProRegPayload();
CMutableTransaction mtx;
SetTxPayload(mtx, pl);
ProRegPL pl2;
BOOST_CHECK(GetTxPayload(mtx, pl2));
BOOST_CHECK(pl.collateralOutpoint == pl2.collateralOutpoint);
BOOST_CHECK(pl.addr == pl2.addr);
BOOST_CHECK(pl.keyIDOwner == pl2.keyIDOwner);
BOOST_CHECK(pl.pubKeyOperator == pl2.pubKeyOperator);
BOOST_CHECK(pl.keyIDVoting == pl2.keyIDVoting);
BOOST_CHECK(pl.scriptPayout == pl2.scriptPayout);
BOOST_CHECK(pl.nOperatorReward == pl2.nOperatorReward);
BOOST_CHECK(pl.scriptOperatorPayout == pl2.scriptOperatorPayout);
BOOST_CHECK(pl.inputsHash == pl2.inputsHash);
BOOST_CHECK(pl.vchSig == pl2.vchSig);
}
BOOST_AUTO_TEST_CASE(proupserv_setpayload_test)
{
const ProUpServPL& pl = GetRandomProUpServPayload();
CMutableTransaction mtx;
SetTxPayload(mtx, pl);
ProUpServPL pl2;
BOOST_CHECK(GetTxPayload(mtx, pl2));
BOOST_CHECK(pl.proTxHash == pl2.proTxHash);
BOOST_CHECK(pl.addr == pl2.addr);
BOOST_CHECK(pl.scriptOperatorPayout == pl2.scriptOperatorPayout);
BOOST_CHECK(pl.inputsHash == pl2.inputsHash);
BOOST_CHECK(pl.sig == pl2.sig);
}
BOOST_AUTO_TEST_CASE(proupreg_setpayload_test)
{
const ProUpRegPL& pl = GetRandomProUpRegPayload();
CMutableTransaction mtx;
SetTxPayload(mtx, pl);
ProUpRegPL pl2;
BOOST_CHECK(GetTxPayload(mtx, pl2));
BOOST_CHECK(pl.proTxHash == pl2.proTxHash);
BOOST_CHECK(pl.pubKeyOperator == pl2.pubKeyOperator);
BOOST_CHECK(pl.keyIDVoting == pl2.keyIDVoting);
BOOST_CHECK(pl.scriptPayout == pl2.scriptPayout);
BOOST_CHECK(pl.inputsHash == pl2.inputsHash);
BOOST_CHECK(pl.vchSig == pl2.vchSig);
}
BOOST_AUTO_TEST_CASE(prouprev_setpayload_test)
{
const ProUpRevPL& pl = GetRandomProUpRevPayload();
CMutableTransaction mtx;
SetTxPayload(mtx, pl);
ProUpRevPL pl2;
BOOST_CHECK(GetTxPayload(mtx, pl2));
BOOST_CHECK(pl.proTxHash == pl2.proTxHash);
BOOST_CHECK(pl.nReason == pl2.nReason);
BOOST_CHECK(pl.inputsHash == pl2.inputsHash);
BOOST_CHECK(pl.sig == pl2.sig);
}
BOOST_AUTO_TEST_CASE(proreg_checkstringsig_test)
{
ProRegPL pl = GetRandomProRegPayload();
pl.vchSig.clear();
const CKey& key = GetRandomKey();
BOOST_CHECK(CMessageSigner::SignMessage(pl.MakeSignString(), pl.vchSig, key));
std::string strError;
const CKeyID& keyID = key.GetPubKey().GetID();
BOOST_CHECK(CMessageSigner::VerifyMessage(keyID, pl.vchSig, pl.MakeSignString(), strError));
// Change owner address or script payout
pl.keyIDOwner = GetRandomKeyID();
BOOST_CHECK(!CMessageSigner::VerifyMessage(keyID, pl.vchSig, pl.MakeSignString(), strError));
pl.scriptPayout = GetRandomScript();
BOOST_CHECK(!CMessageSigner::VerifyMessage(keyID, pl.vchSig, pl.MakeSignString(), strError));
}
BOOST_AUTO_TEST_CASE(llmqcomm_setpayload_test)
{
const llmq::LLMQCommPL& pl = GetRandomLLMQCommPayload();
CMutableTransaction mtx;
SetTxPayload(mtx, pl);
llmq::LLMQCommPL pl2;
BOOST_CHECK(GetTxPayload(mtx, pl2));
BOOST_CHECK(pl.nHeight == pl2.nHeight);
BOOST_CHECK(EqualCommitments(pl.commitment, pl2.commitment));
}
BOOST_AUTO_TEST_SUITE_END()
| {
"content_hash": "22174ca0c65e3854c293acbd66029a47",
"timestamp": "",
"source": "github",
"line_count": 265,
"max_line_length": 97,
"avg_line_length": 33.154716981132076,
"alnum_prop": 0.7020259503755976,
"repo_name": "PIVX-Project/PIVX",
"id": "e32d329ccfaaa3f96432836a204007d564260143",
"size": "9257",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/evo_specialtx_tests.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "953297"
},
{
"name": "C",
"bytes": "5168953"
},
{
"name": "C++",
"bytes": "9188709"
},
{
"name": "CMake",
"bytes": "203234"
},
{
"name": "CSS",
"bytes": "211710"
},
{
"name": "HTML",
"bytes": "21833"
},
{
"name": "Java",
"bytes": "30291"
},
{
"name": "JavaScript",
"bytes": "41357"
},
{
"name": "M4",
"bytes": "263162"
},
{
"name": "Makefile",
"bytes": "139139"
},
{
"name": "Objective-C++",
"bytes": "3642"
},
{
"name": "Python",
"bytes": "1505322"
},
{
"name": "QMake",
"bytes": "26219"
},
{
"name": "Rust",
"bytes": "139132"
},
{
"name": "Sage",
"bytes": "30188"
},
{
"name": "Shell",
"bytes": "101041"
},
{
"name": "TypeScript",
"bytes": "10706"
}
],
"symlink_target": ""
} |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.convertColorToString = convertColorToString;
exports.convertHexToRGB = convertHexToRGB;
exports.decomposeColor = decomposeColor;
exports.getContrastRatio = getContrastRatio;
exports.getLuminance = getLuminance;
exports.emphasize = emphasize;
exports.fade = fade;
exports.darken = darken;
exports.lighten = lighten;
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Converts a color object with type and values to a string
*
* @param {object} color - Decomposed color
* @param {string} color.type - One of, 'rgb', 'rgba', 'hsl', 'hsla'
* @param {array} color.values - [n,n,n] or [n,n,n,n]
*/
function convertColorToString(color) {
var type = color.type;
var values = color.values;
if (type.indexOf('rgb') > -1) {
// Only convert the first 3 values to int (i.e. not alpha)
for (var i = 0; i < 3; i++) {
values[i] = parseInt(values[i]);
}
}
var colorString = void 0;
if (type.indexOf('hsl') > -1) {
colorString = color.type + '(' + values[0] + ', ' + values[1] + '%, ' + values[2] + '%';
} else {
colorString = color.type + '(' + values[0] + ', ' + values[1] + ', ' + values[2];
}
if (values.length === 4) {
colorString += ', ' + color.values[3] + ')';
} else {
colorString += ')';
}
return colorString;
}
/**
* Converts a color from CSS hex format to CSS rgb format.
*
* @param {string} color - Hex color, i.e. #nnn or #nnnnnn
*/
function convertHexToRGB(color) {
if (color.length === 4) {
var extendedColor = '#';
for (var i = 1; i < color.length; i++) {
extendedColor += color.charAt(i) + color.charAt(i);
}
color = extendedColor;
}
var values = {
r: parseInt(color.substr(1, 2), 16),
g: parseInt(color.substr(3, 2), 16),
b: parseInt(color.substr(5, 2), 16)
};
return 'rgb(' + values.r + ', ' + values.g + ', ' + values.b + ')';
}
/**
* Returns an object with the type and values of a color.
*
* Note: Does not support rgb % values.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
*/
function decomposeColor(color) {
if (color.charAt(0) === '#') {
return decomposeColor(convertHexToRGB(color));
}
var marker = color.indexOf('(');
var type = color.substring(0, marker);
var values = color.substring(marker + 1, color.length - 1).split(',');
values = values.map(function (value) {
return parseFloat(value);
});
return { type: type, values: values };
}
/**
* Calculates the contrast ratio between two colors.
*
* Formula: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
*
* @param {string} foreground - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {string} background - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
*/
function getContrastRatio(foreground, background) {
var lumA = getLuminance(foreground);
var lumB = getLuminance(background);
var contrastRatio = (Math.max(lumA, lumB) + 0.05) / (Math.min(lumA, lumB) + 0.05);
return Number(contrastRatio.toFixed(2)); // Truncate at two digits
}
/**
* The relative brightness of any point in a colorspace, normalized to 0 for
* darkest black and 1 for lightest white.
*
* Formula: https://www.w3.org/WAI/GL/wiki/Relative_luminance
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
*/
function getLuminance(color) {
color = decomposeColor(color);
if (color.type.indexOf('rgb') > -1) {
var rgb = color.values.map(function (val) {
val /= 255; // normalized
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return Number((0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]).toFixed(3)); // Truncate at 3 digits
} else if (color.type.indexOf('hsl') > -1) {
return color.values[2] / 100;
}
}
/**
* Darken or lighten a colour, depending on its luminance
* Light colors are darkened, dark colors lightened
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient=0.15 - multiplier in the range 0 - 1
*/
function emphasize(color) {
var coefficient = arguments.length <= 1 || arguments[1] === undefined ? 0.15 : arguments[1];
return getLuminance(color) > 0.5 ? darken(color, coefficient) : lighten(color, coefficient);
}
/**
* Set the absolute transparency of a color.
* Any existing alpha values are overwritten.
* Hex values will be converted to rgba.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} value - value to set the alpha channel to in the range 0 -1
*/
function fade(color, value) {
color = decomposeColor(color);
if (color.type === 'rgb' || color.type === 'hsl') {
color.type += 'a';
}
color.values[3] = value;
return convertColorToString(color);
}
/**
* Note: This naive implementation will change hue slightly,
* but is sufficient for our purpose.
* Hex values will be converted to rgb.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient - multiplier in the range 0 - 1
*/
function darken(color, coefficient) {
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!(coefficient < 0 || coefficient > 1), 'darken(color, coefficient) - coefficient must be between 0 and 1.') : void 0;
color = decomposeColor(color);
if (color.type.indexOf('hsl') > -1) {
color.values[2] *= 1 - coefficient;
} else if (color.type.indexOf('rgb') > -1) {
for (var i = 0; i < 3; i++) {
color.values[i] *= 1 - coefficient;
if (color.values[i] < 0) {
color.values[i] = 0;
}
}
}
return convertColorToString(color);
}
/**
* Lighten color.
* Hex values will be converted to rgb.
*
* @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla()
* @param {number} coefficient - multiplier in the range 0 - 1
*/
function lighten(color, coefficient) {
process.env.NODE_ENV !== "production" ? (0, _warning2.default)(!(coefficient < 0 || coefficient > 1), 'lighten(color, coefficient) - coefficient must be between 0 and 1.') : void 0;
color = decomposeColor(color);
if (color.type.indexOf('hsl') > -1) {
color.values[2] += (100 - color.values[2]) * coefficient;
} else if (color.type.indexOf('rgb') > -1) {
for (var i = 0; i < 3; i++) {
color.values[i] += (255 - color.values[i]) * coefficient;
}
}
return convertColorToString(color);
} | {
"content_hash": "24cdfa64573f1b2e13d5d034953e562c",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 183,
"avg_line_length": 30.85909090909091,
"alnum_prop": 0.6255707762557078,
"repo_name": "rekyyang/ArtificalLiverCloud",
"id": "6b409d1c4e7dd6207178c4646e035ffd5dd9ec34",
"size": "6789",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "node_modules/material-ui/utils/colorManipulator.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3831"
},
{
"name": "HTML",
"bytes": "547"
},
{
"name": "JavaScript",
"bytes": "223966"
}
],
"symlink_target": ""
} |
"""
This component contains all information which stored by the application.
"""
from __future__ import print_function
class bucket(object):
matrix_adj = {} # represent the network topology in matrix
path_list = {} # contains paths of all switch pairs
port_info = {} # contains all ports for each switch in detail
arp_table = {} # map ip address to mac address
flow_entry = {} # contains all flow entry which stored in the switches
gateway = {} | {
"content_hash": "a72277a11885e77f7493871712928081",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 75,
"avg_line_length": 39.75,
"alnum_prop": 0.6834381551362684,
"repo_name": "haidlir/drox",
"id": "e5286cc030097e8212d98e2ba5e50228c0a79beb",
"size": "1586",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bucket.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "45772"
},
{
"name": "Shell",
"bytes": "173"
}
],
"symlink_target": ""
} |
<input id="id_get_last"
type="button"
onclick="getLastReport()"
{% if report_nav.wser.url == '' %}disabled{% endif %}
value="Get Last Report Settings"
title="You can import the settings from a previous report by visiting the archived report just before you come to this form and pressing this button"
{% if not last_report %}disabled{% endif %}
/>
| {
"content_hash": "bf2e08eb00634dca756d35dbab9cab99",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 160,
"avg_line_length": 54.25,
"alnum_prop": 0.5829493087557603,
"repo_name": "opena11y/fae2",
"id": "45bf2c517c8ca92afbca4f7f8140b4a781df671f",
"size": "434",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "fae2/fae2/templates/forms/input_report_get_last.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "13797"
},
{
"name": "HTML",
"bytes": "370034"
},
{
"name": "Java",
"bytes": "128994"
},
{
"name": "JavaScript",
"bytes": "2157386"
},
{
"name": "Python",
"bytes": "500936"
},
{
"name": "Shell",
"bytes": "2666"
}
],
"symlink_target": ""
} |
Below, we first define a real-valued function. Then, using our interpreter (the class `AdvFunc`), we can evaluate the function. (Note that this can be viewed as an implementation of the Gang-of-Four interpreter pattern.)
The main feature is that the function is defined in a Cap'n Proto message.
Hence, it can be efficiently serialised, and parsed in (possibly) a different programming language
on (possibly) a different machine. Or, vice versa, one can define the function in a different language and parse it using the C++ interpreter.
```cpp
#include <commelec-api/schema.capnp.h>
#include <commelec-api/realexpr-convenience.hpp>
#include <commelec-interpreter/adv-interpreter.hpp>
#include <capnp/message.h>
::capnp::MallocMessageBuilder message;
auto adv = message.initRoot<msg::Advertisement>();
auto expr = adv.initCostFunction();
using namespace cv;
double a = 3.0;
double b = 6.0;
double c = 2.4;
Var x("X");
Var y("Y");
// "X" and "Y" are the names of the variables as they will appear in
// the Cap'n Proto message (We use 'x' and 'y' for these
// 'Var' (variable) objects in our C++ code)
buildRealExpr(expr, Real(a) * x + sin(y));
// this uses expression templates, to construct the expression tree at
// compile time
AdvFunc interpreter(adv);
// create the interpreter
double result = interpreter.evaluate(expr,{{"X",b},{"Y",c}});
// evaluate expr using x=b and y=c
```
| {
"content_hash": "d2c340b237184f089ad25ebb926524a2",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 220,
"avg_line_length": 34.925,
"alnum_prop": 0.7315676449534717,
"repo_name": "niekbouman/commelec-api",
"id": "e684c5f16e2eefbb56dd975ae82b811d3dd0137d",
"size": "1448",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/llapi.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "32083"
},
{
"name": "C++",
"bytes": "209614"
},
{
"name": "CMake",
"bytes": "17392"
},
{
"name": "Cap'n Proto",
"bytes": "6028"
},
{
"name": "Python",
"bytes": "5215"
},
{
"name": "Shell",
"bytes": "528"
}
],
"symlink_target": ""
} |
module.exports = function(response){
var data = response.data,
imageUrls = [];
data.forEach(function(datum){
var imageUrl = datum.images.low_resolution.url;
imageUrls.push(imageUrl);
});
return imageUrls;
} | {
"content_hash": "00a49f8e40db71dac5b03d76c3f406aa",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 51,
"avg_line_length": 25.333333333333332,
"alnum_prop": 0.6798245614035088,
"repo_name": "filose/AJAXInstaGallery",
"id": "ab2f689b3248001cd6ce89b998a42365b1f7e21d",
"size": "228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/modules/insta-get-image-urls.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4312"
},
{
"name": "HTML",
"bytes": "467"
},
{
"name": "JavaScript",
"bytes": "254012"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MSBuildLogParameter - FAKE - F# Make</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull">
<script src="https://code.jquery.com/jquery-1.8.0.js"></script>
<script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script>
<script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" />
<script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script>
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="masthead">
<ul class="nav nav-pills pull-right">
<li><a href="http://fsharp.org">fsharp.org</a></li>
<li><a href="http://github.com/fsharp/fake">github page</a></li>
</ul>
<h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3>
</div>
<hr />
<div class="row">
<div class="span9" id="main">
<h1>MSBuildLogParameter</h1>
<div class="xmldoc">
<p>MSBuild log option</p>
</div>
<h3>Union Cases</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>Union Case</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1853', 1853)" onmouseover="showTip(event, '1853', 1853)">
Append
</code>
<div class="tip" id="1853">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L104-104" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1854', 1854)" onmouseover="showTip(event, '1854', 1854)">
DisableConsoleColor
</code>
<div class="tip" id="1854">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L115-115" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1855', 1855)" onmouseover="showTip(event, '1855', 1855)">
DisableMPLogging
</code>
<div class="tip" id="1855">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L116-116" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1856', 1856)" onmouseover="showTip(event, '1856', 1856)">
EnableMPLogging
</code>
<div class="tip" id="1856">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L117-117" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1857', 1857)" onmouseover="showTip(event, '1857', 1857)">
ErrorsOnly
</code>
<div class="tip" id="1857">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L108-108" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1858', 1858)" onmouseover="showTip(event, '1858', 1858)">
ForceNoAlign
</code>
<div class="tip" id="1858">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L114-114" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1859', 1859)" onmouseover="showTip(event, '1859', 1859)">
NoItemAndPropertyList
</code>
<div class="tip" id="1859">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L110-110" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1860', 1860)" onmouseover="showTip(event, '1860', 1860)">
NoSummary
</code>
<div class="tip" id="1860">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L107-107" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1861', 1861)" onmouseover="showTip(event, '1861', 1861)">
PerformanceSummary
</code>
<div class="tip" id="1861">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L105-105" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1862', 1862)" onmouseover="showTip(event, '1862', 1862)">
ShowCommandLine
</code>
<div class="tip" id="1862">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L111-111" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1863', 1863)" onmouseover="showTip(event, '1863', 1863)">
ShowEventId
</code>
<div class="tip" id="1863">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L113-113" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1864', 1864)" onmouseover="showTip(event, '1864', 1864)">
ShowTimestamp
</code>
<div class="tip" id="1864">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L112-112" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1865', 1865)" onmouseover="showTip(event, '1865', 1865)">
Summary
</code>
<div class="tip" id="1865">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L106-106" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
<tr>
<td class="member-name">
<code onmouseout="hideTip(event, '1866', 1866)" onmouseover="showTip(event, '1866', 1866)">
WarningsOnly
</code>
<div class="tip" id="1866">
<strong>Signature:</strong> <br />
</div>
</td>
<td class="xmldoc">
<a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/MSBuildHelper.fs#L109-109" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="span3">
<a href="http://fsharp.github.io/FAKE/index.html">
<img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" />
</a>
<ul class="nav nav-list" id="menu">
<li class="nav-header">FAKE - F# Make</li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li>
<li class="divider"></li>
<li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li>
<li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li>
<li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li>
<li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li>
<li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li>
<li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li>
<li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li>
<li class="nav-header">Tutorials</li>
<li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li>
<li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li>
<li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li>
<li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li>
<li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li>
<li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li>
<li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li>
<li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li>
<li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li>
<li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li>
<li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li>
<li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li>
<li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li>
<li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li>
<li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li>
<li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li>
<li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li>
<li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li>
<li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li>
<li><a href="http://fsharp.github.io/FAKE/chocolatey.html">Using Chocolatey</a></li>
<li><a href="http://fsharp.github.io/FAKE/slacknotification.html">Using Slack</a></li>
<li><a href="http://fsharp.github.io/FAKE/sonarcube.html">Using SonarQube</a></li>
<li class="divider"></li>
<li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li>
<li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li>
<li class="nav-header">Reference</li>
<li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li>
</ul>
</div>
</div>
</div>
<a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a>
</body>
</html>
| {
"content_hash": "ab1cf1442dbf1e5ba9804a4cee464ebe",
"timestamp": "",
"source": "github",
"line_count": 365,
"max_line_length": 209,
"avg_line_length": 43.46027397260274,
"alnum_prop": 0.539935699426338,
"repo_name": "ploeh/dependency-rejection-samples",
"id": "40147bfaf191398876a8c1ee916f9c46d71170b1",
"size": "15863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FSharp/packages/FAKE/docs/apidocs/fake-msbuildhelper-msbuildlogparameter.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4203"
},
{
"name": "F#",
"bytes": "4237"
},
{
"name": "HTML",
"bytes": "6515464"
},
{
"name": "Haskell",
"bytes": "5471"
},
{
"name": "JavaScript",
"bytes": "1295"
},
{
"name": "Shell",
"bytes": "41"
},
{
"name": "XSLT",
"bytes": "17270"
}
],
"symlink_target": ""
} |
#include "input/pulse.h"
#include "input/common.h"
#include <pulse/error.h>
#include <pulse/pulseaudio.h>
#include <pulse/simple.h>
pa_mainloop *m_pulseaudio_mainloop;
void cb(__attribute__((unused)) pa_context *pulseaudio_context, const pa_server_info *i,
void *userdata) {
// getting default sink name
struct audio_data *audio = (struct audio_data *)userdata;
pthread_mutex_lock(&audio->lock);
free(audio->source);
audio->source = malloc(sizeof(char) * 1024);
strcpy(audio->source, i->default_sink_name);
// appending .monitor suufix
audio->source = strcat(audio->source, ".monitor");
pthread_mutex_unlock(&audio->lock);
// quiting mainloop
pa_context_disconnect(pulseaudio_context);
pa_context_unref(pulseaudio_context);
pa_mainloop_quit(m_pulseaudio_mainloop, 0);
pa_mainloop_free(m_pulseaudio_mainloop);
}
void pulseaudio_context_state_callback(pa_context *pulseaudio_context, void *userdata) {
// make sure loop is ready
switch (pa_context_get_state(pulseaudio_context)) {
case PA_CONTEXT_UNCONNECTED:
// printf("UNCONNECTED\n");
break;
case PA_CONTEXT_CONNECTING:
// printf("CONNECTING\n");
break;
case PA_CONTEXT_AUTHORIZING:
// printf("AUTHORIZING\n");
break;
case PA_CONTEXT_SETTING_NAME:
// printf("SETTING_NAME\n");
break;
case PA_CONTEXT_READY: // extract default sink name
// printf("READY\n");
pa_operation_unref(pa_context_get_server_info(pulseaudio_context, cb, userdata));
break;
case PA_CONTEXT_FAILED:
fprintf(stderr, "failed to connect to pulseaudio server\n");
exit(EXIT_FAILURE);
break;
case PA_CONTEXT_TERMINATED:
// printf("TERMINATED\n");
pa_mainloop_quit(m_pulseaudio_mainloop, 0);
break;
}
}
void getPulseDefaultSink(void *data) {
struct audio_data *audio = (struct audio_data *)data;
pa_mainloop_api *mainloop_api;
pa_context *pulseaudio_context;
int ret;
// Create a mainloop API and connection to the default server
m_pulseaudio_mainloop = pa_mainloop_new();
mainloop_api = pa_mainloop_get_api(m_pulseaudio_mainloop);
pulseaudio_context = pa_context_new(mainloop_api, "cava device list");
// This function connects to the pulse server
pa_context_connect(pulseaudio_context, NULL, PA_CONTEXT_NOFLAGS, NULL);
// printf("connecting to server\n");
// This function defines a callback so the server will tell us its state.
pa_context_set_state_callback(pulseaudio_context, pulseaudio_context_state_callback,
(void *)audio);
// starting a mainloop to get default sink
// starting with one nonblokng iteration in case pulseaudio is not able to run
if (!(ret = pa_mainloop_iterate(m_pulseaudio_mainloop, 0, &ret))) {
fprintf(stderr,
"Could not open pulseaudio mainloop to "
"find default device name: %d\n"
"check if pulseaudio is running\n",
ret);
exit(EXIT_FAILURE);
}
pa_mainloop_run(m_pulseaudio_mainloop, &ret);
}
void *input_pulse(void *data) {
struct audio_data *audio = (struct audio_data *)data;
uint16_t frames = audio->input_buffer_size / 2;
int channels = 2;
int16_t buf[frames * channels];
/* The sample type to use */
static const pa_sample_spec ss = {.format = PA_SAMPLE_S16LE, .rate = 44100, .channels = 2};
audio->format = 16;
const int frag_size = frames * channels * audio->format / 8 *
2; // we double this because of cpu performance issues with pulseaudio
pa_buffer_attr pb = {.maxlength = (uint32_t)-1, // BUFSIZE * 2,
.fragsize = frag_size};
pa_simple *s = NULL;
int error;
if (!(s = pa_simple_new(NULL, "cava", PA_STREAM_RECORD, audio->source, "audio for cava", &ss,
NULL, &pb, &error))) {
sprintf(audio->error_message, __FILE__ ": Could not open pulseaudio source: %s, %s. \
To find a list of your pulseaudio sources run 'pacmd list-sources'\n",
audio->source, pa_strerror(error));
audio->terminate = 1;
pthread_exit(NULL);
return 0;
}
while (!audio->terminate) {
if (pa_simple_read(s, buf, sizeof(buf), &error) < 0) {
sprintf(audio->error_message, __FILE__ ": pa_simple_read() failed: %s\n",
pa_strerror(error));
audio->terminate = 1;
}
write_to_cava_input_buffers(frames * channels, buf, data);
}
pa_simple_free(s);
pthread_exit(NULL);
return 0;
}
| {
"content_hash": "6857dd4fd70cf27754e53c65aa849c65",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 97,
"avg_line_length": 32.41095890410959,
"alnum_prop": 0.6158072696534235,
"repo_name": "karlstav/cava",
"id": "523ada1f0ab4c798b3044dcfd50412eec9966f94",
"size": "4732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "input/pulse.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "167528"
},
{
"name": "GLSL",
"bytes": "1393"
},
{
"name": "M4",
"bytes": "9027"
},
{
"name": "Makefile",
"bytes": "1063"
},
{
"name": "Shell",
"bytes": "645"
}
],
"symlink_target": ""
} |
CREATE OR REPLACE FUNCTION on_pipeline_delete() RETURNS TRIGGER AS $$
BEGIN
EXECUTE format('DROP TABLE IF EXISTS pipeline_build_events_%s', OLD.id);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION on_pipeline_insert() RETURNS TRIGGER AS $$
BEGIN
EXECUTE format('CREATE TABLE IF NOT EXISTS pipeline_build_events_%s () INHERITS (build_events)', NEW.id);
EXECUTE format('CREATE INDEX IF NOT EXISTS pipeline_build_events_%s_build_id ON pipeline_build_events_%s (build_id)', NEW.id, NEW.id);
EXECUTE format('CREATE UNIQUE INDEX IF NOT EXISTS pipeline_build_events_%s_build_id_event_id ON pipeline_build_events_%s (build_id, event_id)', NEW.id, NEW.id);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
DROP TRIGGER IF EXISTS pipeline_build_events_delete_trigger ON pipelines;
CREATE TRIGGER pipeline_build_events_delete_trigger AFTER DELETE on pipelines FOR EACH ROW EXECUTE PROCEDURE on_pipeline_delete();
DROP TRIGGER IF EXISTS pipeline_build_events_insert_trigger ON pipelines;
CREATE TRIGGER pipeline_build_events_insert_trigger AFTER INSERT on pipelines FOR EACH ROW EXECUTE PROCEDURE on_pipeline_insert();
| {
"content_hash": "dcf79cc149d9ac2ab493be02fbc4aac7",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 168,
"avg_line_length": 48.708333333333336,
"alnum_prop": 0.7476475620188195,
"repo_name": "concourse/concourse",
"id": "f1c3331e0a888b4cd7e86b38dd947d61cd24257d",
"size": "1170",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "atc/db/migration/migrations/1530824006_create_pipelines_trigger.up.sql",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "992"
},
{
"name": "CSS",
"bytes": "3808"
},
{
"name": "Dockerfile",
"bytes": "2190"
},
{
"name": "Elm",
"bytes": "2301056"
},
{
"name": "Go",
"bytes": "7073824"
},
{
"name": "HCL",
"bytes": "256"
},
{
"name": "HTML",
"bytes": "9052"
},
{
"name": "JavaScript",
"bytes": "76487"
},
{
"name": "Less",
"bytes": "34575"
},
{
"name": "Makefile",
"bytes": "133"
},
{
"name": "Open Policy Agent",
"bytes": "534"
},
{
"name": "PLpgSQL",
"bytes": "8122"
},
{
"name": "Shell",
"bytes": "8019"
}
],
"symlink_target": ""
} |
[](https://travis-ci.org/alistairjcbrown/node_ikettle)
[](http://badge.fury.io/gh/alistairjcbrown%2Fnode_ikettle)
[](https://david-dm.org/alistairjcbrown/node_ikettle)
[](https://david-dm.org/alistairjcbrown/node_ikettle#info=devDependencies)
---
This library enables easy access to an iKettle. Much of the knowledge for interacting with the iKettle was from [Mark Cox](https://github.com/iamamoose)'s blog article, "[Hacking a Wifi Kettle](http://www.awe.com/mark/blog/20140223.html)".
```js
var iKettle = require("ikettle");
```
Currently the functionality is read-only, ie. iKettle state can be read and is updated as the kettle state changes. If it on roadmap to provide write access to kettle state.
Please see the scripts in the [examples](examples) directory for ways in which this library can be used.
### Connecting to your iKettle
```js
iKettle.connect(port, host, function(err, state) {
if (err) {
return;
}
// Use state model here
});
```
The default port for the iKettle is `2000` and does not need to be provided if using the default port.
Calling `connect` will confirm that the host is an iKettle and will retrieve the current state which is used to populate the model.
The callback function follows the nodejs convention, If an error has occurred, the first parameter `err` will be an `Error` object and `model` will be `undefined`. If an error has not occurred, `err` will be `null` and `state` will be a `Backbone` model.
### iKettle state
This state model is held in a `Backbone` model. It is provided as a parameter to the `connect` callback, or via `iKettle.state`.
In depth information on using Backbone models can be found in the [Backbone documentation](http://backbonejs.org/#Model), but basic usecase for using the model:
#### Checking if the kettle is on
```js
var is_kettle_on = state.get("on");
```
#### Monitoring kettle state changes
```js
state.on("change", function(details) {
var what_changed = details.changes;
});
```
### Closing the connection
```js
iKettle.destroy();
```
This will close the connection to the iKettle and destroy the state model.
### Upcoming
1. Sync changes to state model back to the iKettle
- Partially complete. Further work required to support the order of changes,
eg. setting temp then turning on
2. Have periodic sync with iKettle to confirm state model holds correct state
3. Auto detect iKettle on local network
---
## Contact
Twitter @alistairjcbrown
Code signed using keybase as alistairjcbrown. Verify with `keybase dir verify`
| {
"content_hash": "999cf4441d29a768f43470fc2710b398",
"timestamp": "",
"source": "github",
"line_count": 80,
"max_line_length": 254,
"avg_line_length": 36.325,
"alnum_prop": 0.7477632484514797,
"repo_name": "alistairjcbrown/node_ikettle",
"id": "03511c8fa407cfaa198f8a9ff691b38a40a0c246",
"size": "2922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "50875"
}
],
"symlink_target": ""
} |
<?php
namespace book\modules\test\controllers;
use common\components\config\Config;
use yii\web\Controller;
class DefaultController extends Controller
{
public function actions()
{
return [
'auth' => [
'class' => \yii\authclient\AuthAction::className(),
'successCallback' => [$this, 'successCallback'],
],
];
}
/**
* Success Callback
* @param QqAuth|WeiboAuth $client
* @see http://wiki.connect.qq.com/get_user_info
* @see http://stuff.cebe.cc/yii2docs/yii-authclient-authaction.html
*/
public function successCallback($client) {
$id = $client->getId(); // qq | sina | weixin
$attributes = $client->getUserAttributes(); // basic info
$openid = $client->getOpenid(); //user openid
$userInfo = $client->getUserInfo(); // user extend info
var_dump($id, $attributes, $openid, $userInfo);
}
public function actionIndex()
{
\Yii::$app->cache->set('x', '654');
$this->view->params['abc'] = 'abc';
return $this->render('index',[
'abcd' => 'abcd'
]);
}
public function actionTest1()
{
return $this->render('test1',[]);
}
public function actionTest2()
{
return $this->render('test2',[]);
}
public function actionNotice()
{
\Yii::error('123456');
}
public function actionConfig()
{
return $this->render('config');
}
}
| {
"content_hash": "49210bc484b279f2affbdc2ed76c30a6",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 72,
"avg_line_length": 24.403225806451612,
"alnum_prop": 0.5512227362855254,
"repo_name": "wodrowCVM/yeework",
"id": "5229a60fbd529116fba8873335f03f475620a0f7",
"size": "1513",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "book/modules/test/controllers/DefaultController.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "1541"
},
{
"name": "CSS",
"bytes": "1119757"
},
{
"name": "HTML",
"bytes": "244112"
},
{
"name": "Makefile",
"bytes": "3999"
},
{
"name": "PHP",
"bytes": "623775"
},
{
"name": "Shell",
"bytes": "3257"
}
],
"symlink_target": ""
} |
<?php if ( ! defined('EXT')) exit('No direct script access allowed');
/**
* Code Pack - Control Panel
*
* The Control Panel master class that handles all of the CP Requests and Displaying
*
* @package Solspace:Code pack
* @author Solspace DevTeam
* @filesource ./system/expressionengine/third_party/code_pack/mcp.code_pack.php
*/
require_once 'addon_builder/module_builder.php';
class Code_pack_cp_base extends Module_builder_code_pack
{
var $theme_path = '';
var $theme_url = '';
// --------------------------------------------------------------------
/**
* Constructor
*
* @access public
* @param bool Enable calling of methods based on URI string
* @return string
*/
function __construct( $switch = TRUE )
{
parent::Module_builder_code_pack('code_pack');
if ((bool) $switch === FALSE) return; // Install or Uninstall Request
/** --------------------------------------------
/** Automatically Loaded Class Vars
/** --------------------------------------------*/
//$this->base = BASE.'&C=modules&M=code_pack';
/** --------------------------------------------
/** Automatically Loaded Class Vars
/** --------------------------------------------*/
$this->theme_path = $this->sc->addon_theme_path;
$this->theme_url = $this->sc->addon_theme_url;
/** --------------------------------------------
/** Set EE1 nav
/** --------------------------------------------*/
$menu = array(
'module_home' => array(
'name' => 'home',
'link' => $this->base,
'title' => ee()->lang->line('code_packs')
),
'module_documentation' => array(
'name' => 'documentation',
'link' => CODE_PACK_DOCS_URL,
'title' => ee()->lang->line('documentation') . ((APP_VER < 2.0) ? ' (' . CODE_PACK_VERSION . ')' : '')
),
);
$this->cached_vars['lang_module_version'] = ee()->lang->line('code_pack_module_version');
$this->cached_vars['module_version'] = CODE_PACK_VERSION;
$this->cached_vars['module_menu_highlight'] = 'module_home';
$this->cached_vars['module_menu'] = $menu;
/** --------------------------------------------
/** Sites
/** --------------------------------------------*/
$this->cached_vars['sites'] = array();
foreach($this->data->get_sites() as $site_id => $site_label)
{
$this->cached_vars['sites'][$site_id] = $site_label;
}
/** -------------------------------------
/** Module Installed and What Version?
/** -------------------------------------*/
if ( $this->database_version() == FALSE )
{
return;
}
elseif( $this->version_compare($this->database_version(), '<', CODE_PACK_VERSION) )
{
if ( APP_VER < 2.0 )
{
if ( $this->code_pack_module_update() === FALSE )
{
return;
}
}
else
{
// For EE 2.x, we need to redirect the request to Update Routine
$_GET['method'] = 'code_pack_module_update';
}
}
/** -------------------------------------
/** Request and View Builder
/** -------------------------------------*/
if (APP_VER < 2.0 AND $switch !== FALSE)
{
if (ee()->input->get('method') === FALSE)
{
$this->index();
}
elseif( ! method_exists($this, ee()->input->get('method')))
{
$this->add_crumb(ee()->lang->line('invalid_request'));
$this->cached_vars['error_message'] = ee()->lang->line('invalid_request');
return $this->ee_cp_view('error_page.html');
}
else
{
$this->{ee()->input->get('method')}();
}
}
}
/* END */
// --------------------------------------------------------------------
/**
* Code Pack
* @access public
* @param string
* @return string
*/
function code_pack($message='')
{
/** -------------------------------------
/** Get code pack
/** -------------------------------------*/
$code_packs = array();
if (ee()->extensions->active_hook('code_pack_list') === TRUE)
{
$code_packs = ee()->extensions->universal_call( 'code_pack_list', $code_packs );
}
/** -------------------------------------
/** Get meta data for code pack and verify
/** -------------------------------------*/
if ( ee()->input->get_post('code_pack_name') === FALSE OR
ee()->input->get_post('code_pack_name') == '' )
{
$this->cached_vars['error'] = ee()->lang->line('no_code_pack_specified');
}
elseif ( count( $code_packs ) == 0 )
{
$this->cached_vars['error'] = ee()->lang->line('no_code_packs');
}
else
{
$this->cached_vars['code_pack'] = array();
foreach ( $code_packs as $val )
{
if ( isset( $val['code_pack_name'] ) === TRUE AND
$val['code_pack_name'] == ee()->input->get_post('code_pack_name') )
{
$this->cached_vars['code_pack'] = $val;
$this->cached_vars['code_pack_name'] = $val['code_pack_name'];
$this->cached_vars['code_pack_label'] = $val['code_pack_label'];
$this->cached_vars['code_pack_description'] = $val['code_pack_description'];
$this->cached_vars['code_pack_theme_folder'] = $val['code_pack_theme_folder'];
}
}
/** -------------------------------------
/** Validate theme
/** -------------------------------------*/
$themes = $this->fetch_themes(
$this->theme_path . rtrim( $this->cached_vars['code_pack_theme_folder'], '/' ) . '/'
);
if ( count( $this->cached_vars['code_pack'] ) == 0 )
{
$this->cached_vars['error'] = ee()->lang->line('code_pack_not_found');
}
elseif ( count( $themes ) == 0 )
{
$this->cached_vars['error'] = str_replace(
'%code_pack_name%',
$this->cached_vars['code_pack_theme_folder'],
ee()->lang->line('missing_theme')
);
}
else
{
/** -------------------------------------
/** Get themes for this code pack
/** -------------------------------------*/
$themes_path = rtrim( $this->theme_path, '/' ) . '/' .
rtrim( $this->cached_vars['code_pack_theme_folder'], '/' ) . '/';
$themes = $this->fetch_themes( $themes_path );
/** -------------------------------------
/** Get code packs from themes folder
/** -------------------------------------*/
$this->cached_vars['code_packs'] = array();
foreach ( $themes as $folder )
{
$this->cached_vars['code_packs'][$folder]['name'] = ucwords( str_replace( '_', ' ', $folder ) );
$this->cached_vars['code_packs'][$folder]['description'
] = $this->data->get_code_pack_full_description( $themes_path.$folder );
$this->cached_vars['code_packs'][$folder]['img_url'] = $this->data->get_code_pack_image(
$themes_path.$folder,
$this->theme_url .
rtrim( $this->cached_vars['code_pack_theme_folder'], '/' ) . '/' . $folder
);
}
}
}
// --------------------------------------------
// Default Prefix
// --------------------------------------------
$this->cached_vars['prefix_default'] = trim(str_replace('code_pack', '', ee()->input->get_post('code_pack_name')), '_').'_';
/** -------------------------------------
/** Message
/** -------------------------------------*/
if ($message == '' AND isset($_GET['msg']))
{
$message = ee()->lang->line($_GET['msg']);
}
$this->cached_vars['message'] = $message;
/** -------------------------------------
/** Title and Crumbs
/** -------------------------------------*/
$this->add_crumb( $this->cached_vars['code_pack_label'] );
$this->build_crumbs();
$this->cached_vars['module_menu_highlight'] = 'module_home';
/** --------------------------------------------
/** Load Homepage
/** --------------------------------------------*/
return $this->ee_cp_view('code_pack.html');
}
/* End code pack */
// --------------------------------------------------------------------
/**
* Code pack install
*
* This method installs sample data into EE sites.
*
* @access public
* @param message
* @return string
*/
function code_pack_install( $message = '' )
{
$this->cached_vars['errors'] = array();
$this->cached_vars['success'] = array();
/** -------------------------------------
/** Auto load variables. These will be validated in actions->code_pack_install()
/** -------------------------------------*/
$variables = array();
foreach ( array( 'code_pack_name', 'code_pack_label', 'code_pack_theme_folder', 'code_pack_theme', 'prefix' ) as $val )
{
if ( ! empty( $_POST[ $val ] ) )
{
$variables[ $val ] = ee()->security->xss_clean( $_POST[ $val ] );
}
}
/** -------------------------------------
/** Theme
/** -------------------------------------*/
if ( ! empty( $variables['code_pack_name'] ) AND ! empty( $variables['code_pack_theme'] ) )
{
$variables['code_pack_name'] = rtrim( $variables['code_pack_name'], '/' );
$variables['code_pack_theme'] = rtrim( $variables['code_pack_theme'], '/' );
$variables['theme_path'] = $this->theme_path .
$variables['code_pack_theme_folder'] . '/' .
$variables['code_pack_theme'];
$variables['theme_url'] = $this->theme_url .
$variables['code_pack_theme_folder'] . '/' .
$variables['code_pack_theme'];
}
/** -------------------------------------
/** Execute
/** -------------------------------------*/
$this->actions();
$result = $this->actions->code_pack_install( $variables );
if ( count( $result ) == 0 )
{
exit( 'massive fail' );
}
/** -------------------------------------
/** Validate
/** -------------------------------------*/
$this->cached_vars = array_merge( $this->cached_vars, $result );
if ( empty( $this->cached_vars['errors'] ) AND empty( $this->cached_vars['success'] ) )
{
exit( 'another massive fail' );
}
/** -------------------------------------
/** Prep message
/** -------------------------------------*/
$this->_prep_message( $message );
/** -------------------------------------
/** Title and Crumbs
/** -------------------------------------*/
$this->cached_vars['code_pack_label'] = ( ! empty( $variables['code_pack_label'] ) ) ?
$variables['code_pack_label'] :
$variables['code_pack_name'];
$this->add_crumb( $this->cached_vars['code_pack_label'] );
$this->cached_vars['module_menu_highlight'] = 'module_home';
/** -------------------------------------
/** Load Page
/** -------------------------------------*/
return $this->ee_cp_view('code_pack_install.html');
}
/** End code pack install */
// --------------------------------------------------------------------
/**
* Module's Main Homepage
*
* @access public
* @param string
* @return null
*/
function index($message='')
{
/** -------------------------------------
/** Get code packs
/** -------------------------------------*/
$this->cached_vars['code_packs'] = array();
if ( ee()->extensions->active_hook('code_pack_list') === TRUE )
{
$this->cached_vars['code_packs'] = ee()->extensions->universal_call( 'code_pack_list', $this->cached_vars['code_packs'] );
}
ksort( $this->cached_vars['code_packs'] );
/** -------------------------------------
/** Get meta data for code packs and verify
/** -------------------------------------*/
$themes = $this->fetch_themes( $this->theme_path );
foreach ( $this->cached_vars['code_packs'] as $key => $val )
{
/** -------------------------------------
/** Is there a theme for this code pack?
/** -------------------------------------*/
if ( isset( $val['code_pack_theme_folder'] ) === FALSE OR in_array( $val['code_pack_theme_folder'], $themes ) === FALSE )
{
unset( $this->cached_vars['code_packs'][ $key ] );
}
}
/** -------------------------------------
/** Message
/** -------------------------------------*/
if ( $message == '' AND isset( $_GET['msg'] ) )
{
$message = ee()->lang->line( $_GET['msg'] );
}
$this->cached_vars['message'] = $message;
/** -------------------------------------
/** Title and Crumbs
/** -------------------------------------*/
$this->add_crumb(ee()->lang->line('code_packs'));
$this->build_crumbs();
/** --------------------------------------------
/** Load Homepage
/** --------------------------------------------*/
return $this->ee_cp_view('index.html');
}
/* END home() */
// --------------------------------------------------------------------
/**
* Prep message
* @access private
* @param message
* @return boolean
*/
function _prep_message( $message = '' )
{
if ( $message == '' AND isset( $_GET['msg'] ) )
{
$message = ee()->lang->line( $_GET['msg'] );
}
$this->cached_vars['message'] = $message;
return TRUE;
}
/* End prep message */
// --------------------------------------------------------------------
/**
* Module Installation
*
* Due to the nature of the 1.x branch of ExpressionEngine, this function is always required.
* However, because of the large size of the module the actual code for installing, uninstalling,
* and upgrading is located in a separate file to make coding easier
*
* @access public
* @return bool
*/
function code_pack_module_install()
{
require_once 'upd.code_pack.base.php';
$U = new Code_pack_updater_base();
return $U->install();
}
/* END code_pack_module_install() */
// --------------------------------------------------------------------
/**
* Module Uninstallation
*
* Due to the nature of the 1.x branch of ExpressionEngine, this function is always required.
* However, because of the large size of the module the actual code for installing, uninstalling,
* and upgrading is located in a separate file to make coding easier
*
* @access public
* @return bool
*/
function code_pack_module_deinstall()
{
require_once 'upd.code_pack.base.php';
$U = new Code_pack_updater_base();
return $U->uninstall();
}
/* END code_pack_module_deinstall() */
// --------------------------------------------------------------------
/**
* Module Upgrading
*
* This function is not required by the 1.x branch of ExpressionEngine by default. However,
* as the install and deinstall ones are, we are just going to keep the habit and include it
* anyhow.
* - Originally, the $current variable was going to be passed via parameter, but as there might
* be a further use for such a variable throughout the module at a later date we made it
* a class variable.
*
*
* @access public
* @return bool
*/
function code_pack_module_update()
{
if ( ! isset($_POST['run_update']) OR $_POST['run_update'] != 'y')
{
$this->add_crumb(ee()->lang->line('update_code_pack'));
$this->build_crumbs();
$this->cached_vars['form_url'] = $this->base.'&msg=update_successful';
return $this->ee_cp_view('update_module.html');
}
require_once $this->addon_path.'upd.code_pack.base.php';
$U = new Code_pack_updater_base();
if ($U->update() !== TRUE)
{
return $this->index(ee()->lang->line('update_failure'));
}
else
{
return $this->index(ee()->lang->line('update_successful'));
}
}
/* END code_pack_module_update() */
// --------------------------------------------------------------------
function get_theme_path()
{
}
}
// END CLASS Code_pack | {
"content_hash": "52a28de3ef0770b34c56eca3875c1481",
"timestamp": "",
"source": "github",
"line_count": 559,
"max_line_length": 132,
"avg_line_length": 28.212880143112702,
"alnum_prop": 0.44607190412782954,
"repo_name": "noslouch/pa",
"id": "d78e01a80207d4ffcf2c987d0323c90b176309f0",
"size": "16062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/expressionengine/third_party/code_pack/mcp.code_pack.base.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "877034"
},
{
"name": "CoffeeScript",
"bytes": "892"
},
{
"name": "JavaScript",
"bytes": "2917290"
},
{
"name": "PHP",
"bytes": "16079049"
},
{
"name": "Perl",
"bytes": "545632"
},
{
"name": "Ruby",
"bytes": "2133"
},
{
"name": "Shell",
"bytes": "456"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Material" inherits="Resource" category="Core" version="3.0-alpha">
<brief_description>
Abstract base [Resource] for coloring and shading geometry.
</brief_description>
<description>
Material is a base [Resource] used for coloring and shading geometry. All materials inherit from it and almost all [VisualInstance] derived nodes carry a Material. A few flags and parameters are shared between all material types and are configured here.
</description>
<tutorials>
</tutorials>
<demos>
</demos>
<methods>
<method name="get_next_pass" qualifiers="const">
<return type="Material">
</return>
<description>
</description>
</method>
<method name="get_render_priority" qualifiers="const">
<return type="int">
</return>
<description>
</description>
</method>
<method name="set_next_pass">
<return type="void">
</return>
<argument index="0" name="next_pass" type="Material">
</argument>
<description>
</description>
</method>
<method name="set_render_priority">
<return type="void">
</return>
<argument index="0" name="priority" type="int">
</argument>
<description>
</description>
</method>
</methods>
<members>
<member name="next_pass" type="Material" setter="set_next_pass" getter="get_next_pass">
</member>
<member name="render_priority" type="int" setter="set_render_priority" getter="get_render_priority">
</member>
</members>
<constants>
<constant name="RENDER_PRIORITY_MAX" value="127" enum="">
</constant>
<constant name="RENDER_PRIORITY_MIN" value="-128" enum="">
</constant>
</constants>
</class>
| {
"content_hash": "4f743611b1672fbd3015805ce10e46f3",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 255,
"avg_line_length": 30.2,
"alnum_prop": 0.6809151113786875,
"repo_name": "n-pigeon/godot",
"id": "87c2e510037e68d346a19e4f41e50db639b175e7",
"size": "1661",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/classes/Material.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "50004"
},
{
"name": "C#",
"bytes": "175561"
},
{
"name": "C++",
"bytes": "17992786"
},
{
"name": "GLSL",
"bytes": "1271"
},
{
"name": "Java",
"bytes": "499452"
},
{
"name": "JavaScript",
"bytes": "15057"
},
{
"name": "Makefile",
"bytes": "451"
},
{
"name": "Objective-C",
"bytes": "2644"
},
{
"name": "Objective-C++",
"bytes": "171421"
},
{
"name": "Python",
"bytes": "321756"
},
{
"name": "Shell",
"bytes": "19598"
}
],
"symlink_target": ""
} |
// Copyright 2015-2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HIGHWAYHASH_HH_AVX2_H_
#define HIGHWAYHASH_HH_AVX2_H_
// WARNING: this is a "restricted" header because it is included from
// translation units compiled with different flags. This header and its
// dependencies must not define any function unless it is static inline and/or
// within namespace HH_TARGET_NAME. See arch_specific.h for details.
#include "highwayhash/arch_specific.h"
#include "highwayhash/compiler_specific.h"
#include "highwayhash/hh_buffer.h"
#include "highwayhash/hh_types.h"
#include "highwayhash/load3.h"
#include "highwayhash/vector128.h"
#include "highwayhash/vector256.h"
// For auto-dependency generation, we need to include all headers but not their
// contents (otherwise compilation fails because -mavx2 is not specified).
#ifndef HH_DISABLE_TARGET_SPECIFIC
namespace highwayhash {
// See vector128.h for why this namespace is necessary; matching it here makes
// it easier use the vector128 symbols, but requires textual inclusion.
namespace HH_TARGET_NAME {
class HHStateAVX2 {
public:
explicit HH_INLINE HHStateAVX2(const HHKey key_lanes) { Reset(key_lanes); }
HH_INLINE void Reset(const HHKey key_lanes) {
// "Nothing up my sleeve" numbers, concatenated hex digits of Pi from
// http://www.numberworld.org/digits/Pi/, retrieved Feb 22, 2016.
//
// We use this python code to generate the fourth number to have
// more even mixture of bits:
/*
def x(a,b,c):
retval = 0
for i in range(64):
count = ((a >> i) & 1) + ((b >> i) & 1) + ((c >> i) & 1)
if (count <= 1):
retval |= 1 << i
return retval
*/
const V4x64U init0(0x243f6a8885a308d3ull, 0x13198a2e03707344ull,
0xa4093822299f31d0ull, 0xdbe6d5d5fe4cce2full);
const V4x64U init1(0x452821e638d01377ull, 0xbe5466cf34e90c6cull,
0xc0acf169b5f18a8cull, 0x3bd39e10cb0ef593ull);
const V4x64U key = LoadUnaligned<V4x64U>(key_lanes);
v0 = key ^ init0;
v1 = Rotate64By32(key) ^ init1;
mul0 = init0;
mul1 = init1;
}
HH_INLINE void Update(const HHPacket& packet_bytes) {
const uint64_t* HH_RESTRICT packet =
reinterpret_cast<const uint64_t * HH_RESTRICT>(packet_bytes);
Update(LoadUnaligned<V4x64U>(packet));
}
HH_INLINE void UpdateRemainder(const char* bytes, const size_t size_mod32) {
// 'Length padding' differentiates zero-valued inputs that have the same
// size/32. mod32 is sufficient because each Update behaves as if a
// counter were injected, because the state is large and mixed thoroughly.
const V8x32U size256(
_mm256_broadcastd_epi32(_mm_cvtsi64_si128(size_mod32)));
// Equivalent to storing size_mod32 in packet.
v0 += V4x64U(size256);
// Boosts the avalanche effect of mod32.
v1 = Rotate32By(v1, size256);
const char* remainder = bytes + (size_mod32 & ~3);
const size_t size_mod4 = size_mod32 & 3;
const V4x32U size(_mm256_castsi256_si128(size256));
// (Branching is faster than a single _mm256_maskload_epi32.)
if (HH_UNLIKELY(size_mod32 & 16)) { // 16..31 bytes left
const V4x32U packetL =
LoadUnaligned<V4x32U>(reinterpret_cast<const uint32_t*>(bytes));
const V4x32U int_mask = IntMask<16>()(size);
const V4x32U int_lanes = MaskedLoadInt(bytes + 16, int_mask);
const uint32_t last4 =
Load3()(Load3::AllowReadBeforeAndReturn(), remainder, size_mod4);
// The upper four bytes of packetH are zero, so insert there.
const V4x32U packetH(_mm_insert_epi32(int_lanes, last4, 3));
Update(packetH, packetL);
} else { // size_mod32 < 16
const V4x32U int_mask = IntMask<0>()(size);
const V4x32U packetL = MaskedLoadInt(bytes, int_mask);
const uint64_t last3 =
Load3()(Load3::AllowUnordered(), remainder, size_mod4);
// Rather than insert into packetL[3], it is faster to initialize
// the otherwise empty packetH.
const V4x32U packetH(_mm_cvtsi64_si128(last3));
Update(packetH, packetL);
}
}
HH_INLINE void Finalize(HHResult64* HH_RESTRICT result) {
// Mix together all lanes. It is slightly better to permute v0 than v1;
// it will be added to v1.
Update(Permute(v0));
Update(Permute(v0));
Update(Permute(v0));
Update(Permute(v0));
const V2x64U sum0(_mm256_castsi256_si128(v0 + mul0));
const V2x64U sum1(_mm256_castsi256_si128(v1 + mul1));
const V2x64U hash = sum0 + sum1;
// Each lane is sufficiently mixed, so just truncate to 64 bits.
_mm_storel_epi64(reinterpret_cast<__m128i*>(result), hash);
}
HH_INLINE void Finalize(HHResult128* HH_RESTRICT result) {
for (int n = 0; n < 6; n++) {
Update(Permute(v0));
}
const V2x64U sum0(_mm256_castsi256_si128(v0 + mul0));
const V2x64U sum1(_mm256_extracti128_si256(v1 + mul1, 1));
const V2x64U hash = sum0 + sum1;
_mm_storeu_si128(reinterpret_cast<__m128i*>(result), hash);
}
HH_INLINE void Finalize(HHResult256* HH_RESTRICT result) {
for (int n = 0; n < 10; n++) {
Update(Permute(v0));
}
const V4x64U sum0 = v0 + mul0;
const V4x64U sum1 = v1 + mul1;
const V4x64U hash = ModularReduction(sum1, sum0);
StoreUnaligned(hash, &(*result)[0]);
}
// "buffer" must be 32-byte aligned.
static HH_INLINE void ZeroInitialize(char* HH_RESTRICT buffer) {
const __m256i zero = _mm256_setzero_si256();
_mm256_store_si256(reinterpret_cast<__m256i*>(buffer), zero);
}
// "buffer" must be 32-byte aligned.
static HH_INLINE void CopyPartial(const char* HH_RESTRICT from,
const size_t size_mod32,
char* HH_RESTRICT buffer) {
const V4x32U size(size_mod32);
const uint32_t* const HH_RESTRICT from_u32 =
reinterpret_cast<const uint32_t * HH_RESTRICT>(from);
uint32_t* const HH_RESTRICT buffer_u32 =
reinterpret_cast<uint32_t * HH_RESTRICT>(buffer);
if (HH_UNLIKELY(size_mod32 & 16)) { // Copying 16..31 bytes
const V4x32U inL = LoadUnaligned<V4x32U>(from_u32);
Store(inL, buffer_u32);
const V4x32U inH = Load0To16<16, Load3::AllowReadBefore>(
from + 16, size_mod32 - 16, size);
Store(inH, buffer_u32 + V4x32U::N);
} else { // Copying 0..15 bytes
const V4x32U inL = Load0To16<>(from, size_mod32, size);
Store(inL, buffer_u32);
// No need to change upper 16 bytes of buffer.
}
}
// "buffer" must be 32-byte aligned.
static HH_INLINE void AppendPartial(const char* HH_RESTRICT from,
const size_t size_mod32,
char* HH_RESTRICT buffer,
const size_t buffer_valid) {
const V4x32U size(size_mod32);
uint32_t* const HH_RESTRICT buffer_u32 =
reinterpret_cast<uint32_t * HH_RESTRICT>(buffer);
// buffer_valid + size <= 32 => appending 0..16 bytes inside upper 16 bytes.
if (HH_UNLIKELY(buffer_valid & 16)) {
const V4x32U suffix = Load0To16<>(from, size_mod32, size);
const V4x32U bufferH = Load<V4x32U>(buffer_u32 + V4x32U::N);
const V4x32U outH = Concatenate(bufferH, buffer_valid - 16, suffix);
Store(outH, buffer_u32 + V4x32U::N);
} else { // Appending 0..32 bytes starting at offset 0..15.
const V4x32U bufferL = Load<V4x32U>(buffer_u32);
const V4x32U suffixL = Load0To16<>(from, size_mod32, size);
const V4x32U outL = Concatenate(bufferL, buffer_valid, suffixL);
Store(outL, buffer_u32);
const size_t offsetH = sizeof(V4x32U) - buffer_valid;
// Do we have enough input to start filling the upper 16 buffer bytes?
if (size_mod32 > offsetH) {
const size_t sizeH = size_mod32 - offsetH;
const V4x32U outH = Load0To16<>(from + offsetH, sizeH, V4x32U(sizeH));
Store(outH, buffer_u32 + V4x32U::N);
}
}
}
// "buffer" must be 32-byte aligned.
HH_INLINE void AppendAndUpdate(const char* HH_RESTRICT from,
const size_t size_mod32,
const char* HH_RESTRICT buffer,
const size_t buffer_valid) {
const V4x32U size(size_mod32);
const uint32_t* const HH_RESTRICT buffer_u32 =
reinterpret_cast<const uint32_t * HH_RESTRICT>(buffer);
// buffer_valid + size <= 32 => appending 0..16 bytes inside upper 16 bytes.
if (HH_UNLIKELY(buffer_valid & 16)) {
const V4x32U suffix = Load0To16<>(from, size_mod32, size);
const V4x32U packetL = Load<V4x32U>(buffer_u32);
const V4x32U bufferH = Load<V4x32U>(buffer_u32 + V4x32U::N);
const V4x32U packetH = Concatenate(bufferH, buffer_valid - 16, suffix);
Update(packetH, packetL);
} else { // Appending 0..32 bytes starting at offset 0..15.
const V4x32U bufferL = Load<V4x32U>(buffer_u32);
const V4x32U suffixL = Load0To16<>(from, size_mod32, size);
const V4x32U packetL = Concatenate(bufferL, buffer_valid, suffixL);
const size_t offsetH = sizeof(V4x32U) - buffer_valid;
V4x32U packetH = packetL - packetL;
// Do we have enough input to start filling the upper 16 packet bytes?
if (size_mod32 > offsetH) {
const size_t sizeH = size_mod32 - offsetH;
packetH = Load0To16<>(from + offsetH, sizeH, V4x32U(sizeH));
}
Update(packetH, packetL);
}
}
private:
static HH_INLINE V4x32U MaskedLoadInt(const char* from,
const V4x32U& int_mask) {
// No faults will be raised when reading n=0..3 ints from "from" provided
// int_mask[n] = 0.
const int* HH_RESTRICT int_from = reinterpret_cast<const int*>(from);
return V4x32U(_mm_maskload_epi32(int_from, int_mask));
}
// Loads <= 16 bytes without accessing any byte outside [from, from + size).
// from[i] is loaded into lane i; from[i >= size] is undefined.
template <uint32_t kSizeOffset = 0, class Load3Policy = Load3::AllowNone>
static HH_INLINE V4x32U Load0To16(const char* from, const size_t size_mod32,
const V4x32U& size) {
const char* remainder = from + (size_mod32 & ~3);
const uint64_t last3 = Load3()(Load3Policy(), remainder, size_mod32 & 3);
const V4x32U int_mask = IntMask<kSizeOffset>()(size);
const V4x32U int_lanes = MaskedLoadInt(from, int_mask);
return Insert4AboveMask(last3, int_mask, int_lanes);
}
static HH_INLINE V4x64U Rotate64By32(const V4x64U& v) {
return V4x64U(_mm256_shuffle_epi32(v, _MM_SHUFFLE(2, 3, 0, 1)));
}
// Rotates 32-bit lanes by "count" bits.
static HH_INLINE V4x64U Rotate32By(const V4x64U& v, const V8x32U& count) {
// Use variable shifts because sll_epi32 has 4 cycle latency (presumably
// to broadcast the shift count).
const V4x64U shifted_left(_mm256_sllv_epi32(v, count));
const V4x64U shifted_right(_mm256_srlv_epi32(v, V8x32U(32) - count));
return shifted_left | shifted_right;
}
static HH_INLINE V4x64U Permute(const V4x64U& v) {
// For complete mixing, we need to swap the upper and lower 128-bit halves;
// we also swap all 32-bit halves. This is faster than extracti128 plus
// inserti128 followed by Rotate64By32.
const V4x64U indices(0x0000000200000003ull, 0x0000000000000001ull,
0x0000000600000007ull, 0x0000000400000005ull);
return V4x64U(_mm256_permutevar8x32_epi32(v, indices));
}
static HH_INLINE V4x64U MulLow32(const V4x64U& a, const V4x64U& b) {
return V4x64U(_mm256_mul_epu32(a, b));
}
static HH_INLINE V4x64U ZipperMerge(const V4x64U& v) {
// Multiplication mixes/scrambles bytes 0-7 of the 64-bit result to
// varying degrees. In descending order of goodness, bytes
// 3 4 2 5 1 6 0 7 have quality 228 224 164 160 100 96 36 32.
// As expected, the upper and lower bytes are much worse.
// For each 64-bit lane, our objectives are:
// 1) maximizing and equalizing total goodness across the four lanes.
// 2) mixing with bytes from the neighboring lane (AVX-2 makes it difficult
// to cross the 128-bit wall, but PermuteAndUpdate takes care of that);
// 3) placing the worst bytes in the upper 32 bits because those will not
// be used in the next 32x32 multiplication.
const uint64_t hi = 0x070806090D0A040Bull;
const uint64_t lo = 0x000F010E05020C03ull;
return V4x64U(_mm256_shuffle_epi8(v, V4x64U(hi, lo, hi, lo)));
}
// Updates four hash lanes in parallel by injecting four 64-bit packets.
HH_INLINE void Update(const V4x64U& packet) {
v1 += packet;
v1 += mul0;
mul0 ^= MulLow32(v1, v0 >> 32);
HH_COMPILER_FENCE;
v0 += mul1;
mul1 ^= MulLow32(v0, v1 >> 32);
HH_COMPILER_FENCE;
v0 += ZipperMerge(v1);
v1 += ZipperMerge(v0);
}
HH_INLINE void Update(const V4x32U& packetH, const V4x32U& packetL) {
const __m256i packetL256 = _mm256_castsi128_si256(packetL);
Update(V4x64U(_mm256_inserti128_si256(packetL256, packetH, 1)));
}
// XORs a << 1 and a << 2 into *out after clearing the upper two bits of a.
// Also does the same for the upper 128 bit lane "b". Bit shifts are only
// possible on independent 64-bit lanes. We therefore insert the upper bits
// of a[0] that were lost into a[1]. Thanks to D. Lemire for helpful comments!
static HH_INLINE void XorByShift128Left12(const V4x64U& ba,
V4x64U* HH_RESTRICT out) {
const V4x64U zero = ba ^ ba;
const V4x64U top_bits2 = ba >> (64 - 2);
const V4x64U ones = ba == ba; // FF .. FF
const V4x64U shifted1_unmasked = ba + ba; // (avoids needing port0)
HH_COMPILER_FENCE;
// Only the lower halves of top_bits1's 128 bit lanes will be used, so we
// can compute it before clearing the upper two bits of ba.
const V4x64U top_bits1 = ba >> (64 - 1);
const V4x64U upper_8bytes(_mm256_slli_si256(ones, 8)); // F 0 F 0
const V4x64U shifted2 = shifted1_unmasked + shifted1_unmasked;
HH_COMPILER_FENCE;
const V4x64U upper_bit_of_128 = upper_8bytes << 63; // 80..00 80..00
const V4x64U new_low_bits2(_mm256_unpacklo_epi64(zero, top_bits2));
*out ^= shifted2;
HH_COMPILER_FENCE;
// The result must be as if the upper two bits of the input had been clear,
// otherwise we're no longer computing a reduction.
const V4x64U shifted1 = AndNot(upper_bit_of_128, shifted1_unmasked);
*out ^= new_low_bits2;
HH_COMPILER_FENCE;
const V4x64U new_low_bits1(_mm256_unpacklo_epi64(zero, top_bits1));
*out ^= shifted1;
*out ^= new_low_bits1;
}
// Modular reduction by the irreducible polynomial (x^128 + x^2 + x).
// Input: two 256-bit numbers a3210 and b3210, interleaved in 2 vectors.
// The upper and lower 128-bit halves are processed independently.
static HH_INLINE V4x64U ModularReduction(const V4x64U& b32a32,
const V4x64U& b10a10) {
// See Lemire, https://arxiv.org/pdf/1503.03465v8.pdf.
V4x64U out = b10a10;
XorByShift128Left12(b32a32, &out);
return out;
}
V4x64U v0;
V4x64U v1;
V4x64U mul0;
V4x64U mul1;
};
} // namespace HH_TARGET_NAME
} // namespace highwayhash
#endif // HH_DISABLE_TARGET_SPECIFIC
#endif // HIGHWAYHASH_HH_AVX2_H_
| {
"content_hash": "48c3dee741ea84e86258e62995edf4d9",
"timestamp": "",
"source": "github",
"line_count": 381,
"max_line_length": 80,
"avg_line_length": 41.86351706036746,
"alnum_prop": 0.6547962382445142,
"repo_name": "google/highwayhash",
"id": "db44f533cca514cfb87fb8af279ade828752fd8d",
"size": "15950",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "highwayhash/hh_avx2.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "20147"
},
{
"name": "C++",
"bytes": "402657"
},
{
"name": "Java",
"bytes": "14386"
},
{
"name": "Makefile",
"bytes": "4569"
},
{
"name": "Roff",
"bytes": "3456"
},
{
"name": "Shell",
"bytes": "567"
}
],
"symlink_target": ""
} |
(function(/*! Brunch !*/) {
'use strict';
var globals = typeof window !== 'undefined' ? window : global;
if (typeof globals.require === 'function') return;
var modules = {};
var cache = {};
var has = function(object, name) {
return ({}).hasOwnProperty.call(object, name);
};
var expand = function(root, name) {
var results = [], parts, part;
if (/^\.\.?(\/|$)/.test(name)) {
parts = [root, name].join('/').split('/');
} else {
parts = name.split('/');
}
for (var i = 0, length = parts.length; i < length; i++) {
part = parts[i];
if (part === '..') {
results.pop();
} else if (part !== '.' && part !== '') {
results.push(part);
}
}
return results.join('/');
};
var dirname = function(path) {
return path.split('/').slice(0, -1).join('/');
};
var localRequire = function(path) {
return function(name) {
var dir = dirname(path);
var absolute = expand(dir, name);
return globals.require(absolute);
};
};
var initModule = function(name, definition) {
var module = {id: name, exports: {}};
definition(module.exports, localRequire(name), module);
var exports = cache[name] = module.exports;
return exports;
};
var require = function(name) {
var path = expand(name, '.');
if (has(cache, path)) return cache[path];
if (has(modules, path)) return initModule(path, modules[path]);
var dirIndex = expand(path, './index');
if (has(cache, dirIndex)) return cache[dirIndex];
if (has(modules, dirIndex)) return initModule(dirIndex, modules[dirIndex]);
throw new Error('Cannot find module "' + name + '"');
};
var define = function(bundle) {
for (var key in bundle) {
if (has(bundle, key)) {
modules[key] = bundle[key];
}
}
}
globals.require = require;
globals.require.define = define;
globals.require.brunch = true;
})();
window.require.define({"test/spec": function(exports, require, module) {
}});
| {
"content_hash": "6e10c674b0001b3b412c48da6e50d4da",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 79,
"avg_line_length": 24.542168674698797,
"alnum_prop": 0.5670103092783505,
"repo_name": "rtxanson/brunch-crumpets",
"id": "00ecbe5cceaba6a3264a66bc705df833d012cd49",
"size": "2037",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "public/test/javascripts/test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "2357"
},
{
"name": "JavaScript",
"bytes": "355088"
}
],
"symlink_target": ""
} |
using namespace LmkImageLib;
LmkRectangleInt::LmkRectangleInt() {
this->column = 0;
this->row = 0;
this->width = 0;
this->height = 0;
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="rectangle"></param>
LmkRectangleInt::LmkRectangleInt(LmkRectangleInt^ rectangle) {
this->column = rectangle->Column;
this->row = rectangle->Row;
this->width = rectangle->Width;
this->height = rectangle->Height;
}
LmkRectangleInt::LmkRectangleInt(int column, int row, int width, int height) {
this->column = column;
this->row = row;
this->width = width;
this->height = height;
}
LmkRectangleInt^ LmkRectangleInt::Clone() {
return gcnew LmkRectangleInt(this);
}
LmkRectangleDbl^ LmkRectangleInt::ToDouble() {
return gcnew LmkRectangleDbl(
this->column,
this->row,
this->width,
this->height
);
}
int LmkRectangleInt::Column::get() {
return this->column;
}
int LmkRectangleInt::Row::get() {
return this->row;
}
int LmkRectangleInt::Width::get() {
return this->width;
}
int LmkRectangleInt::Height::get() {
return this->height;
}
LmkPointDbl^ LmkRectangleInt::Center::get() {
return gcnew LmkPointDbl(
(double)this->column + (double)this->width / 2.0,
(double)this->row + (double)this->height / 2.0
);
}
| {
"content_hash": "8f1338d1fa11caa60fa2bc0b6d259458",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 79,
"avg_line_length": 21.271186440677965,
"alnum_prop": 0.6860557768924302,
"repo_name": "leetmikeal/LmkPhotoViewer",
"id": "cfdaecad31ca71592c730bb0297b51e481a21094",
"size": "1376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LmkImageLib/src/LmkRectangleInt.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "115534"
},
{
"name": "C#",
"bytes": "50926"
},
{
"name": "C++",
"bytes": "2690827"
},
{
"name": "CMake",
"bytes": "21312"
},
{
"name": "Objective-C",
"bytes": "42405"
}
],
"symlink_target": ""
} |
package org.jrpolish.arithmetic;
import org.jrpolish.Operand;
/**
*
*
* @author dylan.chen 2010-7-31
*
*/
public class LSParenthesis extends ArithmeticOperator {
public final static char OPERATOR = '(';
private final static short ICP=8;
private final static short ISP=1;
private final static short AMOUNT_OF_OPERAND=0;
private static class Holder {
public static LSParenthesis lsparenthesis = new LSParenthesis();
}
private LSParenthesis() {
}
public static LSParenthesis getInstance() {
return Holder.lsparenthesis;
}
@Override
public Operand calculate(Operand[] operands) {
return null;
}
@Override
public short getAmountOfOperand() {
return AMOUNT_OF_OPERAND;
}
@Override
public short getICP() {
return ICP;
}
@Override
public short getISP() {
return ISP;
}
@Override
public String toString() {
return Character.toString(OPERATOR);
}
}
| {
"content_hash": "6a297374ce404bfabb04673e25063e97",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 66,
"avg_line_length": 16.859649122807017,
"alnum_prop": 0.6701352757544224,
"repo_name": "chenzuopeng/jrpolish",
"id": "5ea8334a3beeb121902eca6ad776901ab93dea94",
"size": "961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/jrpolish/arithmetic/LSParenthesis.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "20708"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Class Support_activities extends CI_Model{
function __contruct(){
parent::__contruct();
}
function get_activities_by_keyword( $where ){
$session = $this->session->userdata('logged_in');
$bd = $session['bd'];
$this->load->database( $bd , TRUE);
/*
$this->db->select('*');
$this->db->distinct();
$this->db->from('support_activities');
$this->db->like('description', $where);
$this->db->order_by("description", "asc");
*/
//$this->db->select('SELECT distinct(description) FROM sistema_gascomb.support_activities where description like "%muelles%";');
$query = $this->db->query('SELECT distinct(description) FROM support_activities where description like "%'.$where.'%";');
return $query;
}
function search_support_activity_by_description( $description ){
$session = $this->session->userdata('logged_in');
$bd = $session['bd'];
$this->load->database( $bd , TRUE);
$this->db->select('support_activity_id');
$this->db->from('support_activities');
$this->db->where('description', $description);
$this->db->limit(1);
return $this->db->get();
}
}
?> | {
"content_hash": "4184d8cbfe70aac01ec436ec14c3aa60",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 132,
"avg_line_length": 26.659574468085108,
"alnum_prop": 0.6049481245011972,
"repo_name": "roberto-alarcon/Admin-Gascomb",
"id": "6bc156ada806a5ebc1ac30228ea15cb000053d6f",
"size": "1253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/models/Support_activities.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "621243"
},
{
"name": "HTML",
"bytes": "7439276"
},
{
"name": "JavaScript",
"bytes": "3503737"
},
{
"name": "PHP",
"bytes": "1915001"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/><!-- using block title in layout.dt--><!-- using block ddox.defs in ddox.layout.dt--><!-- using block ddox.title in ddox.layout.dt-->
<title>Method AwesomiumView.shutdown</title>
<link rel="stylesheet" type="text/css" href="../../styles/ddox.css"/>
<link rel="stylesheet" href="../../prettify/prettify.css" type="text/css"/>
<script type="text/javascript" src="../../scripts/jquery.js">/**/</script>
<script type="text/javascript" src="../../prettify/prettify.js">/**/</script>
<script type="text/javascript" src="../../scripts/ddox.js">/**/</script>
</head>
<body onload="prettyPrint(); setupDdox();">
<nav id="main-nav"><!-- using block navigation in layout.dt-->
<ul class="tree-view">
<li class=" tree-view">
<a href="#" class="package">components</a>
<ul class="tree-view">
<li>
<a href="../../components/animation.html" class=" module">animation</a>
</li>
<li>
<a href="../../components/assets.html" class=" module">assets</a>
</li>
<li>
<a href="../../components/behavior.html" class=" module">behavior</a>
</li>
<li>
<a href="../../components/camera.html" class=" module">camera</a>
</li>
<li>
<a href="../../components/icomponent.html" class=" module">icomponent</a>
</li>
<li>
<a href="../../components/lights.html" class=" module">lights</a>
</li>
<li>
<a href="../../components/material.html" class=" module">material</a>
</li>
<li>
<a href="../../components/mesh.html" class=" module">mesh</a>
</li>
<li>
<a href="../../components/userinterface.html" class="selected module">userinterface</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">core</a>
<ul class="tree-view">
<li>
<a href="../../core/dgame.html" class=" module">dgame</a>
</li>
<li>
<a href="../../core/gameobject.html" class=" module">gameobject</a>
</li>
<li>
<a href="../../core/prefabs.html" class=" module">prefabs</a>
</li>
<li>
<a href="../../core/properties.html" class=" module">properties</a>
</li>
<li>
<a href="../../core/reflection.html" class=" module">reflection</a>
</li>
<li>
<a href="../../core/scene.html" class=" module">scene</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">graphics</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">adapters</a>
<ul class="tree-view">
<li>
<a href="../../graphics/adapters/adapter.html" class=" module">adapter</a>
</li>
<li>
<a href="../../graphics/adapters/linux.html" class=" module">linux</a>
</li>
<li>
<a href="../../graphics/adapters/mac.html" class=" module">mac</a>
</li>
<li>
<a href="../../graphics/adapters/win32.html" class=" module">win32</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">shaders</a>
<ul class="tree-view">
<li class="collapsed tree-view">
<a href="#" class="package">glsl</a>
<ul class="tree-view">
<li>
<a href="../../graphics/shaders/glsl/ambientlight.html" class=" module">ambientlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/animatedgeometry.html" class=" module">animatedgeometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/directionallight.html" class=" module">directionallight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/geometry.html" class=" module">geometry</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/pointlight.html" class=" module">pointlight</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/shadowmap.html" class=" module">shadowmap</a>
</li>
<li>
<a href="../../graphics/shaders/glsl/userinterface.html" class=" module">userinterface</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/shaders/glsl.html" class=" module">glsl</a>
</li>
<li>
<a href="../../graphics/shaders/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li>
<a href="../../graphics/adapters.html" class=" module">adapters</a>
</li>
<li>
<a href="../../graphics/graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../graphics/shaders.html" class=" module">shaders</a>
</li>
</ul>
</li>
<li class="collapsed tree-view">
<a href="#" class="package">utility</a>
<ul class="tree-view">
<li>
<a href="../../utility/awesomium.html" class=" module">awesomium</a>
</li>
<li>
<a href="../../utility/concurrency.html" class=" module">concurrency</a>
</li>
<li>
<a href="../../utility/config.html" class=" module">config</a>
</li>
<li>
<a href="../../utility/filepath.html" class=" module">filepath</a>
</li>
<li>
<a href="../../utility/input.html" class=" module">input</a>
</li>
<li>
<a href="../../utility/output.html" class=" module">output</a>
</li>
<li>
<a href="../../utility/string.html" class=" module">string</a>
</li>
<li>
<a href="../../utility/tasks.html" class=" module">tasks</a>
</li>
<li>
<a href="../../utility/time.html" class=" module">time</a>
</li>
</ul>
</li>
<li>
<a href="../../components.html" class=" module">components</a>
</li>
<li>
<a href="../../core.html" class=" module">core</a>
</li>
<li>
<a href="../../graphics.html" class=" module">graphics</a>
</li>
<li>
<a href="../../utility.html" class=" module">utility</a>
</li>
</ul>
<noscript>
<p style="color: red">The search functionality needs JavaScript enabled</p>
</noscript>
<div id="symbolSearchPane" style="display: none">
<p>
<input id="symbolSearch" type="text" placeholder="Search for symbols" onchange="performSymbolSearch(24);" onkeypress="this.onchange();" onpaste="this.onchange();" oninput="this.onchange();"/>
</p>
<ul id="symbolSearchResults" style="display: none"></ul>
<script type="application/javascript" src="../../symbols.js"></script>
<script type="application/javascript">
//<![CDATA[
var symbolSearchRootDir = "../../"; $('#symbolSearchPane').show();
//]]>
</script>
</div>
</nav>
<div id="main-contents">
<h1>Method AwesomiumView.shutdown</h1><!-- using block body in layout.dt--><!-- Default block ddox.description in ddox.layout.dt--><!-- Default block ddox.sections in ddox.layout.dt--><!-- using block ddox.members in ddox.layout.dt-->
<p> TODO
</p>
<section></section>
<section>
<h2>Prototype</h2>
<pre class="code prettyprint lang-d prototype">
void shutdown() override;</pre>
</section>
<section><h2>Parameters</h2>
<table><col class="caption"><tr><th>Name</th><th>Description</th></tr>
</table>
</section>
<section><h2>Returns</h2>
</section>
<section>
<h2>Authors</h2><!-- using block ddox.authors in ddox.layout.dt-->
</section>
<section>
<h2>Copyright</h2><!-- using block ddox.copyright in ddox.layout.dt-->
</section>
<section>
<h2>License</h2><!-- using block ddox.license in ddox.layout.dt-->
</section>
</div>
</body>
</html> | {
"content_hash": "1987402e77495bad1505f7594626877d",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 237,
"avg_line_length": 33.862660944206006,
"alnum_prop": 0.5342205323193916,
"repo_name": "Circular-Studios/Dash-Docs",
"id": "6e246497c4af82db380b9687509c19d1b06ba65e",
"size": "7890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/v0.8.0/components/userinterface/AwesomiumView.shutdown.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "146638"
},
{
"name": "HTML",
"bytes": "212463985"
},
{
"name": "JavaScript",
"bytes": "72098"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue May 12 14:55:48 CEST 2015 -->
<title>Uses of Class service.workflow.ast.ASTNode.BitwiseInclOrOp</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class service.workflow.ast.ASTNode.BitwiseInclOrOp";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../service/workflow/ast/ASTNode.BitwiseInclOrOp.html" title="class in service.workflow.ast">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?service/workflow/ast/class-use/ASTNode.BitwiseInclOrOp.html" target="_top">Frames</a></li>
<li><a href="ASTNode.BitwiseInclOrOp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class service.workflow.ast.ASTNode.BitwiseInclOrOp" class="title">Uses of Class<br>service.workflow.ast.ASTNode.BitwiseInclOrOp</h2>
</div>
<div class="classUseContainer">No usage of service.workflow.ast.ASTNode.BitwiseInclOrOp</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../service/workflow/ast/ASTNode.BitwiseInclOrOp.html" title="class in service.workflow.ast">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?service/workflow/ast/class-use/ASTNode.BitwiseInclOrOp.html" target="_top">Frames</a></li>
<li><a href="ASTNode.BitwiseInclOrOp.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "4a7a99c56435d7fd02df555c119e9892",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 151,
"avg_line_length": 35.62096774193548,
"alnum_prop": 0.6241793072220965,
"repo_name": "musman/RSP",
"id": "7ab304844db4d81c3dfec40a99532a0faaebd050",
"size": "4417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ResearchServicePlatform/doc/service/workflow/ast/class-use/ASTNode.BitwiseInclOrOp.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "12808"
},
{
"name": "HTML",
"bytes": "6379935"
},
{
"name": "Java",
"bytes": "763595"
},
{
"name": "JavaScript",
"bytes": "827"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Cake.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Reflection;
using System;
[assembly: AssemblyTitle("Cake.Coveralls")]
[assembly: AssemblyDescription("Cake Coveralls AddIn")]
[assembly: AssemblyCompany("Cake Contributions")]
[assembly: AssemblyProduct("Cake.Coveralls")]
[assembly: AssemblyVersion("0.1.0")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyCopyright("Copyright © Cake Contributions 2016 - Present")]
[assembly: CLSCompliant(true)]
| {
"content_hash": "1ebc037bfdf820ba63babdbf98025618",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 81,
"avg_line_length": 39.94444444444444,
"alnum_prop": 0.5841446453407511,
"repo_name": "cake-contrib/Cake.Coveralls",
"id": "d146b813c8d5d3575e61e9b15be16673b97331c2",
"size": "722",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "Source/SolutionInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "38207"
},
{
"name": "PowerShell",
"bytes": "394"
},
{
"name": "Shell",
"bytes": "207"
}
],
"symlink_target": ""
} |
# mesos-consul
[](https://travis-ci.org/CiscoCloud/mesos-consul)
Mesos to Consul bridge for service discovery.
Mesos-consul automatically registers/deregisters services run as Mesos tasks.
This means if you have a Mesos task called `application`, this program will register the application in Consul, and it will be exposed via DNS as `application.service.consul`.
This program also does Mesos leader discovery, so that `leader.mesos.service.consul` will point to the current leader.
<!-- markdown-toc start - Don't edit this section. Run M-x markdown-toc/generate-toc again -->
**Table of Contents**
- [mesos-consul](#mesos-consul)
- [Comparisons to other discovery software](#comparisons-to-other-discovery-software)
- [[Mesos-dns](https://github.com/mesosphere/mesos-dns/)](#mesos-dnshttpsgithubcommesospheremesos-dns)
- [[Registrator](https://github.com/gliderlabs/registrator)](#registratorhttpsgithubcomgliderlabsregistrator)
- [Building](#building)
- [Running](#running)
- [Usage](#usage)
- [Options](#options)
- [Consul Registration](#consul-registration)
- [Leader, Master and Follower Nodes](#leader-master-and-follower-nodes)
- [Mesos Tasks](#mesos-tasks)
- [Todo](#todo)
<!-- markdown-toc end -->
## Comparisons to other discovery software
### [Mesos-dns](https://github.com/mesosphere/mesos-dns/)
This project is similar to mesos-dns in that it polls Mesos to get information about tasks. However, instead of exposing this information via a built-in DNS server, we populate Consul service discovery with this information. Consul then exposes the services via DNS and via its API.
Benefits of using Consul:
* Integration with other tools like [consul-template](https://github.com/hashicorp/consul-template)
* Multi-DC DNS lookups
* Configurable health checks that run on each system
### [Registrator](https://github.com/gliderlabs/registrator)
Registrator is another tool that populates Consul (and other backends like etcd) with the status of Docker containers. However, Registrator is currently limited to reporting on Docker containers and does not track Mesos tasks.
## Building and running mesos-consul
### Building and running in Docker
Mesos-consul can be run in a Docker container via Marathon.
To build the Docker image, do:
```
docker build -t mesos-consul .
```
To run mesos-consul, start the docker image within Mesos. If your Zookeeper and Marathon services are registered in consul, you can use `.service.consul` to find them, otherwise change the vaules for your environment:
```
curl -X POST -d@mesos-consul.json -H "Content-Type: application/json" http://marathon.service.consul:8080/v2/apps'
```
Where `mesos-consul.json` is similar to (replacing the image with your image):
```
{
"args": [
"--zk=zk://zookeeper.service.consul:2181/mesos"
],
"container": {
"type": "DOCKER",
"docker": {
"network": "BRIDGE",
"image": "{{ mesos_consul_image }}:{{ mesos_consul_image_tag }}"
}
},
"id": "mesos-consul",
"instances": 1,
"cpus": 0.1,
"mem": 256
}
```
You can add options to authenticate via basic http or Consul token.
### Building and running as a service on the Marathon instance
If you don't want to use Docker, it is possible to compile the binary and run it on a Marathon / Mesos master server.
To build it:
* ensure that Go is installed on the build server
* make sure GOPATH is set
* clone this repository and cd into it
* run `make`
* the binary will be created at bin/mesos-consul
* copy this to the Marathon server and start it with `mesos-consul --zk=zk://zookeeper.service.consul:2181/mesos`
## Usage
### Options
| Option | Description |
|-----------------------|-------------|
| `version` | Print mesos-consul version
| `log-level` | Set the Logging level to one of DEBUG, INFO, WARN, ERROR. (default WARN)
| `refresh` | Time between refreshes of Mesos tasks
| `mesos-ip-order` | Comma separated list to control the order in which github.com/CiscoCloud/mesos-consul searches or the task IP address. Valid options are 'netinfo', 'mesos', 'docker' and 'host' (default netinfo,mesos,host)
| `healthcheck` | Enables a http endpoint for health checks. When this flag is enabled, serves health status on 127.0.0.1:24476
| `healthcheck-ip` | Health check service interface ip
| `healthcheck-port` | Health check service port. (default 24476)
| `consul-auth` | The basic authentication username (and optional password), separated by a colon.
| `consul-ssl` | Use HTTPS while talking to the registry.
| `consul-ssl-verify` | Verify certificates when connecting via SSL.
| `consul-ssl-cert` | Path to an SSL certificate to use to authenticate to the registry server
| `consul-ssl-cacert` | Path to a CA certificate file, containing one or more CA certificates to use to valid the registry server certificate
| `consul-token` | The registry ACL token
| `heartbeats-before-remove` | Number of times that registration needs to fail before removing task from Consul. (default: 1)
| `whitelist` | Only register services matching the provided regex. Can be specified multitple time
| `blacklist` | Does not register services matching the provided regex. Can be specified multitple time
| `service-name=<name>` | Service name of the Mesos hosts
| `service-tags=<tag>,...` | Comma delimited list of tags to register the Mesos hosts. Mesos hosts will be registered as (leader|master|follower).<tag>.<service>.service.consul
| `service-id-prefix=<prefix>` | Prefix to use for consul service ids registered by mesos-consul. (default: mesos-consul)
| `task-tag=<pattern:tag>` | Tag tasks matching pattern with given tag. Can be specified multitple times
| `zk`\* | Location of the Mesos path in Zookeeper. The default value is zk://127.0.0.1:2181/mesos
| `log-level` | Level that mesos-consul should log at. Options are [ "DEBUG", "INFO", "WARN", "ERROR" ]. Default is WARN. |
| `group-separator` | Choose the group separator. Will replace _ in task names (default is empty)
### Consul Registration
#### Leader, Master and Follower Nodes
| Role | Registration
|------------|--------------
| `Leader` | `leader.mesos.service.consul`, `master.mesos.service.consul`
| `Master` | `master.mesos.service.consul`
| `Follower` | `follower.mesos.service.consul`
#### Mesos Tasks
Tasks are registered as `task_name.service.consul`
#### Tags
Tags can be added to consul by using labels in Mesos. If you are using Marathon you can add a label called `tags` to your service definition with a comma-separated list of strings that will be registered in consul as tags.
For example, in your marathon service definition:
```
{
"id": "tagging-test",
"container": { /*...*/},
"labels": {
"tags": "label1,label2,label3"
}
}
```
This will result in a service `tagging-test` being created in consul with 3 separate tags: `label1` `label2` and `label3`
```
// GET /v1/catalog/service/tagging-test
[
{
Node: "consul",
Address: "10.0.2.15",
ServiceID: "mesos-consul:10.0.2.15:tagging-test:31562",
ServiceName: "tagging-test5",
ServiceTags: [
"label1",
"label2",
"label3"
],
ServiceAddress: "10.0.2.15",
ServicePort: 31562
}
]
```
#### Override Task Name
By adding a label `overrideTaskName` with an arbitrary value, the value is used as the service name during consul registration.
Tags are preserved.
## Todo
* Use task labels for metadata
* Support for multiple port tasks
| {
"content_hash": "6cbfe2218bcecfb880cc48aceef67a95",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 282,
"avg_line_length": 41.85405405405405,
"alnum_prop": 0.7008911274699728,
"repo_name": "CiscoCloud/mesos-consul",
"id": "24ba8bfb4758016940ef923a60aafefc9344821e",
"size": "7743",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "49882"
},
{
"name": "Makefile",
"bytes": "989"
}
],
"symlink_target": ""
} |
<?php // vim:ts=4:sw=4:et:fdm=marker
/*
* Undocumented
*
* @link http://agiletoolkit.org/
*//*
==ATK4===================================================
This file is part of Agile Toolkit 4
http://agiletoolkit.org/
(c) 2008-2013 Agile Toolkit Limited <info@agiletoolkit.org>
Distributed under Affero General Public License v3 and
commercial license.
See LICENSE or LICENSE_COM for more information
=====================================================ATK4=*/
class Exception_Hook extends BaseException {
public $return_value;
}
| {
"content_hash": "494941a73190266152a7431a5033246c",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 62,
"avg_line_length": 29.31578947368421,
"alnum_prop": 0.5745062836624776,
"repo_name": "svisystem/atk4",
"id": "f9d49afc8ce1553c6540784dcfab87dbc3744d2d",
"size": "557",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "lib/Exception/Hook.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "55"
},
{
"name": "CSS",
"bytes": "598221"
},
{
"name": "HTML",
"bytes": "171586"
},
{
"name": "JavaScript",
"bytes": "89990"
},
{
"name": "PHP",
"bytes": "1039356"
}
],
"symlink_target": ""
} |
//
// ========================================================================
// Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.security;
import java.security.GeneralSecurityException;
import java.security.InvalidParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Security;
import java.security.cert.CRL;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertPathBuilderResult;
import java.security.cert.CertPathValidator;
import java.security.cert.CertStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* Convenience class to handle validation of certificates, aliases and keystores
*
* Allows specifying Certificate Revocation List (CRL), as well as enabling
* CRL Distribution Points Protocol (CRLDP) certificate extension support,
* and also enabling On-Line Certificate Status Protocol (OCSP) support.
*
* IMPORTANT: at least one of the above mechanisms *MUST* be configured and
* operational, otherwise certificate validation *WILL FAIL* unconditionally.
*/
public class CertificateValidator
{
private static final Logger LOG = Log.getLogger(CertificateValidator.class);
private static AtomicLong __aliasCount = new AtomicLong();
private KeyStore _trustStore;
private Collection<? extends CRL> _crls;
/** Maximum certification path length (n - number of intermediate certs, -1 for unlimited) */
private int _maxCertPathLength = -1;
/** CRL Distribution Points (CRLDP) support */
private boolean _enableCRLDP = false;
/** On-Line Certificate Status Protocol (OCSP) support */
private boolean _enableOCSP = false;
/**
* creates an instance of the certificate validator
*
* @param trustStore
* @param crls
*/
public CertificateValidator(KeyStore trustStore, Collection<? extends CRL> crls)
{
if (trustStore == null)
{
throw new InvalidParameterException("TrustStore must be specified for CertificateValidator.");
}
_trustStore = trustStore;
_crls = crls;
}
/**
* validates a specific certificate inside of the keystore being passed in
*
* @param keyStore
* @param cert
* @throws CertificateException
*/
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException
{
Certificate[] certChain = null;
if (cert != null && cert instanceof X509Certificate)
{
((X509Certificate)cert).checkValidity();
String certAlias = null;
try
{
if (keyStore == null)
{
throw new InvalidParameterException("Keystore cannot be null");
}
certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
if (certAlias == null)
{
certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet());
keyStore.setCertificateEntry(certAlias, cert);
}
certChain = keyStore.getCertificateChain(certAlias);
if (certChain == null || certChain.length == 0)
{
throw new IllegalStateException("Unable to retrieve certificate chain");
}
}
catch (KeyStoreException kse)
{
LOG.debug(kse);
throw new CertificateException("Unable to validate certificate" +
(certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
}
validate(certChain);
}
}
public void validate(Certificate[] certChain) throws CertificateException
{
try
{
ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
for (Certificate item : certChain)
{
if (item == null)
continue;
if (!(item instanceof X509Certificate))
{
throw new IllegalStateException("Invalid certificate type in chain");
}
certList.add((X509Certificate)item);
}
if (certList.isEmpty())
{
throw new IllegalStateException("Invalid certificate chain");
}
X509CertSelector certSelect = new X509CertSelector();
certSelect.setCertificate(certList.get(0));
// Configure certification path builder parameters
PKIXBuilderParameters pbParams = new PKIXBuilderParameters(_trustStore, certSelect);
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList)));
// Set maximum certification path length
pbParams.setMaxPathLength(_maxCertPathLength);
// Enable revocation checking
pbParams.setRevocationEnabled(true);
// Set static Certificate Revocation List
if (_crls != null && !_crls.isEmpty())
{
pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(_crls)));
}
// Enable On-Line Certificate Status Protocol (OCSP) support
if (_enableOCSP)
{
Security.setProperty("ocsp.enable","true");
}
// Enable Certificate Revocation List Distribution Points (CRLDP) support
if (_enableCRLDP)
{
System.setProperty("com.sun.security.enableCRLDP","true");
}
// Build certification path
CertPathBuilderResult buildResult = CertPathBuilder.getInstance("PKIX").build(pbParams);
// Validate certification path
CertPathValidator.getInstance("PKIX").validate(buildResult.getCertPath(),pbParams);
}
catch (GeneralSecurityException gse)
{
LOG.debug(gse);
throw new CertificateException("Unable to validate certificate: " + gse.getMessage(), gse);
}
}
/* ------------------------------------------------------------ */
/**
* @param maxCertPathLength
* maximum number of intermediate certificates in
* the certification path (-1 for unlimited)
*/
public void setMaxCertPathLength(int maxCertPathLength)
{
_maxCertPathLength = maxCertPathLength;
}
/* ------------------------------------------------------------ */
/** Enables CRL Distribution Points Support
* @param enableCRLDP true - turn on, false - turns off
*/
public void setEnableCRLDP(boolean enableCRLDP)
{
_enableCRLDP = enableCRLDP;
}
/* ------------------------------------------------------------ */
/** Enables On-Line Certificate Status Protocol support
* @param enableOCSP true - turn on, false - turn off
*/
public void setEnableOCSP(boolean enableOCSP)
{
_enableOCSP = enableOCSP;
}
}
| {
"content_hash": "eba8146f3f2c78f3557f92fa4adca274",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 117,
"avg_line_length": 37.17982456140351,
"alnum_prop": 0.5842868939483308,
"repo_name": "soulfly/guinea-pig-smart-bot",
"id": "0516a60d1201b08980e6eca2fa5e23249380d111",
"size": "8477",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/quickblox/samples/cordova/text_chat/platforms/android/src/org/eclipse/jetty/util/security/CertificateValidator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "4485"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Voodoo.Messages;
using Voodoo.Tests.TestClasses;
using Voodoo.Validation.Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Voodoo.Logging;
using Voodoo.Tests.Voodoo.Logging;
namespace Voodoo.Tests.Voodoo.Operations
{
[TestClass]
public class CommandTests
{
[TestMethod]
public void Execute_ExceptionIsThrown_IsNotOk()
{
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = false;
var result = new CommandThatThrowsErrors(new EmptyRequest()).Execute();
Assert.AreEqual(false, result.IsOk);
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = true;
}
[TestMethod]
public void Execute_ExceptionIsThrown_ExceptionIsBubbled()
{
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = false;
var result = new CommandThatThrowsErrors(new EmptyRequest()).Execute();
Assert.AreEqual(TestingResponse.OhNo, result.Message);
Assert.IsNotNull(result.Exception);
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = true;
}
[TestMethod]
public void Execute_CommandReturnsResponse_IsOk()
{
var result = new CommandThatDoesNotThrowErrors(new EmptyRequest()).Execute();
Assert.IsNotNull(result);
Assert.IsNull(result.Message);
Assert.AreEqual(true, result.IsOk);
}
[TestMethod]
public void Execute_RequestIsInvalidDataAnnotationsValidatorWithFirstErrorAsMessage_IsNotOk()
{
VoodooGlobalConfiguration.RegisterValidator(new DataAnnotationsValidatorWithFirstErrorAsMessage());
var result = new CommandWithNonEmptyRequest(new RequestWithRequiredString()).Execute();
Assert.IsNotNull(result);
Assert.IsNotNull(result.Message);
Assert.AreEqual(result.Details.First().Value, result.Message);
Assert.AreNotEqual(true, result.IsOk);
VoodooGlobalConfiguration.RegisterValidator(new DataAnnotationsValidatorWithFirstErrorAsMessage());
VoodooGlobalConfiguration.RegisterValidator(new DataAnnotationsValidatorWithGenericMessage());
}
[TestMethod]
public void Execute_RequestIsInvalidDataAnnotationsValidatorWithGenericMessage_IsNotOk()
{
VoodooGlobalConfiguration.RegisterValidator(new DataAnnotationsValidatorWithGenericMessage());
var result = new CommandWithNonEmptyRequest(new RequestWithRequiredString()).Execute();
Assert.IsNotNull(result);
Assert.IsNotNull(result.Message);
Assert.AreEqual(Strings.Validation.validationErrorsOccurred, result.Message);
Assert.AreNotEqual(true, result.IsOk);
}
[TestMethod]
public void Execute_ExceptionIsThrownWithLogInExceptionData_ExtraExceptionPropertiesAreCaptured()
{
var testLogger = new TestLogger();
LogManager.Logger = testLogger;
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = false;
VoodooGlobalConfiguration.ErrorDetailLoggingMethodology = ErrorDetailLoggingMethodology.LogInExceptionData;
var result = new CommandThatThrowsErrors(new EmptyRequest()).Execute();
testLogger.Exceptions.Count().Should().Be(1);
var ex = testLogger.Exceptions.First();
var keys = ex.Data.Keys;
var values = new List<string>();
foreach (var key in keys)
{
values.Add(ex.Data[key].ToString());
}
var hasSpecialPropertyValue = values.Any(c => c.Contains(TestException.UsefulDebugInformation));
hasSpecialPropertyValue.Should().Be(true);
}
[TestMethod]
public void Execute_ExceptionIsThrownWithLogAsSeperateException_ExtraExceptionPropertiesAreCaptured()
{
var testLogger = new TestLogger();
LogManager.Logger = testLogger;
VoodooGlobalConfiguration.RemoveExceptionFromResponseAfterLogging = false;
VoodooGlobalConfiguration.ErrorDetailLoggingMethodology = ErrorDetailLoggingMethodology.LogAsSecondException;
var result = new CommandThatThrowsErrors(new EmptyRequest()).Execute();
testLogger.Exceptions.Count().Should().Be(1);
testLogger.Messages.Count().Should().Be(1);
var ex = testLogger.Messages.First();
ex.IndexOf(TestException.UsefulDebugInformation).Should().BeGreaterThan(0);
}
}
} | {
"content_hash": "a374b2d66f53981e88e2ac04c697f55f",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 121,
"avg_line_length": 45.56730769230769,
"alnum_prop": 0.6881198565098122,
"repo_name": "MiniverCheevy/voodoo",
"id": "68f522ec9c1579e62bebdd25654c317bdeb78820",
"size": "4741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests.net461/Voodoo/Operations/CommandTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2199"
},
{
"name": "C#",
"bytes": "294662"
}
],
"symlink_target": ""
} |
package net.voxelindustry.brokkgui.style.adapter;
import net.voxelindustry.brokkgui.sprite.SpriteRepeat;
public class BackgroundRepeatStyleTranslator implements IStyleDecoder<SpriteRepeat>, IStyleEncoder<SpriteRepeat>, IStyleValidator<SpriteRepeat>
{
@Override
public SpriteRepeat decode(String style)
{
switch (style)
{
case "none":
return SpriteRepeat.NONE;
case "repeat-x":
return SpriteRepeat.REPEAT_X;
case "repeat-y":
return SpriteRepeat.REPEAT_Y;
case "repeat":
return SpriteRepeat.REPEAT_BOTH;
}
throw new IllegalArgumentException("Cannot decode BackgroundRepeat value of [" + style + "]");
}
@Override
public String encode(SpriteRepeat value, boolean prettyPrint)
{
switch (value)
{
case NONE:
return "none";
case REPEAT_X:
return "repeat-x";
case REPEAT_Y:
return "repeat-y";
case REPEAT_BOTH:
return "repeat";
}
throw new RuntimeException("Unknown value given to BackgroundRepeatStyleTranslator! " + value.name());
}
@Override
public int validate(String style)
{
switch (style)
{
case "none":
return 4;
case "repeat-x":
case "repeat-y":
return 8;
case "repeat":
return 6;
}
return 0;
}
}
| {
"content_hash": "42d7b6a32be09e6b1f1a932e17a1c75e",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 143,
"avg_line_length": 27.982142857142858,
"alnum_prop": 0.5411614550095725,
"repo_name": "Yggard/BrokkGUI",
"id": "43c03d3a00b05c9e0425ccffa1880cd676c342a9",
"size": "1567",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/src/main/java/net/voxelindustry/brokkgui/style/adapter/BackgroundRepeatStyleTranslator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3787"
},
{
"name": "Java",
"bytes": "595773"
}
],
"symlink_target": ""
} |
import requests
import json
from functools import wraps
class PocketException(Exception):
'''
Base class for all pocket exceptions
http://getpocket.com/developer/docs/errors
'''
pass
class InvalidQueryException(PocketException):
pass
class AuthException(PocketException):
pass
class RateLimitException(PocketException):
'''
http://getpocket.com/developer/docs/rate-limits
'''
pass
class ServerMaintenanceException(PocketException):
pass
EXCEPTIONS = {
400: InvalidQueryException,
401: AuthException,
403: RateLimitException,
503: ServerMaintenanceException,
}
def method_wrapper(fn):
@wraps(fn)
def wrapped(self, *args, **kwargs):
arg_names = list(fn.__code__.co_varnames)
arg_names.remove('self')
kwargs.update(dict(zip(arg_names, args)))
url = self.api_endpoints[fn.__name__]
payload = dict([
(k, v) for k, v in kwargs.items()
if v is not None
])
payload.update(self.get_payload())
return self.make_request(url, payload)
return wrapped
def bulk_wrapper(fn):
@wraps(fn)
def wrapped(self, *args, **kwargs):
arg_names = list(fn.func_code.co_varnames)
arg_names.remove('self')
kwargs.update(dict(zip(arg_names, args)))
wait = kwargs.get('wait', True)
query = dict(
[(k, v) for k, v in kwargs.items() if v is not None]
)
# TODO: Fix this hack
query['action'] = 'add' if fn.__name__ == 'bulk_add' else fn.__name__
if wait:
self.add_bulk_query(query)
return self
else:
url = self.api_endpoints['send']
payload = {
'actions': [query],
}
payload.update(self.get_payload())
return self.make_request(
url,
json.dumps(payload),
headers={'content-type': 'application/json'},
)
return wrapped
class Pocket(object):
'''
This class implements a basic python wrapper around the pocket api. For a
detailed documentation of the methods and what they do please refer the
official pocket api documentation at
http://getpocket.com/developer/docs/overview
'''
api_endpoints = dict(
(method, 'https://getpocket.com/v3/%s' % method)
for method in "add,send,get".split(",")
)
statuses = {
200: 'Request was successful',
400: 'Invalid request, please make sure you follow the '
'documentation for proper syntax',
401: 'Problem authenticating the user',
403: 'User was authenticated, but access denied due to lack of '
'permission or rate limiting',
503: 'Pocket\'s sync server is down for scheduled maintenance.',
}
def __init__(self, consumer_key, access_token):
self.consumer_key = consumer_key
self.access_token = access_token
self._bulk_query = []
self._payload = {
'consumer_key': self.consumer_key,
'access_token': self.access_token,
}
def get_payload(self):
return self._payload
def add_bulk_query(self, query):
self._bulk_query.append(query)
@staticmethod
def _post_request(url, payload, headers):
r = requests.post(url, data=payload, headers=headers)
return r
@classmethod
def _make_request(cls, url, payload, headers=None):
r = cls._post_request(url, payload, headers)
if r.status_code > 399:
error_msg = cls.statuses.get(r.status_code)
extra_info = r.headers.get('X-Error')
raise EXCEPTIONS.get(r.status_code, PocketException)(
'%s. %s' % (error_msg, extra_info)
)
return r.json() or r.text, r.headers
@classmethod
def make_request(cls, url, payload, headers=None):
return cls._make_request(url, payload, headers)
@method_wrapper
def add(self, url, title=None, tags=None, tweet_id=None):
'''
This method allows you to add a page to a user's list.
In order to use the /v3/add endpoint, your consumer key must have the
"Add" permission.
http://getpocket.com/developer/docs/v3/add
'''
@method_wrapper
def get(
self, state=None, favorite=None, tag=None, contentType=None,
sort=None, detailType=None, search=None, domain=None, since=None,
count=None, offset=None
):
'''
This method allows you to retrieve a user's list. It supports
retrieving items changed since a specific time to allow for syncing.
http://getpocket.com/developer/docs/v3/retrieve
'''
@method_wrapper
def send(self, actions):
'''
This method allows you to make changes to a user's list. It supports
adding new pages, marking pages as read, changing titles, or updating
tags. Multiple changes to items can be made in one request.
http://getpocket.com/developer/docs/v3/modify
'''
@bulk_wrapper
def bulk_add(
self, item_id, ref_id=None, tags=None, time=None, title=None,
url=None, wait=True
):
'''
Add a new item to the user's list
http://getpocket.com/developer/docs/v3/modify#action_add
'''
@bulk_wrapper
def archive(self, item_id, time=None, wait=True):
'''
Move an item to the user's archive
http://getpocket.com/developer/docs/v3/modify#action_archive
'''
@bulk_wrapper
def readd(self, item_id, time=None, wait=True):
'''
Re-add (unarchive) an item to the user's list
http://getpocket.com/developer/docs/v3/modify#action_readd
'''
@bulk_wrapper
def favorite(self, item_id, time=None, wait=True):
'''
Mark an item as a favorite
http://getpocket.com/developer/docs/v3/modify#action_favorite
'''
@bulk_wrapper
def unfavorite(self, item_id, time=None, wait=True):
'''
Remove an item from the user's favorites
http://getpocket.com/developer/docs/v3/modify#action_unfavorite
'''
@bulk_wrapper
def delete(self, item_id, time=None, wait=True):
'''
Permanently remove an item from the user's account
http://getpocket.com/developer/docs/v3/modify#action_delete
'''
@bulk_wrapper
def tags_add(self, item_id, tags, time=None, wait=True):
'''
Add one or more tags to an item
http://getpocket.com/developer/docs/v3/modify#action_tags_add
'''
@bulk_wrapper
def tags_remove(self, item_id, tags, time=None, wait=True):
'''
Remove one or more tags from an item
http://getpocket.com/developer/docs/v3/modify#action_tags_remove
'''
@bulk_wrapper
def tags_replace(self, item_id, tags, time=None, wait=True):
'''
Replace all of the tags for an item with one or more provided tags
http://getpocket.com/developer/docs/v3/modify#action_tags_replace
'''
@bulk_wrapper
def tags_clear(self, item_id, time=None, wait=True):
'''
Remove all tags from an item.
http://getpocket.com/developer/docs/v3/modify#action_tags_clear
'''
@bulk_wrapper
def tag_rename(self, item_id, old_tag, new_tag, time=None, wait=True):
'''
Rename a tag. This affects all items with this tag.
http://getpocket.com/developer/docs/v3/modify#action_tag_rename
'''
def commit(self):
'''
This method executes the bulk query, flushes stored queries and
returns the response
'''
url = self.api_endpoints['send']
payload = {
'actions': self._bulk_query,
}
payload.update(self._payload)
self._bulk_query = []
return self._make_request(
url,
json.dumps(payload),
headers={'content-type': 'application/json'},
)
@classmethod
def get_request_token(
cls, consumer_key, redirect_uri='http://example.com/', state=None
):
'''
Returns the request token that can be used to fetch the access token
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/request'
payload = {
'consumer_key': consumer_key,
'redirect_uri': redirect_uri,
}
if state:
payload['state'] = state
return cls._make_request(url, payload, headers)[0]['code']
@classmethod
def get_credentials(cls, consumer_key, code):
'''
Fetches access token from using the request token and consumer key
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/authorize'
payload = {
'consumer_key': consumer_key,
'code': code,
}
return cls._make_request(url, payload, headers)[0]
@classmethod
def get_access_token(cls, consumer_key, code):
return cls.get_credentials(consumer_key, code)['access_token']
@classmethod
def get_auth_url(cls, code, redirect_uri='http://example.com'):
auth_url = ('https://getpocket.com/auth/authorize'
'?request_token=%s&redirect_uri=%s' % (code, redirect_uri))
return auth_url
@classmethod
def auth(
cls, consumer_key, redirect_uri='http://example.com/', state=None,
):
'''
This is a test method for verifying if oauth worked
http://getpocket.com/developer/docs/authentication
'''
code = cls.get_request_token(consumer_key, redirect_uri, state)
auth_url = 'https://getpocket.com/auth/authorize?request_token='\
'%s&redirect_uri=%s' % (code, redirect_uri)
raw_input(
'Please open %s in your browser to authorize the app and '
'press enter:' % auth_url
)
return cls.get_access_token(consumer_key, code)
| {
"content_hash": "cb05f06aa0049abe970065a2e7881b0d",
"timestamp": "",
"source": "github",
"line_count": 366,
"max_line_length": 79,
"avg_line_length": 27.950819672131146,
"alnum_prop": 0.5851417399804496,
"repo_name": "foolscap/pocket",
"id": "78fed0d73c0f701e52331efe59ff4da9b2debe2c",
"size": "10230",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pocket.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "12790"
}
],
"symlink_target": ""
} |
package com.azure.resourcemanager.deviceupdate.implementation;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.PagedResponse;
import com.azure.core.http.rest.PagedResponseBase;
import com.azure.core.util.CoreUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import reactor.core.publisher.Flux;
final class Utils {
static String getValueFromIdByName(String id, String name) {
if (id == null) {
return null;
}
Iterator<String> itr = Arrays.stream(id.split("/")).iterator();
while (itr.hasNext()) {
String part = itr.next();
if (part != null && !part.trim().isEmpty()) {
if (part.equalsIgnoreCase(name)) {
if (itr.hasNext()) {
return itr.next();
} else {
return null;
}
}
}
}
return null;
}
static String getValueFromIdByParameterName(String id, String pathTemplate, String parameterName) {
if (id == null || pathTemplate == null) {
return null;
}
String parameterNameParentheses = "{" + parameterName + "}";
List<String> idSegmentsReverted = Arrays.asList(id.split("/"));
List<String> pathSegments = Arrays.asList(pathTemplate.split("/"));
Collections.reverse(idSegmentsReverted);
Iterator<String> idItrReverted = idSegmentsReverted.iterator();
int pathIndex = pathSegments.size();
while (idItrReverted.hasNext() && pathIndex > 0) {
String idSegment = idItrReverted.next();
String pathSegment = pathSegments.get(--pathIndex);
if (!CoreUtils.isNullOrEmpty(idSegment) && !CoreUtils.isNullOrEmpty(pathSegment)) {
if (pathSegment.equalsIgnoreCase(parameterNameParentheses)) {
if (pathIndex == 0 || (pathIndex == 1 && pathSegments.get(0).isEmpty())) {
List<String> segments = new ArrayList<>();
segments.add(idSegment);
idItrReverted.forEachRemaining(segments::add);
Collections.reverse(segments);
if (segments.size() > 0 && segments.get(0).isEmpty()) {
segments.remove(0);
}
return String.join("/", segments);
} else {
return idSegment;
}
}
}
}
return null;
}
static <T, S> PagedIterable<S> mapPage(PagedIterable<T> pageIterable, Function<T, S> mapper) {
return new PagedIterableImpl<T, S>(pageIterable, mapper);
}
private static final class PagedIterableImpl<T, S> extends PagedIterable<S> {
private final PagedIterable<T> pagedIterable;
private final Function<T, S> mapper;
private final Function<PagedResponse<T>, PagedResponse<S>> pageMapper;
private PagedIterableImpl(PagedIterable<T> pagedIterable, Function<T, S> mapper) {
super(
PagedFlux
.create(
() ->
(continuationToken, pageSize) ->
Flux.fromStream(pagedIterable.streamByPage().map(getPageMapper(mapper)))));
this.pagedIterable = pagedIterable;
this.mapper = mapper;
this.pageMapper = getPageMapper(mapper);
}
private static <T, S> Function<PagedResponse<T>, PagedResponse<S>> getPageMapper(Function<T, S> mapper) {
return page ->
new PagedResponseBase<Void, S>(
page.getRequest(),
page.getStatusCode(),
page.getHeaders(),
page.getElements().stream().map(mapper).collect(Collectors.toList()),
page.getContinuationToken(),
null);
}
@Override
public Stream<S> stream() {
return pagedIterable.stream().map(mapper);
}
@Override
public Stream<PagedResponse<S>> streamByPage() {
return pagedIterable.streamByPage().map(pageMapper);
}
@Override
public Stream<PagedResponse<S>> streamByPage(String continuationToken) {
return pagedIterable.streamByPage(continuationToken).map(pageMapper);
}
@Override
public Stream<PagedResponse<S>> streamByPage(int preferredPageSize) {
return pagedIterable.streamByPage(preferredPageSize).map(pageMapper);
}
@Override
public Stream<PagedResponse<S>> streamByPage(String continuationToken, int preferredPageSize) {
return pagedIterable.streamByPage(continuationToken, preferredPageSize).map(pageMapper);
}
@Override
public Iterator<S> iterator() {
return new IteratorImpl<T, S>(pagedIterable.iterator(), mapper);
}
@Override
public Iterable<PagedResponse<S>> iterableByPage() {
return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(pagedIterable.iterableByPage(), pageMapper);
}
@Override
public Iterable<PagedResponse<S>> iterableByPage(String continuationToken) {
return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(
pagedIterable.iterableByPage(continuationToken), pageMapper);
}
@Override
public Iterable<PagedResponse<S>> iterableByPage(int preferredPageSize) {
return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(
pagedIterable.iterableByPage(preferredPageSize), pageMapper);
}
@Override
public Iterable<PagedResponse<S>> iterableByPage(String continuationToken, int preferredPageSize) {
return new IterableImpl<PagedResponse<T>, PagedResponse<S>>(
pagedIterable.iterableByPage(continuationToken, preferredPageSize), pageMapper);
}
}
private static final class IteratorImpl<T, S> implements Iterator<S> {
private final Iterator<T> iterator;
private final Function<T, S> mapper;
private IteratorImpl(Iterator<T> iterator, Function<T, S> mapper) {
this.iterator = iterator;
this.mapper = mapper;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public S next() {
return mapper.apply(iterator.next());
}
@Override
public void remove() {
iterator.remove();
}
}
private static final class IterableImpl<T, S> implements Iterable<S> {
private final Iterable<T> iterable;
private final Function<T, S> mapper;
private IterableImpl(Iterable<T> iterable, Function<T, S> mapper) {
this.iterable = iterable;
this.mapper = mapper;
}
@Override
public Iterator<S> iterator() {
return new IteratorImpl<T, S>(iterable.iterator(), mapper);
}
}
}
| {
"content_hash": "4626bbf81befa853c3156e3fdcfe0197",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 116,
"avg_line_length": 37.25,
"alnum_prop": 0.5851006711409396,
"repo_name": "Azure/azure-sdk-for-java",
"id": "a026ee076dddc379d8d29fcdab131543efeb5fc3",
"size": "7607",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/deviceupdate/azure-resourcemanager-deviceupdate/src/main/java/com/azure/resourcemanager/deviceupdate/implementation/Utils.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
<div id="panelContenido" class="row" data-ng-controller="NuestraHistoriaController"
style="">
<div class="col-xs-12 col-sm-offset-1 col-sm-10 col-lg-offset-1 col-lg-10"
style="padding-left: 0;padding-right: 0;height: 100%">
<div class="barraSuperior row">
<div class="logo">
<img ng-src="img/logo-wiltons-express.png" class="img-responsive">
</div>
</div>
<div id="fondo">
<img ng-src="img/fondo-nuestra-historia.jpg"
class="img-responsive imgFondoNormal sample-show-hide visible-md visible-lg"
ng-show="true"
ng-animate="'animate'">
<img ng-src="img/fondo-genericoTablet.jpg"
class="img-responsive imgFondoMovil sample-show-hide hidden-md hidden-lg"
ng-show="true"
ng-animate="'animate'">
<div class="contenido">
<div class="">
<div
class="col-xs-offset-1 col-xs-10 col-md-offset-7 col-md-4">
<section class="text-justify" id="contenidoBody" style="position: relative;">
<h3>
NUESTRA HISTORIA
</h3>
<p>
Desde 1979 somos una empresa dedicada a la panadería y pastelería fina, cuyo objetivo principal es la satisfacción total de nuestros clientes, ofreciendo productos y servicios de alta calidad.
</p>
<p>
Con el transcurrir de los años y la experiencia adquirida estamos convencidos de qye para poder lograr nuestro obejtivo, la estandarización en nuestros procesos de
procucción, la implementación de tecnología de punta, un exhausto control de calidad, y la generación de productos innovadores y creativos, nos han convertido en una buena alternativa para nuestros clientes.
</p>
<p>
Con el transcurrir de los años y la experiencia adquirida estamos convencidos de qye para poder lograr nuestro obejtivo, la estandarización en nuestros procesos de
procucción, la implementación de tecnología de punta, un exhausto control de calidad, y la generación de productos innovadores y creativos, nos han convertido en una buena alternativa para nuestros clientes.
</p>
<p>
Con el transcurrir de los años y la experiencia adquirida estamos convencidos de qye para poder lograr nuestro obejtivo, la estandarización en nuestros procesos de
procucción, la implementación de tecnología de punta, un exhausto control de calidad, y la generación de productos innovadores y creativos, nos han convertido en una buena alternativa para nuestros clientes.
</p>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
<br/>
| {
"content_hash": "d54565bc2bcc288be0cf619f87894c47",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 255,
"avg_line_length": 56.25,
"alnum_prop": 0.5297777777777778,
"repo_name": "BiellconDigital/wiltons-frontend",
"id": "788111c4d1859d2dcc2d16c37fe5fc11bffcc4e8",
"size": "3396",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/views/NuestraHistoria.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "15548"
},
{
"name": "JavaScript",
"bytes": "103802"
},
{
"name": "Perl",
"bytes": "33"
},
{
"name": "Ruby",
"bytes": "503"
},
{
"name": "Shell",
"bytes": "1592"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using SIL.Extensions;
using SIL.PlatformUtilities;
using SIL.Reporting;
namespace SIL.IO
{
public static class PathUtilities
{
// On Unix there are more characters valid in file names, but we
// want the result to be identical on both platforms, so we want
// to use the larger invalid Windows list for both platforms
public static char[] GetInvalidOSIndependentFileNameChars()
{
return new char[]
{
'\0',
'\u0001',
'\u0002',
'\u0003',
'\u0004',
'\u0005',
'\u0006',
'\a',
'\b',
'\t',
'\n',
'\v',
'\f',
'\r',
'\u000e',
'\u000f',
'\u0010',
'\u0011',
'\u0012',
'\u0013',
'\u0014',
'\u0015',
'\u0016',
'\u0017',
'\u0018',
'\u0019',
'\u001a',
'\u001b',
'\u001c',
'\u001d',
'\u001e',
'\u001f',
'"',
'<',
'>',
'|',
':',
'*',
'?',
'\\',
'/'
};
}
// map directory name to its disk device number (not used on Windows)
private static Dictionary<string,int> _deviceNumber = new Dictionary<string, int>();
public static int GetDeviceNumber(string filePath)
{
if (Platform.IsWindows)
{
var driveInfo = new DriveInfo(Path.GetPathRoot(filePath));
return driveInfo.Name.ToUpper()[0] - 'A' + 1;
}
// path can mean a file or a directory. Get the directory
// so that our device number cache can work better. (fewer
// unique directory names than filenames)
var pathToCheck = filePath;
if (File.Exists(pathToCheck))
pathToCheck = Path.GetDirectoryName(pathToCheck);
else if (!Directory.Exists(pathToCheck))
{
// Work up the path until a directory exists.
do
{
pathToCheck = Path.GetDirectoryName(pathToCheck);
}
while (!String.IsNullOrEmpty(pathToCheck) && !Directory.Exists(pathToCheck));
// If the whole path is invalid, give up.
if (String.IsNullOrEmpty(pathToCheck))
return -1;
}
int retval;
// Use cached value if we can to avoid process invocation.
if (_deviceNumber.TryGetValue(pathToCheck, out retval))
return retval;
using (var process = new Process())
{
var statFlags = Platform.IsMac ? "-f" : "-c";
process.StartInfo = new ProcessStartInfo
{
FileName = "stat",
Arguments = string.Format("{0} %d \"{1}\"", statFlags, pathToCheck),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
};
process.Start();
var output = process.StandardOutput.ReadToEnd();
// This process is frequently not exiting even after filling the output string
// with the desired information. So we'll wait a couple of seconds instead of
// waiting forever and just go on. If there's data to process, we'll use it.
// (2 seconds should be more than enough for that simple command to execute.
// "time statc -c %d "/tmp" reports 2ms of real time and 2ms of user time.)
// See https://jira.sil.org/browse/BL-771 for a bug report involving this code
// with a simple process.WaitForExit().
// This feels like a Mono bug of some sort, so feel free to regard this as a
// workaround hack.
process.WaitForExit(2000);
if (!String.IsNullOrWhiteSpace(output))
{
if (Int32.TryParse(output.Trim(), out retval))
{
_deviceNumber.Add(pathToCheck, retval);
return retval;
}
}
return -1;
}
}
public static bool PathsAreOnSameVolume(string firstPath, string secondPath)
{
if (string.IsNullOrEmpty(firstPath) || string.IsNullOrEmpty(secondPath))
return false;
return PathUtilities.GetDeviceNumber(firstPath) == PathUtilities.GetDeviceNumber(secondPath);
}
/// <summary>
/// Possible flags for the SHFileOperation method.
/// </summary>
[CLSCompliant(false)]
[Flags]
public enum FileOperationFlags : ushort
{
/// <summary>
/// Do not show a dialog during the process
/// </summary>
FOF_SILENT = 0x0004,
/// <summary>
/// Do not ask the user to confirm selection
/// </summary>
FOF_NOCONFIRMATION = 0x0010,
/// <summary>
/// Delete the file to the recycle bin. (Required flag to send a file to the bin
/// </summary>
FOF_ALLOWUNDO = 0x0040,
/// <summary>
/// Do not show the names of the files or folders that are being recycled.
/// </summary>
FOF_SIMPLEPROGRESS = 0x0100,
/// <summary>
/// Surpress errors, if any occur during the process.
/// </summary>
FOF_NOERRORUI = 0x0400,
/// <summary>
/// Warn if files are too big to fit in the recycle bin and will need
/// to be deleted completely.
/// </summary>
FOF_WANTNUKEWARNING = 0x4000,
}
/// <summary>
/// File Operation Function Type for SHFileOperation
/// </summary>
[CLSCompliant(false)]
public enum FileOperationType : uint
{
/// <summary>
/// Move the objects
/// </summary>
FO_MOVE = 0x0001,
/// <summary>
/// Copy the objects
/// </summary>
FO_COPY = 0x0002,
/// <summary>
/// Delete (or recycle) the objects
/// </summary>
FO_DELETE = 0x0003,
/// <summary>
/// Rename the object(s)
/// </summary>
FO_RENAME = 0x0004,
}
/// <summary>
/// SHFILEOPSTRUCT for SHFileOperation from COM
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
private struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
[MarshalAs(UnmanagedType.U4)] public FileOperationType wFunc;
public string pFrom;
public string pTo;
public FileOperationFlags fFlags;
[MarshalAs(UnmanagedType.Bool)] public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
public string lpszProgressTitle;
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);
private static void WriteTrashInfoFile(string trashPath, string filePath, string trashedFile)
{
var trashInfo = Path.Combine(trashPath, "info", trashedFile + ".trashinfo");
var lines = new List<string>();
lines.Add("[Trash Info]");
lines.Add(string.Format("Path={0}", filePath));
lines.Add(string.Format("DeletionDate={0}",
DateTime.Now.ToString("yyyyMMddTHH:mm:ss", CultureInfo.InvariantCulture)));
File.WriteAllLines(trashInfo, lines);
}
/// <summary>
/// Delete a file or directory by moving it to the trash bin
/// Display dialog, display warning if files are too big to fit (FOF_WANTNUKEWARNING)
/// </summary>
/// <remarks>See: http://stackoverflow.com/questions/3282418/send-a-file-to-the-recycle-bin</remarks>
/// <param name="filePath">Full path of the file.</param>
/// <returns><c>true</c> if successfully deleted.</returns>
public static bool DeleteToRecycleBin(string filePath)
{
return DeleteToRecycleBin(filePath, FileOperationFlags.FOF_NOCONFIRMATION | FileOperationFlags.FOF_WANTNUKEWARNING);
}
/// <summary>
/// Delete a file or directory by moving it to the trash bin
/// </summary>
/// <param name="filePath">Full path of the file.</param>
/// <param name="flags">options flags from FileOperationFlags</param>
/// <returns><c>true</c> if successfully deleted.</returns>
[CLSCompliant(false)]
public static bool DeleteToRecycleBin(string filePath, FileOperationFlags flags)
{
if (Platform.IsWindows)
{
if (!File.Exists(filePath) && !Directory.Exists(filePath))
return false;
// alternative using visual basic dll:
// FileSystem.DeleteDirectory(item.FolderPath,UIOption.OnlyErrorDialogs), RecycleOption.SendToRecycleBin);
//moves it to the recyle bin
try
{
var shf = new SHFILEOPSTRUCT
{
wFunc = FileOperationType.FO_DELETE,
pFrom = filePath + '\0' + '\0',
fFlags = FileOperationFlags.FOF_ALLOWUNDO | flags
};
SHFileOperation(ref shf);
return !shf.fAnyOperationsAborted;
}
catch (Exception)
{
return false;
}
}
// On Linux we'll have to move the file to $XDG_DATA_HOME/Trash/files and create
// a filename.trashinfo file in $XDG_DATA_HOME/Trash/info that contains the original
// filepath and the deletion date. See http://stackoverflow.com/a/20255190
// and http://freedesktop.org/wiki/Specifications/trash-spec/.
// Environment.SpecialFolder.LocalApplicationData corresponds to $XDG_DATA_HOME.
// move file or directory
if (Directory.Exists(filePath) || File.Exists(filePath))
{
var trashPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData), "Trash");
var trashedFileName = Path.GetRandomFileName();
if (!Directory.Exists(trashPath))
{
// in case the trash bin doesn't exist we create it. This can happen e.g.
// on the build machine
Directory.CreateDirectory(Path.Combine(trashPath, "files"));
Directory.CreateDirectory(Path.Combine(trashPath, "info"));
}
var recyclePath = Path.Combine(Path.Combine(trashPath, "files"), trashedFileName);
WriteTrashInfoFile(trashPath, filePath, trashedFileName);
// Directory.Move works for directories and files
DirectoryUtilities.MoveDirectorySafely(filePath, recyclePath);
return true;
}
return false;
}
[DllImport("shell32.dll", ExactSpelling = true)]
public static extern void ILFree(IntPtr pidlList);
[DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
public static extern IntPtr ILCreateFromPathW(string pszPath);
[DllImport("shell32.dll", ExactSpelling = true)]
[CLSCompliant(false)]
public static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
public static void SelectItemInExplorerEx(string path)
{
var pidlList = ILCreateFromPathW(path);
if(pidlList == IntPtr.Zero)
throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path));
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
/// <summary>
/// On Windows this selects the file or directory in Windows Explorer; on Linux it selects the file
/// in the default file manager if that supports selecting a file and we know it,
/// otherwise we fall back to xdg-open and open the directory that contains that file.
/// </summary>
/// <param name="path">File or directory path.</param>
public static void SelectFileInExplorer(string path)
{
if (Platform.IsWindows)
{
//we need to use this becuase of a bug in windows that strips composed characters before trying to find the target path (http://stackoverflow.com/a/30405340/723299)
var pidlList = ILCreateFromPathW(path);
if(pidlList == IntPtr.Zero)
throw new Exception(string.Format("ILCreateFromPathW({0}) failed", path));
try
{
Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
}
finally
{
ILFree(pidlList);
}
}
else
{
var fileManager = DefaultFileManager;
string arguments;
switch (fileManager)
{
case "nautilus":
case "nemo":
arguments = string.Format("\"{0}\"", path);
break;
default:
fileManager = "xdg-open";
arguments = string.Format("\"{0}\"", Path.GetDirectoryName(path));
break;
}
Process.Start(fileManager, arguments);
}
}
/// <summary>
/// Opens the specified directory in the default file manager
/// </summary>
/// <param name="directory">Full path of the directory</param>
public static void OpenDirectoryInExplorer(string directory)
{
//Enhance: on Windows, use ShellExecuteExW instead, as it will probably be able to
//handle languages with combining characters (diactrics), whereas this explorer
//approach will fail (at least as of windows 8.1)
var fileManager = DefaultFileManager;
var arguments = "\"{0}\"";
// the value returned by GetDefaultFileManager() may include arguments
var firstSpace = fileManager.IndexOf(' ');
if (firstSpace > -1)
{
arguments = fileManager.Substring(firstSpace + 1) + " " + arguments;
fileManager = fileManager.Substring(0, firstSpace);
}
arguments = string.Format(arguments, directory);
Process.Start(new ProcessStartInfo()
{
FileName = fileManager,
Arguments = arguments,
UseShellExecute = false
});
}
/// <summary>
/// Opens the file in the application associated with the file type.
/// </summary>
/// <param name="filePath">Full path to the file</param>
public static void OpenFileInApplication(string filePath)
{
Process.Start(filePath);
}
private static string GetDefaultFileManager()
{
if (PlatformUtilities.Platform.IsWindows)
return "explorer.exe";
const string fallbackFileManager = "xdg-open";
using (var xdgmime = new Process())
{
bool processError = false;
xdgmime.RunProcess("xdg-mime", "query default inode/directory", exception => {
processError = true;
});
if (processError)
{
Logger.WriteMinorEvent("Error executing 'xdg-mime query default inode/directory'");
return fallbackFileManager;
}
string desktopFile = xdgmime.StandardOutput.ReadToEnd().TrimEnd(' ', '\n', '\r');
xdgmime.WaitForExit();
if (string.IsNullOrEmpty(desktopFile))
{
Logger.WriteMinorEvent("Didn't find default value for mime type inode/directory");
return fallbackFileManager;
}
// Look in /usr/share/applications for .desktop file
var desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"applications", desktopFile);
if (!File.Exists(desktopFilename))
{
// We didn't find the .desktop file yet, so check in ~/.local/share/applications
desktopFilename = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"applications", desktopFile);
}
if (!File.Exists(desktopFilename))
{
Logger.WriteMinorEvent("Can't find desktop file for {0}", desktopFile);
return fallbackFileManager;
}
using (var reader = File.OpenText(desktopFilename))
{
string line;
for (line = reader.ReadLine();
!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase) && !reader.EndOfStream;
line = reader.ReadLine())
{
}
if (!line.StartsWith("Exec=", StringComparison.InvariantCultureIgnoreCase))
{
Logger.WriteMinorEvent("Can't find Exec line in {0}", desktopFile);
_defaultFileManager = string.Empty;
return _defaultFileManager;
}
var start = "Exec=".Length;
var argStart = line.IndexOf('%');
var cmdLine = argStart > 0 ? line.Substring(start, argStart - start) : line.Substring(start);
cmdLine = cmdLine.TrimEnd();
Logger.WriteMinorEvent("Detected default file manager as {0}", cmdLine);
return cmdLine;
}
}
}
private static string _defaultFileManager;
private static string DefaultFileManager
{
get
{
if (_defaultFileManager == null)
_defaultFileManager = GetDefaultFileManager();
return _defaultFileManager;
}
}
public static bool PathContainsDirectory(string path, string directory)
{
if (string.IsNullOrEmpty(directory))
return false;
if (path.Contains(directory))
{
while (!string.IsNullOrEmpty(path))
{
var subdir = Path.GetFileName(path);
if (subdir == directory)
return true;
path = Path.GetDirectoryName(path);
}
}
return false;
}
}
}
| {
"content_hash": "1cc5c2ee9157a9751f2cf8f1c7e2cff6",
"timestamp": "",
"source": "github",
"line_count": 527,
"max_line_length": 168,
"avg_line_length": 29.79127134724858,
"alnum_prop": 0.6686624203821656,
"repo_name": "glasseyes/libpalaso",
"id": "12d1185d626a564b727c680b0c750c9d03c2c43c",
"size": "15828",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "SIL.Core/IO/PathUtilities.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "6637"
},
{
"name": "C#",
"bytes": "6789164"
},
{
"name": "HTML",
"bytes": "46279"
},
{
"name": "Makefile",
"bytes": "529"
},
{
"name": "Python",
"bytes": "7859"
},
{
"name": "Shell",
"bytes": "12234"
},
{
"name": "XSLT",
"bytes": "22208"
}
],
"symlink_target": ""
} |
/**
* This class is generated by jOOQ
*/
package de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DefeatStrength extends org.jooq.impl.AbstractRoutine<java.lang.Long> {
private static final long serialVersionUID = -1515614871;
/**
* The parameter <code>defeat_strength.RETURN_VALUE</code>.
*/
public static final org.jooq.Parameter<java.lang.Long> RETURN_VALUE = createParameter("RETURN_VALUE", org.jooq.impl.SQLDataType.BIGINT);
/**
* The parameter <code>defeat_strength.positive_votes_p</code>.
*/
public static final org.jooq.Parameter<java.lang.Integer> POSITIVE_VOTES_P = createParameter("positive_votes_p", org.jooq.impl.SQLDataType.INTEGER);
/**
* The parameter <code>defeat_strength.negative_votes_p</code>.
*/
public static final org.jooq.Parameter<java.lang.Integer> NEGATIVE_VOTES_P = createParameter("negative_votes_p", org.jooq.impl.SQLDataType.INTEGER);
/**
* The parameter <code>defeat_strength.defeat_strength_p</code>.
*/
public static final org.jooq.Parameter<de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DefeatStrength> DEFEAT_STRENGTH_P = createParameter("defeat_strength_p", org.jooq.util.postgres.PostgresDataType.VARCHAR.asEnumDataType(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DefeatStrength.class));
/**
* Create a new routine call instance
*/
public DefeatStrength() {
super("defeat_strength", de.piratenpartei.berlin.ldadmin.dbaccess.generated.DefaultSchema.DEFAULT_SCHEMA, org.jooq.impl.SQLDataType.BIGINT);
setReturnParameter(RETURN_VALUE);
addInParameter(POSITIVE_VOTES_P);
addInParameter(NEGATIVE_VOTES_P);
addInParameter(DEFEAT_STRENGTH_P);
}
/**
* Set the <code>positive_votes_p</code> parameter IN value to the routine
*/
public void setPositiveVotesP(java.lang.Integer value) {
setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DefeatStrength.POSITIVE_VOTES_P, value);
}
/**
* Set the <code>positive_votes_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setPositiveVotesP(org.jooq.Field<java.lang.Integer> field) {
setField(POSITIVE_VOTES_P, field);
}
/**
* Set the <code>negative_votes_p</code> parameter IN value to the routine
*/
public void setNegativeVotesP(java.lang.Integer value) {
setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DefeatStrength.NEGATIVE_VOTES_P, value);
}
/**
* Set the <code>negative_votes_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setNegativeVotesP(org.jooq.Field<java.lang.Integer> field) {
setField(NEGATIVE_VOTES_P, field);
}
/**
* Set the <code>defeat_strength_p</code> parameter IN value to the routine
*/
public void setDefeatStrengthP(de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DefeatStrength value) {
setValue(de.piratenpartei.berlin.ldadmin.dbaccess.generated.routines.DefeatStrength.DEFEAT_STRENGTH_P, value);
}
/**
* Set the <code>defeat_strength_p</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/
public void setDefeatStrengthP(org.jooq.Field<de.piratenpartei.berlin.ldadmin.dbaccess.generated.enums.DefeatStrength> field) {
setField(DEFEAT_STRENGTH_P, field);
}
}
| {
"content_hash": "af46561224e8e8b00a8150a40d34b946",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 313,
"avg_line_length": 40.07865168539326,
"alnum_prop": 0.7462853938884216,
"repo_name": "SMVBE/ldadmin",
"id": "cba6932278492548af2caf8737739d3983dda48e",
"size": "3567",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/routines/DefeatStrength.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2192262"
}
],
"symlink_target": ""
} |
namespace SuperHaxagon {
const int BUFFER_MS = 200;
LightEvent AudioPlayerOgg3DS::_event{};
AudioPlayerOgg3DS::AudioPlayerOgg3DS(const std::string& path) {
_loaded = false;
auto error = 0;
_oggFile = stb_vorbis_open_filename(path.c_str(), &error, nullptr);
if(error || !(_oggFile->channels == 1 || _oggFile->channels == 2)) return;
const auto bufferSize = getWaveBuffSize(_oggFile->sample_rate, _oggFile->channels) * _waveBuffs.size();
_audioBuffer = static_cast<int16_t*>(linearAlloc(bufferSize));
if(!_audioBuffer) {
stb_vorbis_close(_oggFile);
return;
}
memset(&_waveBuffs, 0, _waveBuffs.size());
auto* buffer = _audioBuffer;
for(auto& waveBuff : _waveBuffs) {
waveBuff.data_vaddr = buffer;
waveBuff.status = NDSP_WBUF_DONE;
buffer += getWaveBuffSize(_oggFile->sample_rate, _oggFile->channels) / sizeof(buffer[0]);
}
_loaded = true;
}
AudioPlayerOgg3DS::~AudioPlayerOgg3DS() {
if (!_loaded) return;
_quit = true;
if (_thread) {
LightEvent_Signal(&_event);
threadJoin(_thread, 100000000);
threadFree(_thread);
}
ndspChnWaveBufClear(_channel);
ndspChnReset(_channel);
linearFree(_audioBuffer);
stb_vorbis_close(_oggFile);
}
void AudioPlayerOgg3DS::setChannel(const int channel) {
_channel = channel;
}
void AudioPlayerOgg3DS::setLoop(const bool loop) {
_loop = loop;
}
void AudioPlayerOgg3DS::play() {
if (!_loaded) return;
if (_thread) {
if (_diff) _start += svcGetSystemTick() - _diff;
ndspChnSetPaused(_channel, false);
LightEvent_Signal(&_event);
_diff = 0;
return;
}
ndspChnReset(_channel);
ndspChnSetInterp(_channel, NDSP_INTERP_POLYPHASE);
ndspChnSetRate(_channel, static_cast<float>(_oggFile->sample_rate));
ndspChnSetFormat(_channel, _oggFile->channels == 1 ? NDSP_FORMAT_MONO_PCM16 : NDSP_FORMAT_STEREO_PCM16);
int32_t priority = 0x30;
svcGetThreadPriority(&priority, CUR_THREAD_HANDLE);
priority += 1; // Set LOWER priority and clamp
priority = priority < 0x18 ? 0x18 : priority;
priority = priority > 0x3F ? 0x3F : priority;
// Start the thread, passing the player as an argument.
_thread = threadCreate(audioThread, this, THREAD_STACK_SZ, priority, THREAD_AFFINITY, false);
_start = svcGetSystemTick();
}
void AudioPlayerOgg3DS::pause() {
ndspChnSetPaused(_channel, true);
_diff = svcGetSystemTick();
}
bool AudioPlayerOgg3DS::isDone() const {
return !_quit;
}
float AudioPlayerOgg3DS::getTime() const {
if (!_loaded) return 0;
// If we set diff (paused), we are frozen in time. Otherwise, the current timestamp is
// the system minus the start of the song.
const auto ticks = _diff ? _diff - _start : svcGetSystemTick() - _start;
const auto timeMs = static_cast<float>(ticks) / static_cast<float>(CPU_TICKS_PER_MSEC);
return timeMs / 1000.0f;
}
bool AudioPlayerOgg3DS::audioDecode(stb_vorbis* file, ndspWaveBuf* buff, const int channel) {
long totalSamples = 0;
while (totalSamples < static_cast<long>(getSamplesPerBuff(file->sample_rate))) {
auto* const buffer = buff->data_pcm16 + (totalSamples * file->channels);
const size_t bufferSize = (getSamplesPerBuff(file->sample_rate) - totalSamples) * file->channels;
const auto samples = stb_vorbis_get_samples_short_interleaved(file, file->channels, buffer, bufferSize);
if (samples <= 0) break;
totalSamples += samples;
}
if (totalSamples == 0) return false;
buff->nsamples = totalSamples;
ndspChnWaveBufAdd(channel, buff);
DSP_FlushDataCache(buff->data_pcm16, totalSamples * file->channels * sizeof(int16_t));
return true;
}
void AudioPlayerOgg3DS::audioCallback(void*) {
LightEvent_Signal(&_event);
}
void AudioPlayerOgg3DS::audioThread(void* const self) {
auto* pointer = static_cast<AudioPlayerOgg3DS*>(self);
if (!pointer) return;
while(!pointer->_quit) {
for (auto& waveBuff : pointer->_waveBuffs) {
if (waveBuff.status != NDSP_WBUF_DONE) continue;
if (!audioDecode(pointer->_oggFile, &waveBuff, pointer->_channel)) {
if (!pointer->_loop) {
pointer->_quit = true;
return;
}
// We are looping, so go back to the beginning
stb_vorbis_seek_start(pointer->_oggFile);
pointer->_start = svcGetSystemTick();
}
}
if (pointer->_quit) return;
LightEvent_Wait(&_event);
}
}
unsigned int AudioPlayerOgg3DS::getSamplesPerBuff(const unsigned int sampleRate) {
return sampleRate * BUFFER_MS / 1000;
}
unsigned int AudioPlayerOgg3DS::getWaveBuffSize(const unsigned int sampleRate, const int channels) {
return getSamplesPerBuff(sampleRate) * channels * sizeof(int16_t);
}
} | {
"content_hash": "f67454bed46a6dcad1dafbc7164e8ab3",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 107,
"avg_line_length": 29.11320754716981,
"alnum_prop": 0.6889176928062216,
"repo_name": "RedInquisitive/Super-Haxagon",
"id": "6f7e1a8e760f722167561f09ed658dbe30436471",
"size": "4699",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/Driver/3DS/AudioPlayerOgg3DS.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "65409"
},
{
"name": "C++",
"bytes": "856"
},
{
"name": "Makefile",
"bytes": "1332"
}
],
"symlink_target": ""
} |
package com.elfec.cobranza.model;
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.elfec.cobranza.business_logic.SupplyStatusSet;
import org.joda.time.DateTime;
import java.math.BigDecimal;
import java.util.List;
/**
* Almacena los CBTES_COOP
* @author drodriguez
*
*/
@Table(name = "CoopReceipts")
public class CoopReceipt extends Model {
/**
* IDCBTE Identificador unico de comprobantes
*/
@Column(name = "ReceiptId", notNull=true, index=true)
private int receiptId;
/**
* IDSUMINISTRO
* Identificador del suministros, tabla de referencia suministros
*/
@Column(name = "SupplyId")
private int supplyId;
/**
* IDCLIENTE en Oracle
*/
@Column(name = "ClientId")
private int clientId;
/**
* IDEMPRESA en Oracle
*/
@Column(name = "EnterpriseId")
private int enterpriseId;
/**
* IDSUCURSAL en Oracle
*/
@Column(name = "BranchOfficeId")
private int branchOfficeId;
/**
* TIPO_CBTE en Oracle
*/
@Column(name = "ReceiptType")
private String receiptType;
/**
* GRUPO_CBTE en Oracle
*/
@Column(name = "ReceiptGroup")
private int receiptGroup;
/**
* LETRA_CBTE en Oracle
*/
@Column(name = "ReceiptLetter")
private String receiptLetter;
/**
* NROCBTE en Oracle
*/
@Column(name = "ReceiptNumber")
private int receiptNumber;
/**
* FECHA_EMISION en Oracle
*/
@Column(name = "IssueDate")
private DateTime issueDate;
/**
* FECHA_VTO_ORIGINAL en Oracle
*/
@Column(name = "OrigExpirationDate")
private DateTime origExpirationDate;
/**
* FECHA_VTO en Oracle
*/
@Column(name = "ExpirationDate")
private DateTime expirationDate;
/**
* FECHA_INICIO en Oracle
*/
@Column(name = "StartDate")
private DateTime startDate;
/**
* FECHA_FIN en Oracle
*/
@Column(name = "EndDate")
private DateTime endDate;
/**
* ANIO en Oracle
*/
@Column(name = "Year")
private int year;
/**
* NROPER en Oracle
*/
@Column(name = "PeriodNumber")
private int periodNumber;
/**
* NROSUM en Oracle
*/
@Column(name = "SupplyNumber")
private String supplyNumber;
/**
* IDRUTA en Oracle
*/
@Column(name = "RouteId", index=true)
private int routeId;
/**
* NOMBRE en Oracle
*/
@Column(name = "Name")
private String name;
/**
* IDIVA en Oracle
*/
@Column(name = "IVAId")
private int IVAId;
/**
* CUIT en Oracle
*/
@Column(name = "NIT")
private String NIT;
/**
* DOMICILIO_SUM en Oracle
*/
@Column(name = "SupplyAddress")
private String supplyAddress;
/**
* IDCATEGORIA en Oracle
*/
@Column(name = "CategoryId")
private String categoryId;
/**
* SRV_IMPORTE en Oracle
*/
@Column(name = "ServiceAmount")
private BigDecimal serviceAmount;
/**
* SRV_SALDO en Oracle
*/
@Column(name = "ServiceBalance")
private BigDecimal serviceBalance;
/**
* TOTALIMP en Oracle
*/
@Column(name = "TotalAmount")
private BigDecimal totalAmount;
/**
* ESTADO en Oracle
*/
@Column(name = "Status")
private String status;
/**
* IDLOTE
* Identificador del lote, tabla de referencia fac_lotes
*/
@Column(name = "BatchId")
private int batchId;
/**
* NRO_AUT_IMPRESION
*/
@Column(name = "AuthorizationNumber")
private String authorizationNumber;
/**
* FECHA_VTO_AUT
*/
@Column(name = "AuthExpirationDate")
private DateTime authExpirationDate;
/**
* COD_CONTROL
*/
@Column(name = "ControlCode")
private String controlCode;
//ATRIBUTOS OBTENIDOS CON FUNCIONES
/**
* COBRANZA.FLITERAL(TOTALIMP) LITERAL en Oracle
*/
@Column(name = "Literal")
private String literal;
/**
* DIRECCION sacada de funcion MOVILES.FCOBRA_OBTENER_DIRECCION(IDSUMINISTRO)
*/
@Column(name = "ClientAddress")
private String clientAddress;
/**
* MEDIDOR sacada de funcion MOVILES.FCOBRA_OBTENER_MEDIDOR(IDCBTE)
*/
@Column(name = "MeterNumber")
private String meterNumber;
/**
* DESC_AUT_IMPRESION sacada de funcion MOVILES.FCOBRA_OBTENER_DESC_AUT(NRO_AUT_IMPRESION)
*/
@Column(name = "AuthorizationDescription")
private String authorizationDescription;
//EXTRA ATTRIBUTES
private SupplyStatusSet supplyStatusSet;
/**
* Sirve de caché de la consulta, debe actualizarse al realizar una anulación
*/
private CollectionPayment collectionPayment;
public CoopReceipt() {
super();
}
public CoopReceipt(int receiptId, int supplyId, int clientId,
int enterpriseId, int branchOfficeId, String receiptType,
int receiptGroup, String receiptLetter, int receiptNumber,
DateTime issueDate, DateTime origExpirationDate,
DateTime expirationDate, DateTime startDate, DateTime endDate,
int year, int periodNumber, String supplyNumber, int routeId,
String name, int iVAId, String nIT, String supplyAddress,
String categoryId, BigDecimal serviceAmount,
BigDecimal serviceBalance, BigDecimal totalAmount, String status,
int batchId, String authorizationNumber,
DateTime authExpirationDate, String controlCode) {
super();
this.receiptId = receiptId;
this.supplyId = supplyId;
this.clientId = clientId;
this.enterpriseId = enterpriseId;
this.branchOfficeId = branchOfficeId;
this.receiptType = receiptType;
this.receiptGroup = receiptGroup;
this.receiptLetter = receiptLetter;
this.receiptNumber = receiptNumber;
this.issueDate = issueDate;
this.origExpirationDate = origExpirationDate;
this.expirationDate = expirationDate;
this.startDate = startDate;
this.endDate = endDate;
this.year = year;
this.periodNumber = periodNumber;
this.supplyNumber = supplyNumber;
this.routeId = routeId;
this.name = name;
IVAId = iVAId;
NIT = nIT;
this.supplyAddress = supplyAddress;
this.categoryId = categoryId;
this.serviceAmount = serviceAmount;
this.serviceBalance = serviceBalance;
this.totalAmount = totalAmount;
this.status = status;
this.batchId = batchId;
this.authorizationNumber = authorizationNumber;
this.authExpirationDate = authExpirationDate;
this.controlCode = controlCode;
}
/**
* Encuentra todas las facturas de la ruta indicada
* @param routeId
* @return
*/
public static List<CoopReceipt> findRouteReceipts(int routeId)
{
return new Select().from(CoopReceipt.class).where("RouteId=?",routeId).execute();
}
/**
* Obtiene la lista de SUMIN_ESTADOS (De consumo energia activa) de este comprobante
* @return supplyStatus
*/
public SupplyStatusSet getSupplyStatusSet()
{
if(supplyStatusSet==null)
supplyStatusSet = new SupplyStatusSet(getRelatedSupplyStatus());
return supplyStatusSet;
}
/**
* Obtiene los SUMIN_ESTADOS de energia activa relacionados al comprobante
* @return lista SUMIN_ESTADOS
*/
public List<SupplyStatus> getRelatedSupplyStatus()
{
return new Select().from(SupplyStatus.class)
.where("ReceiptId = ?", this.receiptId)
.where("ConceptId IN (10010, 10080, 10090, 10100)").execute();
}
/**
* Obtiene el SUMIN_ESTADOS (De consumo de potencia) de este comprobante
* @return supplyStatus
*/
public SupplyStatus getPowerSupplyStatus()
{
return new Select().from(SupplyStatus.class)
.where("ReceiptId = ?", this.receiptId)
.where("ConceptId IN (10020, 10140)").executeSingle();
}
/**
* Obtiene su cobro (CollectionPayment) en caso de tener uno, y que tenga el estado en 1
* @return
*/
public CollectionPayment getActiveCollectionPayment()
{
if(collectionPayment==null)
collectionPayment = new Select().from(CollectionPayment.class)
.where("Status=1")
.where("ReceiptId = ? ", receiptId)
.where("SupplyId = ?", supplyId)
.orderBy("PaymentDate DESC")
.executeSingle();
return collectionPayment;
}
/**
* Limpia la variable que sirve de caché para la consulta de obtención del cobro actual activo (estado 1)
*/
public void clearActiveCollectionPayment()
{
collectionPayment = null;
}
/**
* Elimina todas las facturas que pertenecen a la lista de rutas provista
* @param routesString lista de rutas en forma de clausula IN
*/
public static void cleanRoutesCoopReceipts(String routesString)
{
new Delete().from(CoopReceipt.class).where("RouteId IN "+routesString).execute();
}
//#region Getters y Setters
public int getReceiptId() {
return receiptId;
}
public void setReceiptId(int receiptId) {
this.receiptId = receiptId;
}
public int getSupplyId() {
return supplyId;
}
public void setSupplyId(int supplyId) {
this.supplyId = supplyId;
}
public int getClientId() {
return clientId;
}
public void setClientId(int clientId) {
this.clientId = clientId;
}
public int getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(int enterpriseId) {
this.enterpriseId = enterpriseId;
}
public int getBranchOfficeId() {
return branchOfficeId;
}
public void setBranchOfficeId(int branchOfficeId) {
this.branchOfficeId = branchOfficeId;
}
public String getReceiptType() {
return receiptType;
}
public void setReceiptType(String receiptType) {
this.receiptType = receiptType;
}
public int getReceiptGroup() {
return receiptGroup;
}
public void setReceiptGroup(int receiptGroup) {
this.receiptGroup = receiptGroup;
}
public String getReceiptLetter() {
return receiptLetter;
}
public void setReceiptLetter(String receiptLetter) {
this.receiptLetter = receiptLetter;
}
public int getReceiptNumber() {
return receiptNumber;
}
public void setReceiptNumber(int receiptNumber) {
this.receiptNumber = receiptNumber;
}
public DateTime getIssueDate() {
return issueDate;
}
public void setIssueDate(DateTime issueDate) {
this.issueDate = issueDate;
}
public DateTime getOrigExpirationDate() {
return origExpirationDate;
}
public void setOrigExpirationDate(DateTime origExpirationDate) {
this.origExpirationDate = origExpirationDate;
}
public DateTime getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(DateTime expirationDate) {
this.expirationDate = expirationDate;
}
public DateTime getStartDate() {
return startDate;
}
public void setStartDate(DateTime startDate) {
this.startDate = startDate;
}
public DateTime getEndDate() {
return endDate;
}
public void setEndDate(DateTime endDate) {
this.endDate = endDate;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getPeriodNumber() {
return periodNumber;
}
public void setPeriodNumber(int periodNumber) {
this.periodNumber = periodNumber;
}
public String getSupplyNumber() {
return supplyNumber;
}
public void setSupplyNumber(String supplyNumber) {
this.supplyNumber = supplyNumber;
}
public int getRouteId() {
return routeId;
}
public void setRouteId(int routeId) {
this.routeId = routeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIVAId() {
return IVAId;
}
public void setIVAId(int iVAId) {
IVAId = iVAId;
}
public String getNIT() {
return NIT;
}
public void setNIT(String nIT) {
NIT = nIT;
}
public String getSupplyAddress() {
return supplyAddress;
}
public void setSupplyAddress(String supplyAddress) {
this.supplyAddress = supplyAddress;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public BigDecimal getServiceAmount() {
return serviceAmount;
}
public void setServiceAmount(BigDecimal serviceAmount) {
this.serviceAmount = serviceAmount;
}
public BigDecimal getServiceBalance() {
return serviceBalance;
}
public void setServiceBalance(BigDecimal serviceBalance) {
this.serviceBalance = serviceBalance;
}
public BigDecimal getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getBatchId() {
return batchId;
}
public void setBatchId(int batchId) {
this.batchId = batchId;
}
public String getAuthorizationNumber() {
return authorizationNumber;
}
public void setAuthorizationNumber(String authorizationNumber) {
this.authorizationNumber = authorizationNumber;
}
public DateTime getAuthExpirationDate() {
return authExpirationDate;
}
public void setAuthExpirationDate(DateTime authExpirationDate) {
this.authExpirationDate = authExpirationDate;
}
public String getControlCode() {
return controlCode;
}
public void setControlCode(String controlCode) {
this.controlCode = controlCode;
}
public String getLiteral() {
return literal;
}
public void setLiteral(String literal) {
this.literal = literal;
}
public String getClientAddress() {
return clientAddress;
}
public void setClientAddress(String clientAddress) {
this.clientAddress = clientAddress;
}
public String getMeterNumber() {
return meterNumber;
}
public void setMeterNumber(String meterNumber) {
this.meterNumber = meterNumber;
}
public String getAuthorizationDescription() {
return authorizationDescription;
}
public void setAuthorizationDescription(String authorizationDescription) {
this.authorizationDescription = authorizationDescription;
}
//#endregion
}
| {
"content_hash": "1b7779be75f55baeff0f177fb0a115b8",
"timestamp": "",
"source": "github",
"line_count": 548,
"max_line_length": 107,
"avg_line_length": 24.348540145985403,
"alnum_prop": 0.724349846361388,
"repo_name": "diegoRodriguezAguila/Cobranza.Elfec.Mobile",
"id": "8d16c640a61dcaad8803eff291975120c7c85bb1",
"size": "13347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cobranzaElfecMobile/src/main/java/com/elfec/cobranza/model/CoopReceipt.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "612968"
}
],
"symlink_target": ""
} |
using Academy.Models.Abstractions;
using Academy.Models.Contracts;
using Academy.Models.Enums;
using Academy.Models.Utils.Contracts;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Academy.Models
{
public class Student : User, IStudent
{
public Student(string username, Track track) : base(username)
{
this.Track = track;
this.CourseResults = new List<ICourseResult>();
}
public Track Track { get; set; }
public IList<ICourseResult> CourseResults { get; set; }
public override string ToString()
{
var builder = new StringBuilder();
builder.AppendLine($"* Student:");
builder.AppendLine($" - Username: {this.Username}");
builder.AppendLine($" - Track: {this.Track}");
builder.AppendLine($" - Course results:");
if (this.CourseResults.Any())
{
foreach (var result in this.CourseResults)
{
builder.AppendLine(result.ToString());
}
}
else
{
builder.AppendLine(" * User has no course results!");
}
return builder.ToString().TrimEnd();
}
}
}
| {
"content_hash": "2a619ab0df19f4f55e1ee5d02ceb2a26",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 70,
"avg_line_length": 29.652173913043477,
"alnum_prop": 0.5300586510263929,
"repo_name": "TelerikAcademy/Unit-Testing",
"id": "e55829eba2a3aaedd71aaed2ef3b4b1c67b03ea0",
"size": "1366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Topics/04. Workshops/Workshop (Trainers)/Academy/Workshop/Academy/Models/Student.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "515282"
},
{
"name": "HTML",
"bytes": "14045"
}
],
"symlink_target": ""
} |
/* © Utrecht University and DialogueTrainer */
/* exported Load3 */
let Load3;
(function()
{
"use strict";
// eslint-disable-next-line no-global-assign
Load3 =
{
generateGraph: generateGraph,
loadMetadata: loadMetadata,
loadStatement: loadStatement,
loadConversation: loadConversation,
expandConversations: expandConversations
};
// Generates the entire graph, including the objects.
function generateGraph(xml)
{
// Conversations stores all the accumulated conversations so we can expand them and give the nodes fresh ids at the end
const conversations = {};
$(xml).find('interleave').each(function()
{
$(this).children('tree').each(function()
{
const connections = {};
let treeID = this.getAttribute('id').replace(/\./g, '_');
const idMatch = treeID.match(/^tree(\d+)$/);
if (idMatch)
{
const treeNumber = parseInt(idMatch[1]);
Main.maxTreeNumber = Math.max(treeNumber + 1, Main.maxTreeNumber);
treeID = "dialogue" + treeNumber;
}
else
{
treeID = "ext_" + treeID;
}
// Get the position from the XML, note that this is in grid coordinates, not screen coordinates
const position = $(this).children('position')[0];
const leftPos = Math.round(Utils.parseDecimalIntWithDefault($(position).children('x')[0].textContent, 0));
const topPos = Math.round(Utils.parseDecimalIntWithDefault($(position).children('y')[0].textContent, 0));
const tree = Main.createEmptyTree(treeID, leftPos, topPos);
const plumbInstance = tree.plumbInstance;
tree.subject = Utils.unEscapeHTML($(this).children('subject')[0].textContent);
tree.optional = Utils.parseBool($(this).attr('optional'));
const iconDiv = tree.dragDiv.find('.icons');
if (tree.optional) iconDiv.html(Utils.sIcon('icon-tree-is-optional'));
$(tree.dragDiv).toggleClass('optional', tree.optional);
tree.dragDiv.find('.subjectName').text(tree.subject); // Set subject in HTML
tree.dragDiv.find('.subjectNameInput').val(tree.subject); // Set subject in HTML
plumbInstance.batch(function()
{
$(this).children().each(function()
{ // Parse the tree in the container
switch (this.nodeName)
{
case "computerStatement":
loadStatement(this, Main.computerType, connections, treeID);
break;
case "playerStatement":
loadStatement(this, Main.playerType, connections, treeID);
break;
case "conversation":
loadConversation(this, conversations, treeID);
break;
}
});
// Makes the connections between the nodes.
$.each(connections, function(sourceId, targets)
{
for (let i = 0; i < targets.length; i++)
{
plumbInstance.connect(
{
source: sourceId,
target: targets[i]
});
}
});
}.bind(this), true);
});
});
expandConversations(conversations);
}
// Load the metadata of the scenario.
function loadMetadata(metadata)
{
Metadata.container.name = Utils.unEscapeHTML($(metadata).find('name').text());
$('#scenarioNameTab .scenarioName').text(Metadata.container.name);
Main.updateDocumentTitle();
Metadata.container.description = Utils.unEscapeHTML($(metadata).find('description').text());
Metadata.container.difficulty = $(metadata).find('difficulty').text();
const parameters = Parameters.container;
$(metadata).find('parameters').children().each(function()
{
const paramId = this.attributes.id.value;
const paramMatch = paramId.match(/^p(\d+)$/);
if (paramMatch !== null)
{
const paramNumber = parseInt(paramMatch[1]);
if (paramNumber > Parameters.counter) Parameters.counter = paramNumber;
}
const defaultValue = this.hasAttribute('initialValue') ? Utils.parseDecimalIntWithDefault(this.attributes.initialValue.value, 0) : 0;
let minimum, maximum;
if (this.hasAttribute('minimumScore')) minimum = parseInt(this.getAttribute('minimumScore'));
if (this.hasAttribute('maximumScore')) maximum = parseInt(this.getAttribute('maximumScore'));
parameters.byId[paramId] =
{
id: paramId,
name: Utils.unEscapeHTML(this.attributes.name.value),
type: $.extend({}, Types.primitives.integer, { defaultValue: defaultValue, minimum: minimum, maximum: maximum }),
description: this.hasAttribute("parameterDescription") ? Utils.unEscapeHTML(this.attributes.parameterDescription.value) : ""
};
parameters.sequence.push(parameters.byId[paramId]);
});
if ('t' in parameters.byId) Parameters.timeId = 't';
}
// Load a statement.
function loadStatement(statement, type, connections, treeID)
{
let id = $(statement).attr('id').replace(/\./g, '_');
const idMatch = id.match(/^edit_(\d+)$/);
if (idMatch !== null)
{
Main.jsPlumbCounter = Math.max(Main.jsPlumbCounter, parseInt(idMatch[1]));
}
else
{
id = "ext_" + id;
}
let characterIdRef;
if (type === Main.computerType)
{
characterIdRef = Config.container.characters.sequence[0].id;
}
const allowInterleaveNode = Utils.parseBool($(statement).attr('jumpPoint'));
const allowDialogueEndNode = Utils.parseBool($(statement).attr('inits'));
const endNode = Utils.parseBool($(statement).attr('possibleEnd'));
const text = Utils.unEscapeHTML($(statement).find('text').text());
const xPos = $(statement).find('x').text();
const yPos = $(statement).find('y').text();
// Load the preconditions of this node.
const preconditionsXML = $(statement).find("preconditions");
let preconditions;
if (preconditionsXML.length === 0)
{
preconditions = null;
}
else
{
preconditions = loadPreconditions(preconditionsXML.children()[0]);
}
const parameterEffects = Config.getNewDefaultParameterEffects(characterIdRef);
const acceptableScopes = ['per', 'per-' + type];
if (type === Main.computerType) acceptableScopes.push('per-' + type + '-own');
const propertyValues = Config.getNewDefaultPropertyValues(acceptableScopes, characterIdRef);
let targets;
if (type === Main.playerType)
{
const pEffEl = $(statement).find('parameterEffects');
const pEffs = pEffEl.children(); // All parameter effects of the node.
for (let j = 0; j < pEffs.length; j++)
{
const parameter = pEffs[j];
parameterEffects.userDefined.push(
{
idRef: parameter.attributes.idref.value,
operator: parameter.attributes.changeType.value == "delta" ? Types.assignmentOperators.addAssign.name : Types.assignmentOperators.assign.name,
value: parseInt(parameter.attributes.value.value)
});
}
const intents = $(statement).children('intents');
if (intents.length > 0)
{
migrateProperty(intents[0], 'intent', 'intentProperty', propertyValues, true);
}
targets = $(statement).find('nextComputerStatements').children();
if (targets.length === 0) targets = $(statement).find('nextComputerStatement');
}
else
{
targets = $(statement).find('responses').children();
}
const comment = Utils.unEscapeHTML($(statement).find('comment').text());
if (targets.length > 0)
{
// Save all the connections. We will create the connections when all nodes have been added.
connections[id] = [];
for (let m = 0; m < targets.length; m++)
{
let targetID = targets[m].attributes.idref.value.replace(/\./g, '_');
if (!/^edit_\d+$/.test(targetID)) targetID = 'ext_' + targetID;
connections[id].push(targetID);
}
}
const node = Main.createAndReturnNode(type, id, Main.trees[treeID].div, Main.trees[treeID].dragDiv.attr('id'));
Main.nodes[id] = {
text: text,
type: type,
preconditions: preconditions,
parameterEffects: parameterEffects,
propertyValues: propertyValues,
comment: comment,
endNode: endNode,
allowDialogueEndNode: allowDialogueEndNode,
allowInterleaveNode: allowInterleaveNode,
id: id,
parent: treeID
};
if (type === Main.computerType) Main.nodes[id].characterIdRef = characterIdRef;
// Set the position of the node.
Utils.cssPosition(node, {
top: yPos,
left: xPos
});
// Fill the insides with text
const txtView = node.find('.statementText');
txtView.html(Utils.escapeHTML(text));
}
// Load all preconditions from a given precondition element tree.
function loadPreconditions(preconditionXMLElement)
{
const preconditionType = preconditionXMLElement.nodeName;
const preconditionsArray = [];
const preconditionChildren = $(preconditionXMLElement).children();
for (let i = 0; i < preconditionChildren.length; i++)
{
if (preconditionChildren[i].nodeName == "condition")
{
if (preconditionChildren[i].attributes.idref.value in Parameters.container.byId)
{
preconditionsArray.push(
{
idRef: preconditionChildren[i].attributes.idref.value,
operator: preconditionChildren[i].attributes.test.value,
value: parseInt(preconditionChildren[i].attributes.value.value)
});
}
}
else
{
preconditionsArray.push(loadPreconditions(preconditionChildren[i]));
}
}
return {
type: preconditionType,
subconditions: preconditionsArray
};
}
/*
* Migrates the child with the propertyId as the element name of the parentXML into the given migration property as a value.
* attributeName is an optional parameter, when set, it uses the attribute value of the given attribute as the property value.
*/
function migrateProperty(parentXML, propertyId, migrationPropertyName, propertyValues, needsUnEscaping, attributeName)
{
if (migrationPropertyName in Config.container.migration)
{
const valueXML = $(parentXML).children(propertyId);
if (valueXML.length > 0)
{
if (attributeName) valueXML.text(valueXML.attr(attributeName));
let propertyValue;
let type;
const migrationPropertyIdRef = Config.container.migration[migrationPropertyName].idRef;
const firstCharacterId = Config.container.characters.sequence[0].id;
if (migrationPropertyIdRef in propertyValues.characterIndependent)
{
type = Config.container.properties.byId[migrationPropertyIdRef].type;
propertyValue = type.fromXML(valueXML[0]);
propertyValues.characterIndependent[migrationPropertyIdRef] = needsUnEscaping ? Utils.unEscapeHTML(propertyValue) : propertyValue;
}
else if (migrationPropertyIdRef in propertyValues.perCharacter[firstCharacterId])
{
if (migrationPropertyIdRef in Config.container.characters.properties.byId)
{
type = Config.container.characters.properties.byId[migrationPropertyIdRef].type;
propertyValue = type.fromXML(valueXML[0]);
}
else
{
type = Config.container.characters.byId[firstCharacterId].properties.byId[migrationPropertyIdRef].type;
propertyValue = type.fromXML(valueXML[0]);
}
propertyValues.perCharacter[firstCharacterId][migrationPropertyIdRef] = needsUnEscaping ? Utils.unEscapeHTML(propertyValue) : propertyValue;
}
}
}
}
function loadConversation(conversationXMLElement, conversations, treeID)
{
let id = $(conversationXMLElement).attr('id').replace(/\./g, '_');
const idMatch = id.match(/^edit_(\d+)$/);
if (idMatch !== null)
{
Main.jsPlumbCounter = Math.max(Main.jsPlumbCounter, parseInt(idMatch[1]));
}
else
{
id = "ext_" + id;
}
const endNode = Utils.parseBool($(conversationXMLElement).attr('possibleEnd'));
const comment = Utils.unEscapeHTML($(conversationXMLElement).find('comment').text());
const xPos = $(conversationXMLElement).find('x').text();
const yPos = $(conversationXMLElement).find('y').text();
conversations[id] = {};
conversations[id].xPos = xPos;
conversations[id].yPos = yPos;
conversations[id].textNodes = [];
// Get all the text elements of the conversation.
$(conversationXMLElement).children().each(function()
{
if (this.nodeName == "computerText")
{
conversations[id].textNodes.push(
{
type: Main.computerType,
text: Utils.unEscapeHTML(this.textContent)
});
}
else if (this.nodeName == "playerText")
{
conversations[id].textNodes.push(
{
type: Main.playerType,
text: Utils.unEscapeHTML(this.textContent)
});
}
else if (this.nodeName == "situationText")
{
conversations[id].textNodes.push(
{
type: Main.situationType,
text: Utils.unEscapeHTML(this.textContent)
});
}
});
// Load the preconditions of this node.
const preconditionsXML = $(conversationXMLElement).find("preconditions");
let preconditionsJS;
if (preconditionsXML.length === 0)
{
preconditionsJS = null;
}
else
{
preconditionsJS = loadPreconditions(preconditionsXML.children()[0]);
}
const targets = $(conversationXMLElement).find('responses').children();
conversations[id].connections = [];
if (targets.length > 0)
{
// Save all the connections so we can expand the conversation later on and connect the expanded nodes
for (let m = 0; m < targets.length; m++)
{
let targetID = targets[m].attributes.idref.value.replace(/\./g, '_');
if (!/^edit_\d+$/.test(targetID)) targetID = 'ext_' + targetID;
conversations[id].connections.push(targetID);
}
}
let firstConversationNode = conversations[id].textNodes.length > 0 ? conversations[id].textNodes[0] : null;
if (!firstConversationNode)
{
firstConversationNode = { type: Main.playerType, text: "" };
}
let characterIdRef;
const acceptableScopes = ['per', 'per-' + firstConversationNode.type];
if (firstConversationNode.type === Main.computerType)
{
characterIdRef = Config.container.characters.sequence[0].id;
acceptableScopes.push('per-' + firstConversationNode.type + '-own');
}
const node = Main.createAndReturnNode(firstConversationNode.type, id, Main.trees[treeID].div, Main.trees[treeID].dragDiv.attr('id'));
Main.nodes[id] = {
text: firstConversationNode.text,
type: firstConversationNode.type,
parameterEffects: Config.getNewDefaultParameterEffects(characterIdRef),
preconditions: preconditionsJS,
propertyValues: Config.getNewDefaultPropertyValues(acceptableScopes, characterIdRef),
comment: comment,
endNode: endNode,
allowDialogueEndNode: false,
allowInterleaveNode: false,
id: id,
parent: treeID
};
if (firstConversationNode.type === Main.computerType) Main.nodes[id].characterIdRef = characterIdRef;
// Set the position of the node.
Utils.cssPosition(node, {
top: yPos,
left: xPos
});
// Fill the insides with text
const txtView = node.find('.statementText');
txtView.html(Utils.escapeHTML(firstConversationNode.text));
}
function expandConversations(conversations)
{
for (const firstConversationNodeId in conversations)
{
const firstConversationNode = Main.nodes[firstConversationNodeId];
let lastConversationNodeId = firstConversationNodeId;
// Stores the connections single between conversation nodes
const singleConnections = {};
let previousConversationNodeId = firstConversationNodeId;
// Loop over all textNodes except for the first, it has already been created
for (let i = 1; i < conversations[firstConversationNodeId].textNodes.length; i++)
{
const textNode = conversations[firstConversationNodeId].textNodes[i];
const node = Main.createAndReturnNode(textNode.type, null, Main.trees[firstConversationNode.parent].div, Main.trees[firstConversationNode.parent].dragDiv.attr('id'));
const id = node.attr('id');
let endNode = false;
if (i === conversations[firstConversationNodeId].textNodes.length - 1)
{
endNode = firstConversationNode.endNode;
firstConversationNode.endNode = false;
lastConversationNodeId = id;
}
singleConnections[previousConversationNodeId] = id;
let characterIdRef;
const acceptableScopes = ['per', 'per-' + textNode.type];
if (textNode.type === Main.computerType)
{
characterIdRef = Config.container.characters.sequence[0].id;
acceptableScopes.push('per-' + textNode.type + '-own');
}
Main.nodes[id] = {
text: textNode.text,
type: textNode.type,
parameterEffects: Config.getNewDefaultParameterEffects(characterIdRef),
preconditions: null,
propertyValues: Config.getNewDefaultPropertyValues(acceptableScopes, characterIdRef),
comment: "",
endNode: endNode,
allowDialogueEndNode: false,
allowInterleaveNode: false,
id: id,
parent: firstConversationNode.parent
};
if (textNode.type === Main.computerType) Main.nodes[id].characterIdRef = characterIdRef;
// Set the position of the node and offset it by a small amount to show underlying nodes
Utils.cssPosition(node, {
top: Utils.parseDecimalIntWithDefault(conversations[firstConversationNodeId].yPos, 0) + i * 8,
left: Utils.parseDecimalIntWithDefault(conversations[firstConversationNodeId].xPos, 0) + i * 8
});
// Fill the insides with text
const txtView = node.find('.statementText');
txtView.html(Utils.escapeHTML(textNode.text));
previousConversationNodeId = id;
}
const plumbInstance = Main.getPlumbInstanceByNodeID(firstConversationNodeId);
plumbInstance.batch(function()
{
// Connect each conversation node sequentially
for (const source in singleConnections)
{
plumbInstance.connect(
{
source: source,
target: singleConnections[source]
});
}
// Connect last node to the original conversation's targets
conversations[firstConversationNodeId].connections.forEach(function(target)
{
plumbInstance.connect(
{
source: lastConversationNodeId,
target: target
});
});
}, true);
}
}
})();
| {
"content_hash": "6a7949dd6b216cf1dc13413ff271223d",
"timestamp": "",
"source": "github",
"line_count": 540,
"max_line_length": 182,
"avg_line_length": 41.11851851851852,
"alnum_prop": 0.5514321743829941,
"repo_name": "UURAGE/ScenarioEditor",
"id": "e07c1fda0e8fc331c2296f2f38118f6a5978da98",
"size": "22205",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/editor/js/load/load3.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "5764"
},
{
"name": "JavaScript",
"bytes": "552523"
},
{
"name": "PHP",
"bytes": "1825125"
},
{
"name": "SCSS",
"bytes": "46795"
},
{
"name": "TypeScript",
"bytes": "1944"
}
],
"symlink_target": ""
} |
<?php
namespace Numa\CCCAdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class batchXType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('started')
->add('closed')
->add('working_days',ChoiceType::class,array('attr'=>array('class'=>"size50"),'choices_as_values'=>true,'label'=>"Working Days",'choices'=>array(range(0, 31))))
->add('file',FileType::class, array(
'data_class' => null, 'required'=>false, 'label'=>'S3DB Probills File'
))
->add('newsletter',FileType::class, array(
'data_class' => null, 'required'=>false, 'label'=>'Newsletter PDF'
))
;
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults(array(
'data_class' => 'Numa\CCCAdminBundle\Entity\batchX'
));
}
/**
* @return string
*/
public function getBlockPrefix()
{
return 'numa_cccadminbundle_batchx';
}
}
| {
"content_hash": "02c7f27059a65c825a5dc1fb0c53567c",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 172,
"avg_line_length": 29.46938775510204,
"alnum_prop": 0.6087257617728532,
"repo_name": "genjerator13/doa",
"id": "3ff28ead45553ed76481df7332f6a0fff2c00892",
"size": "1444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Numa/CCCAdminBundle/Form/batchXType.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "5118"
},
{
"name": "Batchfile",
"bytes": "188"
},
{
"name": "CSS",
"bytes": "1584121"
},
{
"name": "HTML",
"bytes": "3288662"
},
{
"name": "JavaScript",
"bytes": "3529717"
},
{
"name": "PHP",
"bytes": "3159614"
},
{
"name": "Roff",
"bytes": "45260"
},
{
"name": "Shell",
"bytes": "1367"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
Gaillonia trichophylla Popov
### Remarks
null | {
"content_hash": "a84ad2cd2e0c2940d7b753517ee67fc1",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 12.153846153846153,
"alnum_prop": 0.7278481012658228,
"repo_name": "mdoering/backbone",
"id": "645f557f94b71347e75acf733673076b1b3591eb",
"size": "230",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Plocama/Plocama trichophylla/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
namespace EPubLibraryContracts
{
public interface IRelation : IDataWithLanguage
{
string RelationInfo { get; set; }
}
}
| {
"content_hash": "d3f8d96cc0ab40ec34d1bd1d05080e62",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 50,
"avg_line_length": 20.142857142857142,
"alnum_prop": 0.6666666666666666,
"repo_name": "LordKiRon/fb2converters",
"id": "e6c8131a351331f512c8ff380ad597e02a40ad67",
"size": "143",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "epublibrary/EPubLibraryContracts/IRelation.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "5340"
},
{
"name": "C",
"bytes": "8288"
},
{
"name": "C#",
"bytes": "1780293"
},
{
"name": "C++",
"bytes": "73527"
},
{
"name": "CSS",
"bytes": "7304"
},
{
"name": "HTML",
"bytes": "29008"
},
{
"name": "Inno Setup",
"bytes": "46223"
},
{
"name": "JavaScript",
"bytes": "40722"
},
{
"name": "Objective-C",
"bytes": "403"
},
{
"name": "Smalltalk",
"bytes": "2220"
}
],
"symlink_target": ""
} |
% Thanks to Claudio Fiandrino for his help
% Source: http://tex.stackexchange.com/a/75695/5645
\documentclass{article}
\usepackage[pdftex,active,tightpage]{preview}
\setlength\PreviewBorder{2mm}
\usepackage{amssymb,amsmath}
\usepackage{pgfplots}
\pgfplotsset{compat=1.6}
\begin{document}
\begin{preview}
\begin{tikzpicture}
\begin{axis}[
axis lines=middle,
width=15cm, height=15cm, % size of the image
grid = both,
grid style={dashed, gray!30},
enlargelimits=true,
xmin=-1, % start the diagram at this x-coordinate
xmax= 1, % end the diagram at this x-coordinate
ymin= 0, % start the diagram at this y-coordinate
ymax= 1, % end the diagram at this y-coordinate
/pgfplots/xtick={-1,-0.8,...,1}, % make steps of length 0.2
/pgfplots/ytick={0,0.1,...,1}, % make steps of length 0.1
axis background/.style={fill=white},
ylabel=y,
xlabel=x,]
\addplot[domain=-1:1, ultra thick,samples=100,blue] {1};
\label{plot one}
\addplot[domain=-1:1, ultra thick,samples=100,red] {0};
\label{plot two}
\node [draw,fill=white] at (rel axis cs: 0.8,0.8) {\shortstack[l]{
$f(x) =
\left\lbrace\begin{array}{@{}l@{}l@{}l@{}}
\tikz[baseline=-0.5ex]\node{\ref{plot one}}; \phantom{1cm}& 1 & \text{ if } x \in \mathbb{Q}\\
\tikz[baseline=-0.5ex]\node{\ref{plot two}}; & 0 & \text{ if } x \in \mathbb{R} \setminus \mathbb{Q}
\end{array}\right.
$}};
\end{axis}
\end{tikzpicture}
\end{preview}
\end{document}
| {
"content_hash": "55af893deec7f33c9379221d96d9feeb",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 107,
"avg_line_length": 36.93023255813954,
"alnum_prop": 0.6070528967254408,
"repo_name": "MartinThoma/LaTeX-examples",
"id": "08a4f84cab1d3e4f2ddcb08dc5913eda1abac630",
"size": "1588",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tikz/dirichlet-function/dirichlet-function.tex",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "104"
},
{
"name": "Asymptote",
"bytes": "16054"
},
{
"name": "Batchfile",
"bytes": "187"
},
{
"name": "C",
"bytes": "7885"
},
{
"name": "Gnuplot",
"bytes": "383"
},
{
"name": "HTML",
"bytes": "10585"
},
{
"name": "Haskell",
"bytes": "9401"
},
{
"name": "Java",
"bytes": "95574"
},
{
"name": "JavaScript",
"bytes": "33665"
},
{
"name": "Jupyter Notebook",
"bytes": "15400"
},
{
"name": "Makefile",
"bytes": "403103"
},
{
"name": "Prolog",
"bytes": "4515"
},
{
"name": "Python",
"bytes": "58056"
},
{
"name": "Raku",
"bytes": "357"
},
{
"name": "Scala",
"bytes": "6990"
},
{
"name": "Shell",
"bytes": "2783"
},
{
"name": "ShellSession",
"bytes": "3837"
},
{
"name": "Smarty",
"bytes": "572"
},
{
"name": "Tcl",
"bytes": "250"
},
{
"name": "TeX",
"bytes": "5244843"
},
{
"name": "X10",
"bytes": "2354"
}
],
"symlink_target": ""
} |
package cn.picksomething.slidingtabindicator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | {
"content_hash": "4da8409b738767dd6c406e3dabfaf168",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 81,
"avg_line_length": 24.352941176470587,
"alnum_prop": 0.7028985507246377,
"repo_name": "picksomething/sliding-tab-indicator",
"id": "979341ed8a5a8c298b9dc8ccdfa34157003d50ca",
"size": "414",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "slidingtabindicator/src/test/java/cn/picksomething/slidingtabindicator/ExampleUnitTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "24605"
}
],
"symlink_target": ""
} |
Initial release.
| {
"content_hash": "c4334df53a820d12a9f2b26374c48e77",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 16,
"avg_line_length": 17,
"alnum_prop": 0.8235294117647058,
"repo_name": "justinmakaila/JMSecureEntryTextField",
"id": "6da637372487d58a85501b94b45b43515443b1ce",
"size": "63",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "5119"
},
{
"name": "Ruby",
"bytes": "5132"
}
],
"symlink_target": ""
} |
package net.tomp2p.rpc;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.tomp2p.connection2.ChannelCreator;
import net.tomp2p.connection2.ConnectionBean;
import net.tomp2p.connection2.ConnectionConfiguration;
import net.tomp2p.connection2.PeerBean;
import net.tomp2p.connection2.RequestHandler;
import net.tomp2p.futures.FutureResponse;
import net.tomp2p.message.Message2;
import net.tomp2p.message.Message2.Type;
import net.tomp2p.p2p.builder.ShutdownBuilder;
import net.tomp2p.peers.PeerAddress;
import net.tomp2p.peers.PeerStatusListener;
/**
* This Quit RPC is used to send friendly shutdown messages by peers that are shutdown regularly.
*
* @author Thomas Bocek
*
*/
public class QuitRPC extends DispatchHandler {
private static final Logger LOG = LoggerFactory.getLogger(QuitRPC.class);
public static final byte QUIT_COMMAND = 6;
private final List<PeerStatusListener> listeners = new ArrayList<PeerStatusListener>();
/**
* Constructor that registers this RPC with the message handler.
*
* @param peerBean
* The peer bean that contains data that is unique for each peer
* @param connectionBean
* The connection bean that is unique per connection (multiple peers can share a single connection)
*/
public QuitRPC(final PeerBean peerBean, final ConnectionBean connectionBean) {
super(peerBean, connectionBean, QUIT_COMMAND);
}
/**
* Add a peer status listener that gets notified when a peer is offline.
*
* @param listener
* The listener
* @return This class
*/
public QuitRPC addPeerStatusListener(final PeerStatusListener listener) {
listeners.add(listener);
return this;
}
/**
* Sends a message that indicates this peer is about to quit. This is an RPC.
*
* @param remotePeer
* The remote peer to send this request
* @param shutdownBuilder
* Used for the sign and force TCP flag Set if the message should be signed
* @param channelCreator
* The channel creator that creates connections
* @param configuration
* The client side connection configuration
* @return The future response to keep track of future events
*/
public FutureResponse quit(final PeerAddress remotePeer, final ShutdownBuilder shutdownBuilder,
final ChannelCreator channelCreator) {
final Message2 message = createMessage(remotePeer, QUIT_COMMAND, Type.REQUEST_FF_1);
if (shutdownBuilder.isSignMessage()) {
message.setPublicKeyAndSign(peerBean().getKeyPair());
}
FutureResponse futureResponse = new FutureResponse(message);
final RequestHandler<FutureResponse> requestHandler = new RequestHandler<FutureResponse>(
futureResponse, peerBean(), connectionBean(), shutdownBuilder);
if (!shutdownBuilder.isForceTCP()) {
return requestHandler.fireAndForgetUDP(channelCreator);
} else {
return requestHandler.fireAndForgetTCP(channelCreator);
}
}
@Override
public Message2 handleResponse(final Message2 message, final boolean sign) throws Exception {
if (!(message.getType() == Type.REQUEST_FF_1 && message.getCommand() == QUIT_COMMAND)) {
throw new IllegalArgumentException("Message content is wrong");
}
LOG.debug("received QUIT message {}" + message);
synchronized (listeners) {
for (PeerStatusListener listener : listeners) {
listener.peerFailed(message.getSender(), true);
}
}
return message;
}
}
| {
"content_hash": "11b3cd6b15b0e4719a4b68e166f7ae9b",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 114,
"avg_line_length": 36.66990291262136,
"alnum_prop": 0.6844056129203071,
"repo_name": "maxatp/tomp2p_5",
"id": "ae584e409b639438c38898f71fff1c52dc531203",
"size": "4368",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/main/java/net/tomp2p/rpc/QuitRPC.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "7562"
},
{
"name": "Java",
"bytes": "1957453"
}
],
"symlink_target": ""
} |
TOP = ../../../../../..
include $(TOP)/configs/current
LIBS = -lXvMCW -lXvMC -lXv -lX11
#############################################
.PHONY: default clean
default: test_context test_surface test_subpicture test_blocks test_rendering xvmc_bench
test_context: test_context.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
test_surface: test_surface.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
test_subpicture: test_subpicture.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
test_blocks: test_blocks.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
test_rendering: test_rendering.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
xvmc_bench: xvmc_bench.o testlib.o
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
clean:
$(RM) -rf *.o test_context test_surface test_subpicture test_blocks test_rendering xvmc_bench
| {
"content_hash": "fb5512d4a513ee451eb9b73d5ace14f7",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 94,
"avg_line_length": 26,
"alnum_prop": 0.6116625310173698,
"repo_name": "gzorin/RSXGL",
"id": "88b03763563c5486c6255b243efb9ac473518227",
"size": "806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "extsrc/mesa/src/gallium/state_trackers/xorg/xvmc/tests/Makefile",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "1210761"
},
{
"name": "C",
"bytes": "35145128"
},
{
"name": "C++",
"bytes": "33587085"
},
{
"name": "CSS",
"bytes": "16957"
},
{
"name": "Emacs Lisp",
"bytes": "74"
},
{
"name": "FORTRAN",
"bytes": "1377222"
},
{
"name": "Objective-C",
"bytes": "146655"
},
{
"name": "Perl",
"bytes": "361"
},
{
"name": "Python",
"bytes": "668613"
},
{
"name": "Shell",
"bytes": "70500"
},
{
"name": "XSLT",
"bytes": "4325"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="urn:jboss:module:1.3" name="io.machinecode.chainlink.ext.jdbc">
<resources>
<resource-root path="chainlink-ext-jdbc-${project.version}.jar"/>
</resources>
<dependencies>
<module name="gnu.trove"/>
<module name="io.machinecode.chainlink"/>
</dependencies>
</module>
| {
"content_hash": "c5cac5aec88793a56d6d9bb4e525c4f7",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 78,
"avg_line_length": 32.72727272727273,
"alnum_prop": 0.6416666666666667,
"repo_name": "BrentDouglas/chainlink",
"id": "4357adb60e7ed450ef352df3190acc8870f60f08",
"size": "360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rt/wildfly/modules/io/machinecode/chainlink/ext/jdbc/main/module.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "38244"
},
{
"name": "Java",
"bytes": "3335539"
},
{
"name": "Shell",
"bytes": "46609"
}
],
"symlink_target": ""
} |
module BicycleCms
module Panels
module FeedbackPanel
# TODO Как правильно вызывать?
Panels.define_default_action_links_for :feedback, [:destroy]
end
end
end
| {
"content_hash": "3ecc6ab78d9252705171661941177015",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 66,
"avg_line_length": 18.3,
"alnum_prop": 0.6994535519125683,
"repo_name": "kuraga/bicycle_cms",
"id": "54ed52f0b3964e1897de0c6ece316a3361336bce",
"size": "203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/bicycle_cms/panels/feedback_panel.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CoffeeScript",
"bytes": "398"
},
{
"name": "Ruby",
"bytes": "70051"
}
],
"symlink_target": ""
} |
using GeneticSharporithm.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GeneticSharporithm
{
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISolution<T> where T: class
{
/// <summary>
/// Checks whether the specified chromosome is the solution to the problem.
/// </summary>
/// <param name="chromosome"></param>
/// <returns>
/// true if the specified chromosome is the solution to the problem,
/// false otherwise.
/// </returns>
bool IsSolution(Chromosome<T> chromosome);
}
}
| {
"content_hash": "24fa6493734c93be0cab144642a6e9a7",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 83,
"avg_line_length": 27.192307692307693,
"alnum_prop": 0.6166902404526167,
"repo_name": "axm/geneticsharporithm",
"id": "df2fc7ee9057cb1f3f597220c058c330b43aa4f5",
"size": "709",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/csharp/GeneticSharporithm/Core/ISolution.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "36710"
}
],
"symlink_target": ""
} |
"""Example .konchrc with named configs.
To use a named config, run:
$ konch --name=trig
or
$ konch -n trig
"""
import os
import sys
import math
import konch
# the default config
konch.config({"context": [os, sys], "banner": "The default shell"})
# A named config
konch.named_config(
"trig", {"context": [math.sin, math.tan, math.cos], "banner": "The trig shell"}
)
konch.named_config(
"func", {"context": [math.gamma, math.exp, math.log], "banner": "The func shell"}
)
| {
"content_hash": "54201f462ae24e05344ad20eda623ee1",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 85,
"avg_line_length": 17.642857142857142,
"alnum_prop": 0.645748987854251,
"repo_name": "sloria/konch",
"id": "6ba14d33626b55b86a17454b7698181666989c0c",
"size": "516",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "example_rcfiles/konch_named.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "80893"
}
],
"symlink_target": ""
} |
<?php
namespace Project\Component\Form;
use Project\Service\Container;
use Sy\Bootstrap\Lib\Url;
use Sy\Component\Html\Form;
class CodeEditor extends Form {
private $code;
public function __construct($code = null) {
$this->code = $code;
parent::__construct();
}
public function init() {
$this->addTranslator(LANG_DIR);
$this->setOption('error-class', 'alert alert-error');
$this->setOption('success-class', 'alert alert-success');
$codeArea = new \Project\Component\Form\Element\CodeArea();
$codeArea->setAttribute('name', 'code');
// add code in code area
if (!empty($this->code)) {
$codeArea->setContent([$this->code]);
}
$this->addElement($codeArea);
}
public function submitAction() {
$code = trim($this->post('code'));
$title = trim($this->post('title', ''));
$description = trim($this->post('description', ''));
if (empty($code)) exit();
if ($code === '<?php') exit();
if ($this->post('action') === 'save') {
// save the code
$date = date("Y-m-d H:i:s");
$service = Container::getInstance();
$service->code->change([
'title' => $title,
'description'=> $description,
'code' => $code,
'ip' => ip2long($_SERVER['REMOTE_ADDR']),
], [
'updated_at' => $date,
]);
$id = $service->code->lastInsertId();
$id = empty($id) ? $this->get('id') : $id;
echo '<pre style="color:white">You can share your code using this URL: http://' . $_SERVER['HTTP_HOST'] . Url::build('page', 'home', ['id' => $id]) . '</pre>';
} else {
if (!is_dir(TMP_DIR)) mkdir(TMP_DIR);
$id = uniqid();
file_put_contents(TMP_DIR . "/$id.php", $code);
ob_start();
passthru(sprintf(PHP, TMP_DIR . '/' . $id . '.php'));
$output = ob_get_contents();
ob_end_clean();
$output = htmlentities($output, ENT_QUOTES);
echo "<pre style=\"color:white\">$output</pre>";
unlink(TMP_DIR . "/$id.php");
}
exit();
}
} | {
"content_hash": "18414199ed9a97c20bf506385d6e2d5b",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 162,
"avg_line_length": 27.056338028169016,
"alnum_prop": 0.5845913586673608,
"repo_name": "Syone/SyBox",
"id": "62df99101d0731a6e7a189e78e3dce9c1f63486b",
"size": "1921",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "protected/src/Component/Form/CodeEditor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "29681"
},
{
"name": "HTML",
"bytes": "32222"
},
{
"name": "JavaScript",
"bytes": "13631"
},
{
"name": "PHP",
"bytes": "45264"
},
{
"name": "SCSS",
"bytes": "2679"
},
{
"name": "Smarty",
"bytes": "1683"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: netscaler_nitro_request
short_description: Issue Nitro API requests to a Netscaler instance.
description:
- Issue Nitro API requests to a Netscaler instance.
- This is intended to be a short hand for using the uri Ansible module to issue the raw HTTP requests directly.
- It provides consistent return values and has no other dependencies apart from the base Ansible runtime environment.
- This module is intended to run either on the Ansible control node or a bastion (jumpserver) with access to the actual Netscaler instance
version_added: "2.5.0"
author: George Nikolopoulos (@giorgos-nikolopoulos)
options:
nsip:
description:
- The IP address of the Netscaler or MAS instance where the Nitro API calls will be made.
- "The port can be specified with the colon C(:). E.g. C(192.168.1.1:555)."
nitro_user:
description:
- The username with which to authenticate to the Netscaler node.
required: true
nitro_pass:
description:
- The password with which to authenticate to the Netscaler node.
required: true
nitro_protocol:
choices: [ 'http', 'https' ]
default: http
description:
- Which protocol to use when accessing the Nitro API objects.
validate_certs:
description:
- If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates.
default: 'yes'
type: bool
nitro_auth_token:
description:
- The authentication token provided by the C(mas_login) operation. It is required when issuing Nitro API calls through a MAS proxy.
resource:
description:
- The type of resource we are operating on.
- It is required for all I(operation) values except C(mas_login) and C(save_config).
name:
description:
- The name of the resource we are operating on.
- "It is required for the following I(operation) values: C(update), C(get), C(delete)."
attributes:
description:
- The attributes of the Nitro object we are operating on.
- "It is required for the following I(operation) values: C(add), C(update), C(action)."
args:
description:
- A dictionary which defines the key arguments by which we will select the Nitro object to operate on.
- "It is required for the following I(operation) values: C(get_by_args), C('delete_by_args')."
filter:
description:
- A dictionary which defines the filter with which to refine the Nitro objects returned by the C(get_filtered) I(operation).
operation:
description:
- Define the Nitro operation that we want to perform.
choices:
- add
- update
- get
- get_by_args
- get_filtered
- get_all
- delete
- delete_by_args
- count
- mas_login
- save_config
- action
expected_nitro_errorcode:
description:
- A list of numeric values that signify that the operation was successful.
default: [0]
required: true
action:
description:
- The action to perform when the I(operation) value is set to C(action).
- Some common values for this parameter are C(enable), C(disable), C(rename).
instance_ip:
description:
- The IP address of the target Netscaler instance when issuing a Nitro request through a MAS proxy.
instance_name:
description:
- The name of the target Netscaler instance when issuing a Nitro request through a MAS proxy.
instance_id:
description:
- The id of the target Netscaler instance when issuing a Nitro request through a MAS proxy.
'''
EXAMPLES = '''
- name: Add a server
delegate_to: localhost
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: add
resource: server
name: test-server-1
attributes:
name: test-server-1
ipaddress: 192.168.1.1
- name: Update server
delegate_to: localhost
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: update
resource: server
name: test-server-1
attributes:
name: test-server-1
ipaddress: 192.168.1.2
- name: Get server
delegate_to: localhost
register: result
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: get
resource: server
name: test-server-1
- name: Delete server
delegate_to: localhost
register: result
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: delete
resource: server
name: test-server-1
- name: Rename server
delegate_to: localhost
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: action
action: rename
resource: server
attributes:
name: test-server-1
newname: test-server-2
- name: Get server by args
delegate_to: localhost
register: result
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: get_by_args
resource: server
args:
name: test-server-1
- name: Get server by filter
delegate_to: localhost
register: result
netscaler_nitro_request:
nsip: "{{ nsip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: get_filtered
resource: server
filter:
ipaddress: 192.168.1.2
# Doing a NITRO request through MAS.
# Requires to have an authentication token from the mas_login and used as the nitro_auth_token parameter
# Also nsip is the MAS address and the target Netscaler IP must be defined with instance_ip
# The rest of the task arguments remain the same as when issuing the NITRO request directly to a Netscaler instance.
- name: Do mas login
delegate_to: localhost
register: login_result
netscaler_nitro_request:
nsip: "{{ mas_ip }}"
nitro_user: "{{ nitro_user }}"
nitro_pass: "{{ nitro_pass }}"
operation: mas_login
- name: Add resource through MAS proxy
delegate_to: localhost
netscaler_nitro_request:
nsip: "{{ mas_ip }}"
nitro_auth_token: "{{ login_result.nitro_auth_token }}"
instance_ip: "{{ nsip }}"
operation: add
resource: server
name: test-server-1
attributes:
name: test-server-1
ipaddress: 192.168.1.7
'''
RETURN = '''
nitro_errorcode:
description: A numeric value containing the return code of the NITRO operation. When 0 the operation is successful. Any non zero value indicates an error.
returned: always
type: int
sample: 0
nitro_message:
description: A string containing a human readable explanation for the NITRO operation result.
returned: always
type: str
sample: Success
nitro_severity:
description: A string describing the severity of the NITRO operation error or NONE.
returned: always
type: str
sample: NONE
http_response_data:
description: A dictionary that contains all the HTTP response's data.
returned: always
type: dict
sample: "status: 200"
http_response_body:
description: A string with the actual HTTP response body content if existent. If there is no HTTP response body it is an empty string.
returned: always
type: str
sample: "{ errorcode: 0, message: Done, severity: NONE }"
nitro_object:
description: The object returned from the NITRO operation. This is applicable to the various get operations which return an object.
returned: when applicable
type: list
sample:
-
ipaddress: "192.168.1.8"
ipv6address: "NO"
maxbandwidth: "0"
name: "test-server-1"
port: 0
sp: "OFF"
state: "ENABLED"
nitro_auth_token:
description: The token returned by the C(mas_login) operation when successful.
returned: when applicable
type: str
sample: "##E8D7D74DDBD907EE579E8BB8FF4529655F22227C1C82A34BFC93C9539D66"
'''
from ansible.module_utils.urls import fetch_url
from ansible.module_utils.basic import env_fallback
from ansible.module_utils.basic import AnsibleModule
import codecs
class NitroAPICaller(object):
_argument_spec = dict(
nsip=dict(
fallback=(env_fallback, ['NETSCALER_NSIP']),
),
nitro_user=dict(
fallback=(env_fallback, ['NETSCALER_NITRO_USER']),
),
nitro_pass=dict(
fallback=(env_fallback, ['NETSCALER_NITRO_PASS']),
no_log=True
),
nitro_protocol=dict(
choices=['http', 'https'],
fallback=(env_fallback, ['NETSCALER_NITRO_PROTOCOL']),
default='http'
),
validate_certs=dict(
default=True,
type='bool'
),
nitro_auth_token=dict(
type='str',
no_log=True
),
resource=dict(type='str'),
name=dict(type='str'),
attributes=dict(type='dict'),
args=dict(type='dict'),
filter=dict(type='dict'),
operation=dict(
type='str',
required=True,
choices=[
'add',
'update',
'get',
'get_by_args',
'get_filtered',
'get_all',
'delete',
'delete_by_args',
'count',
'mas_login',
# Actions
'save_config',
# Generic action handler
'action',
]
),
expected_nitro_errorcode=dict(
type='list',
default=[0],
),
action=dict(type='str'),
instance_ip=dict(type='str'),
instance_name=dict(type='str'),
instance_id=dict(type='str'),
)
def __init__(self):
self._module = AnsibleModule(
argument_spec=self._argument_spec,
supports_check_mode=False,
)
self._module_result = dict(
failed=False,
)
# Prepare the http headers according to module arguments
self._headers = {}
self._headers['Content-Type'] = 'application/json'
# Check for conflicting authentication methods
have_token = self._module.params['nitro_auth_token'] is not None
have_userpass = None not in (self._module.params['nitro_user'], self._module.params['nitro_pass'])
login_operation = self._module.params['operation'] == 'mas_login'
if have_token and have_userpass:
self.fail_module(msg='Cannot define both authentication token and username/password')
if have_token:
self._headers['Cookie'] = "NITRO_AUTH_TOKEN=%s" % self._module.params['nitro_auth_token']
if have_userpass and not login_operation:
self._headers['X-NITRO-USER'] = self._module.params['nitro_user']
self._headers['X-NITRO-PASS'] = self._module.params['nitro_pass']
# Do header manipulation when doing a MAS proxy call
if self._module.params['instance_ip'] is not None:
self._headers['_MPS_API_PROXY_MANAGED_INSTANCE_IP'] = self._module.params['instance_ip']
elif self._module.params['instance_name'] is not None:
self._headers['_MPS_API_PROXY_MANAGED_INSTANCE_NAME'] = self._module.params['instance_name']
elif self._module.params['instance_id'] is not None:
self._headers['_MPS_API_PROXY_MANAGED_INSTANCE_ID'] = self._module.params['instance_id']
def edit_response_data(self, r, info, result, success_status):
# Search for body in both http body and http data
if r is not None:
result['http_response_body'] = codecs.decode(r.read(), 'utf-8')
elif 'body' in info:
result['http_response_body'] = codecs.decode(info['body'], 'utf-8')
del info['body']
else:
result['http_response_body'] = ''
result['http_response_data'] = info
# Update the nitro_* parameters according to expected success_status
# Use explicit return values from http response or deduce from http status code
# Nitro return code in http data
result['nitro_errorcode'] = None
result['nitro_message'] = None
result['nitro_severity'] = None
if result['http_response_body'] != '':
try:
data = self._module.from_json(result['http_response_body'])
except ValueError:
data = {}
result['nitro_errorcode'] = data.get('errorcode')
result['nitro_message'] = data.get('message')
result['nitro_severity'] = data.get('severity')
# If we do not have the nitro errorcode from body deduce it from the http status
if result['nitro_errorcode'] is None:
# HTTP status failed
if result['http_response_data'].get('status') != success_status:
result['nitro_errorcode'] = -1
result['nitro_message'] = result['http_response_data'].get('msg', 'HTTP status %s' % result['http_response_data']['status'])
result['nitro_severity'] = 'ERROR'
# HTTP status succeeded
else:
result['nitro_errorcode'] = 0
result['nitro_message'] = 'Success'
result['nitro_severity'] = 'NONE'
def handle_get_return_object(self, result):
result['nitro_object'] = []
if result['nitro_errorcode'] == 0:
if result['http_response_body'] != '':
data = self._module.from_json(result['http_response_body'])
if self._module.params['resource'] in data:
result['nitro_object'] = data[self._module.params['resource']]
else:
del result['nitro_object']
def fail_module(self, msg, **kwargs):
self._module_result['failed'] = True
self._module_result['changed'] = False
self._module_result.update(kwargs)
self._module_result['msg'] = msg
self._module.fail_json(**self._module_result)
def main(self):
if self._module.params['operation'] == 'add':
result = self.add()
if self._module.params['operation'] == 'update':
result = self.update()
if self._module.params['operation'] == 'delete':
result = self.delete()
if self._module.params['operation'] == 'delete_by_args':
result = self.delete_by_args()
if self._module.params['operation'] == 'get':
result = self.get()
if self._module.params['operation'] == 'get_by_args':
result = self.get_by_args()
if self._module.params['operation'] == 'get_filtered':
result = self.get_filtered()
if self._module.params['operation'] == 'get_all':
result = self.get_all()
if self._module.params['operation'] == 'count':
result = self.count()
if self._module.params['operation'] == 'mas_login':
result = self.mas_login()
if self._module.params['operation'] == 'action':
result = self.action()
if self._module.params['operation'] == 'save_config':
result = self.save_config()
if result['nitro_errorcode'] not in self._module.params['expected_nitro_errorcode']:
self.fail_module(msg='NITRO Failure', **result)
self._module_result.update(result)
self._module.exit_json(**self._module_result)
def exit_module(self):
self._module.exit_json()
def add(self):
# Check if required attributes are present
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['attributes'] is None:
self.fail_module(msg='NITRO resource attributes are undefined.')
url = '%s://%s/nitro/v1/config/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
)
data = self._module.jsonify({self._module.params['resource']: self._module.params['attributes']})
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
data=data,
method='POST',
)
result = {}
self.edit_response_data(r, info, result, success_status=201)
if result['nitro_errorcode'] == 0:
self._module_result['changed'] = True
else:
self._module_result['changed'] = False
return result
def update(self):
# Check if required attributes are arguments present
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['name'] is None:
self.fail_module(msg='NITRO resource name is undefined.')
if self._module.params['attributes'] is None:
self.fail_module(msg='NITRO resource attributes are undefined.')
url = '%s://%s/nitro/v1/config/%s/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
self._module.params['name'],
)
data = self._module.jsonify({self._module.params['resource']: self._module.params['attributes']})
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
data=data,
method='PUT',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
if result['nitro_errorcode'] == 0:
self._module_result['changed'] = True
else:
self._module_result['changed'] = False
return result
def get(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['name'] is None:
self.fail_module(msg='NITRO resource name is undefined.')
url = '%s://%s/nitro/v1/config/%s/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
self._module.params['name'],
)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='GET',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
self.handle_get_return_object(result)
self._module_result['changed'] = False
return result
def get_by_args(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['args'] is None:
self.fail_module(msg='NITRO args is undefined.')
url = '%s://%s/nitro/v1/config/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
)
args_dict = self._module.params['args']
args = ','.join(['%s:%s' % (k, args_dict[k]) for k in args_dict])
args = 'args=' + args
url = '?'.join([url, args])
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='GET',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
self.handle_get_return_object(result)
self._module_result['changed'] = False
return result
def get_filtered(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['filter'] is None:
self.fail_module(msg='NITRO filter is undefined.')
keys = list(self._module.params['filter'].keys())
filter_key = keys[0]
filter_value = self._module.params['filter'][filter_key]
filter_str = '%s:%s' % (filter_key, filter_value)
url = '%s://%s/nitro/v1/config/%s?filter=%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
filter_str,
)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='GET',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
self.handle_get_return_object(result)
self._module_result['changed'] = False
return result
def get_all(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
url = '%s://%s/nitro/v1/config/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
)
print('headers %s' % self._headers)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='GET',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
self.handle_get_return_object(result)
self._module_result['changed'] = False
return result
def delete(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['name'] is None:
self.fail_module(msg='NITRO resource is undefined.')
# Deletion by name takes precedence over deletion by attributes
url = '%s://%s/nitro/v1/config/%s/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
self._module.params['name'],
)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='DELETE',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
if result['nitro_errorcode'] == 0:
self._module_result['changed'] = True
else:
self._module_result['changed'] = False
return result
def delete_by_args(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['args'] is None:
self.fail_module(msg='NITRO args is undefined.')
url = '%s://%s/nitro/v1/config/%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
)
args_dict = self._module.params['args']
args = ','.join(['%s:%s' % (k, args_dict[k]) for k in args_dict])
args = 'args=' + args
url = '?'.join([url, args])
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='DELETE',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
if result['nitro_errorcode'] == 0:
self._module_result['changed'] = True
else:
self._module_result['changed'] = False
return result
def count(self):
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
url = '%s://%s/nitro/v1/config/%s?count=yes' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
method='GET',
)
result = {}
self.edit_response_data(r, info, result)
if result['http_response_body'] != '':
data = self._module.from_json(result['http_response_body'])
result['nitro_errorcode'] = data['errorcode']
result['nitro_message'] = data['message']
result['nitro_severity'] = data['severity']
if self._module.params['resource'] in data:
result['nitro_count'] = data[self._module.params['resource']][0]['__count']
self._module_result['changed'] = False
return result
def action(self):
# Check if required attributes are present
if self._module.params['resource'] is None:
self.fail_module(msg='NITRO resource is undefined.')
if self._module.params['attributes'] is None:
self.fail_module(msg='NITRO resource attributes are undefined.')
if self._module.params['action'] is None:
self.fail_module(msg='NITRO action is undefined.')
url = '%s://%s/nitro/v1/config/%s?action=%s' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
self._module.params['resource'],
self._module.params['action'],
)
data = self._module.jsonify({self._module.params['resource']: self._module.params['attributes']})
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
data=data,
method='POST',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
if result['nitro_errorcode'] == 0:
self._module_result['changed'] = True
else:
self._module_result['changed'] = False
return result
def mas_login(self):
url = '%s://%s/nitro/v1/config/login' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
)
login_credentials = {
'login': {
'username': self._module.params['nitro_user'],
'password': self._module.params['nitro_pass'],
}
}
data = 'object=\n%s' % self._module.jsonify(login_credentials)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
data=data,
method='POST',
)
print(r, info)
result = {}
self.edit_response_data(r, info, result, success_status=200)
if result['nitro_errorcode'] == 0:
body_data = self._module.from_json(result['http_response_body'])
result['nitro_auth_token'] = body_data['login'][0]['sessionid']
self._module_result['changed'] = False
return result
def save_config(self):
url = '%s://%s/nitro/v1/config/nsconfig?action=save' % (
self._module.params['nitro_protocol'],
self._module.params['nsip'],
)
data = self._module.jsonify(
{
'nsconfig': {},
}
)
r, info = fetch_url(
self._module,
url=url,
headers=self._headers,
data=data,
method='POST',
)
result = {}
self.edit_response_data(r, info, result, success_status=200)
self._module_result['changed'] = False
return result
def main():
nitro_api_caller = NitroAPICaller()
nitro_api_caller.main()
if __name__ == '__main__':
main()
| {
"content_hash": "bdd4063898848bee88d4a34764a45915",
"timestamp": "",
"source": "github",
"line_count": 904,
"max_line_length": 158,
"avg_line_length": 31.490044247787612,
"alnum_prop": 0.5672181824568799,
"repo_name": "thaim/ansible",
"id": "3cf6366d1dafdf46e6f87b4ff643d511e1bcbc8d",
"size": "28641",
"binary": false,
"copies": "19",
"ref": "refs/heads/fix-broken-link",
"path": "lib/ansible/modules/network/netscaler/netscaler_nitro_request.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "7"
},
{
"name": "Shell",
"bytes": "246"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" standalone="no"?><project basedir="." default="help" name="Compositron">
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!--
The master build file lives at: ${sunspot.home}/build.xml.
If you do not have a Sun SPOT properties file for some reason,
then you can set the sunspot.home property manually.
<property name="sunspot.home" value="/opt/sunspot"/>
The behavior of the build is also controled through properties.
For example, to use a different source directory, you can set
the property 'src.dir'.
<property name="src.dir" value="mysrc"/>
For a complete listing of properties that are used, and their
explanations, see the file ${sunspot.home}/default.properties.
-->
<property name="user.properties.file" value="build.properties"/>
<property file="${user.home}/.sunspotfrc.properties"/>
<import file="${sunspot.home}/build.xml"/>
<!--
This file imports the master build file for compiling and deploying sunspot
applications. This file provides hooks for the user build file, so that
you can accomplish almost anything without having to rewrite any of the
build procedures. However, if need be, you can just look at the imported
build file to determine how exactly any step is accomplished.
Of course, another useful way to find out exactly what is happening is to
run the targets listed below with ant's 'verbose' flag (ant -v). This will
display exactly what is happening at each step.
Some important targets that are defined within the master build file are:
(Do "ant help" to see the full list.)
init: initialize and check all properties
help: display useful a help message
environment displays information about setting up your environment
sdk-info displays information about the current SDK installation
find-spots locate USB ports where SPOTs are connected
info displays information about the configuration of a SPOT
slots displays a list of the applications deployed on the SPOT
clean: delete all compiled/generated files
compile: compiles java source files to classes
jar-app Create a jar for this application
deploy deploy the application to a SPOT as an IMlet
jar-deploy deploy an IMlet jar
run connect to a device and watch the application
debug-run configure the SPOT ro run the debug agent and then start the debug proxy
debug-proxy-run start the proxy for the high-level debugger
Some useful command line properties:
-Dbasestation.addr=1234 set the address of the basestation
-DremoteId=1234 set the target for remote run/deploy/debug-proxy-run
-Dsquawk.startup.class=com.example.MyStartUp
set an alternative startup class name
-Dspotport=COM2 set the port name for communicating with the SPOT
-Djar.file=example.jar set the jar file for jar-app, jar-deploy and make-host-jar
-Dmidlet=2 select a midlet to run for selectapplication
or deploy targets (defaults to 1)
-Dutility.jars=utils.jar a classpath separator delimited list of jars to be
included with the application
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are defined as follows:
For each target above (except help),
-pre-<target>: called before the target
-post-<target>: called after the target
For example, inserting an echo statement after compilation could look like this:
<target name="-post-compile">
<echo>Compile finished!</echo>
</target>
For more information on using ant, see http://ant.apache.org.
-->
</project> | {
"content_hash": "46efea4ba90fe4ab6318fed9e95abe52",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 109,
"avg_line_length": 46.13978494623656,
"alnum_prop": 0.6527615940340247,
"repo_name": "Team1619/Compositron",
"id": "7df5f434457162b8c3ef1708df3cd9cf19d33145",
"size": "4291",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "32129"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<title>Shetland yarns palette picker</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/style.css"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<h1>Shetland yarns palette picker</h1>
<p>This color palette shows Spindrift and Double Knitting yarn colors from
<a href="http://www.jamiesonsofshetland.co.uk">Jamieson's of Shetland</a>. This tool is not affiliated with
Jamieson's in any way.</p>
<h3>How to use this tool</h3>
<ul>
<li>Add yarns to your "selected colors" by clicking on them in the palette</li>
<li>Drag your selected colors to change their order</li>
<li>Hover over a yarn and click the "remove" button to remove it from the selected colors</li>
</ul>
<div class="well" style="overflow:hidden">
<div class="col-xs-12" id="controls">
<button class="btn btn-xs btn-danger clear pull-right">Clear selected colors</button>
</div>
<div class="col-sm-6 col-md-4">
<h2>Color palette</h2>
<ul id="palette">
</ul>
</div>
<div class="col-sm-6 col-md-8">
<h2>Selected colors</h2>
<ul id="selected">
</ul>
</div>
</div>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.min.js"></script>
<script type="text/javascript" src="js/colordragger.js"></script>
</body>
</html>
| {
"content_hash": "2aebe26d05c01894c8ae53cc01ca0067",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 127,
"avg_line_length": 35.089285714285715,
"alnum_prop": 0.5893129770992367,
"repo_name": "jsutcliffe/yarn-color-dragger",
"id": "14c22e2b5321bf2fa0d2c6b6bee2195e39d4bee4",
"size": "1965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1486"
},
{
"name": "HTML",
"bytes": "1965"
},
{
"name": "JavaScript",
"bytes": "3568"
}
],
"symlink_target": ""
} |
package com.facebook.infrastructure.dht;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import com.facebook.infrastructure.io.ICompactSerializer;
import com.facebook.infrastructure.net.Message;
import com.facebook.infrastructure.service.StorageService;
/**
* This class encapsulates the message that needs to be sent to nodes that
* handoff data. The message contains information about the node to be
* bootstrapped and the ranges with which it needs to be bootstrapped.
*/
class BootstrapMetadataMessage {
private static ICompactSerializer<BootstrapMetadataMessage> serializer_;
static {
serializer_ = new BootstrapMetadataMessageSerializer();
}
protected static ICompactSerializer<BootstrapMetadataMessage> serializer() {
return serializer_;
}
protected static Message makeBootstrapMetadataMessage(
BootstrapMetadataMessage bsMetadataMessage) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
BootstrapMetadataMessage.serializer().serialize(bsMetadataMessage, dos);
return new Message(StorageService.getLocalStorageEndPoint(), "",
StorageService.bsMetadataVerbHandler_,
new Object[] { bos.toByteArray() });
}
protected BootstrapMetadata[] bsMetadata_ = new BootstrapMetadata[0];
BootstrapMetadataMessage(BootstrapMetadata[] bsMetadata) {
bsMetadata_ = bsMetadata;
}
}
class BootstrapMetadataMessageSerializer implements
ICompactSerializer<BootstrapMetadataMessage> {
public void serialize(BootstrapMetadataMessage bsMetadataMessage,
DataOutputStream dos) throws IOException {
BootstrapMetadata[] bsMetadata = bsMetadataMessage.bsMetadata_;
int size = (bsMetadata == null) ? 0 : bsMetadata.length;
dos.writeInt(size);
for (BootstrapMetadata bsmd : bsMetadata) {
BootstrapMetadata.serializer().serialize(bsmd, dos);
}
}
public BootstrapMetadataMessage deserialize(DataInputStream dis)
throws IOException {
int size = dis.readInt();
BootstrapMetadata[] bsMetadata = new BootstrapMetadata[size];
for (int i = 0; i < size; ++i) {
bsMetadata[i] = BootstrapMetadata.serializer().deserialize(dis);
}
return new BootstrapMetadataMessage(bsMetadata);
}
}
| {
"content_hash": "449dbdad32190ea4c6f8a13599f1a3a4",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 78,
"avg_line_length": 36.37313432835821,
"alnum_prop": 0.7443578169881001,
"repo_name": "toddlipcon/helenus",
"id": "77810afa7c9e8610498297de29098e980cbe4b26",
"size": "3259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/com/facebook/infrastructure/dht/BootstrapMetadataMessage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1581366"
}
],
"symlink_target": ""
} |
<?php
namespace Gladtur\TagBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File as SFFile;
use Gladtur\TagBundle\Entity\TagCategory;
use Gladtur\TagBundle\Form\TagCategoryType;
/**
* TagCategory controller.
*
* @Route("tagcategory")
*/
class TagCategoryController extends Controller
{
/**
* Lists all TagCategory entities.
*
* @Route("", name="tagcategory")
* @Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('GladturTagBundle:TagCategory')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Finds and displays a TagCategory entity.
*
* @Route("/{id}/show", name="tagcategory_show")
* @Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GladturTagBundle:TagCategory')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find TagCategory entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to create a new TagCategory entity.
*
* @Route("/new", name="tagcategory_new")
* @Template()
*/
public function newAction()
{
$entity = new TagCategory();
$form = $this->createForm(new TagCategoryType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a new TagCategory entity.
*
* @Route("/create", name="tagcategory_create")
* @Method("POST")
* @Template("GladturTagBundle:TagCategory:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new TagCategory();
$form = $this->createForm(new TagCategoryType(), $entity);
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tagcategory', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Displays a form to edit an existing TagCategory entity.
*
* @Route("/{id}/edit", name="tagcategory_edit")
* @Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GladturTagBundle:TagCategory')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find TagCategory entity.');
}
if($entity->getIconFilepath()){
$entity->setIconFilepath(new SFFile($entity->getIconFilepath()));
}
$editForm = $this->createForm(new TagCategoryType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing TagCategory entity.
*
* @Route("/{id}/update", name="tagcategory_update")
* @Method("POST")
* @Template("GladturTagBundle:TagCategory:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
/* $document = new Document();
$editForm = $this->createFormBuilder($document)
->add('iconFilepath')
->add('file')
->getForm();*/
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GladturTagBundle:TagCategory')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find TagCategory entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new TagCategoryType(), $entity);
/*$eIconFile = new \Symfony\Component\HttpFoundation\File\File($entity->image);
$fName = 'aFile.png';
$eIconFile->move(__DIR__ . '/../../../../web/uploads', $fName);*/
// $entity->setIconFilepath($entity->iconFilepath->getClientOriginalName());
//$entity->setIconFilepath('/Users/mortenthorpe/sites/symf21/web/uploads/' . $fName);
$editForm->bind($request);
if ($editForm->isValid()) {
/* $file=$editForm->getData()->getIconFilepath();
$fName = 'aNewFile2' . '.png';
$file->move('/Users/mortenthorpe/sites/gladtur/web/uploads', $fName);
$entity->setIconFilepath('/Users/mortenthorpe/sites/gladtur/web/uploads/' . $fName);*/
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('tagcategory_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a TagCategory entity.
*
* @Route("/{id}/delete", name="tagcategory_delete")
*/
public function deleteAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GladturTagBundle:TagCategory')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find TagCategory entity.');
}
$em->remove($entity);
$em->flush();
return $this->redirect($this->generateUrl('tagcategory'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm();
}
}
| {
"content_hash": "2c33a306873033817fc43c25e8872b5c",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 103,
"avg_line_length": 29.850467289719628,
"alnum_prop": 0.5662179085785849,
"repo_name": "mortenthorpe/gladturdev",
"id": "b7148a6bbe6d3f587f2fd6d70a6dc3bf73abb4eb",
"size": "6388",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/Gladtur/TagBundle/Controller/TagCategoryController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "146"
},
{
"name": "CSS",
"bytes": "120284"
},
{
"name": "HTML",
"bytes": "869934"
},
{
"name": "JavaScript",
"bytes": "2120136"
},
{
"name": "PHP",
"bytes": "973214"
}
],
"symlink_target": ""
} |
Anything you intend to do well must first be planned well. In our case, our intention is to develop a blogging system, so the first step we should take is to design the flow of the application in its entirety. When we have a clear understanding of the our application's process of execution, the subsequent design and coding steps become much easier.
## GOPATH and project settings
Let's proceed by assuming that our GOPATH points to a folder with an ordinary directory name (if not, we can easily set up a suitable directory and set its path as the GOPATH). As we've describe earlier, a GOPATH can contain more than one directory: in Windows, we can set this as an environment variable; in linux/OSX systems, GOPATH can be set using `export`, i.e: `export gopath=/path/to/your/directory`, as long as the directory which GOPATH points to contains the three sub-directories: `pkg`, `bin` and `src`. Below, we've placed the source code of our new project in the `src` directory with the tentative name `beelog`. Here are some screenshots of the Windows environment variables as well as of the directory structure.

Figure 13.1 Setting the GOPATH environment variable

Figure 13.2 The working directory under $gopath/src
## Application flowchart
Our blogging system will be based on the model-view-controller design pattern. MVC is the separation of the application logic from the presentation layer. In practice, when we keep the presentation layer separated, we can drastically reduce the amount of code needed on our web pages.
- Models represent data as well as the rules and logic governing it. In General, a model class will contain functions for removing, inserting and updating database information.
- Views are a representation of the state of a model. A view is usually a page, but in Go, a view can also be a fragment of a page, such as a header or footer. It can also be an RSS feed, or any other type of "page". Go's `template` package provides very good support for view layer functionality.
- Controllers are the glue logic between the model and view layers and encompasses all the intermediary logic necessary for handling HTTP requests and generating Web pages.
The following figure is an overview of the project framework and demonstrates how data will flow through the system:

Figure 13.3 framework data flow
1. Main.go is the application's entry point and initializes some basic resources required to run the blog such as configuration information, listening ports, etc.
2. Routing checks all incoming HTTP requests and, according to the method, URL and parameters, matches it with the corresponding controller action.
3. If the requested resource has already been cached, the application will bypass the usual execution process and return a response directly to the user's browser.
4. Security detection: The application will filter incoming HTTP requests and any other user submitted data before handing it off to the controller.
5. Controller loads models, core libraries, and any other resources required to process specific requests. The controller is primarily responsible for handling business logic.
6. Output the rendered view to be sent to the client's web browser. If caching has been enabled, the first view is cached for future requests to the same resource.
## Directory structure
According to the framework flow we've designed above, our blog project's directory structure should look something like the following:
|——main.go import documents
|——conf configuration files and processing module
|——controllers controller entry
|——models database processing module
|——utils useful function library
|——static static file directory
|——views view gallery
## Framework design
In order to quickly build our blog, we need to develop a minimal framework based on the application we've designed above. The framework should include routing capabilities, support for RESTful controllers, automated template rendering, a logging system, configuration management, and more.
## Summary
This section describes the initial design of our blogging system, from setting up our GOPATH to briefly introducing the MVC pattern. We also looked at the flow of data and the execution sequence of our blogging system. Finally, we designed the structure of our project directory. At this point, we've basically completed the groundwork required for assembling our framework. In the next few sections, we will implement each of the components we've discussed, one by one.
## Links
- [Directory](preface.md)
- Previous section: [Building a web framework](13.0.md)
- Next section: [Customizing routers](13.2.md)
| {
"content_hash": "b616cf5e9c7072cc871f49aeec6847f5",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 732,
"avg_line_length": 80.38333333333334,
"alnum_prop": 0.7810491395397056,
"repo_name": "songqii/build-web-application-with-golang",
"id": "4ccb158566266b6936410bee6d675fa7876c331d",
"size": "4876",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "en/13.1.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "210040"
},
{
"name": "Groovy",
"bytes": "22539"
},
{
"name": "Shell",
"bytes": "1524"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $created</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Thu Oct 23 18:57:41 2014 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_variables';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logVariable('created');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Variable Cross Reference</h3>
<h2><a href="index.html#created">$created</a></h2>
<br><b>Referenced 1 times:</b><ul>
<li><a href="../bonfire/modules/activities/views/reports/view.php.html">/bonfire/modules/activities/views/reports/view.php</a> -> <a href="../bonfire/modules/activities/views/reports/view.php.source.html#l57"> line 57</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Thu Oct 23 18:57:41 2014</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| {
"content_hash": "f1238cc786ab3346a43001d5cac2828e",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 253,
"avg_line_length": 49.29032258064516,
"alnum_prop": 0.668630017452007,
"repo_name": "inputx/code-ref-doc",
"id": "1fee0d22306f373c447f9be80db370f5265a869f",
"size": "4584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bonfire/_variables/created.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "17952"
},
{
"name": "JavaScript",
"bytes": "255489"
}
],
"symlink_target": ""
} |
// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** An interface for the ADT dictionary. (Distinct search keys.)
Listing 18-1
@file DictionaryInterface.h */
#ifndef _DICTIONARY_INTERFACE
#define _DICTIONARY_INTERFACE
#include <exception>
#include <vector>
template<class KeyType, class ItemType>
class DictionaryInterface {
public:
/** Sees whether this dictionary is empty.
@return True if the dictionary is empty;
otherwise returns false. */
virtual bool isEmpty() const = 0;
/** Gets the number of items in this dictionary.
@return The number of items in the dictionary. */
virtual int getNumberOfItems() const = 0;
/** Inserts an item into this dictionary according to the item’s search key.
@pre The search key of the new item differs from all search
keys presently in the dictionary.
@post If the insertion is successful, newItem is in its
proper position within the dictionary.
@param searchKey The search key associated with the item to be inserted.
@param newItem The item to add to the dictionary.
@return True if item was successfully added, or false if not. */
virtual bool add(const KeyType &searchKey, const ItemType &newItem) = 0;
/** Removes an item with the given search key from this dictionary.
@post If the item whose search key equals searchKey existed in the dictionary,
the item was removed.
@param searchKey The search key of the item to be removed.
@return True if the item was successfully removed, or false if not. */
virtual bool remove(const KeyType &searchKey) = 0;
/** Removes all entries from this dictionary. */
virtual void clear() = 0;
/** Retrieves an item with a given search key from a dictionary.
@post If the retrieval is successful, the item is returned.
@param searchKey The search key of the item to be retrieved.
@return The item associated with the search key.
@throw (Default)exception if the item does not exist. */
virtual ItemType getItem(const KeyType &searchKey) const = 0;
/** Sees whether this dictionary contains an item with a given
search key.
@post The dictionary is unchanged.
@param searchKey The search key of the item to be retrieved.
@return True if an item with the given search key exists in the dictionary. */
virtual bool contains(const KeyType &searchKey) const = 0;
/** Traverses this dictionary and calls a given client function once for each item.
@post The given function’s action occurs once for each item in the
dictionary and possibly alters the item.
@param visit A client function. */
virtual void traverse(void visit(ItemType &)) const = 0;
virtual std::vector<ItemType> toVector() const = 0;
}; // end DictionaryInterface
#endif
| {
"content_hash": "0eef8b8e0a9db74a645b9947d046ffbb",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 87,
"avg_line_length": 41.140845070422536,
"alnum_prop": 0.702841492639507,
"repo_name": "kchin168/csc340hw8",
"id": "0a5ca068f91c512812ea6c65b70dd610f40d4b4e",
"size": "2925",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DictionaryInterface.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "16422"
},
{
"name": "CMake",
"bytes": "940"
}
],
"symlink_target": ""
} |
"""
MIT License
Copyright (c) 2017 - 2018 FrostLuma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import datetime
import textwrap
import discord
from mousey import Cog
from mousey.utils import clean_accents, clean_text, human_delta
LOG_INDENT = ' '
def fmt_msg(text, guild):
text = clean_text(text, guild)
if '\n' in text:
return f'\n{textwrap.indent(text, LOG_INDENT)}'
return f' {text}'
class Observer(Cog, depends=['Events', 'State', 'Tasks']):
"""Passively observes Discord events and creates Mod Log entries."""
@discord.utils.cached_property
def log(self):
# we can assume the main ModLog Cog is loaded as it's loaded first in __init__.py
return self.mousey.get_cog('ModLog').log
async def on_member_join(self, member):
_create_delta = (datetime.datetime.utcnow() - member.created_at).total_seconds()
create_delta = human_delta(_create_delta)
is_new = ' \N{SQUARED NEW}' if _create_delta < 60 * 60 * 72 else ''
msg = f'\N{INBOX TRAY} `{member} {member.id}` joined (created `{create_delta}` ago{is_new})'
await self.log(guild=member.guild, event='member_join', message=msg, target=member)
async def on_member_remove(self, member):
if member.id == self.mousey.user.id:
return # Mousey left the guild
_join_delta = (datetime.datetime.utcnow() - member.joined_at).total_seconds()
join_delta = human_delta(_join_delta)
bounced = ' \N{BASKETBALL AND HOOP}' if _join_delta < 60 * 15 else ''
if len(member.roles) > 1:
_roles = ', '.join(clean_accents(x.name) for x in member.roles if not x.is_default())
roles = f', role(s): `{_roles}`'
else:
roles = ''
last_spoken = await self.state.get_last_spoken(member)
if last_spoken is None:
spoken = ''
else:
_spoken = human_delta(last_spoken)
spoken = f', last spoke: `{_spoken}` ago'
msg = f'\N{OUTBOX TRAY} `{member} {member.id}` left (joined `{join_delta}` ago{bounced}{spoken}{roles})'
await self.log(guild=member.guild, event='member_remove', message=msg, target=member)
async def on_member_kick(self, guild, member, moderator, reason):
msg = f'\N{BOXING GLOVE} `{member} {member.id}` kicked\n{self._create_mod_field(moderator, reason)}'
await self.log(guild=guild, event='member_kick', message=msg, target=member)
async def on_user_ban(self, guild, user, moderator, reason):
msg = f'\N{HAMMER} `{user} {user.id}` banned\n{self._create_mod_field(moderator, reason)}'
await self.log(guild=guild, event='member_ban', message=msg, target=user)
async def on_user_unban(self, guild, user, moderator, reason):
msg = f'\N{SPARKLES} `{user} {user.id}` unbanned\n{self._create_mod_field(moderator, reason)}'
await self.log(guild=guild, event='member_unban', message=msg, target=user)
async def on_role_add(self, member, role, moderator, reason):
msg = (
f'\N{GREEN BOOK} `{member} {member.id}` add role `{role} {role.id}`\n'
f'{self._create_mod_field(moderator, reason, require_reason=False)}')
await self.log(guild=member.guild, event='role_add', message=msg, target=member)
async def on_role_remove(self, member, role, moderator, reason):
msg = (
f'\N{ORANGE BOOK} `{member} {member.id}` removed role `{role} {role.id}`\n'
f'{self._create_mod_field(moderator, reason, require_reason=False)}'
)
await self.log(guild=member.guild, event='role_remove', message=msg, target=member)
async def on_voice_join(self, member, state):
msg = (
f'\N{SPEAKER WITH ONE SOUND WAVE} `{member} {member.id}` '
f'connected to `{state.channel} {state.channel.id}`'
)
await self.log(guild=member.guild, event='voice_join', message=msg, target=member)
async def on_voice_move(self, member, before, after):
msg = (
f'\N{SPEAKER WITH ONE SOUND WAVE} `{member} {member.id}` '
f'changed from `{before.channel} {before.channel.id}` to `{after.channel} {after.channel.id}`'
)
await self.log(guild=member.guild, event='voice_move', message=msg, target=member)
async def on_voice_remove(self, member, state):
msg = (
f'\N{TELEPHONE RECEIVER} `{member} {member.id}` '
f'disconnected from `{state.channel} {state.channel.id}`'
)
await self.log(guild=member.guild, event='voice_remove', message=msg, target=member)
async def on_partial_message_edit(self, before, after):
if before.author.bot:
return
msg = f'\N{MEMO} `{before.author} {before.author.id}` message edited in `{before.channel} {before.channel.id}`'
old = fmt_msg(before.content, before.guild)
new = fmt_msg(after.content, before.guild)
msg = f'{msg}\n**before:**{old}\n**after:**{new}'
await self.log(guild=before.guild, event='message_edit', message=msg, target=before.author)
async def on_partial_message_delete(self, message):
if message.author.bot:
return
_msg = f'`{message.author} {message.author.id}` message deleted in `{message.channel} {message.channel.id}`'
content = fmt_msg(message.content, message.guild)
_attachments = '\n'.join(f' <{url}>' for url in message.attachments)
attachments = f'**Attachments:**\n{_attachments}' if _attachments else ''
msg = f'\N{PUT LITTER IN ITS PLACE SYMBOL} {_msg}\n**Content:**{content}\n{attachments}'
await self.log(guild=message.guild, event='message_delete', message=msg, target=message.author)
async def on_partial_message_purge(self, messages):
_msg = f'{len(messages)} messages deleted in `{messages[0].channel} {messages[0].channel.id}`'
archive = await self.tasks.create_archive(messages)
msg = f'\N{PUT LITTER IN ITS PLACE SYMBOL} {_msg}\n**archive:** <{archive}>'
await self.log(guild=messages[0].guild, event='message_delete', message=msg)
async def on_name_change(self, member, before, after):
def fmt_name(data):
# data is a name, discrim pair
return '#'.join((clean_accents(data[0]), data[1]))
before, after = fmt_name(before), fmt_name(after)
msg = f'\N{LOWER LEFT CRAYON} `{member} {member.id}` changed name from `{before}` to `{after}`'
await self.log(guild=member.guild, event='name_change', message=msg, target=member)
async def on_nick_update(self, member, before, after):
if before is not None:
if after is not None:
before, after = clean_accents(before), clean_accents(after)
msg = f'\N{LOWER LEFT BALLPOINT PEN} `{member} {member.id}` changed nick from `{before}` to `{after}`'
else:
msg = f'\N{LOWER LEFT BALLPOINT PEN} `{member} {member.id}` removed nick `{clean_accents(before)}`'
else:
msg = f'\N{LOWER LEFT BALLPOINT PEN} `{member} {member.id}` added nick `{clean_accents(after)}`'
await self.log(guild=member.guild, event='nick_change', message=msg, target=member)
def _create_mod_field(self, moderator, reason, require_reason=True):
moderator = f'{clean_accents(str(moderator))} {moderator.id}' if moderator is not None else 'unknown'
if reason is None and not require_reason:
return f'**moderator:** {moderator}'
reason = clean_accents(reason.strip()) if reason is not None else 'no reason'
reason = f'\n{reason}' if '\n' in reason else reason
return f'**moderator:** {moderator}\n**reason:** {reason}'
| {
"content_hash": "ec59e5538d297ed3d90dc805750b1bfb",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 119,
"avg_line_length": 43.206896551724135,
"alnum_prop": 0.6412039676205677,
"repo_name": "FrostLuma/Mousey",
"id": "0b9a4f4dd318fae95aa77b1ad8865c645c82d4ed",
"size": "8796",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mousey/ext/modlog/observer.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "PLpgSQL",
"bytes": "489"
},
{
"name": "Python",
"bytes": "284988"
}
],
"symlink_target": ""
} |
<component name="libraryTable">
<library name="support-annotations-23.0.1">
<CLASSES>
<root url="jar://C:/softwarethree/extras/android/m2repository/com/android/support/support-annotations/23.0.1/support-annotations-23.0.1.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES>
<root url="jar://C:/softwarethree/extras/android/m2repository/com/android/support/support-annotations/23.0.1/support-annotations-23.0.1-sources.jar!/" />
</SOURCES>
</library>
</component> | {
"content_hash": "3432aa6d3413bbb6f7c8d451ccc83587",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 159,
"avg_line_length": 44.45454545454545,
"alnum_prop": 0.6993865030674846,
"repo_name": "guoxiaozhou/coolweather",
"id": "472deefa981b0f6ac5581b497bb988f921efa8c6",
"size": "489",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/libraries/support_annotations_23_0_1.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "34244"
}
],
"symlink_target": ""
} |
package org.workcraft.plugins.mpsat.tasks;
import org.workcraft.plugins.mpsat.MpsatSynthesisParameters;
import org.workcraft.plugins.shared.tasks.ExternalProcessResult;
import org.workcraft.tasks.Result;
public class MpsatSynthesisChainResult {
private Result<? extends Object> exportResult;
private Result<? extends ExternalProcessResult> punfResult;
private Result<? extends ExternalProcessResult> mpsatResult;
private MpsatSynthesisParameters mpsatSettings;
private String message;
public MpsatSynthesisChainResult(Result<? extends Object> exportResult,
Result<? extends ExternalProcessResult> pcompResult,
Result<? extends ExternalProcessResult> punfResult,
Result<? extends ExternalProcessResult> mpsatResult,
MpsatSynthesisParameters mpsatSettings, String message) {
this.exportResult = exportResult;
this.punfResult = punfResult;
this.mpsatResult = mpsatResult;
this.mpsatSettings = mpsatSettings;
this.message = message;
}
public MpsatSynthesisChainResult(Result<? extends Object> exportResult,
Result<? extends ExternalProcessResult> pcompResult,
Result<? extends ExternalProcessResult> punfResult,
Result<? extends ExternalProcessResult> mpsatResult,
MpsatSynthesisParameters mpsatSettings) {
this(exportResult, pcompResult, punfResult, mpsatResult, mpsatSettings, null);
}
public MpsatSynthesisParameters getMpsatSettings() {
return mpsatSettings;
}
public Result<? extends Object> getExportResult() {
return exportResult;
}
public Result<? extends ExternalProcessResult> getPunfResult() {
return punfResult;
}
public Result<? extends ExternalProcessResult> getMpsatResult() {
return mpsatResult;
}
public String getMessage() {
return message;
}
}
| {
"content_hash": "98080532e338d5535bfcc4fcf227a66a",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 86,
"avg_line_length": 35.09090909090909,
"alnum_prop": 0.7176165803108808,
"repo_name": "jrbeaumont/workcraft",
"id": "450e399929d41db13456e88c46e829ccdc25fa57",
"size": "1930",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MpsatSynthesisPlugin/src/org/workcraft/plugins/mpsat/tasks/MpsatSynthesisChainResult.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "366"
},
{
"name": "GAP",
"bytes": "1153"
},
{
"name": "Java",
"bytes": "5260787"
},
{
"name": "JavaScript",
"bytes": "13422"
},
{
"name": "Shell",
"bytes": "10385"
}
],
"symlink_target": ""
} |
package com.eebbk.joy.joke;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.eebbk.joy.R;
import com.eebbk.joy.dao.JokeDao;
import com.eebbk.joy.utils.JoyConstant;
import com.eebbk.joy.utils.L;
public class JokeAdapter extends BaseAdapter{
private List<JokeInfo> mLists = new ArrayList<JokeInfo>();
private LayoutInflater inflater;
private JokeInfo mJokeInfo;
private JokeDao mJokeDao;
public JokeAdapter(Context context) {
inflater = LayoutInflater.from(context);
L.i("bbb","youBUG");
mJokeDao = new JokeDao(context);
// List<JokeInfo> infos = mJokeDao.getJokeList();
// if(null != infos && infos.size() > 0 ){
// mLists.addAll(infos);
// }
//
//
// for(JokeInfo info:mLists){
// L.i("bbb",info.content);
// }
L.i("bbb","youBUG1");
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mLists.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mLists.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = null;
if(convertView == null){
holder = new Holder();
convertView = inflater.inflate(R.layout.item_joke, null);
holder.content = (TextView) convertView.findViewById(R.id.tv_joke_content_show);
// holder.gifimage = (GifView) convertView.findViewById(R.id.iv_fun_picture_show);
// holder.image = (ImageView) convertView.findViewById(R.id.iv_fun_picture_show);
holder.updatetime = (TextView) convertView.findViewById(R.id.tv_joke_time_show);
convertView.setTag(holder);
}else{
holder = (Holder) convertView.getTag();
}
if(null != mLists && mLists.size() > 0 ){
mJokeInfo = mLists.get(position);
holder.content.setText("\t\t"+mJokeInfo.content);
holder.updatetime.setText(mJokeInfo.updateTime);
}else{
}
return convertView;
}
class Holder{
TextView content;
TextView updatetime;
// ImageView image;
// GifView gifimage;
}
public boolean addList(List<JokeInfo> lists){
if(mLists == null){
return false;
}
boolean added = mLists.addAll(lists);
notifyDataSetChanged();
return added;
}
public boolean clear(){
if(mLists.isEmpty() || mLists == null){
return false;
}
mLists.clear();
notifyDataSetChanged();
return true;
}
public void setList(List<JokeInfo> lists){
if(null == lists || lists.isEmpty()){
return;
}
mLists = lists;
notifyDataSetChanged();
mJokeDao.deleteAll(JoyConstant.JOKE_TYPE_JOKE);
mJokeDao.addAllJoke(lists);
}
public void loadLocalJokes(){
List<JokeInfo> infos = mJokeDao.getJokeList();
if(null != infos && infos.size() > 0 ){
if( infos.size() >= mLists.size() ){
mLists.clear();
mLists.addAll(infos);
}
}
for(JokeInfo info:mLists){
L.i("bbb",info.content);
}
notifyDataSetChanged();
}
}
| {
"content_hash": "91256bd44eb2a878454ce6a0938be448",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 88,
"avg_line_length": 21.572327044025158,
"alnum_prop": 0.6478134110787171,
"repo_name": "jyqqhw/Joy",
"id": "febf0dca95aa8c64884f22e68342f9319fdff89a",
"size": "3430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/eebbk/joy/joke/JokeAdapter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "63536"
}
],
"symlink_target": ""
} |
<?php declare(strict_types = 1);
namespace Adeira\Connector\Common\DomainModel;
interface IStubProcessor
{
public const ORIENTATION_ASC = 'ASC';
public const ORIENTATION_DESC = 'DESC';
//FIXME:
public const HYDRATE_OBJECT = \Doctrine\ORM\AbstractQuery::HYDRATE_OBJECT;
public const HYDRATE_ARRAY = \Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY;
public const HYDRATE_SINGLE_SCALAR = \Doctrine\ORM\AbstractQuery::HYDRATE_SINGLE_SCALAR;
// MANIPULATORS:
public function orientation(string $key, string $direction = self::ORIENTATION_ASC): void;
public function first(int $count): void;
public function after($identifier, string $orientationKey, string $orientationValue): void;
public function applyExpression(\Doctrine\Common\Collections\Expr\Expression $expression): void;
// HYDRATATION:
public function hydrate($hydrationMode = self::HYDRATE_OBJECT);
public function hydrateOne($hydrationMode = self::HYDRATE_OBJECT);
public function hydrateCount();
}
| {
"content_hash": "2eacc6b8901e2a45493d3245cc6d327f",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 97,
"avg_line_length": 28.794117647058822,
"alnum_prop": 0.7711950970377937,
"repo_name": "adeira/connector",
"id": "b453e13dc6ddb0850f1a852eafceba2af340f48c",
"size": "979",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Common/DomainModel/IStubProcessor.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "786"
},
{
"name": "HTML",
"bytes": "2904"
},
{
"name": "PHP",
"bytes": "270182"
},
{
"name": "Shell",
"bytes": "1060"
}
],
"symlink_target": ""
} |
#import <UIKit/UIKit.h>
#import "FSAudioStream.h"
@class FSPlaylistItem;
@class FSAudioController;
@class FSFrequencyDomainAnalyzer;
@class FSFrequencyPlotView;
/**
* The player view controller of the iOS example application.
*
* The view allows the user to control the player. See the
* play:, pause: and seek: actions.
*/
@interface FSPlayerViewController : UIViewController <FSPCMAudioStreamDelegate> {
FSPlaylistItem *_selectedPlaylistItem;
// State
BOOL _paused;
BOOL _shouldStartPlaying;
// UI
NSTimer *_progressUpdateTimer;
NSTimer *_playbackSeekTimer;
double _seekToPoint;
NSURL *_stationURL;
UIBarButtonItem *_infoButton;
FSAudioController *_controller;
}
/**
* If this property is set to true, the stream playback is started
* when the view appears. When the playback starts, the property
* is automatically set to false. For consequent playback requests,
* the flag must be activated again.
*/
@property (nonatomic,assign) BOOL shouldStartPlaying;
/**
* The current (active) playlist item for playback.
*/
@property (nonatomic,strong) FSPlaylistItem *selectedPlaylistItem;
/**
* Reference to the play button.
*/
@property (nonatomic,strong) IBOutlet UIButton *playButton;
/**
* Reference to the pause button.
*/
@property (nonatomic,strong) IBOutlet UIButton *pauseButton;
/**
* Reference to the progress slider.
*/
@property (nonatomic,strong) IBOutlet UISlider *progressSlider;
/**
* Reference to the status label.
*/
@property (nonatomic,strong) IBOutlet UILabel *statusLabel;
/**
* Reference to the label displaying the current playback time.
*/
@property (nonatomic,strong) IBOutlet UILabel *currentPlaybackTime;
/**
* Reference to the audio controller.
*/
@property (nonatomic,strong) FSAudioController *audioController;
/**
* Frequency analyzer.
*/
@property (nonatomic,strong) FSFrequencyDomainAnalyzer *analyzer;
/**
* Reference to the frequency plot.
*/
@property (nonatomic,strong) IBOutlet FSFrequencyPlotView *frequencyPlotView;
/**
* Handles the notification upon the audio stream state change.
*
* @param notification The audio stream state notification.
*/
- (void)audioStreamStateDidChange:(NSNotification *)notification;
/**
* Handles the notification upon entering background.
*
* @param notification The notification.
*/
- (void)applicationDidEnterBackgroundNotification:(NSNotification *)notification;
/**
* Handles the notification upon entering foreground.
*
* @param notification The notification.
*/
- (void)applicationWillEnterForegroundNotification:(NSNotification *)notification;
/**
* Handles remote control events.
* @param receivedEvent The event received.
*/
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent;
/**
* An action for starting the playback of the stream.
*
* @param sender The sender of the action.
*/
- (IBAction)play:(id)sender;
/**
* An action for pausing the stream.
*
* @param sender The sender of the action.
*/
- (IBAction)pause:(id)sender;
/**
* An action for seeking the stream.
*
* @param sender The sender of the action.
*/
- (IBAction)seek:(id)sender;
/**
* An action for opening the station URL.
*
* @param sender The sender of the action.
*/
- (IBAction)openStationUrl:(id)sender;
@end | {
"content_hash": "b4950a270fa1b2e7f193a076c28f3b1d",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 82,
"avg_line_length": 25.58139534883721,
"alnum_prop": 0.7327272727272728,
"repo_name": "iOSTestApps/FreeStreamer",
"id": "d4fe2f343616c1ed6681c303a63ecffee94d3903",
"size": "3446",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FreeStreamerMobile/FSPlayerViewController.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "91657"
},
{
"name": "Objective-C",
"bytes": "173094"
},
{
"name": "Objective-C++",
"bytes": "28124"
},
{
"name": "Ruby",
"bytes": "916"
},
{
"name": "Shell",
"bytes": "826"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.3.1"/>
<title>The Red Matrix: mod/item.php File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="rhash-64.png"/></td>
<td style="padding-left: 0.5em;">
<div id="projectname">The Red Matrix
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.3.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('item_8php.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">item.php File Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a693cd09805755ab85bbb5ecae69a48c3"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="item_8php.html#a693cd09805755ab85bbb5ecae69a48c3">item_post</a> (&$a)</td></tr>
<tr class="separator:a693cd09805755ab85bbb5ecae69a48c3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a764bbb2e9a885a86fb23d0b5e4a09221"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="item_8php.html#a764bbb2e9a885a86fb23d0b5e4a09221">item_content</a> (&$a)</td></tr>
<tr class="separator:a764bbb2e9a885a86fb23d0b5e4a09221"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:abd0e603a6696051af16476eb968d52e7"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="item_8php.html#abd0e603a6696051af16476eb968d52e7">handle_tag</a> ($a, &$body, &$inform, &$str_tags, $profile_uid, $tag)</td></tr>
<tr class="separator:abd0e603a6696051af16476eb968d52e7"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a7b63a9d0cd02096e17dcf11f4afa7c10"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="item_8php.html#a7b63a9d0cd02096e17dcf11f4afa7c10">fix_attached_photo_permissions</a> ($uid, $xchan_hash, $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)</td></tr>
<tr class="separator:a7b63a9d0cd02096e17dcf11f4afa7c10"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3daae7944f737bd30412a0d042207c0f"><td class="memItemLeft" align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><a class="el" href="item_8php.html#a3daae7944f737bd30412a0d042207c0f">fix_attached_file_permissions</a> ($channel, $observer_hash, $body, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny)</td></tr>
<tr class="separator:a3daae7944f737bd30412a0d042207c0f"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a3daae7944f737bd30412a0d042207c0f"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">fix_attached_file_permissions </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$channel</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$observer_hash</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$body</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_contact_allow</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_group_allow</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_contact_deny</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_group_deny</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Referenced by <a class="el" href="item_8php.html#a693cd09805755ab85bbb5ecae69a48c3">item_post()</a>.</p>
</div>
</div>
<a class="anchor" id="a7b63a9d0cd02096e17dcf11f4afa7c10"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">fix_attached_photo_permissions </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$uid</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$xchan_hash</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$body</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_contact_allow</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_group_allow</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_contact_deny</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$str_group_deny</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Referenced by <a class="el" href="item_8php.html#a693cd09805755ab85bbb5ecae69a48c3">item_post()</a>.</p>
</div>
</div>
<a class="anchor" id="abd0e603a6696051af16476eb968d52e7"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">handle_tag </td>
<td>(</td>
<td class="paramtype"> </td>
<td class="paramname"><em>$a</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">& </td>
<td class="paramname"><em>$body</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">& </td>
<td class="paramname"><em>$inform</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">& </td>
<td class="paramname"><em>$str_tags</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$profile_uid</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype"> </td>
<td class="paramname"><em>$tag</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This function removes the tag $tag from the text $body and replaces it with the appropiate link.</p>
<dl class="params"><dt>Parameters</dt><dd>
<table class="params">
<tr><td class="paramtype">unknown_type</td><td class="paramname">$body</td><td>the text to replace the tag in </td></tr>
<tr><td class="paramtype">unknown_type</td><td class="paramname">$inform</td><td>a comma-seperated string containing everybody to inform </td></tr>
<tr><td class="paramtype">unknown_type</td><td class="paramname">$str_tags</td><td>string to add the tag to </td></tr>
<tr><td class="paramtype">unknown_type</td><td class="paramname">$profile_uid</td><td></td></tr>
<tr><td class="paramtype">unknown_type</td><td class="paramname">$tag</td><td>the tag to replace</td></tr>
</table>
</dd>
</dl>
<dl class="section return"><dt>Returns</dt><dd>boolean true if replaced, false if not replaced </dd></dl>
<p>Referenced by <a class="el" href="item_8php.html#a693cd09805755ab85bbb5ecae69a48c3">item_post()</a>.</p>
</div>
</div>
<a class="anchor" id="a764bbb2e9a885a86fb23d0b5e4a09221"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">item_content </td>
<td>(</td>
<td class="paramtype">& </td>
<td class="paramname"><em>$a</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
</div>
</div>
<a class="anchor" id="a693cd09805755ab85bbb5ecae69a48c3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">item_post </td>
<td>(</td>
<td class="paramtype">& </td>
<td class="paramname"><em>$a</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>This is the POST destination for most all locally posted text stuff. This function handles status, wall-to-wall status, local comments, and remote coments that are posted on this site (as opposed to being delivered in a feed). Also processed here are posts and comments coming through the statusnet/twitter API. All of these become an "item" which is our basic unit of information. Posts that originate externally or do not fall into the above posting categories go through <a class="el" href="items_8php.html#a2541e6861a56d145c9281877cc501615">item_store()</a> instead of this function. </p>
<p>Is this a reply to something?</p>
<p>fix naked links by passing through a callback to see if this is a red site (already known to us) which will get a zrl, otherwise link with url</p>
<p>When a photo was uploaded into the message using the (profile wall) ajax uploader, The permissions are initially set to disallow anybody but the owner from seeing it. This is because the permissions may not yet have been set for the post. If it's private, the photo permissions should be set appropriately. But we didn't know the final permissions on the post until now. So now we'll look for links of uploaded messages that are in the post and set them to the same permissions as the post itself.</p>
<p>Fold multi-line [code] sequences</p>
<p>Look for any tags and linkify them</p>
<p>Referenced by <a class="el" href="include_2api_8php.html#a450d8732b7b608f7ac929aee61572b95">api_statuses_mediap()</a>, <a class="el" href="include_2api_8php.html#ae0fa388479cace9c5a7a45b571ab42f8">api_statuses_repeat()</a>, <a class="el" href="include_2api_8php.html#ad4d1634df6b35126552324683caaffa2">api_statuses_update()</a>, and <a class="el" href="oexchange_8php.html#a2d8b785cd7d041a4e6274f5af370cf26">oexchange_content()</a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
| {
"content_hash": "fb1a9c25f739ac7c37acbaf76afd6989",
"timestamp": "",
"source": "github",
"line_count": 349,
"max_line_length": 957,
"avg_line_length": 46.598853868194844,
"alnum_prop": 0.6128635553095985,
"repo_name": "waitman/red",
"id": "5ace8bb7b991ec1bea3d3e874fde7aef11e7b109",
"size": "16263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/html/item_8php.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "17461"
},
{
"name": "CSS",
"bytes": "188262"
},
{
"name": "JavaScript",
"bytes": "762381"
},
{
"name": "PHP",
"bytes": "5461648"
},
{
"name": "Perl",
"bytes": "884"
},
{
"name": "Python",
"bytes": "7747"
},
{
"name": "Shell",
"bytes": "2396"
}
],
"symlink_target": ""
} |
#ifndef _CK_FIFO_H
#define _CK_FIFO_H
#include <ck_cc.h>
#include <ck_md.h>
#include <ck_pr.h>
#include <ck_spinlock.h>
#include <stddef.h>
#ifndef CK_F_FIFO_SPSC
#define CK_F_FIFO_SPSC
struct ck_fifo_spsc_entry {
void *value;
struct ck_fifo_spsc_entry *next;
};
typedef struct ck_fifo_spsc_entry ck_fifo_spsc_entry_t;
struct ck_fifo_spsc {
ck_spinlock_t m_head;
struct ck_fifo_spsc_entry *head;
char pad[CK_MD_CACHELINE - sizeof(struct ck_fifo_spsc_entry *) - sizeof(ck_spinlock_t)];
ck_spinlock_t m_tail;
struct ck_fifo_spsc_entry *tail;
struct ck_fifo_spsc_entry *head_snapshot;
struct ck_fifo_spsc_entry *garbage;
};
typedef struct ck_fifo_spsc ck_fifo_spsc_t;
CK_CC_INLINE static bool
ck_fifo_spsc_enqueue_trylock(struct ck_fifo_spsc *fifo)
{
return ck_spinlock_trylock(&fifo->m_tail);
}
CK_CC_INLINE static void
ck_fifo_spsc_enqueue_lock(struct ck_fifo_spsc *fifo)
{
ck_spinlock_lock(&fifo->m_tail);
return;
}
CK_CC_INLINE static void
ck_fifo_spsc_enqueue_unlock(struct ck_fifo_spsc *fifo)
{
ck_spinlock_unlock(&fifo->m_tail);
return;
}
CK_CC_INLINE static bool
ck_fifo_spsc_dequeue_trylock(struct ck_fifo_spsc *fifo)
{
return ck_spinlock_trylock(&fifo->m_head);
}
CK_CC_INLINE static void
ck_fifo_spsc_dequeue_lock(struct ck_fifo_spsc *fifo)
{
ck_spinlock_lock(&fifo->m_head);
return;
}
CK_CC_INLINE static void
ck_fifo_spsc_dequeue_unlock(struct ck_fifo_spsc *fifo)
{
ck_spinlock_unlock(&fifo->m_head);
return;
}
CK_CC_INLINE static void
ck_fifo_spsc_init(struct ck_fifo_spsc *fifo, struct ck_fifo_spsc_entry *stub)
{
ck_spinlock_init(&fifo->m_head);
ck_spinlock_init(&fifo->m_tail);
stub->next = NULL;
fifo->head = fifo->tail = fifo->head_snapshot = fifo->garbage = stub;
return;
}
CK_CC_INLINE static void
ck_fifo_spsc_deinit(struct ck_fifo_spsc *fifo, struct ck_fifo_spsc_entry **garbage)
{
*garbage = fifo->head;
fifo->head = fifo->tail = NULL;
return;
}
CK_CC_INLINE static void
ck_fifo_spsc_enqueue(struct ck_fifo_spsc *fifo,
struct ck_fifo_spsc_entry *entry,
void *value)
{
entry->value = value;
entry->next = NULL;
/* If stub->next is visible, guarantee that entry is consistent. */
ck_pr_fence_store();
ck_pr_store_ptr(&fifo->tail->next, entry);
fifo->tail = entry;
return;
}
CK_CC_INLINE static bool
ck_fifo_spsc_dequeue(struct ck_fifo_spsc *fifo, void *value)
{
struct ck_fifo_spsc_entry *entry;
/*
* The head pointer is guaranteed to always point to a stub entry.
* If the stub entry does not point to an entry, then the queue is
* empty.
*/
entry = ck_pr_load_ptr(&fifo->head->next);
if (entry == NULL)
return false;
/* If entry is visible, guarantee store to value is visible. */
ck_pr_store_ptr(value, entry->value);
ck_pr_fence_store();
ck_pr_store_ptr(&fifo->head, entry);
return true;
}
/*
* Recycle a node. This technique for recycling nodes is based on
* Dmitriy Vyukov's work.
*/
CK_CC_INLINE static struct ck_fifo_spsc_entry *
ck_fifo_spsc_recycle(struct ck_fifo_spsc *fifo)
{
struct ck_fifo_spsc_entry *garbage;
if (fifo->head_snapshot == fifo->garbage) {
fifo->head_snapshot = ck_pr_load_ptr(&fifo->head);
if (fifo->head_snapshot == fifo->garbage)
return NULL;
}
garbage = fifo->garbage;
fifo->garbage = garbage->next;
return garbage;
}
CK_CC_INLINE static bool
ck_fifo_spsc_isempty(struct ck_fifo_spsc *fifo)
{
struct ck_fifo_spsc_entry *head = ck_pr_load_ptr(&fifo->head);
return ck_pr_load_ptr(&head->next) == NULL;
}
#define CK_FIFO_SPSC_ISEMPTY(f) ((f)->head->next == NULL)
#define CK_FIFO_SPSC_FIRST(f) ((f)->head->next)
#define CK_FIFO_SPSC_NEXT(m) ((m)->next)
#define CK_FIFO_SPSC_SPARE(f) ((f)->head)
#define CK_FIFO_SPSC_FOREACH(fifo, entry) \
for ((entry) = CK_FIFO_SPSC_FIRST(fifo); \
(entry) != NULL; \
(entry) = CK_FIFO_SPSC_NEXT(entry))
#define CK_FIFO_SPSC_FOREACH_SAFE(fifo, entry, T) \
for ((entry) = CK_FIFO_SPSC_FIRST(fifo); \
(entry) != NULL && ((T) = (entry)->next, 1); \
(entry) = (T))
#endif /* CK_F_FIFO_SPSC */
#ifdef CK_F_PR_CAS_PTR_2
#ifndef CK_F_FIFO_MPMC
#define CK_F_FIFO_MPMC
struct ck_fifo_mpmc_entry;
struct ck_fifo_mpmc_pointer {
struct ck_fifo_mpmc_entry *pointer;
char *generation CK_CC_PACKED;
} CK_CC_ALIGN(16);
struct ck_fifo_mpmc_entry {
void *value;
struct ck_fifo_mpmc_pointer next;
};
typedef struct ck_fifo_mpmc_entry ck_fifo_mpmc_entry_t;
struct ck_fifo_mpmc {
struct ck_fifo_mpmc_pointer head;
char pad[CK_MD_CACHELINE - sizeof(struct ck_fifo_mpmc_pointer)];
struct ck_fifo_mpmc_pointer tail;
};
typedef struct ck_fifo_mpmc ck_fifo_mpmc_t;
CK_CC_INLINE static void
ck_fifo_mpmc_init(struct ck_fifo_mpmc *fifo, struct ck_fifo_mpmc_entry *stub)
{
stub->next.pointer = NULL;
stub->next.generation = NULL;
fifo->head.pointer = fifo->tail.pointer = stub;
fifo->head.generation = fifo->tail.generation = NULL;
return;
}
CK_CC_INLINE static void
ck_fifo_mpmc_deinit(struct ck_fifo_mpmc *fifo, struct ck_fifo_mpmc_entry **garbage)
{
*garbage = fifo->head.pointer;
fifo->head.pointer = fifo->tail.pointer = NULL;
return;
}
CK_CC_INLINE static void
ck_fifo_mpmc_enqueue(struct ck_fifo_mpmc *fifo,
struct ck_fifo_mpmc_entry *entry,
void *value)
{
struct ck_fifo_mpmc_pointer tail, next, update;
/*
* Prepare the upcoming node and make sure to commit the updates
* before publishing.
*/
entry->value = value;
entry->next.pointer = NULL;
entry->next.generation = 0;
ck_pr_fence_store_atomic();
for (;;) {
tail.generation = ck_pr_load_ptr(&fifo->tail.generation);
ck_pr_fence_load();
tail.pointer = ck_pr_load_ptr(&fifo->tail.pointer);
next.generation = ck_pr_load_ptr(&tail.pointer->next.generation);
next.pointer = ck_pr_load_ptr(&tail.pointer->next.pointer);
if (ck_pr_load_ptr(&fifo->tail.generation) != tail.generation)
continue;
if (next.pointer != NULL) {
/*
* If the tail pointer has an entry following it then
* it needs to be forwarded to the next entry. This
* helps us guarantee we are always operating on the
* last entry.
*/
update.pointer = next.pointer;
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
} else {
/*
* Attempt to commit new entry to the end of the
* current tail.
*/
update.pointer = entry;
update.generation = next.generation + 1;
if (ck_pr_cas_ptr_2(&tail.pointer->next, &next, &update) == true)
break;
}
}
ck_pr_fence_atomic();
/* After a successful insert, forward the tail to the new entry. */
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
return;
}
CK_CC_INLINE static bool
ck_fifo_mpmc_tryenqueue(struct ck_fifo_mpmc *fifo,
struct ck_fifo_mpmc_entry *entry,
void *value)
{
struct ck_fifo_mpmc_pointer tail, next, update;
entry->value = value;
entry->next.pointer = NULL;
entry->next.generation = 0;
ck_pr_fence_store_atomic();
tail.generation = ck_pr_load_ptr(&fifo->tail.generation);
ck_pr_fence_load();
tail.pointer = ck_pr_load_ptr(&fifo->tail.pointer);
next.generation = ck_pr_load_ptr(&tail.pointer->next.generation);
next.pointer = ck_pr_load_ptr(&tail.pointer->next.pointer);
if (ck_pr_load_ptr(&fifo->tail.generation) != tail.generation)
return false;
if (next.pointer != NULL) {
/*
* If the tail pointer has an entry following it then
* it needs to be forwarded to the next entry. This
* helps us guarantee we are always operating on the
* last entry.
*/
update.pointer = next.pointer;
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
return false;
} else {
/*
* Attempt to commit new entry to the end of the
* current tail.
*/
update.pointer = entry;
update.generation = next.generation + 1;
if (ck_pr_cas_ptr_2(&tail.pointer->next, &next, &update) == false)
return false;
}
ck_pr_fence_atomic();
/* After a successful insert, forward the tail to the new entry. */
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
return true;
}
CK_CC_INLINE static bool
ck_fifo_mpmc_dequeue(struct ck_fifo_mpmc *fifo,
void *value,
struct ck_fifo_mpmc_entry **garbage)
{
struct ck_fifo_mpmc_pointer head, tail, next, update;
for (;;) {
head.generation = ck_pr_load_ptr(&fifo->head.generation);
ck_pr_fence_load();
head.pointer = ck_pr_load_ptr(&fifo->head.pointer);
tail.generation = ck_pr_load_ptr(&fifo->tail.generation);
ck_pr_fence_load();
tail.pointer = ck_pr_load_ptr(&fifo->tail.pointer);
next.generation = ck_pr_load_ptr(&head.pointer->next.generation);
next.pointer = ck_pr_load_ptr(&head.pointer->next.pointer);
update.pointer = next.pointer;
if (head.pointer == tail.pointer) {
/*
* The head is guaranteed to always point at a stub
* entry. If the stub entry has no references then the
* queue is empty.
*/
if (next.pointer == NULL)
return false;
/* Forward the tail pointer if necessary. */
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
} else {
/*
* It is possible for head snapshot to have been
* re-used. Avoid deferencing during enqueue
* re-use.
*/
if (next.pointer == NULL)
continue;
/* Save value before commit. */
*(void **)value = ck_pr_load_ptr(&next.pointer->value);
/* Forward the head pointer to the next entry. */
update.generation = head.generation + 1;
if (ck_pr_cas_ptr_2(&fifo->head, &head, &update) == true)
break;
}
}
*garbage = head.pointer;
return true;
}
CK_CC_INLINE static bool
ck_fifo_mpmc_trydequeue(struct ck_fifo_mpmc *fifo,
void *value,
struct ck_fifo_mpmc_entry **garbage)
{
struct ck_fifo_mpmc_pointer head, tail, next, update;
head.generation = ck_pr_load_ptr(&fifo->head.generation);
ck_pr_fence_load();
head.pointer = ck_pr_load_ptr(&fifo->head.pointer);
tail.generation = ck_pr_load_ptr(&fifo->tail.generation);
ck_pr_fence_load();
tail.pointer = ck_pr_load_ptr(&fifo->tail.pointer);
next.generation = ck_pr_load_ptr(&head.pointer->next.generation);
next.pointer = ck_pr_load_ptr(&head.pointer->next.pointer);
update.pointer = next.pointer;
if (head.pointer == tail.pointer) {
/*
* The head is guaranteed to always point at a stub
* entry. If the stub entry has no references then the
* queue is empty.
*/
if (next.pointer == NULL)
return false;
/* Forward the tail pointer if necessary. */
update.generation = tail.generation + 1;
ck_pr_cas_ptr_2(&fifo->tail, &tail, &update);
return false;
} else {
/*
* It is possible for head snapshot to have been
* re-used. Avoid deferencing during enqueue.
*/
if (next.pointer == NULL)
return false;
/* Save value before commit. */
*(void **)value = ck_pr_load_ptr(&next.pointer->value);
/* Forward the head pointer to the next entry. */
update.generation = head.generation + 1;
if (ck_pr_cas_ptr_2(&fifo->head, &head, &update) == false)
return false;
}
*garbage = head.pointer;
return true;
}
#define CK_FIFO_MPMC_ISEMPTY(f) ((f)->head.pointer->next.pointer == NULL)
#define CK_FIFO_MPMC_FIRST(f) ((f)->head.pointer->next.pointer)
#define CK_FIFO_MPMC_NEXT(m) ((m)->next.pointer)
#define CK_FIFO_MPMC_FOREACH(fifo, entry) \
for ((entry) = CK_FIFO_MPMC_FIRST(fifo); \
(entry) != NULL; \
(entry) = CK_FIFO_MPMC_NEXT(entry))
#define CK_FIFO_MPMC_FOREACH_SAFE(fifo, entry, T) \
for ((entry) = CK_FIFO_MPMC_FIRST(fifo); \
(entry) != NULL && ((T) = (entry)->next.pointer, 1); \
(entry) = (T))
#endif /* CK_F_FIFO_MPMC */
#endif /* CK_F_PR_CAS_PTR_2 */
#endif /* _CK_FIFO_H */
| {
"content_hash": "c7386b6611f3151b86a58a37093d9375",
"timestamp": "",
"source": "github",
"line_count": 450,
"max_line_length": 89,
"avg_line_length": 26.006666666666668,
"alnum_prop": 0.6683756301802957,
"repo_name": "GregBowyer/softheap",
"id": "a65bcfca26d7e44a0f734c7c854c49e4548860eb",
"size": "13090",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ck/include/ck_fifo.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1291199"
},
{
"name": "C++",
"bytes": "84008"
},
{
"name": "Makefile",
"bytes": "33011"
},
{
"name": "Python",
"bytes": "6557"
},
{
"name": "Shell",
"bytes": "282"
}
],
"symlink_target": ""
} |
package org.talend.sdk.component.junit.http.junit5;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toMap;
import static org.junit.Assert.assertEquals;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.apache.ziplock.IO;
import org.junit.jupiter.api.RepeatedTest;
import org.talend.sdk.component.junit.http.api.HttpApiHandler;
import org.talend.sdk.component.junit.http.api.Response;
import org.talend.sdk.component.junit.http.internal.impl.ResponseImpl;
@HttpApi(useSsl = true)
class JUnit5HttpsApiTest {
@HttpApiInject
private HttpApiHandler<?> handler;
@HttpApiName("${class}_${method}")
@RepeatedTest(5) // just ensure it is reentrant
void getProxy() throws Exception {
final Response response = get();
assertEquals(HttpURLConnection.HTTP_OK, response.status());
assertEquals(new String(response.payload()), "worked as expected");
assertEquals("text/plain", response.headers().get("content-type"));
assertEquals("true", response.headers().get("mocked"));
assertEquals("true", response.headers().get("X-Talend-Proxy-JUnit"));
}
private Response get() throws Exception {
final URL url = new URL("https://foo.bar.not.existing.talend.com/component/test?api=true");
final HttpsURLConnection connection = HttpsURLConnection.class.cast(url.openConnection());
connection.setSSLSocketFactory(handler.getSslContext().getSocketFactory());
connection.setConnectTimeout(300000);
connection.setReadTimeout(20000);
connection.connect();
final int responseCode = connection.getResponseCode();
try {
final Map<String, String> headers = connection
.getHeaderFields()
.entrySet()
.stream()
.filter(e -> e.getKey() != null)
.collect(toMap(Map.Entry::getKey, e -> e.getValue().stream().collect(joining(","))));
return new ResponseImpl(headers, responseCode, IO.readBytes(connection.getInputStream()));
} finally {
connection.disconnect();
}
}
}
| {
"content_hash": "ad0362ab62705e703657bbb1b638709b",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 105,
"avg_line_length": 39.6140350877193,
"alnum_prop": 0.6762621789193977,
"repo_name": "chmyga/component-runtime",
"id": "aa2ec1cb32327d93b648728ca5702595425251d2",
"size": "2875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "component-runtime-testing/component-runtime-http-junit/src/test/java/org/talend/sdk/component/junit/http/junit5/JUnit5HttpsApiTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25603"
},
{
"name": "Dockerfile",
"bytes": "6587"
},
{
"name": "Groovy",
"bytes": "47870"
},
{
"name": "HTML",
"bytes": "24797"
},
{
"name": "Java",
"bytes": "3624002"
},
{
"name": "JavaScript",
"bytes": "160759"
},
{
"name": "Shell",
"bytes": "7620"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1470ece59f0dec606e867f60aef6c5e7",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "aa6342521f2b4461981184f35750a1f19fc87397",
"size": "194",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Caucaea/Caucaea phalaenopsis/ Syn. Oncidium cucullatum phalaenopsis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import Wreqr from 'backbone.wreqr';
import Marionette from 'backbone.marionette';
import template from 'templates/overPassTimeoutNotification.ejs';
import Locale from 'core/locale';
export default Marionette.ItemView.extend({
template,
behaviors: {
l20n: {},
notification: {
destroyOnClose: true
}
},
ui: {
notification: '.notification',
content: '.content'
},
initialize() {
this._radio = Wreqr.radio.channel('global');
return this.render();
},
open() {
this.triggerMethod('open');
return this;
},
close() {
this.triggerMethod('close');
return this;
},
onRender() {
this.ui.content.html(
document.l10n.getSync('overpassTimeoutNotification_content', {
name: Locale.getLocalized(this.model, 'name')
})
);
}
});
| {
"content_hash": "725cd85b492b082a11ade8ecb52c63e4",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 68,
"avg_line_length": 18.288888888888888,
"alnum_prop": 0.6318347509113001,
"repo_name": "MapContrib/MapContrib",
"id": "5591e3ae65e967c841511bc545c40bcb0829316a",
"size": "823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/view/overPassTimeoutNotification.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "64484"
},
{
"name": "HTML",
"bytes": "176933"
},
{
"name": "JavaScript",
"bytes": "660933"
},
{
"name": "Shell",
"bytes": "195"
}
],
"symlink_target": ""
} |
using GladNet.Common;
using Lidgren.Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Client
{
public class ServerConnectionDetails : IConnectionDetails
{
public IPEndPoint RemoteConnectionEndpoint { get; private set; }
public long UniqueConnectionId { get; private set; }
public NetConnection InternalNetConnection { get; private set; }
public ServerConnectionDetails(IPEndPoint endPoint, long uniqueConnectionID, NetConnection netConnection)
{
InternalNetConnection = netConnection;
RemoteConnectionEndpoint = endPoint;
UniqueConnectionId = uniqueConnectionID;
}
}
}
| {
"content_hash": "8e72e90542df6bc14f2d201c7e1dd742",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 107,
"avg_line_length": 24.88888888888889,
"alnum_prop": 0.7916666666666666,
"repo_name": "HelloKitty/GladNet",
"id": "469efbd7990da686a4b4e45975dd517f4327f29b",
"size": "674",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Client/ServerConnectionDetails.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Batchfile",
"bytes": "181"
},
{
"name": "C#",
"bytes": "838773"
},
{
"name": "Protocol Buffer",
"bytes": "21880"
},
{
"name": "XSLT",
"bytes": "82915"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4c735d5a77e0e29cc41b6e7948e99d45",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "f76bba1f1d040ca637048f8cdba22628a0a9c2f6",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Dendrobium/Dendrobium sarcophyllum/ Syn. Grastidium sarcophyllum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.