text
stringlengths
2
1.04M
meta
dict
from django.core.cache import cache from django.test import TestCase class PolyaxonBaseTest(TestCase): COLLECT_TASKS = False def setUp(self): # Flush cache cache.clear() # Mock celery default sent task self.mock_send_task() super().setUp() self.worker_send = {} def mock_send_task(self): from celery import current_app def send_task(name, args=(), kwargs=None, **opts): kwargs = kwargs or {} if name in current_app.tasks: task = current_app.tasks[name] return task.apply_async(args, kwargs, **opts) elif self.worker_send: self.worker_send[name] = {"args": args, "kwargs": kwargs, "opts": opts} current_app.send_task = send_task class PolyaxonBaseTestSerializer(PolyaxonBaseTest): query = None serializer_class = None model_class = None factory_class = None expected_keys = {} num_objects = 2 def test_serialize_one(self): raise NotImplementedError def create_one(self): raise NotImplementedError def create_multiple(self): for i in range(self.num_objects): self.create_one() def test_serialize_many(self): self.create_multiple() data = self.serializer_class(self.query.all(), many=True).data assert len(data) == self.num_objects for d in data: assert set(d.keys()) == self.expected_keys
{ "content_hash": "3b4719e5e4ddbea3f6288ade3978643f", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 87, "avg_line_length": 28.056603773584907, "alnum_prop": 0.6005379959650302, "repo_name": "polyaxon/polyaxon", "id": "2db017d763e39949dcd302cccec4f2c5a80e6426", "size": "2092", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/polycommon/polycommon/test_cases/base.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1989" }, { "name": "Python", "bytes": "5201898" }, { "name": "Shell", "bytes": "1565" } ], "symlink_target": "" }
module Text.PrettyPrint.Leijen ( -- * Documents Doc, putDoc, hPutDoc, -- * Basic combinators empty, char, text, (<>), nest, line, linebreak, group, softline, softbreak, -- * Alignment -- -- The combinators in this section can not be described by Wadler's -- original combinators. They align their output relative to the -- current output position - in contrast to @nest@ which always -- aligns to the current nesting level. This deprives these -- combinators from being \`optimal\'. In practice however they -- prove to be very useful. The combinators in this section should -- be used with care, since they are more expensive than the other -- combinators. For example, @align@ shouldn't be used to pretty -- print all top-level declarations of a language, but using @hang@ -- for let expressions is fine. align, hang, indent, encloseSep, list, tupled, semiBraces, -- * Operators (<+>), (Text.PrettyPrint.Leijen.<$>), (</>), (<$$>), (<//>), -- * List combinators hsep, vsep, fillSep, sep, hcat, vcat, fillCat, cat, punctuate, -- * Fillers fill, fillBreak, -- * Bracketing combinators enclose, squotes, dquotes, parens, angles, braces, brackets, -- * Character documents lparen, rparen, langle, rangle, lbrace, rbrace, lbracket, rbracket, squote, dquote, semi, colon, comma, space, dot, backslash, equals, -- * Primitive type documents string, int, integer, float, double, rational, -- * Pretty class Pretty(..), -- * Rendering SimpleDoc(..), renderPretty, renderCompact, displayS, displayIO -- * Undocumented , bool , column, nesting, width ) where import System.IO (Handle,hPutStr,hPutChar,stdout) infixr 5 </>,<//>,<$>,<$$> infixr 6 <>,<+> ----------------------------------------------------------- -- list, tupled and semiBraces pretty print a list of -- documents either horizontally or vertically aligned. ----------------------------------------------------------- -- | The document @(list xs)@ comma separates the documents @xs@ and -- encloses them in square brackets. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. list :: [Doc] -> Doc list = encloseSep lbracket rbracket comma -- | The document @(tupled xs)@ comma separates the documents @xs@ and -- encloses them in parenthesis. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All comma separators are put in front of the elements. tupled :: [Doc] -> Doc tupled = encloseSep lparen rparen comma -- | The document @(semiBraces xs)@ separates the documents @xs@ with -- semi colons and encloses them in braces. The documents are rendered -- horizontally if that fits the page. Otherwise they are aligned -- vertically. All semi colons are put in front of the elements. semiBraces :: [Doc] -> Doc semiBraces = encloseSep lbrace rbrace semi -- | The document @(encloseSep l r sep xs)@ concatenates the documents -- @xs@ separated by @sep@ and encloses the resulting document by @l@ -- and @r@. The documents are rendered horizontally if that fits the -- page. Otherwise they are aligned vertically. All separators are put -- in front of the elements. For example, the combinator 'list' can be -- defined with @encloseSep@: -- -- > list xs = encloseSep lbracket rbracket comma xs -- > test = text "list" <+> (list (map int [10,200,3000])) -- -- Which is layed out with a page width of 20 as: -- -- @ -- list [10,200,3000] -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- list [10 -- ,200 -- ,3000] -- @ encloseSep :: Doc -> Doc -> Doc -> [Doc] -> Doc encloseSep left right sep ds = case ds of [] -> left <> right [d] -> left <> d <> right _ -> align (cat (zipWith (<>) (left : repeat sep) ds) <> right) ----------------------------------------------------------- -- punctuate p [d1,d2,...,dn] => [d1 <> p,d2 <> p, ... ,dn] ----------------------------------------------------------- -- | @(punctuate p xs)@ concatenates all documents in @xs@ with -- document @p@ except for the last document. -- -- > someText = map text ["words","in","a","tuple"] -- > test = parens (align (cat (punctuate comma someText))) -- -- This is layed out on a page width of 20 as: -- -- @ -- (words,in,a,tuple) -- @ -- -- But when the page width is 15, it is layed out as: -- -- @ -- (words, -- in, -- a, -- tuple) -- @ -- -- (If you want put the commas in front of their elements instead of -- at the end, you should use 'tupled' or, in general, 'encloseSep'.) punctuate :: Doc -> [Doc] -> [Doc] punctuate p [] = [] punctuate p [d] = [d] punctuate p (d:ds) = (d <> p) : punctuate p ds ----------------------------------------------------------- -- high-level combinators ----------------------------------------------------------- -- | The document @(sep xs)@ concatenates all documents @xs@ either -- horizontally with @(\<+\>)@, if it fits the page, or vertically with -- @(\<$\>)@. -- -- > sep xs = group (vsep xs) sep :: [Doc] -> Doc sep = group . vsep -- | The document @(fillSep xs)@ concatenates documents @xs@ -- horizontally with @(\<+\>)@ as long as its fits the page, than -- inserts a @line@ and continues doing that for all documents in -- @xs@. -- -- > fillSep xs = foldr (\<\/\>) empty xs fillSep :: [Doc] -> Doc fillSep = fold (</>) -- | The document @(hsep xs)@ concatenates all documents @xs@ -- horizontally with @(\<+\>)@. hsep :: [Doc] -> Doc hsep = fold (<+>) -- | The document @(vsep xs)@ concatenates all documents @xs@ -- vertically with @(\<$\>)@. If a 'group' undoes the line breaks -- inserted by @vsep@, all documents are separated with a space. -- -- > someText = map text (words ("text to lay out")) -- > -- > test = text "some" <+> vsep someText -- -- This is layed out as: -- -- @ -- some text -- to -- lay -- out -- @ -- -- The 'align' combinator can be used to align the documents under -- their first element -- -- > test = text "some" <+> align (vsep someText) -- -- Which is printed as: -- -- @ -- some text -- to -- lay -- out -- @ vsep :: [Doc] -> Doc vsep = fold (Text.PrettyPrint.Leijen.<$>) -- | The document @(cat xs)@ concatenates all documents @xs@ either -- horizontally with @(\<\>)@, if it fits the page, or vertically with -- @(\<$$\>)@. -- -- > cat xs = group (vcat xs) cat :: [Doc] -> Doc cat = group . vcat -- | The document @(fillCat xs)@ concatenates documents @xs@ -- horizontally with @(\<\>)@ as long as its fits the page, than inserts -- a @linebreak@ and continues doing that for all documents in @xs@. -- -- > fillCat xs = foldr (\<\/\/\>) empty xs fillCat :: [Doc] -> Doc fillCat = fold (<//>) -- | The document @(hcat xs)@ concatenates all documents @xs@ -- horizontally with @(\<\>)@. hcat :: [Doc] -> Doc hcat = fold (<>) -- | The document @(vcat xs)@ concatenates all documents @xs@ -- vertically with @(\<$$\>)@. If a 'group' undoes the line breaks -- inserted by @vcat@, all documents are directly concatenated. vcat :: [Doc] -> Doc vcat = fold (<$$>) fold f [] = empty fold f ds = foldr1 f ds -- | The document @(x \<\> y)@ concatenates document @x@ and document -- @y@. It is an associative operation having 'empty' as a left and -- right unit. (infixr 6) (<>) :: Doc -> Doc -> Doc x <> y = x `beside` y -- | The document @(x \<+\> y)@ concatenates document @x@ and @y@ with a -- @space@ in between. (infixr 6) (<+>) :: Doc -> Doc -> Doc x <+> y = x <> space <> y -- | The document @(x \<\/\> y)@ concatenates document @x@ and @y@ with a -- 'softline' in between. This effectively puts @x@ and @y@ either -- next to each other (with a @space@ in between) or underneath each -- other. (infixr 5) (</>) :: Doc -> Doc -> Doc x </> y = x <> softline <> y -- | The document @(x \<\/\/\> y)@ concatenates document @x@ and @y@ with -- a 'softbreak' in between. This effectively puts @x@ and @y@ either -- right next to each other or underneath each other. (infixr 5) (<//>) :: Doc -> Doc -> Doc x <//> y = x <> softbreak <> y -- | The document @(x \<$\> y)@ concatenates document @x@ and @y@ with a -- 'line' in between. (infixr 5) (<$>) :: Doc -> Doc -> Doc x <$> y = x <> line <> y -- | The document @(x \<$$\> y)@ concatenates document @x@ and @y@ with -- a @linebreak@ in between. (infixr 5) (<$$>) :: Doc -> Doc -> Doc x <$$> y = x <> linebreak <> y -- | The document @softline@ behaves like 'space' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softline = group line softline :: Doc softline = group line -- | The document @softbreak@ behaves like 'empty' if the resulting -- output fits the page, otherwise it behaves like 'line'. -- -- > softbreak = group linebreak softbreak :: Doc softbreak = group linebreak -- | Document @(squotes x)@ encloses document @x@ with single quotes -- \"'\". squotes :: Doc -> Doc squotes = enclose squote squote -- | Document @(dquotes x)@ encloses document @x@ with double quotes -- '\"'. dquotes :: Doc -> Doc dquotes = enclose dquote dquote -- | Document @(braces x)@ encloses document @x@ in braces, \"{\" and -- \"}\". braces :: Doc -> Doc braces = enclose lbrace rbrace -- | Document @(parens x)@ encloses document @x@ in parenthesis, \"(\" -- and \")\". parens :: Doc -> Doc parens = enclose lparen rparen -- | Document @(angles x)@ encloses document @x@ in angles, \"\<\" and -- \"\>\". angles :: Doc -> Doc angles = enclose langle rangle -- | Document @(brackets x)@ encloses document @x@ in square brackets, -- \"[\" and \"]\". brackets :: Doc -> Doc brackets = enclose lbracket rbracket -- | The document @(enclose l r x)@ encloses document @x@ between -- documents @l@ and @r@ using @(\<\>)@. -- -- > enclose l r x = l <> x <> r enclose :: Doc -> Doc -> Doc -> Doc enclose l r x = l <> x <> r -- | The document @lparen@ contains a left parenthesis, \"(\". lparen :: Doc lparen = char '(' -- | The document @rparen@ contains a right parenthesis, \")\". rparen :: Doc rparen = char ')' -- | The document @langle@ contains a left angle, \"\<\". langle :: Doc langle = char '<' -- | The document @rangle@ contains a right angle, \">\". rangle :: Doc rangle = char '>' -- | The document @lbrace@ contains a left brace, \"{\". lbrace :: Doc lbrace = char '{' -- | The document @rbrace@ contains a right brace, \"}\". rbrace :: Doc rbrace = char '}' -- | The document @lbracket@ contains a left square bracket, \"[\". lbracket :: Doc lbracket = char '[' -- | The document @rbracket@ contains a right square bracket, \"]\". rbracket :: Doc rbracket = char ']' -- | The document @squote@ contains a single quote, \"'\". squote :: Doc squote = char '\'' -- | The document @dquote@ contains a double quote, '\"'. dquote :: Doc dquote = char '"' -- | The document @semi@ contains a semi colon, \";\". semi :: Doc semi = char ';' -- | The document @colon@ contains a colon, \":\". colon :: Doc colon = char ':' -- | The document @comma@ contains a comma, \",\". comma :: Doc comma = char ',' -- | The document @space@ contains a single space, \" \". -- -- > x <+> y = x <> space <> y space :: Doc space = char ' ' -- | The document @dot@ contains a single dot, \".\". dot :: Doc dot = char '.' -- | The document @backslash@ contains a back slash, \"\\\". backslash :: Doc backslash = char '\\' -- | The document @equals@ contains an equal sign, \"=\". equals :: Doc equals = char '=' ----------------------------------------------------------- -- Combinators for prelude types ----------------------------------------------------------- -- string is like "text" but replaces '\n' by "line" -- | The document @(string s)@ concatenates all characters in @s@ -- using @line@ for newline characters and @char@ for all other -- characters. It is used instead of 'text' whenever the text contains -- newline characters. string :: String -> Doc string "" = empty string ('\n':s) = line <> string s string s = case (span (/='\n') s) of (xs,ys) -> text xs <> string ys bool :: Bool -> Doc bool b = text (show b) -- | The document @(int i)@ shows the literal integer @i@ using -- 'text'. int :: Int -> Doc int i = text (show i) -- | The document @(integer i)@ shows the literal integer @i@ using -- 'text'. integer :: Integer -> Doc integer i = text (show i) -- | The document @(float f)@ shows the literal float @f@ using -- 'text'. float :: Float -> Doc float f = text (show f) -- | The document @(double d)@ shows the literal double @d@ using -- 'text'. double :: Double -> Doc double d = text (show d) -- | The document @(rational r)@ shows the literal rational @r@ using -- 'text'. rational :: Rational -> Doc rational r = text (show r) ----------------------------------------------------------- -- overloading "pretty" ----------------------------------------------------------- -- | The member @prettyList@ is only used to define the @instance Pretty -- a => Pretty [a]@. In normal circumstances only the @pretty@ function -- is used. class Pretty a where pretty :: a -> Doc prettyList :: [a] -> Doc prettyList = list . map pretty instance Pretty a => Pretty [a] where pretty = prettyList instance Pretty Doc where pretty = id instance Pretty () where pretty () = text "()" instance Pretty Bool where pretty b = bool b instance Pretty Char where pretty c = char c prettyList s = string s instance Pretty Int where pretty i = int i instance Pretty Integer where pretty i = integer i instance Pretty Float where pretty f = float f instance Pretty Double where pretty d = double d --instance Pretty Rational where -- pretty r = rational r instance (Pretty a,Pretty b) => Pretty (a,b) where pretty (x,y) = tupled [pretty x, pretty y] instance (Pretty a,Pretty b,Pretty c) => Pretty (a,b,c) where pretty (x,y,z)= tupled [pretty x, pretty y, pretty z] instance Pretty a => Pretty (Maybe a) where pretty Nothing = empty pretty (Just x) = pretty x ----------------------------------------------------------- -- semi primitive: fill and fillBreak ----------------------------------------------------------- -- | The document @(fillBreak i x)@ first renders document @x@. It -- than appends @space@s until the width is equal to @i@. If the -- width of @x@ is already larger than @i@, the nesting level is -- increased by @i@ and a @line@ is appended. When we redefine @ptype@ -- in the previous example to use @fillBreak@, we get a useful -- variation of the previous output: -- -- > ptype (name,tp) -- > = fillBreak 6 (text name) <+> text "::" <+> text tp -- -- The output will now be: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak -- :: Doc -- @ fillBreak :: Int -> Doc -> Doc fillBreak f x = width x (\w -> if (w > f) then nest f linebreak else text (spaces (f - w))) -- | The document @(fill i x)@ renders document @x@. It than appends -- @space@s until the width is equal to @i@. If the width of @x@ is -- already larger, nothing is appended. This combinator is quite -- useful in practice to output a list of bindings. The following -- example demonstrates this. -- -- > types = [("empty","Doc") -- > ,("nest","Int -> Doc -> Doc") -- > ,("linebreak","Doc")] -- > -- > ptype (name,tp) -- > = fill 6 (text name) <+> text "::" <+> text tp -- > -- > test = text "let" <+> align (vcat (map ptype types)) -- -- Which is layed out as: -- -- @ -- let empty :: Doc -- nest :: Int -> Doc -> Doc -- linebreak :: Doc -- @ fill :: Int -> Doc -> Doc fill f d = width d (\w -> if (w >= f) then empty else text (spaces (f - w))) width :: Doc -> (Int -> Doc) -> Doc width d f = column (\k1 -> d <> column (\k2 -> f (k2 - k1))) ----------------------------------------------------------- -- semi primitive: Alignment and indentation ----------------------------------------------------------- -- | The document @(indent i x)@ indents document @x@ with @i@ spaces. -- -- > test = indent 4 (fillSep (map text -- > (words "the indent combinator indents these words !"))) -- -- Which lays out with a page width of 20 as: -- -- @ -- the indent -- combinator -- indents these -- words ! -- @ indent :: Int -> Doc -> Doc indent i d = hang i (text (spaces i) <> d) -- | The hang combinator implements hanging indentation. The document -- @(hang i x)@ renders document @x@ with a nesting level set to the -- current column plus @i@. The following example uses hanging -- indentation for some text: -- -- > test = hang 4 (fillSep (map text -- > (words "the hang combinator indents these words !"))) -- -- Which lays out on a page with a width of 20 characters as: -- -- @ -- the hang combinator -- indents these -- words ! -- @ -- -- The @hang@ combinator is implemented as: -- -- > hang i x = align (nest i x) hang :: Int -> Doc -> Doc hang i d = align (nest i d) -- | The document @(align x)@ renders document @x@ with the nesting -- level set to the current column. It is used for example to -- implement 'hang'. -- -- As an example, we will put a document right above another one, -- regardless of the current nesting level: -- -- > x $$ y = align (x <$> y) -- -- > test = text "hi" <+> (text "nice" $$ text "world") -- -- which will be layed out as: -- -- @ -- hi nice -- world -- @ align :: Doc -> Doc align d = column (\k -> nesting (\i -> nest (k - i) d)) --nesting might be negative :-) ----------------------------------------------------------- -- Primitives ----------------------------------------------------------- -- | The abstract data type @Doc@ represents pretty documents. -- -- @Doc@ is an instance of the 'Show' class. @(show doc)@ pretty -- prints document @doc@ with a page width of 100 characters and a -- ribbon width of 40 characters. -- -- > show (text "hello" <$> text "world") -- -- Which would return the string \"hello\\nworld\", i.e. -- -- @ -- hello -- world -- @ data Doc = Empty | Char Char -- invariant: char is not '\n' | Text !Int String -- invariant: text doesn't contain '\n' | Line !Bool -- True <=> when undone by group, do not insert a space | Cat Doc Doc | Nest !Int Doc | Union Doc Doc -- invariant: first lines of first doc longer than the first lines of the second doc | Column (Int -> Doc) | Nesting (Int -> Doc) -- | The data type @SimpleDoc@ represents rendered documents and is -- used by the display functions. -- -- The @Int@ in @SText@ contains the length of the string. The @Int@ -- in @SLine@ contains the indentation for that line. The library -- provides two default display functions 'displayS' and -- 'displayIO'. You can provide your own display function by writing a -- function from a @SimpleDoc@ to your own output format. data SimpleDoc = SEmpty | SChar Char SimpleDoc | SText !Int String SimpleDoc | SLine !Int SimpleDoc -- | The empty document is, indeed, empty. Although @empty@ has no -- content, it does have a \'height\' of 1 and behaves exactly like -- @(text \"\")@ (and is therefore not a unit of @\<$\>@). empty :: Doc empty = Empty -- | The document @(char c)@ contains the literal character @c@. The -- character shouldn't be a newline (@'\n'@), the function 'line' -- should be used for line breaks. char :: Char -> Doc char '\n' = line char c = Char c -- | The document @(text s)@ contains the literal string @s@. The -- string shouldn't contain any newline (@'\n'@) characters. If the -- string contains newline characters, the function 'string' should be -- used. text :: String -> Doc text "" = Empty text s = Text (length s) s -- | The @line@ document advances to the next line and indents to the -- current nesting level. Document @line@ behaves like @(text \" \")@ -- if the line break is undone by 'group'. line :: Doc line = Line False -- | The @linebreak@ document advances to the next line and indents to -- the current nesting level. Document @linebreak@ behaves like -- 'empty' if the line break is undone by 'group'. linebreak :: Doc linebreak = Line True beside x y = Cat x y -- | The document @(nest i x)@ renders document @x@ with the current -- indentation level increased by i (See also 'hang', 'align' and -- 'indent'). -- -- > nest 2 (text "hello" <$> text "world") <$> text "!" -- -- outputs as: -- -- @ -- hello -- world -- ! -- @ nest :: Int -> Doc -> Doc nest i x = Nest i x column, nesting :: (Int -> Doc) -> Doc column f = Column f nesting f = Nesting f -- | The @group@ combinator is used to specify alternative -- layouts. The document @(group x)@ undoes all line breaks in -- document @x@. The resulting line is added to the current line if -- that fits the page. Otherwise, the document @x@ is rendered without -- any changes. group :: Doc -> Doc group x = Union (flatten x) x flatten :: Doc -> Doc flatten (Cat x y) = Cat (flatten x) (flatten y) flatten (Nest i x) = Nest i (flatten x) flatten (Line break) = if break then Empty else Text 1 " " flatten (Union x y) = flatten x flatten (Column f) = Column (flatten . f) flatten (Nesting f) = Nesting (flatten . f) flatten other = other --Empty,Char,Text ----------------------------------------------------------- -- Renderers ----------------------------------------------------------- ----------------------------------------------------------- -- renderPretty: the default pretty printing algorithm ----------------------------------------------------------- -- list of indentation/document pairs; saves an indirection over [(Int,Doc)] data Docs = Nil | Cons !Int Doc Docs -- | This is the default pretty printer which is used by 'show', -- 'putDoc' and 'hPutDoc'. @(renderPretty ribbonfrac width x)@ renders -- document @x@ with a page width of @width@ and a ribbon width of -- @(ribbonfrac * width)@ characters. The ribbon width is the maximal -- amount of non-indentation characters on a line. The parameter -- @ribbonfrac@ should be between @0.0@ and @1.0@. If it is lower or -- higher, the ribbon width will be 0 or @width@ respectively. renderPretty :: Float -> Int -> Doc -> SimpleDoc renderPretty rfrac w x = best 0 0 (Cons 0 x Nil) where -- r :: the ribbon width in characters r = max 0 (min w (round (fromIntegral w * rfrac))) -- best :: n = indentation of current line -- k = current column -- (ie. (k >= n) && (k - n == count of inserted characters) best n k Nil = SEmpty best n k (Cons i d ds) = case d of Empty -> best n k ds Char c -> let k' = k+1 in seq k' (SChar c (best n k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (best n k' ds)) Line _ -> SLine i (best i i ds) Cat x y -> best n k (Cons i x (Cons i y ds)) Nest j x -> let i' = i+j in seq i' (best n k (Cons i' x ds)) Union x y -> nicest n k (best n k (Cons i x ds)) (best n k (Cons i y ds)) Column f -> best n k (Cons i (f k) ds) Nesting f -> best n k (Cons i (f i) ds) --nicest :: r = ribbon width, w = page width, -- n = indentation of current line, k = current column -- x and y, the (simple) documents to chose from. -- precondition: first lines of x are longer than the first lines of y. nicest n k x y | fits width x = x | otherwise = y where width = min (w - k) (r - k + n) fits w x | w < 0 = False fits w SEmpty = True fits w (SChar c x) = fits (w - 1) x fits w (SText l s x) = fits (w - l) x fits w (SLine i x) = True ----------------------------------------------------------- -- renderCompact: renders documents without indentation -- fast and fewer characters output, good for machines ----------------------------------------------------------- -- | @(renderCompact x)@ renders document @x@ without adding any -- indentation. Since no \'pretty\' printing is involved, this -- renderer is very fast. The resulting output contains fewer -- characters than a pretty printed version and can be used for output -- that is read by other programs. renderCompact :: Doc -> SimpleDoc renderCompact x = scan 0 [x] where scan k [] = SEmpty scan k (d:ds) = case d of Empty -> scan k ds Char c -> let k' = k+1 in seq k' (SChar c (scan k' ds)) Text l s -> let k' = k+l in seq k' (SText l s (scan k' ds)) Line _ -> SLine 0 (scan 0 ds) Cat x y -> scan k (x:y:ds) Nest j x -> scan k (x:ds) Union x y -> scan k (y:ds) Column f -> scan k (f k:ds) Nesting f -> scan k (f 0:ds) ----------------------------------------------------------- -- Displayers: displayS and displayIO ----------------------------------------------------------- -- | @(displayS simpleDoc)@ takes the output @simpleDoc@ from a -- rendering function and transforms it to a 'ShowS' type (for use in -- the 'Show' class). -- -- > showWidth :: Int -> Doc -> String -- > showWidth w x = displayS (renderPretty 0.4 w x) "" displayS :: SimpleDoc -> ShowS displayS SEmpty = id displayS (SChar c x) = showChar c . displayS x displayS (SText l s x) = showString s . displayS x displayS (SLine i x) = showString ('\n':indentation i) . displayS x -- | @(displayIO handle simpleDoc)@ writes @simpleDoc@ to the file -- handle @handle@. This function is used for example by 'hPutDoc': -- -- > hPutDoc handle doc = displayIO handle (renderPretty 0.4 100 doc) displayIO :: Handle -> SimpleDoc -> IO () displayIO handle simpleDoc = display simpleDoc where display SEmpty = return () display (SChar c x) = do{ hPutChar handle c; display x} display (SText l s x) = do{ hPutStr handle s; display x} display (SLine i x) = do{ hPutStr handle ('\n':indentation i); display x} ----------------------------------------------------------- -- default pretty printers: show, putDoc and hPutDoc ----------------------------------------------------------- instance Show Doc where showsPrec d doc = displayS (renderPretty 0.4 80 doc) -- | The action @(putDoc doc)@ pretty prints document @doc@ to the -- standard output, with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main :: IO () -- > main = do{ putDoc (text "hello" <+> text "world") } -- -- Which would output -- -- @ -- hello world -- @ putDoc :: Doc -> IO () putDoc doc = hPutDoc stdout doc -- | @(hPutDoc handle doc)@ pretty prints document @doc@ to the file -- handle @handle@ with a page width of 100 characters and a ribbon -- width of 40 characters. -- -- > main = do{ handle <- openFile "MyFile" WriteMode -- > ; hPutDoc handle (vcat (map text -- > ["vertical","text"])) -- > ; hClose handle -- > } hPutDoc :: Handle -> Doc -> IO () hPutDoc handle doc = displayIO handle (renderPretty 0.4 80 doc) ----------------------------------------------------------- -- insert spaces -- "indentation" used to insert tabs but tabs seem to cause -- more trouble than they solve :-) ----------------------------------------------------------- spaces n | n <= 0 = "" | otherwise = replicate n ' ' indentation n = spaces n --indentation n | n >= 8 = '\t' : indentation (n-8) -- | otherwise = spaces n -- LocalWords: PPrint combinators Wadler Wadler's encloseSep
{ "content_hash": "0ede5d9818070b1f17c5f29953e75aa9", "timestamp": "", "source": "github", "line_count": 900, "max_line_length": 124, "avg_line_length": 32.17111111111111, "alnum_prop": 0.5545347793051046, "repo_name": "bergmark/wl-pprint", "id": "b35700235d886681d9282480ac45f0e41f269d8f", "size": "31293", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Text/PrettyPrint/Leijen.hs", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Haskell", "bytes": "31368" } ], "symlink_target": "" }
'use strict'; angular.module('kaleoProject', [ 'ui.bootstrap', 'ui.router', 'selectize' ]) .config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $stateProvider.state({ name: 'default', url: '/', templateUrl: 'app/partials/search.html' }); $stateProvider.state({ name: '404', url: '/404', templateUrl: 'app/partials/404.html' }); $urlRouterProvider .when('/', 'default') .otherwise('404'); }]) .run(['$state', '$rootScope', function($state, $rootScope) { $state.transitionTo('default'); }]) .controller('mainCtrl', ['$scope', '$location', function($scope, $location) { $scope.getClass = function(path) { if ($location.path().substr(0, path.length) === path) { return 'active'; } else { return ''; } }; } ]);
{ "content_hash": "66dc81c1d02c95ed278581f46b356b38", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 99, "avg_line_length": 28.31578947368421, "alnum_prop": 0.46189591078066916, "repo_name": "fezimmer89/kaleoChallenge", "id": "4fb2bef2fa7cd86ffc45405f5b1a10622274dfc9", "size": "1076", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3083" }, { "name": "HTML", "bytes": "9010" }, { "name": "JavaScript", "bytes": "15592" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Copyright (c) 2001-2004 World Wide Web Consortium, (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. This program is distributed under the W3C's Software Intellectual Property License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See W3C License http://www.w3.org/Consortium/Legal/ for more details. --><!DOCTYPE test SYSTEM "dom1.dtd"> <test xmlns="http://www.w3.org/2001/DOM-Test-Suite/Level-1" name="nodecdatasectionnodeattribute"> <metadata> <title>nodeCDATASectionNodeAttribute</title> <creator>NIST</creator> <description> The "getAttributes()" method invoked on a CDATASection Node returns null. Retrieve the CDATASection node contained inside the second child of the second employee and invoke the "getAttributes()" method on the CDATASection node. It should return null. </description> <contributor>Mary Brady</contributor> <date qualifier="created">2001-08-17</date> <!--attributes attribute --> <subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-84CF096"/> <!-- CDATASection interface --> <subject resource="http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-667469212"/> </metadata> <var name="doc" type="Document"/> <var name="elementList" type="NodeList"/> <var name="cdataName" type="Element"/> <var name="cdataNode" type="Node"/> <var name="attrList" type="NamedNodeMap"/> <var name="nodeType" type="int"/> <load var="doc" href="staff" willBeModified="false"/> <getElementsByTagName interface="Document" obj="doc" var="elementList" tagname="&quot;name&quot;"/> <item interface="NodeList" obj="elementList" index="1" var="cdataName"/> <lastChild interface="Node" obj="cdataName" var="cdataNode"/> <nodeType var="nodeType" obj="cdataNode"/> <if><notEquals actual="nodeType" expected="4" ignoreCase="false"/> <createCDATASection var="cdataNode" obj="doc" data='""'/> </if> <attributes obj="cdataNode" var="attrList"/> <assertNull actual="attrList" id="cdataSection"/> </test>
{ "content_hash": "45a2fe0a48039649dc04b2cdea2bf643", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 100, "avg_line_length": 44.44, "alnum_prop": 0.7542754275427542, "repo_name": "reznikmm/matreshka", "id": "69d7c5bd381ae0746252af11a00ae303d27d9e94", "size": "2222", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "testsuite/xml/DOM-Test-Suite/level1/core/nodecdatasectionnodeattribute.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "77822094" }, { "name": "C", "bytes": "50705" }, { "name": "CSS", "bytes": "2253" }, { "name": "HTML", "bytes": "780653" }, { "name": "JavaScript", "bytes": "24113" }, { "name": "Lex", "bytes": "117165" }, { "name": "Makefile", "bytes": "27341" }, { "name": "Perl", "bytes": "4796" }, { "name": "Python", "bytes": "10482" }, { "name": "Roff", "bytes": "13069" }, { "name": "Shell", "bytes": "3034" }, { "name": "TeX", "bytes": "116491" }, { "name": "XSLT", "bytes": "6108" }, { "name": "Yacc", "bytes": "96865" } ], "symlink_target": "" }
Professional portfolio for Jeff Torres
{ "content_hash": "85b89ed4fe43bf1fb8d7d54a575196d7", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 38, "avg_line_length": 39, "alnum_prop": 0.8717948717948718, "repo_name": "ilikesounds/jt_portfolio", "id": "e727bcd7f9666ffcbe270e8a19b334c5c63a4e33", "size": "54", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "31615" }, { "name": "JavaScript", "bytes": "329108" }, { "name": "Python", "bytes": "21799" } ], "symlink_target": "" }
/* crypto/ec/ecp_mont.c */ /* * Originally written by Bodo Moeller for the OpenSSL project. */ /* ==================================================================== * Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * Portions of this software developed by SUN MICROSYSTEMS, INC., * and contributed to the OpenSSL project. */ #include <openssl/err.h> #include "ec_lcl.h" const EC_METHOD *EC_GFp_mont_method(void) { static const EC_METHOD ret = { EC_FLAGS_DEFAULT_OCT, NID_X9_62_prime_field, ec_GFp_mont_group_init, ec_GFp_mont_group_finish, ec_GFp_mont_group_clear_finish, ec_GFp_mont_group_copy, ec_GFp_mont_group_set_curve, ec_GFp_simple_group_get_curve, ec_GFp_simple_group_get_degree, ec_GFp_simple_group_check_discriminant, ec_GFp_simple_point_init, ec_GFp_simple_point_finish, ec_GFp_simple_point_clear_finish, ec_GFp_simple_point_copy, ec_GFp_simple_point_set_to_infinity, ec_GFp_simple_set_Jprojective_coordinates_GFp, ec_GFp_simple_get_Jprojective_coordinates_GFp, ec_GFp_simple_point_set_affine_coordinates, ec_GFp_simple_point_get_affine_coordinates, 0, 0, 0, ec_GFp_simple_add, ec_GFp_simple_dbl, ec_GFp_simple_invert, ec_GFp_simple_is_at_infinity, ec_GFp_simple_is_on_curve, ec_GFp_simple_cmp, ec_GFp_simple_make_affine, ec_GFp_simple_points_make_affine, 0 /* mul */ , 0 /* precompute_mult */ , 0 /* have_precompute_mult */ , ec_GFp_mont_field_mul, ec_GFp_mont_field_sqr, 0 /* field_div */ , ec_GFp_mont_field_encode, ec_GFp_mont_field_decode, ec_GFp_mont_field_set_to_one }; return &ret; } int ec_GFp_mont_group_init(EC_GROUP *group) { int ok; ok = ec_GFp_simple_group_init(group); group->field_data1 = NULL; group->field_data2 = NULL; return ok; } void ec_GFp_mont_group_finish(EC_GROUP *group) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; ec_GFp_simple_group_finish(group); } void ec_GFp_mont_group_clear_finish(EC_GROUP *group) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_clear_free(group->field_data2); group->field_data2 = NULL; ec_GFp_simple_group_clear_finish(group); } int ec_GFp_mont_group_copy(EC_GROUP *dest, const EC_GROUP *src) { BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; BN_clear_free(dest->field_data2); dest->field_data2 = NULL; if (!ec_GFp_simple_group_copy(dest, src)) return 0; if (src->field_data1 != NULL) { dest->field_data1 = BN_MONT_CTX_new(); if (dest->field_data1 == NULL) return 0; if (!BN_MONT_CTX_copy(dest->field_data1, src->field_data1)) goto err; } if (src->field_data2 != NULL) { dest->field_data2 = BN_dup(src->field_data2); if (dest->field_data2 == NULL) goto err; } return 1; err: BN_MONT_CTX_free(dest->field_data1); dest->field_data1 = NULL; return 0; } int ec_GFp_mont_group_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { BN_CTX *new_ctx = NULL; BN_MONT_CTX *mont = NULL; BIGNUM *one = NULL; int ret = 0; BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) return 0; } mont = BN_MONT_CTX_new(); if (mont == NULL) goto err; if (!BN_MONT_CTX_set(mont, p, ctx)) { ECerr(EC_F_EC_GFP_MONT_GROUP_SET_CURVE, ERR_R_BN_LIB); goto err; } one = BN_new(); if (one == NULL) goto err; if (!BN_to_montgomery(one, BN_value_one(), mont, ctx)) goto err; group->field_data1 = mont; mont = NULL; group->field_data2 = one; one = NULL; ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx); if (!ret) { BN_MONT_CTX_free(group->field_data1); group->field_data1 = NULL; BN_free(group->field_data2); group->field_data2 = NULL; } err: BN_CTX_free(new_ctx); BN_MONT_CTX_free(mont); return ret; } int ec_GFp_mont_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_MUL, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, b, group->field_data1, ctx); } int ec_GFp_mont_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_SQR, EC_R_NOT_INITIALIZED); return 0; } return BN_mod_mul_montgomery(r, a, a, group->field_data1, ctx); } int ec_GFp_mont_field_encode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_ENCODE, EC_R_NOT_INITIALIZED); return 0; } return BN_to_montgomery(r, a, (BN_MONT_CTX *)group->field_data1, ctx); } int ec_GFp_mont_field_decode(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { if (group->field_data1 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_DECODE, EC_R_NOT_INITIALIZED); return 0; } return BN_from_montgomery(r, a, group->field_data1, ctx); } int ec_GFp_mont_field_set_to_one(const EC_GROUP *group, BIGNUM *r, BN_CTX *ctx) { if (group->field_data2 == NULL) { ECerr(EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE, EC_R_NOT_INITIALIZED); return 0; } if (!BN_copy(r, group->field_data2)) return 0; return 1; }
{ "content_hash": "eedfd5690ad7bebb170ccd83f852ebbf", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 78, "avg_line_length": 31.46594982078853, "alnum_prop": 0.61100353115389, "repo_name": "vbloodv/blood", "id": "af914aa5975b6d6f082cc994acc533742462b3fe", "size": "8779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "extern/openssl.orig/crypto/ec/ecp_mont.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "96920" }, { "name": "C++", "bytes": "280112" }, { "name": "CMake", "bytes": "12573" }, { "name": "Python", "bytes": "9874" } ], "symlink_target": "" }
/** * @class Ext.chart.series.sprite.Pie3DPart * @extends Ext.draw.sprite.Path * * Pie3D series sprite. */ Ext.define('Ext.chart.series.sprite.Pie3DPart', { extend: 'Ext.draw.sprite.Path', mixins: { markerHolder: 'Ext.chart.MarkerHolder' }, alias: 'sprite.pie3dPart', type: 'pie3dPart', inheritableStatics: { def: { processors: { /** * @cfg {Number} [centerX=0] The central point of the series on the x-axis. */ centerX: 'number', /** * @cfg {Number} [centerY=0] The central point of the series on the x-axis. */ centerY: 'number', /** * @cfg {Number} [startAngle=0] The starting angle of the polar series. */ startAngle: 'number', /** * @cfg {Number} [endAngle=Math.PI] The ending angle of the polar series. */ endAngle: 'number', /** * @cfg {Number} [startRho=0] The starting radius of the polar series. */ startRho: 'number', /** * @cfg {Number} [endRho=150] The ending radius of the polar series. */ endRho: 'number', /** * @cfg {Number} [margin=0] Margin from the center of the pie. Used for donut. */ margin: 'number', /** * @cfg {Number} [thickness=0] The thickness of the 3D pie part. */ thickness: 'number', /** * @cfg {Number} [distortion=0] The distortion of the 3D pie part. */ distortion: 'number', /** * @cfg {Object} [baseColor='white'] The color of the 3D pie part before adding the 3D effect. */ baseColor: 'color', /** * @cfg {Number} [baseRotation=0] The starting rotation of the polar series. */ baseRotation: 'number', /** * @cfg {String} [part='top'] The part of the 3D Pie represented by the sprite. */ part: 'enums(top,start,end,inner,outer)' }, aliases: { rho: 'endRho' }, triggers: { centerX: 'path,bbox', centerY: 'path,bbox', startAngle: 'path,partZIndex', endAngle: 'path,partZIndex', startRho: 'path', endRho: 'path,bbox', margin: 'path,bbox', thickness: 'path', baseRotation: 'path,partZIndex', baseColor: 'partZIndex,partColor', part: 'path,partZIndex' }, defaults: { centerX: 0, centerY: 0, startAngle: 0, endAngle: 0, startRho: 0, endRho: 150, margin: 0, distortion: 1, baseRotation: 0, baseColor: 'white', miterLimit: 1, part: 'top' }, updaters: { partColor: function (attr) { var color = Ext.draw.Color.fly(attr.baseColor), fillStyle; switch (attr.part) { case 'top': fillStyle = color.toString(); break; case 'outer': fillStyle = Ext.create('Ext.draw.gradient.Linear', { type: 'linear', stops: [ { offset: 0, color: color.createDarker(0.3).toString() }, { offset: 0.3, color: color.toString() }, { offset: 0.8, color: color.createLighter(0.2).toString() }, { offset: 1, color: color.createDarker(0.4).toString() } ] }); break; case 'start': fillStyle = color.createDarker(0.3).toString(); break; case 'end': fillStyle = color.createDarker(0.3).toString(); break; case 'inner': fillStyle = Ext.create('Ext.draw.gradient.Linear', { type: 'linear', stops: [ { offset: 0, color: color.createDarker(0.4).toString() }, { offset: 0.2, color: color.createLighter(0.2).toString() }, { offset: 0.7, color: color.toString() }, { offset: 1, color: color.createDarker(0.3).toString() } ] }); break; } attr.fillStyle = fillStyle; attr.canvasAttributes.fillStyle = fillStyle; }, partZIndex: function (attr) { var rotation = attr.baseRotation, midAngle = (attr.startAngle + attr.endAngle) * 0.5, depth = Math.sin(midAngle + rotation); switch (attr.part) { case 'top': attr.zIndex = 5; break; case 'outer': attr.zIndex = 4 + depth; break; case 'start': attr.zIndex = 1 + Math.sin(attr.startAngle + rotation); break; case 'end': attr.zIndex = 1 + Math.sin(attr.endAngle + rotation); break; case 'inner': attr.zIndex = 1 + depth; break; } attr.dirtyZIndex = true; } } } }, updatePlainBBox: function (plain) { var attr = this.attr, rho = attr.part === 'inner' ? attr.startRho : attr.endRho; plain.width = rho * 2; plain.height = rho * attr.distortion * 2 + attr.thickness; plain.x = attr.centerX - rho; plain.y = attr.centerY - rho * attr.distortion; }, updateTransformedBBox: function (transform) { return this.updatePlainBBox(transform); }, updatePath: function (path) { if (this.attr.endAngle < this.attr.startAngle) { return; } this[this.attr.part + 'Renderer'](path); }, topRenderer: function (path) { var attr = this.attr, margin = attr.margin, distortion = attr.distortion, centerX = attr.centerX, centerY = attr.centerY, baseRotation = attr.baseRotation, startAngle = attr.startAngle + baseRotation, endAngle = attr.endAngle + baseRotation, midAngle = (startAngle + endAngle) * 0.5, startRho = attr.startRho, endRho = attr.endRho, sinEnd = Math.sin(endAngle), cosEnd = Math.cos(endAngle); centerX += Math.cos(midAngle) * margin; centerY += Math.sin(midAngle) * margin * distortion; path.ellipse(centerX, centerY, startRho, startRho * distortion, 0, startAngle, endAngle, false); path.lineTo(centerX + cosEnd * endRho, centerY + sinEnd * endRho * distortion); path.ellipse(centerX, centerY, endRho, endRho * distortion, 0, endAngle, startAngle, true); path.closePath(); }, startRenderer: function (path) { var attr = this.attr, margin = attr.margin, centerX = attr.centerX, centerY = attr.centerY, distortion = attr.distortion, baseRotation = attr.baseRotation, startAngle = attr.startAngle + baseRotation , endAngle = attr.endAngle + baseRotation, thickness = attr.thickness, startRho = attr.startRho, endRho = attr.endRho, sinStart = Math.sin(startAngle), cosStart = Math.cos(startAngle), midAngle; if (cosStart < 0) { midAngle = (startAngle + endAngle) * 0.5; centerX += Math.cos(midAngle) * margin; centerY += Math.sin(midAngle) * margin * distortion; path.moveTo(centerX + cosStart * startRho, centerY + sinStart * startRho * distortion); path.lineTo(centerX + cosStart * endRho, centerY + sinStart * endRho * distortion); path.lineTo(centerX + cosStart * endRho, centerY + sinStart * endRho * distortion + thickness); path.lineTo(centerX + cosStart * startRho, centerY + sinStart * startRho * distortion + thickness); path.closePath(); } }, endRenderer: function (path) { var attr = this.attr, margin = attr.margin, centerX = attr.centerX, centerY = attr.centerY, distortion = attr.distortion, baseRotation = attr.baseRotation, startAngle = attr.startAngle + baseRotation , endAngle = attr.endAngle + baseRotation, thickness = attr.thickness, startRho = attr.startRho, endRho = attr.endRho, sin = Math.sin(endAngle), cos = Math.cos(endAngle), midAngle; if (cos > 0) { midAngle = (startAngle + endAngle) * 0.5; centerX += Math.cos(midAngle) * margin; centerY += Math.sin(midAngle) * margin * distortion; path.moveTo(centerX + cos * startRho, centerY + sin * startRho * distortion); path.lineTo(centerX + cos * endRho, centerY + sin * endRho * distortion); path.lineTo(centerX + cos * endRho, centerY + sin * endRho * distortion + thickness); path.lineTo(centerX + cos * startRho, centerY + sin * startRho * distortion + thickness); path.closePath(); } }, innerRenderer: function (path) { var attr = this.attr, margin = attr.margin, centerX = attr.centerX, centerY = attr.centerY, distortion = attr.distortion, baseRotation = attr.baseRotation, startAngle = attr.startAngle + baseRotation , endAngle = attr.endAngle + baseRotation, midAngle = (startAngle + endAngle) * 0.5, thickness = attr.thickness, startRho = attr.startRho, isTranslucent = attr.globalAlpha < 1, sinEnd, cosEnd, tempStart, tempEnd; centerX += Math.cos(midAngle) * margin; centerY += Math.sin(midAngle) * margin * distortion; if (startAngle >= Math.PI * 2 || isTranslucent) { startAngle -= Math.PI * 2; endAngle -= Math.PI * 2; } if (endAngle > Math.PI && endAngle < Math.PI * 3 || isTranslucent) { tempStart = startAngle; tempEnd = Math.min(endAngle, Math.PI * 2); sinEnd = Math.sin(tempEnd); cosEnd = Math.cos(tempEnd); path.ellipse(centerX, centerY, startRho, startRho * distortion, 0, tempStart, tempEnd, false); path.lineTo(centerX + cosEnd * startRho, centerY + sinEnd * startRho * distortion + thickness); path.ellipse(centerX, centerY + thickness, startRho, startRho * distortion, 0, tempEnd, tempStart, true); path.closePath(); } if (endAngle > Math.PI * 3) { tempStart = Math.PI; tempEnd = endAngle; sinEnd = Math.sin(tempEnd); cosEnd = Math.cos(tempEnd); path.ellipse(centerX, centerY, startRho, startRho * distortion, 0, tempStart, tempEnd, false); path.lineTo(centerX + cosEnd * startRho, centerY + sinEnd * startRho * distortion + thickness); path.ellipse(centerX, centerY + thickness, startRho, startRho * distortion, 0, tempEnd, tempStart, true); path.closePath(); } }, outerRenderer: function (path) { var attr = this.attr, margin = attr.margin, centerX = attr.centerX, centerY = attr.centerY, distortion = attr.distortion, baseRotation = attr.baseRotation, startAngle = attr.startAngle + baseRotation , endAngle = attr.endAngle + baseRotation, midAngle = (startAngle + endAngle) * 0.5, thickness = attr.thickness, endRho = attr.endRho, isTranslucent = attr.globalAlpha < 1, sinEnd, cosEnd, tempStart, tempEnd; centerX += Math.cos(midAngle) * margin; centerY += Math.sin(midAngle) * margin * distortion; if (startAngle >= Math.PI * 2 || isTranslucent) { startAngle -= Math.PI * 4; endAngle -= Math.PI * 4; } if (startAngle < Math.PI || isTranslucent) { tempStart = startAngle; tempEnd = Math.min(endAngle, Math.PI); sinEnd = Math.sin(tempEnd); cosEnd = Math.cos(tempEnd); path.ellipse(centerX, centerY, endRho, endRho * distortion, 0, tempStart, tempEnd, false); path.lineTo(centerX + cosEnd * endRho, centerY + sinEnd * endRho * distortion + thickness); path.ellipse(centerX, centerY + thickness, endRho, endRho * distortion, 0, tempEnd, tempStart, true); path.closePath(); } if (endAngle > Math.PI * 2) { tempStart = Math.max(startAngle, Math.PI * 2); tempEnd = endAngle; sinEnd = Math.sin(tempEnd); cosEnd = Math.cos(tempEnd); path.ellipse(centerX, centerY, endRho, endRho * distortion, 0, tempStart, tempEnd, false); path.lineTo(centerX + cosEnd * endRho, centerY + sinEnd * endRho * distortion + thickness); path.ellipse(centerX, centerY + thickness, endRho, endRho * distortion, 0, tempEnd, tempStart, true); path.closePath(); } } });
{ "content_hash": "2fa023b9901c47aebe7ecbf792395e98", "timestamp": "", "source": "github", "line_count": 389, "max_line_length": 117, "avg_line_length": 40.42416452442159, "alnum_prop": 0.4507472178060413, "repo_name": "devmaster-terian/hwt-backend", "id": "afb3224403b8907b84f3534e433958034f90b404", "size": "15725", "binary": false, "copies": "21", "ref": "refs/heads/master", "path": "gestion/recurso/framework/ext-5.1.3/packages/sencha-charts/src/chart/series/sprite/Pie3DPart.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "8940" }, { "name": "ApacheConf", "bytes": "14" }, { "name": "CSS", "bytes": "75609178" }, { "name": "HTML", "bytes": "4905468" }, { "name": "JavaScript", "bytes": "67293340" }, { "name": "PHP", "bytes": "19336265" }, { "name": "Python", "bytes": "38400" }, { "name": "Ruby", "bytes": "15395" } ], "symlink_target": "" }
============================ OSPC Multi-Country Tax Model ============================ This repository includes the data used to calibrate the model along with all the necessary Python code to solve and simulate. The Model ========= This project builds, calibrates and simulates the effects of changes in various taxes on multiple economies in the context of a dynamic overlapping generations general equilibrium model. This project builds on the work of Fehr et al. (2008), Fehr et al. (2011), Fehr et al. (2013) and Benzell et al. (2015). Laurence J. Kotlikoff of Boston University has been a major contributor to those papers and to this project. Disclaimer ========== The model is currently under development. Users should be forewarned that the model componenents could change significantly. Therefore, there is NO GUARANTEE OF ACCURACY. THE CODE SHOULD NOT CURRENTLY BE USED FOR PUBLICATIONS, JOURNAL ARTICLES, OR RESEARCH PURPOSES. Essentially, you should assume the calculations are unreliable until we finish the code re-architecture and have checked the results against other existing implementations of the tax code. The package will have released versions, which will be checked against existing code prior to release. Stay tuned for an upcoming release! Current Contributors ==================== - Richard W. Evans (University of Chicago) - James Olmstead (Brigham Young University) - Kerk Phillips (Brigham Young University) Contributors to Earlier Work ============================ - Seth Benzell (Boston University) - Jeff Clawson (University of Maryland) - Laurence J. Kotlikoff (Boston University) - Keena Li (Brigham Young University) About OSPC ========== The Open-Source Policy Center (OSPC) seeks to make policy analysis more transparent, trustworthy, and collaborative by harnessing open-source methods to build cutting-edge economic models.
{ "content_hash": "aec99cdca7d635807a87c3e089cfbb22", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 594, "avg_line_length": 49.5, "alnum_prop": 0.7453482190324295, "repo_name": "kerkphil/multi-country", "id": "37ad9626fcbbcf7445228848bdb752f46107f425", "size": "1881", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "172" }, { "name": "Python", "bytes": "719635" }, { "name": "TeX", "bytes": "57744" } ], "symlink_target": "" }
C $Header$ C $Name$ #ifndef ECCO_CPPOPTIONS_H #define ECCO_CPPOPTIONS_H C C CPP flags controlling which code is included in the files that C will be compiled. C ******************************************************************** C *** Adjoint Support Package *** C ******************************************************************** C o Include/exclude code in order to be able to automatically C differentiate the MITgcmUV by using the Tangent Linear and C Adjoint Model Compiler (TAMC). #define ALLOW_AUTODIFF_TAMC C >>> Checkpointing as handled by TAMC #define ALLOW_TAMC_CHECKPOINTING C >>> Extract adjoint state #undef ALLOW_AUTODIFF_MONITOR C >>> DO 2-level checkpointing instead of 3-level #undef AUTODIFF_2_LEVEL_CHECKPOINT C o use divided adjoint to split adjoint computations #undef ALLOW_DIVIDED_ADJOINT C ******************************************************************** C *** Cost function Package *** C ******************************************************************** C >>> Cost function contributions #define ALLOW_COST_TEST C ******************************************************************** C *** Control vector Package *** C ******************************************************************** #undef EXCLUDE_CTRL_PACK #undef ALLOW_NONDIMENSIONAL_CONTROL_IO C >>> Initial values. #define ALLOW_GENARR2D_CONTROL #define ALLOW_GENTIM2D_CONTROL #endif /* ECCO_CPPOPTIONS_H */
{ "content_hash": "e184907216fe84fe20ab5de124046ef9", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 70, "avg_line_length": 31.32, "alnum_prop": 0.48659003831417624, "repo_name": "altMITgcm/MITgcm66h", "id": "71b955fd18b825e1ccb8decf91b4b44498e06ea8", "size": "1566", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "verification/halfpipe_streamice/code_ad/ECCO_CPPOPTIONS.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1131380" }, { "name": "C++", "bytes": "84807" }, { "name": "ColdFusion", "bytes": "1596" }, { "name": "Fortran", "bytes": "14325997" }, { "name": "HTML", "bytes": "117757" }, { "name": "M", "bytes": "9906" }, { "name": "Makefile", "bytes": "36504" }, { "name": "Mathematica", "bytes": "1639" }, { "name": "Matlab", "bytes": "915987" }, { "name": "Objective-C", "bytes": "1289569" }, { "name": "Perl", "bytes": "59438" }, { "name": "Perl 6", "bytes": "2528" }, { "name": "Python", "bytes": "320243" }, { "name": "Shell", "bytes": "139458" }, { "name": "TeX", "bytes": "31173" }, { "name": "Terra", "bytes": "3909" } ], "symlink_target": "" }
(function() { 'use strict'; angular .module('boardGamesApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('user-management', { parent: 'admin', url: '/user-management?page&sort', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'BoardGames' }, views: { 'content@': { templateUrl: 'app/admin/user-management/user-management.html', controller: 'UserManagementController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true } }, resolve: { pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) { return { page: PaginationUtil.parsePage($stateParams.page), sort: $stateParams.sort, predicate: PaginationUtil.parsePredicate($stateParams.sort), ascending: PaginationUtil.parseAscending($stateParams.sort) }; }] } }) .state('user-management-detail', { parent: 'admin', url: '/user/:login', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'BoardGames' }, views: { 'content@': { templateUrl: 'app/admin/user-management/user-management-detail.html', controller: 'UserManagementDetailController', controllerAs: 'vm' } } }) .state('user-management.new', { parent: 'user-management', url: '/new', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-dialog.html', controller: 'UserManagementDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: function () { return { id: null, login: null, firstName: null, lastName: null, email: null, activated: true, langKey: null, createdBy: null, createdDate: null, lastModifiedBy: null, lastModifiedDate: null, resetDate: null, resetKey: null, authorities: null }; } } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('user-management'); }); }] }) .state('user-management.edit', { parent: 'user-management', url: '/{login}/edit', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-dialog.html', controller: 'UserManagementDialogController', controllerAs: 'vm', backdrop: 'static', size: 'lg', resolve: { entity: ['User', function(User) { return User.get({login : $stateParams.login}); }] } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('user-management.delete', { parent: 'user-management', url: '/{login}/delete', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/admin/user-management/user-management-delete-dialog.html', controller: 'UserManagementDeleteController', controllerAs: 'vm', size: 'md', resolve: { entity: ['User', function(User) { return User.get({login : $stateParams.login}); }] } }).result.then(function() { $state.go('user-management', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
{ "content_hash": "cde7768634a03d192e2b534bb6810a48", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 106, "avg_line_length": 39.07142857142857, "alnum_prop": 0.4113345521023766, "repo_name": "simpleliving40/boardgamers", "id": "090f80445b07e08c1b1a9ef744e159d77afb268a", "size": "5470", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/webapp/app/admin/user-management/user-management.state.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "5006" }, { "name": "CSS", "bytes": "10453" }, { "name": "HTML", "bytes": "123081" }, { "name": "Java", "bytes": "336074" }, { "name": "JavaScript", "bytes": "187865" }, { "name": "Scala", "bytes": "3582" }, { "name": "Shell", "bytes": "7058" } ], "symlink_target": "" }
var chai = require('chai'); var expect = chai.expect; var sinon = require('sinon'); var sinonChai = require("sinon-chai"); var chaiAsPromised = require('chai-as-promised'); var process = require('child_process'); var mockSpawn = require('mock-spawn'); chai.use(sinonChai); chai.use(chaiAsPromised); describe('Playbook command', function () { var mySpawn = mockSpawn(); var oldSpawn = process.spawn; var spawnSpy; before(function () { process.spawn = mySpawn; spawnSpy = sinon.spy(process, 'spawn'); }) beforeEach(function() { spawnSpy.reset(); }) var Playbook = require("../index").Playbook; describe('with only playbook', function () { it('should execute the playbook', function (done) { var command = new Playbook().playbook('test'); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml'], {}); done(); }).done(); }) }) describe('with variables', function () { it('should execute the playbook with the given variables', function (done) { var command = new Playbook().playbook('test').variables({foo: "bar"}); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-e', '{"foo":"bar"}'], {}); done(); }).done(); }) it('should execute the playbook with the given complex variables', function (done) { variable = { foo: { bar: ["shu"] } }; var command = new Playbook().playbook('test').variables(variable); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-e', '{"foo":{"bar":["shu"]}}'], {}); done(); }).done(); }) }) describe('with forks', function() { it('should execute the playbook with forks param as specified', function (done) { var command = new Playbook().playbook('test').forks(10); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-f', 10], {}); done(); }).done(); }) }) describe('with verbose', function() { it('should execute the playbook with verbosity level', function (done) { var command = new Playbook().playbook('test').verbose("vv"); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-vv'], {}); done(); }).done(); }) }) describe('with user', function() { it('should execute the playbook with specified user', function (done) { var command = new Playbook().playbook('test').user("root"); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-u', 'root'], {}); done(); }).done(); }) }) describe('with sudo user specified', function() { it('should execute the playbook with specified sudo user', function (done) { var command = new Playbook().playbook('test').su("root"); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-U', 'root'], {}); done(); }).done(); }) }) describe('as sudo user', function() { it('should execute the playbook with sudo user flag', function (done) { var command = new Playbook().playbook('test').asSudo(); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '-s'], {}); done(); }).done(); }) }) describe('with inventory', function() { it('should execute the playbook with specified inventory', function (done) { var command = new Playbook().playbook('test').inventory("/etc/my/hosts"); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook' ,['test.yml', '-i', '/etc/my/hosts'], {}); done(); }).done(); }) }) describe('with working directory', function () { var path = require('path'); it('should change to working directory during execution', function (done) { var command = new Playbook().playbook('test'); var workingDir = path.resolve(__dirname, './fixtures'); var promise = command.exec({cwd: workingDir}); expect(promise).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml'], {cwd: workingDir}); done(); }).done(); }) }) describe('with --ask-pass flag', function() { it('should execute the playbook with --ask-pass flag', function (done) { var command = new Playbook().playbook('test').askPass(); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '--ask-pass'], {}); done(); }).done(); }) }) describe('with --ask-sudo-pass flag', function() { it('should execute the playbook with --ask-sudo-pass flag', function (done) { var command = new Playbook().playbook('test').askSudoPass(); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '--ask-sudo-pass'], {}); done(); }).done(); }) }) describe('with --tags param', function() { it('should execute the playbook with --tags', function (done) { var command = new Playbook().playbook('test').tags('onetag'); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', "--tags=onetag"], {}); done(); }).done(); }) it('should execute the playbook with multiple --tags', function (done) { var command = new Playbook().playbook('test').tags('onetag','twotags'); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', "--tags=onetag,twotags"], {}); done(); }).done(); }) it('should execute the playbook with array of --tags', function (done) { var command = new Playbook().playbook('test').tags(['onetag','twotags']); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', "--tags=onetag,twotags"], {}); done(); }).done(); }) }) describe('with --skip-tags param', function() { it('should execute the playbook with --skip-tags', function (done) { var command = new Playbook().playbook('test').skipTags('onetag'); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '--skip-tags=onetag'], {}); done(); }).done(); }) it('should execute the playbook with multiple --skip-tags', function (done) { var command = new Playbook().playbook('test').skipTags('onetag','twotags'); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '--skip-tags=onetag,twotags'], {}); done(); }).done(); }) it('should execute the playbook with array of --skip-tags', function (done) { var command = new Playbook().playbook('test').skipTags(['one tag','twotags']); expect(command.exec()).to.be.fulfilled.then(function () { expect(spawnSpy).to.be.calledWith('ansible-playbook', ['test.yml', '--skip-tags=one tag,twotags'], {}); done(); }).done(); }) }) after(function () { process.spawn = oldSpawn; spawnSpy.restore(); }) })
{ "content_hash": "cb3a36c923ca43eda393a64b1bd1d7c6", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 113, "avg_line_length": 32.57786885245902, "alnum_prop": 0.5963014215624607, "repo_name": "deployable/node-ansible", "id": "e9cbe4602c99583ea40a8266732d5fd37e603590", "size": "7949", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "test/playbook.spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "19771" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
package com.amazonaws.services.pinpoint.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/pinpoint-2016-12-01/GetCampaignVersion" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetCampaignVersionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> */ private String applicationId; /** * <p> * The unique identifier for the campaign. * </p> */ private String campaignId; /** * <p> * The unique version number (Version property) for the campaign version. * </p> */ private String version; /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @param applicationId * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. */ public void setApplicationId(String applicationId) { this.applicationId = applicationId; } /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @return The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. */ public String getApplicationId() { return this.applicationId; } /** * <p> * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the Amazon * Pinpoint console. * </p> * * @param applicationId * The unique identifier for the application. This identifier is displayed as the <b>Project ID</b> on the * Amazon Pinpoint console. * @return Returns a reference to this object so that method calls can be chained together. */ public GetCampaignVersionRequest withApplicationId(String applicationId) { setApplicationId(applicationId); return this; } /** * <p> * The unique identifier for the campaign. * </p> * * @param campaignId * The unique identifier for the campaign. */ public void setCampaignId(String campaignId) { this.campaignId = campaignId; } /** * <p> * The unique identifier for the campaign. * </p> * * @return The unique identifier for the campaign. */ public String getCampaignId() { return this.campaignId; } /** * <p> * The unique identifier for the campaign. * </p> * * @param campaignId * The unique identifier for the campaign. * @return Returns a reference to this object so that method calls can be chained together. */ public GetCampaignVersionRequest withCampaignId(String campaignId) { setCampaignId(campaignId); return this; } /** * <p> * The unique version number (Version property) for the campaign version. * </p> * * @param version * The unique version number (Version property) for the campaign version. */ public void setVersion(String version) { this.version = version; } /** * <p> * The unique version number (Version property) for the campaign version. * </p> * * @return The unique version number (Version property) for the campaign version. */ public String getVersion() { return this.version; } /** * <p> * The unique version number (Version property) for the campaign version. * </p> * * @param version * The unique version number (Version property) for the campaign version. * @return Returns a reference to this object so that method calls can be chained together. */ public GetCampaignVersionRequest withVersion(String version) { setVersion(version); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getApplicationId() != null) sb.append("ApplicationId: ").append(getApplicationId()).append(","); if (getCampaignId() != null) sb.append("CampaignId: ").append(getCampaignId()).append(","); if (getVersion() != null) sb.append("Version: ").append(getVersion()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof GetCampaignVersionRequest == false) return false; GetCampaignVersionRequest other = (GetCampaignVersionRequest) obj; if (other.getApplicationId() == null ^ this.getApplicationId() == null) return false; if (other.getApplicationId() != null && other.getApplicationId().equals(this.getApplicationId()) == false) return false; if (other.getCampaignId() == null ^ this.getCampaignId() == null) return false; if (other.getCampaignId() != null && other.getCampaignId().equals(this.getCampaignId()) == false) return false; if (other.getVersion() == null ^ this.getVersion() == null) return false; if (other.getVersion() != null && other.getVersion().equals(this.getVersion()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getApplicationId() == null) ? 0 : getApplicationId().hashCode()); hashCode = prime * hashCode + ((getCampaignId() == null) ? 0 : getCampaignId().hashCode()); hashCode = prime * hashCode + ((getVersion() == null) ? 0 : getVersion().hashCode()); return hashCode; } @Override public GetCampaignVersionRequest clone() { return (GetCampaignVersionRequest) super.clone(); } }
{ "content_hash": "211dfcf04326e3f615a5a9e53962d8c3", "timestamp": "", "source": "github", "line_count": 226, "max_line_length": 121, "avg_line_length": 30.4070796460177, "alnum_prop": 0.6087019790454016, "repo_name": "aws/aws-sdk-java", "id": "cd1dac8eb5e8e6ed6012e32090feb897941daed0", "size": "7452", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/GetCampaignVersionRequest.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var path = require('path'); var webpack = require('webpack'); var gulp = require('gulp'); var gutil = require('gulp-util'); var config = require(path.resolve('webpack.config.js')); var webpackDevelopmentTask = function(callback) { webpack( config, function(err, stats) { if(err) throw new gutil.PluginError("webpack", err); callback(); }); } gulp.task('webpack:development', webpackDevelopmentTask)
{ "content_hash": "0615910ee9a4640ea448cac5b35a32aa", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 58, "avg_line_length": 25.176470588235293, "alnum_prop": 0.677570093457944, "repo_name": "resmio/elzar", "id": "1e94611f842afae8fedd0380745c43aa815547ec", "size": "428", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gulpfile.js/tasks/webpackDevelopment.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21353" }, { "name": "HTML", "bytes": "23686" }, { "name": "JavaScript", "bytes": "15695" } ], "symlink_target": "" }
@interface EKTableViewController () @property (nonatomic, assign) EKTableViewStyle style; @property (nonatomic, strong) NSMutableArray *registeredCellClasses; @property (nonatomic, strong) NSMutableDictionary *proxyCells; @end @implementation EKTableViewController #pragma mark - Initialisers - (instancetype)init { return [self initWithStyle:EKTableViewStylePlain]; } - (instancetype)initWithStyle:(EKTableViewStyle)style { if (self = [super init]) { _style = style; _registeredCellClasses = [NSMutableArray array]; _clearsSelectionOnViewWillAppear = YES; } return self; } #pragma mark - View lifecycle - (void)loadView { [super loadView]; CGRect frame = [[UIScreen mainScreen] bounds]; self.tableView = [[EKTableView alloc] initWithFrame:frame style:self.style]; self.tableView.delegate = self; self.tableView.dataSource = self; self.view = self.tableView; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (self.clearsSelectionOnViewWillAppear) { [self clearSelectionAnimated:animated]; } } #pragma mark - Actions - (void)setSections:(NSArray *)sections reload:(BOOL)reload animated:(BOOL)animated { self.sections = sections; if (reload) { [self reloadSectionsAnimated:animated]; } } - (void)addSection:(id <EKTableSectionProtocol>)section { if (!self.sections) { self.sections = @[section]; } else { self.sections = [self.sections arrayByAddingObject:section]; } } - (void)reloadSectionsAnimated:(BOOL)animated { [self.tableView reloadData]; } - (void)clearSelectionAnimated:(BOOL)animated { [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:animated]; } #pragma mark - Table view datasoure - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return self.sections.count; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex { id <EKTableSectionProtocol> section = [self sectionAtIndex:sectionIndex]; return section.sectionRows.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { Class cellClass = [self cellClassForIndexPath:indexPath]; // Check to see if cell class is registered with table-view; if not, register it. if (![self isCellClassRegistered:cellClass]) { [self registerCellClass:cellClass]; } EKTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(cellClass) forIndexPath:indexPath]; [self configureCell:cell forIndexPath:indexPath]; return cell; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)sectionIndex { id <EKTableSectionProtocol> section = [self sectionAtIndex:sectionIndex]; return section.sectionHeaderTitle; } - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)sectionIndex { id <EKTableSectionProtocol> section = [self sectionAtIndex:sectionIndex]; return section.sectionFooterTitle; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; if ([row respondsToSelector:@selector(rowHeightForConstraintSize:)]) { CGSize constaintSize = CGSizeMake(self.view.bounds.size.width, MAXFLOAT); return [row rowHeightForConstraintSize:constaintSize]; } else { return [self automaticCellHeightForIndexPath:indexPath]; } } - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { return 100; } #pragma mark - TableView delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { id <EKTableSectionProtocol> section = [self sectionAtIndex:indexPath.section]; id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; EKTableSelectionHandler handler = nil; if ([section respondsToSelector:@selector(sectionSelectionHandler)]) { handler = [section sectionSelectionHandler]; } if ([row respondsToSelector:@selector(rowSelectionHandler)]) { // Don't overide the section handler unless row has handler if ([row rowSelectionHandler]) { handler = [row rowSelectionHandler]; } } EKTableRowSelection *selection = [EKTableRowSelection selectionWithIndexPath:indexPath object:row]; if (handler) { handler(selection); } else { [self clearSelectionAnimated:YES]; } } #pragma mark - Model Helpers - (id <EKTableSectionProtocol>)sectionAtIndex:(NSInteger)index { return self.sections[index]; } - (id <EKTableRowProtocol>)rowAtIndexPath:(NSIndexPath *)indexPath { id <EKTableSectionProtocol> section = [self sectionAtIndex:indexPath.section]; return section.sectionRows[indexPath.row]; } - (BOOL)isIndexPathSelectable:(NSIndexPath *)indexPath { id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; id <EKTableSectionProtocol> section = [self sectionAtIndex:indexPath.section]; if ([row respondsToSelector:@selector(rowSelectionHandler)]) { if (row.rowSelectionHandler) { return YES; } else { return NO; } } else if (section.sectionSelectionHandler) { return YES; } else { return NO; } } #pragma mark - Cell helpers - (void)configureCell:(EKTableViewCell *)cell forIndexPath:(NSIndexPath *)indexPath { id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; if ([row respondsToSelector:@selector(rowTitle)]) { cell.textLabel.text = [row rowTitle]; } if ([row respondsToSelector:@selector(rowSubtitle)]) { cell.detailTextLabel.text = [row rowSubtitle]; } if ([row respondsToSelector:@selector(rowImage)]) { cell.imageView.image = [row rowImage]; } if ([self isIndexPathSelectable:indexPath]) { cell.accessoryType = kNilOptions; } if ([row respondsToSelector:@selector(rowAccessoryType)]) { cell.accessoryType = [row rowAccessoryType]; } // Allow row to configure cell if ([row respondsToSelector:@selector(configureRowCell:)]) { [row configureRowCell:cell]; } } - (void)registerCellClass:(Class)cellClass { [self.tableView registerClass:cellClass forCellReuseIdentifier:NSStringFromClass(cellClass)]; [self.registeredCellClasses addObject:NSStringFromClass(cellClass)]; } - (BOOL)isCellClassRegistered:(Class)cellClass { return [self.registeredCellClasses containsObject:NSStringFromClass(cellClass)]; } - (Class)cellClassForIndexPath:(NSIndexPath *)indexPath { id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; Class cellClass = [EKTableViewCell class]; if ([row respondsToSelector:@selector(rowCellClass)]) { cellClass = [row rowCellClass]; } return cellClass; } - (EKTableViewCell *)dequeueProxyCellForIndexPath:(NSIndexPath *)indexPath { Class cellClass = [self cellClassForIndexPath:indexPath]; NSString *reuseIdentifier = NSStringFromClass(cellClass); EKTableViewCell *cell = self.proxyCells[reuseIdentifier]; if (!cell) { cell = [[cellClass alloc] initWithStyle:(UITableViewCellStyle)EKTableViewCellStyleDefault reuseIdentifier:reuseIdentifier]; } return cell; } - (CGFloat)automaticCellHeightForIndexPath:(NSIndexPath *)indexPath { // Configure a proxy instance of the row's cell EKTableViewCell *proxyCell = [self dequeueProxyCellForIndexPath:indexPath]; [self configureCell:proxyCell forIndexPath:indexPath]; // Force cell to layout [proxyCell layoutSubviews]; CGFloat height = self.tableView.rowHeight; CGFloat greatestY = 0; CGFloat lowestY = 0; // Go through each subview and find view with greatest and lowest y & height values for (UIView *view in proxyCell.contentView.subviews) { CGFloat maxY = view.frame.size.height + view.frame.origin.y; if (maxY > greatestY) { greatestY = maxY; } if (view.frame.origin.y < lowestY) { lowestY = view.frame.origin.y; } } height = greatestY + abs(lowestY); // Default cell edge insets UIEdgeInsets insets = UIEdgeInsetsMake(10, 10, 10, 10); id <EKTableRowProtocol> row = [self rowAtIndexPath:indexPath]; if ([row respondsToSelector:@selector(rowEdgeInsets)]) { insets = [row rowEdgeInsets]; } height += insets.top + insets.bottom; return height; } @end
{ "content_hash": "2aa07e549e662dc9e7e2561f3c320fb7", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 131, "avg_line_length": 27.473846153846154, "alnum_prop": 0.6914548101691119, "repo_name": "electrickangaroo/Lightning-Table", "id": "d1be6fa96626b729a1dfdac727b7b40a646712a0", "size": "9135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LightningTable/EKTableViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "40927" } ], "symlink_target": "" }
package com.meida.model; import com.meida.model.base.BaseUser; /** * * @author liuzhen * @version * May 30, 2015 5:08:21 PM * DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL auto_increment, `name` VARCHAR (50) NOT null, `email` varchar(50) NOT NULL, `password` varchar(128) NOT NULL, `status` int DEFAULT 0, `openId` varchar(50), `company` VARCHAR (50), `companyAddress` VARCHAR (50), `deleteFlag` BIT DEFAULT 0, `createTime` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, `creater` bigint(20) NOT NULL , `updateTime` TIMESTAMP NOT NULL, `updater` bigint(20) NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE `user` ADD UNIQUE (`email`); ALTER TABLE `user` ADD UNIQUE (`openId`); */ @SuppressWarnings("serial") public class User extends BaseUser<User> { public final static User dao = new User(); public final static String TABLE_NAME = "user", CACHE_NAME = "user", CACHE_KEY_START = "user_"; public final static String name = "name", email = "email", password = "password", status = "status", openId = "openId", company = "company", companyAddress = "companyAddress"; public final static String sql_findAll = "select * from " + User.TABLE_NAME, sql_findByEmail = sql_findAll + " where email=?", sql_findByOpenId = sql_findAll + " where openId=?", sql_findMyFriends = sql_findAll + " where id in(" +"select "+ UserFriend.friendId+" from " + UserFriend.TABLE_NAME + " where " + UserFriend.userId + "=?)"; private String currentMenu, prevMenu; public String getCurrentMenu() { return currentMenu == null ? "" : currentMenu; } public void setCurrentMenu(String currentMenu) { this.prevMenu = this.currentMenu; this.currentMenu = currentMenu; } public String getPrevMenu() { return prevMenu; } }
{ "content_hash": "662f1443f533a48c5e7070ad650c23e7", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 165, "avg_line_length": 30.567164179104477, "alnum_prop": 0.609375, "repo_name": "liuzhen9327/meida", "id": "f46b1704a7cb7a188cc581387145a0024fa92e9b", "size": "2048", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/meida/model/User.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "122490" }, { "name": "HTML", "bytes": "180579" }, { "name": "Java", "bytes": "411271" }, { "name": "JavaScript", "bytes": "51921" } ], "symlink_target": "" }
- **[Welcome](#welcome)** - [Free Tutoring](#tutoring) - [Goals](#goals) - **[FAQ](#faq)** - [What do I need?](#need) - [What if I finish ahead of time?](#finished) - **[Before You Get Started](#getstarted)** # [JS Fundamentals: eFarmony Project](id:welcome) Welcome to the project portion of "JS Fundamentals"! Glad you are here mastering objects, arrays and functions with us! This document will guide you through the entire process for the project, with plenty of extra work for you to do at home for practice. ##### [A Note on Free Tutoring](id:tutoring): If you keep track of typos and unclear directions, whoever submits the most mistakes to <bianca@hackreactor.com> by the end of the week gets one free tutoring session! Please send them numbered in one e-mail or do a pull request to Github with the number of corrections in the comments. The Github method is preferred, feel free to ask for a mini-lesson on how to do this. #### [Goals](id:goals) Today we will practice our JS Fundamentals by creating eFarmony, a dating app that enables animals to find the love they deserve! We will create the data structures and logic that will power your application. After the exercises, all you'll need to do is create the user interface using HTML/CSS and a little jQuery (or JS DOM for the purists)! ##[FAQ](id:faq) #### [What will I need to do well in the class?](id:need) - You should have some exposure to JavaScript syntax fundamentals, such as loops and control flow, objects and arrays. **If you are relatively new to these concepts, please tell a TA immediately so we can take extra care in keeping you on track during the exercises.** - Some of the instructions are written with the assumption you're using [Google Chrome](www.google.com/chrome/). While you are welcome to use any browser you like, Chrome has some of the best dev tools available, and it's highly recommended you try it for the duration of this class. - Any plain text editor will suffice for you to edit the exercise files. [Sublime Text](http://www.sublimetext.com/download) is a good choice. #### [What if I finish an exercise with extra time?](id:finished) If you finish one of the assignments ahead of schedule, your best bet is to research and reinforce any previous concepts you'd felt shaky on, since each lecture is designed to build on a firm understanding of the previous ones. If you feel strong in all the material you've covered already, talk to an instructor and we will find some extra credit for you. ## [Before You Get Started](id:getstarted) Download the zip file of this repository. Explore the files. Run the **index.html** file in your browser. It will appear blank, but will make all your JavaScript files available in your JavaScript console. You will be console.log()'ing a lot to check your work. When you complete a section, feel free to comment out any console.logs so that you don't clutter up your console as you are testing your code. The **scripts.js** are the files you will be coding in today. --- Links to Exercises ===== [Objects](https://github.com/bgando/object-exercises/) [Arrays](https://github.com/bgando/array-exercises/) [Nested Data](https://github.com/bgando/nested-data-exercises) [Functions](https://github.com/bgando/function-exercises/)
{ "content_hash": "0e703bfc431011d615cadca658ae27cd", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 372, "avg_line_length": 62.132075471698116, "alnum_prop": 0.7561494078348011, "repo_name": "alexstevenson19/front_end_masters_js_exer", "id": "1bf10caa7812c22f147f11e8c87f9c2807c4be7f", "size": "3293", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "mit", "language": [ { "name": "HTML", "bytes": "598" }, { "name": "JavaScript", "bytes": "6002" } ], "symlink_target": "" }
var anyoneApp = angular.module("anyoneApp", ['ngRoute']); anyoneApp.config(['$routeProvider', function ($routeProvider) { $routeProvider .when('/', {templateUrl: './anyone/home.htm', controller: 'homeController'}) .when('/contacts', {templateUrl: './anyone/contacts.htm', controller: 'contactsController'}) .when('/newsList/:type', {templateUrl: './anyone/newsList.htm', controller: 'newsListController'}) .when('/superstarList', {templateUrl: './anyone/superstarList.htm', controller: 'superstarListController'}) .when('/newsInfo/:number', {templateUrl: './anyone/newsInfo.htm', controller: 'newsInfoController'}) .when('/search/:searchText', {templateUrl: './anyone/search.htm', controller: 'searchController'}) .when('/style/:number', {templateUrl: './anyone/styleInfo.htm', controller: 'styleInfoController'}) .otherwise({redirectTo: '/'}); }]); anyoneApp.service("mineHttp", function ($http) { this.send = function (method, url, params, callback) { var setting = { method: method, url: fullPath(url) }; $.extend(setting, params); $http(setting).then(function successCallback(response) { callback(response.data); }, function errorCallback(response) { alert("请求异常!") }); }; }); /*网页头部操作*/ anyoneApp.controller("headerController", function ($scope, $location, mineHttp) { $scope.gotToUrl = function (url) { $location.path(url) }; $scope.gotToUrlBlank = function (url) { window.open(url); }; mineHttp.send("GET", "topic/types", null, function (data) { $scope.topics = data; }); $scope.search = function () { if (typeof $scope.searchText != "string" || $scope.searchText == "") { return; } $location.path("/search/" + encodeURIComponent($scope.searchText)); } }); /*首页*/ anyoneApp.controller("homeController", function ($scope, mineHttp) { $scope.home = {}; $scope.loadDatas = function () { mineHttp.send("GET", "free/home", null, function (data) { for (var i = 0; i < data.picNews.length; i++) { data.picNews[i].imageUrl = imageUrl(data.picNews[i].imageId); } for (var i = 0; i < data.jzStyles.length; i++) { data.jzStyles[i].imageUrl = imageUrl(data.jzStyles[i].imageId); } $scope.home = data; tpxwRoll(data.picNews.length);//图片滚动 xjmjRoll(data.superstars.length);//图片滚动 jzfcRoll(data.jzStyles.length);//图片滚动 }); }; $scope.loadDatas(); }); /*新闻列表*/ anyoneApp.controller("newsListController", function ($scope, $routeParams) { /*alert($routeParams.type);*/ if ($routeParams.type == "tpxw") { $scope.newsType = "图片新闻"; } else if ($routeParams.type == "jqkx") { $scope.newsType = "警情快讯"; } else if ($routeParams.type == "dwjs") { $scope.newsType = "队伍建设"; } else if ($routeParams.type == "bmdt") { $scope.newsType = "部门动态"; } else if ($routeParams.type == "xxyd") { $scope.newsType = "学习园地"; } else if ($routeParams.type == "whsb") { $scope.newsType = "网海拾贝"; } else if ($routeParams.type == "kjlw") { $scope.newsType = "科技瞭望"; } else { return; } $("#newsListTable").bootstrapTable({ url: fullPath("free/newsList/" + $routeParams.type), dataType: "json", method: "post", singleSelect: false, sidePagination: "server", //服务端处理分页 pageNumber: 1, pageSize: 20, pageList: [20, 50], pagination: true, //分页 search: false, queryParamsType: "", queryParams: function (params) { return $.extend({}, params); }, sortable: true, sortName: "publishTime", sortOrder: "desc", columns: [ { title: '标题', field: 'title', align: 'left', formatter: function (value, row, index) { return '<a href="#/newsInfo/' + row.number + '">' + row.title + '</a>'; } }, { title: '发布日期', field: 'publishTime', align: 'center', width: 150, sortable: true } ] }); }); /*搜索结果*/ anyoneApp.controller("searchController", function ($scope, $routeParams) { var searchText = decodeURIComponent($routeParams.searchText); $("#searchListTable").bootstrapTable({ url: fullPath("free/search/news"), dataType: "json", method: "post", singleSelect: false, sidePagination: "server", //服务端处理分页 pageNumber: 1, pageSize: 20, pageList: [20, 50], pagination: true, //分页 search: false, queryParamsType: "", queryParams: function (params) { return $.extend({}, params, {"searchText": searchText}); }, sortable: true, sortName: "publishTime", sortOrder: "desc", columns: [ { title: '标题', field: 'title', align: 'left', formatter: function (value, row) { return '<a href="#/newsInfo/' + row.number + '">' + row.title + '</a>'; } }, { title: '发布日期', field: 'publishTime', align: 'center', width: 150, sortable: true } ] }); }); /*技侦明星列表*/ anyoneApp.controller("superstarListController", function ($scope, mineHttp) { $("#superstarListTable").bootstrapTable({ url: fullPath("free/superstarList/"), dataType: "json", method: "post", singleSelect: false, sidePagination: "server", //服务端处理分页 pageNumber: 1, pageSize: 5, pageList: [5, 10], pagination: true, //分页 search: false, queryParamsType: "", queryParams: function (params) { return $.extend({}, params); }, sortable: true, sortName: "year", sortOrder: "desc", columns: [ { title: '相片', field: 'imageBase64', align: 'left', width: 150, formatter: function (value, row) { return '<img src="' + row.imageBase64 + '" class="superstar-image" />'; } }, { title: '姓名', field: 'name', align: 'center', width: 100 }, { title: '年月', field: 'year', align: 'center', width: 100, sortable: true, formatter: function (value, row) { return row.year + "-" + row.month; } }, { title: '荣誉', field: 'honor', width: 200 }, { title: '事迹', field: 'story' } ] }); }); /*新闻查看*/ anyoneApp.controller("newsInfoController", function ($scope, $routeParams, mineHttp) { var number = $routeParams.number; if (typeof number != "string") { return; } mineHttp.send("GET", "free/newsInfo/" + number, null, function (data) { $scope.news = data; $("#newsContent").html(data.content); for (index in $scope.news.attachments) { $scope.news.attachments[index].fileUrl = fileUrl($scope.news.attachments[index].fileId); } }); }); /*通讯录*/ anyoneApp.controller("contactsController", function ($scope, mineHttp) { mineHttp.send("GET", "free/contacts", null, function (data) { $("#contactsContent").html(data.content); }); }); /*新闻查看*/ anyoneApp.controller("styleInfoController", function ($scope, $routeParams, mineHttp) { var number = $routeParams.number; if (typeof number != "string") { return; } mineHttp.send("GET", "free/styleInfo/" + number, null, function (data) { for (index in data.styleLines) { data.styleLines[index].imageUrl = imageUrl(data.styleLines[index].imageId); } $scope.style = data; }); }); /*设置主页*/ function setHome(obj) { var url = window.location.href; var webContext = fullPath(""); url = url.substr(0, url.indexOf(webContext)) + webContext; try { obj.style.behavior = 'url(#default#homepage)'; obj.setHomePage(url); } catch (e) { if (window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("抱歉,此操作被浏览器拒绝!\n\n请在浏览器地址栏输入“about:config”并回车然后将[signed.applets.codebase_principal_support]设置为'true'"); } } else { alert("抱歉,您所使用的浏览器无法完成此操作。\n\n您需要手动将【" + url + "】设置为首页。"); } } } /**图片新闻滚动**/ var _tpxwInterval = null; function tpxwRoll(count) { if (_tpxwInterval != null) { clearInterval(_tpxwInterval); } var callback = function (obj) { if (typeof obj != "object") { return; } var number = $(obj).attr("number"); $("tr[type='tpxw']").each(function () { if ($(this).attr("number") == number) { $(this).removeClass("news-no-select"); $(this).addClass("news-selected"); } else { $(this).removeClass("news-selected"); $(this).addClass("news-no-select"); } }); }; _tpxwInterval = imageRoll($(".tpxw-show"), 400, count, 5000, callback); } /**星级民警滚动**/ var _xjmjInterval = null; function xjmjRoll(count) { if (_xjmjInterval != null) { clearInterval(_xjmjInterval); } _xjmjInterval = imageRoll($(".xjmj-show"), 150, count, 8000); } /**技侦风采滚动**/ var _jzfcInterval = null; function jzfcRoll(count) { if (_jzfcInterval != null) { clearInterval(_jzfcInterval); } _jzfcInterval = imageRoll($(".jzfc-show"), 195, count, 8000); } function imageRoll(obj, imageWidth, imageCount, mills, callback) { if (imageCount <= 1) { return null; } var rollLeft = function () { var rollUL = $(obj).find(".roll-inbox > ul"); var first = $(rollUL).children("li").first(); ; var loop = true; $(rollUL).children("li").not(":animated").animate({ left: -imageWidth }, 1000, function () { if (loop) { $(rollUL).append($(first).clone(false)); $(rollUL).children("li").last().css("left", 0); $(first).remove(); loop = false; } ; $(this).css("left", 0); if (callback && typeof callback == "function") { callback($(rollUL).children("li").first()); } }); }; var rollRun = function () { var imageWidthTotal = imageWidth * imageCount; if ($(obj).find(".roll-inbox").width() >= imageWidthTotal) { return null; } $(obj).find(".roll-inbox > ul").width(imageWidthTotal); return setInterval(function () { rollLeft(); }, mills); }; return rollRun(); }
{ "content_hash": "ee0cc88c314ff8b41830b7bd4dcc913c", "timestamp": "", "source": "github", "line_count": 360, "max_line_length": 125, "avg_line_length": 32.16388888888889, "alnum_prop": 0.5100613179031004, "repo_name": "dayupu/acme", "id": "20bd0f0bed0a457b8a90470356199bc571d9e83f", "size": "12011", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "cqjz/src/main/resources/static/js/anyone/app.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "611789" }, { "name": "HTML", "bytes": "244706" }, { "name": "Java", "bytes": "662311" }, { "name": "JavaScript", "bytes": "3995062" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.commonsware.android.abf" android:versionCode="1" android:versionName="1.0"> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="true"/> <application android:name=".ScrapApp" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.Holo.Light.DarkActionBar"> <activity android:name="ActionBarFragmentActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application> </manifest>
{ "content_hash": "cc9d6f40c1bc717df6a60b85d4d33df3", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 68, "avg_line_length": 28.17241379310345, "alnum_prop": 0.7307221542227662, "repo_name": "commonsguy/cw-omnibus", "id": "dde32b2609411dc1056c8f8493e3a0b466ce45d1", "size": "817", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Testing/Orchestrator/app/src/main/AndroidManifest.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "54274" }, { "name": "Groovy", "bytes": "4601" }, { "name": "HTML", "bytes": "2293656" }, { "name": "Java", "bytes": "3404604" }, { "name": "JavaScript", "bytes": "646239" }, { "name": "Kotlin", "bytes": "7397" }, { "name": "Python", "bytes": "546" }, { "name": "Ruby", "bytes": "2071" }, { "name": "Shell", "bytes": "1020" } ], "symlink_target": "" }
set -e set -x # enable some apache stuff a2enmod wsgi a2enmod expires
{ "content_hash": "6f2beae898bae3bb44bab9bf92053896", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 26, "avg_line_length": 12, "alnum_prop": 0.75, "repo_name": "Quelquechose/dockerfiles", "id": "d22a073d4955b0126c019439bcff641e72f0e20c", "size": "85", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "qqch-wsgi/prepare_wsgi.sh", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "1004" }, { "name": "Shell", "bytes": "16954" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Blumea 44:301. 1999 #### Original name null ### Remarks null
{ "content_hash": "e61f161e614a5a5007c918e20a2b5429", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 11.461538461538462, "alnum_prop": 0.697986577181208, "repo_name": "mdoering/backbone", "id": "a788f237756ff45baa7dfc76e920672cee648633", "size": "211", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Coelogyne/Coelogyne speciosa/Coelogyne speciosa fimbriata/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package javax.swing; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.LayoutManager2; import java.beans.BeanProperty; import java.beans.JavaBean; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serial; import java.io.Serializable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; import javax.swing.plaf.ToolBarUI; import javax.swing.plaf.UIResource; /** * <code>JToolBar</code> provides a component that is useful for * displaying commonly used <code>Action</code>s or controls. * For examples and information on using tool bars see * <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/toolbar.html">How to Use Tool Bars</a>, * a section in <em>The Java Tutorial</em>. * * <p> * With most look and feels, * the user can drag out a tool bar into a separate window * (unless the <code>floatable</code> property is set to <code>false</code>). * For drag-out to work correctly, it is recommended that you add * <code>JToolBar</code> instances to one of the four "sides" of a * container whose layout manager is a <code>BorderLayout</code>, * and do not add children to any of the other four "sides". * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * <p> * <strong>Warning:</strong> * Serialized objects of this class will not be compatible with * future Swing releases. The current serialization support is * appropriate for short term storage or RMI between applications running * the same version of Swing. As of 1.4, support for long term storage * of all JavaBeans * has been added to the <code>java.beans</code> package. * Please see {@link java.beans.XMLEncoder}. * * @author Georges Saab * @author Jeff Shapiro * @see Action * @since 1.2 */ @JavaBean(defaultProperty = "UI", description = "A component which displays commonly used controls or Actions.") @SwingContainer @SuppressWarnings("serial") // Same-version serialization only public class JToolBar extends JComponent implements SwingConstants, Accessible { /** * @see #getUIClassID * @see #readObject */ private static final String uiClassID = "ToolBarUI"; private boolean paintBorder = true; private Insets margin = null; private boolean floatable = true; private int orientation = HORIZONTAL; /** * Creates a new tool bar; orientation defaults to <code>HORIZONTAL</code>. */ public JToolBar() { this( HORIZONTAL ); } /** * Creates a new tool bar with the specified <code>orientation</code>. * The <code>orientation</code> must be either <code>HORIZONTAL</code> * or <code>VERTICAL</code>. * * @param orientation the orientation desired */ public JToolBar( int orientation ) { this(null, orientation); } /** * Creates a new tool bar with the specified <code>name</code>. The * name is used as the title of the undocked tool bar. The default * orientation is <code>HORIZONTAL</code>. * * @param name the name of the tool bar * @since 1.3 */ public JToolBar( String name ) { this(name, HORIZONTAL); } /** * Creates a new tool bar with a specified <code>name</code> and * <code>orientation</code>. * All other constructors call this constructor. * If <code>orientation</code> is an invalid value, an exception will * be thrown. * * @param name the name of the tool bar * @param orientation the initial orientation -- it must be * either <code>HORIZONTAL</code> or <code>VERTICAL</code> * @exception IllegalArgumentException if orientation is neither * <code>HORIZONTAL</code> nor <code>VERTICAL</code> * @since 1.3 */ public JToolBar( String name , int orientation) { setName(name); checkOrientation( orientation ); this.orientation = orientation; DefaultToolBarLayout layout = new DefaultToolBarLayout( orientation ); setLayout( layout ); addPropertyChangeListener( layout ); updateUI(); } /** * Returns the tool bar's current UI. * * @return the tool bar's current UI. * @see #setUI */ public ToolBarUI getUI() { return (ToolBarUI)ui; } /** * Sets the L&amp;F object that renders this component. * * @param ui the <code>ToolBarUI</code> L&amp;F object * @see UIDefaults#getUI */ @BeanProperty(hidden = true, visualUpdate = true, description = "The UI object that implements the Component's LookAndFeel.") public void setUI(ToolBarUI ui) { super.setUI(ui); } /** * Notification from the <code>UIFactory</code> that the L&amp;F has changed. * Called to replace the UI with the latest version from the * <code>UIFactory</code>. * * @see JComponent#updateUI */ public void updateUI() { setUI((ToolBarUI)UIManager.getUI(this)); // GTKLookAndFeel installs a different LayoutManager, and sets it // to null after changing the look and feel, so, install the default // if the LayoutManager is null. if (getLayout() == null) { setLayout(new DefaultToolBarLayout(getOrientation())); } invalidate(); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ToolBarUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ @BeanProperty(bound = false) public String getUIClassID() { return uiClassID; } /** * Returns the index of the specified component. * (Note: Separators occupy index positions.) * * @param c the <code>Component</code> to find * @return an integer indicating the component's position, * where 0 is first */ public int getComponentIndex(Component c) { int ncomponents = this.getComponentCount(); Component[] component = this.getComponents(); for (int i = 0 ; i < ncomponents ; i++) { Component comp = component[i]; if (comp == c) return i; } return -1; } /** * Returns the component at the specified index. * * @param i the component's position, where 0 is first * @return the <code>Component</code> at that position, * or <code>null</code> for an invalid index * */ public Component getComponentAtIndex(int i) { int ncomponents = this.getComponentCount(); if ( i >= 0 && i < ncomponents) { Component[] component = this.getComponents(); return component[i]; } return null; } /** * Sets the margin between the tool bar's border and * its buttons. Setting to <code>null</code> causes the tool bar to * use the default margins. The tool bar's default <code>Border</code> * object uses this value to create the proper margin. * However, if a non-default border is set on the tool bar, * it is that <code>Border</code> object's responsibility to create the * appropriate margin space (otherwise this property will * effectively be ignored). * * @param m an <code>Insets</code> object that defines the space * between the border and the buttons * @see Insets */ @BeanProperty(expert = true, description = "The margin between the tool bar's border and contents") public void setMargin(Insets m) { Insets old = margin; margin = m; firePropertyChange("margin", old, m); revalidate(); repaint(); } /** * Returns the margin between the tool bar's border and * its buttons. * * @return an <code>Insets</code> object containing the margin values * @see Insets */ public Insets getMargin() { if(margin == null) { return new Insets(0,0,0,0); } else { return margin; } } /** * Gets the <code>borderPainted</code> property. * * @return the value of the <code>borderPainted</code> property * @see #setBorderPainted */ public boolean isBorderPainted() { return paintBorder; } /** * Sets the <code>borderPainted</code> property, which is * <code>true</code> if the border should be painted. * The default value for this property is <code>true</code>. * Some look and feels might not implement painted borders; * they will ignore this property. * * @param b if true, the border is painted * @see #isBorderPainted */ @BeanProperty(expert = true, description = "Does the tool bar paint its borders?") public void setBorderPainted(boolean b) { if ( paintBorder != b ) { boolean old = paintBorder; paintBorder = b; firePropertyChange("borderPainted", old, b); revalidate(); repaint(); } } /** * Paints the tool bar's border if the <code>borderPainted</code> property * is <code>true</code>. * * @param g the <code>Graphics</code> context in which the painting * is done * @see JComponent#paint * @see JComponent#setBorder */ protected void paintBorder(Graphics g) { if (isBorderPainted()) { super.paintBorder(g); } } /** * Gets the <code>floatable</code> property. * * @return the value of the <code>floatable</code> property * * @see #setFloatable */ public boolean isFloatable() { return floatable; } /** * Sets the <code>floatable</code> property, * which must be <code>true</code> for the user to move the tool bar. * Typically, a floatable tool bar can be * dragged into a different position within the same container * or out into its own window. * The default value of this property is <code>true</code>. * Some look and feels might not implement floatable tool bars; * they will ignore this property. * * @param b if <code>true</code>, the tool bar can be moved; * <code>false</code> otherwise * @see #isFloatable */ @BeanProperty(preferred = true, description = "Can the tool bar be made to float by the user?") public void setFloatable( boolean b ) { if ( floatable != b ) { boolean old = floatable; floatable = b; firePropertyChange("floatable", old, b); revalidate(); repaint(); } } /** * Returns the current orientation of the tool bar. The value is either * <code>HORIZONTAL</code> or <code>VERTICAL</code>. * * @return an integer representing the current orientation -- either * <code>HORIZONTAL</code> or <code>VERTICAL</code> * @see #setOrientation */ public int getOrientation() { return this.orientation; } /** * Sets the orientation of the tool bar. The orientation must have * either the value <code>HORIZONTAL</code> or <code>VERTICAL</code>. * If <code>orientation</code> is * an invalid value, an exception will be thrown. * * @param o the new orientation -- either <code>HORIZONTAL</code> or * <code>VERTICAL</code> * @exception IllegalArgumentException if orientation is neither * <code>HORIZONTAL</code> nor <code>VERTICAL</code> * @see #getOrientation */ @BeanProperty(preferred = true, enumerationValues = { "SwingConstants.HORIZONTAL", "SwingConstants.VERTICAL"}, description = "The current orientation of the tool bar") public void setOrientation( int o ) { checkOrientation( o ); if ( orientation != o ) { int old = orientation; orientation = o; firePropertyChange("orientation", old, o); revalidate(); repaint(); } } /** * Sets the rollover state of this toolbar. If the rollover state is true * then the border of the toolbar buttons will be drawn only when the * mouse pointer hovers over them. The default value of this property * is false. * <p> * The implementation of a look and feel may choose to ignore this * property. * * @param rollover true for rollover toolbar buttons; otherwise false * @since 1.4 */ @BeanProperty(preferred = true, visualUpdate = true, description = "Will draw rollover button borders in the toolbar.") public void setRollover(boolean rollover) { putClientProperty("JToolBar.isRollover", rollover ? Boolean.TRUE : Boolean.FALSE); } /** * Returns the rollover state. * * @return true if rollover toolbar buttons are to be drawn; otherwise false * @see #setRollover(boolean) * @since 1.4 */ public boolean isRollover() { Boolean rollover = (Boolean)getClientProperty("JToolBar.isRollover"); if (rollover != null) { return rollover.booleanValue(); } return false; } private void checkOrientation( int orientation ) { switch ( orientation ) { case VERTICAL: case HORIZONTAL: break; default: throw new IllegalArgumentException( "orientation must be one of: VERTICAL, HORIZONTAL" ); } } /** * Appends a separator of default size to the end of the tool bar. * The default size is determined by the current look and feel. */ public void addSeparator() { addSeparator(null); } /** * Appends a separator of a specified size to the end * of the tool bar. * * @param size the <code>Dimension</code> of the separator */ public void addSeparator( Dimension size ) { JToolBar.Separator s = new JToolBar.Separator( size ); add(s); } /** * Adds a new <code>JButton</code> which dispatches the action. * * @param a the <code>Action</code> object to add as a new menu item * @return the new button which dispatches the action */ public JButton add(Action a) { JButton b = createActionComponent(a); b.setAction(a); add(b); return b; } /** * Factory method which creates the <code>JButton</code> for * <code>Action</code>s added to the <code>JToolBar</code>. * The default name is empty if a <code>null</code> action is passed. * * @param a the <code>Action</code> for the button to be added * @return the newly created button * @see Action * @since 1.3 */ protected JButton createActionComponent(Action a) { JButton b = new JButton() { protected PropertyChangeListener createActionPropertyChangeListener(Action a) { PropertyChangeListener pcl = createActionChangeListener(this); if (pcl==null) { pcl = super.createActionPropertyChangeListener(a); } return pcl; } }; if (a != null && (a.getValue(Action.SMALL_ICON) != null || a.getValue(Action.LARGE_ICON_KEY) != null)) { b.setHideActionText(true); } b.setHorizontalTextPosition(JButton.CENTER); b.setVerticalTextPosition(JButton.BOTTOM); return b; } /** * Returns a properly configured <code>PropertyChangeListener</code> * which updates the control as changes to the <code>Action</code> occur, * or <code>null</code> if the default * property change listener for the control is desired. * * @param b a {@code JButton} * @return {@code null} */ protected PropertyChangeListener createActionChangeListener(JButton b) { return null; } /** * If a <code>JButton</code> is being added, it is initially * set to be disabled. * * @param comp the component to be enhanced * @param constraints the constraints to be enforced on the component * @param index the index of the component * */ protected void addImpl(Component comp, Object constraints, int index) { if (comp instanceof Separator) { if (getOrientation() == VERTICAL) { ( (Separator)comp ).setOrientation(JSeparator.HORIZONTAL); } else { ( (Separator)comp ).setOrientation(JSeparator.VERTICAL); } } super.addImpl(comp, constraints, index); if (comp instanceof JButton) { ((JButton)comp).setDefaultCapable(false); } } /** * A toolbar-specific separator. An object with dimension but * no contents used to divide buttons on a tool bar into groups. */ public static class Separator extends JSeparator { private Dimension separatorSize; /** * Creates a new toolbar separator with the default size * as defined by the current look and feel. */ public Separator() { this( null ); // let the UI define the default size } /** * Creates a new toolbar separator with the specified size. * * @param size the <code>Dimension</code> of the separator */ public Separator( Dimension size ) { super( JSeparator.HORIZONTAL ); setSeparatorSize(size); } /** * Returns the name of the L&amp;F class that renders this component. * * @return the string "ToolBarSeparatorUI" * @see JComponent#getUIClassID * @see UIDefaults#getUI */ public String getUIClassID() { return "ToolBarSeparatorUI"; } /** * Sets the size of the separator. * * @param size the new <code>Dimension</code> of the separator */ public void setSeparatorSize( Dimension size ) { if (size != null) { separatorSize = size; } else { super.updateUI(); } this.invalidate(); } /** * Returns the size of the separator * * @return the <code>Dimension</code> object containing the separator's * size (This is a reference, NOT a copy!) */ public Dimension getSeparatorSize() { return separatorSize; } /** * Returns the minimum size for the separator. * * @return the <code>Dimension</code> object containing the separator's * minimum size */ public Dimension getMinimumSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getMinimumSize(); } } /** * Returns the maximum size for the separator. * * @return the <code>Dimension</code> object containing the separator's * maximum size */ public Dimension getMaximumSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getMaximumSize(); } } /** * Returns the preferred size for the separator. * * @return the <code>Dimension</code> object containing the separator's * preferred size */ public Dimension getPreferredSize() { if (separatorSize != null) { return separatorSize.getSize(); } else { return super.getPreferredSize(); } } } /** * See <code>readObject</code> and <code>writeObject</code> in * <code>JComponent</code> for more * information about serialization in Swing. */ @Serial private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); if (getUIClassID().equals(uiClassID)) { byte count = JComponent.getWriteObjCounter(this); JComponent.setWriteObjCounter(this, --count); if (count == 0 && ui != null) { ui.installUI(this); } } } /** * Returns a string representation of this <code>JToolBar</code>. * This method * is intended to be used only for debugging purposes, and the * content and format of the returned string may vary between * implementations. The returned string may be empty but may not * be <code>null</code>. * * @return a string representation of this <code>JToolBar</code>. */ protected String paramString() { String paintBorderString = (paintBorder ? "true" : "false"); String marginString = (margin != null ? margin.toString() : ""); String floatableString = (floatable ? "true" : "false"); String orientationString = (orientation == HORIZONTAL ? "HORIZONTAL" : "VERTICAL"); return super.paramString() + ",floatable=" + floatableString + ",margin=" + marginString + ",orientation=" + orientationString + ",paintBorder=" + paintBorderString; } private class DefaultToolBarLayout implements LayoutManager2, Serializable, PropertyChangeListener, UIResource { BoxLayout lm; DefaultToolBarLayout(int orientation) { if (orientation == JToolBar.VERTICAL) { lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS); } else { lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS); } } public void addLayoutComponent(String name, Component comp) { lm.addLayoutComponent(name, comp); } public void addLayoutComponent(Component comp, Object constraints) { lm.addLayoutComponent(comp, constraints); } public void removeLayoutComponent(Component comp) { lm.removeLayoutComponent(comp); } public Dimension preferredLayoutSize(Container target) { return lm.preferredLayoutSize(target); } public Dimension minimumLayoutSize(Container target) { return lm.minimumLayoutSize(target); } public Dimension maximumLayoutSize(Container target) { return lm.maximumLayoutSize(target); } public void layoutContainer(Container target) { lm.layoutContainer(target); } public float getLayoutAlignmentX(Container target) { return lm.getLayoutAlignmentX(target); } public float getLayoutAlignmentY(Container target) { return lm.getLayoutAlignmentY(target); } public void invalidateLayout(Container target) { lm.invalidateLayout(target); } public void propertyChange(PropertyChangeEvent e) { String name = e.getPropertyName(); if( name.equals("orientation") ) { int o = ((Integer)e.getNewValue()).intValue(); if (o == JToolBar.VERTICAL) lm = new BoxLayout(JToolBar.this, BoxLayout.PAGE_AXIS); else { lm = new BoxLayout(JToolBar.this, BoxLayout.LINE_AXIS); } } } } public void setLayout(LayoutManager mgr) { LayoutManager oldMgr = getLayout(); if (oldMgr instanceof PropertyChangeListener) { removePropertyChangeListener((PropertyChangeListener)oldMgr); } super.setLayout(mgr); } ///////////////// // Accessibility support //////////////// /** * Gets the AccessibleContext associated with this JToolBar. * For tool bars, the AccessibleContext takes the form of an * AccessibleJToolBar. * A new AccessibleJToolBar instance is created if necessary. * * @return an AccessibleJToolBar that serves as the * AccessibleContext of this JToolBar */ @BeanProperty(bound = false) public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleJToolBar(); } return accessibleContext; } /** * This class implements accessibility support for the * <code>JToolBar</code> class. It provides an implementation of the * Java Accessibility API appropriate to toolbar user-interface elements. */ protected class AccessibleJToolBar extends AccessibleJComponent { /** * Constructs an {@code AccessibleJToolBar}. */ protected AccessibleJToolBar() {} /** * Get the state of this object. * * @return an instance of AccessibleStateSet containing the current * state set of the object * @see AccessibleState */ public AccessibleStateSet getAccessibleStateSet() { AccessibleStateSet states = super.getAccessibleStateSet(); // FIXME: [[[WDW - need to add orientation from BoxLayout]]] // FIXME: [[[WDW - need to do SELECTABLE if SelectionModel is added]]] return states; } /** * Get the role of this object. * * @return an instance of AccessibleRole describing the role of the object */ public AccessibleRole getAccessibleRole() { return AccessibleRole.TOOL_BAR; } } // inner class AccessibleJToolBar }
{ "content_hash": "befca656ca0cd03febaec37f3fb9931b", "timestamp": "", "source": "github", "line_count": 846, "max_line_length": 112, "avg_line_length": 31.77304964539007, "alnum_prop": 0.5893229166666667, "repo_name": "mirkosertic/Bytecoder", "id": "114ef0d169c2a8c0c97c01f858c237f3fbd9a119", "size": "28092", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "classlib/java.desktop/src/main/resources/META-INF/modules/java.desktop/classes/javax/swing/JToolBar.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "153" }, { "name": "C++", "bytes": "1301" }, { "name": "CSS", "bytes": "5154" }, { "name": "Clojure", "bytes": "87" }, { "name": "HTML", "bytes": "599386" }, { "name": "Java", "bytes": "106011215" }, { "name": "Kotlin", "bytes": "15858" }, { "name": "LLVM", "bytes": "2839" }, { "name": "Shell", "bytes": "164" } ], "symlink_target": "" }
package io.craft.atom.protocol.ssl.api; import io.craft.atom.protocol.ssl.spi.SslHandshakeHandler; /** * SSL codec, it is a combination of ssl encoder and decoder. * * @author mindwind * @version 1.0, Aug 5, 2014 */ public interface SslCodec { /** * Encode data to ssl encrypted data. * * @param data * @return Encrypted app data */ byte[] encode(byte[] data); /** * Decode for ssl encrypted data * * @param data * @return Only decrypted app data, the handshake data will write back to remote by {@link SslHandshakeHandler} */ byte[] decode(byte[] data); }
{ "content_hash": "3f69a8d5f96b45075379e683815ec70e", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 112, "avg_line_length": 19.933333333333334, "alnum_prop": 0.6672240802675585, "repo_name": "mindwind/craft-atom", "id": "c8d4c5c1dad2f974c20142fc99f08a1029bc2ccc", "size": "598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "craft-atom-protocol-ssl/src/main/java/io/craft/atom/protocol/ssl/api/SslCodec.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1423550" }, { "name": "Shell", "bytes": "1000" } ], "symlink_target": "" }
import Ember from 'ember'; import layout from '../templates/components/bulma-panel-tabs'; import { _helpers, _responsiveHelpers } from '../constants'; const { Component } = Ember; export default Component.extend({ layout, classNames: ['panel-tabs'], classNameBindings: [].concat(_helpers, _responsiveHelpers) });
{ "content_hash": "608636deccceb050dddefe9125c50c24", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 62, "avg_line_length": 24.846153846153847, "alnum_prop": 0.7151702786377709, "repo_name": "open-tux/ember-bulma", "id": "7e14ad5fa6eed99c7288f9a53ba53f6ef21973dc", "size": "323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "addon/components/bulma-panel-tabs.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1170" }, { "name": "HTML", "bytes": "112812" }, { "name": "JavaScript", "bytes": "100656" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Aspose.Imaging.Live.Demos.UI.Models { /// <summary> /// Base class for results. /// </summary> public class BaseResult { /// <summary> /// Is result success? /// </summary> public bool IsSuccess { get; set; } /// <summary> /// idError. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "id always small")] public string idError { get; set; } } }
{ "content_hash": "b1c8cdd05e20bd92921138f808191fac", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 120, "avg_line_length": 22.208333333333332, "alnum_prop": 0.6679174484052532, "repo_name": "aspose-imaging/Aspose.Imaging-for-.NET", "id": "d5d604f1efa1b1e126a94ab5447f0b86f6a8189e", "size": "533", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Demos/src/Aspose.Imaging.Live.Demos.UI/Models/BaseResult.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12494496" }, { "name": "CSS", "bytes": "1073" } ], "symlink_target": "" }
<!-- ~ Copyright 2013-2014 must-be.org ~ ~ 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. --> <list> <!--See http://docs.unity3d.com/ScriptReference/MonoBehaviour.html--> <function name="Awake"> <description>Awake is called when the script instance is being loaded.</description> </function> <function name="FixedUpdate"> <description>This function is called every fixed framerate frame, if the MonoBehaviour is enabled.</description> </function> <function name="LateUpdate"> <description>LateUpdate is called every frame, if the Behaviour is enabled.</description> </function> <function name="OnAnimatorIK"> <parameters> <parameter name="layerIndex" type="System.Int32" /> </parameters> <description>Callback for setting up animation IK (inverse kinematics).</description> </function> <function name="OnAnimatorMove"> <description>Callback for processing animation movements for modifying root motion.</description> </function> <function name="OnApplicationFocus"> <description>Sent to all game objects when the player gets or loses focus.</description> </function> <function name="OnApplicationPause"> <parameters> <parameter type="System.Bool" name="pause"/> </parameters> <description>Sent to all game objects when the player pauses.</description> </function> <function name="OnApplicationQuit"> <description>Sent to all game objects before the application is quit.</description> </function> <function name="OnAudioFilterRead"> <parameters> <parameter name="data" type="System.Single[]" /> <parameter name="channels" type="System.Int32" /> </parameters> <description>If OnAudioFilterRead is implemented, Unity will insert a custom filter into the audio DSP chain.</description> </function> <function name="OnBecameInvisible"> <description>OnBecameInvisible is called when the renderer is no longer visible by any camera.</description> </function> <function name="OnBecameVisible"> <description>OnBecameVisible is called when the renderer became visible by any camera.</description> </function> <function name="OnCollisionEnter"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision"/> </parameters> <description>OnCollisionEnter is called when this collider/rigidbody has begun touching another rigidbody/collider.</description> </function> <function name="OnCollisionEnter2D"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision2D"/> </parameters> <description>Sent when an incoming collider makes contact with this object's collider (2D physics only).</description> </function> <function name="OnCollisionExit"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision"/> </parameters> <description>OnCollisionEnter is called when this collider/rigidbody has stopped touching another rigidbody/collider.</description> </function> <function name="OnCollisionExit2D"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision2D"/> </parameters> <description>Sent when a collider on another object stops touching this object's collider (2D physics only).</description> </function> <function name="OnCollisionStay"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision"/> </parameters> <description>OnCollisionEnter is called once per frame for every collider/rigidbody that is touching rigidbody/collider.</description> </function> <function name="OnCollisionStay2D"> <parameters> <parameter name="collisionInfo" type="UnityEngine.Collision2D"/> </parameters> <description>Sent each frame where a collider on another object is touching this object's collider (2D physics only).</description> </function> <function name="OnConnectedToServer"> <description>Called on the client when you have successfully connected to a server</description> </function> <function name="OnControllerColliderHit"> <parameters> <parameter name="hit" type="UnityEngine.ControllerColliderHit"/> </parameters> <description>OnControllerColliderHit is called when the controller hits a collider while performing a Move.</description> </function> <function name="OnDestroy"> <description>This function is called when the MonoBehaviour will be destroyed.</description> </function> <function name="OnDisable"> <description>This function is called when the behaviour becomes disabled () or inactive.</description> </function> <function name="OnDisconnectedFromServer"> <parameters> <parameter name="mode" type="UnityEngine.NetworkDisconnection"/> </parameters> <description>Called on the client when the connection was lost or you disconnected from the server.</description> </function> <function name="OnDrawGizmos"> <description>Implement this OnDrawGizmos if you want to draw gizmos that are also pickable and always drawn.</description> </function> <function name="OnDrawGizmosSelected"> <description>Implement this OnDrawGizmosSelected if you want to draw gizmos only if the object is selected.</description> </function> <function name="OnEnable"> <description>This function is called when the object becomes enabled and active.</description> </function> <function name="OnFailedToConnect"> <parameters> <parameter name="error" type="UnityEngine.NetworkConnectionError"/> </parameters> <description>Called on the client when a connection attempt fails for some reason.</description> </function> <function name="OnFailedToConnectToMasterServer"> <parameters> <parameter name="error" type="UnityEngine.NetworkConnectionError"/> </parameters> <description>Called on clients or servers when there is a problem connecting to the master server.</description> </function> <function name="OnGUI"> <description>OnGUI is called for rendering and handling GUI events.</description> </function> <function name="OnJointBreak"> <parameters> <parameter name="breakForce" type="System.Single"/> </parameters> <description>Called when a joint attached to the same game object broke.</description> </function> <function name="OnLevelWasLoaded"> <parameters> <parameter name="level" type="System.Int32"/> </parameters> <description>This function is called after a new level was loaded.</description> </function> <function name="OnMasterServerEvent"> <parameters> <parameter name="msEvent" type="UnityEngine.MasterServerEvent" /> </parameters> <description>Called on clients or servers when reporting events from the MasterServer.</description> </function> <function name="OnMouseDown"> <description>OnMouseDown is called when the user has pressed the mouse button while over the GUIElement or Collider.</description> </function> <function name="OnMouseDrag"> <description>OnMouseDrag is called when the user has clicked on a GUIElement or Collider and is still holding down the mouse.</description> </function> <function name="OnMouseEnter"> <description>OnMouseEnter is called when the mouse entered the GUIElement or Collider.</description> </function> <function name="OnMouseExit"> <description>OnMouseExit is called when the mouse is not any longer over the GUIElement or Collider.</description> </function> <function name="OnMouseOver"> <description>OnMouseOver is called every frame while the mouse is over the GUIElement or Collider.</description> </function> <function name="OnMouseUp"> <description>OnMouseUp is called when the user has released the mouse button.</description> </function> <function name="OnMouseUpAsButton"> <description>OnMouseUpAsButton is only called when the mouse is released over the same GUIElement or Collider as it was pressed.</description> </function> <function name="OnNetworkInstantiate"> <parameters> <parameter name="info" type="UnityEngine.NetworkMessageInfo"/> </parameters> <description>Called on objects which have been network instantiated with Network.Instantiate</description> </function> <function name="OnParticleCollision"> <parameters> <parameter name="other" type="UnityEngine.GameObject"/> </parameters> <description>OnParticleCollision is called when a particle hits a collider.</description> </function> <function name="OnPlayerConnected"> <parameters> <parameter name="player" type="UnityEngine.NetworkPlayer"/> </parameters> <description>Called on the server whenever a new player has successfully connected.</description> </function> <function name="OnPlayerDisconnected"> <parameters> <parameter name="player" type="UnityEngine.NetworkPlayer"/> </parameters> <description>Called on the server whenever a player disconnected from the server.</description> </function> <function name="OnPostRender"> <description>OnPostRender is called after a camera finished rendering the scene.</description> </function> <function name="OnPreCull"> <description>OnPreCull is called before a camera culls the scene.</description> </function> <function name="OnPreRender"> <description>OnPreRender is called before a camera starts rendering the scene.</description> </function> <function name="OnRenderImage"> <parameters> <parameter name="source" type="UnityEngine.RenderTexture"/> <parameter name="destionation" type="UnityEngine.RenderTexture"/> </parameters> <description>OnRenderImage is called after all rendering is complete to render image.</description> </function> <function name="OnRenderObject"> <parameters> <parameter name="queueIndex" type="System.Int32"/> </parameters> <description>OnRenderObject is used to render your own objects using Graphics.DrawMesh or other functions.</description> </function> <function name="OnSerializeNetworkView"> <parameters> <parameter name="stream" type="UnityEngine.BitStream"/> <parameter name="info" type="UnityEngine.NetworkMessageInfo"/> </parameters> <description>Used to customize synchronization of variables in a script watched by a network view.</description> </function> <function name="OnServerInitialized"> <description>Called on the server whenever a Network.InitializeServer was invoked and has completed.</description> </function> <function name="OnTransformChildrenChanged"> <description>This function is called when the list of children of the transform of the GameObject has changed.</description> </function> <function name="OnTransformParentChanged"> <description>This function is called when the parent property of the transform of the GameObject has changed.</description> </function> <function name="OnTriggerEnter"> <parameters> <parameter name="other" type="UnityEngine.Collider"/> </parameters> <description>OnTriggerEnter is called when the Collider other enters the trigger.</description> </function> <function name="OnTriggerEnter2D"> <parameters> <parameter name="other" type="UnityEngine.Collider2D"/> </parameters> <description>Sent when another object enters a trigger collider attached to this object (2D physics only).</description> </function> <function name="OnTriggerExit"> <parameters> <parameter name="other" type="UnityEngine.Collider"/> </parameters> <description>OnTriggerExit is called when the Collider other has stopped touching the trigger.</description> </function> <function name="OnTriggerExit2D"> <parameters> <parameter name="other" type="UnityEngine.Collider2D"/> </parameters> <description>Sent when another object leaves a trigger collider attached to this object (2D physics only).</description> </function> <function name="OnTriggerStay"> <parameters> <parameter name="other" type="UnityEngine.Collider"/> </parameters> <description>OnTriggerStay is called once per frame for every Collider other that is touching the trigger.</description> </function> <function name="OnTriggerStay2D"> <parameters> <parameter name="other" type="UnityEngine.Collider2D"/> </parameters> <description>Sent each frame where another object is within a trigger collider attached to this object (2D physics only).</description> </function> <function name="OnValidate"> <description>This function is called when the script is loaded or a value is changed in the inspector (Called in the editor only).</description> </function> <function name="OnWillRenderObject"> <description>OnWillRenderObject is called once for each camera if the object is visible.</description> </function> <function name="Reset"> <description>Reset to default values.</description> </function> <function name="Start"> <description>Start is called just before any of the Update methods is called the first time.</description> </function> <function name="Update"> <description>Update is called every frame, if the MonoBehaviour is enabled.</description> </function> </list>
{ "content_hash": "fe93179b30928ba7fb11f03b9a9d92e6", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 146, "avg_line_length": 45.24149659863946, "alnum_prop": 0.7634012480264641, "repo_name": "minhdu/consulo-unity3d", "id": "4a5fbc90b9685e158198100bb0550df381d90e13", "size": "13301", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "resources/functions.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "416895" }, { "name": "Lex", "bytes": "2388" } ], "symlink_target": "" }
DELETE FROM analysis WHERE logic_name like 'Submit%'; -- Remove pipeline tables DROP TABLE input_id_analysis; DROP TABLE input_id_type_analysis; DROP TABLE job; DROP TABLE job_status; DROP TABLE rule_conditions; DROP TABLE rule_goal;
{ "content_hash": "12f2c0fa7c60e685054f2a1d25a49f4f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 53, "avg_line_length": 15.125, "alnum_prop": 0.7603305785123967, "repo_name": "navygit/ncRNA_Pipeline", "id": "55049e513afc045463945edfe9202d4040f90f1b", "size": "944", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sql/final_cleaning_steps.sql", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Perl", "bytes": "840271" }, { "name": "Shell", "bytes": "91968" } ], "symlink_target": "" }
package com.cloudsiness.csmongo.active.validators.unique; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.cloudsiness.csmongo.active.CsActiveForm; import com.cloudsiness.csmongo.active.validators.CsConstraint; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @CsConstraint(validatedBy={UniqueValidation.class}) public @interface Unique { String[] scenarios() default {CsActiveForm.MAIN_SCENARIO}; String message() default "{com.cloudiness.csmongo.Unique.message}"; boolean canBeNull() default false; boolean nullIsAValue() default false; }
{ "content_hash": "97dcfcb0f1dc3b6c99a67904aaa7616e", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 68, "avg_line_length": 36.05263157894737, "alnum_prop": 0.8218978102189781, "repo_name": "rogelio-o/csmongo", "id": "cfd20f24af008227f9905bc479d55bbd436f4600", "size": "685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "csmongo/src/main/java/com/cloudsiness/csmongo/active/validators/unique/Unique.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "308511" } ], "symlink_target": "" }
fileSvr="http://download.cloud.com/templates/devcloud/" install_xen() { aptitude update echo "install xen" aptitude -y install linux-headers-3.2.0-23-generic-pae aptitude -y install xen-hypervisor-4.1-i386 xcp-xapi echo "configure xen" sed -i -e 's/xend_start$/#xend_start/' -e 's/xend_stop$/#xend_stop/' /etc/init.d/xend update-rc.d xendomains disable sed -i 's/GRUB_DEFAULT=.\+/GRUB_DEFAULT="Xen 4.1-i386"/' /etc/default/grub echo 'GRUB_CMDLINE_XEN_DEFAULT="dom0_mem=512M,max:512M"' | cat /etc/default/grub - >> /etc/default/newgrub mv /etc/default/newgrub /etc/default/grub update-grub mkdir /usr/share/qemu ln -s /usr/share/qemu-linaro/keymaps /usr/share/qemu/keymaps cat > /etc/network/interfaces << EOF # The loopback network interface auto lo iface lo inet loopback # The primary network interface auto xenbr0 iface xenbr0 inet dhcp gateway 10.0.2.2 bridge_ports eth0 auto eth0 iface eth0 inet dhcp pre-up iptables-save < /etc/iptables.save pre-up /etc/init.d/ebtables load EOF echo TOOLSTACK=xapi > /etc/default/xen echo bridge > /etc/xcp/network.conf echo "set root password" echo "root:password" | chpasswd echo "reboot" reboot } postsetup() { #check xen dom0 is working xe host-list > /dev/null if [ $? -gt 0 ]; then print "xen dom0 is not running, make sure dom0 is installed" exit 1 fi #disable virtualbox dhcp server for Vms created by cloudstack apt-get install ebtables iptables -A POSTROUTING -t mangle -p udp --dport bootpc -j CHECKSUM --checksum-fill mac=`ifconfig xenbr0 |grep HWaddr |awk '{print $5}'` ebtables -I FORWARD -d ! $mac -i eth0 -p IPV4 --ip-prot udp --ip-dport 67:68 -j DROP iptables-save > /etc/iptables.save /etc/init.d/ebtables save echo "configure NFS server" aptitude -y install nfs-server if [ ! -d /opt/storage/secondary ];then mkdir -p /opt/storage/secondary mkdir -p /opt/storage/secondary/template/tmpl/1/1 mkdir -p /opt/storage/secondary/template/tmpl/1/5 echo "/opt/storage/secondary *(rw,no_subtree_check,no_root_squash,fsid=0)" > /etc/exports wget $fileSvr/defaulttemplates/1/dc68eb4c-228c-4a78-84fa-b80ae178fbfd.vhd -P /opt/storage/secondary/template/tmpl/1/1/ wget $fileSvr/defaulttemplates/1/template.properties -P /opt/storage/secondary/template/tmpl/1/1/ wget $fileSvr/defaulttemplates/5/ce5b212e-215a-3461-94fb-814a635b2215.vhd -P /opt/storage/secondary/template/tmpl/1/5/ wget $fileSvr/defaulttemplates/5/template.properties -P /opt/storage/secondary/template/tmpl/1/5/ /etc/init.d/nfs-kernel-server restart fi echo "configure local storage" if [ ! -d /opt/storage/primary ]; then mkdir -p /opt/storage/primary hostuuid=`xe host-list |grep uuid|awk '{print $5}'` xe sr-create host-uuid=$hostuuid name-label=local-storage shared=false type=file device-config:location=/opt/storage/primary fi echo "generate ssh key" ssh-keygen -A -q echo "configure xcp" wget $fileSvr/echo -P /usr/lib/xcp/plugins/ chmod -R 777 /usr/lib/xcp sed -i 's/VNCTERM_LISTEN=.\+/VNCTERM_LISTEN="-v 0.0.0.0:1"/' /usr/lib/xcp/lib/vncterm-wrapper echo "install cloudstack " if [ ! -d /opt/cloudstack ];then aptitude -y install git unzip openjdk-6-jdk mysql-server ant mkdir /opt/cloudstack cd /opt/cloudstack git clone https://git-wip-us.apache.org/repos/asf/incubator-cloudstack.git mkdir incubator-cloudstack/target mkdir incubator-cloudstack/dist wget http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.32/bin/apache-tomcat-6.0.32.zip -P /opt/cloudstack/ unzip apache-tomcat-6.0.32.zip echo "export CATALINA_HOME=/opt/cloudstack/apache-tomcat-6.0.32" >> /root/.bashrc cd ~ fi echo "devCloud is ready to use" } usage() { print "$0 -p: presetup enviroment, e.g. install xen, configure xcp etc" print "$0 -P: postsetup, install cloudstack, prepare template etc" } while getopts "pP" OPTION do case $OPTION in p) install_xen exit 0 ;; P) postsetup exit 0 ;; ?) usage exit ;; esac done
{ "content_hash": "131ba2657670bcb689ccb04d4967c375", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 132, "avg_line_length": 32.661654135338345, "alnum_prop": 0.6597605893186004, "repo_name": "cinderella/incubator-cloudstack", "id": "f8b69faa92e67c3c3f09530d1ebdc854f0304837", "size": "5144", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/devcloud/devcloudsetup.sh", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "30051196" }, { "name": "JavaScript", "bytes": "2530360" }, { "name": "Perl", "bytes": "184903" }, { "name": "Python", "bytes": "2076305" }, { "name": "Shell", "bytes": "471280" } ], "symlink_target": "" }
package org.teavm.backend.c.util.json; public class JsonObjectVisitor extends JsonVisitor { private JsonPropertyVisitor propertyVisitor; public JsonObjectVisitor(JsonPropertyVisitor propertyVisitor) { this.propertyVisitor = propertyVisitor; } @Override public JsonVisitor object(JsonErrorReporter reporter) { return propertyVisitor; } }
{ "content_hash": "f8f98dbabd5f5cff4c0a87ce9f0d1ac7", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 67, "avg_line_length": 25.4, "alnum_prop": 0.7506561679790026, "repo_name": "konsoletyper/teavm", "id": "08a423a7c4ea96948cee484770eb97d78d8f1e7e", "size": "990", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/org/teavm/backend/c/util/json/JsonObjectVisitor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "146734" }, { "name": "CSS", "bytes": "1533" }, { "name": "HTML", "bytes": "27508" }, { "name": "Java", "bytes": "14562907" }, { "name": "JavaScript", "bytes": "86216" }, { "name": "Shell", "bytes": "6477" } ], "symlink_target": "" }
package hydrograph.ui.engine.converter.impl; import hydrograph.ui.common.util.Constants; import hydrograph.ui.engine.converter.StraightPullConverter; import hydrograph.ui.engine.helper.ConverterHelper; import hydrograph.ui.engine.xpath.ComponentXpath; import hydrograph.ui.engine.xpath.ComponentXpathConstants; import hydrograph.ui.engine.xpath.ComponentsAttributeAndValue; import hydrograph.ui.graph.model.Component; import hydrograph.ui.graph.model.Link; import hydrograph.ui.logging.factory.LogFactory; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import hydrograph.engine.jaxb.commontypes.TypeBaseInSocket; import hydrograph.engine.jaxb.commontypes.TypeOutSocketAsInSocket; import hydrograph.engine.jaxb.commontypes.TypeStraightPullOutSocket; import hydrograph.engine.jaxb.straightpulltypes.Limit; /** * Converter to convert Limit component into engine specific limit object * * @author BITWISE */ public class LimitConverter extends StraightPullConverter { private static final Logger logger = LogFactory.INSTANCE.getLogger(LimitConverter.class); public LimitConverter(Component component) { super(component); this.baseComponent = new Limit(); this.component = component; this.properties = component.getProperties(); } @Override public void prepareForXML() { logger.debug("Generating XML for :{}", properties.get(Constants.PARAM_NAME)); super.prepareForXML(); Limit limit = (Limit) baseComponent; String count =(String)properties.get(Constants.PARAM_COUNT); if (StringUtils.isNotBlank(count)){ Limit.MaxRecords value = new Limit.MaxRecords(); limit.setMaxRecords(value); try{ Long longCount = Long.parseLong(count); value.setValue(StringUtils.isBlank(count) ? null : longCount); } catch(NumberFormatException exception){ ComponentXpath.INSTANCE.getXpathMap().put( (ComponentXpathConstants.COMPONENT_XPATH_COUNT.value().replace(ID, componentName)), new ComponentsAttributeAndValue(null, count)); } } } @Override protected List<TypeStraightPullOutSocket> getOutSocket() { logger.debug("getOutSocket - Generating TypeStraightPullOutSocket data for :{}", properties.get(Constants.PARAM_NAME)); List<TypeStraightPullOutSocket> outSockectList = new ArrayList<TypeStraightPullOutSocket>(); for (Link link : component.getSourceConnections()) { TypeStraightPullOutSocket outSocket = new TypeStraightPullOutSocket(); TypeOutSocketAsInSocket outSocketAsInsocket = new TypeOutSocketAsInSocket(); outSocketAsInsocket.setInSocketId(Constants.FIXED_INSOCKET_ID); outSocketAsInsocket.getOtherAttributes(); outSocket.setCopyOfInsocket(outSocketAsInsocket); outSocket.setId(link.getSource().getPort(link.getSourceTerminal()).getPortType() + link.getLinkNumber()); outSocket.setType(link.getSource().getPort(link.getSourceTerminal()).getPortType()); outSocket.getOtherAttributes(); outSockectList.add(outSocket); } return outSockectList; } @Override public List<TypeBaseInSocket> getInSocket() { logger.debug("Generating TypeBaseInSocket data for :{}", component.getProperties().get(Constants.PARAM_NAME)); List<TypeBaseInSocket> inSocketsList = new ArrayList<>(); for (Link link : component.getTargetConnections()) { TypeBaseInSocket inSocket = new TypeBaseInSocket(); inSocket.setFromComponentId(link.getSource().getComponentId()); inSocket.setFromSocketId(converterHelper.getFromSocketId(link)); inSocket.setFromSocketType(link.getSource().getPorts().get(link.getSourceTerminal()).getPortType()); inSocket.setId(link.getTargetTerminal()); inSocket.setType(link.getTarget().getPort(link.getTargetTerminal()).getPortType()); inSocket.getOtherAttributes(); inSocketsList.add(inSocket); } return inSocketsList; } }
{ "content_hash": "c3d29e37f31606a710d11cbdcd268911", "timestamp": "", "source": "github", "line_count": 101, "max_line_length": 112, "avg_line_length": 38.10891089108911, "alnum_prop": 0.7838399584307613, "repo_name": "capitalone/Hydrograph", "id": "cf0a8755cff13d0b5ccf9e839496b92ba7cb0590", "size": "4618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hydrograph.ui/hydrograph.ui.engine/src/main/java/hydrograph/ui/engine/converter/impl/LimitConverter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "9581" }, { "name": "CSS", "bytes": "162185" }, { "name": "HTML", "bytes": "1036397" }, { "name": "Java", "bytes": "10606203" }, { "name": "Scala", "bytes": "1464765" }, { "name": "Shell", "bytes": "12318" } ], "symlink_target": "" }
Adds an indicator to the status bar that lights up if the active editor has soft wrap enabled. ## Usage The indicator is present when the active pane is an editor and removed when the active pane is anything else. The indicator is lit when soft wrap is enabled on the active editor and dark if not. Indicator Lit: ![Indicator Lit](https://raw.githubusercontent.com/lee-dohm/soft-wrap-indicator/master/indicator-lit.png) Indicator Dark: ![Indicator Dark](https://raw.githubusercontent.com/lee-dohm/soft-wrap-indicator/master/indicator-dark.png) ### Styles The soft wrap indicator can be styled using the following classes: * `.soft-wrap-indicator` - For styling all instances of the indicator * `.soft-wrap-indicator.lit` - For styling the indicator when lit It uses the following values from `ui-variables` as defaults in order to blend in to your theme: * `@text-color` - Text color when not lit * `@text-color-highlight` - Text color when lit By default it also includes a blurred text shadow to give it a kind of glow when lit. ## License [MIT](https://github.com/lee-dohm/soft-wrap-indicator/blob/master/LICENSE.md)
{ "content_hash": "83f0361d1b5dab3d8ef752c612f5da2a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 194, "avg_line_length": 36.58064516129032, "alnum_prop": 0.7663139329805997, "repo_name": "lee-dohm/soft-wrap-indicator", "id": "535f29a295fa863a79114fae3d274e267cdee1c1", "size": "1426", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "197" }, { "name": "JavaScript", "bytes": "11573" } ], "symlink_target": "" }
"""Implements a sparse balanced and asynchronous E-I model, loosely based on Borges and Kopell, 2005. """ from __future__ import division import argparse import numpy as np from brian2 import * from syncological.async import model from syncological.ping import analyze_result, save_result parser = argparse.ArgumentParser( description="A sparse, balanced, and asynchronous E-I model.", formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument( "name", help="Name of exp, used to save results as hdf5." ) parser.add_argument( "-t", "--time", help="Simulation run time (in ms)", default=2, type=float ) parser.add_argument( "--stim", help="Simulus time (in ms)", default=1.5, type=float ) parser.add_argument( "--rate", help="Stimulus firing rate (approx)", default=5, type=float ) parser.add_argument( "--w_e", help="Input weight to E (msiemens)", default=0.5, type=float ) parser.add_argument( "--w_i", help="Input weight to E (msiemens)", default=0.5, type=float ) parser.add_argument( "--w_ei", help="Weight E -> I (msiemens)", default=0.1, type=float ) parser.add_argument( "--w_ie", help="Weight I -> E (msiemens)", default=0.5, type=float ) parser.add_argument( "--seed", help="Seed value", default=None ) args = parser.parse_args() try: seed = int(args.seed) except TypeError: seed = None result = model( args.time, args.stim, args.rate, args.w_e, args.w_i, args.w_ei, args.w_ie, seed=seed ) save_result(args.name, result) analysis = analyze_result(args.name, args.stim, result, fs=10000, save=True)
{ "content_hash": "4a454163624293a7066176411caa23c0", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 76, "avg_line_length": 20.925925925925927, "alnum_prop": 0.6489675516224189, "repo_name": "voytekresearch/syncological", "id": "12f530849cb9fb87f3e2ec141728cdeffae6c7f1", "size": "1741", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "bin/async.py", "mode": "33188", "license": "mit", "language": [ { "name": "Jupyter Notebook", "bytes": "1897596" }, { "name": "Makefile", "bytes": "13307" }, { "name": "Python", "bytes": "56039" }, { "name": "R", "bytes": "11198" } ], "symlink_target": "" }
package org.springframework.cloud.stream.binder.kafka.streams.function; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.kafka.streams.kstream.GlobalKTable; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KTable; import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.ResolvableType; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; /** * Custom {@link org.springframework.context.annotation.Condition} that detects the presence * of java.util.Function|Consumer beans. Used for Kafka Streams function support. * * @author Soby Chacko * @since 2.2.0 */ public class FunctionDetectorCondition extends SpringBootCondition { private static final Log LOG = LogFactory.getLog(FunctionDetectorCondition.class); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) { if (context != null && context.getBeanFactory() != null) { String[] functionTypes = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), Function.class, true, false); String[] consumerTypes = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), Consumer.class, true, false); String[] biFunctionTypes = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), BiFunction.class, true, false); String[] biConsumerTypes = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(context.getBeanFactory(), BiConsumer.class, true, false); List<String> functionComponents = new ArrayList<>(); functionComponents.addAll(Arrays.asList(functionTypes)); functionComponents.addAll(Arrays.asList(consumerTypes)); functionComponents.addAll(Arrays.asList(biFunctionTypes)); functionComponents.addAll(Arrays.asList(biConsumerTypes)); List<String> kafkaStreamsFunctions = pruneFunctionBeansForKafkaStreams(functionComponents, context); if (!CollectionUtils.isEmpty(kafkaStreamsFunctions)) { return ConditionOutcome.match("Matched. Function/BiFunction/Consumer beans found"); } else { return ConditionOutcome.noMatch("No match. No Function/BiFunction/Consumer beans found"); } } return ConditionOutcome.noMatch("No match. No Function/BiFunction/Consumer beans found"); } private static List<String> pruneFunctionBeansForKafkaStreams(List<String> functionComponents, ConditionContext context) { final List<String> prunedList = new ArrayList<>(); for (String key : functionComponents) { final Class<?> classObj = ClassUtils.resolveClassName(((AnnotatedBeanDefinition) context.getBeanFactory().getBeanDefinition(key)) .getMetadata().getClassName(), ClassUtils.getDefaultClassLoader()); try { Method[] methods = classObj.getDeclaredMethods(); Optional<Method> kafkaStreamMethod = Arrays.stream(methods).filter(m -> m.getName().equals(key)).findFirst(); // check if the bean name is overridden. if (kafkaStreamMethod.isEmpty()) { final BeanDefinition beanDefinition = context.getBeanFactory().getBeanDefinition(key); final String factoryMethodName = beanDefinition.getFactoryMethodName(); kafkaStreamMethod = Arrays.stream(methods).filter(m -> m.getName().equals(factoryMethodName)).findFirst(); } if (kafkaStreamMethod.isPresent()) { Method method = kafkaStreamMethod.get(); ResolvableType resolvableType = ResolvableType.forMethodReturnType(method, classObj); final Class<?> rawClass = resolvableType.getGeneric(0).getRawClass(); if (rawClass == KStream.class || rawClass == KTable.class || rawClass == GlobalKTable.class) { prunedList.add(key); } } else { //check if it is a @Component bean. Optional<Method> componentBeanMethod = Arrays.stream(methods).filter( m -> (m.getName().equals("apply") || m.getName().equals("accept")) && isKafkaStreamsTypeFound(m)).findFirst(); if (componentBeanMethod.isPresent()) { Method method = componentBeanMethod.get(); final ResolvableType resolvableType1 = ResolvableType.forMethodParameter(method, 0); final Class<?> rawClass = resolvableType1.getRawClass(); if (rawClass == KStream.class || rawClass == KTable.class || rawClass == GlobalKTable.class) { prunedList.add(key); } } } } catch (Exception e) { LOG.error("Function not found: " + key, e); } } return prunedList; } private static boolean isKafkaStreamsTypeFound(Method method) { return KStream.class.isAssignableFrom(method.getParameters()[0].getType()) || KTable.class.isAssignableFrom(method.getParameters()[0].getType()) || GlobalKTable.class.isAssignableFrom(method.getParameters()[0].getType()); } }
{ "content_hash": "2bd268baea337cf1d9781875b9ae8788", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 139, "avg_line_length": 44.46031746031746, "alnum_prop": 0.7631203141735095, "repo_name": "spring-cloud/spring-cloud-stream", "id": "eac3bd7ac8421035b5547cbc4e587096778b96c5", "size": "6223", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "binders/kafka-binder/spring-cloud-stream-binder-kafka-streams/src/main/java/org/springframework/cloud/stream/binder/kafka/streams/function/FunctionDetectorCondition.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2796695" }, { "name": "Kotlin", "bytes": "1141" }, { "name": "Shell", "bytes": "4133" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2f797bc728a1f9c08a8db800dc877516", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "1b807ab2b52380088916212e55068aaa61e6ecdb", "size": "170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Xanthorrhoeaceae/Apicra/Apicra aspera/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Sprache; using Versatile; using Alpheus; namespace DevAudit.AuditLibrary { public class YarnPackageSource : PackageSource, IDeveloperPackageSource { #region Constructors public YarnPackageSource(Dictionary<string, object> package_source_options, EventHandler<EnvironmentEventArgs> message_handler = null) : base(package_source_options, message_handler) { } #endregion #region Overriden members public override string PackageManagerId { get { return "yarn"; } } public override string PackageManagerLabel { get { return "Yarn"; } } public override string DefaultPackageManagerConfigurationFile { get { return "package.json"; } } public override IEnumerable<Package> GetPackages(params string[] o) { List<Package> packages = new List<Package>(); AuditFileInfo config_file = this.AuditEnvironment.ConstructFile(this.PackageManagerConfigurationFile); JObject json = (JObject)JToken.Parse(config_file.ReadAsText()); JObject dependencies = (JObject)json["dependencies"]; JObject dev_dependencies = (JObject)json["devDependencies"]; JObject peer_dependencies = (JObject)json["peerDependencies"]; JObject optional_dependencies = (JObject)json["optionalDependencies"]; JObject bundled_dependencies = (JObject)json["bundledDependencies"]; if (dependencies != null) { packages.AddRange(dependencies.Properties() .SelectMany(d => GetDeveloperPackages(d.Name.Replace("@", ""), d.Value.ToString()))); } if (dev_dependencies != null) { packages.AddRange(dev_dependencies.Properties() .SelectMany(d => GetDeveloperPackages(d.Name.Replace("@", ""), d.Value.ToString()))); } if (peer_dependencies != null) { packages.AddRange(peer_dependencies.Properties() .SelectMany(d => GetDeveloperPackages(d.Name.Replace("@", ""), d.Value.ToString()))); } if (optional_dependencies != null) { packages.AddRange(optional_dependencies.Properties() .SelectMany(d => GetDeveloperPackages(d.Name.Replace("@", ""), d.Value.ToString()))); } if (bundled_dependencies != null) { packages.AddRange(bundled_dependencies.Properties() .SelectMany(d => GetDeveloperPackages(d.Name.Replace("@", ""), d.Value.ToString()))); } if (!string.IsNullOrEmpty(this.PackageSourceLockFile)) { this.GetPackageManagerLockFilePackages(packages); } return packages; } public override bool IsVulnerabilityVersionInPackageVersionRange(string vulnerability_version, string package_version) { string message = ""; bool r = SemanticVersion.RangeIntersect(vulnerability_version, package_version, out message); if (!r && !string.IsNullOrEmpty(message)) { throw new Exception(message); } else return r; } #endregion #region Properties public string PackageSourceLockFile {get; set;} public string DefaultPackageSourceLockFile {get; } = "yarn.lock"; #endregion #region Methods public bool PackageVersionIsRange(string version) { var lcs = SemanticVersion.Grammar.Range.Parse(version); if (lcs.Count > 1) { return true; } else if (lcs.Count == 1) { var cs = lcs.Single(); if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal) { return false; } else { return true; } } else throw new ArgumentException($"Failed to parser {version} as a Yarn version."); } public List<string> GetMinimumPackageVersions(string version) { if (version == "*") { this.AuditEnvironment.Debug("Using {0} package version {1} which satisfies range {2}.", this.PackageManagerLabel, "0.1", version); return new List<string>(1) {"0.1"}; } else if (version.StartsWith("git")) { this.AuditEnvironment.Info("Using {0} package version {1} since it specifies a git commit in the version field.", this.PackageManagerLabel, "0.1", version); return new List<string>(1) {"0.1"}; } else if (version.StartsWith("file")) { this.AuditEnvironment.Info("Using {0} package version {1} since it specifies a file in the version field.", this.PackageManagerLabel, "0.1", version); return new List<string>(1) { "0.1" }; } else if (version.StartsWith("http")) { this.AuditEnvironment.Info("Using {0} package version {1} since it specifies an http/https URL in the version field.", this.PackageManagerLabel, "0.1", version); return new List<string>(1) { "0.1" }; } else if (version.StartsWith("npm:")) { var s = version.Split('@').Last(); this.AuditEnvironment.Info("Using {0} package version {1} since it specifies an npm package in the version field.", this.PackageManagerLabel, s, version); return new List<string>(1) { s }; } var lcs = SemanticVersion.Grammar.Range.Parse(version); List<string> minVersions = new List<string>(); foreach(ComparatorSet<SemanticVersion> cs in lcs) { if (cs.Count == 1 && cs.Single().Operator == ExpressionType.Equal) { minVersions.Add(cs.Single().Version.ToNormalizedString()); } else { var gt = cs.Where(c => c.Operator == ExpressionType.GreaterThan || c.Operator == ExpressionType.GreaterThanOrEqual).Single(); if (gt.Operator == ExpressionType.GreaterThan) { var v = gt.Version; minVersions.Add((v++).ToNormalizedString()); this.AuditEnvironment.Debug("Using {0} package version {1} which satisfies range {2}.", this.PackageManagerLabel, (v++).ToNormalizedString(), version); } else { minVersions.Add(gt.Version.ToNormalizedString()); this.AuditEnvironment.Debug("Using {0} package version {1} which satisfies range {2}.", this.PackageManagerLabel, gt.Version.ToNormalizedString(), version); } } } return minVersions; } public List<Package> GetDeveloperPackages(string name, string version, string vendor = null, string group = null, string architecture = null) { return GetMinimumPackageVersions(version).Select(v => new Package("npm", name, v, vendor, group, architecture)).ToList(); } public void GetPackageManagerLockFilePackages(List<Package> packages) { int origCount = packages.Count; AuditFileInfo f = this.AuditEnvironment.ConstructFile(this.PackageSourceLockFile); string text = f.ReadAsText(); string[] lines = text.Split(new[] { "\n" }, StringSplitOptions.None); bool insideDeps = false; List<string> deps = new List<string>(); for(int i = 0; i < lines.Length; i++) { string line = lines[i]; if (!insideDeps && line.Trim().StartsWith("dependencies:")) { insideDeps = true; continue; } else if(insideDeps && string.IsNullOrEmpty(line.Trim()) || line.Trim() == "optionalDependencies:") { insideDeps = false; continue; } else if (insideDeps) { deps.Add(line); } else { continue; } } foreach(var d in deps) { var m = dRegEx.Match(d); if (m.Success) { string n = m.Groups[1].Value.Replace("@", "").Trim(); string v = m.Groups[2].Value.Trim(); var depPackages = GetDeveloperPackages(n, v); foreach(var package in depPackages) { if(!packages.Any(p => p.Name == package.Name && p.Version == package.Version)) { packages.Add(package); } } } else { this.AuditEnvironment.Error("Could not parse lock file dependency line {0}. Skipping.", d.Trim()); } } //var m = l.Matches(text); if (packages.Count > origCount) { this.AuditEnvironment.Info("Added {0} package dependencies from Yarn lock file {1}.", packages.Count - origCount, this.PackageSourceLockFile); } } #endregion #region Fields private static Regex l = new Regex("\"@\\S+\":\\s+.+\"", RegexOptions.Compiled); private static Regex dRegEx = new Regex("^\\s+\"?(\\S+?)\"?\\s+\"?(.+?)\"?$", RegexOptions.Compiled); #endregion } }
{ "content_hash": "60459dc3a0dffa9d81a79bf9ce8218a7", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 190, "avg_line_length": 41.05813953488372, "alnum_prop": 0.5167563485320494, "repo_name": "OSSIndex/DevAudit", "id": "28386dd70b53a9728d5fade65d434e4551f4bc79", "size": "10595", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "DevAudit.AuditLibrary/PackageSources/YarnPackageSource.cs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "4606" }, { "name": "C#", "bytes": "2395353" }, { "name": "Dockerfile", "bytes": "1310" }, { "name": "Roff", "bytes": "35976" }, { "name": "Shell", "bytes": "3001" } ], "symlink_target": "" }
namespace v8 { namespace internal { namespace compiler { namespace { bool CanAllocate(const Node* node) { switch (node->opcode()) { case IrOpcode::kBitcastTaggedToWord: case IrOpcode::kBitcastWordToTagged: case IrOpcode::kChangeCompressedToTagged: case IrOpcode::kChangeCompressedSignedToTaggedSigned: case IrOpcode::kChangeCompressedPointerToTaggedPointer: case IrOpcode::kChangeTaggedToCompressed: case IrOpcode::kChangeTaggedSignedToCompressedSigned: case IrOpcode::kChangeTaggedPointerToCompressedPointer: case IrOpcode::kComment: case IrOpcode::kAbortCSAAssert: case IrOpcode::kDebugBreak: case IrOpcode::kDeoptimizeIf: case IrOpcode::kDeoptimizeUnless: case IrOpcode::kEffectPhi: case IrOpcode::kIfException: case IrOpcode::kLoad: case IrOpcode::kLoadElement: case IrOpcode::kLoadField: case IrOpcode::kLoadFromObject: case IrOpcode::kPoisonedLoad: case IrOpcode::kProtectedLoad: case IrOpcode::kProtectedStore: case IrOpcode::kRetain: // TODO(tebbi): Store nodes might do a bump-pointer allocation. // We should introduce a special bump-pointer store node to // differentiate that. case IrOpcode::kStore: case IrOpcode::kStoreElement: case IrOpcode::kStoreField: case IrOpcode::kStoreToObject: case IrOpcode::kTaggedPoisonOnSpeculation: case IrOpcode::kUnalignedLoad: case IrOpcode::kUnalignedStore: case IrOpcode::kUnsafePointerAdd: case IrOpcode::kUnreachable: case IrOpcode::kStaticAssert: case IrOpcode::kWord32AtomicAdd: case IrOpcode::kWord32AtomicAnd: case IrOpcode::kWord32AtomicCompareExchange: case IrOpcode::kWord32AtomicExchange: case IrOpcode::kWord32AtomicLoad: case IrOpcode::kWord32AtomicOr: case IrOpcode::kWord32AtomicPairAdd: case IrOpcode::kWord32AtomicPairAnd: case IrOpcode::kWord32AtomicPairCompareExchange: case IrOpcode::kWord32AtomicPairExchange: case IrOpcode::kWord32AtomicPairLoad: case IrOpcode::kWord32AtomicPairOr: case IrOpcode::kWord32AtomicPairStore: case IrOpcode::kWord32AtomicPairSub: case IrOpcode::kWord32AtomicPairXor: case IrOpcode::kWord32AtomicStore: case IrOpcode::kWord32AtomicSub: case IrOpcode::kWord32AtomicXor: case IrOpcode::kWord32PoisonOnSpeculation: case IrOpcode::kWord64AtomicAdd: case IrOpcode::kWord64AtomicAnd: case IrOpcode::kWord64AtomicCompareExchange: case IrOpcode::kWord64AtomicExchange: case IrOpcode::kWord64AtomicLoad: case IrOpcode::kWord64AtomicOr: case IrOpcode::kWord64AtomicStore: case IrOpcode::kWord64AtomicSub: case IrOpcode::kWord64AtomicXor: case IrOpcode::kWord64PoisonOnSpeculation: return false; case IrOpcode::kCall: return !(CallDescriptorOf(node->op())->flags() & CallDescriptor::kNoAllocate); default: break; } return true; } Node* SearchAllocatingNode(Node* start, Node* limit, Zone* temp_zone) { ZoneQueue<Node*> queue(temp_zone); ZoneSet<Node*> visited(temp_zone); visited.insert(limit); queue.push(start); while (!queue.empty()) { Node* const current = queue.front(); queue.pop(); if (visited.find(current) == visited.end()) { visited.insert(current); if (CanAllocate(current)) { return current; } for (int i = 0; i < current->op()->EffectInputCount(); ++i) { queue.push(NodeProperties::GetEffectInput(current, i)); } } } return nullptr; } bool CanLoopAllocate(Node* loop_effect_phi, Zone* temp_zone) { Node* const control = NodeProperties::GetControlInput(loop_effect_phi); // Start the effect chain walk from the loop back edges. for (int i = 1; i < control->InputCount(); ++i) { if (SearchAllocatingNode(loop_effect_phi->InputAt(i), loop_effect_phi, temp_zone) != nullptr) { return true; } } return false; } Node* EffectPhiForPhi(Node* phi) { Node* control = NodeProperties::GetControlInput(phi); for (Node* use : control->uses()) { if (use->opcode() == IrOpcode::kEffectPhi) { return use; } } return nullptr; } void WriteBarrierAssertFailed(Node* node, Node* object, const char* name, Zone* temp_zone) { std::stringstream str; str << "MemoryOptimizer could not remove write barrier for node #" << node->id() << "\n"; str << " Run mksnapshot with --csa-trap-on-node=" << name << "," << node->id() << " to break in CSA code.\n"; Node* object_position = object; if (object_position->opcode() == IrOpcode::kPhi) { object_position = EffectPhiForPhi(object_position); } Node* allocating_node = nullptr; if (object_position && object_position->op()->EffectOutputCount() > 0) { allocating_node = SearchAllocatingNode(node, object_position, temp_zone); } if (allocating_node) { str << "\n There is a potentially allocating node in between:\n"; str << " " << *allocating_node << "\n"; str << " Run mksnapshot with --csa-trap-on-node=" << name << "," << allocating_node->id() << " to break there.\n"; if (allocating_node->opcode() == IrOpcode::kCall) { str << " If this is a never-allocating runtime call, you can add an " "exception to Runtime::MayAllocate.\n"; } } else { str << "\n It seems the store happened to something different than a " "direct " "allocation:\n"; str << " " << *object << "\n"; str << " Run mksnapshot with --csa-trap-on-node=" << name << "," << object->id() << " to break there.\n"; } FATAL("%s", str.str().c_str()); } } // namespace MemoryOptimizer::MemoryOptimizer( JSGraph* jsgraph, Zone* zone, PoisoningMitigationLevel poisoning_level, MemoryLowering::AllocationFolding allocation_folding, const char* function_debug_name, TickCounter* tick_counter) : memory_lowering_(jsgraph, zone, poisoning_level, allocation_folding, WriteBarrierAssertFailed, function_debug_name), jsgraph_(jsgraph), empty_state_(AllocationState::Empty(zone)), pending_(zone), tokens_(zone), zone_(zone), tick_counter_(tick_counter) {} void MemoryOptimizer::Optimize() { EnqueueUses(graph()->start(), empty_state()); while (!tokens_.empty()) { Token const token = tokens_.front(); tokens_.pop(); VisitNode(token.node, token.state); } DCHECK(pending_.empty()); DCHECK(tokens_.empty()); } void MemoryOptimizer::VisitNode(Node* node, AllocationState const* state) { tick_counter_->DoTick(); DCHECK(!node->IsDead()); DCHECK_LT(0, node->op()->EffectInputCount()); switch (node->opcode()) { case IrOpcode::kAllocate: // Allocate nodes were purged from the graph in effect-control // linearization. UNREACHABLE(); case IrOpcode::kAllocateRaw: return VisitAllocateRaw(node, state); case IrOpcode::kCall: return VisitCall(node, state); case IrOpcode::kLoadFromObject: return VisitLoadFromObject(node, state); case IrOpcode::kLoadElement: return VisitLoadElement(node, state); case IrOpcode::kLoadField: return VisitLoadField(node, state); case IrOpcode::kStoreToObject: return VisitStoreToObject(node, state); case IrOpcode::kStoreElement: return VisitStoreElement(node, state); case IrOpcode::kStoreField: return VisitStoreField(node, state); case IrOpcode::kStore: return VisitStore(node, state); default: if (!CanAllocate(node)) { // These operations cannot trigger GC. return VisitOtherEffect(node, state); } } DCHECK_EQ(0, node->op()->EffectOutputCount()); } bool MemoryOptimizer::AllocationTypeNeedsUpdateToOld(Node* const node, const Edge edge) { if (COMPRESS_POINTERS_BOOL && IrOpcode::IsCompressOpcode(node->opcode())) { // In Pointer Compression we might have a Compress node between an // AllocateRaw and the value used as input. This case is trickier since we // have to check all of the Compress node edges to test for a StoreField. for (Edge const new_edge : node->use_edges()) { if (AllocationTypeNeedsUpdateToOld(new_edge.from(), new_edge)) { return true; } } // If we arrived here, we tested all the edges of the Compress node and // didn't find it necessary to update the AllocationType. return false; } // Test to see if we need to update the AllocationType. if (node->opcode() == IrOpcode::kStoreField && edge.index() == 1) { Node* parent = node->InputAt(0); if (parent->opcode() == IrOpcode::kAllocateRaw && AllocationTypeOf(parent->op()) == AllocationType::kOld) { return true; } } return false; } void MemoryOptimizer::VisitAllocateRaw(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kAllocateRaw, node->opcode()); const AllocateParameters& allocation = AllocateParametersOf(node->op()); AllocationType allocation_type = allocation.allocation_type(); // Propagate tenuring from outer allocations to inner allocations, i.e. // when we allocate an object in old space and store a newly allocated // child object into the pretenured object, then the newly allocated // child object also should get pretenured to old space. if (allocation_type == AllocationType::kOld) { for (Edge const edge : node->use_edges()) { Node* const user = edge.from(); if (user->opcode() == IrOpcode::kStoreField && edge.index() == 0) { Node* child = user->InputAt(1); // In Pointer Compression we might have a Compress node between an // AllocateRaw and the value used as input. If so, we need to update // child to point to the StoreField. if (COMPRESS_POINTERS_BOOL && IrOpcode::IsCompressOpcode(child->opcode())) { child = child->InputAt(0); } if (child->opcode() == IrOpcode::kAllocateRaw && AllocationTypeOf(child->op()) == AllocationType::kYoung) { NodeProperties::ChangeOp(child, node->op()); break; } } } } else { DCHECK_EQ(AllocationType::kYoung, allocation_type); for (Edge const edge : node->use_edges()) { Node* const user = edge.from(); if (AllocationTypeNeedsUpdateToOld(user, edge)) { allocation_type = AllocationType::kOld; break; } } } memory_lowering()->ReduceAllocateRaw( node, allocation_type, allocation.allow_large_objects(), &state); EnqueueUses(state->effect(), state); } void MemoryOptimizer::VisitLoadFromObject(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kLoadFromObject, node->opcode()); memory_lowering()->ReduceLoadFromObject(node); EnqueueUses(node, state); } void MemoryOptimizer::VisitStoreToObject(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kStoreToObject, node->opcode()); memory_lowering()->ReduceStoreToObject(node, state); EnqueueUses(node, state); } void MemoryOptimizer::VisitLoadElement(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kLoadElement, node->opcode()); memory_lowering()->ReduceLoadElement(node); EnqueueUses(node, state); } void MemoryOptimizer::VisitLoadField(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kLoadField, node->opcode()); memory_lowering()->ReduceLoadField(node); EnqueueUses(node, state); } void MemoryOptimizer::VisitStoreElement(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kStoreElement, node->opcode()); memory_lowering()->ReduceStoreElement(node, state); EnqueueUses(node, state); } void MemoryOptimizer::VisitStoreField(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kStoreField, node->opcode()); memory_lowering()->ReduceStoreField(node, state); EnqueueUses(node, state); } void MemoryOptimizer::VisitStore(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kStore, node->opcode()); memory_lowering()->ReduceStore(node, state); EnqueueUses(node, state); } void MemoryOptimizer::VisitCall(Node* node, AllocationState const* state) { DCHECK_EQ(IrOpcode::kCall, node->opcode()); // If the call can allocate, we start with a fresh state. if (!(CallDescriptorOf(node->op())->flags() & CallDescriptor::kNoAllocate)) { state = empty_state(); } EnqueueUses(node, state); } void MemoryOptimizer::VisitOtherEffect(Node* node, AllocationState const* state) { EnqueueUses(node, state); } MemoryOptimizer::AllocationState const* MemoryOptimizer::MergeStates( AllocationStates const& states) { // Check if all states are the same; or at least if all allocation // states belong to the same allocation group. AllocationState const* state = states.front(); MemoryLowering::AllocationGroup* group = state->group(); for (size_t i = 1; i < states.size(); ++i) { if (states[i] != state) state = nullptr; if (states[i]->group() != group) group = nullptr; } if (state == nullptr) { if (group != nullptr) { // We cannot fold any more allocations into this group, but we can still // eliminate write barriers on stores to this group. // TODO(bmeurer): We could potentially just create a Phi here to merge // the various tops; but we need to pay special attention not to create // an unschedulable graph. state = AllocationState::Closed(group, nullptr, zone()); } else { // The states are from different allocation groups. state = empty_state(); } } return state; } void MemoryOptimizer::EnqueueMerge(Node* node, int index, AllocationState const* state) { DCHECK_EQ(IrOpcode::kEffectPhi, node->opcode()); int const input_count = node->InputCount() - 1; DCHECK_LT(0, input_count); Node* const control = node->InputAt(input_count); if (control->opcode() == IrOpcode::kLoop) { if (index == 0) { if (CanLoopAllocate(node, zone())) { // If the loop can allocate, we start with an empty state at the // beginning. EnqueueUses(node, empty_state()); } else { // If the loop cannot allocate, we can just propagate the state from // before the loop. EnqueueUses(node, state); } } else { // Do not revisit backedges. } } else { DCHECK_EQ(IrOpcode::kMerge, control->opcode()); // Check if we already know about this pending merge. NodeId const id = node->id(); auto it = pending_.find(id); if (it == pending_.end()) { // Insert a new pending merge. it = pending_.insert(std::make_pair(id, AllocationStates(zone()))).first; } // Add the next input state. it->second.push_back(state); // Check if states for all inputs are available by now. if (it->second.size() == static_cast<size_t>(input_count)) { // All inputs to this effect merge are done, merge the states given all // input constraints, drop the pending merge and enqueue uses of the // EffectPhi {node}. state = MergeStates(it->second); EnqueueUses(node, state); pending_.erase(it); } } } void MemoryOptimizer::EnqueueUses(Node* node, AllocationState const* state) { for (Edge const edge : node->use_edges()) { if (NodeProperties::IsEffectEdge(edge)) { EnqueueUse(edge.from(), edge.index(), state); } } } void MemoryOptimizer::EnqueueUse(Node* node, int index, AllocationState const* state) { if (node->opcode() == IrOpcode::kEffectPhi) { // An EffectPhi represents a merge of different effect chains, which // needs special handling depending on whether the merge is part of a // loop or just a normal control join. EnqueueMerge(node, index, state); } else { Token token = {node, state}; tokens_.push(token); } } Graph* MemoryOptimizer::graph() const { return jsgraph()->graph(); } } // namespace compiler } // namespace internal } // namespace v8
{ "content_hash": "4e4f4de5e1e0a57c7879586fc1e4d39c", "timestamp": "", "source": "github", "line_count": 457, "max_line_length": 80, "avg_line_length": 35.921225382932164, "alnum_prop": 0.655458089668616, "repo_name": "Simran-B/arangodb", "id": "6527dfb2877f4b4ecfc51f8396d26789e6f67ee1", "size": "16929", "binary": false, "copies": "4", "ref": "refs/heads/devel", "path": "3rdParty/V8/v7.9.317/src/compiler/memory-optimizer.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "Batchfile", "bytes": "3282" }, { "name": "C", "bytes": "275955" }, { "name": "C++", "bytes": "29221660" }, { "name": "CMake", "bytes": "375992" }, { "name": "CSS", "bytes": "212174" }, { "name": "EJS", "bytes": "218744" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "30616196" }, { "name": "LLVM", "bytes": "14753" }, { "name": "Makefile", "bytes": "526" }, { "name": "NASL", "bytes": "129286" }, { "name": "NSIS", "bytes": "49153" }, { "name": "PHP", "bytes": "46519" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "7885" }, { "name": "Python", "bytes": "181384" }, { "name": "Ruby", "bytes": "1041531" }, { "name": "SCSS", "bytes": "254419" }, { "name": "Shell", "bytes": "128175" }, { "name": "TypeScript", "bytes": "25245" }, { "name": "Yacc", "bytes": "68516" } ], "symlink_target": "" }
/* * This file is auto-generated. DO NOT MODIFY. * Original file: /Users/kishonti/work/_ronen/android-chromium-view/eyes-free/src/com/googlecode/eyesfree/braille/display/IBrailleServiceCallback.aidl */ package com.googlecode.eyesfree.braille.display; /** * Callback interface that a braille display client can expose to * get information about various braille display events. */ public interface IBrailleServiceCallback extends android.os.IInterface { /** Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements com.googlecode.eyesfree.braille.display.IBrailleServiceCallback { private static final java.lang.String DESCRIPTOR = "com.googlecode.eyesfree.braille.display.IBrailleServiceCallback"; /** Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); } /** * Cast an IBinder object into an com.googlecode.eyesfree.braille.display.IBrailleServiceCallback interface, * generating a proxy if needed. */ public static com.googlecode.eyesfree.braille.display.IBrailleServiceCallback asInterface(android.os.IBinder obj) { if ((obj==null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin!=null)&&(iin instanceof com.googlecode.eyesfree.braille.display.IBrailleServiceCallback))) { return ((com.googlecode.eyesfree.braille.display.IBrailleServiceCallback)iin); } return new com.googlecode.eyesfree.braille.display.IBrailleServiceCallback.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { return this; } @Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { switch (code) { case INTERFACE_TRANSACTION: { reply.writeString(DESCRIPTOR); return true; } case TRANSACTION_onDisplayConnected: { data.enforceInterface(DESCRIPTOR); com.googlecode.eyesfree.braille.display.BrailleDisplayProperties _arg0; if ((0!=data.readInt())) { _arg0 = com.googlecode.eyesfree.braille.display.BrailleDisplayProperties.CREATOR.createFromParcel(data); } else { _arg0 = null; } this.onDisplayConnected(_arg0); reply.writeNoException(); return true; } case TRANSACTION_onDisplayDisconnected: { data.enforceInterface(DESCRIPTOR); this.onDisplayDisconnected(); reply.writeNoException(); return true; } case TRANSACTION_onInput: { data.enforceInterface(DESCRIPTOR); com.googlecode.eyesfree.braille.display.BrailleInputEvent _arg0; if ((0!=data.readInt())) { _arg0 = com.googlecode.eyesfree.braille.display.BrailleInputEvent.CREATOR.createFromParcel(data); } else { _arg0 = null; } this.onInput(_arg0); reply.writeNoException(); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements com.googlecode.eyesfree.braille.display.IBrailleServiceCallback { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { return mRemote; } public java.lang.String getInterfaceDescriptor() { return DESCRIPTOR; } @Override public void onDisplayConnected(com.googlecode.eyesfree.braille.display.BrailleDisplayProperties displayProperties) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); if ((displayProperties!=null)) { _data.writeInt(1); displayProperties.writeToParcel(_data, 0); } else { _data.writeInt(0); } mRemote.transact(Stub.TRANSACTION_onDisplayConnected, _data, _reply, 0); _reply.readException(); } finally { _reply.recycle(); _data.recycle(); } } @Override public void onDisplayDisconnected() throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.TRANSACTION_onDisplayDisconnected, _data, _reply, 0); _reply.readException(); } finally { _reply.recycle(); _data.recycle(); } } @Override public void onInput(com.googlecode.eyesfree.braille.display.BrailleInputEvent inputEvent) throws android.os.RemoteException { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); try { _data.writeInterfaceToken(DESCRIPTOR); if ((inputEvent!=null)) { _data.writeInt(1); inputEvent.writeToParcel(_data, 0); } else { _data.writeInt(0); } mRemote.transact(Stub.TRANSACTION_onInput, _data, _reply, 0); _reply.readException(); } finally { _reply.recycle(); _data.recycle(); } } } static final int TRANSACTION_onDisplayConnected = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); static final int TRANSACTION_onDisplayDisconnected = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); static final int TRANSACTION_onInput = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2); } public void onDisplayConnected(com.googlecode.eyesfree.braille.display.BrailleDisplayProperties displayProperties) throws android.os.RemoteException; public void onDisplayDisconnected() throws android.os.RemoteException; public void onInput(com.googlecode.eyesfree.braille.display.BrailleInputEvent inputEvent) throws android.os.RemoteException; }
{ "content_hash": "398603c554f85cb1b0af248a7deedfde", "timestamp": "", "source": "github", "line_count": 166, "max_line_length": 158, "avg_line_length": 31.481927710843372, "alnum_prop": 0.7902793723689246, "repo_name": "csabakeszegh/android-chromium-view", "id": "abb1893973d029383ff8accb9a5164e42bf94950", "size": "5226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "eyes-free/gen/com/googlecode/eyesfree/braille/display/IBrailleServiceCallback.java", "mode": "33188", "license": "mit", "language": [ { "name": "Groovy", "bytes": "9278" }, { "name": "Java", "bytes": "1312185" }, { "name": "Shell", "bytes": "13168" } ], "symlink_target": "" }
namespace mojo { namespace system { void DataPipeImpl::ConvertDataToMessages(const char* buffer, size_t* start_index, size_t* current_num_bytes, MessageInTransitQueue* message_queue) { // The maximum amount of data to send per message (make it a multiple of the // element size. size_t max_message_num_bytes = GetConfiguration().max_message_num_bytes; max_message_num_bytes -= max_message_num_bytes % element_num_bytes(); DCHECK_GT(max_message_num_bytes, 0u); while (*current_num_bytes > 0) { size_t current_contiguous_num_bytes = (*start_index + *current_num_bytes > capacity_num_bytes()) ? (capacity_num_bytes() - *start_index) : *current_num_bytes; size_t message_num_bytes = std::min(max_message_num_bytes, current_contiguous_num_bytes); // Note: |message_num_bytes| fits in a |uint32_t| since the capacity does. std::unique_ptr<MessageInTransit> message(new MessageInTransit( MessageInTransit::Type::ENDPOINT_CLIENT, MessageInTransit::Subtype::ENDPOINT_CLIENT_DATA, static_cast<uint32_t>(message_num_bytes), buffer + *start_index)); message_queue->AddMessage(std::move(message)); DCHECK_LE(message_num_bytes, *current_num_bytes); *start_index += message_num_bytes; *start_index %= capacity_num_bytes(); *current_num_bytes -= message_num_bytes; } } } // namespace system } // namespace mojo
{ "content_hash": "22ca0e31a37bbf455248986fd7ef11a1", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 80, "avg_line_length": 41.5945945945946, "alnum_prop": 0.6289798570500325, "repo_name": "mdakin/engine", "id": "91ddb02af82a8c75a8e990f79f4ff8e4d4e51698", "size": "1981", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "mojo/edk/system/data_pipe_impl.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "2706" }, { "name": "C", "bytes": "303331" }, { "name": "C++", "bytes": "22853521" }, { "name": "Dart", "bytes": "1267911" }, { "name": "Groff", "bytes": "29030" }, { "name": "HTML", "bytes": "423" }, { "name": "Java", "bytes": "771538" }, { "name": "JavaScript", "bytes": "27365" }, { "name": "Makefile", "bytes": "402" }, { "name": "Objective-C", "bytes": "136844" }, { "name": "Objective-C++", "bytes": "433425" }, { "name": "Python", "bytes": "2890498" }, { "name": "Shell", "bytes": "173367" }, { "name": "Yacc", "bytes": "31141" }, { "name": "nesC", "bytes": "18347" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Runscope.Messages; using Tavis; namespace Runscope.Links { [LinkRelationType("https://runscope.com/rels/collections")] public class CollectionsLink : Link { public CollectionsLink() { } public static List<Collection> InterpretMessageBody(RunscopeApiDocument document) { return RunscopeApiDocument<Collection>.ParseDataArray(document.Data as JArray, Collection.Parse); } } }
{ "content_hash": "82e257d72abcf3cc5fc2a52fed9d2b0e", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 109, "avg_line_length": 24.64, "alnum_prop": 0.6915584415584416, "repo_name": "Runscope/dotnet-webpack", "id": "8f825e3528e58808f4da381f5d1f5fc835600a7c", "size": "618", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Runscope.WebPack/Links/CollectionsLink.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "46992" } ], "symlink_target": "" }
% MBEToolbox -- Molecular Biology & Evolution Toolbox (old files) % % Data type and file IO % codonise64 - Codonises sequence(s) % copyalnheader - Copy header information of an alignment structure into another % encodeseq - Converts nucleotide from letters to integer % seqcode - Return matrix for mapping sequence letters to integers % codontable - Return codon matrix and genetic tables matrix % readfasta - Reads data from a FASTA formatted file into a MATLAB structure % readphylip_i - Reads data from an interleaved PHYLIP formatted file % readphylip_s - Reads data from a sequential PHYLIP formatted file % printmatrix - Prints to the screen a printout of the matrix % viewseq - View sequences in alignment % writefasta - Write alignment structure into a FASTA formatted file % writephylip_i - Write alignment structure into an interleaved PHYLIP formatted file % writephylip_s - Write alignment structure into a sequential PHYLIP formatted file % writematrix - Writes data in tabular form to the file system. % writeshadedhtml - Write shaded alignment into HTML file % % Basic statistic and sequence manipulation % countntchange - Count nucleotide changes in two DNA sequences % countaachange - Count amino-acid changes in two protein sequences % countseqppq - Counts transitions (P1 and P2) and transversion (Q) % countseqpq - Counts transition (P) and transversion (Q) for the given sequence pair S % gc4 - Counts GC content at fourfold degenerate sites % cai - Calculates the Codon Adaptation Index (CAI) % rscu - Calculates the Relative Synonymous Codon Usage (RSCU) value % codonusage - Counts codon usage % codonvolatility - Calculates codon volatility % countdegeneratesites - Counts degenerate sites in two aligned DNA sequences. % countinvariablesites - Counts invariable sites. % ntcomposition - Counts nucleotide composition % aacomposition - Counts AA composition % countsegregatingsites - Count segregating sites % extractdegeneratesites - Extract 0-, 2- and 4-fold degenerate sites % extractinformativesites - Extract informative sites % extractinvariablesites - Extract invariable sites % extractpos - Extract coding position 1, 2, 3 or 1 and 2 % extractsegregatingsites - Extract segregating sites % getsynnonsyndiff - Return matrices of Syn- Nonsyn- differences between codons % getsynnonsynsites - Return matrices of Syn- Nonsyn- sites of codons % hasgap - Check if alignment contains gap % rmcodongaps - Remove codons with gaps % rmgaps - Remove gaps in alignment % revcomseq - Return reverse complement of sequences % revseq - Return reverse strand of nucleotide sequences % translatealn - Translate coding DNA sequence into protein sequence in an alignment % translateseq - Translate coding DNA sequence into protein. % smithwaterman - Local alignment by Smith & Waterman algorithm % needlemanwunsch - Gobal alignment of two proteins. % zscoreprotaln - Z score of protein alignment % alignseqfile - Align sequence file % clustalw - Mulitple sequence alignment % karlinsig - Return the Karlin genomic signatures for a given sequence % karlinsigdiff - Return the difference of Karlin genomic signatures between two given sequences % buildpssm - Builds a position specific scoring matrix (PSSM) % compcomp - Calculates the compositional complexity of sequence % cataln - Concatenate alignments % randcut - Cuts genome DNA randomly into shot fragment % % Genetic distances % dc_ng86 - Compute syn. non-syn. substitutions rates by Nei-Gojobori method % dc_li85 - Compute syn. non-syn. substitutions rates by Li85 method % dc_li93 - Computes Syn. non-syn. substitutions rates by Li93 method % dc_ml - Estimate dS and dN by using maximum likelihood algorithm % dn_ntdiff - Number of different nucleotides and gaps between two sequences % dn_pdist - p-distances (nucleotide) % dn_ntfreqdist - Euclidean distances between nucleotide frequencies % dn_jc - Jukes-Cantor Distance % dn_k2p - Kimura 80 (2-parameter) Distance % dn_tajima_nei84 - Tajima & Nei 84 Distance % dn_tamura92 - Tamura 92 Distance % dn_f84 - Felsenstain 84 Distance % dn_hky - Hasegawa, Kishino and Yano 85 (HKY) Distance % dn_gtr - Distance of GTR model % dn_jin_nei90 - Jin-Nei Gamma distance % dn_logdet - Log-det (paralinear) distance % dn_ntfreqdist - Euclidean distances between nucleotide frequencies % dp_aadiff - Uncorrected distance of protein sequences % dp_pdist - p-distances (amino acid) % dp_poisson - Poisson Correction (PC) distance (amino acid) % dp_gamma - Gamma distance (amino acids) % dp_dayhoff - Dayhoff Distance % dp_jtt - JTT Distance % dp_wag - WAG Distance % estimatefreq - Estimates base frequencies of the given sequence(s) % estimatekappa - Estimates kappa for given sequence pair % estimateyn00kappa - Estimate transition/transversion rate ratio (kappa) by method of YN00 % gammadistrib - Discrete Gamma model of rate heterogeneity % invdistrib - Invariable sites model of rate heterogeneity % % Phylogeny and likelihood % mbe_dnaml - M-file for mbe_dnaml.fig % mbe_dnapars - M-file for mbe_dnapars.fig % mbe_proml - M-file for mbe_proml.fig % mbe_protpars - M-file for mbe_protpars.fig % plotupgma - Performs UPGMA on distance matrix and produces plot of dendrogram % plotnjtree - Performs neighbor joining (NJ) on distance data and plot NJ tree % runaddin - Run add-in Phylip commands % likelidist - Estimates log likelihood of branch length (distance) % seqpairlikeli - Estimates log-likelihood of branch length (distance) % likelitree - Estimates log likelihood of a tree % model_nt - Returns a structure of nucleotide substitution model % modeljc - Returns a structure of model JC % modelk2p - Returns a structure of model K2P % modelf81 - Returns a structure of model F81 % modelhky - Returns a structure of model HKY % modelgtr - Returns a structure of model GTR % model_aa - Returns a structure of amino-acid substitution model % modeldayhoff - Returns a structure of model Dayhoff % modeljtt - Returns a structure of model JTT % modelwag - Returns a structure of model WAG % randtre - Generates a random tree with n OTUs % readnewick - Reads tree from standart file in Newick format % sitepattern - Infers site patterns for a given alignment % optimlikelidist - Optimises distance of given sequence pair under a model % optimlikelidistk2p - Optimises distance and kappa under a K2P model % optimseqpairlikeli - Optimises distance of given sequence pair under a model % parsetree - Parses string of tree in Newick format % composeQ - Computes normalized rate matrix Q from R matrix (general reversible model) % compequtest - Compositional equilibrium test % % Graph and plot % plotcorresp - Performs correspondence analysis and plot result % plotdiplomo - Plot DiPloMo graph % plotdistvstrans - Plot genetic distances (NG86) vs. transitions and transversions % plotkavsks - Plot Ka vs. Ks % plotntcomposition - Plot nucleotide composition % plotslidingwin - Performs sliding window analysis on a nucleotide sequence % plotslidingwinkaks - Plot cumulative Ka and Ks curves % plotzcurve - Z curve plotter % zcurve - Return Z curve components % % Polymorphism % reportpolysites - Report polymorphic sites % tajima89test - Tajima's Test of Neutrality % MBEGUI - MBEToolbox GUI % MBEDEMO - DEMO1: Alignment file IO % - DEMO2: Basic sequence statistics % - DEMO3: Genetic distances estimation % - DEMO4: Phylogenetic inferences % %% $Date: 5/18/2007 $
{ "content_hash": "7ca5794097afe1a909eb22ccd5d3f96a", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 109, "avg_line_length": 65.03472222222223, "alnum_prop": 0.617512012813668, "repo_name": "RiboZones/RiboLab", "id": "83192c97b45767f7e7ad9ba803cf2b06952ddd79", "size": "9365", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ToolBoxes/mbetoolbox/Contents.m", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "44" }, { "name": "C", "bytes": "1338856" }, { "name": "C++", "bytes": "22920" }, { "name": "HTML", "bytes": "136590" }, { "name": "M", "bytes": "4853" }, { "name": "Makefile", "bytes": "15751" }, { "name": "Mathematica", "bytes": "6010" }, { "name": "Matlab", "bytes": "2496907" } ], "symlink_target": "" }
<?php namespace app\components; use Yii; use yii\base\ActionFilter; class Access extends ActionFilter { public static $format = 'FORMAT_JSON'; public function beforeAction($action) { \Yii::$app->controller->enableCsrfValidation = false; $this->setBasicResponse(); return $this->filterResponse($this->auth()); } /** * setBasicResponse function. * * @access public * @return void * * set the basic response header for all REST response */ public function setBasicResponse() { Yii::$app->response->getHeaders()->set('Cache-Control', 'no-store, no-cache, must-revalidate'); Yii::$app->response->getHeaders()->set('Cache-Control', 'post-check=0, pre-check=0'); Yii::$app->response->getHeaders()->set('Pragma', 'no-cache'); Yii::$app->response->getHeaders()->set('Expires', '0'); } /** * Filter response * * @param bool $response * @return bool */ public function filterResponse($response = false) { Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; if ($response) { return true; } else { Yii::$app->response->setStatusCode('401'); return false; } } /** * check valid Key * * @return bool */ public function auth() { $wsKey = $this->getApikey(); $request = Yii::$app->request; $key = $request->post('key'); if ($key && $key == $wsKey) { return true; } return false; } public function getApikey() { return \Yii::$app->params['apiKey']; } }
{ "content_hash": "d7b0311046b5ef81a22017001169d284", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 103, "avg_line_length": 20.2, "alnum_prop": 0.5375655212580082, "repo_name": "gimox/foxboxApi", "id": "77020a379fb13f389e35b580151200ce2a0830d1", "size": "1717", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/Access.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1041" }, { "name": "CSS", "bytes": "1364" }, { "name": "PHP", "bytes": "41015" } ], "symlink_target": "" }
package model; public class County { private int id; private String countyName; private String countyCode; private int cityId; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getCountyName() { return countyName; } public void setCountyName(String countyName) { this.countyName = countyName; } public String getCountyCode() { return countyCode; } public void setCountyCode(String countyCode) { this.countyCode = countyCode; } public int getCityId() { return cityId; } public void setCityId(int cityId) { this.cityId = cityId; } }
{ "content_hash": "e57ada34dce1e15887d906800c6a60d4", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 47, "avg_line_length": 18.545454545454547, "alnum_prop": 0.7107843137254902, "repo_name": "caogeng-git/coolweather", "id": "317721e73946bc523f3778d471496067665cedf9", "size": "612", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/model/County.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "29450" } ], "symlink_target": "" }
import simplejson from flask import jsonify, request, url_for from . import viewing import iiifoo_utils from dbmodels import Manifest, Image from source_mappings import source_mapping, is_dynamic_source pub_req_optmap = ['source_url', 'manifest_id'] # Make sure to change relevant paths in tests etc. if/when this changes. @viewing.route('/iiif/<source_type>/<path:options>/manifest') @iiifoo_utils.crossdomain(origin="*") @iiifoo_utils.iiif_presentation_api_view def get_manifest(source_type, options): """Get a manifest for the given info. For authoring sources, gets it from db. For dynamic sources, creates it on request. """ source_type = source_mapping.get((source_type, 'base')) if not source_type: return jsonify({"message": "bad type", "success": False}), 502 if not is_dynamic_source(source_type): options = iiifoo_utils.parse_mapped_rest_options(options, pub_req_optmap) if not source_type: return jsonify({"message": "bad type", "success": False}), 502 manifest = Manifest.query.filter_by( id=options['manifest_id'], source_type=source_type.type_name, source_url=options['source_url'] ).first() if not manifest: return jsonify({"message": "manifest not found", "success": False}), 404 # canvases = manifest['sequences'][0]['canvases'] # canvas_image_ids = [image_id_from_canvas_id(canvas['@id']) # for canvas in canvases] # for image_id in canvas_image_ids: # if source_type.allowed_access(image_id=image_id, # cookie=session['']) # TODO responsetext = manifest.manifest else: parsed_options = iiifoo_utils.parse_rest_options(options) nph = source_type(parsed_options) responsetext = \ nph.get_manifest(url_root=request.base_url.rstrip("manifest")) return responsetext, 200 @viewing.route('/iiif/<source_type>/<path:options>' '/list/<canvas_name>') @iiifoo_utils.crossdomain(origin="*") @iiifoo_utils.iiif_presentation_api_view def get_annotation_list(source_type, options, canvas_name): source_type = source_mapping.get((source_type, 'base')) if not source_type: return jsonify({"message": "bad type", "success": False}), 502 if not is_dynamic_source(source_type): options = iiifoo_utils.parse_mapped_rest_options(options, pub_req_optmap) pi = Image.query.filter_by( identifier=canvas_name, manifest_id=options['manifest_id'], source_type=source_type.type_name, source_url=options['source_url'] ).first() if pi: response = jsonify(simplejson.loads(pi.annotations)), 200 else: response = jsonify({"message": "image not found", "success": False}), 404 return response else: options = iiifoo_utils.parse_rest_options(options) nph = source_type(options) manifest_url = url_for('.get_manifest', source_type=source_type, options=options) manifest_url = "".join([request.url_root.rstrip('/'), manifest_url]) annotations = nph.get_annotations(canvas_name=canvas_name, manifest_url=manifest_url) return jsonify(annotations) @viewing.route('/iiif/<source_type>/<path:options>/canvas/<canvas_name>') @iiifoo_utils.crossdomain(origin="*") @iiifoo_utils.iiif_presentation_api_view def get_canvas(source_type, options, canvas_name): source_type = source_mapping.get((source_type, 'base')) if not source_type: return jsonify({"message": "bad type", "success": False}), 502 if not is_dynamic_source(source_type): options = iiifoo_utils.parse_mapped_rest_options(options, pub_req_optmap) m = Manifest.query.filter_by( id=options['manifest_id'], source_type=source_type.type_name, source_url=options['source_url'] ).first() if not m: return jsonify({"message": "manifest not found", "success": False}), 404 manifest = simplejson.loads(m.manifest) canvases = manifest['sequences'][0]['canvases'] canvas_image_ids = [iiifoo_utils.image_id_from_canvas_id(canvas['@id']) for canvas in canvases] index = canvas_image_ids.index(canvas_name) response = jsonify(canvases[index]), 200 return response else: raise NotImplementedError()
{ "content_hash": "025ee2bd20bdcf31dde252683e08dd37", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 81, "avg_line_length": 42.08108108108108, "alnum_prop": 0.6118604153286235, "repo_name": "hashimmm/iiifoo", "id": "7e335a4830b70b3dee89948329178ec951ac4e8c", "size": "4671", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "iiifoo_server/viewing/iiif_metadata_api_views.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "104017" }, { "name": "Gherkin", "bytes": "7898" }, { "name": "HTML", "bytes": "11507" }, { "name": "JavaScript", "bytes": "14754" }, { "name": "Python", "bytes": "204017" }, { "name": "Shell", "bytes": "400" } ], "symlink_target": "" }
const { expect } = require('chai'); const { runDecider } = require('../../../src/decision_task_runner/run'); const NOOP = () => undefined; describe('Decision Task Runner - Running the Decider', () => { it('calls decider', () => { const task = { events: [], }; let deciderCalled = 0; function decider(items, availableDecisions) { deciderCalled++; expect(availableDecisions).to.exist; } const decisions = runDecider(task, decider, NOOP, {}); expect(decisions).to.deep.equal([]); expect(deciderCalled).to.equal(1); }); it('handles an actual decision', () => { const task = { events: [], }; function decider(items, availableDecisions) { const { startTimer } = availableDecisions; return startTimer('testTimer', 30); } const decisions = runDecider(task, decider, NOOP, {}); expect(decisions).to.deep.equal([ { decisionType: 'StartTimer', startTimerDecisionAttributes: { startToFireTimeout: '30', timerId: 'testTimer', }, }, ]); }); });
{ "content_hash": "87a4aface49ffcea837f2d9abc74c397", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 72, "avg_line_length": 31.35, "alnum_prop": 0.5087719298245614, "repo_name": "matthinz/worky-mcworkflowface", "id": "5bcc6cd194d4bd7e3bcdea7ed4401e370729b221", "size": "1254", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/unit/decision_task_runner/run_decider.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "109185" } ], "symlink_target": "" }
<?php namespace LaravelAdminPanel\Http\Controllers; use Illuminate\Http\Request; use LaravelAdminPanel\Facades\Admin; class MenuController extends BaseController { public function builder($id) { $menu = Admin::model('Menu')->findOrFail($id); $this->authorize('edit', $menu); $isModelTranslatable = is_crud_translatable(Admin::model('MenuItem')); return Admin::view('admin::menus.builder', compact('menu', 'isModelTranslatable')); } public function delete_menu($menu, $id) { $item = Admin::model('MenuItem')->findOrFail($id); $this->authorize('delete', $item->menu); $item->deleteAttributeTranslation('title'); $item->destroy($id); return redirect() ->route('admin.menus.builder', [$menu]) ->with([ 'message' => __('admin.menu_builder.successfully_deleted'), 'alert-type' => 'success', ]); } public function add_item(Request $request) { $menu = Admin::model('Menu'); $this->authorize('add', $menu); $data = $this->prepareParameters( $request->all() ); unset($data['id']); $data['order'] = Admin::model('MenuItem')->highestOrderMenuItem(); // Check if is translatable $_isTranslatable = is_crud_translatable(Admin::model('MenuItem')); if ($_isTranslatable) { // Prepare data before saving the menu $trans = $this->prepareMenuTranslations($data); } $menuItem = Admin::model('MenuItem')->create($data); // Save menu translations if ($_isTranslatable) { $menuItem->setAttributeTranslations('title', $trans, true); } return redirect() ->route('admin.menus.builder', [$data['menu_id']]) ->with([ 'message' => __('admin.menu_builder.successfully_created'), 'alert-type' => 'success', ]); } public function update_item(Request $request) { $id = $request->input('id'); $data = $this->prepareParameters( $request->except(['id']) ); $menuItem = Admin::model('MenuItem')->findOrFail($id); $this->authorize('edit', $menuItem->menu); if (is_crud_translatable($menuItem)) { $trans = $this->prepareMenuTranslations($data); // Save menu translations $menuItem->setAttributeTranslations('title', $trans, true); } $menuItem->update($data); return redirect() ->route('admin.menus.builder', [$menuItem->menu_id]) ->with([ 'message' => __('admin.menu_builder.successfully_updated'), 'alert-type' => 'success', ]); } public function order_item(Request $request) { $menuItemOrder = json_decode($request->input('order')); $this->orderMenu($menuItemOrder, null); } private function orderMenu(array $menuItems, $parentId) { foreach ($menuItems as $index => $menuItem) { $item = Admin::model('MenuItem')->findOrFail($menuItem->id); $item->order = $index + 1; $item->parent_id = $parentId; $item->save(); if (isset($menuItem->children)) { $this->orderMenu($menuItem->children, $item->id); } } } protected function prepareParameters($parameters) { switch (array_get($parameters, 'type')) { case 'route': $parameters['url'] = null; break; default: $parameters['route'] = null; $parameters['parameters'] = ''; break; } if (isset($parameters['type'])) { unset($parameters['type']); } return $parameters; } /** * Prepare menu translations. * * @param array $data menu data * * @return JSON translated item */ protected function prepareMenuTranslations(&$data) { $trans = json_decode($data['title_i18n'], true); // Set field value with the default locale $data['title'] = $trans[config('admin.multilingual.default', 'en')]; unset($data['title_i18n']); // Remove hidden input holding translations unset($data['i18n_selector']); // Remove language selector input radio return $trans; } }
{ "content_hash": "9ad818a329b86d9f84dc96d8d2341dcb", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 91, "avg_line_length": 28.06832298136646, "alnum_prop": 0.5348528435494578, "repo_name": "laraveladminpanel/admin", "id": "10cfef0c3455a6ab3846b5dfc314f0a7222d1c53", "size": "4519", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Http/Controllers/MenuController.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "46806" }, { "name": "HTML", "bytes": "89565" }, { "name": "Less", "bytes": "9725" }, { "name": "PHP", "bytes": "1495466" }, { "name": "SCSS", "bytes": "226906" } ], "symlink_target": "" }
#include "core/dom/ProcessingInstruction.h" #include "core/css/CSSStyleSheet.h" #include "core/css/MediaList.h" #include "core/css/StyleSheetContents.h" #include "core/dom/Document.h" #include "core/dom/IncrementLoadEventDelayCount.h" #include "core/dom/StyleEngine.h" #include "core/fetch/CSSStyleSheetResource.h" #include "core/fetch/FetchInitiatorTypeNames.h" #include "core/fetch/FetchRequest.h" #include "core/fetch/ResourceFetcher.h" #include "core/fetch/XSLStyleSheetResource.h" #include "core/xml/DocumentXSLT.h" #include "core/xml/XSLStyleSheet.h" #include "core/xml/parser/XMLDocumentParser.h" // for parseAttributes() namespace blink { inline ProcessingInstruction::ProcessingInstruction(Document& document, const String& target, const String& data) : CharacterData(document, data, CreateOther) , m_target(target) , m_loading(false) , m_alternate(false) , m_isCSS(false) , m_isXSL(false) , m_listenerForXSLT(nullptr) { } ProcessingInstruction* ProcessingInstruction::create(Document& document, const String& target, const String& data) { return new ProcessingInstruction(document, target, data); } ProcessingInstruction::~ProcessingInstruction() { } EventListener* ProcessingInstruction::eventListenerForXSLT() { if (!m_listenerForXSLT) return 0; return m_listenerForXSLT->toEventListener(); } void ProcessingInstruction::clearEventListenerForXSLT() { if (m_listenerForXSLT) { m_listenerForXSLT->detach(); m_listenerForXSLT.clear(); } } String ProcessingInstruction::nodeName() const { return m_target; } Node::NodeType ProcessingInstruction::getNodeType() const { return PROCESSING_INSTRUCTION_NODE; } Node* ProcessingInstruction::cloneNode(bool /*deep*/) { // FIXME: Is it a problem that this does not copy m_localHref? // What about other data members? return create(document(), m_target, m_data); } void ProcessingInstruction::didAttributeChanged() { if (m_sheet) clearSheet(); String href; String charset; if (!checkStyleSheet(href, charset)) return; process(href, charset); } bool ProcessingInstruction::checkStyleSheet(String& href, String& charset) { if (m_target != "xml-stylesheet" || !document().frame() || parentNode() != document()) return false; // see http://www.w3.org/TR/xml-stylesheet/ // ### support stylesheet included in a fragment of this (or another) document // ### make sure this gets called when adding from javascript bool attrsOk; const HashMap<String, String> attrs = parseAttributes(m_data, attrsOk); if (!attrsOk) return false; HashMap<String, String>::const_iterator i = attrs.find("type"); String type; if (i != attrs.end()) type = i->value; m_isCSS = type.isEmpty() || type == "text/css"; m_isXSL = (type == "text/xml" || type == "text/xsl" || type == "application/xml" || type == "application/xhtml+xml" || type == "application/rss+xml" || type == "application/atom+xml"); if (!m_isCSS && !m_isXSL) return false; href = attrs.get("href"); charset = attrs.get("charset"); String alternate = attrs.get("alternate"); m_alternate = alternate == "yes"; m_title = attrs.get("title"); m_media = attrs.get("media"); return !m_alternate || !m_title.isEmpty(); } void ProcessingInstruction::process(const String& href, const String& charset) { if (href.length() > 1 && href[0] == '#') { m_localHref = href.substring(1); // We need to make a synthetic XSLStyleSheet that is embedded. // It needs to be able to kick off import/include loads that // can hang off some parent sheet. if (m_isXSL && RuntimeEnabledFeatures::xsltEnabled()) { KURL finalURL(ParsedURLString, m_localHref); m_sheet = XSLStyleSheet::createEmbedded(this, finalURL); m_loading = false; } return; } clearResource(); String url = document().completeURL(href).getString(); StyleSheetResource* resource = nullptr; FetchRequest request(ResourceRequest(document().completeURL(href)), FetchInitiatorTypeNames::processinginstruction); if (m_isXSL) { if (RuntimeEnabledFeatures::xsltEnabled()) resource = XSLStyleSheetResource::fetch(request, document().fetcher()); } else { request.setCharset(charset.isEmpty() ? document().characterSet() : charset); resource = CSSStyleSheetResource::fetch(request, document().fetcher()); } if (resource) { m_loading = true; if (!m_isXSL) document().styleEngine().addPendingSheet(m_styleEngineContext); setResource(resource); } } bool ProcessingInstruction::isLoading() const { if (m_loading) return true; if (!m_sheet) return false; return m_sheet->isLoading(); } bool ProcessingInstruction::sheetLoaded() { if (!isLoading()) { if (!DocumentXSLT::sheetLoaded(document(), this)) document().styleEngine().removePendingSheet(this, m_styleEngineContext); return true; } return false; } void ProcessingInstruction::setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource* sheet) { if (!inShadowIncludingDocument()) { DCHECK(!m_sheet); return; } DCHECK(m_isCSS); CSSParserContext parserContext(document(), 0, baseURL, charset); StyleSheetContents* newSheet = StyleSheetContents::create(href, parserContext); CSSStyleSheet* cssSheet = CSSStyleSheet::create(newSheet, this); cssSheet->setDisabled(m_alternate); cssSheet->setTitle(m_title); cssSheet->setMediaQueries(MediaQuerySet::create(m_media)); m_sheet = cssSheet; // We don't need the cross-origin security check here because we are // getting the sheet text in "strict" mode. This enforces a valid CSS MIME // type. parseStyleSheet(sheet->sheetText()); } void ProcessingInstruction::setXSLStyleSheet(const String& href, const KURL& baseURL, const String& sheet) { if (!inShadowIncludingDocument()) { DCHECK(!m_sheet); return; } DCHECK(m_isXSL); m_sheet = XSLStyleSheet::create(this, href, baseURL); OwnPtr<IncrementLoadEventDelayCount> delay = IncrementLoadEventDelayCount::create(document()); parseStyleSheet(sheet); } void ProcessingInstruction::parseStyleSheet(const String& sheet) { if (m_isCSS) toCSSStyleSheet(m_sheet.get())->contents()->parseString(sheet); else if (m_isXSL) toXSLStyleSheet(m_sheet.get())->parseString(sheet); clearResource(); m_loading = false; if (m_isCSS) toCSSStyleSheet(m_sheet.get())->contents()->checkLoaded(); else if (m_isXSL) toXSLStyleSheet(m_sheet.get())->checkLoaded(); } Node::InsertionNotificationRequest ProcessingInstruction::insertedInto(ContainerNode* insertionPoint) { CharacterData::insertedInto(insertionPoint); if (!insertionPoint->inShadowIncludingDocument()) return InsertionDone; String href; String charset; bool isValid = checkStyleSheet(href, charset); if (!DocumentXSLT::processingInstructionInsertedIntoDocument(document(), this)) document().styleEngine().addStyleSheetCandidateNode(this); if (isValid) process(href, charset); return InsertionDone; } void ProcessingInstruction::removedFrom(ContainerNode* insertionPoint) { CharacterData::removedFrom(insertionPoint); if (!insertionPoint->inShadowIncludingDocument()) return; // No need to remove XSLStyleSheet from StyleEngine. if (!DocumentXSLT::processingInstructionRemovedFromDocument(document(), this)) document().styleEngine().removeStyleSheetCandidateNode(this); StyleSheet* removedSheet = m_sheet; if (m_sheet) { DCHECK_EQ(m_sheet->ownerNode(), this); clearSheet(); } // No need to remove pending sheets. clearResource(); // If we're in document teardown, then we don't need to do any notification of our sheet's removal. if (document().isActive()) document().styleEngine().setNeedsActiveStyleUpdate(removedSheet, FullStyleUpdate); } void ProcessingInstruction::clearSheet() { DCHECK(m_sheet); if (m_sheet->isLoading()) document().styleEngine().removePendingSheet(this, m_styleEngineContext); m_sheet.release()->clearOwnerNode(); } DEFINE_TRACE(ProcessingInstruction) { visitor->trace(m_sheet); visitor->trace(m_listenerForXSLT); CharacterData::trace(visitor); ResourceOwner<StyleSheetResource>::trace(visitor); } } // namespace blink
{ "content_hash": "dbfc20a79b519643036d87849c82a85c", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 188, "avg_line_length": 30.49122807017544, "alnum_prop": 0.6833141542002301, "repo_name": "axinging/chromium-crosswalk", "id": "0c9eb8c53acd5243a3f0774d6857e3dfc482e3b9", "size": "9586", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "8242" }, { "name": "AppleScript", "bytes": "6973" }, { "name": "Arduino", "bytes": "464" }, { "name": "Assembly", "bytes": "23945" }, { "name": "C", "bytes": "4103204" }, { "name": "C++", "bytes": "225022948" }, { "name": "CSS", "bytes": "949808" }, { "name": "Dart", "bytes": "74976" }, { "name": "Go", "bytes": "18155" }, { "name": "HTML", "bytes": "28206993" }, { "name": "Java", "bytes": "7651204" }, { "name": "JavaScript", "bytes": "18831169" }, { "name": "Makefile", "bytes": "96270" }, { "name": "Objective-C", "bytes": "1228122" }, { "name": "Objective-C++", "bytes": "7563676" }, { "name": "PHP", "bytes": "97817" }, { "name": "Perl", "bytes": "63937" }, { "name": "Protocol Buffer", "bytes": "418221" }, { "name": "Python", "bytes": "7855597" }, { "name": "Shell", "bytes": "472586" }, { "name": "Standard ML", "bytes": "4965" }, { "name": "XSLT", "bytes": "418" }, { "name": "nesC", "bytes": "18335" } ], "symlink_target": "" }
package com.facebook.buck.haskell; import com.facebook.buck.cxx.CxxBuckConfig; import com.facebook.buck.cxx.CxxPlatform; import com.facebook.buck.cxx.CxxPlatformUtils; import com.facebook.buck.cxx.NativeLinkable; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.model.FlavorDomain; import com.facebook.buck.rules.AbstractNodeBuilder; import com.facebook.buck.rules.coercer.SourceList; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import java.util.Optional; public class HaskellLibraryBuilder extends AbstractNodeBuilder< HaskellLibraryDescription.Arg, HaskellLibraryDescription, HaskellLibrary> { public HaskellLibraryBuilder( BuildTarget target, HaskellConfig haskellConfig, CxxBuckConfig cxxBuckConfig, FlavorDomain<CxxPlatform> cxxPlatforms) { super( new HaskellLibraryDescription(haskellConfig, cxxBuckConfig, cxxPlatforms), target); } public HaskellLibraryBuilder(BuildTarget target) { this( target, FakeHaskellConfig.DEFAULT, CxxPlatformUtils.DEFAULT_CONFIG, CxxPlatformUtils.DEFAULT_PLATFORMS); } public HaskellLibraryBuilder setSrcs(SourceList srcs) { arg.srcs = srcs; return this; } public HaskellLibraryBuilder setCompilerFlags(ImmutableList<String> flags) { arg.compilerFlags = flags; return this; } public HaskellLibraryBuilder setLinkWhole(boolean linkWhole) { arg.linkWhole = Optional.of(linkWhole); return this; } public HaskellLibraryBuilder setPreferredLinkage(NativeLinkable.Linkage preferredLinkage) { arg.preferredLinkage = Optional.of(preferredLinkage); return this; } public HaskellLibraryBuilder setDeps(ImmutableSortedSet<BuildTarget> deps) { arg.deps = deps; return this; } }
{ "content_hash": "0946fa976b1f75a08f68ab7792b54b40", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 93, "avg_line_length": 28.03030303030303, "alnum_prop": 0.7632432432432432, "repo_name": "darkforestzero/buck", "id": "ba7af27d0ea995a968a4b71a9f14514e795e9ea4", "size": "2455", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/com/facebook/buck/haskell/HaskellLibraryBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "579" }, { "name": "Batchfile", "bytes": "2093" }, { "name": "C", "bytes": "252516" }, { "name": "C#", "bytes": "237" }, { "name": "C++", "bytes": "10341" }, { "name": "CSS", "bytes": "54863" }, { "name": "D", "bytes": "1017" }, { "name": "Go", "bytes": "15018" }, { "name": "Groovy", "bytes": "3362" }, { "name": "HTML", "bytes": "6372" }, { "name": "Haskell", "bytes": "895" }, { "name": "IDL", "bytes": "128" }, { "name": "Java", "bytes": "18604983" }, { "name": "JavaScript", "bytes": "934679" }, { "name": "Kotlin", "bytes": "2079" }, { "name": "Lex", "bytes": "2595" }, { "name": "Makefile", "bytes": "1816" }, { "name": "Matlab", "bytes": "47" }, { "name": "OCaml", "bytes": "4384" }, { "name": "Objective-C", "bytes": "1171361" }, { "name": "Objective-C++", "bytes": "34" }, { "name": "PowerShell", "bytes": "244" }, { "name": "Python", "bytes": "580037" }, { "name": "Roff", "bytes": "1109" }, { "name": "Rust", "bytes": "3542" }, { "name": "Scala", "bytes": "4906" }, { "name": "Shell", "bytes": "48705" }, { "name": "Smalltalk", "bytes": "4920" }, { "name": "Standard ML", "bytes": "15" }, { "name": "Swift", "bytes": "6897" }, { "name": "Thrift", "bytes": "19820" }, { "name": "Yacc", "bytes": "323" } ], "symlink_target": "" }
require 'travis/cli' module Travis module CLI class Show < RepoCommand description "displays a build or job" def run(number = last_build.number) number = repository.branch(number).number if number !~ /^\d+(\.\d+)?$/ and repository.branch(number) entity = job(number) || build(number) error "could not find job or build #{repository.slug}##{number}" unless entity say template(__FILE__) % [ entity.class.one.capitalize, entity.number, entity.commit.subject, entity.state, entity.color, entity.pull_request? ? "pull request" : "push", entity.branch_info, entity.commit.compare_url, formatter.duration(entity.duration), formatter.time(entity.started_at), formatter.time(entity.finished_at) ] if entity.respond_to? :jobs empty_line entity.jobs.each do |job| say [ color("##{job.number} #{job.state}:".ljust(16), [job.color, :bold]), formatter.duration(job.duration).ljust(14), formatter.job_config(job.config), (color("(failure allowed)", :info) if job.allow_failures?) ].compact.join(" ").rstrip end else config = formatter.job_config(entity.config) say color("Allow Failure: ", :info) + entity.allow_failures?.inspect say color("Config: ", :info) + config unless config.empty? end if entity.respond_to? :annotations and entity.annotations.any? empty_line say color("Annotations:", :bold) entity.annotations.each do |annotation| say [ color("#{annotation.provider_name} #{annotation.status}:", [annotation.color, :bold]), color(annotation.description, annotation.color), color("(%s)" % annotation.url, :info) ].compact.join(" ").rstrip end end end end end end __END__ <[[ color("%s #%s: ", :bold) ]]> <[[ color(%p, :bold) ]]> <[[ color("State: ", :info) ]]><[[ color(%p, :%s) ]]> <[[ color("Type: ", :info) ]]>%s <[[ color("Branch: ", :info) ]]>%s <[[ color("Compare URL: ", :info) ]]>%s <[[ color("Duration: ", :info) ]]>%s <[[ color("Started: ", :info) ]]>%s <[[ color("Finished: ", :info) ]]>%s
{ "content_hash": "5720908d2a2efae8477140cb0f8c6f17", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 108, "avg_line_length": 35.04347826086956, "alnum_prop": 0.5359801488833746, "repo_name": "snordhausen/travis.rb", "id": "f802b1d2824a80501fc982142f25279590560c40", "size": "2418", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "lib/travis/cli/show.rb", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "3538" }, { "name": "Ruby", "bytes": "257889" }, { "name": "Shell", "bytes": "88295" } ], "symlink_target": "" }
namespace ash { namespace phonehub { const char kVisibleAppName[] = "visible_app_name"; const char kPackageName[] = "package_name"; const char kUserId[] = "user_id"; const char kIcon[] = "icon"; Notification::AppMetadata::AppMetadata(const std::u16string& visible_app_name, const std::string& package_name, const gfx::Image& icon, int64_t user_id) : visible_app_name(visible_app_name), package_name(package_name), icon(icon), user_id(user_id) {} Notification::AppMetadata::AppMetadata(const AppMetadata& other) = default; Notification::AppMetadata& Notification::AppMetadata::operator=( const AppMetadata& other) = default; bool Notification::AppMetadata::operator==(const AppMetadata& other) const { return visible_app_name == other.visible_app_name && package_name == other.package_name && icon == other.icon && user_id == other.user_id; } bool Notification::AppMetadata::operator!=(const AppMetadata& other) const { return !(*this == other); } base::Value Notification::AppMetadata::ToValue() const { scoped_refptr<base::RefCountedMemory> png_data = icon.As1xPNGBytes(); base::Value val(base::Value::Type::DICTIONARY); val.SetKey(kVisibleAppName, base::Value(visible_app_name)); val.SetKey(kPackageName, base::Value(package_name)); val.SetDoubleKey(kUserId, user_id); val.SetKey(kIcon, base::Value(base::Base64Encode(*png_data))); return val; } // static Notification::AppMetadata Notification::AppMetadata::FromValue( const base::Value& value) { DCHECK(value.is_dict()); DCHECK(value.FindKey(kVisibleAppName)); DCHECK(value.FindKey(kVisibleAppName)->is_string()); DCHECK(value.FindKey(kPackageName)); DCHECK(value.FindKey(kPackageName)->is_string()); DCHECK(value.FindKey(kUserId)); DCHECK(value.FindKey(kUserId)->is_double()); DCHECK(value.FindKey(kIcon)); DCHECK(value.FindKey(kIcon)->is_string()); const base::Value* visible_app_name_value = value.FindPath(kVisibleAppName); std::u16string visible_app_name_string_value; visible_app_name_value->GetAsString(&visible_app_name_string_value); std::string icon_str; base::Base64Decode(*(value.FindStringPath(kIcon)), &icon_str); gfx::Image decode_icon = gfx::Image::CreateFrom1xPNGBytes( base::RefCountedString::TakeString(&icon_str)); return Notification::AppMetadata( visible_app_name_string_value, *(value.FindStringPath(kPackageName)), decode_icon, *(value.FindDoublePath(kUserId))); } Notification::Notification( int64_t id, const AppMetadata& app_metadata, const base::Time& timestamp, Importance importance, Notification::Category category, const base::flat_map<Notification::ActionType, int64_t>& action_id_map, InteractionBehavior interaction_behavior, const absl::optional<std::u16string>& title, const absl::optional<std::u16string>& text_content, const absl::optional<gfx::Image>& shared_image, const absl::optional<gfx::Image>& contact_image) : id_(id), app_metadata_(app_metadata), timestamp_(timestamp), importance_(importance), category_(category), action_id_map_(action_id_map), interaction_behavior_(interaction_behavior), title_(title), text_content_(text_content), shared_image_(shared_image), contact_image_(contact_image) {} Notification::Notification(const Notification& other) = default; Notification::~Notification() = default; bool Notification::operator<(const Notification& other) const { return std::tie(timestamp_, id_) < std::tie(other.timestamp_, other.id_); } bool Notification::operator==(const Notification& other) const { return id_ == other.id_ && app_metadata_ == other.app_metadata_ && timestamp_ == other.timestamp_ && importance_ == other.importance_ && category_ == other.category_ && action_id_map_ == other.action_id_map_ && interaction_behavior_ == other.interaction_behavior_ && title_ == other.title_ && text_content_ == other.text_content_ && shared_image_ == other.shared_image_ && contact_image_ == other.contact_image_; } bool Notification::operator!=(const Notification& other) const { return !(*this == other); } std::ostream& operator<<(std::ostream& stream, const Notification::AppMetadata& app_metadata) { stream << "{VisibleAppName: \"" << app_metadata.visible_app_name << "\", " << "PackageName: \"" << app_metadata.package_name << "\"}"; return stream; } std::ostream& operator<<(std::ostream& stream, Notification::Importance importance) { switch (importance) { case Notification::Importance::kUnspecified: stream << "[Unspecified]"; break; case Notification::Importance::kNone: stream << "[None]"; break; case Notification::Importance::kMin: stream << "[Min]"; break; case Notification::Importance::kLow: stream << "[Low]"; break; case Notification::Importance::kDefault: stream << "[Default]"; break; case Notification::Importance::kHigh: stream << "[High]"; break; } return stream; } std::ostream& operator<<(std::ostream& stream, Notification::InteractionBehavior behavior) { switch (behavior) { case Notification::InteractionBehavior::kNone: stream << "[None]"; break; case Notification::InteractionBehavior::kOpenable: stream << "[Openable]"; break; } return stream; } std::ostream& operator<<(std::ostream& stream, Notification::Category catetory) { switch (catetory) { case Notification::Category::kNone: stream << "[None]"; break; case Notification::Category::kConversation: stream << "[Conversation]"; break; case Notification::Category::kIncomingCall: stream << "[IncomingCall]"; break; case Notification::Category::kOngoingCall: stream << "[OngoingCall]"; break; case Notification::Category::kScreenCall: stream << "[ScreenCall]"; break; } return stream; } std::ostream& operator<<(std::ostream& stream, const Notification& notification) { stream << "{Id: " << notification.id() << ", " << "App: " << notification.app_metadata() << ", " << "Timestamp: " << notification.timestamp() << ", " << "Importance: " << notification.importance() << ", " << "Category: " << notification.category() << ", " << "InteractionBehavior: " << notification.interaction_behavior() << "}"; return stream; } } // namespace phonehub } // namespace ash
{ "content_hash": "59fbbd6fe48f94d2f339ccdea06e4431", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 78, "avg_line_length": 34.40909090909091, "alnum_prop": 0.6418611478056656, "repo_name": "ric2b/Vivaldi-browser", "id": "ad4aa4ebe60d256a4f55eaa2230fa278caa017d3", "size": "7138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/ash/components/phonehub/notification.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
using namespace std; using namespace boost; namespace impala { scoped_ptr<HdfsFsCache> HdfsFsCache::instance_; void HdfsFsCache::Init() { DCHECK(HdfsFsCache::instance_.get() == NULL); HdfsFsCache::instance_.reset(new HdfsFsCache()); } hdfsFS HdfsFsCache::GetConnection(const string& host, int port) { lock_guard<mutex> l(lock_); HdfsFsMap::iterator i = fs_map_.find(make_pair(host, port)); if (i == fs_map_.end()) { hdfsBuilder* hdfs_builder = hdfsNewBuilder(); if (!host.empty()) { hdfsBuilderSetNameNode(hdfs_builder, host.c_str()); } else { // Connect to local filesystem hdfsBuilderSetNameNode(hdfs_builder, NULL); } hdfsBuilderSetNameNodePort(hdfs_builder, port); hdfsFS conn = hdfsBuilderConnect(hdfs_builder); DCHECK(conn != NULL); fs_map_.insert(make_pair(make_pair(host, port), conn)); return conn; } else { return i->second; } } hdfsFS HdfsFsCache::GetDefaultConnection() { // "default" uses the default NameNode configuration from the XML configuration files. return GetConnection("default", 0); } hdfsFS HdfsFsCache::GetLocalConnection() { return GetConnection("", 0); } }
{ "content_hash": "41b6a7923508e320f3f8ba08baf23001", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 88, "avg_line_length": 27.209302325581394, "alnum_prop": 0.6888888888888889, "repo_name": "gistic/PublicSpatialImpala", "id": "0e35505b653551a6296563aee04ff0cbdedc5014", "size": "1943", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "be/src/runtime/hdfs-fs-cache.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Bison", "bytes": "77235" }, { "name": "C", "bytes": "338448" }, { "name": "C++", "bytes": "5257233" }, { "name": "CSS", "bytes": "86925" }, { "name": "Java", "bytes": "3038316" }, { "name": "Objective-C", "bytes": "15162" }, { "name": "PHP", "bytes": "361" }, { "name": "Python", "bytes": "1303612" }, { "name": "Shell", "bytes": "99373" }, { "name": "Thrift", "bytes": "230697" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@color/qs_detail_transition" /> <item android:drawable="?android:colorPrimary" /> </transition>
{ "content_hash": "9a4323d5ca36dc9598b54c98e413a127", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 61, "avg_line_length": 40, "alnum_prop": 0.7083333333333334, "repo_name": "BatMan-Rom/ModdedFiles", "id": "960dc7296f5884c887efbd0c5721f9ac6488f725", "size": "240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SystemUI/res/drawable/qs_customizer_background.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "GLSL", "bytes": "15069" }, { "name": "HTML", "bytes": "139176" }, { "name": "Smali", "bytes": "541934400" } ], "symlink_target": "" }
package com.intellij.codeInsight.daemon.impl; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.util.ProperTextRange; import com.intellij.openapi.util.TextRange; import com.intellij.util.SmartList; import com.intellij.util.containers.MultiMap; import javax.annotation.Nonnull; import java.util.Collection; import java.util.HashMap; import java.util.Map; class HighlightersRecycler { private final MultiMap<TextRange, RangeHighlighter> incinerator = new MultiMap<TextRange, RangeHighlighter>(){ @Override protected Map<TextRange, Collection<RangeHighlighter>> createMap() { return new HashMap<TextRange, Collection<RangeHighlighter>>(); } @Override protected Collection<RangeHighlighter> createCollection() { return new SmartList<RangeHighlighter>(); } }; void recycleHighlighter(@Nonnull RangeHighlighter highlighter) { if (highlighter.isValid()) { incinerator.putValue(ProperTextRange.create(highlighter), highlighter); } } RangeHighlighter pickupHighlighterFromGarbageBin(int startOffset, int endOffset, int layer){ TextRange range = new TextRange(startOffset, endOffset); Collection<RangeHighlighter> collection = incinerator.get(range); for (RangeHighlighter highlighter : collection) { if (highlighter.isValid() && highlighter.getLayer() == layer) { incinerator.remove(range, highlighter); return highlighter; } } return null; } @Nonnull Collection<? extends RangeHighlighter> forAllInGarbageBin() { return incinerator.values(); } }
{ "content_hash": "fc9f6b77230dda89989f86ecb79de447", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 112, "avg_line_length": 32.08, "alnum_prop": 0.7481296758104738, "repo_name": "consulo/consulo", "id": "bd1ea211a7dca0d383b573afcea596f9a14d6a6a", "size": "2204", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/base/analysis-impl/src/main/java/com/intellij/codeInsight/daemon/impl/HighlightersRecycler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "299" }, { "name": "C", "bytes": "52718" }, { "name": "C++", "bytes": "72795" }, { "name": "CMake", "bytes": "854" }, { "name": "CSS", "bytes": "64655" }, { "name": "Groovy", "bytes": "36006" }, { "name": "HTML", "bytes": "173780" }, { "name": "Java", "bytes": "64026758" }, { "name": "Lex", "bytes": "5909" }, { "name": "Objective-C", "bytes": "23787" }, { "name": "Python", "bytes": "3276" }, { "name": "SCSS", "bytes": "9782" }, { "name": "Shell", "bytes": "5689" }, { "name": "Thrift", "bytes": "1216" }, { "name": "XSLT", "bytes": "49230" } ], "symlink_target": "" }
require File.expand_path(File.dirname(__FILE__)) + '/integration_helper' require 'lhm/table' require 'lhm/migration' describe Lhm::Chunker do include IntegrationHelper before(:each) { connect_master! } describe 'copying' do before(:each) do @origin = table_create(:origin) @destination = table_create(:destination) @migration = Lhm::Migration.new(@origin, @destination) end it 'should copy 23 rows from origin to destination with time based throttler' do 23.times { |n| execute("insert into origin set id = '#{ n * n + 23 }'") } printer = MiniTest::Mock.new 5.times { printer.expect(:notify, :return_value, [Fixnum, Fixnum]) } printer.expect(:end, :return_value, []) Lhm::Chunker.new( @migration, connection, { :throttler => Lhm::Throttler::Time.new(:stride => 100), :printer => printer } ).run slave do count_all(@destination.name).must_equal(23) end printer.verify end it 'should copy 23 rows from origin to destination with slave lag based throttler' do 23.times { |n| execute("insert into origin set id = '#{ n * n + 23 }'") } printer = MiniTest::Mock.new 5.times { printer.expect(:notify, :return_value, [Fixnum, Fixnum]) } printer.expect(:end, :return_value, []) Lhm::Chunker.new( @migration, connection, { :throttler => Lhm::Throttler::SlaveLag.new(:stride => 100), :printer => printer } ).run slave do count_all(@destination.name).must_equal(23) end printer.verify end it 'should throttle work stride based on slave lag' do 5.times { |n| execute("insert into origin set id = '#{ (n * n) + 1 }'") } printer = MiniTest::Mock.new 15.times { printer.expect(:notify, :return_value, [Fixnum, Fixnum]) } printer.expect(:end, :return_value, []) throttler = Lhm::Throttler::SlaveLag.new(:stride => 10, :allowed_lag => 0) def throttler.max_current_slave_lag 1 end Lhm::Chunker.new( @migration, connection, { :throttler => throttler, :printer => printer } ).run assert_equal(Lhm::Throttler::SlaveLag::INITIAL_TIMEOUT * 2 * 2, throttler.timeout_seconds) slave do count_all(@destination.name).must_equal(5) end printer.verify end it 'should detect a single slave with no lag in the default configuration' do 5.times { |n| execute("insert into origin set id = '#{ (n * n) + 1 }'") } printer = MiniTest::Mock.new 15.times { printer.expect(:notify, :return_value, [Fixnum, Fixnum]) } printer.expect(:end, :return_value, []) throttler = Lhm::Throttler::SlaveLag.new(:stride => 10, :allowed_lag => 0) def throttler.slave_hosts ['127.0.0.1'] end if master_slave_mode? def throttler.slave_connection(slave) adapter_method = defined?(Mysql2) ? 'mysql2_connection' : 'mysql_connection' config = ActiveRecord::Base.connection_pool.spec.config.dup config[:host] = slave config[:port] = 3307 ActiveRecord::Base.send(adapter_method, config) end end Lhm::Chunker.new( @migration, connection, { :throttler => throttler, :printer => printer } ).run assert_equal(Lhm::Throttler::SlaveLag::INITIAL_TIMEOUT, throttler.timeout_seconds) assert_equal(0, throttler.send(:max_current_slave_lag)) slave do count_all(@destination.name).must_equal(5) end printer.verify end end end
{ "content_hash": "2ec08c80c136f2c10b86470834873481", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 115, "avg_line_length": 31.069565217391304, "alnum_prop": 0.6154492023509656, "repo_name": "timeplayinc/lhm", "id": "4bf6d521a824d121e12e9cb28a02b9921a8805be", "size": "3669", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "spec/integration/chunker_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ruby", "bytes": "98692" }, { "name": "Shell", "bytes": "3306" } ], "symlink_target": "" }
package com.example.avjindersinghsekhon.minimaltodo; import io.reactivex.Single; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by ismael on 6/12/17. */ public class ReceiptInteractor { private ReceiptApi api; public ReceiptInteractor() { Retrofit retrofit = new Retrofit.Builder() .baseUrl(BuildConfig.API_BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); api = retrofit.create(ReceiptApi.class); } public ReceiptInteractor(ReceiptApi api) { this.api = api; } public Single<Receipt> getReceipt(String txCode) { return api.getReceipt(txCode, BuildConfig.MERCHANT_ID); } }
{ "content_hash": "290dfc1615e2df3de90ee218d7c1f080", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 74, "avg_line_length": 26.352941176470587, "alnum_prop": 0.6886160714285714, "repo_name": "ismaellg/Minimal-Todo", "id": "c5df21b274044580fc5ec4c11fc892c80d372a5d", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/example/avjindersinghsekhon/minimaltodo/ReceiptInteractor.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "119249" } ], "symlink_target": "" }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.bpmn.converter; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.activiti.bpmn.converter.util.BpmnXMLUtil; import org.activiti.bpmn.model.BaseElement; import org.activiti.bpmn.model.BpmnModel; import org.activiti.bpmn.model.StartEvent; import org.activiti.bpmn.model.alfresco.AlfrescoStartEvent; import org.apache.commons.lang3.StringUtils; /** * @author Tijs Rademakers */ public class StartEventXMLConverter extends BaseBpmnXMLConverter { public Class<? extends BaseElement> getBpmnElementType() { return StartEvent.class; } @Override protected String getXMLElementName() { return ELEMENT_EVENT_START; } @Override protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { String formKey = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_FORM_FORMKEY); StartEvent startEvent = null; if (StringUtils.isNotEmpty(formKey)) { if (model.getStartEventFormTypes() != null && model.getStartEventFormTypes().contains(formKey)) { startEvent = new AlfrescoStartEvent(); } } if (startEvent == null) { startEvent = new StartEvent(); } BpmnXMLUtil.addXMLLocation(startEvent, xtr); startEvent.setInitiator(xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_EVENT_START_INITIATOR)); boolean interrupting = true; String interruptingAttribute = xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_EVENT_START_INTERRUPTING); if (ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(interruptingAttribute)) { interrupting = false; } startEvent.setInterrupting(interrupting); startEvent.setFormKey(formKey); parseChildElements(getXMLElementName(), startEvent, model, xtr); return startEvent; } @Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { StartEvent startEvent = (StartEvent) element; writeQualifiedAttribute(ATTRIBUTE_EVENT_START_INITIATOR, startEvent.getInitiator(), xtw); writeQualifiedAttribute(ATTRIBUTE_FORM_FORMKEY, startEvent.getFormKey(), xtw); if (startEvent.getEventDefinitions() != null && startEvent.getEventDefinitions().size() > 0) { writeQualifiedAttribute(ATTRIBUTE_EVENT_START_INTERRUPTING, String.valueOf(startEvent.isInterrupting()), xtw); } } @Override protected boolean writeExtensionChildElements(BaseElement element, boolean didWriteExtensionStartElement, XMLStreamWriter xtw) throws Exception { StartEvent startEvent = (StartEvent) element; didWriteExtensionStartElement = writeFormProperties(startEvent, didWriteExtensionStartElement, xtw); return didWriteExtensionStartElement; } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { StartEvent startEvent = (StartEvent) element; writeEventDefinitions(startEvent, startEvent.getEventDefinitions(), model, xtw); } }
{ "content_hash": "6cec4cce720dd17faad1622e30f845c7", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 147, "avg_line_length": 40.764044943820224, "alnum_prop": 0.7681918412348401, "repo_name": "stefan-ziel/Activiti", "id": "0c66a194dd5aa3dbcd16597f4d2276533c012b3c", "size": "3628", "binary": false, "copies": "3", "ref": "refs/heads/6.x-c", "path": "modules/activiti-bpmn-converter/src/main/java/org/activiti/bpmn/converter/StartEventXMLConverter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "292473" }, { "name": "HTML", "bytes": "774326" }, { "name": "Java", "bytes": "20888915" }, { "name": "JavaScript", "bytes": "8873337" }, { "name": "PLSQL", "bytes": "1426" }, { "name": "PLpgSQL", "bytes": "4868" }, { "name": "Shell", "bytes": "8194" } ], "symlink_target": "" }
package org.insightech.er.editor.view.dialog.edit; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.eclipse.draw2d.ColorConstants; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.TableEditor; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.insightech.er.ERDiagramActivator; import org.insightech.er.ImageKey; import org.insightech.er.ResourceString; import org.insightech.er.common.dialog.AbstractDialog; import org.insightech.er.common.exception.InputException; import org.insightech.er.common.widgets.CenteredContentCellPaint; import org.insightech.er.common.widgets.ListenerAppender; import org.insightech.er.db.sqltype.SqlType; import org.insightech.er.editor.model.ERDiagram; import org.insightech.er.editor.model.diagram_contents.DiagramContents; import org.insightech.er.editor.model.diagram_contents.element.node.NodeElement; import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable; import org.insightech.er.editor.model.diagram_contents.element.node.table.column.Column; import org.insightech.er.editor.model.diagram_contents.element.node.table.column.NormalColumn; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.CopyWord; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.Dictionary; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.TypeData; import org.insightech.er.editor.model.diagram_contents.not_element.dictionary.Word; import org.insightech.er.editor.model.edit.CopyManager; import org.insightech.er.editor.view.dialog.common.EditableTable; import org.insightech.er.util.Check; import org.insightech.er.util.Format; public class EditAllAttributesDialog extends AbstractDialog implements EditableTable { private static final int KEY_WIDTH = 45; private static final int NAME_WIDTH = 150; private static final int TYPE_WIDTH = 100; private static final int NOT_NULL_WIDTH = 80; private static final int UNIQUE_KEY_WIDTH = 70; private Table attributeTable; private TableEditor tableEditor; private ERDiagram diagram; private DiagramContents copyContents; private List<Column> columnList; private List<Word> wordList; private String errorMessage; // private Map<Column, TableEditor[]> columnNotNullCheckMap = new // HashMap<Column, TableEditor[]>(); public EditAllAttributesDialog(Shell parentShell, ERDiagram diagram) { super(parentShell); this.diagram = diagram; CopyManager copyManager = new CopyManager(null); this.copyContents = copyManager.copy(this.diagram.getDiagramContents()); this.columnList = new ArrayList<Column>(); } /** * {@inheritDoc} */ @Override protected String getErrorMessage() { return errorMessage; } // @Override // protected void addListener() { // super.addListener(); // // this.attributeTable.addListener(SWT.EraseItem, new Listener() { // public void handleEvent(Event event) { // // event.detail &= ~SWT.HOT; // if ((event.detail & SWT.SELECTED) == 0) { // Table table = (Table) event.widget; // TableItem item = (TableItem) event.item; // // if (item.getBackground().equals( // Resources.SELECTED_FOREIGNKEY_COLUMN)) { // int clientWidth = table.getClientArea().width; // // GC gc = event.gc; // // Color oldForeground = gc.getForeground(); // Color oldBackground = gc.getBackground(); // // gc.setBackground(Resources.SELECTED_FOREIGNKEY_COLUMN); // // gc.setForeground(colorForeground); // gc.fillRectangle(0, event.y, clientWidth, event.height); // // // gc.setForeground(oldForeground); // gc.setBackground(oldBackground); // // event.detail &= ~SWT.SELECTED; // } // } // } // }); // } @Override protected String getTitle() { return "dialog.title.edit.all.attributes"; } @Override protected void initialize(Composite composite) { this.createTable(composite); } /** * This method initializes composite2 * */ private void createTable(Composite composite) { GridData tableGridData = new GridData(); tableGridData.horizontalSpan = 3; tableGridData.heightHint = 400; tableGridData.horizontalAlignment = GridData.FILL; tableGridData.grabExcessHorizontalSpace = true; this.attributeTable = new Table(composite, SWT.SINGLE | SWT.BORDER | SWT.FULL_SELECTION); this.attributeTable.setLayoutData(tableGridData); this.attributeTable.setHeaderVisible(true); this.attributeTable.setLinesVisible(true); TableColumn columnLogicalName = new TableColumn(this.attributeTable, SWT.NONE); columnLogicalName.setWidth(NAME_WIDTH); columnLogicalName.setText(ResourceString .getResourceString("label.column.logical.name")); TableColumn columnPhysicalName = new TableColumn(this.attributeTable, SWT.NONE); columnPhysicalName.setWidth(NAME_WIDTH); columnPhysicalName.setText(ResourceString .getResourceString("label.column.physical.name")); TableColumn tableLogicalName = new TableColumn(this.attributeTable, SWT.NONE); tableLogicalName.setWidth(NAME_WIDTH); tableLogicalName.setText(ResourceString .getResourceString("label.table.logical.name")); TableColumn tablePhysicalName = new TableColumn(this.attributeTable, SWT.NONE); tablePhysicalName.setWidth(NAME_WIDTH); tablePhysicalName.setText(ResourceString .getResourceString("label.table.physical.name")); TableColumn tableWord = new TableColumn(this.attributeTable, SWT.NONE); tableWord.setWidth(NAME_WIDTH); tableWord.setText(ResourceString.getResourceString("label.word")); TableColumn columnType = new TableColumn(this.attributeTable, SWT.NONE); columnType.setWidth(TYPE_WIDTH); columnType.setText(ResourceString .getResourceString("label.column.type")); TableColumn columnLength = new TableColumn(this.attributeTable, SWT.RIGHT); columnLength.setWidth(TYPE_WIDTH); columnLength.setText(ResourceString .getResourceString("label.column.length")); TableColumn columnDecimal = new TableColumn(this.attributeTable, SWT.RIGHT); columnDecimal.setWidth(TYPE_WIDTH); columnDecimal.setText(ResourceString .getResourceString("label.column.decimal")); TableColumn columnKey = new TableColumn(this.attributeTable, SWT.CENTER); columnKey.setText("PK"); columnKey.setWidth(KEY_WIDTH); new CenteredContentCellPaint(this.attributeTable, 8); TableColumn columnForeignKey = new TableColumn(this.attributeTable, SWT.CENTER); columnForeignKey.setText("FK"); columnForeignKey.setWidth(KEY_WIDTH); new CenteredContentCellPaint(this.attributeTable, 9); TableColumn columnNotNull = new TableColumn(this.attributeTable, SWT.CENTER); columnNotNull.setWidth(NOT_NULL_WIDTH); columnNotNull.setText(ResourceString .getResourceString("label.not.null")); new CenteredContentCellPaint(this.attributeTable, 10); TableColumn columnUnique = new TableColumn(this.attributeTable, SWT.CENTER); columnUnique.setWidth(UNIQUE_KEY_WIDTH); columnUnique.setText(ResourceString .getResourceString("label.unique.key")); new CenteredContentCellPaint(this.attributeTable, 11); this.tableEditor = new TableEditor(this.attributeTable); this.tableEditor.grabHorizontal = true; ListenerAppender.addTableEditListener(this.attributeTable, this.tableEditor, this); } private Combo createTypeCombo(NormalColumn targetColumn) { GridData gridData = new GridData(); gridData.widthHint = 100; final Combo typeCombo = new Combo(this.attributeTable, SWT.READ_ONLY); initializeTypeCombo(typeCombo); typeCombo.setLayoutData(gridData); typeCombo.addSelectionListener(new SelectionAdapter() { /** * {@inheritDoc} */ @Override public void widgetSelected(SelectionEvent event) { validate(); } }); SqlType sqlType = targetColumn.getType(); String database = this.diagram.getDatabase(); if (sqlType != null && sqlType.getAlias(database) != null) { typeCombo.setText(sqlType.getAlias(database)); } return typeCombo; } private void initializeTypeCombo(Combo combo) { combo.setVisibleItemCount(20); combo.add(""); String database = this.diagram.getDatabase(); for (String alias : SqlType.getAliasList(database)) { combo.add(alias); } } protected Combo createWordCombo(NormalColumn targetColumn) { GridData gridData = new GridData(); gridData.widthHint = 100; final Combo wordCombo = new Combo(this.attributeTable, SWT.READ_ONLY); initializeWordCombo(wordCombo); wordCombo.setLayoutData(gridData); this.setWordValue(wordCombo, targetColumn); return wordCombo; } private void initializeWordCombo(Combo combo) { combo.setVisibleItemCount(20); combo.add(""); this.wordList = this.copyContents.getDictionary().getWordList(); Collections.sort(this.wordList); for (Word word : this.wordList) { combo.add(Format.null2blank(word.getLogicalName())); } } private void setWordValue(Combo combo, NormalColumn targetColumn) { Word word = targetColumn.getWord(); while (word instanceof CopyWord) { word = ((CopyWord) word).getOriginal(); } if (word != null) { int index = wordList.indexOf(word); combo.select(index + 1); } } @Override protected void perfomeOK() throws InputException { } @Override protected void setData() { for (NodeElement nodeElement : this.copyContents.getContents()) { if (nodeElement instanceof ERTable) { ERTable table = (ERTable) nodeElement; for (Column column : table.getColumns()) { TableItem tableItem = new TableItem(this.attributeTable, SWT.NONE); this.column2TableItem(table, column, tableItem); this.columnList.add(column); } } } } private void column2TableItem(ERTable table, Column column, TableItem tableItem) { // this.disposeCheckBox(column); if (table != null) { tableItem.setText(2, Format.null2blank(table.getLogicalName())); tableItem.setText(3, Format.null2blank(table.getPhysicalName())); } if (column instanceof NormalColumn) { NormalColumn normalColumn = (NormalColumn) column; // if (normalColumn.isForeignKey()) { // tableItem.setBackground(Resources.SELECTED_FOREIGNKEY_COLUMN); // // } else { // tableItem.setBackground(ColorConstants.white); // } Color keyColor = ColorConstants.black; Color color = ColorConstants.black; if (normalColumn.isPrimaryKey() && normalColumn.isForeignKey()) { keyColor = ColorConstants.blue; color = ColorConstants.gray; } else if (normalColumn.isPrimaryKey()) { keyColor = ColorConstants.red; } else if (normalColumn.isForeignKey()) { keyColor = ColorConstants.darkGreen; color = ColorConstants.gray; } tableItem.setForeground(color); int colCount = 0; tableItem.setForeground(colCount, keyColor); tableItem.setText(colCount, Format.null2blank(normalColumn.getLogicalName())); colCount++; tableItem.setForeground(colCount, keyColor); tableItem.setText(colCount, Format.null2blank(normalColumn.getPhysicalName())); colCount++; tableItem.setForeground(colCount, ColorConstants.gray); colCount++; tableItem.setForeground(colCount, ColorConstants.gray); colCount++; if (normalColumn.getWord() != null) { tableItem.setText(colCount, Format.null2blank(normalColumn .getWord().getLogicalName())); } colCount++; SqlType sqlType = normalColumn.getType(); if (sqlType != null) { String database = this.diagram.getDatabase(); if (sqlType.getAlias(database) != null) { tableItem.setText(colCount, sqlType.getAlias(database)); } else { tableItem.setText(colCount, ""); } } else { tableItem.setText(colCount, ""); } colCount++; if (normalColumn.getTypeData().getLength() != null) { tableItem.setText(colCount, normalColumn.getTypeData() .getLength().toString()); } else { tableItem.setText(colCount, ""); } colCount++; if (normalColumn.getTypeData().getDecimal() != null) { tableItem.setText(colCount, normalColumn.getTypeData() .getDecimal().toString()); } else { tableItem.setText(colCount, ""); } colCount++; if (normalColumn.isPrimaryKey()) { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.PRIMARY_KEY)); } else { tableItem.setImage(colCount, null); } colCount++; if (normalColumn.isForeignKey()) { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.FOREIGN_KEY)); // CLabel imageLabel = new CLabel(this.attributeTable, // SWT.NONE); // imageLabel.setImage(Activator.getImage(ImageKey.FOREIGN_KEY)); // imageLabel.pack(); // TableEditor editor = new TableEditor(this.attributeTable); // editor.minimumWidth = imageLabel.getSize().x; // editor.horizontalAlignment = SWT.CENTER; // editor.setEditor(imageLabel, tableItem, 9); } else { tableItem.setImage(colCount, null); } colCount++; if (normalColumn.isNotNull()) { if (normalColumn.isPrimaryKey()) { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.CHECK_GREY)); } else { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.CHECK)); } } else { tableItem.setImage(colCount, null); } colCount++; if (normalColumn.isUniqueKey()) { if (table != null && normalColumn.isRefered()) { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.CHECK_GREY)); } else { tableItem.setImage(colCount, ERDiagramActivator.getImage(ImageKey.CHECK)); } } else { tableItem.setImage(colCount, null); } // this.setTableEditor(table, normalColumn, tableItem); } else { // group column // tableItem.setBackground(ColorConstants.white); tableItem.setForeground(ColorConstants.gray); // tableItem.setImage(2, Activator // .getImage(ImageKey.COLUMN_GROUP_IMAGE)); tableItem.setText(0, column.getName()); tableItem.setImage(8, null); tableItem.setImage(9, null); } } // private void disposeCheckBox(Column column) { // TableEditor[] oldEditors = this.columnNotNullCheckMap.get(column); // // if (oldEditors != null) { // for (TableEditor oldEditor : oldEditors) { // if (oldEditor.getEditor() != null) { // oldEditor.getEditor().dispose(); // oldEditor.dispose(); // } // } // // this.columnNotNullCheckMap.remove(column); // } // } // private void setTableEditor(ERTable table, final NormalColumn // normalColumn, // TableItem tableItem) { // // TableEditor[] editors = new TableEditor[] { // CompositeFactory.createCheckBoxTableEditor(tableItem, // normalColumn.isNotNull(), 10), // CompositeFactory.createCheckBoxTableEditor(tableItem, // normalColumn.isUniqueKey(), 11) }; // // final Button notNullCheckButton = (Button) editors[0].getEditor(); // final Button uniqueCheckButton = (Button) editors[1].getEditor(); // // if (normalColumn.isPrimaryKey()) { // notNullCheckButton.setEnabled(false); // } // // if (table != null) { // if (normalColumn.isRefered()) { // uniqueCheckButton.setEnabled(false); // } // } // // this.columnNotNullCheckMap.put(normalColumn, editors); // // notNullCheckButton.addSelectionListener(new SelectionAdapter() { // // /** // * {@inheritDoc} // */ // @Override // public void widgetSelected(SelectionEvent e) { // normalColumn.setNotNull(notNullCheckButton.getSelection()); // super.widgetSelected(e); // } // }); // // uniqueCheckButton.addSelectionListener(new SelectionAdapter() { // // /** // * {@inheritDoc} // */ // @Override // public void widgetSelected(SelectionEvent e) { // normalColumn.setUniqueKey(uniqueCheckButton.getSelection()); // super.widgetSelected(e); // } // }); // } public Control getControl(Point xy) { Column column = this.getColumn(xy); if (column instanceof NormalColumn) { NormalColumn targetColumn = (NormalColumn) column; String database = this.diagram.getDatabase(); if (xy.x == 4) { if (targetColumn.isForeignKey()) { return null; } return this.createWordCombo(targetColumn); } if (xy.x == 0 || xy.x == 1) { return new Text(this.attributeTable, SWT.BORDER); } if (xy.x == 6) { if (targetColumn.isForeignKey()) { return null; } if (targetColumn.getType() != null && targetColumn.getType().isNeedLength(database)) { return new Text(this.attributeTable, SWT.BORDER | SWT.RIGHT); } } if (xy.x == 7) { if (targetColumn.isForeignKey()) { return null; } if (targetColumn.getType() != null && targetColumn.getType().isNeedDecimal(database)) { return new Text(this.attributeTable, SWT.BORDER | SWT.RIGHT); } } if (xy.x == 5) { if (targetColumn.isForeignKey()) { return null; } return this.createTypeCombo(targetColumn); } } return null; } private Column getColumn(Point xy) { return this.columnList.get(xy.y); } public void setData(Point xy, Control control) { this.errorMessage = null; Column column = this.getColumn(xy); if (column instanceof NormalColumn) { NormalColumn targetColumn = (NormalColumn) column; String database = this.diagram.getDatabase(); Word word = targetColumn.getWord(); if (xy.x == 4) { if (targetColumn.isForeignKey()) { return; } int index = ((Combo) control).getSelectionIndex(); Dictionary dictionary = this.copyContents.getDictionary(); dictionary.remove(targetColumn); if (index == 0) { word = new Word(word); word.setLogicalName(""); } else { Word selectedWord = this.wordList.get(index - 1); if (word != selectedWord) { word = selectedWord; } } targetColumn.setWord(word); dictionary.add(targetColumn); this.resetNormalColumn(targetColumn); } else { if (xy.x == 0) { String text = ((Text) control).getText(); if (targetColumn.isForeignKey()) { targetColumn.setForeignKeyLogicalName(text); } else { word.setLogicalName(text); } } else if (xy.x == 1) { String text = ((Text) control).getText(); if (!Check.isAlphabet(text)) { if (this.diagram.getDiagramContents().getSettings() .isValidatePhysicalName()) { this.errorMessage = "error.column.physical.name.not.alphabet"; return; } } if (targetColumn.isForeignKey()) { targetColumn.setForeignKeyPhysicalName(text); } else { word.setPhysicalName(text); } } else if (xy.x == 5) { if (targetColumn.isForeignKey()) { return; } SqlType selectedType = SqlType.valueOf(database, ((Combo) control).getText()); word.setType(selectedType, word.getTypeData(), database); } else if (xy.x == 6) { if (targetColumn.isForeignKey()) { return; } String text = ((Text) control).getText().trim(); try { if (!text.equals("")) { int len = Integer.parseInt(text); if (len < 0) { this.errorMessage = "error.column.length.zero"; return; } TypeData oldTypeData = word.getTypeData(); TypeData newTypeData = new TypeData( Integer.parseInt(((Text) control).getText()), oldTypeData.getDecimal(), oldTypeData .isArray(), oldTypeData .getArrayDimension(), oldTypeData .isUnsigned(), oldTypeData .isZerofill(), oldTypeData .isBinary(), oldTypeData.getArgs(), oldTypeData.isCharSemantics()); word.setType(word.getType(), newTypeData, database); } } catch (NumberFormatException e) { this.errorMessage = "error.column.length.degit"; return; } } else if (xy.x == 7) { if (targetColumn.isForeignKey()) { return; } String text = ((Text) control).getText().trim(); try { if (!text.equals("")) { int decimal = Integer.parseInt(text); if (decimal < 0) { this.errorMessage = "error.column.decimal.zero"; return; } TypeData oldTypeData = word.getTypeData(); TypeData newTypeData = new TypeData( oldTypeData.getLength(), decimal, oldTypeData.isArray(), oldTypeData.getArrayDimension(), oldTypeData.isUnsigned(), oldTypeData.isZerofill(), oldTypeData.isBinary(), oldTypeData.getArgs(), oldTypeData.isCharSemantics()); word.setType(word.getType(), newTypeData, database); } } catch (NumberFormatException e) { this.errorMessage = "error.column.decimal.degit"; return; } } this.resetRowUse(word, targetColumn); } } return; } private void resetRowUse(Word word, NormalColumn targetColumn) { if (targetColumn.isForeignKey()) { this.resetNormalColumn(targetColumn); } else { for (int i = 0; i < this.columnList.size(); i++) { Column column = this.columnList.get(i); if (column instanceof NormalColumn) { NormalColumn normalColumn = (NormalColumn) column; if (word.equals(normalColumn.getWord())) { this.resetNormalColumn(normalColumn); } } } } } private void resetNormalColumn(NormalColumn normalColumn) { for (int i = 0; i < this.columnList.size(); i++) { if (this.columnList.get(i) == normalColumn) { TableItem tableItem = this.attributeTable.getItem(i); this.column2TableItem(null, normalColumn, tableItem); break; } } List<NormalColumn> foreignKeyList = normalColumn.getForeignKeyList(); for (NormalColumn foreignKey : foreignKeyList) { this.resetNormalColumn(foreignKey); } } public DiagramContents getDiagramContents() { return this.copyContents; } public void onDoubleClicked(Point xy) { Column column = getColumn(xy); if (column instanceof NormalColumn) { NormalColumn normalColumn = (NormalColumn) column; if (normalColumn.isPrimaryKey()) { return; } if (normalColumn.isRefered()) { return; } if (xy.x == 10) { normalColumn.setNotNull(!normalColumn.isNotNull()); resetNormalColumn(normalColumn); } else if (xy.x == 11) { normalColumn.setUniqueKey(!normalColumn.isUniqueKey()); resetNormalColumn(normalColumn); } } } }
{ "content_hash": "a4d04aec280a7bfa98b61306809e72a5", "timestamp": "", "source": "github", "line_count": 826, "max_line_length": 94, "avg_line_length": 28.502421307506054, "alnum_prop": 0.6734061079726458, "repo_name": "kozake/ermaster-k", "id": "400383a52ce1966609fb3e999e822a5870f9c8b1", "size": "23543", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "org.insightech.er/src/org/insightech/er/editor/view/dialog/edit/EditAllAttributesDialog.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "18" }, { "name": "Batchfile", "bytes": "454" }, { "name": "CSS", "bytes": "5617" }, { "name": "HTML", "bytes": "36395" }, { "name": "Java", "bytes": "2554922" }, { "name": "JavaScript", "bytes": "13" } ], "symlink_target": "" }
/** * Created by diego on 23/01/17. */ 'use strict'; var mongoose = require('mongoose'); var alive = new mongoose.Schema({ name: {type: String, require: true}, description: {type: String}, req: { url: {type: String, require: true}, port: {type: Number, require: true}, path: {type: String}, method: {type: String}, headers: {type: Object} }, res: { status: {type: String}, description: {type: String}, config: { date: {type: String}, description: [{type: String}] } }, type: {type: String, require: true, enum: ["ERROR", "WARN", "INFO"]}, mail: { status: {type: Boolean}, period: {type: String}, count: {type: Number}, accounts: [{type: String}] }, cron: { second: {type: Number}, minute: {type: Number}, hour: {type: Number}, day: {type: Number}, month: {type: Number}, dayOfWeek: [{type: Number}] }, group: [{type: String}], status: {type: Boolean, default: false} }); module.exports = mongoose.model('alives', alive);
{ "content_hash": "195332b008328625af52df14d3e1e413", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 73, "avg_line_length": 25.08695652173913, "alnum_prop": 0.5181975736568457, "repo_name": "reyesdiego/notificador", "id": "6f5b48d3e155493b1d7160770496b9b11f0c1f5e", "size": "1154", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/alive.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "168051" }, { "name": "HTML", "bytes": "46374" }, { "name": "JavaScript", "bytes": "93914" }, { "name": "Shell", "bytes": "76" } ], "symlink_target": "" }
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> Authorizable Actions -------------------------------------------------------------------------------- ### Overview Oak 1.0 comes with a extension to the Jackrabbit user management API that allows to perform additional actions or validations upon common user management tasks such as - create authorizables - remove authorizables - change a user's password Similar functionality has been present in Jackrabbit 2.x as internal interface. Compared to the Jackrabbit interface the new `AuthorizableAction` has been slightly adjusted to match Oak requirements operate directly on the Oak API, which eases the handling of implementation specific tasks such as writing protected items. ### AuthorizableAction API The following public interfaces are provided by Oak in the package `org.apache.jackrabbit.oak.spi.security.user.action`: - [AuthorizableAction] - [AuthorizableActionProvider] The `AuthorizableAction` interface itself allows to perform validations or write additional application specific content while executing user management related write operations. Therefore these actions are executed as part of the transient user management modifications. This contrasts to `org.apache.jackrabbit.oak.spi.commit.CommitHook`s which in turn are only triggered once modifications are persisted. Consequently, implementations of the `AuthorizableAction` interface are expected to adhere to this rule and perform transient repository operation or validation. They must not force changes to be persisted by calling `org.apache.jackrabbit.oak.api.Root.commit()`. See section [Group Actions](groupaction.html) for a related extension to monitor group specific operations and [User Actions](useraction.html) for user specific operations. ### Default Implementations Oak 1.0 provides the following base implementations: - `AbstractAuthorizableAction`: abstract base implementation that doesn't perform any action. - `DefaultAuthorizableActionProvider`: default action provider service that allows to enable the built-in actions provided with oak. - `CompositeActionProvider`: Allows to aggregate multiple provider implementations. #### Changes wrt Jackrabbit 2.x - actions no longer operate on JCR API but rather on the Oak API direct. - provider interface simplifies pluggability #### Built-in AuthorizableAction Implementations The following implementations of the `AuthorizableAction` interface are provided: * `AccessControlAction`: set up permission for new authorizables * `PasswordValidationAction`: simplistic password verification upon user creation and password modification * `PasswordChangeAction`: verifies that the new password is different from the old one * `ClearMembershipAction`: clear group membership upon removal of an authorizable. Note, that this will only remove those membership references that are visible to the editing session. As in Jackrabbit 2.x the actions are executed with the editing session and the target operation will fail if any of the configured actions fails (e.g. due to insufficient permissions by the editing Oak ContentSession). ### Pluggability The default security setup as present with Oak 1.0 is able to provide custom `AuthorizableActionProvider` implementations and will automatically combine the different implementations using the `CompositeActionProvider`. In an OSGi setup the following steps are required in order to add an action provider implementation: - implement `AuthorizableActionProvider` interface exposing your custom action(s). - make the provider implementation an OSGi service and make it available to the Oak repository. - make sure the `AuthorizableActionProvider` is listed as required service with the `SecurityProvider` (see also [Introduction](../introduction.html#configuration])) ##### Examples ###### Example Action Provider @Component() @Service(AuthorizableActionProvider.class) public class MyAuthorizableActionProvider implements AuthorizableActionProvider { private static final String PUBLIC_PROFILE_NAME = "publicProfileName"; private static final String PRIVATE_PROFILE_NAME = "privateProfileName"; private static final String FRIENDS_PROFILE_NAME = "friendsProfileName"; @Property(name = PUBLIC_PROFILE_NAME, value = "publicProfile") private String publicName; @Property(name = PRIVATE_PROFILE_NAME, value = "privateProfile") private String privateName; @Property(name = FRIENDS_PROFILE_NAME, value = "friendsProfile") private String friendsName; private ConfigurationParameters config = ConfigurationParameters.EMPTY; public MyAuthorizableActionProvider() {} public MyAuthorizableActionProvider(ConfigurationParameters config) { this.config = config; } //-----------------------------------------< AuthorizableActionProvider >--- @Override public List<? extends AuthorizableAction> getAuthorizableActions(SecurityProvider securityProvider) { AuthorizableAction action = new ProfileAction(publicName, privateName, friendsName); action.init(securityProvider, config); return Collections.singletonList(action); } //----------------------------------------------------< SCR Integration >--- @Activate private void activate(Map<String, Object> properties) { config = ConfigurationParameters.of(properties); } } ###### Example Action This example action generates additional child nodes upon user/group creation that will later be used to store various target-specific profile information: class ProfileAction extends AbstractAuthorizableAction { private final String publicName; private final String privateName; private final String friendsName; ProfileAction(@Nullable String publicName, @Nullable String privateName, @Nullable String friendsName) { this.publicName = publicName; this.privateName = privateName; this.friendsName = friendsName; } @Override public void onCreate(Group group, Root root, NamePathMapper namePathMapper) throws RepositoryException { createProfileNodes(group.getPath(), root); } @Override public void onCreate(User user, String password, Root root, NamePathMapper namePathMapper) throws RepositoryException { createProfileNodes(user.getPath(), root); } private void createProfileNodes(@Nonnull String authorizablePath, @Nonnull Root root) throws AccessDeniedException { Tree tree = root.getTree(authorizablePath); if (tree.exists()) { NodeUtil authorizableNode = new NodeUtil(tree); if (publicName != null) { authorizableNode.addChild(publicName, NodeTypeConstants.NT_OAK_UNSTRUCTURED); } if (privateName != null) { authorizableNode.addChild(privateName, NodeTypeConstants.NT_OAK_UNSTRUCTURED); } if (friendsName != null) { authorizableNode.addChild(friendsName, NodeTypeConstants.NT_OAK_UNSTRUCTURED); } } } ###### Example Non-OSGI Setup Map<String, Object> userParams = new HashMap<String, Object>(); userParams.put(UserConstants.PARAM_AUTHORIZABLE_ACTION_PROVIDER, new MyAuthorizableActionProvider()); ConfigurationParameters config = ConfigurationParameters.of(ImmutableMap.of(UserConfiguration.NAME, ConfigurationParameters.of(userParams))); SecurityProvider securityProvider = SecurityProviderBuilder.newBuilder().with(config).build(); Repository repo = new Jcr(new Oak()).with(securityProvider).createRepository(); <!-- hidden references --> [AuthorizableAction]: /oak/docs/apidocs/org/apache/jackrabbit/oak/spi/security/user/action/AuthorizableAction.html [AuthorizableActionProvider]: /oak/docs/apidocs/org/apache/jackrabbit/oak/spi/security/user/action/AuthorizableActionProvider.html
{ "content_hash": "b09e4f552b29b95650bcf0730ae9ae7d", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 184, "avg_line_length": 45.824742268041234, "alnum_prop": 0.7349831271091114, "repo_name": "amit-jain/jackrabbit-oak", "id": "d49f72f4cacdba14929df06e563daf7ffd43eb56", "size": "8890", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "oak-doc/src/site/markdown/security/user/authorizableaction.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24043" }, { "name": "Groovy", "bytes": "146403" }, { "name": "HTML", "bytes": "1406" }, { "name": "Java", "bytes": "33038785" }, { "name": "JavaScript", "bytes": "43898" }, { "name": "Perl", "bytes": "7585" }, { "name": "Rich Text Format", "bytes": "64887" }, { "name": "Shell", "bytes": "18524" } ], "symlink_target": "" }
""" A port of Infobot's nickometer command from Perl. This plugin provides one command (called nickometer) which will tell you how 'lame' an IRC nick is. It's an elitist hacker thing, but quite fun. """ import supybot import supybot.world as world # Use this for the version of this plugin. You may wish to put a CVS keyword # in here if you're keeping the plugin in CVS or some similar system. __version__ = "" # XXX Replace this with an appropriate author or supybot.Author instance. __author__ = supybot.authors.baggins # This is a dictionary mapping supybot.Author instances to lists of # contributions. __contributors__ = {} import config import plugin reload(plugin) # In case we're being reloaded. # Add more reloads here if you add third-party modules and want them to be # reloaded when this plugin is reloaded. Don't forget to import them as well! if world.testing: import test Class = plugin.Class configure = config.configure # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
{ "content_hash": "18bae78fea3f886649831576bc254bad", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 78, "avg_line_length": 29.823529411764707, "alnum_prop": 0.7544378698224852, "repo_name": "kblin/supybot-gsoc", "id": "e27199e508cf396b97f91b7a4c40eedfd0580a4f", "size": "3182", "binary": false, "copies": "15", "ref": "refs/heads/stable", "path": "plugins/Nickometer/__init__.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "2238011" } ], "symlink_target": "" }
#import <Foundation/Foundation.h> @protocol HUEditableLabelDelegate <NSObject> @optional - (BOOL)textViewShouldBeginEditing:(id)textView; - (void)textViewDidBeginEditing:(id)textView; - (void)textFieldDidEndEditing:(id)textView; - (BOOL)textView:(id)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; - (void)onTouch:(id)textView; @end
{ "content_hash": "3c63a07adbb8705fb14bb89371f0b26b", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 102, "avg_line_length": 24.866666666666667, "alnum_prop": 0.7908847184986595, "repo_name": "JustinMuniz/HoverChat-iOS-App", "id": "d94182df9de7a351f8d7ac7992abb331d591e648", "size": "1506", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Spika/Views/HUEditableLabelView/HUEditableLabelDelegate.h", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "1038" }, { "name": "JavaScript", "bytes": "2670" }, { "name": "Objective-C", "bytes": "2190303" }, { "name": "Perl", "bytes": "9111" }, { "name": "Shell", "bytes": "4090" } ], "symlink_target": "" }
import angular from 'angular'; import _ from 'underscore'; import template from './dimLoadout.directive.template.html'; angular.module('dimApp').directive('dimLoadout', Loadout); function Loadout(dimLoadoutService, $translate) { return { controller: LoadoutCtrl, controllerAs: 'vm', bindToController: true, link: Link, scope: {}, template: template }; function Link(scope) { var vm = scope.vm; scope.$on('dim-stores-updated', function(evt, data) { vm.classTypeValues = [{ label: $translate.instant('Loadouts.Any'), value: -1 }]; /* Bug here was localization tried to change the label order, but users have saved their loadouts with data that was in the original order. These changes broke loadouts. Next time, you have to map values between new and old values to preserve backwards compatability. */ _.each(_.uniq(_.reject(data.stores, 'isVault'), false, function(store) { return store.classType; }), function(store) { let classType = 0; switch (parseInt(store.classType, 10)) { case 0: { classType = 1; break; } case 1: { classType = 2; break; } case 2: { classType = 0; break; } } vm.classTypeValues.push({ label: store.className, value: classType }); }); }); scope.$on('dim-create-new-loadout', function() { vm.show = true; dimLoadoutService.dialogOpen = true; vm.loadout = angular.copy(vm.defaults); }); scope.$on('dim-delete-loadout', function() { vm.show = false; dimLoadoutService.dialogOpen = false; vm.loadout = angular.copy(vm.defaults); }); scope.$watchCollection('vm.originalLoadout.items', function() { vm.loadout = angular.copy(vm.originalLoadout); }); scope.$on('dim-edit-loadout', function(event, args) { if (args.loadout) { vm.show = true; dimLoadoutService.dialogOpen = true; vm.originalLoadout = args.loadout; // Filter out any vendor items and equip all if requested args.loadout.warnitems = _.reduce(args.loadout.items, function(o, items) { var vendorItems = _.filter(items, function(item) { return !item.owner; }); o = o.concat(...vendorItems); return o; }, []); _.each(args.loadout.items, function(items, type) { args.loadout.items[type] = _.filter(items, function(item) { return item.owner; }); if (args.equipAll && args.loadout.items[type][0]) { args.loadout.items[type][0].equipped = true; } }); vm.loadout = angular.copy(args.loadout); } }); scope.$on('dim-store-item-clicked', function(event, args) { vm.add(args.item, args.clickEvent); }); scope.$on('dim-active-platform-updated', function() { vm.show = false; }); scope.$watchCollection('vm.loadout.items', function() { vm.recalculateStats(); }); } } function LoadoutCtrl(dimLoadoutService, dimCategory, toaster, dimPlatformService, dimSettingsService, $translate, dimStoreService, dimDefinitions) { var vm = this; vm.settings = dimSettingsService; vm.types = _.chain(dimCategory) .values() .flatten() .map(function(t) { return t.toLowerCase(); }) .value(); vm.show = false; dimLoadoutService.dialogOpen = false; vm.defaults = { classType: -1, items: {} }; vm.loadout = angular.copy(vm.defaults); vm.save = function save() { var platform = dimPlatformService.getActive(); vm.loadout.platform = platform.label; // Playstation or Xbox dimLoadoutService .saveLoadout(vm.loadout) .catch((e) => { toaster.pop('error', $translate.instant('Loadouts.SaveErrorTitle'), $translate.instant('Loadouts.SaveErrorDescription', { loadoutName: vm.loadout.name, error: e.message })); console.error(e); }); vm.cancel(); }; vm.saveAsNew = function saveAsNew() { delete vm.loadout.id; // Let it be a new ID vm.save(); }; vm.cancel = function cancel() { vm.loadout = angular.copy(vm.defaults); dimLoadoutService.dialogOpen = false; vm.show = false; }; vm.add = function add(item, $event) { if (item.canBeInLoadout()) { var clone = angular.copy(item); var discriminator = clone.type.toLowerCase(); var typeInventory = vm.loadout.items[discriminator] = (vm.loadout.items[discriminator] || []); clone.amount = Math.min(clone.amount, $event.shiftKey ? 5 : 1); var dupe = _.findWhere(typeInventory, { hash: clone.hash, id: clone.id }); var maxSlots = 10; if (item.type === 'Material') { maxSlots = 20; } else if (item.type === 'Consumable') { maxSlots = 19; } if (!dupe) { if (typeInventory.length < maxSlots) { clone.equipped = item.equipment && (typeInventory.length === 0); // Only allow one subclass per burn if (clone.type === 'Class') { var other = vm.loadout.items.class; if (other && other.length && other[0].dmg !== clone.dmg) { vm.loadout.items.class.splice(0, vm.loadout.items.class.length); } clone.equipped = true; } typeInventory.push(clone); } else { toaster.pop('warning', '', $translate.instant('Loadouts.MaxSlots', { slots: maxSlots })); } } else if (dupe && clone.maxStackSize > 1) { var increment = Math.min(dupe.amount + clone.amount, dupe.maxStackSize) - dupe.amount; dupe.amount += increment; // TODO: handle stack splits } } else { toaster.pop('warning', '', $translate.instant('Loadouts.OnlyItems')); } vm.recalculateStats(); }; vm.remove = function remove(item, $event) { var discriminator = item.type.toLowerCase(); var typeInventory = vm.loadout.items[discriminator] = (vm.loadout.items[discriminator] || []); var index = _.findIndex(typeInventory, function(i) { return i.hash === item.hash && i.id === item.id; }); if (index >= 0) { var decrement = $event.shiftKey ? 5 : 1; item.amount -= decrement; if (item.amount <= 0) { typeInventory.splice(index, 1); } } if (item.equipped && typeInventory.length > 0) { typeInventory[0].equipped = true; } vm.recalculateStats(); }; vm.equip = function equip(item) { if (item.equipment) { if ((item.type === 'Class') && (!item.equipped)) { item.equipped = true; } else if (item.equipped) { item.equipped = false; } else { if (item.isExotic) { var exotic = _.chain(vm.loadout.items) .values() .flatten() .findWhere({ sort: item.bucket.sort, isExotic: true, equipped: true }) .value(); if (!_.isUndefined(exotic)) { exotic.equipped = false; } } _.chain(vm.loadout.items) .values() .flatten() .where({ type: item.type, equipped: true }) .each(function(i) { i.equipped = false; }); item.equipped = true; } } vm.recalculateStats(vm.loadout.items); }; vm.recalculateStats = function() { if (!vm.loadout || !vm.loadout.items) { vm.stats = null; return; } const items = vm.loadout.items; const interestingStats = new Set(['STAT_INTELLECT', 'STAT_DISCIPLINE', 'STAT_STRENGTH']); let numInterestingStats = 0; const combinedStats = _.chain(items) .values() .flatten() .filter('equipped') .map('stats') .flatten() .filter() .filter((stat) => interestingStats.has(stat.id)) .reduce((stats, stat) => { numInterestingStats++; if (stats[stat.id]) { stats[stat.id].value += stat.value; } else { stats[stat.id] = { statHash: stat.statHash, value: stat.value }; } return stats; }, {}) .value(); // Seven types of things that contribute to these stats, times 3 stats, equals // a complete set of armor, ghost and artifact. vm.hasArmor = numInterestingStats > 0; vm.completeArmor = numInterestingStats === (7 * 3); if (_.isEmpty(combinedStats)) { vm.stats = null; return; } dimDefinitions.getDefinitions().then((defs) => { vm.stats = dimStoreService.getCharacterStatsData(defs.Stat, { stats: combinedStats }); }); }; }
{ "content_hash": "8fac135bd91a52fe42a52e447be4b1b8", "timestamp": "", "source": "github", "line_count": 309, "max_line_length": 148, "avg_line_length": 28.41747572815534, "alnum_prop": 0.5711194624758, "repo_name": "48klocs/DIM", "id": "0568b75aebce9e79d4274d599389d4f7ca08ce05", "size": "8781", "binary": false, "copies": "1", "ref": "refs/heads/WeaponRankingServiceAbstraction", "path": "src/scripts/loadout/dimLoadout.directive.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "37213" }, { "name": "CSS", "bytes": "66967" }, { "name": "HTML", "bytes": "73103" }, { "name": "JavaScript", "bytes": "449436" }, { "name": "Shell", "bytes": "140" } ], "symlink_target": "" }
package org.bpim.transformer.executionpath; import org.bpim.model.execpath.v1.Wait; import org.bpim.transformer.base.TransformationResult; import org.bpim.transformer.base.TransformerUnit; import org.bpim.transformer.util.ExecutionPathHelper; import org.jbpm.workflow.instance.NodeInstance; public class TimerNodeInstanceTransformerUnit extends TransformerUnit { @Override public void transform(NodeInstance nodeInstance, TransformationResult transformationResult) { Wait wait = ExecutionPathHelper.createWaitWithEventTransition(nodeInstance); transformationResult.setFlowNode(wait); } }
{ "content_hash": "b7ebe4c8575c908924d2e897d25e535a", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 94, "avg_line_length": 35.294117647058826, "alnum_prop": 0.8466666666666667, "repo_name": "nmoghadam/jbpm", "id": "c7f4048011f826cfca60ba1eefa0384bfff19dcb", "size": "600", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bpim-bpmn2/bpim-bpmn2-transformer/src/main/java/org/bpim/transformer/executionpath/TimerNodeInstanceTransformerUnit.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "14604" }, { "name": "HTML", "bytes": "251" }, { "name": "Java", "bytes": "10502749" }, { "name": "Protocol Buffer", "bytes": "6420" }, { "name": "Shell", "bytes": "98" } ], "symlink_target": "" }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/networksecurity/v1beta1/client_tls_policy.proto package com.google.cloud.networksecurity.v1beta1; public interface ListClientTlsPoliciesRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.networksecurity.v1beta1.ListClientTlsPoliciesRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The project and location from which the ClientTlsPolicies should * be listed, specified in the format `projects/&#42;&#47;locations/{location}`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The parent. */ java.lang.String getParent(); /** * * * <pre> * Required. The project and location from which the ClientTlsPolicies should * be listed, specified in the format `projects/&#42;&#47;locations/{location}`. * </pre> * * <code> * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for parent. */ com.google.protobuf.ByteString getParentBytes(); /** * * * <pre> * Maximum number of ClientTlsPolicies to return per call. * </pre> * * <code>int32 page_size = 2;</code> * * @return The pageSize. */ int getPageSize(); /** * * * <pre> * The value returned by the last `ListClientTlsPoliciesResponse` * Indicates that this is a continuation of a prior * `ListClientTlsPolicies` call, and that the system * should return the next page of data. * </pre> * * <code>string page_token = 3;</code> * * @return The pageToken. */ java.lang.String getPageToken(); /** * * * <pre> * The value returned by the last `ListClientTlsPoliciesResponse` * Indicates that this is a continuation of a prior * `ListClientTlsPolicies` call, and that the system * should return the next page of data. * </pre> * * <code>string page_token = 3;</code> * * @return The bytes for pageToken. */ com.google.protobuf.ByteString getPageTokenBytes(); }
{ "content_hash": "e91df31fe416342f774e930054053652", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 116, "avg_line_length": 26.162790697674417, "alnum_prop": 0.6462222222222223, "repo_name": "googleapis/google-cloud-java", "id": "3db917993c1a185f544fb0f845317275621b47df", "size": "2844", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "java-network-security/proto-google-cloud-network-security-v1beta1/src/main/java/com/google/cloud/networksecurity/v1beta1/ListClientTlsPoliciesRequestOrBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "2614" }, { "name": "HCL", "bytes": "28592" }, { "name": "Java", "bytes": "826434232" }, { "name": "Jinja", "bytes": "2292" }, { "name": "Python", "bytes": "200408" }, { "name": "Shell", "bytes": "97954" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8"> <title>Beautiful Flat Buttons</title> <meta name="description" content=""> <meta name="author" content=""> <!-- Mobile Specific Metas ================================================== --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- CSS ================================================== --> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="skeleton.css"> <link href='http://fonts.googleapis.com/css?family=Montez' rel='stylesheet' type='text/css'> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- Favicons ================================================== --> <link rel="shortcut icon" href="images/favicon.ico"> <link rel="apple-touch-icon" href="images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png"> </head> <body> <!-- Primary Page Layout ================================================== --> <div class="container"> <div class="sixteen columns"> <h1 class="remove-bottom" style="margin-top: 40px">Beautiful Flat Buttons</h1> <h2>by Petia Koleva</h2> <h3><a href="http://designify.me" title="Designify.me">http://designify.me</a></h3> <hr /> </div> <div class="one-third column"> <h3>Sun Flower Flat Button</h3> <p><input type="submit" value="Sun Flower" class="sun-flower-button"> </p> </div> <div class="one-third column"> <h3>Orange Flat Button</h3> <p><input type="submit" value="Orange" class="orange-flat-button"> </p> </div> <div class="one-third column"> <h3>Carrot Flat Button</h3> <p><input type="submit" value="Carrot" class="carrot-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Pumpkin Flat Button</h3> <p><input type="submit" value="Pumpkin" class="pumpkin-flat-button"> </p> </div> <div class="one-third column"> <h3>Alizarin Flat Button</h3> <p><input type="submit" value="Alizarin" class="alizarin-flat-button"> </p> </div> <div class="one-third column"> <h3>Pomegranate Flat Button</h3> <p><input type="submit" value="Pomegranate" class="pomegranate-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Turquoise Flat Button</h3> <p><input type="submit" value="Turquoise" class="turquoise-flat-button"> </p> </div> <div class="one-third column"> <h3>Green Sea Flat Button</h3> <p><input type="submit" value="Green Sea" class="green-sea-flat-button"> </p> </div> <div class="one-third column"> <h3>Emerald Flat Button</h3> <p><input type="submit" value="Emerald" class="emerald-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Nephritis Flat Button</h3> <p><input type="submit" value="Nephritis" class="nephritis-flat-button"> </p> </div> <div class="one-third column"> <h3>Peter River Flat Button</h3> <p><input type="submit" value="Peter River" class="peter-river-flat-button"> </p> </div> <div class="one-third column"> <h3>Belize Hole Flat Button</h3> <p><input type="submit" value="Belize Hole" class="belize-hole-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Amethyst Flat Button</h3> <p><input type="submit" value="Amethyst" class="amethyst-flat-button"> </p> </div> <div class="one-third column"> <h3>Wisteria Flat Button</h3> <p><input type="submit" value="Wisteria" class="wisteria-flat-button"> </p> </div> <div class="one-third column"> <h3>Wet Asphalt Flat Button</h3> <p><input type="submit" value="Wet Asphalt" class="wet-asphalt-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Midnight Blue Flat Button</h3> <p><input type="submit" value="Midnight Blue" class="midnight-blue-flat-button"> </p> </div> <div class="one-third column"> <h3>Clouds Flat Button</h3> <p><input type="submit" value="Clouds" class="clouds-flat-button"> </p> </div> <div class="one-third column"> <h3>Silver Flat Button</h3> <p><input type="submit" value="Silver" class="silver-flat-button"> </p> </div> <div class="sixteen columns"> </div> <div class="one-third column"> <h3>Concrete Blue Flat Button</h3> <p><input type="submit" value="Concrete Blue" class="concrete-flat-button"> </p> </div> <div class="one-third column"> <h3>Asbestos Flat Button</h3> <p><input type="submit" value="Asbestos" class="asbestos-flat-button"> </p> </div> <div class="one-third column"> <h3>Graphite Flat Button</h3> <p><input type="submit" value="Graphite" class="graphite-flat-button"> </p> </div> <div class="sixteen columns"> <hr /> Inspired by <a href="http://flatuicolors.com/">FLAT UI COLOURS</a>. </div> </div><!-- container --> <!-- End Document ================================================== --> </body> </html>
{ "content_hash": "635572d53b463baeda1589d2ba8c6ab5", "timestamp": "", "source": "github", "line_count": 193, "max_line_length": 96, "avg_line_length": 30.248704663212436, "alnum_prop": 0.5698869475847893, "repo_name": "Hayawi/TAB2PDF", "id": "dface6f9587a4163698dd9b7d5093a587a52db26", "size": "5838", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/fxml/flat-buttons/flat-buttons/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12589" }, { "name": "HTML", "bytes": "5162389" }, { "name": "Java", "bytes": "59874" } ], "symlink_target": "" }
<?php namespace Aja\AssetManager; use Asset as AssetFacade; use Assetic\Asset\AssetCollection; class AssetBuilder { protected $collections = array(); protected $name; protected $path; protected $factory; public function __construct($name, $path, $factory) { $this->name = $name; $this->path = $path; $this->factory = $factory; } public function addLess($files) { $this->addFiles('css', $files, 'less'); } public function addCss($files) { $this->addFiles('css', $files); } public function addJs($files) { $this->addFiles('js', $files); } public function loadConfigFiles($config) { foreach(array('css', 'js', 'less') as $sub) { if (!empty($config[$sub])) { if ($sub == 'less') { // Special case for LESS files. $this->addFiles('css', $config[$sub], 'less'); } else { $this->addFiles($sub, $config[$sub]); } } } } public function addFiles($type, $files, $filter = NULL) { if (is_null($filter)) { $filter = $type; } $filter = AssetFacade::GetFilter($filter); if (!isset($this->collections[$type])) { $col = new AssetCollection(); $col->setTargetPath($this->path.'/'.$this->name.'.'.$type); $this->collections[$type] = $col; } $collection = $this->factory->createAsset( $files, $filter ); $this->collections[$type]->add($collection); } public function getCollection($type) { if (!isset($this->collections[$type])) { return FALSE; } // We only want a specific subset. return $this->collections[$type]; } public function getCollections() { // Return everything. return $this->collections; } }
{ "content_hash": "28a6f55cca72076dad2b8ed828c95e20", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 71, "avg_line_length": 23.03191489361702, "alnum_prop": 0.46420323325635104, "repo_name": "dustingraham/asset-manager", "id": "018a5e60e3fc5c38219b083e57ebb1750ca8dfb3", "size": "2165", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Aja/AssetManager/AssetBuilder.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "18312" } ], "symlink_target": "" }
package hackerrank.quorahackathon2014; import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; //TODO doesn't work public class Schedule { static class Test implements Comparable<Test>{ int duration; double passProbability; public double getValue(){return duration*passProbability;} public Test(int duration, double passProbability){ this.duration = duration; this.passProbability = passProbability; } @Override public int compareTo(Test other) { if(other.duration > duration) return -1; if(other.duration < duration) return 1; return 0; } @Override public String toString() { return "Test(" + duration +", " + passProbability + ", " + getValue() + ")"; } } static ArrayList<Test> T; public static double addTest(int i){ if(i < T.size()-1){ return T.get(i).duration + (T.get(i).passProbability * addTest(i+1)); } else{ return T.get(i).duration; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int N = in.nextInt(); T = new ArrayList<>(N); for(int i = 0; i < N; ++i){ Test t = new Test(in.nextInt(), in.nextDouble()); if(t.passProbability >= 1.0) continue; if(t.passProbability <= 0.0) { System.out.println("0.0"); return; } T.add(t); } Collections.sort(T); System.out.println(Arrays.toString(T.toArray())); double result = addTest(0); System.out.println(result); } }
{ "content_hash": "548496d912f0aa20cffe7d8bdf8eef7a", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 88, "avg_line_length": 25.666666666666668, "alnum_prop": 0.5409373235460192, "repo_name": "wlk/contests", "id": "fbd884298848ebd14bd211f2f437b6bc98776931", "size": "1771", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/hackerrank/quorahackathon2014/Schedule.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "19761" }, { "name": "Shell", "bytes": "93" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>free-groups: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.10.0 / free-groups - 8.6.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> free-groups <small> 8.6.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-25 05:58:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-25 05:58:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/free-groups&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/FreeGroups&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.6&quot; &amp; &lt; &quot;8.7~&quot;} ] tags: [ &quot;keyword: free group&quot; &quot;category: Mathematics/Algebra&quot; ] authors: [ &quot;Daniel Schepler &lt;dschepler@gmail.com&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/free-groups/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/free-groups.git&quot; synopsis: &quot;Free Groups&quot; description: &quot;This small contribution is a formalization of van der Waerden&#39;s proof of the construction of a free group on a set of generators, as the reduced words where a letter is a generator or its formal inverse.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/free-groups/archive/v8.6.0.tar.gz&quot; checksum: &quot;md5=47edb0046c31e2813c03f36fe171614a&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-free-groups.8.6.0 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-free-groups -&gt; coq &lt; 8.7~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-free-groups.8.6.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
{ "content_hash": "32a2b14c6938c1fee0e1a21d8a990593", "timestamp": "", "source": "github", "line_count": 162, "max_line_length": 221, "avg_line_length": 41.93827160493827, "alnum_prop": 0.5395937591992935, "repo_name": "coq-bench/coq-bench.github.io", "id": "b646253f471adcde993afe8d11e5044fa0202acc", "size": "6796", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.07.1-2.0.1/released/8.10.0/free-groups/8.6.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
function [rotationEuler, rotationQuat, curr_data_index] = extractRotation(skel,node_index,data,curr_data_index,rotationEuler,rotationQuat,compute_quats) switch lower(skel.angleUnit) case 'deg' conversion_factor = pi/180; case 'rad' conversion_factor = 1; end node = skel.nodes(node_index); nDOF = size(node.DOF,1); % number of DOFs for this node if (isempty(node.DOF{1})) nDOF = 0; end if nDOF > 0 %%%%%% compute rotation order string and indices of this node's data streams rotationOrder = ''; indices = []; rx_missing = true; ry_missing = true; rz_missing = true; for k = 1:nDOF switch lower(node.DOF{k}) case 'rx' rotationOrder = [rotationOrder 'x']; indices = [indices k]; rx_missing = false; case 'ry' rotationOrder = [rotationOrder 'y']; indices = [indices k]; ry_missing = false; case 'rz' rotationOrder = [rotationOrder 'z']; indices = [indices k]; rz_missing = false; case 'tx' case 'ty' case 'tz' otherwise warning(['Invalid DOF specification: ' node.DOF{k} '!']); end end nRotDOF = length(indices); % number of rotational DOFs if nRotDOF > 0 %%%%%%%% adjust channel indices so as to point at correct location in our data array indices = indices + curr_data_index - 1; %%%%%%%%%% extract Euler information pertaining to this node rotationEuler{node.ID,1} = data(indices, :); %%%%%%%%%% compute quaternion representation if rx_missing rotationOrder = [rotationOrder 'x']; end if ry_missing rotationOrder = [rotationOrder 'y']; end if rz_missing rotationOrder = [rotationOrder 'z']; end if (compute_quats) switch nRotDOF case 3 rotationQuat{node.ID,1} = euler2quat(data(indices, :)*conversion_factor,rotationOrder); case 2 rotationQuat{node.ID,1} = euler2quat([data(indices, :)*conversion_factor;zeros(1,size(data,2))],rotationOrder); case 1 rotationQuat{node.ID,1} = euler2quat([data(indices, :)*conversion_factor;zeros(2,size(data,2))],rotationOrder); otherwise error(['Too many rotational DOFs for node ' node.jointName '!']); end end end curr_data_index = curr_data_index + nDOF; end for k=1:length(node.children) [rotationEuler, rotationQuat, curr_data_index] = extractRotation(skel,node.children(k),data,curr_data_index,rotationEuler,rotationQuat,compute_quats); end
{ "content_hash": "0e9572eb65571b802a410503293e605f", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 153, "avg_line_length": 36.135802469135804, "alnum_prop": 0.5459514861633071, "repo_name": "iqbalu/3D_Pose_Estimation_CVPR2016", "id": "1320cc0bfdc6c89a6cd354e7009232065d66eaad", "size": "2927", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/parser/BVHparser/extractRotation.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "3751" }, { "name": "C", "bytes": "188196" }, { "name": "C++", "bytes": "2016823" }, { "name": "CMake", "bytes": "12832" }, { "name": "CSS", "bytes": "3682" }, { "name": "HTML", "bytes": "340919" }, { "name": "Limbo", "bytes": "42" }, { "name": "M", "bytes": "4133" }, { "name": "Makefile", "bytes": "26071" }, { "name": "Matlab", "bytes": "5856729" }, { "name": "Mercury", "bytes": "520" }, { "name": "Objective-C", "bytes": "6778" }, { "name": "Protocol Buffer", "bytes": "662" }, { "name": "Shell", "bytes": "20881" }, { "name": "TeX", "bytes": "12883" }, { "name": "XSLT", "bytes": "15892" } ], "symlink_target": "" }
#ifndef __CONFIG_ZYNQ_COMMON_H #define __CONFIG_ZYNQ_COMMON_H /* CPU clock */ #ifndef CONFIG_CPU_FREQ_HZ # define CONFIG_CPU_FREQ_HZ 800000000 #endif /* Cache options */ #define CONFIG_SYS_L2CACHE_OFF #ifndef CONFIG_SYS_L2CACHE_OFF # define CONFIG_SYS_L2_PL310 # define CONFIG_SYS_PL310_BASE 0xf8f02000 #endif #define ZYNQ_SCUTIMER_BASEADDR 0xF8F00600 #define CONFIG_SYS_TIMERBASE ZYNQ_SCUTIMER_BASEADDR #define CONFIG_SYS_TIMER_COUNTS_DOWN #define CONFIG_SYS_TIMER_COUNTER (CONFIG_SYS_TIMERBASE + 0x4) /* Serial drivers */ /* The following table includes the supported baudrates */ #define CONFIG_SYS_BAUDRATE_TABLE \ {300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400} #define CONFIG_ARM_DCC /* Ethernet driver */ #if defined(CONFIG_ZYNQ_GEM) # define CONFIG_MII # define CONFIG_SYS_FAULT_ECHO_LINK_DOWN # define CONFIG_PHY_MARVELL # define CONFIG_PHY_REALTEK # define CONFIG_PHY_XILINX # define CONFIG_BOOTP_BOOTPATH # define CONFIG_BOOTP_GATEWAY # define CONFIG_BOOTP_HOSTNAME # define CONFIG_BOOTP_MAY_FAIL #endif /* SPI */ #ifdef CONFIG_ZYNQ_SPI #endif /* QSPI */ #ifdef CONFIG_ZYNQ_QSPI # define CONFIG_SF_DEFAULT_SPEED 30000000 # define CONFIG_SPI_FLASH_ISSI #endif /* NOR */ #ifdef CONFIG_MTD_NOR_FLASH # define CONFIG_SYS_FLASH_BASE 0xE2000000 # define CONFIG_SYS_FLASH_SIZE (16 * 1024 * 1024) # define CONFIG_SYS_MAX_FLASH_BANKS 1 # define CONFIG_SYS_MAX_FLASH_SECT 512 # define CONFIG_SYS_FLASH_ERASE_TOUT 1000 # define CONFIG_SYS_FLASH_WRITE_TOUT 5000 # define CONFIG_FLASH_SHOW_PROGRESS 10 # define CONFIG_SYS_FLASH_CFI # undef CONFIG_SYS_FLASH_EMPTY_INFO # define CONFIG_FLASH_CFI_DRIVER # undef CONFIG_SYS_FLASH_PROTECTION # define CONFIG_SYS_FLASH_USE_BUFFER_WRITE #endif #ifdef CONFIG_NAND_ZYNQ #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_SYS_NAND_ONFI_DETECTION #define CONFIG_MTD_DEVICE #endif /* MMC */ #if defined(CONFIG_MMC_SDHCI_ZYNQ) # define CONFIG_ZYNQ_SDHCI_MAX_FREQ 52000000 #endif #ifdef CONFIG_USB_EHCI_ZYNQ # define CONFIG_EHCI_IS_TDI # define CONFIG_SYS_DFU_DATA_BUF_SIZE 0x600000 # define DFU_DEFAULT_POLL_TIMEOUT 300 # define CONFIG_USB_CABLE_CHECK # define CONFIG_THOR_RESET_OFF # define CONFIG_USB_FUNCTION_THOR # define DFU_ALT_INFO_RAM \ "dfu_ram_info=" \ "set dfu_alt_info " \ "${kernel_image} ram 0x3000000 0x500000\\\\;" \ "${devicetree_image} ram 0x2A00000 0x20000\\\\;" \ "${ramdisk_image} ram 0x2000000 0x600000\0" \ "dfu_ram=run dfu_ram_info && dfu 0 ram 0\0" \ "thor_ram=run dfu_ram_info && thordown 0 ram 0\0" # if defined(CONFIG_MMC_SDHCI_ZYNQ) # define DFU_ALT_INFO_MMC \ "dfu_mmc_info=" \ "set dfu_alt_info " \ "${kernel_image} fat 0 1\\\\;" \ "${devicetree_image} fat 0 1\\\\;" \ "${ramdisk_image} fat 0 1\0" \ "dfu_mmc=run dfu_mmc_info && dfu 0 mmc 0\0" \ "thor_mmc=run dfu_mmc_info && thordown 0 mmc 0\0" # define DFU_ALT_INFO \ DFU_ALT_INFO_RAM \ DFU_ALT_INFO_MMC # else # define DFU_ALT_INFO \ DFU_ALT_INFO_RAM # endif #endif #if !defined(DFU_ALT_INFO) # define DFU_ALT_INFO #endif #if defined(CONFIG_MMC_SDHCI_ZYNQ) || defined(CONFIG_ZYNQ_USB) # define CONFIG_SUPPORT_VFAT #endif #if defined(CONFIG_ZYNQ_I2C0) || defined(CONFIG_ZYNQ_I2C1) #define CONFIG_SYS_I2C_ZYNQ #endif /* I2C */ #if defined(CONFIG_SYS_I2C_ZYNQ) # define CONFIG_SYS_I2C # define CONFIG_SYS_I2C_ZYNQ_SPEED 100000 # define CONFIG_SYS_I2C_ZYNQ_SLAVE 0 #endif /* EEPROM */ #ifdef CONFIG_ZYNQ_EEPROM # define CONFIG_SYS_I2C_EEPROM_ADDR_LEN 1 # define CONFIG_SYS_I2C_EEPROM_ADDR 0x54 # define CONFIG_SYS_EEPROM_PAGE_WRITE_BITS 4 # define CONFIG_SYS_EEPROM_PAGE_WRITE_DELAY_MS 5 # define CONFIG_SYS_EEPROM_SIZE 1024 /* Bytes */ #endif /* Total Size of Environment Sector */ #define CONFIG_ENV_SIZE (128 << 10) /* Allow to overwrite serial and ethaddr */ #define CONFIG_ENV_OVERWRITE /* Environment */ #ifndef CONFIG_ENV_IS_NOWHERE # define CONFIG_ENV_SECT_SIZE CONFIG_ENV_SIZE # define CONFIG_ENV_OFFSET 0xE0000 #endif /* enable preboot to be loaded before CONFIG_BOOTDELAY */ #define CONFIG_PREBOOT /* Boot configuration */ #define CONFIG_BOOTCOMMAND "run $modeboot || run distro_bootcmd" #define CONFIG_SYS_LOAD_ADDR 0 /* default? */ /* Distro boot enablement */ #ifdef CONFIG_SPL_BUILD #define BOOTENV #else #include <config_distro_defaults.h> #ifdef CONFIG_CMD_MMC #define BOOT_TARGET_DEVICES_MMC(func) func(MMC, mmc, 0) #else #define BOOT_TARGET_DEVICES_MMC(func) #endif #ifdef CONFIG_CMD_USB #define BOOT_TARGET_DEVICES_USB(func) func(USB, usb, 0) #else #define BOOT_TARGET_DEVICES_USB(func) #endif #if defined(CONFIG_CMD_PXE) #define BOOT_TARGET_DEVICES_PXE(func) func(PXE, pxe, na) #else #define BOOT_TARGET_DEVICES_PXE(func) #endif #if defined(CONFIG_CMD_DHCP) #define BOOT_TARGET_DEVICES_DHCP(func) func(DHCP, dhcp, na) #else #define BOOT_TARGET_DEVICES_DHCP(func) #endif #define BOOT_TARGET_DEVICES(func) \ BOOT_TARGET_DEVICES_MMC(func) \ BOOT_TARGET_DEVICES_USB(func) \ BOOT_TARGET_DEVICES_PXE(func) \ BOOT_TARGET_DEVICES_DHCP(func) #include <config_distro_bootcmd.h> #endif /* CONFIG_SPL_BUILD */ /* Default environment */ #ifndef CONFIG_EXTRA_ENV_SETTINGS #define CONFIG_EXTRA_ENV_SETTINGS \ "fit_image=fit.itb\0" \ "load_addr=0x2000000\0" \ "fit_size=0x800000\0" \ "flash_off=0x100000\0" \ "nor_flash_off=0xE2100000\0" \ "fdt_high=0x20000000\0" \ "initrd_high=0x20000000\0" \ "loadbootenv_addr=0x2000000\0" \ "fdt_addr_r=0x1f00000\0" \ "pxefile_addr_r=0x2000000\0" \ "kernel_addr_r=0x2000000\0" \ "scriptaddr=0x3000000\0" \ "ramdisk_addr_r=0x3100000\0" \ "bootenv=uEnv.txt\0" \ "bootenv_dev=mmc\0" \ "loadbootenv=load ${bootenv_dev} 0 ${loadbootenv_addr} ${bootenv}\0" \ "importbootenv=echo Importing environment from ${bootenv_dev} ...; " \ "env import -t ${loadbootenv_addr} $filesize\0" \ "bootenv_existence_test=test -e ${bootenv_dev} 0 /${bootenv}\0" \ "setbootenv=if env run bootenv_existence_test; then " \ "if env run loadbootenv; then " \ "env run importbootenv; " \ "fi; " \ "fi; \0" \ "sd_loadbootenv=set bootenv_dev mmc && " \ "run setbootenv \0" \ "usb_loadbootenv=set bootenv_dev usb && usb start && run setbootenv \0" \ "preboot=if test $modeboot = sdboot; then " \ "run sd_loadbootenv; " \ "echo Checking if uenvcmd is set ...; " \ "if test -n $uenvcmd; then " \ "echo Running uenvcmd ...; " \ "run uenvcmd; " \ "fi; " \ "fi; \0" \ "norboot=echo Copying FIT from NOR flash to RAM... && " \ "cp.b ${nor_flash_off} ${load_addr} ${fit_size} && " \ "bootm ${load_addr}\0" \ "sdboot=echo Copying FIT from SD to RAM... && " \ "load mmc 0 ${load_addr} ${fit_image} && " \ "bootm ${load_addr}\0" \ "jtagboot=echo TFTPing FIT to RAM... && " \ "tftpboot ${load_addr} ${fit_image} && " \ "bootm ${load_addr}\0" \ "usbboot=if usb start; then " \ "echo Copying FIT from USB to RAM... && " \ "load usb 0 ${load_addr} ${fit_image} && " \ "bootm ${load_addr}; fi\0" \ DFU_ALT_INFO \ BOOTENV #endif /* Miscellaneous configurable options */ #define CONFIG_CMDLINE_EDITING #define CONFIG_AUTO_COMPLETE #define CONFIG_SYS_LONGHELP #define CONFIG_CLOCKS #define CONFIG_SYS_MAXARGS 32 /* max number of command args */ #ifndef CONFIG_NR_DRAM_BANKS # define CONFIG_NR_DRAM_BANKS 1 #endif #define CONFIG_SYS_MEMTEST_START 0 #define CONFIG_SYS_MEMTEST_END 0x1000 #define CONFIG_SYS_MALLOC_LEN 0x1400000 #define CONFIG_SYS_INIT_RAM_ADDR 0xFFFF0000 #define CONFIG_SYS_INIT_RAM_SIZE 0x1000 #define CONFIG_SYS_INIT_SP_ADDR (CONFIG_SYS_INIT_RAM_ADDR + \ CONFIG_SYS_INIT_RAM_SIZE - \ GENERATED_GBL_DATA_SIZE) /* Enable the PL to be downloaded */ #define CONFIG_FPGA_ZYNQPL /* FIT support */ #define CONFIG_IMAGE_FORMAT_LEGACY /* enable also legacy image format */ /* Extend size of kernel image for uncompression */ #define CONFIG_SYS_BOOTM_LEN (60 * 1024 * 1024) /* Boot FreeBSD/vxWorks from an ELF image */ #define CONFIG_SYS_MMC_MAX_DEVICE 1 #define CONFIG_SYS_LDSCRIPT "arch/arm/mach-zynq/u-boot.lds" /* Commands */ /* SPL part */ #define CONFIG_SPL_FRAMEWORK /* MMC support */ #ifdef CONFIG_MMC_SDHCI_ZYNQ #define CONFIG_SYS_MMCSD_FS_BOOT_PARTITION 1 #define CONFIG_SPL_FS_LOAD_PAYLOAD_NAME "u-boot.img" #endif /* Disable dcache for SPL just for sure */ #ifdef CONFIG_SPL_BUILD #define CONFIG_SYS_DCACHE_OFF #endif /* Address in RAM where the parameters must be copied by SPL. */ #define CONFIG_SYS_SPL_ARGS_ADDR 0x10000000 #define CONFIG_SPL_FS_LOAD_ARGS_NAME "system.dtb" #define CONFIG_SPL_FS_LOAD_KERNEL_NAME "uImage" /* Not using MMC raw mode - just for compilation purpose */ #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTOR 0 #define CONFIG_SYS_MMCSD_RAW_MODE_ARGS_SECTORS 0 #define CONFIG_SYS_MMCSD_RAW_MODE_KERNEL_SECTOR 0 /* qspi mode is working fine */ #ifdef CONFIG_ZYNQ_QSPI #define CONFIG_SPL_SPI_LOAD #define CONFIG_SYS_SPI_U_BOOT_OFFS 0x100000 #define CONFIG_SYS_SPI_ARGS_OFFS 0x200000 #define CONFIG_SYS_SPI_ARGS_SIZE 0x80000 #define CONFIG_SYS_SPI_KERNEL_OFFS (CONFIG_SYS_SPI_ARGS_OFFS + \ CONFIG_SYS_SPI_ARGS_SIZE) #endif /* for booting directly linux */ /* SP location before relocation, must use scratch RAM */ #define CONFIG_SPL_TEXT_BASE 0x0 /* 3 * 64kB blocks of OCM - one is on the top because of bootrom */ #define CONFIG_SPL_MAX_SIZE 0x30000 /* On the top of OCM space */ #define CONFIG_SYS_SPL_MALLOC_START CONFIG_SPL_STACK_R_ADDR #define CONFIG_SYS_SPL_MALLOC_SIZE 0x2000000 /* * SPL stack position - and stack goes down * 0xfffffe00 is used for putting wfi loop. * Set it up as limit for now. */ #define CONFIG_SPL_STACK 0xfffffe00 /* BSS setup */ #define CONFIG_SPL_BSS_START_ADDR 0x100000 #define CONFIG_SPL_BSS_MAX_SIZE 0x100000 #define CONFIG_SYS_UBOOT_START CONFIG_SYS_TEXT_BASE #endif /* __CONFIG_ZYNQ_COMMON_H */
{ "content_hash": "a6336b80a859992eab5325720ee84558", "timestamp": "", "source": "github", "line_count": 357, "max_line_length": 74, "avg_line_length": 27.34173669467787, "alnum_prop": 0.707202130929208, "repo_name": "guileschool/beagleboard", "id": "b10cb3f572204131e2af35d3b322eb917504036d", "size": "9952", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "u-boot/include/configs/zynq-common.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "960094" }, { "name": "Awk", "bytes": "269" }, { "name": "Batchfile", "bytes": "3451" }, { "name": "C", "bytes": "62720528" }, { "name": "C++", "bytes": "5261365" }, { "name": "CSS", "bytes": "8362" }, { "name": "GDB", "bytes": "3642" }, { "name": "HTML", "bytes": "237884" }, { "name": "Lex", "bytes": "13917" }, { "name": "Makefile", "bytes": "429363" }, { "name": "Objective-C", "bytes": "370078" }, { "name": "Perl", "bytes": "358570" }, { "name": "Python", "bytes": "884691" }, { "name": "Roff", "bytes": "9384" }, { "name": "Shell", "bytes": "96042" }, { "name": "Tcl", "bytes": "967" }, { "name": "XSLT", "bytes": "445" }, { "name": "Yacc", "bytes": "26163" } ], "symlink_target": "" }
'use strict'; var chai = require('chai') , expect = chai.expect , sinon = require('sinon') , sinonChai = require('sinon-chai') , html = require('./fixtures/html.json') , Minimize = require('../lib/minimize') , minimize = new Minimize(); chai.use(sinonChai); chai.Assertion.includeStack = true; describe('Minimize', function () { describe('is module', function () { it('which has a constructor', function () { expect(Minimize).to.be.a('function'); }); it('which has minifier', function () { expect(minimize).to.have.property('minifier'); expect(minimize.minifier).to.be.a('function'); }); it('which has traverse', function () { expect(minimize).to.have.property('traverse'); expect(minimize.traverse).to.be.a('function'); }); it('which has parse', function () { expect(minimize).to.have.property('parse'); expect(minimize.parse).to.be.a('function'); }); it('which has walk', function () { expect(minimize).to.have.property('walk'); expect(minimize.walk).to.be.a('function'); }); it('which has htmlparser', function () { expect(minimize).to.have.property('htmlparser'); expect(minimize.htmlparser).to.be.an('object'); }); }); describe('function minifier', function () { it('throws an error if HTML parsing failed', function () { function err () { minimize.minifier('some error', []); } expect(err).throws('Minifier failed to parse DOM'); }); it('should start traversing the DOM as soon as HTML parser is ready', function () { var emit = sinon.spy(minimize, 'emit'); minimize.minifier(null, []); expect(emit).to.be.calledOnce; var result = emit.getCall(0).args; expect(result).to.be.an('array'); expect(result[0]).to.be.equal('parsed'); expect(result[1]).to.be.equal(null); expect(result[2]).to.be.equal(''); emit.restore(); }); it('should handle inline flow properly', function (done) { minimize.parse(html.interpunction, function (error, result) { expect(result).to.equal('<h3>Become a partner</h3><p>Interested in being part of the solution? <a href=/company/contact>Contact Nodejitsu to discuss</a>.</p>'); done(); }); }); it('should be configurable to retain comments', function (done) { var commentable = new Minimize({ comments: true }); commentable.parse(html.comment, function (error, result) { expect(result).to.equal('<!-- some HTML comment --><!--#include virtual=\"/header.html\" --><div class=\"slide nodejs\"><h3>100% Node.js</h3><p>We are Node.js experts and the first hosting platform to build our full stack in node. We understand your node application better than anyone.</p></div>'); done(); }); }); it('should be configurable to retain server side includes', function (done) { var commentable = new Minimize({ ssi: true }); commentable.parse(html.comment, function (error, result) { expect(result).to.equal('<!--#include virtual=\"/header.html\" --><div class=\"slide nodejs\"><h3>100% Node.js</h3><p>We are Node.js experts and the first hosting platform to build our full stack in node. We understand your node application better than anyone.</p></div>'); done(); }); }); it('should be configurable to retain conditional internet explorer comments', function (done) { var commentable = new Minimize({ conditionals: true }); commentable.parse(html.ie, function (error, result) { expect(result).to.equal('<!--[if IE 6]>Special instructions for IE 6 here<![endif]--><div class=\"slide nodejs\"><h3>100% Node.js</h3></div>'); done(); }); }); it('should be configurable to retain empty attributes', function (done) { var empty = new Minimize({ empty: true }); empty.parse(html.empty, function (error, result) { expect(result).to.equal('<h1 class="slide nodejs">a</h1><h2 name="">b</h2><h3 id=lol>c</h3><h4 disabled>d</h4><h5 autofocus>e</h5><h6 itemscope>f</h6>'); done(); }); }); it('should be configurable to retain spare attributes', function (done) { var spare = new Minimize({ spare: true }); spare.parse(html.empty, function (error, result) { expect(result).to.equal('<h1 class="slide nodejs">a</h1><h2>b</h2><h3 id=lol>c</h3><h4 disabled=disabled>d</h4><h5 autofocus=true>e</h5><h6 itemscope="">f</h6>'); done(); }); }); it('should leave structural elements (like scripts and code) intact', function (done) { minimize.parse(html.code, function (error, result) { expect(result).to.equal("<code class=copy><span>var http = require('http');\nhttp.createServer(function (req, res) {\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.end('hello, i know nodejitsu');\n})listen(8080);</span><a href=#><s class=ss-layers role=presentation></s> copy</a></code>"); done(); }); }); it('should leave style element content intact', function (done) { minimize.parse(html.styles, function (error, result) { expect(result).to.equal("<style>.test { color: #FFF }</style><style>.test { color: black }</style>"); done(); }); }); it('should minify script content that is not real text/javascript as much as possible', function (done) { minimize.parse(html.noscript, function (error, result) { expect(result).to.equal('<script type=imno/script id=plates-forgot><h3> Forgot your password? <a href="#" class="close ss-delete"></a> </h3> <p>Tell us your username and we will reset it for you.</p> <p class="error alert"></p> <p class="success alert"></p></script>'); done(); }); }); it('should replace newlines between text with spaces', function (done) { minimize.parse(html.newlines, function (error, result) { expect(result).to.equal("<li>We&#39;re <a href=http://nodejitsu.com>Nodejitsu</a>, and we can give you scalable, fault-tolerant cloud hosting for your Node.js apps - and we&#39;re the best you&#39;ll find.</li>"); done(); }); }); it('should prepend spaces inside structural elements if required', function (done) { minimize.parse(html.spacing, function (error, result) { expect(result).to.equal("<strong>npm</strong>. You don't have to worry about installing npm since it comes bundled with Node.js.<pre class=copy>$ <span>npm install jitsu -g</span><a href=#><s class=ss-layers role=presentation></s> copy</a></pre>"); done(); }); }); it('should not prepend spaces between inline elements if not required', function (done) { minimize.parse(html.scripts, function (error, result) { expect(result).to.equal("<script type=text/javascript src=//use.typekit.net/gmp8svh.js></script><script type=text/javascript></script>"); done(); }); }); it('should parse the full stack', function (done) { minimize.parse(html.full, function (error, result) { expect(result).to.equal("<!doctype html><html class=no-js><head></head><body class=container><section class=navigation id=navigation><nav class=row><h1><a href=\"/\" class=logo title=\"Back to the homepage\">Nodejitsu</a></h1><a href=#navigation class=\"mobile btn ss-rows\"></a> <a href=/paas>Cloud</a> <a href=/enterprise/private-cloud>Enterprise</a></nav></section><input type=text name=temp></body></html>"); done(); }); }); it('should prepend space if inline element is preluded by text', function (done) { minimize.parse('some text -\n <strong class="lol">keyword</strong>\n - more text', function (error, result) { expect(result).to.equal("some text - <strong class=lol>keyword</strong> - more text"); done(); }); }); it('should remove empty attributes which have no function', function (done) { minimize.parse('<strong class="">keyword</strong><p id="">text</p>', function (error, result) { expect(result).to.equal("<strong>keyword</strong><p>text</p>"); done(); }); }); it('should retain empty attributes of type ', function (done) { minimize.parse('<strong class="">keyword</strong><p id="">text</p>', function (error, result) { expect(result).to.equal("<strong>keyword</strong><p>text</p>"); done(); }); }); it('should remove CDATA from scripts', function (done) { minimize.parse(html.cdata, function (error, result) { expect(result).to.equal("<script type=text/javascript>\n...code...\n</script>"); done(); }); }); it('should be configurable to retain CDATA', function (done) { var cdata = new Minimize({ cdata: true }); cdata.parse(html.cdata, function (error, result) { expect(result).to.equal("<script type=text/javascript>//<![CDATA[\n...code...\n//]]></script>"); done(); }); }); it('should always quote attributes that end with / regardless of options', function (done) { var quote = new Minimize({ quotes: false }); quote.parse('<a href="#/">test</a>', function (error, result) { expect(result).to.equal('<a href="#/">test</a>'); done(); }); }); it('should clobber space around <br> elements', function (done) { var quote = new Minimize; quote.parse(html.br, function (error, result) { expect(result).to.equal("<p class=slide><span><em>Does your organization have security or licensing restrictions?</em></span><br><br><span>Your private npm registry makes managing them simple by giving you the power to work with a blacklist and a whitelist of public npm packages.</span></p>"); done(); }); }); }); describe('function traverse', function () { it('should traverse the DOM object and return string', function () { var result = minimize.traverse([html.element], ''); expect(result).to.be.a('string'); expect(result).to.be.equal( '<html class=no-js><head></head><body class=container></body></html>' ); }); }); describe('function walk', function () { it('should walk once if there are no children in the element', function () { var result = minimize.walk('', html.inline); expect(result).to.be.equal('<strong></strong>'); }); it('should traverse children and insert data', function () { var result = minimize.walk('', html.element); expect(result).to.be.equal( '<html class=no-js><head></head><body class=container></body></html>' ); }); }); describe('function walk', function () { it('should throw an error if no callback is provided', function () { function err () { minimize.parse(html.content, null); } expect(err).throws('No callback provided'); }); it('applies callback after DOM is parsed', function () { function fn () { } var once = sinon.spy(minimize, 'once'); minimize.parse(html.content, fn); expect(once).to.be.calledOnce; var result = once.getCall(0).args; expect(result).to.be.an('array'); expect(result[0]).to.be.equal('parsed'); expect(result[1]).to.be.equal(fn); once.restore(); }); it('calls htmlparser to process the DOM', function () { var parser = sinon.mock(minimize.htmlparser); parser.expects('parseComplete').once().withArgs(html.content); minimize.parse(html.content, function () {}); parser.restore(); }); }); });
{ "content_hash": "881ff50450d4d0567727509f01d32ebe", "timestamp": "", "source": "github", "line_count": 278, "max_line_length": 420, "avg_line_length": 41.75539568345324, "alnum_prop": 0.6176774638180565, "repo_name": "Keats/invoicer", "id": "0a087568e4f4d33df42ef39b3b9ec65604a2808d", "size": "11608", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/gulp-minify-html/node_modules/minimize/test/minimize-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "36853" }, { "name": "CoffeeScript", "bytes": "6528" }, { "name": "JavaScript", "bytes": "436" }, { "name": "TypeScript", "bytes": "231161" } ], "symlink_target": "" }
package org.pentaho.big.data.kettle.plugins.hive; import org.pentaho.database.DatabaseDialectException; import org.pentaho.database.IValueMeta; import org.pentaho.database.dialect.AbstractDatabaseDialect; import org.pentaho.database.model.DatabaseAccessType; import org.pentaho.database.model.DatabaseType; import org.pentaho.database.model.IDatabaseConnection; import org.pentaho.database.model.IDatabaseType; public class Hive2DatabaseDialect extends AbstractDatabaseDialect { public Hive2DatabaseDialect() { super(); } /** * UID for serialization */ private static final long serialVersionUID = -8456961348836455937L; protected static final int DEFAULT_PORT = 10000; private static final IDatabaseType DBTYPE = new DatabaseType( "Hadoop Hive 2", "HIVE2", DatabaseAccessType.getList( DatabaseAccessType.NATIVE, DatabaseAccessType.JNDI ), DEFAULT_PORT, "http://www.cloudera.com/content/support/en/documentation/cloudera-impala/cloudera-impala-documentation-v1" + "-latest.html" ); public IDatabaseType getDatabaseType() { return DBTYPE; } @Override public String getNativeDriver() { return "org.apache.hive.jdbc.HiveDriver"; } @Override public String getURL( IDatabaseConnection connection ) throws DatabaseDialectException { StringBuffer urlBuffer = new StringBuffer( getNativeJdbcPre() ); /* * String username = connection.getUsername(); if(username != null && !"".equals(username)) { * urlBuffer.append(username); String password = connection.getPassword(); if(password != null && * !"".equals(password)) { urlBuffer.append(":"); urlBuffer.append(password); } urlBuffer.append("@"); } */ urlBuffer.append( connection.getHostname() ); urlBuffer.append( ":" ); urlBuffer.append( connection.getDatabasePort() ); urlBuffer.append( "/" ); urlBuffer.append( connection.getDatabaseName() ); return urlBuffer.toString(); } @Override public String getNativeJdbcPre() { return "jdbc:hive2://"; } /** * Generates the SQL statement to add a column to the specified table * * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to add a column to the specified table */ @Override public String getAddColumnStatement( String tablename, IValueMeta v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " ADD " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); } /** * Generates the SQL statement to modify a column in the specified table * * @param tablename The table to add * @param v The column defined as a value * @param tk the name of the technical key field * @param use_autoinc whether or not this field uses auto increment * @param pk the name of the primary key field * @param semicolon whether or not to add a semi-colon behind the statement. * @return the SQL statement to modify a column in the specified table */ @Override public String getModifyColumnStatement( String tablename, IValueMeta v, String tk, boolean use_autoinc, String pk, boolean semicolon ) { return "ALTER TABLE " + tablename + " MODIFY " + getFieldDefinition( v, tk, pk, use_autoinc, true, false ); } @Override public String getFieldDefinition( IValueMeta v, String tk, String pk, boolean use_autoinc, boolean add_fieldname, boolean add_cr ) { String retval = ""; String fieldname = v.getName(); int length = v.getLength(); int precision = v.getPrecision(); if ( add_fieldname ) { retval += fieldname + " "; } int type = v.getType(); switch ( type ) { case IValueMeta.TYPE_DATE: retval += "DATETIME"; break; case IValueMeta.TYPE_BOOLEAN: if ( supportsBooleanDataType() ) { retval += "BOOLEAN"; } else { retval += "CHAR(1)"; } break; case IValueMeta.TYPE_NUMBER: case IValueMeta.TYPE_INTEGER: case IValueMeta.TYPE_BIGNUMBER: if ( fieldname.equalsIgnoreCase( tk ) || // Technical key fieldname.equalsIgnoreCase( pk ) // Primary key ) { if ( use_autoinc ) { retval += "BIGINT AUTO_INCREMENT NOT NULL PRIMARY KEY"; } else { retval += "BIGINT NOT NULL PRIMARY KEY"; } } else { // Integer values... if ( precision == 0 ) { if ( length > 9 ) { if ( length < 19 ) { // can hold signed values between -9223372036854775808 and 9223372036854775807 // 18 significant digits retval += "BIGINT"; } else { retval += "DECIMAL(" + length + ")"; } } else { retval += "INT"; } } else { // Floating point values... if ( length > 15 ) { retval += "DECIMAL(" + length; if ( precision > 0 ) { retval += ", " + precision; } retval += ")"; } else { // A double-precision floating-point number is accurate to approximately 15 decimal places. // http://mysql.mirrors-r-us.net/doc/refman/5.1/en/numeric-type-overview.html retval += "DOUBLE"; } } } break; case IValueMeta.TYPE_STRING: if ( length > 0 ) { if ( length == 1 ) { retval += "CHAR(1)"; } else if ( length < 256 ) { retval += "VARCHAR(" + length + ")"; } else if ( length < 65536 ) { retval += "TEXT"; } else if ( length < 16777215 ) { retval += "MEDIUMTEXT"; } else { retval += "LONGTEXT"; } } else { retval += "TINYTEXT"; } break; case IValueMeta.TYPE_BINARY: retval += "LONGBLOB"; break; default: retval += " UNKNOWN"; break; } if ( add_cr ) { retval += CR; } return retval; } @Override public String[] getUsedLibraries() { return new String[] { "pentaho-hadoop-hive-jdbc-shim-1.4-SNAPSHOT.jar" }; } @Override public int getDefaultDatabasePort() { return DEFAULT_PORT; } /* * (non-Javadoc) * * @see org.pentaho.database.dialect.AbstractDatabaseDialect#supportsSchemas() */ @Override public boolean supportsSchemas() { return false; } @Override public boolean initialize( String classname ) { return true; } }
{ "content_hash": "dc798806e2e3487e6ddbf171144d3c6e", "timestamp": "", "source": "github", "line_count": 217, "max_line_length": 116, "avg_line_length": 32.60829493087557, "alnum_prop": 0.5941209723007349, "repo_name": "SergeyTravin/big-data-plugin", "id": "1cfe8bf97274e7b167d1c357abe382e30a61e692", "size": "7978", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "kettle-plugins/hive/src/main/java/org/pentaho/big/data/kettle/plugins/hive/Hive2DatabaseDialect.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "23" }, { "name": "Java", "bytes": "4987445" }, { "name": "PigLatin", "bytes": "11262" } ], "symlink_target": "" }
using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V12.Enums { /// <summary>Holder for reflection information generated from google/ads/googleads/v12/enums/campaign_draft_status.proto</summary> public static partial class CampaignDraftStatusReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v12/enums/campaign_draft_status.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CampaignDraftStatusReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjpnb29nbGUvYWRzL2dvb2dsZWFkcy92MTIvZW51bXMvY2FtcGFpZ25fZHJh", "ZnRfc3RhdHVzLnByb3RvEh5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTIuZW51", "bXMimgEKF0NhbXBhaWduRHJhZnRTdGF0dXNFbnVtIn8KE0NhbXBhaWduRHJh", "ZnRTdGF0dXMSDwoLVU5TUEVDSUZJRUQQABILCgdVTktOT1dOEAESDAoIUFJP", "UE9TRUQQAhILCgdSRU1PVkVEEAMSDQoJUFJPTU9USU5HEAUSDAoIUFJPTU9U", "RUQQBBISCg5QUk9NT1RFX0ZBSUxFRBAGQvIBCiJjb20uZ29vZ2xlLmFkcy5n", "b29nbGVhZHMudjEyLmVudW1zQhhDYW1wYWlnbkRyYWZ0U3RhdHVzUHJvdG9Q", "AVpDZ29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hZHMv", "Z29vZ2xlYWRzL3YxMi9lbnVtcztlbnVtc6ICA0dBQaoCHkdvb2dsZS5BZHMu", "R29vZ2xlQWRzLlYxMi5FbnVtc8oCHkdvb2dsZVxBZHNcR29vZ2xlQWRzXFYx", "MlxFbnVtc+oCIkdvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYxMjo6RW51bXNi", "BnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V12.Enums.CampaignDraftStatusEnum), global::Google.Ads.GoogleAds.V12.Enums.CampaignDraftStatusEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V12.Enums.CampaignDraftStatusEnum.Types.CampaignDraftStatus) }, null, null) })); } #endregion } #region Messages /// <summary> /// Container for enum describing possible statuses of a campaign draft. /// </summary> public sealed partial class CampaignDraftStatusEnum : pb::IMessage<CampaignDraftStatusEnum> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<CampaignDraftStatusEnum> _parser = new pb::MessageParser<CampaignDraftStatusEnum>(() => new CampaignDraftStatusEnum()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<CampaignDraftStatusEnum> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V12.Enums.CampaignDraftStatusReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignDraftStatusEnum() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignDraftStatusEnum(CampaignDraftStatusEnum other) : this() { _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public CampaignDraftStatusEnum Clone() { return new CampaignDraftStatusEnum(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as CampaignDraftStatusEnum); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(CampaignDraftStatusEnum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(CampaignDraftStatusEnum other) { if (other == null) { return; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; } } } #endif #region Nested types /// <summary>Container for nested types declared in the CampaignDraftStatusEnum message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static partial class Types { /// <summary> /// Possible statuses of a campaign draft. /// </summary> public enum CampaignDraftStatus { /// <summary> /// The status has not been specified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Used for return value only. Represents value unknown in this version. /// </summary> [pbr::OriginalName("UNKNOWN")] Unknown = 1, /// <summary> /// Initial state of the draft, the advertiser can start adding changes with /// no effect on serving. /// </summary> [pbr::OriginalName("PROPOSED")] Proposed = 2, /// <summary> /// The campaign draft is removed. /// </summary> [pbr::OriginalName("REMOVED")] Removed = 3, /// <summary> /// Advertiser requested to promote draft's changes back into the original /// campaign. Advertiser can poll the long running operation returned by /// the promote action to see the status of the promotion. /// </summary> [pbr::OriginalName("PROMOTING")] Promoting = 5, /// <summary> /// The process to merge changes in the draft back to the original campaign /// has completed successfully. /// </summary> [pbr::OriginalName("PROMOTED")] Promoted = 4, /// <summary> /// The promotion failed after it was partially applied. Promote cannot be /// attempted again safely, so the issue must be corrected in the original /// campaign. /// </summary> [pbr::OriginalName("PROMOTE_FAILED")] PromoteFailed = 6, } } #endregion } #endregion } #endregion Designer generated code
{ "content_hash": "f760c223ea6ce80b971f1b4b8475a920", "timestamp": "", "source": "github", "line_count": 249, "max_line_length": 315, "avg_line_length": 40.01204819277108, "alnum_prop": 0.6890494830874234, "repo_name": "googleads/google-ads-dotnet", "id": "4a640fa4daca17e1511d15667b0c65ec91939475", "size": "10222", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "Google.Ads.GoogleAds/src/V12/CampaignDraftStatus.g.cs", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ASP.NET", "bytes": "1468" }, { "name": "C#", "bytes": "97173437" }, { "name": "CSS", "bytes": "705" }, { "name": "HTML", "bytes": "5996" }, { "name": "JavaScript", "bytes": "1543" }, { "name": "Shell", "bytes": "20116" } ], "symlink_target": "" }
import * as React from "react"; import { CarbonIconProps } from "../../"; declare const Image32: React.ForwardRefExoticComponent< CarbonIconProps & React.RefAttributes<SVGSVGElement> >; export default Image32;
{ "content_hash": "b6d05dbe9135352b8a2ccc908a9dd6c7", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 55, "avg_line_length": 35.333333333333336, "alnum_prop": 0.7641509433962265, "repo_name": "mcliment/DefinitelyTyped", "id": "5994c276bb9e5d7c14d7d8ad6f84ffbe87bf674f", "size": "212", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "types/carbon__icons-react/lib/image/32.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "15" }, { "name": "Protocol Buffer", "bytes": "678" }, { "name": "TypeScript", "bytes": "17214021" } ], "symlink_target": "" }
namespace blink { class ExecutionContext; class InspectedFrames; class InspectorAgent; class InstrumentingAgents; class LocalFrame; class V8InspectorSession; class CORE_EXPORT InspectorSession : public GarbageCollectedFinalized<InspectorSession> , WTF_NON_EXPORTED_BASE(public protocol::FrontendChannel) , public V8InspectorSessionClient { WTF_MAKE_NONCOPYABLE(InspectorSession); public: class Client { public: virtual void sendProtocolMessage(int sessionId, int callId, const String& response, const String& state) = 0; virtual void resumeStartup() { } virtual void profilingStarted() { } virtual void profilingStopped() { } virtual ~Client() {} }; InspectorSession(Client*, InspectedFrames*, InstrumentingAgents*, int sessionId, bool autoFlush); int sessionId() { return m_sessionId; } void append(InspectorAgent*); void attach(V8InspectorSession*, const String* savedState); void detach(); void didCommitLoadForLocalFrame(LocalFrame*); void dispatchProtocolMessage(const String& message); void flushPendingProtocolNotifications(); // Instrumentation methods marked by [V8] void scriptExecutionBlockedByCSP(const String& directiveText); void asyncTaskScheduled(const String& taskName, void* task); void asyncTaskScheduled(const String& taskName, void* task, bool recurring); void asyncTaskCanceled(void* task); void allAsyncTasksCanceled(); void asyncTaskStarted(void* task); void asyncTaskFinished(void* task); void didStartProvisionalLoad(LocalFrame*); void didClearDocumentOfWindowObject(LocalFrame*); DECLARE_TRACE(); private: // protocol::FrontendChannel implementation. void sendProtocolResponse(int sessionId, int callId, PassOwnPtr<protocol::DictionaryValue> message) override; void sendProtocolNotification(PassOwnPtr<protocol::DictionaryValue> message) override; void flush(); // V8InspectorSessionClient implementation. void startInstrumenting() override; void stopInstrumenting() override; void resumeStartup() override; bool canExecuteScripts() override; void profilingStarted() override; void profilingStopped() override; void forceContextsInAllFrames(); #if ENABLE(ASSERT) bool isInstrumenting(); #endif Client* m_client; V8InspectorSession* m_v8Session; int m_sessionId; bool m_autoFlush; bool m_attached; Member<InspectedFrames> m_inspectedFrames; Member<InstrumentingAgents> m_instrumentingAgents; OwnPtr<protocol::Frontend> m_inspectorFrontend; OwnPtr<protocol::Dispatcher> m_inspectorBackendDispatcher; OwnPtr<protocol::DictionaryValue> m_state; HeapVector<Member<InspectorAgent>> m_agents; Vector<OwnPtr<protocol::DictionaryValue>> m_notificationQueue; String m_lastSentState; }; } // namespace blink #endif // !defined(InspectorSession_h)
{ "content_hash": "9d6e9ae4332265743dd8cdf8a66c80fc", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 117, "avg_line_length": 34.79761904761905, "alnum_prop": 0.7454669859733151, "repo_name": "wuhengzhi/chromium-crosswalk", "id": "733ae5513a5d6f89b3cc378aff9c293c837b695e", "size": "3591", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "third_party/WebKit/Source/core/inspector/InspectorSession.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package org.motechproject.security.repository; import org.joda.time.DateTime; import org.motechproject.commons.api.Range; import org.motechproject.commons.date.util.DateUtil; import org.motechproject.security.domain.PasswordRecovery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Locale; /** * Implementation of DAO interface that utilizes a MDS back-end for storage. * Class responsible for handling PasswordRecoveries. */ @Repository public class AllPasswordRecoveries { private PasswordRecoveriesDataService dataService; /** * Returns all expired PasswordRecoveries * * @return list that contains recoveries */ @Transactional public List<PasswordRecovery> getExpired() { Range<DateTime> range = new Range<>(new DateTime(0), DateUtil.now()); return dataService.findByExpirationDate(range); } /** * Returns all PasswordRecoveries * * @return list that contains recoveries */ @Transactional public List<PasswordRecovery> allRecoveries() { return dataService.retrieveAll(); } /** * Gets PasswordRecovery for user with given name * * @param username name of user * @return recovery for given name or null in case when username is a null */ @Transactional public PasswordRecovery findForUser(String username) { return null == username ? null : dataService.findForUser(username); } /** * Gets PasswordRecovery for given token * * @param token for recovery * @return recovery for given token or null in case when token is a null */ @Transactional public PasswordRecovery findForToken(String token) { return null == token ? null : dataService.findForToken(token); } /** * Creates PasswordRecovery for given informations and return it * * @param username for recovery * @param email for recovery * @param token for recovery * @param expirationDate for recovery * @param locale for recovery * @return recovery with given informations */ @Transactional public PasswordRecovery createRecovery(String username, String email, String token, DateTime expirationDate, Locale locale) { PasswordRecovery oldRecovery = findForUser(username); if (oldRecovery != null) { remove(oldRecovery); } PasswordRecovery recovery = new PasswordRecovery(); recovery.setUsername(username); recovery.setEmail(email); recovery.setToken(token); recovery.setExpirationDate(expirationDate); recovery.setLocale(locale); add(recovery); return recovery; } /** * Updates given PasswordRecovery * * @param passwordRecovery to be updated */ @Transactional public void update(PasswordRecovery passwordRecovery) { dataService.update(passwordRecovery); } /** * Adds given PasswordRecovery provided tha one doesn't exist yet for the user * * @param passwordRecovery to be added */ @Transactional public void add(PasswordRecovery passwordRecovery) { if (findForUser(passwordRecovery.getUsername()) == null) { dataService.create(passwordRecovery); } } /** * Deletes given PasswordRecovery * * @param passwordRecovery to be removed */ @Transactional public void remove(PasswordRecovery passwordRecovery) { dataService.delete(passwordRecovery); } @Autowired public void setDataService(PasswordRecoveriesDataService dataService) { this.dataService = dataService; } }
{ "content_hash": "b3a8e01710a5d5d2d7849764faeb5f34", "timestamp": "", "source": "github", "line_count": 131, "max_line_length": 129, "avg_line_length": 29.290076335877863, "alnum_prop": 0.6836069846234037, "repo_name": "tstalka/motech", "id": "70a35a304ff4b4c9862e02edd2d803e41c0662bf", "size": "3837", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "platform/web-security/src/main/java/org/motechproject/security/repository/AllPasswordRecoveries.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "194509" }, { "name": "HTML", "bytes": "410421" }, { "name": "Java", "bytes": "5866342" }, { "name": "JavaScript", "bytes": "1928726" }, { "name": "Shell", "bytes": "47537" } ], "symlink_target": "" }
package main import ( "fmt" "strings" "github.com/lxc/lxd" "github.com/lxc/lxd/i18n" "github.com/lxc/lxd/shared" "github.com/lxc/lxd/shared/gnuflag" ) type launchCmd struct{} func (c *launchCmd) showByDefault() bool { return true } func (c *launchCmd) usage() string { return i18n.G( `Launch a container from a particular image. lxc launch [remote:]<image> [remote:][<name>] [--ephemeral|-e] [--profile|-p <profile>...] [--config|-c <key=value>...] Launches a container using the specified image and name. Not specifying -p will result in the default profile. Specifying "-p" with no argument will result in no profile. Example: lxc launch ubuntu u1`) } func (c *launchCmd) flags() { massage_args() gnuflag.Var(&confArgs, "config", i18n.G("Config key/value to apply to the new container")) gnuflag.Var(&confArgs, "c", i18n.G("Config key/value to apply to the new container")) gnuflag.Var(&profArgs, "profile", i18n.G("Profile to apply to the new container")) gnuflag.Var(&profArgs, "p", i18n.G("Profile to apply to the new container")) gnuflag.BoolVar(&ephem, "ephemeral", false, i18n.G("Ephemeral container")) gnuflag.BoolVar(&ephem, "e", false, i18n.G("Ephemeral container")) } func (c *launchCmd) run(config *lxd.Config, args []string) error { if len(args) > 2 || len(args) < 1 { return errArgs } iremote, image := config.ParseRemoteAndContainer(args[0]) var name string var remote string if len(args) == 2 { remote, name = config.ParseRemoteAndContainer(args[1]) } else { remote, name = config.ParseRemoteAndContainer("") } d, err := lxd.NewClient(config, remote) if err != nil { return err } /* * requested_empty_profiles means user requested empty * !requested_empty_profiles but len(profArgs) == 0 means use profile default */ var resp *lxd.Response profiles := []string{} for _, p := range profArgs { profiles = append(profiles, p) } if !requested_empty_profiles && len(profiles) == 0 { resp, err = d.Init(name, iremote, image, nil, configMap, ephem) } else { resp, err = d.Init(name, iremote, image, &profiles, configMap, ephem) } if err != nil { return err } initProgressTracker(d, resp.Operation) if name == "" { op, err := resp.MetadataAsOperation() if err != nil { return fmt.Errorf(i18n.G("didn't get any affected image, container or snapshot from server")) } containers, ok := op.Resources["containers"] if !ok || len(containers) == 0 { return fmt.Errorf(i18n.G("didn't get any affected image, container or snapshot from server")) } var version string toScan := strings.Replace(containers[0], "/", " ", -1) count, err := fmt.Sscanf(toScan, " %s containers %s", &version, &name) if err != nil { return err } if count != 2 { return fmt.Errorf(i18n.G("bad number of things scanned from image, container or snapshot")) } if version != shared.APIVersion { return fmt.Errorf(i18n.G("got bad version")) } } fmt.Printf(i18n.G("Creating %s")+"\n", name) if err = d.WaitForSuccess(resp.Operation); err != nil { return err } fmt.Printf(i18n.G("Starting %s")+"\n", name) resp, err = d.Action(name, shared.Start, -1, false) if err != nil { return err } err = d.WaitForSuccess(resp.Operation) if err != nil { return fmt.Errorf("%s\n"+i18n.G("Try `lxc info --show-log %s` for more info"), err, name) } return nil }
{ "content_hash": "efff9fa6b7c3e768ac76c1c110b7fc42", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 119, "avg_line_length": 25.9, "alnum_prop": 0.6700326700326701, "repo_name": "dustinkirkland/lxd", "id": "98179f2e04cff43ddc8210f40de63b7aeb8f8dca", "size": "3367", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lxc/launch.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "788810" }, { "name": "Makefile", "bytes": "2920" }, { "name": "Protocol Buffer", "bytes": "711" }, { "name": "Python", "bytes": "47381" }, { "name": "Shell", "bytes": "65406" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_lobby" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="ca.dal.cs.scavenger.PlayChallenges"> <include layout="@layout/toolbar" /> <include layout="@layout/recycler_pulltorefresh" /> <include layout="@layout/fab" /> </android.support.design.widget.CoordinatorLayout>
{ "content_hash": "2adfd6187f97b23e30e4ac4e492641e2", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 107, "avg_line_length": 40.53846153846154, "alnum_prop": 0.7685009487666035, "repo_name": "teammockr/scavenger", "id": "8668760f6ce4f7f38c824a9ed4a61bbc3f1c7ae4", "size": "527", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/main/res/layout/activity_play_challenges.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "212529" } ], "symlink_target": "" }
package com.hazelcast.nio.tcp; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import java.io.IOException; public class DummyPayload implements IdentifiedDataSerializable { private long referenceId; private boolean urgent; private byte[] bytes; public DummyPayload() { } public DummyPayload(byte[] bytes, boolean urgent) { this(bytes, urgent, -1); } public DummyPayload(byte[] bytes, boolean urgent, long referenceId) { this.bytes = bytes; this.urgent = urgent; this.referenceId = referenceId; } public boolean isUrgent() { return urgent; } public byte[] getBytes() { return bytes; } public long getReferenceId() { return referenceId; } @Override public int getFactoryId() { return TestDataFactory.FACTORY_ID; } @Override public int getId() { return TestDataFactory.DUMMY_PAYLOAD; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeByteArray(bytes); out.writeBoolean(urgent); out.writeLong(referenceId); } @Override public void readData(ObjectDataInput in) throws IOException { bytes = in.readByteArray(); urgent = in.readBoolean(); referenceId = in.readLong(); } }
{ "content_hash": "47de7c35ff8a30f456348dc7096250f7", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 73, "avg_line_length": 22.625, "alnum_prop": 0.6553867403314917, "repo_name": "Donnerbart/hazelcast", "id": "db97e918dbc0a97deb6f90367b7d943b4834209e", "size": "2073", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hazelcast/src/test/java/com/hazelcast/nio/tcp/DummyPayload.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1438" }, { "name": "C", "bytes": "344" }, { "name": "Java", "bytes": "39184651" }, { "name": "Shell", "bytes": "15150" } ], "symlink_target": "" }
package com.twu.biblioteca; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Before; import org.junit.Test; /** * Created by isabellamers on 24/04/17. */ public class UserTest { User user; String libraryNumber = "LIB-5577"; String password = "456ef"; String name = "Steven"; String phone = "043448355"; String email = "test@test.com"; @Before public void before() { user = new User(name, phone, email, libraryNumber, password); } @Test public void verify() throws Exception { Assert.assertTrue(user.verify(libraryNumber, password)); } @Test public void getDetails() throws Exception { String expectedDetail = "Steven"; Assert.assertThat(user.getDetails(), CoreMatchers.containsString(expectedDetail)); } }
{ "content_hash": "6a639cf66bb4e96ba9c57f495a8e1d44", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 90, "avg_line_length": 24.470588235294116, "alnum_prop": 0.6658653846153846, "repo_name": "AnaYs/twu-biblioteca-Anays", "id": "9fa48c91525d511be0a1ed9cd4eaedb0ad815303", "size": "832", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/com/twu/biblioteca/UserTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "17263" } ], "symlink_target": "" }
==== gaem ==== This is a fork of Silas Sewell's Google App Engine Middleware (gaem), which is currently in his graveyard_ github repository. Original README by Silas Sewell =============================== Google App Engine Middleware (gaem) is a collection of utilities for hosting external sites on Google App Engine. I created gaem because I wanted to host my blog on an unreliable server and let Google App Engine serve the content while my server was down or in maintenance mode. I plan on adding the following features: - Initial and periodic crawler - RESTful API for managing content .. ----- .. _graveyard: https://github.com/silas/graveyard/tree/master/python-gaem
{ "content_hash": "faf5888e2c29bcd301da82649278b5a0", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 164, "avg_line_length": 25.48148148148148, "alnum_prop": 0.7267441860465116, "repo_name": "llaisdy/python-gaem", "id": "1c7ccdf7934ab9513c0ac5f73eb0cbaee38c24b8", "size": "688", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "19180" } ], "symlink_target": "" }
<?php /* Safe sample input : get the $_GET['userData'] in an array sanitize : cast via + = 0 construction : concatenation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $array = array(); $array[] = 'safe' ; $array[] = $_GET['userData'] ; $array[] = 'safe' ; $tainted = $array[1] ; $tainted = $tainted + 0; $query = "SELECT * FROM COURSE c WHERE c.id IN (SELECT idcourse FROM REGISTRATION WHERE idstudent='". $tainted . "')"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
{ "content_hash": "a536cad995869770bef20027412493fb", "timestamp": "", "source": "github", "line_count": 67, "max_line_length": 123, "avg_line_length": 24.597014925373134, "alnum_prop": 0.7233009708737864, "repo_name": "stivalet/PHP-Vulnerability-test-suite", "id": "3e95d177a0c8e0f8f0a641c0ed3b621b9d24ee7f", "size": "1648", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Injection/CWE_89/safe/CWE_89__array-GET__CAST-cast_int_sort_of2__multiple_select-concatenation_simple_quote.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "64184004" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="Source to the Rust file `io\impls.rs`."> <meta name="keywords" content="rust, rustlang, rust-lang"> <title>impls.rs.html -- source</title> <link rel="stylesheet" type="text/css" href="../../../rustdoc.css"> <link rel="stylesheet" type="text/css" href="../../../main.css"> <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../../std/index.html'><img src='https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='logo' width='100'></a> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content source"><pre class="line-numbers"><span id="1"> 1</span> <span id="2"> 2</span> <span id="3"> 3</span> <span id="4"> 4</span> <span id="5"> 5</span> <span id="6"> 6</span> <span id="7"> 7</span> <span id="8"> 8</span> <span id="9"> 9</span> <span id="10"> 10</span> <span id="11"> 11</span> <span id="12"> 12</span> <span id="13"> 13</span> <span id="14"> 14</span> <span id="15"> 15</span> <span id="16"> 16</span> <span id="17"> 17</span> <span id="18"> 18</span> <span id="19"> 19</span> <span id="20"> 20</span> <span id="21"> 21</span> <span id="22"> 22</span> <span id="23"> 23</span> <span id="24"> 24</span> <span id="25"> 25</span> <span id="26"> 26</span> <span id="27"> 27</span> <span id="28"> 28</span> <span id="29"> 29</span> <span id="30"> 30</span> <span id="31"> 31</span> <span id="32"> 32</span> <span id="33"> 33</span> <span id="34"> 34</span> <span id="35"> 35</span> <span id="36"> 36</span> <span id="37"> 37</span> <span id="38"> 38</span> <span id="39"> 39</span> <span id="40"> 40</span> <span id="41"> 41</span> <span id="42"> 42</span> <span id="43"> 43</span> <span id="44"> 44</span> <span id="45"> 45</span> <span id="46"> 46</span> <span id="47"> 47</span> <span id="48"> 48</span> <span id="49"> 49</span> <span id="50"> 50</span> <span id="51"> 51</span> <span id="52"> 52</span> <span id="53"> 53</span> <span id="54"> 54</span> <span id="55"> 55</span> <span id="56"> 56</span> <span id="57"> 57</span> <span id="58"> 58</span> <span id="59"> 59</span> <span id="60"> 60</span> <span id="61"> 61</span> <span id="62"> 62</span> <span id="63"> 63</span> <span id="64"> 64</span> <span id="65"> 65</span> <span id="66"> 66</span> <span id="67"> 67</span> <span id="68"> 68</span> <span id="69"> 69</span> <span id="70"> 70</span> <span id="71"> 71</span> <span id="72"> 72</span> <span id="73"> 73</span> <span id="74"> 74</span> <span id="75"> 75</span> <span id="76"> 76</span> <span id="77"> 77</span> <span id="78"> 78</span> <span id="79"> 79</span> <span id="80"> 80</span> <span id="81"> 81</span> <span id="82"> 82</span> <span id="83"> 83</span> <span id="84"> 84</span> <span id="85"> 85</span> <span id="86"> 86</span> <span id="87"> 87</span> <span id="88"> 88</span> <span id="89"> 89</span> <span id="90"> 90</span> <span id="91"> 91</span> <span id="92"> 92</span> <span id="93"> 93</span> <span id="94"> 94</span> <span id="95"> 95</span> <span id="96"> 96</span> <span id="97"> 97</span> <span id="98"> 98</span> <span id="99"> 99</span> <span id="100">100</span> <span id="101">101</span> <span id="102">102</span> <span id="103">103</span> <span id="104">104</span> <span id="105">105</span> <span id="106">106</span> <span id="107">107</span> <span id="108">108</span> <span id="109">109</span> <span id="110">110</span> <span id="111">111</span> <span id="112">112</span> <span id="113">113</span> <span id="114">114</span> <span id="115">115</span> <span id="116">116</span> <span id="117">117</span> <span id="118">118</span> <span id="119">119</span> <span id="120">120</span> <span id="121">121</span> <span id="122">122</span> <span id="123">123</span> <span id="124">124</span> <span id="125">125</span> <span id="126">126</span> <span id="127">127</span> <span id="128">128</span> <span id="129">129</span> <span id="130">130</span> <span id="131">131</span> <span id="132">132</span> <span id="133">133</span> <span id="134">134</span> <span id="135">135</span> <span id="136">136</span> <span id="137">137</span> <span id="138">138</span> <span id="139">139</span> <span id="140">140</span> <span id="141">141</span> <span id="142">142</span> <span id="143">143</span> <span id="144">144</span> <span id="145">145</span> <span id="146">146</span> <span id="147">147</span> <span id="148">148</span> <span id="149">149</span> <span id="150">150</span> <span id="151">151</span> <span id="152">152</span> <span id="153">153</span> <span id="154">154</span> <span id="155">155</span> <span id="156">156</span> <span id="157">157</span> <span id="158">158</span> <span id="159">159</span> <span id="160">160</span> <span id="161">161</span> <span id="162">162</span> <span id="163">163</span> <span id="164">164</span> <span id="165">165</span> <span id="166">166</span> <span id="167">167</span> <span id="168">168</span> <span id="169">169</span> <span id="170">170</span> <span id="171">171</span> <span id="172">172</span> <span id="173">173</span> <span id="174">174</span> <span id="175">175</span> <span id="176">176</span> <span id="177">177</span> <span id="178">178</span> <span id="179">179</span> <span id="180">180</span> <span id="181">181</span> <span id="182">182</span> <span id="183">183</span> <span id="184">184</span> <span id="185">185</span> <span id="186">186</span> <span id="187">187</span> <span id="188">188</span> <span id="189">189</span> <span id="190">190</span> <span id="191">191</span> <span id="192">192</span> <span id="193">193</span> <span id="194">194</span> <span id="195">195</span> <span id="196">196</span> <span id="197">197</span> <span id="198">198</span> <span id="199">199</span> <span id="200">200</span> <span id="201">201</span> <span id="202">202</span> <span id="203">203</span> <span id="204">204</span> <span id="205">205</span> <span id="206">206</span> <span id="207">207</span> <span id="208">208</span> <span id="209">209</span> <span id="210">210</span> <span id="211">211</span> <span id="212">212</span> <span id="213">213</span> <span id="214">214</span> <span id="215">215</span> <span id="216">216</span> <span id="217">217</span> <span id="218">218</span> <span id="219">219</span> <span id="220">220</span> <span id="221">221</span> <span id="222">222</span> <span id="223">223</span> <span id="224">224</span> <span id="225">225</span> <span id="226">226</span> <span id="227">227</span> <span id="228">228</span> <span id="229">229</span> <span id="230">230</span> <span id="231">231</span> <span id="232">232</span> <span id="233">233</span> <span id="234">234</span> <span id="235">235</span> <span id="236">236</span> <span id="237">237</span> <span id="238">238</span> <span id="239">239</span> <span id="240">240</span> <span id="241">241</span> <span id="242">242</span> <span id="243">243</span> <span id="244">244</span> <span id="245">245</span> <span id="246">246</span> <span id="247">247</span> <span id="248">248</span> <span id="249">249</span> <span id="250">250</span> <span id="251">251</span> <span id="252">252</span> <span id="253">253</span> <span id="254">254</span> <span id="255">255</span> <span id="256">256</span> <span id="257">257</span> <span id="258">258</span> <span id="259">259</span> <span id="260">260</span> <span id="261">261</span> <span id="262">262</span> <span id="263">263</span> <span id="264">264</span> <span id="265">265</span> <span id="266">266</span> <span id="267">267</span> <span id="268">268</span> <span id="269">269</span> <span id="270">270</span> <span id="271">271</span> <span id="272">272</span> <span id="273">273</span> <span id="274">274</span> <span id="275">275</span> <span id="276">276</span> <span id="277">277</span> <span id="278">278</span> <span id="279">279</span> <span id="280">280</span> <span id="281">281</span> <span id="282">282</span> <span id="283">283</span> <span id="284">284</span> <span id="285">285</span> </pre><pre class='rust '> <span class='comment'>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT</span> <span class='comment'>// file at the top-level directory of this distribution and at</span> <span class='comment'>// http://rust-lang.org/COPYRIGHT.</span> <span class='comment'>//</span> <span class='comment'>// Licensed under the Apache License, Version 2.0 &lt;LICENSE-APACHE or</span> <span class='comment'>// http://www.apache.org/licenses/LICENSE-2.0&gt; or the MIT license</span> <span class='comment'>// &lt;LICENSE-MIT or http://opensource.org/licenses/MIT&gt;, at your</span> <span class='comment'>// option. This file may not be copied, modified, or distributed</span> <span class='comment'>// except according to those terms.</span> <span class='kw'>use</span> <span class='ident'>cmp</span>; <span class='kw'>use</span> <span class='ident'>io</span>::{<span class='self'>self</span>, <span class='ident'>SeekFrom</span>, <span class='ident'>Read</span>, <span class='ident'>Write</span>, <span class='ident'>Seek</span>, <span class='ident'>BufRead</span>, <span class='ident'>Error</span>, <span class='ident'>ErrorKind</span>}; <span class='kw'>use</span> <span class='ident'>fmt</span>; <span class='kw'>use</span> <span class='ident'>mem</span>; <span class='comment'>// =============================================================================</span> <span class='comment'>// Forwarding implementations</span> <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>R</span>: <span class='ident'>Read</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Read</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>R</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_to_end</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_to_end</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_to_string</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_to_string</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_exact</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_exact</span>(<span class='ident'>buf</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>W</span>: <span class='ident'>Write</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Write</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>W</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>flush</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>flush</span>() } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write_all</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_fmt</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>fmt</span>: <span class='ident'>fmt</span>::<span class='ident'>Arguments</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write_fmt</span>(<span class='ident'>fmt</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>S</span>: <span class='ident'>Seek</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Seek</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>S</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>seek</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>pos</span>: <span class='ident'>SeekFrom</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>u64</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>seek</span>(<span class='ident'>pos</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span>, <span class='ident'>B</span>: <span class='ident'>BufRead</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>BufRead</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> <span class='ident'>B</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>fill_buf</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>fill_buf</span>() } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>consume</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>amt</span>: <span class='ident'>usize</span>) { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>consume</span>(<span class='ident'>amt</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_until</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>byte</span>: <span class='ident'>u8</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_until</span>(<span class='ident'>byte</span>, <span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_line</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_line</span>(<span class='ident'>buf</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>R</span>: <span class='ident'>Read</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Read</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>R</span><span class='op'>&gt;</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_to_end</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_to_end</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_to_string</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_to_string</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_exact</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_exact</span>(<span class='ident'>buf</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>W</span>: <span class='ident'>Write</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Write</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>W</span><span class='op'>&gt;</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>flush</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>flush</span>() } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write_all</span>(<span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_fmt</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>fmt</span>: <span class='ident'>fmt</span>::<span class='ident'>Arguments</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>write_fmt</span>(<span class='ident'>fmt</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>S</span>: <span class='ident'>Seek</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>Seek</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>S</span><span class='op'>&gt;</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>seek</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>pos</span>: <span class='ident'>SeekFrom</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>u64</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>seek</span>(<span class='ident'>pos</span>) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='ident'>B</span>: <span class='ident'>BufRead</span> <span class='op'>+</span> ?<span class='ident'>Sized</span><span class='op'>&gt;</span> <span class='ident'>BufRead</span> <span class='kw'>for</span> <span class='ident'>Box</span><span class='op'>&lt;</span><span class='ident'>B</span><span class='op'>&gt;</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>fill_buf</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]<span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>fill_buf</span>() } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>consume</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>amt</span>: <span class='ident'>usize</span>) { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>consume</span>(<span class='ident'>amt</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_until</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>byte</span>: <span class='ident'>u8</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_until</span>(<span class='ident'>byte</span>, <span class='ident'>buf</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_line</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>String</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { (<span class='op'>*</span><span class='op'>*</span><span class='self'>self</span>).<span class='ident'>read_line</span>(<span class='ident'>buf</span>) } } <span class='comment'>// =============================================================================</span> <span class='comment'>// In-memory buffer implementations</span> <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='ident'>Read</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> [<span class='ident'>u8</span>] { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>amt</span> <span class='op'>=</span> <span class='ident'>cmp</span>::<span class='ident'>min</span>(<span class='ident'>buf</span>.<span class='ident'>len</span>(), <span class='self'>self</span>.<span class='ident'>len</span>()); <span class='kw'>let</span> (<span class='ident'>a</span>, <span class='ident'>b</span>) <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>split_at</span>(<span class='ident'>amt</span>); <span class='ident'>buf</span>[..<span class='ident'>amt</span>].<span class='ident'>copy_from_slice</span>(<span class='ident'>a</span>); <span class='op'>*</span><span class='self'>self</span> <span class='op'>=</span> <span class='ident'>b</span>; <span class='prelude-val'>Ok</span>(<span class='ident'>amt</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>read_exact</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> [<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='ident'>buf</span>.<span class='ident'>len</span>() <span class='op'>&gt;</span> <span class='self'>self</span>.<span class='ident'>len</span>() { <span class='kw'>return</span> <span class='prelude-val'>Err</span>(<span class='ident'>Error</span>::<span class='ident'>new</span>(<span class='ident'>ErrorKind</span>::<span class='ident'>UnexpectedEof</span>, <span class='string'>&quot;failed to fill whole buffer&quot;</span>)); } <span class='kw'>let</span> (<span class='ident'>a</span>, <span class='ident'>b</span>) <span class='op'>=</span> <span class='self'>self</span>.<span class='ident'>split_at</span>(<span class='ident'>buf</span>.<span class='ident'>len</span>()); <span class='ident'>buf</span>.<span class='ident'>copy_from_slice</span>(<span class='ident'>a</span>); <span class='op'>*</span><span class='self'>self</span> <span class='op'>=</span> <span class='ident'>b</span>; <span class='prelude-val'>Ok</span>(()) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='ident'>BufRead</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> [<span class='ident'>u8</span>] { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>fill_buf</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]<span class='op'>&gt;</span> { <span class='prelude-val'>Ok</span>(<span class='op'>*</span><span class='self'>self</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>consume</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>amt</span>: <span class='ident'>usize</span>) { <span class='op'>*</span><span class='self'>self</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='self'>self</span>[<span class='ident'>amt</span>..]; } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span><span class='op'>&lt;</span><span class='lifetime'>&#39;a</span><span class='op'>&gt;</span> <span class='ident'>Write</span> <span class='kw'>for</span> <span class='kw-2'>&amp;</span><span class='lifetime'>&#39;a</span> <span class='kw-2'>mut</span> [<span class='ident'>u8</span>] { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>data</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { <span class='kw'>let</span> <span class='ident'>amt</span> <span class='op'>=</span> <span class='ident'>cmp</span>::<span class='ident'>min</span>(<span class='ident'>data</span>.<span class='ident'>len</span>(), <span class='self'>self</span>.<span class='ident'>len</span>()); <span class='kw'>let</span> (<span class='ident'>a</span>, <span class='ident'>b</span>) <span class='op'>=</span> <span class='ident'>mem</span>::<span class='ident'>replace</span>(<span class='self'>self</span>, <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> []).<span class='ident'>split_at_mut</span>(<span class='ident'>amt</span>); <span class='ident'>a</span>.<span class='ident'>copy_from_slice</span>(<span class='kw-2'>&amp;</span><span class='ident'>data</span>[..<span class='ident'>amt</span>]); <span class='op'>*</span><span class='self'>self</span> <span class='op'>=</span> <span class='ident'>b</span>; <span class='prelude-val'>Ok</span>(<span class='ident'>amt</span>) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>data</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='kw'>if</span> <span class='self'>self</span>.<span class='ident'>write</span>(<span class='ident'>data</span>)? <span class='op'>==</span> <span class='ident'>data</span>.<span class='ident'>len</span>() { <span class='prelude-val'>Ok</span>(()) } <span class='kw'>else</span> { <span class='prelude-val'>Err</span>(<span class='ident'>Error</span>::<span class='ident'>new</span>(<span class='ident'>ErrorKind</span>::<span class='ident'>WriteZero</span>, <span class='string'>&quot;failed to write whole buffer&quot;</span>)) } } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>flush</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='prelude-val'>Ok</span>(()) } } <span class='attribute'>#[<span class='ident'>stable</span>(<span class='ident'>feature</span> <span class='op'>=</span> <span class='string'>&quot;rust1&quot;</span>, <span class='ident'>since</span> <span class='op'>=</span> <span class='string'>&quot;1.0.0&quot;</span>)]</span> <span class='kw'>impl</span> <span class='ident'>Write</span> <span class='kw'>for</span> <span class='ident'>Vec</span><span class='op'>&lt;</span><span class='ident'>u8</span><span class='op'>&gt;</span> { <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span><span class='ident'>usize</span><span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>extend_from_slice</span>(<span class='ident'>buf</span>); <span class='prelude-val'>Ok</span>(<span class='ident'>buf</span>.<span class='ident'>len</span>()) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>, <span class='ident'>buf</span>: <span class='kw-2'>&amp;</span>[<span class='ident'>u8</span>]) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='self'>self</span>.<span class='ident'>extend_from_slice</span>(<span class='ident'>buf</span>); <span class='prelude-val'>Ok</span>(()) } <span class='attribute'>#[<span class='ident'>inline</span>]</span> <span class='kw'>fn</span> <span class='ident'>flush</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='self'>self</span>) <span class='op'>-&gt;</span> <span class='ident'>io</span>::<span class='prelude-ty'>Result</span><span class='op'>&lt;</span>()<span class='op'>&gt;</span> { <span class='prelude-val'>Ok</span>(()) } } <span class='attribute'>#[<span class='ident'>cfg</span>(<span class='ident'>test</span>)]</span> <span class='kw'>mod</span> <span class='ident'>tests</span> { <span class='kw'>use</span> <span class='ident'>io</span>::<span class='ident'>prelude</span>::<span class='op'>*</span>; <span class='kw'>use</span> <span class='ident'>test</span>; <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_read_slice</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>) { <span class='kw'>let</span> <span class='ident'>buf</span> <span class='op'>=</span> [<span class='number'>5</span>; <span class='number'>1024</span>]; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dst</span> <span class='op'>=</span> [<span class='number'>0</span>; <span class='number'>128</span>]; <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>rd</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>buf</span>[..]; <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>8</span> { <span class='kw'>let</span> _ <span class='op'>=</span> <span class='ident'>rd</span>.<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>dst</span>); <span class='ident'>test</span>::<span class='ident'>black_box</span>(<span class='kw-2'>&amp;</span><span class='ident'>dst</span>); } }) } <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_write_slice</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>) { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>buf</span> <span class='op'>=</span> [<span class='number'>0</span>; <span class='number'>1024</span>]; <span class='kw'>let</span> <span class='ident'>src</span> <span class='op'>=</span> [<span class='number'>5</span>; <span class='number'>128</span>]; <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>wr</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>buf</span>[..]; <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>8</span> { <span class='kw'>let</span> _ <span class='op'>=</span> <span class='ident'>wr</span>.<span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='ident'>src</span>); <span class='ident'>test</span>::<span class='ident'>black_box</span>(<span class='kw-2'>&amp;</span><span class='ident'>wr</span>); } }) } <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_read_vec</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>) { <span class='kw'>let</span> <span class='ident'>buf</span> <span class='op'>=</span> <span class='macro'>vec</span><span class='macro'>!</span>[<span class='number'>5</span>; <span class='number'>1024</span>]; <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>dst</span> <span class='op'>=</span> [<span class='number'>0</span>; <span class='number'>128</span>]; <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>rd</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='ident'>buf</span>[..]; <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>8</span> { <span class='kw'>let</span> _ <span class='op'>=</span> <span class='ident'>rd</span>.<span class='ident'>read</span>(<span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>dst</span>); <span class='ident'>test</span>::<span class='ident'>black_box</span>(<span class='kw-2'>&amp;</span><span class='ident'>dst</span>); } }) } <span class='attribute'>#[<span class='ident'>bench</span>]</span> <span class='kw'>fn</span> <span class='ident'>bench_write_vec</span>(<span class='ident'>b</span>: <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>test</span>::<span class='ident'>Bencher</span>) { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>buf</span> <span class='op'>=</span> <span class='ident'>Vec</span>::<span class='ident'>with_capacity</span>(<span class='number'>1024</span>); <span class='kw'>let</span> <span class='ident'>src</span> <span class='op'>=</span> [<span class='number'>5</span>; <span class='number'>128</span>]; <span class='ident'>b</span>.<span class='ident'>iter</span>(<span class='op'>||</span> { <span class='kw'>let</span> <span class='kw-2'>mut</span> <span class='ident'>wr</span> <span class='op'>=</span> <span class='kw-2'>&amp;</span><span class='kw-2'>mut</span> <span class='ident'>buf</span>[..]; <span class='kw'>for</span> _ <span class='kw'>in</span> <span class='number'>0</span>..<span class='number'>8</span> { <span class='kw'>let</span> _ <span class='op'>=</span> <span class='ident'>wr</span>.<span class='ident'>write_all</span>(<span class='kw-2'>&amp;</span><span class='ident'>src</span>); <span class='ident'>test</span>::<span class='ident'>black_box</span>(<span class='kw-2'>&amp;</span><span class='ident'>wr</span>); } }) } } </pre> </section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> <dt>+</dt> <dd>Collapse/expand all sections</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code> or <code>* -> vec</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../../"; window.currentCrate = "std"; window.playgroundUrl = "https://play.rust-lang.org/"; </script> <script src="../../../jquery.js"></script> <script src="../../../main.js"></script> <script src="../../../playpen.js"></script> <script defer src="../../../search-index.js"></script> </body> </html>
{ "content_hash": "08fe20460e8040c4d4bbd77a9f3c4656", "timestamp": "", "source": "github", "line_count": 680, "max_line_length": 625, "avg_line_length": 77.91176470588235, "alnum_prop": 0.6103624009060022, "repo_name": "liigo/liigo.github.io", "id": "f8eb8447671e55aa5af91af02e371424ea4cd7ce", "size": "52990", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tmp/rust/inline-sidebar-items/src/std/io/impls.rs.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11826" }, { "name": "HTML", "bytes": "3895" }, { "name": "JavaScript", "bytes": "48" } ], "symlink_target": "" }
var RotateIcon = function(options){ this.options = options || {}; this.rImg = options.img || new Image(); this.rImg.src = this.rImg.src || this.options.url || '/static/groups/img/car_map_state_go.png'; this.options.width = this.options.width || this.rImg.width || 52; this.options.height = this.options.height || this.rImg.height || 60; canvas = document.createElement("canvas"); canvas.width = this.options.width; canvas.height = this.options.height; this.context = canvas.getContext("2d"); this.canvas = canvas; }; RotateIcon.makeIcon = function(url) { return new RotateIcon({url: url}); }; RotateIcon.prototype.setRotation = function(options){ var canvas = this.context, angle = options.deg ? options.deg * Math.PI / 180: options.rad, centerX = this.options.width/2, centerY = this.options.height/2; canvas.clearRect(0, 0, this.options.width, this.options.height); canvas.save(); canvas.translate(centerX, centerY); canvas.rotate(angle); canvas.translate(-centerX, -centerY); canvas.drawImage(this.rImg, 0, 0); canvas.restore(); return this; }; RotateIcon.prototype.getUrl = function(){ return this.canvas.toDataURL('image/png'); };
{ "content_hash": "50293b8098a9cd7063e577de38b87b65", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 99, "avg_line_length": 36.5, "alnum_prop": 0.669621273166801, "repo_name": "ychen1986/CarSensorDemoWeb", "id": "f5dc8116c2a988cbbf403980b46d0320c8aff120", "size": "1241", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "CarReplay/RotateIcon.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5728" }, { "name": "HTML", "bytes": "40312" }, { "name": "JavaScript", "bytes": "1257524" } ], "symlink_target": "" }
/* First off, code is include which follows the "include" declaration ** in the input file. */ #include <stdio.h> #line 27 "parser.lemon" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "ext/standard/php_smart_str.h" #include "Zend/zend_exceptions.h" #include "parser.h" #include "scanner.h" #include "annot.h" static zval *phannot_ret_literal_zval(int type, phannot_parser_token *T) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", type); if (T) { add_assoc_stringl(ret, "value", T->token, T->token_len, 0); efree(T); } return ret; } static zval *phannot_ret_array(zval *items) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ARRAY); if (items) { add_assoc_zval(ret, "items", items); } return ret; } static zval *phannot_ret_zval_list(zval *list_left, zval *right_list) { zval *ret; HashPosition pos; HashTable *list; MAKE_STD_ZVAL(ret); array_init(ret); if (list_left) { list = Z_ARRVAL_P(list_left); if (zend_hash_index_exists(list, 0)) { zend_hash_internal_pointer_reset_ex(list, &pos); for (;; zend_hash_move_forward_ex(list, &pos)) { zval ** item; if (zend_hash_get_current_data_ex(list, (void**) &item, &pos) == FAILURE) { break; } Z_ADDREF_PP(item); add_next_index_zval(ret, *item); } zval_ptr_dtor(&list_left); } else { add_next_index_zval(ret, list_left); } } add_next_index_zval(ret, right_list); return ret; } static zval *phannot_ret_named_item(phannot_parser_token *name, zval *expr) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_zval(ret, "expr", expr); if (name != NULL) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } return ret; } static zval *phannot_ret_annotation(phannot_parser_token *name, zval *arguments, phannot_scanner_state *state) { zval *ret; MAKE_STD_ZVAL(ret); array_init(ret); add_assoc_long(ret, "type", PHANNOT_T_ANNOTATION); if (name) { add_assoc_stringl(ret, "name", name->token, name->token_len, 0); efree(name); } if (arguments) { add_assoc_zval(ret, "arguments", arguments); } Z_ADDREF_P(state->active_file); add_assoc_zval(ret, "file", state->active_file); add_assoc_long(ret, "line", state->active_line); return ret; } #line 132 "parser.c" /* Next is all token values, in a form suitable for use by makeheaders. ** This section will be null unless lemon is run with the -m switch. */ /* ** These constants (all generated automatically by the parser generator) ** specify the various kinds of tokens (terminals) that the parser ** understands. ** ** Each symbol here is a terminal symbol in the grammar. */ /* Make sure the INTERFACE macro is defined. */ #ifndef INTERFACE # define INTERFACE 1 #endif /* The next thing included is series of defines which control ** various aspects of the generated parser. ** YYCODETYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 terminals ** and nonterminals. "int" is used otherwise. ** YYNOCODE is a number of type YYCODETYPE which corresponds ** to no legal terminal or nonterminal number. This ** number is used to fill in empty slots of the hash ** table. ** YYFALLBACK If defined, this indicates that one or more tokens ** have fall-back values which should be used if the ** original value of the token will not parse. ** YYACTIONTYPE is the data type used for storing terminal ** and nonterminal numbers. "unsigned char" is ** used if there are fewer than 250 rules and ** states combined. "int" is used otherwise. ** phannot_TOKENTYPE is the data type used for minor tokens given ** directly to the parser from the tokenizer. ** YYMINORTYPE is the data type used for all minor tokens. ** This is typically a union of many types, one of ** which is phannot_TOKENTYPE. The entry in the union ** for base tokens is called "yy0". ** YYSTACKDEPTH is the maximum depth of the parser's stack. ** phannot_ARG_SDECL A static variable declaration for the %extra_argument ** phannot_ARG_PDECL A parameter declaration for the %extra_argument ** phannot_ARG_STORE Code to store %extra_argument into yypParser ** phannot_ARG_FETCH Code to extract %extra_argument from yypParser ** YYNSTATE the combined number of states. ** YYNRULE the number of rules in the grammar ** YYERRORSYMBOL is the code number of the error symbol. If not ** defined, then do no error processing. */ #define YYCODETYPE unsigned char #define YYNOCODE 28 #define YYACTIONTYPE unsigned char #define phannot_TOKENTYPE phannot_parser_token* typedef union { phannot_TOKENTYPE yy0; zval* yy36; int yy55; } YYMINORTYPE; #define YYSTACKDEPTH 100 #define phannot_ARG_SDECL phannot_parser_status *status; #define phannot_ARG_PDECL ,phannot_parser_status *status #define phannot_ARG_FETCH phannot_parser_status *status = yypParser->status #define phannot_ARG_STORE yypParser->status = status #define YYNSTATE 40 #define YYNRULE 25 #define YYERRORSYMBOL 18 #define YYERRSYMDT yy55 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) /* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. ** ** Suppose the action integer is N. Then the action is determined as ** follows ** ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead ** token onto the stack and goto state N. ** ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE. ** ** N == YYNSTATE+YYNRULE A syntax error has occurred. ** ** N == YYNSTATE+YYNRULE+1 The parser accepts its input. ** ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused ** slots in the yy_action[] table. ** ** The action table is constructed as a single large table named yy_action[]. ** Given state S and lookahead X, the action is computed as ** ** yy_action[ yy_shift_ofst[S] + X ] ** ** If the index value yy_shift_ofst[S]+X is out of range or if the value ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S] ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table ** and that yy_default[S] should be used instead. ** ** The formula above is for computing the action when the lookahead is ** a terminal symbol. If the lookahead is a non-terminal (as occurs after ** a reduce action) then the yy_reduce_ofst[] array is used in place of ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of ** YY_SHIFT_USE_DFLT. ** ** The following are the tables generated in this section: ** ** yy_action[] A single table containing all actions. ** yy_lookahead[] A table containing the lookahead for each entry in ** yy_action. Used to detect hash collisions. ** yy_shift_ofst[] For each state, the offset into yy_action for ** shifting terminals. ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static YYACTIONTYPE yy_action[] = { /* 0 */ 4, 28, 15, 38, 12, 37, 16, 18, 20, 21, /* 10 */ 22, 23, 24, 4, 31, 4, 17, 15, 40, 19, /* 20 */ 35, 16, 18, 20, 21, 22, 23, 24, 3, 31, /* 30 */ 4, 28, 15, 6, 12, 30, 16, 18, 20, 21, /* 40 */ 22, 23, 24, 54, 31, 15, 25, 27, 11, 16, /* 50 */ 13, 36, 15, 7, 27, 11, 16, 15, 32, 27, /* 60 */ 11, 16, 15, 9, 10, 11, 16, 66, 1, 2, /* 70 */ 39, 15, 9, 5, 14, 16, 41, 26, 4, 9, /* 80 */ 29, 34, 54, 8, 54, 54, 54, 54, 33, }; static YYCODETYPE yy_lookahead[] = { /* 0 */ 2, 3, 22, 5, 6, 25, 26, 9, 10, 11, /* 10 */ 12, 13, 14, 2, 16, 2, 3, 22, 0, 6, /* 20 */ 25, 26, 9, 10, 11, 12, 13, 14, 22, 16, /* 30 */ 2, 3, 22, 4, 6, 25, 26, 9, 10, 11, /* 40 */ 12, 13, 14, 27, 16, 22, 23, 24, 25, 26, /* 50 */ 7, 8, 22, 23, 24, 25, 26, 22, 23, 24, /* 60 */ 25, 26, 22, 1, 24, 25, 26, 19, 20, 21, /* 70 */ 22, 22, 1, 3, 25, 26, 0, 15, 2, 1, /* 80 */ 7, 8, 27, 5, 27, 27, 27, 27, 17, }; #define YY_SHIFT_USE_DFLT (-3) static signed char yy_shift_ofst[] = { /* 0 */ 11, 18, 76, -3, 70, 29, -2, 78, -3, 28, /* 10 */ -3, -3, 43, 13, -3, -3, -3, -3, -3, -3, /* 20 */ -3, -3, -3, -3, 28, 62, -3, -3, 73, 13, /* 30 */ -3, 28, 71, -3, 13, -3, 13, -3, -3, -3, }; #define YY_REDUCE_USE_DFLT (-21) static signed char yy_reduce_ofst[] = { /* 0 */ 48, -21, 6, -21, -21, -21, 30, -21, -21, 40, /* 10 */ -21, -21, -21, 49, -21, -21, -21, -21, -21, -21, /* 20 */ -21, -21, -21, -21, 23, -21, -21, -21, -21, 10, /* 30 */ -21, 35, -21, -21, -5, -21, -20, -21, -21, -21, }; static YYACTIONTYPE yy_default[] = { /* 0 */ 65, 65, 65, 42, 65, 46, 65, 65, 44, 65, /* 10 */ 47, 49, 58, 65, 50, 54, 55, 56, 57, 58, /* 20 */ 59, 60, 61, 62, 65, 65, 63, 48, 56, 65, /* 30 */ 52, 65, 65, 64, 65, 53, 65, 51, 45, 43, }; #define YY_SZ_ACTTAB (sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: ** ** %fallback ID X Y Z. ** ** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. */ #ifdef YYFALLBACK static const YYCODETYPE yyFallback[] = { }; #endif /* YYFALLBACK */ /* The following structure represents a single element of the ** parser's stack. Information stored includes: ** ** + The state number for the parser at this level of the stack. ** ** + The value of the token stored at this level of the stack. ** (In other words, the "major" token.) ** ** + The semantic value stored at this level of the stack. This is ** the information used by the action routines in the grammar. ** It is sometimes called the "minor" token. */ struct yyStackEntry { int stateno; /* The state-number */ int major; /* The major token value. This is the code ** number for the token at this stack level */ YYMINORTYPE minor; /* The user-supplied minor token value. This ** is the value of the token */ }; typedef struct yyStackEntry yyStackEntry; /* The state of the parser is completely contained in an instance of ** the following structure */ struct yyParser { int yyidx; /* Index of top element in stack */ int yyerrcnt; /* Shifts left before out of the error */ phannot_ARG_SDECL /* A place to hold %extra_argument */ yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */ }; typedef struct yyParser yyParser; #ifndef NDEBUG #include <stdio.h> static FILE *yyTraceFILE = 0; static char *yyTracePrompt = 0; #endif /* NDEBUG */ #ifndef NDEBUG /* ** Turn parser tracing on by giving a stream to which to write the trace ** and a prompt to preface each trace message. Tracing is turned off ** by making either argument NULL ** ** Inputs: ** <ul> ** <li> A FILE* to which trace output should be written. ** If NULL, then tracing is turned off. ** <li> A prefix string written at the beginning of every ** line of trace output. If NULL, then tracing is ** turned off. ** </ul> ** ** Outputs: ** None. */ void phannot_Trace(FILE *TraceFILE, char *zTracePrompt){ yyTraceFILE = TraceFILE; yyTracePrompt = zTracePrompt; if( yyTraceFILE==0 ) yyTracePrompt = 0; else if( yyTracePrompt==0 ) yyTraceFILE = 0; } #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing shifts, the names of all terminals and nonterminals ** are required. The following table supplies these names */ static const char *yyTokenName[] = { "$", "COMMA", "AT", "IDENTIFIER", "PARENTHESES_OPEN", "PARENTHESES_CLOSE", "STRING", "EQUALS", "COLON", "INTEGER", "DOUBLE", "NULL", "FALSE", "TRUE", "BRACKET_OPEN", "BRACKET_CLOSE", "SBRACKET_OPEN", "SBRACKET_CLOSE", "error", "program", "annotation_language", "annotation_list", "annotation", "argument_list", "argument_item", "expr", "array", }; #endif /* NDEBUG */ #ifndef NDEBUG /* For tracing reduce actions, the names of all rules are required. */ static const char *yyRuleName[] = { /* 0 */ "program ::= annotation_language", /* 1 */ "annotation_language ::= annotation_list", /* 2 */ "annotation_list ::= annotation_list annotation", /* 3 */ "annotation_list ::= annotation", /* 4 */ "annotation ::= AT IDENTIFIER PARENTHESES_OPEN argument_list PARENTHESES_CLOSE", /* 5 */ "annotation ::= AT IDENTIFIER PARENTHESES_OPEN PARENTHESES_CLOSE", /* 6 */ "annotation ::= AT IDENTIFIER", /* 7 */ "argument_list ::= argument_list COMMA argument_item", /* 8 */ "argument_list ::= argument_item", /* 9 */ "argument_item ::= expr", /* 10 */ "argument_item ::= STRING EQUALS expr", /* 11 */ "argument_item ::= STRING COLON expr", /* 12 */ "argument_item ::= IDENTIFIER EQUALS expr", /* 13 */ "argument_item ::= IDENTIFIER COLON expr", /* 14 */ "expr ::= annotation", /* 15 */ "expr ::= array", /* 16 */ "expr ::= IDENTIFIER", /* 17 */ "expr ::= INTEGER", /* 18 */ "expr ::= STRING", /* 19 */ "expr ::= DOUBLE", /* 20 */ "expr ::= NULL", /* 21 */ "expr ::= FALSE", /* 22 */ "expr ::= TRUE", /* 23 */ "array ::= BRACKET_OPEN argument_list BRACKET_CLOSE", /* 24 */ "array ::= SBRACKET_OPEN argument_list SBRACKET_CLOSE", }; #endif /* NDEBUG */ /* ** This function returns the symbolic name associated with a token ** value. */ const char *phannot_TokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif } /* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to phannot_ and phannot_Free. */ void *phannot_Alloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; } /* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: #line 214 "parser.lemon" { if ((yypminor->yy0)) { if ((yypminor->yy0)->free_flag) { efree((yypminor->yy0)->token); } efree((yypminor->yy0)); } } #line 498 "parser.c" break; case 20: case 21: case 22: case 23: case 24: case 25: #line 227 "parser.lemon" { zval_ptr_dtor(&(yypminor->yy36)); } #line 508 "parser.c" break; default: break; /* If no destructor action specified: do nothing */ } } /* ** Pop the parser's stack once. ** ** If there is a destructor routine associated with the token which ** is popped from the stack, then call it. ** ** Return the major token number for the symbol popped. */ static int yy_pop_parser_stack(yyParser *pParser){ YYCODETYPE yymajor; yyStackEntry *yytos = &pParser->yystack[pParser->yyidx]; if( pParser->yyidx<0 ) return 0; #ifndef NDEBUG if( yyTraceFILE && pParser->yyidx>=0 ){ fprintf(yyTraceFILE,"%sPopping %s\n", yyTracePrompt, yyTokenName[yytos->major]); } #endif yymajor = yytos->major; yy_destructor( yymajor, &yytos->minor); pParser->yyidx--; return yymajor; } /* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: ** <ul> ** <li> A pointer to the parser. This should be a pointer ** obtained from phannot_Alloc. ** <li> A pointer to a function used to reclaim memory obtained ** from malloc. ** </ul> */ void phannot_Free( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); } /* ** Find the appropriate action for a parser given the terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_shift_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; /* if( pParser->yyidx<0 ) return YY_NO_ACTION; */ i = yy_shift_ofst[stateno]; if( i==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0]) && (iFallback = yyFallback[iLookAhead])!=0 ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n", yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]); } #endif return yy_find_shift_action(pParser, iFallback); } #endif return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Find the appropriate action for a parser given the non-terminal ** look-ahead token iLookAhead. ** ** If the look-ahead token is YYNOCODE, then check to see if the action is ** independent of the look-ahead. If it is, return the action, otherwise ** return YY_NO_ACTION. */ static int yy_find_reduce_action( yyParser *pParser, /* The parser */ int iLookAhead /* The look-ahead token */ ){ int i; int stateno = pParser->yystack[pParser->yyidx].stateno; i = yy_reduce_ofst[stateno]; if( i==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } if( iLookAhead==YYNOCODE ){ return YY_NO_ACTION; } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; }else{ return yy_action[i]; } } /* ** Perform a shift action. */ static void yy_shift( yyParser *yypParser, /* The parser to be shifted */ int yyNewState, /* The new state to shift in */ int yyMajor, /* The major token to shift in */ YYMINORTYPE *yypMinor /* Pointer ot the minor token to shift in */ ){ yyStackEntry *yytos; yypParser->yyidx++; if( yypParser->yyidx>=YYSTACKDEPTH ){ phannot_ARG_FETCH; yypParser->yyidx--; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will execute if the parser ** stack every overflows */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument var */ return; } yytos = &yypParser->yystack[yypParser->yyidx]; yytos->stateno = yyNewState; yytos->major = yyMajor; yytos->minor = *yypMinor; #ifndef NDEBUG if( yyTraceFILE && yypParser->yyidx>0 ){ int i; fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState); fprintf(yyTraceFILE,"%sStack:",yyTracePrompt); for(i=1; i<=yypParser->yyidx; i++) fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]); fprintf(yyTraceFILE,"\n"); } #endif } /* The following table contains information about every rule that ** is used during the reduce. */ static struct { YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */ unsigned char nrhs; /* Number of right-hand side symbols in the rule */ } yyRuleInfo[] = { { 19, 1 }, { 20, 1 }, { 21, 2 }, { 21, 1 }, { 22, 5 }, { 22, 4 }, { 22, 2 }, { 23, 3 }, { 23, 1 }, { 24, 1 }, { 24, 3 }, { 24, 3 }, { 24, 3 }, { 24, 3 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 25, 1 }, { 26, 3 }, { 26, 3 }, }; static void yy_accept(yyParser*); /* Forward Declaration */ /* ** Perform a reduce action and the shift that must immediately ** follow the reduce. */ static void yy_reduce( yyParser *yypParser, /* The parser */ int yyruleno /* Number of the rule by which to reduce */ ){ int yygoto; /* The next state */ int yyact; /* The next action */ YYMINORTYPE yygotominor; /* The LHS of the rule reduced */ yyStackEntry *yymsp; /* The top of the parser's stack */ int yysize; /* Amount to pop the stack */ phannot_ARG_FETCH; yymsp = &yypParser->yystack[yypParser->yyidx]; #ifndef NDEBUG if( yyTraceFILE && yyruleno>=0 && yyruleno<sizeof(yyRuleName)/sizeof(yyRuleName[0]) ){ fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt, yyRuleName[yyruleno]); } #endif /* NDEBUG */ switch( yyruleno ){ /* Beginning here are the reduction cases. A typical example ** follows: ** case 0: ** #line <lineno> <grammarfile> ** { ... } // User supplied code ** #line <lineno> <thisfile> ** break; */ case 0: #line 223 "parser.lemon" { status->ret = yymsp[0].minor.yy36; } #line 750 "parser.c" break; case 1: case 14: case 15: #line 229 "parser.lemon" { yygotominor.yy36 = yymsp[0].minor.yy36; } #line 759 "parser.c" break; case 2: #line 235 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(yymsp[-1].minor.yy36, yymsp[0].minor.yy36); } #line 766 "parser.c" break; case 3: case 8: #line 239 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(NULL, yymsp[0].minor.yy36); } #line 774 "parser.c" break; case 4: #line 246 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[-3].minor.yy0, yymsp[-1].minor.yy36, status->scanner_state); yy_destructor(2,&yymsp[-4].minor); yy_destructor(4,&yymsp[-2].minor); yy_destructor(5,&yymsp[0].minor); } #line 784 "parser.c" break; case 5: #line 250 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[-2].minor.yy0, NULL, status->scanner_state); yy_destructor(2,&yymsp[-3].minor); yy_destructor(4,&yymsp[-1].minor); yy_destructor(5,&yymsp[0].minor); } #line 794 "parser.c" break; case 6: #line 254 "parser.lemon" { yygotominor.yy36 = phannot_ret_annotation(yymsp[0].minor.yy0, NULL, status->scanner_state); yy_destructor(2,&yymsp[-1].minor); } #line 802 "parser.c" break; case 7: #line 260 "parser.lemon" { yygotominor.yy36 = phannot_ret_zval_list(yymsp[-2].minor.yy36, yymsp[0].minor.yy36); yy_destructor(1,&yymsp[-1].minor); } #line 810 "parser.c" break; case 9: #line 270 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(NULL, yymsp[0].minor.yy36); } #line 817 "parser.c" break; case 10: case 12: #line 274 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(yymsp[-2].minor.yy0, yymsp[0].minor.yy36); yy_destructor(7,&yymsp[-1].minor); } #line 826 "parser.c" break; case 11: case 13: #line 278 "parser.lemon" { yygotominor.yy36 = phannot_ret_named_item(yymsp[-2].minor.yy0, yymsp[0].minor.yy36); yy_destructor(8,&yymsp[-1].minor); } #line 835 "parser.c" break; case 16: #line 300 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_IDENTIFIER, yymsp[0].minor.yy0); } #line 842 "parser.c" break; case 17: #line 304 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_INTEGER, yymsp[0].minor.yy0); } #line 849 "parser.c" break; case 18: #line 308 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_STRING, yymsp[0].minor.yy0); } #line 856 "parser.c" break; case 19: #line 312 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_DOUBLE, yymsp[0].minor.yy0); } #line 863 "parser.c" break; case 20: #line 316 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_NULL, NULL); yy_destructor(11,&yymsp[0].minor); } #line 871 "parser.c" break; case 21: #line 320 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_FALSE, NULL); yy_destructor(12,&yymsp[0].minor); } #line 879 "parser.c" break; case 22: #line 324 "parser.lemon" { yygotominor.yy36 = phannot_ret_literal_zval(PHANNOT_T_TRUE, NULL); yy_destructor(13,&yymsp[0].minor); } #line 887 "parser.c" break; case 23: #line 328 "parser.lemon" { yygotominor.yy36 = phannot_ret_array(yymsp[-1].minor.yy36); yy_destructor(14,&yymsp[-2].minor); yy_destructor(15,&yymsp[0].minor); } #line 896 "parser.c" break; case 24: #line 332 "parser.lemon" { yygotominor.yy36 = phannot_ret_array(yymsp[-1].minor.yy36); yy_destructor(16,&yymsp[-2].minor); yy_destructor(17,&yymsp[0].minor); } #line 905 "parser.c" break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; yypParser->yyidx -= yysize; yyact = yy_find_reduce_action(yypParser,yygoto); if( yyact < YYNSTATE ){ yy_shift(yypParser,yyact,yygoto,&yygotominor); }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } /* ** The following code executes when the parse fails */ static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ phannot_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following code executes when a syntax error first occurs. */ static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ phannot_ARG_FETCH; #define TOKEN (yyminor.yy0) #line 151 "parser.lemon" if (status->scanner_state->start_length) { { char *token_name = NULL; const phannot_token_names *tokens = phannot_tokens; int token_found = 0; int active_token = status->scanner_state->active_token; int near_length = status->scanner_state->start_length; if (active_token) { do { if (tokens->code == active_token) { token_found = 1; token_name = tokens->name; break; } ++tokens; } while (tokens[0].code != 0); } if (!token_name) { token_found = 0; token_name = estrndup("UNKNOWN", strlen("UNKNOWN")); } status->syntax_error_len = 128 + strlen(token_name) + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); if (near_length > 0) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), near to '%s' in %s on line %d", token_name, status->token->value, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, near to '%s' in %s on line %d", token_name, status->scanner_state->start, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { if (active_token != PHANNOT_T_IGNORE) { if (status->token->value) { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s(%s), at the end of docblock in %s on line %d", token_name, status->token->value, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected token %s, at the end of docblock in %s on line %d", token_name, Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } } else { snprintf(status->syntax_error, status->syntax_error_len, "Syntax error, unexpected EOF, at the end of docblock in %s on line %d", Z_STRVAL_P(status->scanner_state->active_file), status->scanner_state->active_line); } status->syntax_error[status->syntax_error_len-1] = '\0'; } if (!token_found) { if (token_name) { efree(token_name); } } } } else { status->syntax_error_len = 48 + Z_STRLEN_P(status->scanner_state->active_file); status->syntax_error = emalloc(sizeof(char) * status->syntax_error_len); sprintf(status->syntax_error, "Syntax error, unexpected EOF in %s", Z_STRVAL_P(status->scanner_state->active_file)); } status->status = PHANNOT_PARSING_FAILED; #line 1010 "parser.c" phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts */ static void yy_accept( yyParser *yypParser /* The parser */ ){ phannot_ARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ phannot_ARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* The main parser program. ** The first argument is a pointer to a structure obtained from ** "phannot_Alloc" which describes the current state of the parser. ** The second argument is the major token number. The third is ** the minor token. The fourth optional argument is whatever the ** user wants (and specified in the grammar) and is available for ** use by the action routines. ** ** Inputs: ** <ul> ** <li> A pointer to the parser (an opaque structure.) ** <li> The major token number. ** <li> The minor token number. ** <li> An option argument of a grammar-specified type. ** </ul> ** ** Outputs: ** None. */ void phannot_( void *yyp, /* The parser */ int yymajor, /* The major token code number */ phannot_TOKENTYPE yyminor /* The value for the token */ phannot_ARG_PDECL /* Optional %extra_argument parameter */ ){ YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ int yyerrorhit = 0; /* True if yymajor has invoked an error */ yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ if( yymajor==0 ) return; yypParser->yyidx = 0; yypParser->yyerrcnt = -1; yypParser->yystack[0].stateno = 0; yypParser->yystack[0].major = 0; } yyminorunion.yy0 = yyminor; yyendofinput = (yymajor==0); phannot_ARG_STORE; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]); } #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyact<YYNSTATE ){ yy_shift(yypParser,yyact,yymajor,&yyminorunion); yypParser->yyerrcnt--; if( yyendofinput && yypParser->yyidx>=0 ){ yymajor = 0; }else{ yymajor = YYNOCODE; } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); }else if( yyact == YY_ERROR_ACTION ){ int yymx; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif #ifdef YYERRORSYMBOL /* A syntax error has occurred. ** The response to an error depends upon whether or not the ** grammar defines an error token "ERROR". ** ** This is what we do if the grammar does define ERROR: ** ** * Call the %syntax_error function. ** ** * Begin popping the stack until we enter a state where ** it is legal to shift the error symbol, then shift ** the error symbol. ** ** * Set the error count to three. ** ** * Begin accepting and shifting new tokens. No new error ** processing will occur until three tokens have been ** shifted successfully. ** */ if( yypParser->yyerrcnt<0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yymx = yypParser->yystack[yypParser->yyidx].major; if( yymx==YYERRORSYMBOL || yyerrorhit ){ #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sDiscard input token %s\n", yyTracePrompt,yyTokenName[yymajor]); } #endif yy_destructor(yymajor,&yyminorunion); yymajor = YYNOCODE; }else{ while( yypParser->yyidx >= 0 && yymx != YYERRORSYMBOL && (yyact = yy_find_shift_action(yypParser,YYERRORSYMBOL)) >= YYNSTATE ){ yy_pop_parser_stack(yypParser); } if( yypParser->yyidx < 0 || yymajor==0 ){ yy_destructor(yymajor,&yyminorunion); yy_parse_failed(yypParser); yymajor = YYNOCODE; }else if( yymx!=YYERRORSYMBOL ){ YYMINORTYPE u2; u2.YYERRSYMDT = 0; yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2); } } yypParser->yyerrcnt = 3; yyerrorhit = 1; #else /* YYERRORSYMBOL is not defined */ /* This is what we do if the grammar does not define ERROR: ** ** * Report an error message, and throw away the input token. ** ** * If the input token is $, then fail the parse. ** ** As before, subsequent error messages are suppressed until ** three input tokens have been successfully shifted. */ if( yypParser->yyerrcnt<=0 ){ yy_syntax_error(yypParser,yymajor,yyminorunion); } yypParser->yyerrcnt = 3; yy_destructor(yymajor,&yyminorunion); if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif }else{ yy_accept(yypParser); yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } /* +------------------------------------------------------------------------+ | Phalcon Framework | +------------------------------------------------------------------------+ | Copyright (c) 2011-2014 Phalcon Team (http://www.phalconphp.com) | +------------------------------------------------------------------------+ | This source file is subject to the New BSD License that is bundled | | with this package in the file docs/LICENSE.txt. | | | | If you did not receive a copy of the license and are unable to | | obtain it through the world-wide-web, please send an email | | to license@phalconphp.com so we can send you a copy immediately. | +------------------------------------------------------------------------+ | Authors: Andres Gutierrez <andres@phalconphp.com> | | Eduar Carvajal <eduar@phalconphp.com> | +------------------------------------------------------------------------+ */ const phannot_token_names phannot_tokens[] = { { "INTEGER", PHANNOT_T_INTEGER }, { "DOUBLE", PHANNOT_T_DOUBLE }, { "STRING", PHANNOT_T_STRING }, { "IDENTIFIER", PHANNOT_T_IDENTIFIER }, { "@", PHANNOT_T_AT }, { ",", PHANNOT_T_COMMA }, { "=", PHANNOT_T_EQUALS }, { ":", PHANNOT_T_COLON }, { "(", PHANNOT_T_PARENTHESES_OPEN }, { ")", PHANNOT_T_PARENTHESES_CLOSE }, { "{", PHANNOT_T_BRACKET_OPEN }, { "}", PHANNOT_T_BRACKET_CLOSE }, { "[", PHANNOT_T_SBRACKET_OPEN }, { "]", PHANNOT_T_SBRACKET_CLOSE }, { "ARBITRARY TEXT", PHANNOT_T_ARBITRARY_TEXT }, { NULL, 0 } }; /** * Wrapper to alloc memory within the parser */ static void *phannot_wrapper_alloc(size_t bytes){ return emalloc(bytes); } /** * Wrapper to free memory within the parser */ static void phannot_wrapper_free(void *pointer){ efree(pointer); } /** * Creates a parser_token to be passed to the parser */ static void phannot_parse_with_token(void* phannot_parser, int opcode, int parsercode, phannot_scanner_token *token, phannot_parser_status *parser_status){ phannot_parser_token *pToken; pToken = emalloc(sizeof(phannot_parser_token)); pToken->opcode = opcode; pToken->token = token->value; pToken->token_len = token->len; pToken->free_flag = 1; phannot_(phannot_parser, parsercode, pToken, parser_status); token->value = NULL; token->len = 0; } /** * Creates an error message when it's triggered by the scanner */ static void phannot_scanner_error_msg(phannot_parser_status *parser_status, zval **error_msg TSRMLS_DC){ int error_length; char *error, *error_part; phannot_scanner_state *state = parser_status->scanner_state; ALLOC_INIT_ZVAL(*error_msg); if (state->start) { error_length = 128 + state->start_length + Z_STRLEN_P(state->active_file); error = emalloc(sizeof(char) * error_length); if (state->start_length > 16) { error_part = estrndup(state->start, 16); snprintf(error, 64 + state->start_length, "Scanning error before '%s...' in %s on line %d", error_part, Z_STRVAL_P(state->active_file), state->active_line); efree(error_part); } else { snprintf(error, error_length - 1, "Scanning error before '%s' in %s on line %d", state->start, Z_STRVAL_P(state->active_file), state->active_line); } error[error_length - 1] = '\0'; ZVAL_STRING(*error_msg, error, 1); } else { error_length = sizeof(char) * (64 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanning error near to EOF in %s", Z_STRVAL_P(state->active_file)); ZVAL_STRING(*error_msg, error, 1); error[error_length - 1] = '\0'; } efree(error); } /** * Receives the comment tokenizes and parses it */ int phannot_parse_annotations(zval *result, zval *comment, zval *file_path, zval *line TSRMLS_DC){ zval *error_msg = NULL; ZVAL_NULL(result); if (Z_TYPE_P(comment) != IS_STRING) { zend_throw_exception(zend_exception_get_default(TSRMLS_C), "Comment must be a string", 0 TSRMLS_CC); return FAILURE; } if(phannot_internal_parse_annotations(&result, comment, file_path, line, &error_msg TSRMLS_CC) == FAILURE){ if (error_msg != NULL) { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, Z_STRVAL_P(error_msg), Z_STRLEN_P(error_msg), 1 TSRMLS_CC); zend_throw_exception(zend_exception_get_default(TSRMLS_C), Z_STRVAL_P(error_msg) , 0 TSRMLS_CC); } else { // phalcon_throw_exception_string(phalcon_annotations_exception_ce, ZEND_STRL("There was an error parsing annotation"), 1 TSRMLS_CC); zend_throw_exception(zend_exception_get_default(TSRMLS_C), "There was an error parsing annotation" , 0 TSRMLS_CC); } return FAILURE; } return SUCCESS; } /** * Remove comment separators from a docblock */ void phannot_remove_comment_separators(zval *return_value, char *comment, int length, int *start_lines) { int start_mode = 1, j, i, open_parentheses; smart_str processed_str = {0}; char ch; (*start_lines) = 0; for (i = 0; i < length; i++) { ch = comment[i]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (ch == '@') { smart_str_appendc(&processed_str, ch); i++; open_parentheses = 0; for (j = i; j < length; j++) { ch = comment[j]; if (start_mode) { if (ch == ' ' || ch == '*' || ch == '/' || ch == '\t' || ch == 11) { continue; } start_mode = 0; } if (open_parentheses == 0) { if (isalnum(ch) || '_' == ch || '\\' == ch) { smart_str_appendc(&processed_str, ch); continue; } if (ch == '(') { smart_str_appendc(&processed_str, ch); open_parentheses++; continue; } } else { smart_str_appendc(&processed_str, ch); if (ch == '(') { open_parentheses++; } else if (ch == ')') { open_parentheses--; } else if (ch == '\n') { (*start_lines)++; start_mode = 1; } if (open_parentheses > 0) { continue; } } i = j; smart_str_appendc(&processed_str, ' '); break; } } if (ch == '\n') { (*start_lines)++; start_mode = 1; } } smart_str_0(&processed_str); if (processed_str.len) { RETURN_STRINGL(processed_str.c, processed_str.len, 0); } else { RETURN_EMPTY_STRING(); } } /** * Parses a comment returning an intermediate array representation */ int phannot_internal_parse_annotations(zval **result, zval *comment, zval *file_path, zval *line, zval **error_msg TSRMLS_DC) { char *error; phannot_scanner_state *state; phannot_scanner_token token; int scanner_status, status = SUCCESS, start_lines, error_length; phannot_parser_status *parser_status = NULL; void* phannot_parser; zval processed_comment; /** * Check if the comment has content */ if (!Z_STRVAL_P(comment)) { ZVAL_BOOL(*result, 0); return FAILURE; } if (Z_STRLEN_P(comment) < 2) { ZVAL_BOOL(*result, 0); return SUCCESS; } /** * Remove comment separators */ phannot_remove_comment_separators(&processed_comment, Z_STRVAL_P(comment), Z_STRLEN_P(comment), &start_lines); if (Z_STRLEN(processed_comment) < 2) { ZVAL_BOOL(*result, 0); efree(Z_STRVAL(processed_comment)); return SUCCESS; } /** * Start the reentrant parser */ phannot_parser = phannot_Alloc(phannot_wrapper_alloc); parser_status = emalloc(sizeof(phannot_parser_status)); state = emalloc(sizeof(phannot_scanner_state)); parser_status->status = PHANNOT_PARSING_OK; parser_status->scanner_state = state; parser_status->ret = NULL; parser_status->token = &token; parser_status->syntax_error = NULL; /** * Initialize the scanner state */ state->active_token = 0; state->start = Z_STRVAL(processed_comment); state->start_length = 0; state->mode = PHANNOT_MODE_RAW; state->active_file = file_path; token.value = NULL; token.len = 0; /** * Possible start line */ if (Z_TYPE_P(line) == IS_LONG) { state->active_line = Z_LVAL_P(line) - start_lines; } else { state->active_line = 1; } state->end = state->start; while(0 <= (scanner_status = phannot_get_token(state, &token))) { state->active_token = token.opcode; state->start_length = (Z_STRVAL(processed_comment) + Z_STRLEN(processed_comment) - state->start); switch (token.opcode) { case PHANNOT_T_IGNORE: break; case PHANNOT_T_AT: phannot_(phannot_parser, PHANNOT_AT, NULL, parser_status); break; case PHANNOT_T_COMMA: phannot_(phannot_parser, PHANNOT_COMMA, NULL, parser_status); break; case PHANNOT_T_EQUALS: phannot_(phannot_parser, PHANNOT_EQUALS, NULL, parser_status); break; case PHANNOT_T_COLON: phannot_(phannot_parser, PHANNOT_COLON, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_OPEN: phannot_(phannot_parser, PHANNOT_PARENTHESES_OPEN, NULL, parser_status); break; case PHANNOT_T_PARENTHESES_CLOSE: phannot_(phannot_parser, PHANNOT_PARENTHESES_CLOSE, NULL, parser_status); break; case PHANNOT_T_BRACKET_OPEN: phannot_(phannot_parser, PHANNOT_BRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_BRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_BRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_SBRACKET_OPEN: phannot_(phannot_parser, PHANNOT_SBRACKET_OPEN, NULL, parser_status); break; case PHANNOT_T_SBRACKET_CLOSE: phannot_(phannot_parser, PHANNOT_SBRACKET_CLOSE, NULL, parser_status); break; case PHANNOT_T_NULL: phannot_(phannot_parser, PHANNOT_NULL, NULL, parser_status); break; case PHANNOT_T_TRUE: phannot_(phannot_parser, PHANNOT_TRUE, NULL, parser_status); break; case PHANNOT_T_FALSE: phannot_(phannot_parser, PHANNOT_FALSE, NULL, parser_status); break; case PHANNOT_T_INTEGER: phannot_parse_with_token(phannot_parser, PHANNOT_T_INTEGER, PHANNOT_INTEGER, &token, parser_status); break; case PHANNOT_T_DOUBLE: phannot_parse_with_token(phannot_parser, PHANNOT_T_DOUBLE, PHANNOT_DOUBLE, &token, parser_status); break; case PHANNOT_T_STRING: phannot_parse_with_token(phannot_parser, PHANNOT_T_STRING, PHANNOT_STRING, &token, parser_status); break; case PHANNOT_T_IDENTIFIER: phannot_parse_with_token(phannot_parser, PHANNOT_T_IDENTIFIER, PHANNOT_IDENTIFIER, &token, parser_status); break; /*case PHANNOT_T_ARBITRARY_TEXT: phannot_parse_with_token(phannot_parser, PHANNOT_T_ARBITRARY_TEXT, PHANNOT_ARBITRARY_TEXT, &token, parser_status); break;*/ default: parser_status->status = PHANNOT_PARSING_FAILED; if (!*error_msg) { error_length = sizeof(char) * (48 + Z_STRLEN_P(state->active_file)); error = emalloc(error_length); snprintf(error, error_length - 1, "Scanner: unknown opcode %d on in %s line %d", token.opcode, Z_STRVAL_P(state->active_file), state->active_line); error[error_length - 1] = '\0'; ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, error, 1); efree(error); } break; } if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; break; } state->end = state->start; } if (status != FAILURE) { switch (scanner_status) { case PHANNOT_SCANNER_RETCODE_ERR: case PHANNOT_SCANNER_RETCODE_IMPOSSIBLE: if (!*error_msg) { phannot_scanner_error_msg(parser_status, error_msg TSRMLS_CC); } status = FAILURE; break; default: phannot_(phannot_parser, 0, NULL, parser_status); } } state->active_token = 0; state->start = NULL; if (parser_status->status != PHANNOT_PARSING_OK) { status = FAILURE; if (parser_status->syntax_error) { if (!*error_msg) { ALLOC_INIT_ZVAL(*error_msg); ZVAL_STRING(*error_msg, parser_status->syntax_error, 1); } efree(parser_status->syntax_error); } } phannot_Free(phannot_parser, phannot_wrapper_free); if (status != FAILURE) { if (parser_status->status == PHANNOT_PARSING_OK) { if (parser_status->ret) { ZVAL_ZVAL(*result, parser_status->ret, 0, 0); ZVAL_NULL(parser_status->ret); zval_ptr_dtor(&parser_status->ret); } else { array_init(*result); } } } efree(Z_STRVAL(processed_comment)); efree(parser_status); efree(state); return status; }
{ "content_hash": "bdf9d67bce014fb50e1b4e2210e8a26f", "timestamp": "", "source": "github", "line_count": 1619, "max_line_length": 282, "avg_line_length": 30.570105003088326, "alnum_prop": 0.6098640211747116, "repo_name": "c9s/r3", "id": "29cb76ce42f762243e9606dd145bb1771bb8f1a7", "size": "49601", "binary": false, "copies": "6", "ref": "refs/heads/2.0", "path": "php/r3/annotation/parser.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "573755" }, { "name": "C++", "bytes": "7629" }, { "name": "CMake", "bytes": "8070" }, { "name": "HTML", "bytes": "11611" }, { "name": "M4", "bytes": "5127" }, { "name": "Makefile", "bytes": "3288" }, { "name": "Ruby", "bytes": "1793" }, { "name": "Shell", "bytes": "1885" } ], "symlink_target": "" }
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "LinearTrend", cycle_length = 5, transform = "Difference", sigma = 0.0, exog_count = 20, ar_order = 0);
{ "content_hash": "bad25ae196614095b77a61a7e6fc9ac2", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 166, "avg_line_length": 38, "alnum_prop": 0.706766917293233, "repo_name": "antoinecarme/pyaf", "id": "6c14f5d549fd313673db39e6bf5b8c1e5fd135a2", "size": "266", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/artificial/transf_Difference/trend_LinearTrend/cycle_5/ar_/test_artificial_32_Difference_LinearTrend_5__20.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "6773299" }, { "name": "Procfile", "bytes": "24" }, { "name": "Python", "bytes": "54209093" }, { "name": "R", "bytes": "807" }, { "name": "Shell", "bytes": "3619" } ], "symlink_target": "" }
Developer Notes =============== <!-- markdown-toc start --> **Table of Contents** - [Developer Notes](#developer-notes) - [Coding Style (General)](#coding-style-general) - [Coding Style (C++)](#coding-style-c) - [Coding Style (Python)](#coding-style-python) - [Coding Style (Doxygen-compatible comments)](#coding-style-doxygen-compatible-comments) - [Development tips and tricks](#development-tips-and-tricks) - [Compiling for debugging](#compiling-for-debugging) - [Compiling for gprof profiling](#compiling-for-gprof-profiling) - [debug.log](#debuglog) - [Testnet and Regtest modes](#testnet-and-regtest-modes) - [DEBUG_LOCKORDER](#debug_lockorder) - [Valgrind suppressions file](#valgrind-suppressions-file) - [Compiling for test coverage](#compiling-for-test-coverage) - [Performance profiling with perf](#performance-profiling-with-perf) - [Locking/mutex usage notes](#lockingmutex-usage-notes) - [Threads](#threads) - [Ignoring IDE/editor files](#ignoring-ideeditor-files) - [Development guidelines](#development-guidelines) - [General Bitcoin Core](#general-bitcoin-core) - [Wallet](#wallet) - [General C++](#general-c) - [C++ data structures](#c-data-structures) - [Strings and formatting](#strings-and-formatting) - [Variable names](#variable-names) - [Threads and synchronization](#threads-and-synchronization) - [Scripts](#scripts) - [Shebang](#shebang) - [Source code organization](#source-code-organization) - [GUI](#gui) - [Subtrees](#subtrees) - [Git and GitHub tips](#git-and-github-tips) - [Scripted diffs](#scripted-diffs) - [Release notes](#release-notes) - [RPC interface guidelines](#rpc-interface-guidelines) <!-- markdown-toc end --> Coding Style (General) ---------------------- Various coding styles have been used during the history of the codebase, and the result is not very consistent. However, we're now trying to converge to a single style, which is specified below. When writing patches, favor the new style over attempting to mimic the surrounding style, except for move-only commits. Do not submit patches solely to modify the style of existing code. Coding Style (C++) ------------------ - **Indentation and whitespace rules** as specified in [src/.clang-format](/src/.clang-format). You can use the provided [clang-format-diff script](/contrib/devtools/README.md#clang-format-diffpy) tool to clean up patches automatically before submission. - Braces on new lines for classes, functions, methods. - Braces on the same line for everything else. - 4 space indentation (no tabs) for every block except namespaces. - No indentation for `public`/`protected`/`private` or for `namespace`. - No extra spaces inside parenthesis; don't do ( this ) - No space after function names; one space after `if`, `for` and `while`. - If an `if` only has a single-statement `then`-clause, it can appear on the same line as the `if`, without braces. In every other case, braces are required, and the `then` and `else` clauses must appear correctly indented on a new line. - **Symbol naming conventions**. These are preferred in new code, but are not required when doing so would need changes to significant pieces of existing code. - Variable (including function arguments) and namespace names are all lowercase, and may use `_` to separate words (snake_case). - Class member variables have a `m_` prefix. - Global variables have a `g_` prefix. - Constant names are all uppercase, and use `_` to separate words. - Class names, function names and method names are UpperCamelCase (PascalCase). Do not prefix class names with `C`. - Test suite naming convention: The Boost test suite in file `src/test/foo_tests.cpp` should be named `foo_tests`. Test suite names must be unique. - **Miscellaneous** - `++i` is preferred over `i++`. - `nullptr` is preferred over `NULL` or `(void*)0`. - `static_assert` is preferred over `assert` where possible. Generally; compile-time checking is preferred over run-time checking. - `enum class` is preferred over `enum` where possible. Scoped enumerations avoid two potential pitfalls/problems with traditional C++ enumerations: implicit conversions to int, and name clashes due to enumerators being exported to the surrounding scope. Block style example: ```c++ int g_count = 0; namespace foo { class Class { std::string m_name; public: bool Function(const std::string& s, int n) { // Comment summarising what this section of code does for (int i = 0; i < n; ++i) { int total_sum = 0; // When something fails, return early if (!Something()) return false; ... if (SomethingElse(i)) { total_sum += ComputeSomething(g_count); } else { DoSomething(m_name, total_sum); } } // Success return is usually at the end return true; } } } // namespace foo ``` Coding Style (Python) --------------------- Refer to [/test/functional/README.md#style-guidelines](/test/functional/README.md#style-guidelines). Coding Style (Doxygen-compatible comments) ------------------------------------------ Bitcoin Core uses [Doxygen](http://www.doxygen.nl/) to generate its official documentation. Use Doxygen-compatible comment blocks for functions, methods, and fields. For example, to describe a function use: ```c++ /** * ... text ... * @param[in] arg1 A description * @param[in] arg2 Another argument description * @pre Precondition for function... */ bool function(int arg1, const char *arg2) ``` A complete list of `@xxx` commands can be found at http://www.stack.nl/~dimitri/doxygen/manual/commands.html. As Doxygen recognizes the comments by the delimiters (`/**` and `*/` in this case), you don't *need* to provide any commands for a comment to be valid; just a description text is fine. To describe a class use the same construct above the class definition: ```c++ /** * Alerts are for notifying old versions if they become too obsolete and * need to upgrade. The message is displayed in the status bar. * @see GetWarnings() */ class CAlert { ``` To describe a member or variable use: ```c++ int var; //!< Detailed description after the member ``` or ```c++ //! Description before the member int var; ``` Also OK: ```c++ /// /// ... text ... /// bool function2(int arg1, const char *arg2) ``` Not OK (used plenty in the current source, but not picked up): ```c++ // // ... text ... // ``` A full list of comment syntaxes picked up by Doxygen can be found at https://www.stack.nl/~dimitri/doxygen/manual/docblocks.html, but the above styles are favored. Documentation can be generated with `make docs` and cleaned up with `make clean-docs`. The resulting files are located in `doc/doxygen/html`; open `index.html` to view the homepage. Before running `make docs`, you will need to install dependencies `doxygen` and `dot`. For example, on MacOS via Homebrew: ``` brew install doxygen --with-graphviz ``` Development tips and tricks --------------------------- ### Compiling for debugging Run configure with `--enable-debug` to add additional compiler flags that produce better debugging builds. ### Compiling for gprof profiling Run configure with the `--enable-gprof` option, then make. ### debug.log If the code is behaving strangely, take a look in the debug.log file in the data directory; error and debugging messages are written there. The `-debug=...` command-line option controls debugging; running with just `-debug` or `-debug=1` will turn on all categories (and give you a very large debug.log file). The Qt code routes `qDebug()` output to debug.log under category "qt": run with `-debug=qt` to see it. ### Testnet and Regtest modes Run with the `-testnet` option to run with "play bitcoins" on the test network, if you are testing multi-machine code that needs to operate across the internet. If you are testing something that can run on one machine, run with the `-regtest` option. In regression test mode, blocks can be created on-demand; see [test/functional/](/test/functional) for tests that run in `-regtest` mode. ### DEBUG_LOCKORDER Bitcoin Core is a multi-threaded application, and deadlocks or other multi-threading bugs can be very difficult to track down. The `--enable-debug` configure option adds `-DDEBUG_LOCKORDER` to the compiler flags. This inserts run-time checks to keep track of which locks are held, and adds warnings to the debug.log file if inconsistencies are detected. ### Valgrind suppressions file Valgrind is a programming tool for memory debugging, memory leak detection, and profiling. The repo contains a Valgrind suppressions file ([`valgrind.supp`](https://github.com/bitcoin/bitcoin/blob/master/contrib/valgrind.supp)) which includes known Valgrind warnings in our dependencies that cannot be fixed in-tree. Example use: ```shell $ valgrind --suppressions=contrib/valgrind.supp src/test/test_bitcoin $ valgrind --suppressions=contrib/valgrind.supp --leak-check=full \ --show-leak-kinds=all src/test/test_bitcoin --log_level=test_suite $ valgrind -v --leak-check=full src/bitcoind -printtoconsole ``` ### Compiling for test coverage LCOV can be used to generate a test coverage report based upon `make check` execution. LCOV must be installed on your system (e.g. the `lcov` package on Debian/Ubuntu). To enable LCOV report generation during test runs: ```shell ./configure --enable-lcov make make cov # A coverage report will now be accessible at `./test_bitcoin.coverage/index.html`. ``` ### Performance profiling with perf Profiling is a good way to get a precise idea of where time is being spent in code. One tool for doing profiling on Linux platforms is called [`perf`](http://www.brendangregg.com/perf.html), and has been integrated into the functional test framework. Perf can observe a running process and sample (at some frequency) where its execution is. Perf installation is contingent on which kernel version you're running; see [this StackExchange thread](https://askubuntu.com/questions/50145/how-to-install-perf-monitoring-tool) for specific instructions. Certain kernel parameters may need to be set for perf to be able to inspect the running process' stack. ```sh $ sudo sysctl -w kernel.perf_event_paranoid=-1 $ sudo sysctl -w kernel.kptr_restrict=0 ``` Make sure you [understand the security trade-offs](https://lwn.net/Articles/420403/) of setting these kernel parameters. To profile a running bitcoind process for 60 seconds, you could use an invocation of `perf record` like this: ```sh $ perf record \ -g --call-graph dwarf --per-thread -F 140 \ -p `pgrep bitcoind` -- sleep 60 ``` You could then analyze the results by running ```sh perf report --stdio | c++filt | less ``` or using a graphical tool like [Hotspot](https://github.com/KDAB/hotspot). See the functional test documentation for how to invoke perf within tests. **Sanitizers** Bitcoin Core can be compiled with various "sanitizers" enabled, which add instrumentation for issues regarding things like memory safety, thread race conditions, or undefined behavior. This is controlled with the `--with-sanitizers` configure flag, which should be a comma separated list of sanitizers to enable. The sanitizer list should correspond to supported `-fsanitize=` options in your compiler. These sanitizers have runtime overhead, so they are most useful when testing changes or producing debugging builds. Some examples: ```bash # Enable both the address sanitizer and the undefined behavior sanitizer ./configure --with-sanitizers=address,undefined # Enable the thread sanitizer ./configure --with-sanitizers=thread ``` If you are compiling with GCC you will typically need to install corresponding "san" libraries to actually compile with these flags, e.g. libasan for the address sanitizer, libtsan for the thread sanitizer, and libubsan for the undefined sanitizer. If you are missing required libraries, the configure script will fail with a linker error when testing the sanitizer flags. The test suite should pass cleanly with the `thread` and `undefined` sanitizers, but there are a number of known problems when using the `address` sanitizer. The address sanitizer is known to fail in [sha256_sse4::Transform](/src/crypto/sha256_sse4.cpp) which makes it unusable unless you also use `--disable-asm` when running configure. We would like to fix sanitizer issues, so please send pull requests if you can fix any errors found by the address sanitizer (or any other sanitizer). Not all sanitizer options can be enabled at the same time, e.g. trying to build with `--with-sanitizers=address,thread` will fail in the configure script as these sanitizers are mutually incompatible. Refer to your compiler manual to learn more about these options and which sanitizers are supported by your compiler. Additional resources: * [AddressSanitizer](https://clang.llvm.org/docs/AddressSanitizer.html) * [LeakSanitizer](https://clang.llvm.org/docs/LeakSanitizer.html) * [MemorySanitizer](https://clang.llvm.org/docs/MemorySanitizer.html) * [ThreadSanitizer](https://clang.llvm.org/docs/ThreadSanitizer.html) * [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) * [GCC Instrumentation Options](https://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html) * [Google Sanitizers Wiki](https://github.com/google/sanitizers/wiki) * [Issue #12691: Enable -fsanitize flags in Travis](https://github.com/bitcoin/bitcoin/issues/12691) Locking/mutex usage notes ------------------------- The code is multi-threaded, and uses mutexes and the `LOCK` and `TRY_LOCK` macros to protect data structures. Deadlocks due to inconsistent lock ordering (thread 1 locks `cs_main` and then `cs_wallet`, while thread 2 locks them in the opposite order: result, deadlock as each waits for the other to release its lock) are a problem. Compile with `-DDEBUG_LOCKORDER` (or use `--enable-debug`) to get lock order inconsistencies reported in the debug.log file. Re-architecting the core code so there are better-defined interfaces between the various components is a goal, with any necessary locking done by the components (e.g. see the self-contained `CBasicKeyStore` class and its `cs_KeyStore` lock for example). Threads ------- - ThreadScriptCheck : Verifies block scripts. - ThreadImport : Loads blocks from blk*.dat files or bootstrap.dat. - StartNode : Starts other threads. - ThreadDNSAddressSeed : Loads addresses of peers from the DNS. - ThreadMapPort : Universal plug-and-play startup/shutdown - ThreadSocketHandler : Sends/Receives data from peers on port 8333. - ThreadOpenAddedConnections : Opens network connections to added nodes. - ThreadOpenConnections : Initiates new connections to peers. - ThreadMessageHandler : Higher-level message handling (sending and receiving). - DumpAddresses : Dumps IP addresses of nodes to peers.dat. - ThreadRPCServer : Remote procedure call handler, listens on port 8332 for connections and services them. - Shutdown : Does an orderly shutdown of everything. Ignoring IDE/editor files -------------------------- In closed-source environments in which everyone uses the same IDE it is common to add temporary files it produces to the project-wide `.gitignore` file. However, in open source software such as Bitcoin Core, where everyone uses their own editors/IDE/tools, it is less common. Only you know what files your editor produces and this may change from version to version. The canonical way to do this is thus to create your local gitignore. Add this to `~/.gitconfig`: ``` [core] excludesfile = /home/.../.gitignore_global ``` (alternatively, type the command `git config --global core.excludesfile ~/.gitignore_global` on a terminal) Then put your favourite tool's temporary filenames in that file, e.g. ``` # NetBeans nbproject/ ``` Another option is to create a per-repository excludes file `.git/info/exclude`. These are not committed but apply only to one repository. If a set of tools is used by the build system or scripts the repository (for example, lcov) it is perfectly acceptable to add its files to `.gitignore` and commit them. Development guidelines ============================ A few non-style-related recommendations for developers, as well as points to pay attention to for reviewers of Bitcoin Core code. General Bitcoin Core ---------------------- - New features should be exposed on RPC first, then can be made available in the GUI - *Rationale*: RPC allows for better automatic testing. The test suite for the GUI is very limited - Make sure pull requests pass Travis CI before merging - *Rationale*: Makes sure that they pass thorough testing, and that the tester will keep passing on the master branch. Otherwise all new pull requests will start failing the tests, resulting in confusion and mayhem - *Explanation*: If the test suite is to be updated for a change, this has to be done first Wallet ------- - Make sure that no crashes happen with run-time option `-disablewallet`. - *Rationale*: In RPC code that conditionally uses the wallet (such as `validateaddress`) it is easy to forget that global pointer `pwalletMain` can be nullptr. See `test/functional/disablewallet.py` for functional tests exercising the API with `-disablewallet` - Include `db_cxx.h` (BerkeleyDB header) only when `ENABLE_WALLET` is set - *Rationale*: Otherwise compilation of the disable-wallet build will fail in environments without BerkeleyDB General C++ ------------- - Assertions should not have side-effects - *Rationale*: Even though the source code is set to refuse to compile with assertions disabled, having side-effects in assertions is unexpected and makes the code harder to understand - If you use the `.h`, you must link the `.cpp` - *Rationale*: Include files define the interface for the code in implementation files. Including one but not linking the other is confusing. Please avoid that. Moving functions from the `.h` to the `.cpp` should not result in build errors - Use the RAII (Resource Acquisition Is Initialization) paradigm where possible. For example by using `unique_ptr` for allocations in a function. - *Rationale*: This avoids memory and resource leaks, and ensures exception safety - Use `MakeUnique()` to construct objects owned by `unique_ptr`s - *Rationale*: `MakeUnique` is concise and ensures exception safety in complex expressions. `MakeUnique` is a temporary project local implementation of `std::make_unique` (C++14). C++ data structures -------------------- - Never use the `std::map []` syntax when reading from a map, but instead use `.find()` - *Rationale*: `[]` does an insert (of the default element) if the item doesn't exist in the map yet. This has resulted in memory leaks in the past, as well as race conditions (expecting read-read behavior). Using `[]` is fine for *writing* to a map - Do not compare an iterator from one data structure with an iterator of another data structure (even if of the same type) - *Rationale*: Behavior is undefined. In C++ parlor this means "may reformat the universe", in practice this has resulted in at least one hard-to-debug crash bug - Watch out for out-of-bounds vector access. `&vch[vch.size()]` is illegal, including `&vch[0]` for an empty vector. Use `vch.data()` and `vch.data() + vch.size()` instead. - Vector bounds checking is only enabled in debug mode. Do not rely on it - Initialize all non-static class members where they are defined. If this is skipped for a good reason (i.e., optimization on the critical path), add an explicit comment about this - *Rationale*: Ensure determinism by avoiding accidental use of uninitialized values. Also, static analyzers balk about this. Initializing the members in the declaration makes it easy to spot uninitialized ones. ```cpp class A { uint32_t m_count{0}; } ``` - By default, declare single-argument constructors `explicit`. - *Rationale*: This is a precaution to avoid unintended conversions that might arise when single-argument constructors are used as implicit conversion functions. - Use explicitly signed or unsigned `char`s, or even better `uint8_t` and `int8_t`. Do not use bare `char` unless it is to pass to a third-party API. This type can be signed or unsigned depending on the architecture, which can lead to interoperability problems or dangerous conditions such as out-of-bounds array accesses - Prefer explicit constructions over implicit ones that rely on 'magical' C++ behavior - *Rationale*: Easier to understand what is happening, thus easier to spot mistakes, even for those that are not language lawyers Strings and formatting ------------------------ - Be careful of `LogPrint` versus `LogPrintf`. `LogPrint` takes a `category` argument, `LogPrintf` does not. - *Rationale*: Confusion of these can result in runtime exceptions due to formatting mismatch, and it is easy to get wrong because of subtly similar naming - Use `std::string`, avoid C string manipulation functions - *Rationale*: C++ string handling is marginally safer, less scope for buffer overflows and surprises with `\0` characters. Also some C string manipulations tend to act differently depending on platform, or even the user locale - Use `ParseInt32`, `ParseInt64`, `ParseUInt32`, `ParseUInt64`, `ParseDouble` from `utilstrencodings.h` for number parsing - *Rationale*: These functions do overflow checking, and avoid pesky locale issues. - Avoid using locale dependent functions if possible. You can use the provided [`lint-locale-dependence.sh`](/test/lint/lint-locale-dependence.sh) to check for accidental use of locale dependent functions. - *Rationale*: Unnecessary locale dependence can cause bugs that are very tricky to isolate and fix. - These functions are known to be locale dependent: `alphasort`, `asctime`, `asprintf`, `atof`, `atoi`, `atol`, `atoll`, `atoq`, `btowc`, `ctime`, `dprintf`, `fgetwc`, `fgetws`, `fprintf`, `fputwc`, `fputws`, `fscanf`, `fwprintf`, `getdate`, `getwc`, `getwchar`, `isalnum`, `isalpha`, `isblank`, `iscntrl`, `isdigit`, `isgraph`, `islower`, `isprint`, `ispunct`, `isspace`, `isupper`, `iswalnum`, `iswalpha`, `iswblank`, `iswcntrl`, `iswctype`, `iswdigit`, `iswgraph`, `iswlower`, `iswprint`, `iswpunct`, `iswspace`, `iswupper`, `iswxdigit`, `isxdigit`, `mblen`, `mbrlen`, `mbrtowc`, `mbsinit`, `mbsnrtowcs`, `mbsrtowcs`, `mbstowcs`, `mbtowc`, `mktime`, `putwc`, `putwchar`, `scanf`, `snprintf`, `sprintf`, `sscanf`, `stoi`, `stol`, `stoll`, `strcasecmp`, `strcasestr`, `strcoll`, `strfmon`, `strftime`, `strncasecmp`, `strptime`, `strtod`, `strtof`, `strtoimax`, `strtol`, `strtold`, `strtoll`, `strtoq`, `strtoul`, `strtoull`, `strtoumax`, `strtouq`, `strxfrm`, `swprintf`, `tolower`, `toupper`, `towctrans`, `towlower`, `towupper`, `ungetwc`, `vasprintf`, `vdprintf`, `versionsort`, `vfprintf`, `vfscanf`, `vfwprintf`, `vprintf`, `vscanf`, `vsnprintf`, `vsprintf`, `vsscanf`, `vswprintf`, `vwprintf`, `wcrtomb`, `wcscasecmp`, `wcscoll`, `wcsftime`, `wcsncasecmp`, `wcsnrtombs`, `wcsrtombs`, `wcstod`, `wcstof`, `wcstoimax`, `wcstol`, `wcstold`, `wcstoll`, `wcstombs`, `wcstoul`, `wcstoull`, `wcstoumax`, `wcswidth`, `wcsxfrm`, `wctob`, `wctomb`, `wctrans`, `wctype`, `wcwidth`, `wprintf` - For `strprintf`, `LogPrint`, `LogPrintf` formatting characters don't need size specifiers - *Rationale*: Bitcoin Core uses tinyformat, which is type safe. Leave them out to avoid confusion Variable names -------------- Although the shadowing warning (`-Wshadow`) is not enabled by default (it prevents issues rising from using a different variable with the same name), please name variables so that their names do not shadow variables defined in the source code. E.g. in member initializers, prepend `_` to the argument name shadowing the member name: ```c++ class AddressBookPage { Mode m_mode; } AddressBookPage::AddressBookPage(Mode _mode) : m_mode(_mode) ... ``` When using nested cycles, do not name the inner cycle variable the same as in upper cycle etc. Threads and synchronization ---------------------------- - Build and run tests with `-DDEBUG_LOCKORDER` to verify that no potential deadlocks are introduced. As of 0.12, this is defined by default when configuring with `--enable-debug` - When using `LOCK`/`TRY_LOCK` be aware that the lock exists in the context of the current scope, so surround the statement and the code that needs the lock with braces OK: ```c++ { TRY_LOCK(cs_vNodes, lockNodes); ... } ``` Wrong: ```c++ TRY_LOCK(cs_vNodes, lockNodes); { ... } ``` Scripts -------------------------- ### Shebang - Use `#!/usr/bin/env bash` instead of obsolete `#!/bin/bash`. - [*Rationale*](https://github.com/dylanaraps/pure-bash-bible#shebang): `#!/bin/bash` assumes it is always installed to /bin/ which can cause issues; `#!/usr/bin/env bash` searches the user's PATH to find the bash binary. OK: ```bash #!/usr/bin/env bash ``` Wrong: ```bash #!/bin/bash ``` Source code organization -------------------------- - Implementation code should go into the `.cpp` file and not the `.h`, unless necessary due to template usage or when performance due to inlining is critical - *Rationale*: Shorter and simpler header files are easier to read, and reduce compile time - Use only the lowercase alphanumerics (`a-z0-9`), underscore (`_`) and hyphen (`-`) in source code filenames. - *Rationale*: `grep`:ing and auto-completing filenames is easier when using a consistent naming pattern. Potential problems when building on case-insensitive filesystems are avoided when using only lowercase characters in source code filenames. - Every `.cpp` and `.h` file should `#include` every header file it directly uses classes, functions or other definitions from, even if those headers are already included indirectly through other headers. - *Rationale*: Excluding headers because they are already indirectly included results in compilation failures when those indirect dependencies change. Furthermore, it obscures what the real code dependencies are. - Don't import anything into the global namespace (`using namespace ...`). Use fully specified types such as `std::string`. - *Rationale*: Avoids symbol conflicts - Terminate namespaces with a comment (`// namespace mynamespace`). The comment should be placed on the same line as the brace closing the namespace, e.g. ```c++ namespace mynamespace { ... } // namespace mynamespace namespace { ... } // namespace ``` - *Rationale*: Avoids confusion about the namespace context - Use `#include <primitives/transaction.h>` bracket syntax instead of `#include "primitives/transactions.h"` quote syntax. - *Rationale*: Bracket syntax is less ambiguous because the preprocessor searches a fixed list of include directories without taking location of the source file into account. This allows quoted includes to stand out more when the location of the source file actually is relevant. - Use include guards to avoid the problem of double inclusion. The header file `foo/bar.h` should use the include guard identifier `BITCOIN_FOO_BAR_H`, e.g. ```c++ #ifndef BITCOIN_FOO_BAR_H #define BITCOIN_FOO_BAR_H ... #endif // BITCOIN_FOO_BAR_H ``` GUI ----- - Do not display or manipulate dialogs in model code (classes `*Model`) - *Rationale*: Model classes pass through events and data from the core, they should not interact with the user. That's where View classes come in. The converse also holds: try to not directly access core data structures from Views. - Avoid adding slow or blocking code in the GUI thread. In particular do not add new `interfaces::Node` and `interfaces::Wallet` method calls, even if they may be fast now, in case they are changed to lock or communicate across processes in the future. Prefer to offload work from the GUI thread to worker threads (see `RPCExecutor` in console code as an example) or take other steps (see https://doc.qt.io/archives/qq/qq27-responsive-guis.html) to keep the GUI responsive. - *Rationale*: Blocking the GUI thread can increase latency, and lead to hangs and deadlocks. Subtrees ---------- Several parts of the repository are subtrees of software maintained elsewhere. Some of these are maintained by active developers of Bitcoin Core, in which case changes should probably go directly upstream without being PRed directly against the project. They will be merged back in the next subtree merge. Others are external projects without a tight relationship with our project. Changes to these should also be sent upstream but bugfixes may also be prudent to PR against Bitcoin Core so that they can be integrated quickly. Cosmetic changes should be purely taken upstream. There is a tool in `test/lint/git-subtree-check.sh` to check a subtree directory for consistency with its upstream repository. Current subtrees include: - src/leveldb - Upstream at https://github.com/google/leveldb ; Maintained by Google, but open important PRs to Core to avoid delay. - **Note**: Follow the instructions in [Upgrading LevelDB](#upgrading-leveldb) when merging upstream changes to the LevelDB subtree. - src/libsecp256k1 - Upstream at https://github.com/bitcoin-core/secp256k1/ ; actively maintained by Core contributors. - src/crypto/ctaes - Upstream at https://github.com/bitcoin-core/ctaes ; actively maintained by Core contributors. - src/univalue - Upstream at https://github.com/bitcoin-core/univalue ; actively maintained by Core contributors, deviates from upstream https://github.com/jgarzik/univalue Upgrading LevelDB --------------------- Extra care must be taken when upgrading LevelDB. This section explains issues you must be aware of. ### File Descriptor Counts In most configurations we use the default LevelDB value for `max_open_files`, which is 1000 at the time of this writing. If LevelDB actually uses this many file descriptors it will cause problems with Bitcoin's `select()` loop, because it may cause new sockets to be created where the fd value is >= 1024. For this reason, on 64-bit Unix systems we rely on an internal LevelDB optimization that uses `mmap()` + `close()` to open table files without actually retaining references to the table file descriptors. If you are upgrading LevelDB, you must sanity check the changes to make sure that this assumption remains valid. In addition to reviewing the upstream changes in `env_posix.cc`, you can use `lsof` to check this. For example, on Linux this command will show open `.ldb` file counts: ```bash $ lsof -p $(pidof bitcoind) |\ awk 'BEGIN { fd=0; mem=0; } /ldb$/ { if ($4 == "mem") mem++; else fd++ } END { printf "mem = %s, fd = %s\n", mem, fd}' mem = 119, fd = 0 ``` The `mem` value shows how many files are mmap'ed, and the `fd` value shows you many file descriptors these files are using. You should check that `fd` is a small number (usually 0 on 64-bit hosts). See the notes in the `SetMaxOpenFiles()` function in `dbwrapper.cc` for more details. ### Consensus Compatibility It is possible for LevelDB changes to inadvertently change consensus compatibility between nodes. This happened in Bitcoin 0.8 (when LevelDB was first introduced). When upgrading LevelDB you should review the upstream changes to check for issues affecting consensus compatibility. For example, if LevelDB had a bug that accidentally prevented a key from being returned in an edge case, and that bug was fixed upstream, the bug "fix" would be an incompatible consensus change. In this situation the correct behavior would be to revert the upstream fix before applying the updates to Bitcoin's copy of LevelDB. In general you should be wary of any upstream changes affecting what data is returned from LevelDB queries. Scripted diffs -------------- For reformatting and refactoring commits where the changes can be easily automated using a bash script, we use scripted-diff commits. The bash script is included in the commit message and our Travis CI job checks that the result of the script is identical to the commit. This aids reviewers since they can verify that the script does exactly what it's supposed to do. It is also helpful for rebasing (since the same script can just be re-run on the new master commit). To create a scripted-diff: - start the commit message with `scripted-diff:` (and then a description of the diff on the same line) - in the commit message include the bash script between lines containing just the following text: - `-BEGIN VERIFY SCRIPT-` - `-END VERIFY SCRIPT-` The scripted-diff is verified by the tool `test/lint/commit-script-check.sh`. The tool's default behavior when supplied with a commit is to verify all scripted-diffs from the beginning of time up to said commit. Internally, the tool passes the first supplied argument to `git rev-list --reverse` to determine which commits to verify script-diffs for, ignoring commits that don't conform to the commit message format described above. For development, it might be more convenient to verify all scripted-diffs in a range `A..B`, for example: ```bash test/lint/commit-script-check.sh origin/master..HEAD ``` Commit [`bb81e173`](https://github.com/bitcoin/bitcoin/commit/bb81e173) is an example of a scripted-diff. Release notes ------------- Release notes should be written for any PR that: - introduces a notable new feature - fixes a significant bug - changes an API or configuration model - makes any other visible change to the end-user experience. Release notes should be added to a PR-specific release note file at `/doc/release-notes-<PR number>.md` to avoid conflicts between multiple PRs. All `release-notes*` files are merged into a single [/doc/release-notes.md](/doc/release-notes.md) file prior to the release. RPC interface guidelines -------------------------- A few guidelines for introducing and reviewing new RPC interfaces: - Method naming: use consecutive lower-case names such as `getrawtransaction` and `submitblock` - *Rationale*: Consistency with existing interface. - Argument naming: use snake case `fee_delta` (and not, e.g. camel case `feeDelta`) - *Rationale*: Consistency with existing interface. - Use the JSON parser for parsing, don't manually parse integers or strings from arguments unless absolutely necessary. - *Rationale*: Introduces hand-rolled string manipulation code at both the caller and callee sites, which is error prone, and it is easy to get things such as escaping wrong. JSON already supports nested data structures, no need to re-invent the wheel. - *Exception*: AmountFromValue can parse amounts as string. This was introduced because many JSON parsers and formatters hard-code handling decimal numbers as floating point values, resulting in potential loss of precision. This is unacceptable for monetary values. **Always** use `AmountFromValue` and `ValueFromAmount` when inputting or outputting monetary values. The only exceptions to this are `prioritisetransaction` and `getblocktemplate` because their interface is specified as-is in BIP22. - Missing arguments and 'null' should be treated the same: as default values. If there is no default value, both cases should fail in the same way. The easiest way to follow this guideline is detect unspecified arguments with `params[x].isNull()` instead of `params.size() <= x`. The former returns true if the argument is either null or missing, while the latter returns true if is missing, and false if it is null. - *Rationale*: Avoids surprises when switching to name-based arguments. Missing name-based arguments are passed as 'null'. - Try not to overload methods on argument type. E.g. don't make `getblock(true)` and `getblock("hash")` do different things. - *Rationale*: This is impossible to use with `bitcoin-cli`, and can be surprising to users. - *Exception*: Some RPC calls can take both an `int` and `bool`, most notably when a bool was switched to a multi-value, or due to other historical reasons. **Always** have false map to 0 and true to 1 in this case. - Don't forget to fill in the argument names correctly in the RPC command table. - *Rationale*: If not, the call can not be used with name-based arguments. - Set okSafeMode in the RPC command table to a sensible value: safe mode is when the blockchain is regarded to be in a confused state, and the client deems it unsafe to do anything irreversible such as send. Anything that just queries should be permitted. - *Rationale*: Troubleshooting a node in safe mode is difficult if half the RPCs don't work. - Add every non-string RPC argument `(method, idx, name)` to the table `vRPCConvertParams` in `rpc/client.cpp`. - *Rationale*: `bitcoin-cli` and the GUI debug console use this table to determine how to convert a plaintext command line to JSON. If the types don't match, the method can be unusable from there. - A RPC method must either be a wallet method or a non-wallet method. Do not introduce new methods such as `signrawtransaction` that differ in behavior based on presence of a wallet. - *Rationale*: as well as complicating the implementation and interfering with the introduction of multi-wallet, wallet and non-wallet code should be separated to avoid introducing circular dependencies between code units. - Try to make the RPC response a JSON object. - *Rationale*: If a RPC response is not a JSON object then it is harder to avoid API breakage if new data in the response is needed. - Wallet RPCs call BlockUntilSyncedToCurrentChain to maintain consistency with `getblockchaininfo`'s state immediately prior to the call's execution. Wallet RPCs whose behavior does *not* depend on the current chainstate may omit this call. - *Rationale*: In previous versions of Bitcoin Core, the wallet was always in-sync with the chainstate (by virtue of them all being updated in the same cs_main lock). In order to maintain the behavior that wallet RPCs return results as of at least the highest best-known block an RPC client may be aware of prior to entering a wallet RPC call, we must block until the wallet is caught up to the chainstate as of the RPC call's entry. This also makes the API much easier for RPC clients to reason about. - Be aware of RPC method aliases and generally avoid registering the same callback function pointer for different RPCs. - *Rationale*: RPC methods registered with the same function pointer will be considered aliases and only the first method name will show up in the `help` rpc command list. - *Exception*: Using RPC method aliases may be appropriate in cases where a new RPC is replacing a deprecated RPC, to avoid both RPCs confusingly showing up in the command list.
{ "content_hash": "503162dde0f81402b93f482c030e7d4d", "timestamp": "", "source": "github", "line_count": 989, "max_line_length": 256, "avg_line_length": 39.841253791708795, "alnum_prop": 0.732203131741238, "repo_name": "myriadcoin/myriadcoin", "id": "f765346cd8560f7e230e1e0969a07474bd6df2ae", "size": "39403", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/developer-notes.md", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "1590918" }, { "name": "C++", "bytes": "6467954" }, { "name": "HTML", "bytes": "21860" }, { "name": "Java", "bytes": "30290" }, { "name": "M4", "bytes": "201405" }, { "name": "Makefile", "bytes": "121719" }, { "name": "Objective-C", "bytes": "6345" }, { "name": "Objective-C++", "bytes": "5378" }, { "name": "Python", "bytes": "1611450" }, { "name": "QMake", "bytes": "756" }, { "name": "Shell", "bytes": "92134" } ], "symlink_target": "" }
using Newtonsoft.Json.Linq; namespace Xamarin.Ide.Telemetry.Data.Readers { public interface IContextReader { JObject ReadContextProperties (); JObject ReadEventProperties (); } }
{ "content_hash": "ce96c3479d8a4f83d8c22fa5d77a6eb9", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 44, "avg_line_length": 17.181818181818183, "alnum_prop": 0.7671957671957672, "repo_name": "MobileEssentials/Telemetry", "id": "a6104f0023250e7e5c9cd87aa98a0695af401732", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/InstrumentedApp/Data/Readers/IContextReader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "36099" } ], "symlink_target": "" }
import logging from classymq import exchanges, queues from classymq.lib.uuid import UUIDRequest log = logging.getLogger(__name__) class AMQPAPIRequest(UUIDRequest): def __init__(self, uuid=None, message=None, *args, **kwargs): super(AMQPAPIRequest, self).__init__(uuid, *args, **kwargs) self.message = message def __str__(self): d = {} for k, v in self.items(): sv = str(v) if len(sv) > 500: sv = sv[:500] + '...' d[k] = sv return str(d) class AMQPAPIExchange(exchanges.BaseExchange): KEY = "amqpapi" # TYPE = exchanges.EXCHANGE_TYPES.TOPIC class AMQPAPIQueue(queues.BaseQueue): KEY = "amqpapi-%(prefix)s-%(uuid)s" AUTO_DELETE = True
{ "content_hash": "18158099d682f7f30283fafe629e805d", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 67, "avg_line_length": 26.964285714285715, "alnum_prop": 0.5933774834437087, "repo_name": "gdoermann/classymq", "id": "ae98c9fbd13bc05efa8ad8c1a8b7f18aa8951566", "size": "755", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "classymq/api/common.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "6986" }, { "name": "Python", "bytes": "68656" }, { "name": "Shell", "bytes": "6463" } ], "symlink_target": "" }
layout: post title: Deployment Properties categories: XAP97 parent: the-processing-unit-structure-and-configuration.html weight: 400 --- {% summary %}The processing unit can be injected with dynamic property values at deployment time. The mechanism leverages Spring's [`PropertyPlaceholderConfigurer`](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer) to provide powerful and simple properties-based injection.{% endsummary %} # Overview When a processing unit is deployed and provisioned, you can inject property values to it only known at deployment time, or in order to further configure the processing unit elements. Injected properties can be either properties that have been explicitly externalized from the [processing unit configuration file](./configuring-processing-unit-elements.html) or properties related to one the platform components (e.g. a space) that can be configured at deployment time. This mechanism is built on top of Spring's support for an externalized properties configuration called [PropertyPlaceholderConfigurer](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-placeholderconfigurer). This mechanism has been enhanced to provide a powerful yet simple property injection. {% info %} One of the core values of GigaSpaces XAP processing unit model is the fact that a processing unit need not be changed at all in the transition from the development environment (namely your IDE) to the production environment. This feature, along with others, is one of the enablers of this behavior. {%endinfo%} # Defining Property Place Holders in Your Processing Unit Property injection to the processing unit's configuration is supported at the Spring application context scope, which means that it can be applied to all of the components configured in the [processing unit's configuration file](./configuring-processing-unit-elements.html) (whether GigaSpaces out of the box components like the space, space proxy or event containers, or user-defined beans). Below you can find an example of an XML configuration which defines to property place holders, `spaceSchema` and `connectionTimeout`. In this example we also specify default values for them, which is always a good practice and does not force the deployer to specify values for these place holders. {% tip %} Note that for property place holders we use the `${placeholder name`} notation. {%endtip%} {% inittab os_simple_space|top %} {% tabcontent Namespace %} {% highlight xml %} <!-- The PropertyPlaceholderConfigurer must be present in order to define default value for properties. --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="properties"><props> <prop key="spaceSchema">default</prop> <prop key="connectionTimeout">1000</prop> </props></property> </bean> <os-core:space id="space" url="/./space" schema="${spaceSchema}" /> <bean id="connBean" class="MyConnection"> <property name="timeout" value="${connectionTimeout}" /> </bean> {% endhighlight %} {% endtabcontent %} {% tabcontent Plain %} {% highlight xml %} <!-- Define sensible defaults --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="properties"><props> <prop key="spaceSchema">default</prop> <prop key="connectionTimeout">1000</prop> </props></property> </bean> <bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean"> <property name="url" value="/./space" /> <property name="schema" value="${spaceSchema}" /> </bean> <bean id="connBean" class="MyConnection"> <property name="timeout" value="${connectionTimeout}" /> </bean> {% endhighlight %} {% endtabcontent %} {% endinittab %} The various [processing unit runtime modes](./deploying-and-running-the-processing-unit.html) all provide support for injecting property values instead of place holders. There are several ways to define the values for the property place holders, depending on how you choose to run/deploy your processing unit. ### Using a `.properties` File If you would like your properties to be configured in a dedicated file this can be done in various ways. - Including a `pu.properties` file in the processing unit. This file can be placed under the root of the processing unit or under the `META-INF/spring` directory (This is also described [here](./the-processing-unit-structure-and-configuration.html)). The values of this file will be loaded and injected automatically to the processing unit instances at deployment time. - External `.properties` file. The file can have any name, as long as it's accessible to the deployment tool (UI, CLI, etc.) or specified when [running the processing unit within your IDE](./running-and-debugging-within-your-ide.html) or in [standalone mode](./running-in-standalone-mode.html). When deploying through the [CLI](./command-line-interface.html) or [running within the IDE](./running-and-debugging-within-your-ide.html), you specify the location of the file using `-properties <location>` as a command line argument with the CLI or a program argument within the IDE. {% highlight java %} gs deploy -properties file://myConfigFolder/pu.properties data-processor.jar {% endhighlight %} By default, the location is a file-system-based location of a properties file (follows Spring [Resource Loader](http://static.springframework.org/spring/docs/2.5.x/reference/resources.html#resources-resourceloader) syntax). The following is an example of a `.properties` file that can be used with the sample `pu.xml` configuration shown above. In this case, the values within the `.properties` file are injected to the processing unit instances (overriding values in `pu.properties` if it exists). When deploying via the UI, the file can be loaded into the deployment wizard by clicking "Next" in the first screen of the wizard and then "Load Properties", locating the properties file on your local disk. This will load all the property place holders that are in the file. - Direct property injection. This can also be done via one of the deployment tools (UI, CLI) or specified when [running the processing unit within your IDE](./running-and-debugging-within-your-ide.html). When deploying through the [CLI](./command-line-interface.html) or [running within the IDE](./running-and-debugging-within-your-ide.html), you specify property values by using the following syntax: {% highlight java %} -properties embed://spaceSchema=persistent;connectionTimeout=15000 {% endhighlight %} This can be specified as part of the command line arguments or as a program argument when running within your IDE. When deploying via the UI, click "Next" in the first screen of the deployment wizard and then "+" to add properties. Any property you specify here will be injected to the appropriate property place holder (if such exists) and will override the `pu.properties` within the processing unit. {% info title=Property Injection for SLA Definitions %} From version 7.0 onwards, the processing unit's [SLA definitions](./configuring-the-processing-unit-sla.html) can be defined in a separate `sla.xml` file (unlike previous release in which they could only have been defined in the `pu.xml` file). As you may recall, the SLA definition are expressed via the `<os-sla:sla>` XML element in either the `pu.xml` of the `sla.xml` files. You should note however that property injection, as described in this page, and any external jars imports, is only available for SLA definitions expressed in a separate `sla.xml` file, and will not be applied to the `<os-sla:sla>` element if it is part of the `pu.xml` file. Also note that the parsing of the SLA element happens on the deploy tool side, so the properties should be available on the deploy tool side. {% endinfo %} # Using Deployment Properties to Override Space Schema and Cluster Schema When a [Space](./the-space-configuration.html) is created, two major groups of configuration elements determine its runtime configuration: the space schema and the cluster schema. The cluster schema controls the space clustering topology (partitioned or replicated), whether the replication to its replicas is synchronous or asynchronous, and various other aspects that control its clustering behavior. The space schema on the other hand, controls other elements which are not related to the space clustering topology, such as the eviction strategy (LRU, ALL_IN_CACHE), whether or not its persistent, etc. The basis for these two configuration groups are XML files located inside the GigaSpaces libraries. In order to override the values in these XML files, one can simply specify the [XPath](http://en.wikipedia.org/wiki/XPath) expression that corresponds to the element to be overridden. These expression can also be included in all of the above mentioned property injection mechanisms (with the exception that you do not have to explicitly specify property placeholders for them). Here's an example for a space configured within the processing unit, and a property injection overriding its schema name: {% inittab os_simple_space|top %} {% tabcontent Namespace %} {% highlight xml %} <os-core:space id="space" url="/./space" /> {% endhighlight %} {% endtabcontent %} {% tabcontent Plain %} {% highlight xml %} <bean id="space" class="org.openspaces.core.space.UrlSpaceFactoryBean"> <property name="url" value="/./space" /> </bean> {% endhighlight %} {% endtabcontent %} {% endinittab %} When deploying the space you should use `-properties space embed://gs.space.url.arg.schema=persistent`. This instructs the runtime to override the configuration of the bean named "space" in your pu.xml file with the specified value. You may also configure the space directly inside your processing unit using direct property injection on the space bean.
{ "content_hash": "42125b2227d9e875a05d147ad2a71f21", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 800, "avg_line_length": 69.17808219178082, "alnum_prop": 0.7626732673267327, "repo_name": "rasteroid/gigaspaces-wiki-jekyll", "id": "0bfd2c58a09147de25ef2856e373a67f66cef37f", "size": "10105", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xap97/deployment-properties.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "24326" }, { "name": "CSS", "bytes": "233963" }, { "name": "Java", "bytes": "2983" }, { "name": "JavaScript", "bytes": "70644" }, { "name": "Ruby", "bytes": "49915" }, { "name": "Shell", "bytes": "454" } ], "symlink_target": "" }
// // IBAutolayoutConstraintAdditionViewController.h // RRConstraintsPlugin // // Copyright (c) 2014 Rolandas Razma <rolandas@razma.lt> // // 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 Cocoa; @class IBAutolayoutConstraintAdditionTypeConfig, IBDocument; @protocol IBAutolayoutConstraintAdditionViewController <NSObject> @optional - (void)_addEdgeOrCenterAlignmentTypeConfigurationsToSet:(NSMutableSet *)typeConfigurations; - (IBAutolayoutConstraintAdditionTypeConfig *)_typeConfigurationWithField:(id /* DVTButtonTextField */)textField checkBox:(id /* NSButton */)button startingConstant:(id /* _NSStateMarker */)startingConstant andConstraints:(NSSet *)constraints; - (IBAutolayoutConstraintAdditionTypeConfig *)_typeConfigurationForAlignmentType:(unsigned long long)alignmentType; - (IBDocument *)document; @end @interface IBAutolayoutConstraintAdditionViewController : NSViewController <IBAutolayoutConstraintAdditionViewController> @end
{ "content_hash": "0086cccca498069964a98179c203abc8", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 243, "avg_line_length": 46.53488372093023, "alnum_prop": 0.7906046976511744, "repo_name": "Hs-Yeah/RRConstraintsPlugin", "id": "cd7838b507f6345c58e2f6d7d09e55056b15b454", "size": "2001", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "RRConstraintsPlugin/Classes/Support/XcodeInternals/Controller/IBAutolayoutConstraintAdditionViewController.h", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "5975" }, { "name": "Objective-C", "bytes": "119042" } ], "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 (version 1.7.0_65) on Thu Feb 26 12:21:50 ART 2015 --> <title>Overview List</title> <meta name="date" content="2015-02-26"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> </head> <body> <div class="indexHeader"><a href="allclasses-frame.html" target="packageFrame">All Classes</a></div> <div class="indexContainer"> <h2 title="Packages">Packages</h2> <ul title="Packages"> <li><a href="com/biasedbit/efflux/package-frame.html" target="packageFrame">com.biasedbit.efflux</a></li> <li><a href="com/biasedbit/efflux/logging/package-frame.html" target="packageFrame">com.biasedbit.efflux.logging</a></li> <li><a href="com/biasedbit/efflux/network/package-frame.html" target="packageFrame">com.biasedbit.efflux.network</a></li> <li><a href="com/biasedbit/efflux/packet/package-frame.html" target="packageFrame">com.biasedbit.efflux.packet</a></li> <li><a href="com/biasedbit/efflux/participant/package-frame.html" target="packageFrame">com.biasedbit.efflux.participant</a></li> <li><a href="com/biasedbit/efflux/session/package-frame.html" target="packageFrame">com.biasedbit.efflux.session</a></li> <li><a href="com/biasedbit/efflux/util/package-frame.html" target="packageFrame">com.biasedbit.efflux.util</a></li> </ul> </div> <p>&nbsp;</p> </body> </html>
{ "content_hash": "498c734c81789a83a216cebed1e36509", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 129, "avg_line_length": 55.88461538461539, "alnum_prop": 0.7274604267033723, "repo_name": "ekumenlabs/AndroidStreamingClient", "id": "d8a6c2fc4ff3ba9a8ca74496549a45c86552a15d", "size": "1453", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "efflux/doc/overview-frame.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "22278" }, { "name": "HTML", "bytes": "1767224" }, { "name": "Java", "bytes": "294742" }, { "name": "Shell", "bytes": "104" } ], "symlink_target": "" }
<?php error_reporting(E_ALL); ini_set("display_errors", 1); use Monolog\Logger; use App\Services\Env; class Notification extends Logger { public static function sendPush($deviceToken, $message, $data = null, $type = null) { $log = new \Monolog\Logger('notifications'); $log->pushHandler(new \Monolog\Handler\StreamHandler(Env::$config->logPath.'notifications.log', Logger::DEBUG)); $log->addInfo('Entering to send a push'); if(strlen($deviceToken) == 64) { $log->addInfo('Sending notification to ios device', ["deviceToken" => $deviceToken]); $ctx = stream_context_create(); //dev pem /home7/quesoazu/www/doyride/push/dev_key.pem stream_context_set_option($ctx, 'ssl', 'local_cert', Env::$config->pem); stream_context_set_option($ctx, 'ssl', 'passphrase', Env::$config->passphrase); // Open a connection to the APNS server // DEV APNS gateway.sandbox.push.apple.com:2195 $fp = stream_socket_client( Env::$config->apns, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); //echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array( 'alert' => $message, 'sound' => 'default', 'content-available' => 1 //'badge' => 0 ); $body['d'] = $data; $body['t'] = $type; // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); $log->addDebug($result); // Close the connection to the server fclose($fp); } else { $log->addInfo('Sending notification to android device', ["deviceToken" => $deviceToken]); //AIzaSyBpweimzrQ-5pjUO1absB4cTrDVRHIxmMg $api_key = Env::$config->apikey; //$registrationIDs = array("APA91bHOZnfPwVys28cus-w9s18zZw4lXb-CU1Os8OiA2MpLpvGc4b9sxipnAVZNiDHe3iWv4T-_5B7UHJ_ce2ybu_w_Z4Y_kXWsIJqE4bjyF0tcrZrofszmE42xJ_sg15Tw2yG2IxVXcFu37LyP7ZHx9DqRqqRByPSLUwkrUqzqavQSWt1A3l4"); $registrationIDs = array($deviceToken); $message = $message; $url = 'https://android.googleapis.com/gcm/send'; /*$body['registration_ids'] = $deviceToken; $body['aps'] = array( 'alert' => $message, 'sound' => 'default' ); $body['d'] = $data; $body['t'] = $type;*/ $fields = array( 'registration_ids' => $registrationIDs, 'data' => array( "message" => $message, "d" => $data, "t" => $type ), ); $headers = array( 'Authorization: key=' . $api_key, 'Content-Type: application/json'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch); $log->addDebug($result); curl_close($ch); } } public static function sendMain($recipient, $message) { $to = $recipient; $subject = "Autostop te da la bienvenida."; $headers = "From: hola@autostop.mx\r\n"; $headers .= "MIME-version: 1.0\r\n"; $headers .= "Content-Type: text/html; charset=UTF-8\r\n"; } }
{ "content_hash": "8c2a9e11e296d5af993c0fe4065ace0a", "timestamp": "", "source": "github", "line_count": 114, "max_line_length": 217, "avg_line_length": 31.20175438596491, "alnum_prop": 0.5965701433792522, "repo_name": "renomx/apistarter", "id": "2ca5f85775f111bb37dff7a1ca3d1c070b8826cc", "size": "3557", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/services/Notification.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "332" }, { "name": "CSS", "bytes": "43123" }, { "name": "Cucumber", "bytes": "1676" }, { "name": "HTML", "bytes": "3290" }, { "name": "JavaScript", "bytes": "120259" }, { "name": "PHP", "bytes": "375441" } ], "symlink_target": "" }
// .NAME vtkImageLaplacian - Computes divergence of gradient. // .SECTION Description // vtkImageLaplacian computes the Laplacian (like a second derivative) // of a scalar image. The operation is the same as taking the // divergence after a gradient. Boundaries are handled, so the input // is the same as the output. // Dimensionality determines how the input regions are interpreted. // (images, or volumes). The Dimensionality defaults to two. #ifndef vtkImageLaplacian_h #define vtkImageLaplacian_h #include "vtkImagingGeneralModule.h" // For export macro #include "vtkThreadedImageAlgorithm.h" class VTKIMAGINGGENERAL_EXPORT vtkImageLaplacian : public vtkThreadedImageAlgorithm { public: static vtkImageLaplacian *New(); vtkTypeMacro(vtkImageLaplacian,vtkThreadedImageAlgorithm); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Determines how the input is interpreted (set of 2d slices ...) vtkSetClampMacro(Dimensionality,int,2,3); vtkGetMacro(Dimensionality,int); protected: vtkImageLaplacian(); ~vtkImageLaplacian() {} int Dimensionality; virtual int RequestUpdateExtent (vtkInformation *, vtkInformationVector **, vtkInformationVector *); void ThreadedRequestData(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector, vtkImageData ***inData, vtkImageData **outData, int outExt[6], int id); private: vtkImageLaplacian(const vtkImageLaplacian&); // Not implemented. void operator=(const vtkImageLaplacian&); // Not implemented. }; #endif
{ "content_hash": "a751ecce98dd3f40dc382e842fb554af", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 83, "avg_line_length": 30.85185185185185, "alnum_prop": 0.7244897959183674, "repo_name": "candy7393/VTK", "id": "f2f0af3c5bf6bb1a874fd9bf5a0ee1f1895d8924", "size": "2253", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "Imaging/General/vtkImageLaplacian.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "37444" }, { "name": "Batchfile", "bytes": "106" }, { "name": "C", "bytes": "45726018" }, { "name": "C++", "bytes": "69182935" }, { "name": "CMake", "bytes": "1676815" }, { "name": "CSS", "bytes": "50625" }, { "name": "Cuda", "bytes": "29062" }, { "name": "GAP", "bytes": "14120" }, { "name": "GLSL", "bytes": "205024" }, { "name": "HTML", "bytes": "292104" }, { "name": "Java", "bytes": "147449" }, { "name": "JavaScript", "bytes": "1130278" }, { "name": "Lex", "bytes": "45258" }, { "name": "M4", "bytes": "121356" }, { "name": "Makefile", "bytes": "253851" }, { "name": "Objective-C", "bytes": "23327" }, { "name": "Objective-C++", "bytes": "191806" }, { "name": "Perl", "bytes": "173168" }, { "name": "Python", "bytes": "15675703" }, { "name": "Roff", "bytes": "65394" }, { "name": "Shell", "bytes": "72670" }, { "name": "Slash", "bytes": "1476" }, { "name": "Smarty", "bytes": "1325" }, { "name": "Tcl", "bytes": "1406798" }, { "name": "Yacc", "bytes": "174481" } ], "symlink_target": "" }
package com.sas.mkt.kafka; public class NoiseThread implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { System.out.println("NOISE!!!!"); Thread.sleep(1000); } catch (Exception ex) { done = true; } } } }
{ "content_hash": "cdd2d82250d43c78f49a22258dc1c66f", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 46, "avg_line_length": 14.6, "alnum_prop": 0.6061643835616438, "repo_name": "randyzingle/tools", "id": "0c65d2b609f19a5928671c289a2f2fed026dfc8d", "size": "292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring/store/src/main/java/com/sas/mkt/kafka/NoiseThread.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "773" }, { "name": "Go", "bytes": "118058" }, { "name": "Groovy", "bytes": "1555" }, { "name": "HTML", "bytes": "4288" }, { "name": "Java", "bytes": "818301" }, { "name": "JavaScript", "bytes": "605048" }, { "name": "Makefile", "bytes": "5063" }, { "name": "Python", "bytes": "10438760" }, { "name": "Scala", "bytes": "37406" }, { "name": "Shell", "bytes": "8611" } ], "symlink_target": "" }
import { Component, OnInit, AfterViewChecked, EventEmitter, Output, Input } from '@angular/core'; import { CurrencyPipe } from '@angular/common'; import { Subscription } from 'rxjs/Rx'; import { Router } from '@angular/router'; import { MaterializeAction } from 'angular2-materialize'; import createNumberMask from 'text-mask-addons/dist/createNumberMask' import { VendasService } from './../../_services/vendas.service'; import { ClientesService } from './../../_services/clientes.service'; import { ItensService } from './../../_services/itens.service'; import { environment } from './../../../environments/environment'; declare var Materialize:any; const numberMask = createNumberMask({ prefix: 'R$', allowDecimal:true, integerLimit: 7, decimalLimit: 2, thousandsSeparatorSymbol: '.', decimalSymbol: ',' }) @Component({ selector: 'app-nova-venda', templateUrl: './nova-venda.component.html', styleUrls: ['./nova-venda.component.css'] }) export class NovaVendaComponent implements OnInit, AfterViewChecked { maskMoney = numberMask; loadStatus: boolean = false; globalActions = new EventEmitter<string|MaterializeAction>(); baseUrl: string = environment.API_ENDPOINT; clientes: any[] = []; produtos: any[] = []; servicos: any[] = []; paramsPickdate: any = { monthsFull: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'], monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'], weekdaysFull: ['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sabádo'], weekdaysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'], today: 'Hoje', clear: 'Limpar', close: 'Pronto', labelMonthNext: 'Próximo mês', labelMonthPrev: 'Mês anterior', labelMonthSelect: 'Selecione um mês', labelYearSelect: 'Selecione um ano', format:'dd/mm/yyyy', closeOnSelect: true, selectMonths: true, selectYears: 15, onSet: function (ele) { if(ele.select){ this.close(); } } }; venda: any = { cliente: { images: [] }, itens: [], valor_total: 0, observacao: undefined, tipo: undefined }; novoItem: any = { item: { valor_venda: undefined, images: [] }, qntde: undefined, validade: undefined, total: undefined, tipo: undefined }; constructor( private vendasService: VendasService, private clientesService: ClientesService, private itensService: ItensService, private router: Router ) { } ngOnInit() { this.itensService.getItens().subscribe((itens) => { for (var i = 0; i < itens.length; ++i) { if(itens[i].qntde_minima) { // Tem quantidade minima // Então é produto if(itens[i].qntde_atual>0) this.produtos.push(itens[i]); } else { this.servicos.push(itens[i]); } } }); this.clientesService.getClientes().subscribe((clientes) => { this.clientes = clientes; this.loadStatus = true; }); } ngAfterViewChecked() { if(Materialize.updateTextFields) Materialize.updateTextFields(); } resetNovoItem() { // Reseta novoItem this.novoItem = { item: { images: [] }, qntde: undefined, validade: undefined, total: undefined, tipo: undefined }; } addItem() { if(!this.novoItem.item._id) return false; this.venda.itens.push(this.novoItem); this.resetNovoItem(); } currencyPipe(value: number, currencyCode: string = 'BRL', symbolDisplay: boolean = true, digits?: string): string { if (!value) { return ''; } let currencyPipe: CurrencyPipe = new CurrencyPipe('pt-BR'); let newValue: string = currencyPipe.transform(value, currencyCode, symbolDisplay, digits); return newValue.replace('R$', ''); } setNovoItem(item: any, edit?: boolean, row?: any) { this.novoItem.item = item; // Se tem valor de custo é um produto // Caso não: é um serviço this.novoItem.tipo = !this.novoItem.item.valor_custo ? false : true; this.novoItem.qntde = edit ? row.qntde : 1; // Validade do produto // APENAS produto if(this.novoItem.tipo) { let date = new Date(); date.setMonth(date.getMonth() + 12); this.novoItem.validade = date.toLocaleDateString('pt-BR'); } else { this.novoItem.validade = undefined; } this.sumNovo(); this.venda.itens.filter((filterItem) => { if(item._id === filterItem.item._id) { this.resetNovoItem(); this.triggerToast('Item já está sendo usado!', ''); } }); } formatDecimal(decimal: any) { if(typeof decimal === "number") decimal = decimal.toString(); if(decimal.indexOf('R$')!==-1) decimal = decimal.replace('R$',''); if(decimal.indexOf('.')!==-1) decimal = decimal.split('.').join(''); if(decimal.indexOf(',')!==-1) decimal = decimal.replace(',','.'); return decimal; } deleteRow(_item: any) { _item.selected = false; this.venda.itens = this.venda.itens.filter((filterItem) => { if(filterItem.item._id !== _item._id) return filterItem; }); } editarRow(item: any) { if(this.novoItem.item._id) { this.triggerToast('Salve o atual item, para editar outros!', ''); return false; } this.deleteRow(item.item); this.novoItem.item = item.item; this.setNovoItem(item.item, true, item); } sumNovo() { let priceFloat = parseFloat(this.formatDecimal(this.novoItem.item.valor_venda)); let priceCalculed = priceFloat * this.novoItem.qntde; this.novoItem.total = this.currencyPipe(priceCalculed); this.verificaQntdeMax(this.novoItem); } valorTotal() { let valorTotal = 0; for (var i = 0; i < this.venda.itens.length; ++i) { let priceFloat = parseFloat(this.formatDecimal(this.venda.itens[i].total)); valorTotal += priceFloat; } this.venda.valor_total = this.currencyPipe(valorTotal); return valorTotal; } verificaQntdeMax(item: any) { // Quantidade máxima em estoque permitida if(item.qntde >= item.item.qntde_atual) { this.triggerToast('Apenas ' + item.item.qntde_atual + ' unidades existentes em estoque', ''); item.qntde = item.item.qntde_atual; return false; } } novaVenda(event) { event.preventDefault(); if(!this.venda.cliente.length&&!this.venda.itens.length) { this.triggerToast('Adicione ao menos 1 produto', 'red'); return false; }; this.vendasService.addVenda(this.venda).subscribe(venda => { this.router.navigate(['vendas']); this.triggerToast('Venda efetuada com sucesso!', 'green'); }); } triggerToast(stringToast: string, bgColor: string) { this.globalActions.emit({action: 'toast', params: [stringToast, 4000, bgColor]}); } }
{ "content_hash": "a0a420786f40ff5879d817c879e27067", "timestamp": "", "source": "github", "line_count": 275, "max_line_length": 143, "avg_line_length": 24.29090909090909, "alnum_prop": 0.6483532934131736, "repo_name": "MuriloEduardo/extinfire_v2", "id": "3d368e2a7dd884812b84a4616162576aea1e1cdb", "size": "6696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/vendas/nova-venda/nova-venda.component.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8261" }, { "name": "HTML", "bytes": "110401" }, { "name": "JavaScript", "bytes": "26744" }, { "name": "TypeScript", "bytes": "92894" } ], "symlink_target": "" }
from __future__ import print_function import os import csv import sys if os.path.exists("/home/ggdhines/github/pyIBCC/python"): sys.path.append("/home/ggdhines/github/pyIBCC/python") else: sys.path.append("/Users/greghines/Code/pyIBCC/python") import ibcc if os.path.isdir("/Users/greghines/Databases/serengeti"): baseDir = "/Users/greghines/Databases/serengeti/" else: baseDir = "/home/ggdhines/Databases/serengeti/" species2 = ['elephant','zebra','warthog','impala','buffalo','wildebeest','gazelleThomsons','dikDik','giraffe','gazelleGrants','lionFemale','baboon','hippopotamus','ostrich','human','otherBird','hartebeest','secretaryBird','hyenaSpotted','mongoose','reedbuck','topi','guineaFowl','eland','aardvark','lionMale','porcupine','koriBustard','bushbuck','hyenaStriped','jackal','cheetah','waterbuck','leopard','reptiles','serval','aardwolf','vervetMonkey','rodents','honeyBadger','batEaredFox','rhinoceros','civet','genet','zorilla','hare','caracal','wildcat'] #species = ['gazelleThomsons'] species = ['buffalo','wildebeest','zebra'] users = [] photos = [] def createConfigFile(classID): f = open(baseDir+"ibcc/"+str(classID)+"config.py",'wb') print("import numpy as np\nscores = np.array([0,1])", file=f) print("nScores = len(scores)", file=f) print("nClasses = 2",file=f) print("inputFile = '"+baseDir+"ibcc/"+str(classID)+".in'", file=f) print("outputFile = '"+baseDir+"ibcc/"+str(classID)+".out'", file=f) print("confMatFile = '"+baseDir+"ibcc/"+str(classID)+".mat'", file=f) # if numClasses == 4: # print("alpha0 = np.array([[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2], [2, 2,2, 2]])", file=f) # print("nu0 = np.array([25.0, 25.0, 25.0, 1.0])", file=f) # elif numClasses == 2: # print("alpha0 = np.array([[2, 1], [1, 2],])", file=f) # print("nu0 = np.array([50.,50.])", file=f) # else: # assert(False) f.close() individualClassifications = [] reader = csv.reader(open(baseDir+"filtered20","rU"), delimiter="\t") for userName, photoName, classification in reader: individualClassifications.append((userName,photoName,classification)) ibccClassifications = [] for i, s in enumerate(species): print(s) createConfigFile(i) f = open(baseDir+"ibcc/"+str(i)+".in",'wb') for userName,photoName,classification in individualClassifications: if classification == "[]": classification = [] else: classification = [int(v) for v in classification[1:-1].split(",")] if not(userName in users): users.append(userName) userIndex = len(users)-1 else: userIndex = users.index(userName) if not(photoName in photos): photos.append(photoName) photoIndex = len(photos)- 1 else: photoIndex = photos.index(photoName) if i in classification: print(str(userIndex)+","+str(photoIndex)+",1", file=f) else: print(str(userIndex)+","+str(photoIndex)+",0", file=f) f.close() ibcc.runIbcc(baseDir+"ibcc/"+str(i)+"config.py") #read in the predicted classifications #next, read in the the experts' classifications ibccClassifications = [0 for p in photos] print("Reading in IBCC results") reader = csv.reader(open(baseDir+"ibcc/"+str(i)+".out", "rU"), delimiter=" ") next(reader, None) for row in reader: photoIndex = int(float(row[0])) pos = float(row[2]) if pos >= 0.5: ibccClassifications[photoIndex] = 1 mistakes = {} #now go back to the users input and estimate what their confusion matrices would like for userName,photoName,classification in individualClassifications: photoIndex = photos.index(photoName) if classification == "[]": classification = [] else: classification = [int(v) for v in classification[1:-1].split(",")] if ibccClassifications[photoIndex] == 1: if not(i in classification) and len(classification) == 1: if len(classification) != 1: continue correct = species[i] reported = species2[classification[0]] if correct == reported: continue if not((correct,reported) in mistakes) : mistakes[(correct,reported)] = 1 else: mistakes[(correct,reported)] += 1 for (correct,incorrect) in mistakes: print(correct,incorrect,mistakes[(correct,incorrect)]) continue #next, read in the the experts' classifications expertClassifications = [0 for p in photos] print("Reading in expert classification") reader = csv.reader(open(baseDir+"expert_classifications_raw.csv", "rU"), delimiter=",") next(reader, None) for row in reader: photoName = row[2] photoIndex = photos.index(photoName) tagged = row[12] if s in tagged: expertClassifications[photoIndex] = 1
{ "content_hash": "0088b06b47e3cf7a2215bde65e2e560e", "timestamp": "", "source": "github", "line_count": 146, "max_line_length": 552, "avg_line_length": 34.897260273972606, "alnum_prop": 0.6125613346418057, "repo_name": "zooniverse/aggregation", "id": "0057358f70a9bdb47cfd2e1aa630936093e22a43", "size": "5117", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "experimental/serengeti/individualIBCC.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "723" }, { "name": "Python", "bytes": "2184451" }, { "name": "Scala", "bytes": "629" }, { "name": "Shell", "bytes": "190" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <template type="basic" name="StdyscpH1C13alphaALL" author="Agilent" investigator="" time_created="20120109T161942" tabname="AutoSolids Experiments" menu1="Calibration Studies" menu2="" apptype="solidseq1d" application="Solids" scans="StdyscpH1C13alphaALL" seqfil="StdyscpH1C13alphaALL"> <protocol title="StdyscpH1C13alphaALL" type="protocol"> <action type="LIB" status="Ready" lock="off" title="StdyscpH1C13alphaALL" exp="StdyscpH1C13alphaALL" time="21:00" macro="StdyscpH1C13alphaALL" data="" /> </protocol> </template>
{ "content_hash": "f44f5511fe9741d53fff16f6acf09a50", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 129, "avg_line_length": 67.77777777777777, "alnum_prop": 0.7327868852459016, "repo_name": "OpenVnmrJ/OpenVnmrJ", "id": "63e7af407d137b20402b030308133009e7ac1dba", "size": "610", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/solidspack/templates/vnmrj/protocols/StdyscpH1C13alphaALL.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "8033" }, { "name": "Awk", "bytes": "3726" }, { "name": "Batchfile", "bytes": "993" }, { "name": "C", "bytes": "44578835" }, { "name": "C++", "bytes": "1895471" }, { "name": "CSS", "bytes": "12739" }, { "name": "Fortran", "bytes": "1661682" }, { "name": "HTML", "bytes": "68197" }, { "name": "Inno Setup", "bytes": "18741" }, { "name": "Java", "bytes": "17274464" }, { "name": "JavaScript", "bytes": "44448" }, { "name": "Lex", "bytes": "42593" }, { "name": "LiveScript", "bytes": "1071" }, { "name": "MATLAB", "bytes": "77708" }, { "name": "Makefile", "bytes": "126047" }, { "name": "OpenEdge ABL", "bytes": "6980" }, { "name": "PLpgSQL", "bytes": "1040" }, { "name": "Perl", "bytes": "10286" }, { "name": "PostScript", "bytes": "801" }, { "name": "Python", "bytes": "590263" }, { "name": "R", "bytes": "1082" }, { "name": "RPC", "bytes": "43654" }, { "name": "Roff", "bytes": "41584" }, { "name": "Shell", "bytes": "1478413" }, { "name": "Tcl", "bytes": "864859" }, { "name": "Vim Script", "bytes": "7711" }, { "name": "Yacc", "bytes": "95121" } ], "symlink_target": "" }
// This code is auto-generated, do not modify namespace Ds3.Models { public enum DatabasePhysicalSpaceState { CRITICAL, LOW, NEAR_LOW, NORMAL } }
{ "content_hash": "8246a7a6c674f33f401bc98bf45eb5af", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 45, "avg_line_length": 13.785714285714286, "alnum_prop": 0.5803108808290155, "repo_name": "RachelTucker/ds3_net_sdk", "id": "0854a3dc094f2c6e628d48cbf7e7c7784c3238e7", "size": "950", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Ds3/Models/DatabasePhysicalSpaceState.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "617" }, { "name": "C#", "bytes": "3606193" }, { "name": "Dockerfile", "bytes": "162" }, { "name": "Makefile", "bytes": "654" }, { "name": "Ruby", "bytes": "2446" }, { "name": "Shell", "bytes": "453" } ], "symlink_target": "" }
package edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2; /** ECP SAML 2 SSO configuration settings. */ public class ECPConfiguration extends SSOConfiguration { /** ID for this profile configuration. */ public static final String PROFILE_ID = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp"; /** {@inheritDoc} */ public String getProfileId() { return PROFILE_ID; } }
{ "content_hash": "548d552f0cc1ded167333e0a5aae54dd", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 91, "avg_line_length": 28.066666666666666, "alnum_prop": 0.7054631828978623, "repo_name": "brainysmith/shibboleth-common", "id": "8eebde5e169520d420f893a4cd7b98211f7461b5", "size": "1265", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/edu/internet2/middleware/shibboleth/common/relyingparty/provider/saml2/ECPConfiguration.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "149" }, { "name": "Java", "bytes": "1857935" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using ModernDesignTemplate.Annotations; namespace ModernDesignTemplate { public class ViewModelSwitcher : IViewModelSwitcher, INotifyPropertyChanged { public delegate void SwitchViewEventHandler(object sender, SwitchViewEventArgs e); private readonly IList<ISwitchableViewModel> _viewModels; private readonly Type _defaultViewModel; private ISwitchableViewModel _currentView; public ViewModelSwitcher(IEnumerable<ISwitchableViewModel> viewModels, Type defaultViewModel) { _viewModels = viewModels.ToList(); _defaultViewModel = defaultViewModel; foreach (ISwitchableViewModel viewModel in _viewModels) { //TODO: Add abstraction for the viewmodel collection (beware of circular dependency) if (viewModel.GetType() == typeof(HomeViewModel)) { HomeViewModel homeViewModel = (HomeViewModel)viewModel; homeViewModel.ViewModels = _viewModels.Where(x => x != homeViewModel); } viewModel.Switch += Switch; } } public event PropertyChangedEventHandler PropertyChanged; public ISwitchableViewModel CurrentView { get { return _currentView ?? (_currentView = _viewModels.Single(x => x.GetType() == _defaultViewModel)); } set { if (Equals(value, _currentView)) return; _currentView = value; OnPropertyChanged(); } } public void Switch(object sender, SwitchViewEventArgs e) { CurrentView = _viewModels.Single(x => x.GetType() == e.ViewModelType); } [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } }
{ "content_hash": "eccadf1df870235f6e2b6ae047674037", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 118, "avg_line_length": 35.63492063492063, "alnum_prop": 0.6249443207126949, "repo_name": "TedMANNERs/ModernDesignTemplate", "id": "afcaa4543a5041e5c5ecf9acfa43c9f0c8e51069", "size": "2245", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ModernDesignTemplate/ViewModelSwitcher.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "51478" } ], "symlink_target": "" }