text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}

-----------------------------------------------------------------------------
-- |
-- Module      : FFICXX.Generate.Type.Class
-- Copyright   : (c) 2011-2013 Ian-Woo Kim
--
-- License     : BSD3
-- Maintainer  : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability   : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------

module FFICXX.Generate.Type.Class where

import Control.Applicative ((<$>),(<*>))
import Data.Char
import Data.List
import Data.Monoid
import qualified Data.Map as M
import System.FilePath
--
import FFICXX.Generate.Util

-- | C types
data CTypes = CTString
            | CTChar
            | CTInt
            | CTUInt
            | CTLong
            | CTULong
            | CTDouble
            | CTBool
            | CTDoubleStar
            | CTVoidStar
            | CTIntStar
            | CTCharStarStar
            | CPointer CTypes
            deriving Show

-- | C++ types
data CPPTypes = CPTClass Class
              | CPTClassRef Class
              deriving Show

-- | const flag
data IsConst = Const | NoConst
             deriving Show

data Types = Void
           | SelfType
           | CT  CTypes IsConst
           | CPT CPPTypes IsConst
           deriving Show

cvarToStr :: CTypes -> IsConst -> String -> String
cvarToStr ctyp isconst varname = (ctypToStr ctyp isconst) `connspace` varname

ctypToStr :: CTypes -> IsConst -> String
ctypToStr ctyp isconst =
  let typword = case ctyp of
        CTString -> "char*"
        CTChar   -> "char"
        CTInt    -> "int"
        CTUInt   -> "unsigned int"
        CTLong   -> "signed long"
        CTULong  -> "long unsigned int"
        CTDouble -> "double"
        CTBool   -> "int"              -- Currently available solution
        CTDoubleStar -> "double *"
        CTVoidStar -> "void*"
        CTIntStar -> "int*"
        CTCharStarStar -> "char**"
        CPointer s -> ctypToStr s NoConst ++ "*"
  in case isconst of
        Const   -> "const" `connspace` typword
        NoConst -> typword

self_ :: Types
self_ = SelfType

cstring_ :: Types
cstring_ = CT CTString Const

cint_ :: Types
cint_    = CT CTInt    Const

int_ :: Types
int_     = CT CTInt    NoConst

uint_ :: Types
uint_ = CT CTUInt NoConst

ulong_ :: Types
ulong_ = CT CTULong NoConst

long_ :: Types
long_ = CT CTLong NoConst

culong_ :: Types
culong_ = CT CTULong Const

clong_ :: Types
clong_ = CT CTLong Const

cchar_ :: Types
cchar_ = CT CTChar Const

char_ :: Types
char_ = CT CTChar NoConst

short_ :: Types
short_ = int_

cdouble_ :: Types
cdouble_ = CT CTDouble Const

double_ :: Types
double_  = CT CTDouble NoConst

doublep_ :: Types
doublep_ = CT CTDoubleStar NoConst

float_ :: Types
float_ = double_

bool_ :: Types
bool_    = CT CTBool   NoConst

void_ :: Types
void_ = Void

voidp_ :: Types
voidp_ = CT CTVoidStar NoConst

intp_ :: Types
intp_ = CT CTIntStar NoConst

charpp_ :: Types
charpp_ = CT CTCharStarStar NoConst

star_ :: CTypes -> Types
star_ t = CT (CPointer t) NoConst

cstar_ :: CTypes -> Types
cstar_ t = CT (CPointer t) Const

self :: String -> (Types, String)
self var = (self_, var)

voidp :: String -> (Types,String)
voidp var = (voidp_ , var)

cstring :: String -> (Types,String)
cstring var = (cstring_ , var)

cint :: String -> (Types,String)
cint    var = (cint_    , var)

int :: String -> (Types,String)
int     var = (int_     , var)

uint :: String -> (Types,String)
uint var = (uint_ , var)

long :: String -> (Types,String)
long var = (long_, var)

ulong :: String -> (Types,String)
ulong var = (ulong_ , var)

clong :: String -> (Types,String)
clong var = (clong_, var)

culong :: String -> (Types,String)
culong var = (culong_ , var)

cchar :: String -> (Types,String)
cchar var = (cchar_ , var)

char :: String -> (Types,String)
char var = (char_ , var)

short :: String -> (Types,String)
short = int

cdouble :: String -> (Types,String)
cdouble var = (cdouble_ , var)

double :: String -> (Types,String)
double  var = (double_  , var)

doublep :: String -> (Types,String)
doublep var = (doublep_ , var)

float :: String -> (Types,String)
float = double

bool :: String -> (Types,String)
bool    var = (bool_    , var)

intp :: String -> (Types, String)
intp var = (intp_ , var)

charpp :: String -> (Types, String)
charpp var = (charpp_, var)

star :: CTypes -> String -> (Types, String)
star t var = (star_ t, var)

cstar :: CTypes -> String -> (Types, String)
cstar t var = (cstar_ t, var)

cppclass_ :: Class -> Types
cppclass_ c =  CPT (CPTClass c) NoConst

cppclass :: Class -> String -> (Types, String)
cppclass c vname = ( cppclass_ c, vname)

cppclassconst :: Class -> String -> (Types, String)
cppclassconst c vname = ( CPT (CPTClass c) Const, vname)

cppclassref_ :: Class -> Types
cppclassref_ c = CPT (CPTClassRef c) NoConst

cppclassref :: Class -> String -> (Types, String)
cppclassref c vname = (cppclassref_ c, vname)

hsCTypeName :: CTypes -> String
hsCTypeName CTString = "CString"
hsCTypeName CTChar   = "CChar"
hsCTypeName CTInt    = "CInt"
hsCTypeName CTUInt   = "CUInt"
hsCTypeName CTLong   = "CLong"
hsCTypeName CTULong  = "CULong"
hsCTypeName CTDouble = "CDouble"
hsCTypeName CTDoubleStar = "(Ptr CDouble)"
hsCTypeName CTBool   = "CInt"
hsCTypeName CTVoidStar = "(Ptr ())"
hsCTypeName CTIntStar = "(Ptr CInt)"
hsCTypeName CTCharStarStar = "(Ptr (CString))"
hsCTypeName (CPointer t) = "(Ptr " ++ hsCTypeName t ++ ")"

hsCppTypeName :: CPPTypes -> String
hsCppTypeName (CPTClass c) =  "(Ptr "++rawname++")"  where rawname = snd (hsClassName c)
hsCppTypeName (CPTClassRef c) = "(Ptr "++rawname++")" where rawname = snd (hsClassName c)

-------------

type Args = [(Types,String)]

data Function = Constructor { func_args :: Args
                            , func_alias :: Maybe String
                            }
              | Virtual { func_ret :: Types
                        , func_name :: String
                        , func_args :: Args
                        , func_alias :: Maybe String
                        }
              | NonVirtual { func_ret :: Types
                           , func_name :: String
                           , func_args :: Args
                           , func_alias :: Maybe String
                           }
              | Static     { func_ret :: Types
                           , func_name :: String
                           , func_args :: Args
                           , func_alias :: Maybe String
                           }
              | Destructor  { func_alias :: Maybe String }
              deriving Show

data TopLevelFunction = TopLevelFunction { toplevelfunc_ret :: Types
                                         , toplevelfunc_name :: String
                                         , toplevelfunc_args :: Args
                                         , toplevelfunc_alias :: Maybe String
                                         }
                      | TopLevelVariable { toplevelvar_ret :: Types
                                         , toplevelvar_name :: String
                                         , toplevelvar_alias :: Maybe String }
                      deriving Show

hsFrontNameForTopLevelFunction :: TopLevelFunction -> String
hsFrontNameForTopLevelFunction tfn =
    let (x:xs) = case tfn of
                   TopLevelFunction {..} -> maybe toplevelfunc_name id toplevelfunc_alias
                   TopLevelVariable {..} -> maybe toplevelvar_name id toplevelvar_alias
    in toLower x : xs

data TopLevelImportHeader = TopLevelImportHeader { tihHeaderFileName :: String
                                                 , tihClassDep :: [ClassImportHeader]
                                                 , tihFuncs :: [TopLevelFunction]
                                                 }

isNewFunc :: Function -> Bool
isNewFunc (Constructor _ _) = True
isNewFunc _ = False

isDeleteFunc :: Function -> Bool
isDeleteFunc (Destructor _) = True
isDeleteFunc _ = False

isVirtualFunc :: Function -> Bool
isVirtualFunc (Destructor _)           = True
isVirtualFunc (Virtual _ _ _ _)        = True
isVirtualFunc _ = False

isStaticFunc :: Function -> Bool
isStaticFunc (Static _ _ _ _) = True
isStaticFunc _ = False

virtualFuncs :: [Function] -> [Function]
virtualFuncs = filter isVirtualFunc

constructorFuncs :: [Function] -> [Function]
constructorFuncs = filter isNewFunc

nonVirtualNotNewFuncs :: [Function] -> [Function]
nonVirtualNotNewFuncs =
  filter (\x -> (not.isVirtualFunc) x && (not.isNewFunc) x && (not.isDeleteFunc) x && (not.isStaticFunc) x )

staticFuncs :: [Function] -> [Function]
staticFuncs = filter isStaticFunc

argToString :: (Types,String) -> String
argToString (CT ctyp isconst, varname) = cvarToStr ctyp isconst varname
argToString (SelfType, varname) = "Type ## _p " ++ varname
argToString (CPT (CPTClass c) isconst, varname) = case isconst of
    Const   -> "const_" ++ cname ++ "_p " ++ varname
    NoConst -> cname ++ "_p " ++ varname
  where cname = class_name c
argToString (CPT (CPTClassRef c) isconst, varname) = case isconst of
    Const   -> "const_" ++ cname ++ "_p " ++ varname
    NoConst -> cname ++ "_p " ++ varname
  where cname = class_name c
argToString _ = error "undefined argToString"

argsToString :: Args -> String
argsToString args =
  let args' = (SelfType, "p") : args
  in  intercalateWith conncomma argToString args'

argsToStringNoSelf :: Args -> String
argsToStringNoSelf = intercalateWith conncomma argToString

argToCallString :: (Types,String) -> String
argToCallString (CPT (CPTClass c) _,varname) =
    "to_nonconst<"++str++","++str++"_t>("++varname++")" where str = class_name c
argToCallString (CPT (CPTClassRef c) _,varname) =
    "to_nonconstref<"++str++","++str++"_t>(*"++varname++")" where str = class_name c
argToCallString (_,varname) = varname

argsToCallString :: Args -> String
argsToCallString = intercalateWith conncomma argToCallString

rettypeToString :: Types -> String
rettypeToString (CT ctyp isconst) = ctypToStr ctyp isconst
rettypeToString Void = "void"
rettypeToString SelfType = "Type ## _p"
rettypeToString (CPT (CPTClass c) _) = str ++ "_p"
  where str = class_name c
rettypeToString (CPT (CPTClassRef c) _) = str ++ "_p"
  where str = class_name c

--------

newtype ProtectedMethod = Protected { unProtected :: [String] }
    deriving (Monoid)

data Cabal = Cabal { cabal_pkgname :: String
                   , cabal_cheaderprefix :: String
                   , cabal_moduleprefix :: String }

data Class = Class { class_cabal :: Cabal
                   , class_name :: String
                   , class_parents :: [Class]
                   , class_protected :: ProtectedMethod
                   , class_alias :: Maybe String
                   , class_funcs :: [Function]
                   }
           | AbstractClass { class_cabal :: Cabal
                           , class_name :: String
                           , class_parents :: [Class]
                           , class_protected :: ProtectedMethod
                           , class_alias :: Maybe String
                           , class_funcs :: [Function]
                           }

newtype Namespace = NS { unNamespace :: String } deriving (Show)

data ClassImportHeader = ClassImportHeader
                       { cihClass :: Class
                       , cihSelfHeader :: String
                       , cihNamespace :: [Namespace]
                       , cihSelfCpp :: String
                       , cihIncludedHPkgHeadersInH :: [String]
                       , cihIncludedHPkgHeadersInCPP :: [String]
                       , cihIncludedCPkgHeaders :: [String]
                       } deriving (Show)

data ClassModule = ClassModule
                   { cmModule :: String
                   , cmClass :: [Class]
                   , cmCIH :: [ClassImportHeader]
                   , cmImportedModulesHighNonSource :: [String]
                   , cmImportedModulesRaw :: [String]
                   , cmImportedModulesHighSource :: [String]
                   , cmImportedModulesForFFI :: [String]
                   } deriving (Show)

data ClassGlobal = ClassGlobal
                   { cgDaughterSelfMap :: DaughterMap
                   , cgDaughterMap :: DaughterMap
                   }

-- | Check abstract class

isAbstractClass :: Class -> Bool
isAbstractClass (Class _ _ _ _ _ _) = False
isAbstractClass (AbstractClass _ _ _ _ _ _) = True

instance Show Class where
  show x = show (class_name x)

instance Eq Class where
  (==) x y = class_name x == class_name y

instance Ord Class where
  compare x y = compare (class_name x) (class_name y)

type DaughterMap = M.Map String [Class]

class_allparents :: Class -> [Class]
class_allparents c = let ps = class_parents c
                     in  if null ps
                           then []
                           else nub (ps ++ (concatMap class_allparents ps))

getClassModuleBase :: Class -> String
getClassModuleBase = (<.>) <$> (cabal_moduleprefix.class_cabal) <*> (fst.hsClassName)

-- | Daughter map not including itself
mkDaughterMap :: [Class] -> DaughterMap
mkDaughterMap = foldl mkDaughterMapWorker M.empty
  where mkDaughterMapWorker m c = let ps = map getClassModuleBase (class_allparents c)
                                  in  foldl (addmeToYourDaughterList c) m ps
        addmeToYourDaughterList c m p = let f Nothing = Just [c]
                                            f (Just cs)  = Just (c:cs)
                                        in  M.alter f p m

-- | Daughter Map including itself as a daughter
mkDaughterSelfMap :: [Class] -> DaughterMap
mkDaughterSelfMap = foldl worker M.empty
  where worker m c = let ps = map getClassModuleBase (c:class_allparents c)
                     in  foldl (addToList c) m ps
        addToList c m p = let f Nothing = Just [c]
                              f (Just cs)  = Just (c:cs)
                          in  M.alter f p m

-- |
ctypToHsTyp :: Maybe Class -> Types -> String
ctypToHsTyp _c Void = "()"
ctypToHsTyp (Just c) SelfType = (fst.hsClassName) c
ctypToHsTyp Nothing SelfType = error "ctypToHsTyp : SelfType but no class "
ctypToHsTyp _c (CT CTString _) = "CString"
ctypToHsTyp _c (CT CTInt _) = "CInt"
ctypToHsTyp _c (CT CTUInt _) = "CUInt"
ctypToHsTyp _c (CT CTChar _) = "CChar"
ctypToHsTyp _c (CT CTLong _) = "CLong"
ctypToHsTyp _c (CT CTULong _) = "CULong"
ctypToHsTyp _c (CT CTDouble _) = "CDouble"
ctypToHsTyp _c (CT CTBool _ ) = "CInt"
ctypToHsTyp _c (CT CTDoubleStar _) = "(Ptr CDouble)"
ctypToHsTyp _c (CT CTVoidStar _) = "(Ptr ())"
ctypToHsTyp _c (CT CTIntStar _) = "(Ptr CInt)"
ctypToHsTyp _c (CT CTCharStarStar _) = "(Ptr CString)"
ctypToHsTyp _c (CT (CPointer t) _) = hsCTypeName (CPointer t)
ctypToHsTyp _c (CPT (CPTClass c') _) = class_name c'
ctypToHsTyp _c (CPT (CPTClassRef c') _) = class_name c'

typeclassName :: Class -> String
typeclassName c = 'I' : fst (hsClassName c)

typeclassNameFromStr :: String -> String
typeclassNameFromStr = ('I':)

hsClassName :: Class -> (String, String)  -- ^ High-level, 'Raw'-level
hsClassName c =
  let cname = maybe (class_name c) id (class_alias c)
  in (cname, "Raw" ++ cname)

existConstructorName :: Class -> String
existConstructorName c = 'E' : (fst.hsClassName) c

-- | this is for FFI type.
hsFuncTyp :: Class -> Function -> String
hsFuncTyp c f = let args = genericFuncArgs f
                    ret  = genericFuncRet f
                in  selfstr ++ " -> " ++ concatMap ((++ " -> ") . hsargtype . fst) args ++ hsrettype ret

  where (_hcname,rcname) = hsClassName c
        selfstr = "(Ptr " ++ rcname ++ ")"

        hsargtype (CT ctype _) = hsCTypeName ctype
        hsargtype (CPT x _) = hsCppTypeName x
        hsargtype SelfType = selfstr
        hsargtype _ = error "undefined hsargtype"

        hsrettype Void = "IO ()"
        hsrettype SelfType = "IO " ++ selfstr
        hsrettype (CT ctype _) = "IO " ++ hsCTypeName ctype
        hsrettype (CPT x _ ) = "IO " ++ hsCppTypeName x

-- | this is for FFI
hsFuncTypNoSelf :: Class -> Function -> String
hsFuncTypNoSelf c f = let args = genericFuncArgs f
                          ret  = genericFuncRet f
                      in  intercalateWith connArrow id $ map (hsargtype . fst) args ++ [hsrettype ret]

  where (_hcname,rcname) = hsClassName c
        selfstr = "(Ptr " ++ rcname ++ ")"

        hsargtype (CT ctype _) = hsCTypeName ctype
        hsargtype (CPT x _) = hsCppTypeName x
        hsargtype SelfType = selfstr
        hsargtype _ = error "undefined hsargtype"

        hsrettype Void = "IO ()"
        hsrettype SelfType = "IO " ++ selfstr
        hsrettype (CT ctype _) = "IO " ++ hsCTypeName ctype
        hsrettype (CPT x _ ) = "IO " ++ hsCppTypeName x

hscFuncName :: Class -> Function -> String
hscFuncName c f = "c_" ++ toLowers (class_name c) ++ "_" ++ toLowers (aliasedFuncName c f)

hsFuncName :: Class -> Function -> String
hsFuncName c f = let (x:xs) = aliasedFuncName c f
                 in (toLower x) : xs

hsFuncXformer :: Function -> String
hsFuncXformer func@(Constructor _ _) = let len = length (genericFuncArgs func)
                                       in if len > 0
                                          then "xform" ++ show (len - 1)
                                          else "xformnull"
hsFuncXformer func@(Static _ _ _ _) =
  let len = length (genericFuncArgs func)
  in if len > 0
     then "xform" ++ show (len - 1)
     else "xformnull"
hsFuncXformer func = let len = length (genericFuncArgs func)
                     in "xform" ++ show len

genericFuncRet :: Function -> Types
genericFuncRet f =
  case f of
    Constructor _ _ -> self_
    Virtual t _ _ _ -> t
    NonVirtual t _ _ _-> t
    Static t _ _ _ -> t
    -- AliasVirtual t _ _ _ -> t
    Destructor _ -> void_

genericFuncArgs :: Function -> Args
genericFuncArgs (Destructor _) = []
genericFuncArgs f = func_args f

aliasedFuncName :: Class -> Function -> String
aliasedFuncName c f =
  case f of
    Constructor _ a -> maybe (constructorName c) id a
    Virtual _ str _ a -> maybe str id a
    NonVirtual _ str _ a-> maybe (nonvirtualName c str) id a
    Static _ str _ a -> maybe (nonvirtualName c str) id a
    -- AliasVirtual _ _  _ alias -> alias
    Destructor a -> maybe destructorName id a

cppStaticName :: Class -> Function -> String
cppStaticName c f = class_name c ++ "::" ++ func_name f

cppFuncName :: Class -> Function -> String
cppFuncName c f =   case f of
    Constructor _ _ -> "new"
    Virtual _ _  _ _ -> func_name f
    NonVirtual _ _ _ _-> func_name f
    Static _ _ _ _-> cppStaticName c f
    -- AliasVirtual _ _  _ _ _ -> func_name f
    Destructor _ -> destructorName

constructorName :: Class -> String
constructorName c = "new" ++ (fst.hsClassName) c

nonvirtualName :: Class -> String -> String
nonvirtualName c str = (firstLower.fst.hsClassName) c ++ str

destructorName :: String
destructorName = "delete"


text:
package org.gazzax.labs.jena.nosql.fwk;

import org.gazzax.labs.jena.nosql.fwk.dictionary.node.TopLevelDictionaryBase;
import org.gazzax.labs.jena.nosql.fwk.factory.StorageLayerFactory;

/**
 * A bidirectional index that can be accessed both by key and value.
 *
 * This class has been derived from CumulusRDF code, with many thanks to CumulusRDF team for allowing this.
 *
 * @see https://code.google.com/p/cumulusrdf
 * @author Andrea Gazzarini
 * @since 1.0
 */
public class BIndex implements Initialisable{
	PersistentKeyValueMap<byte[], String> byId;
	PersistentKeyValueMap<String, byte[]> byValue;

	final String name;

	/**
	 * Builds a new index with the given name.
	 *
	 * @param name the name of this index.
	 */
	public BIndex(final String name) {
		this.name = name;
	}

	@Override
	public void initialise(final StorageLayerFactory factory) throws InitialisationException {
		byValue = new PersistentKeyValueMap<String, byte[]>(
				String.class,
				byte[].class,
				name,
				false,
				TopLevelDictionaryBase.NOT_SET);
		byValue.initialise(factory);

		byId = new PersistentKeyValueMap<byte[], String>(
				byte[].class,
				String.class,
				name + "_REVERSE",
				false,
				Constants.EMPTY_STRING);
		byId.initialise(factory);
	}

	/**
	 * Returns the id associated with the given value.
	 *
	 * @param value the n3 value.
	 * @return the id associated with the given value.
	 * @throws StorageLayerException in case of data access failure.
	 */
	public byte[] getId(final String value) throws StorageLayerException {
		return byValue.get(value);
	}

	/**
	 * Returns the value associated with the given id.
	 *
	 * @param id the Cumulus internal id.
	 * @return the value associated with the given id.
	 * @throws StorageLayerException in case of data access failure.
	 */
	public String getValue(final byte[] id) throws StorageLayerException {
		return byId.get(id);
	}

	/**
	 * Puts the given pair on this index.
	 *
	 * @param value the resource.
	 * @param id the id associated with that resource.
	 * @throws StorageLayerException in case of data access failure.
	 */
	public void putEntry(final String value, final byte[] id) throws StorageLayerException {
		byValue.put(value, id);
		byId.put(id, value);
	}

	/**
	 * Returns true if this index contains the given id.
	 *
	 * @param id the id of a given resource.
	 * @return true if this index contains the given id.
	 * @throws StorageLayerException in case of data access failure.

	 */
	public boolean contains(final byte[] id) throws StorageLayerException {
		return byId.containsKey(id);
	}

	/**
	 * Removes the given resource from this index.
	 *
	 * @param value the n3 representation of the resource to be removed.
	 * @throws StorageLayerException in case of data access failure.
	 */
	public void remove(final String value) throws StorageLayerException {
		byId.remove(byValue.get(value));
		byValue.remove(value);
	}
}

redpajama_set_name: RedPajamaGithub


text:
author: alex
comments: true
date: 2013-06-03 14:58:12+00:00
layout: post
redirect_from: /2013/06/podcast-48-sponsored-by-powdermilk-biscuits
hero: /images/category/podcasts.jpg
slug: podcast-48-sponsored-by-powdermilk-biscuits
title: 'Podcast #48 - Sponsored by Powdermilk Biscuits'
wordpress_id: 13428
tags:
- company
- podcasts
---

Welcome to Stack Exchange Podcast #48! Our guest today is [Jorge Castro](http://jorgecastro.org/), member of the Community Team at [Canonical](http://www.canonical.com/) (of [Ubuntu](http://ubuntu.com/) fame). We also have Robert Cartaino, our very own Director of Community Development, here at Stack Exchange, as well as the usual suspects - David Fullerton, Jay Hanlon, and Joel Spolsky..  Our guest Jorge Castro works **on** Ubuntu, **at** Canonical. He says to pretend it's double Os instead of U's: Ooboontoo. (David, Jay, and Joel work **on** Stack Exchange, **at** Stack Exchange.)

  * So, Jorge! What does a Community Manager at Canonical do? What's the role, and what does that actually mean day to day?

  * At Canonical, the Community Team is a part of the _engineering_ department, not the marketing department. They are tasked with doing things that help engineers do their job and help people improve Ubuntu.

  * Jorge usually wears pants to work. Usually. The whole team is distributed, and they use IRC, Trello, and Google Hangouts to keep everything moving remotely.

  * This is all well and good, but what do community managers actually _do_? Nobody is really sure, either at Canonical or at Stack Exchange. Jorge walks us through the team's core responsibilities.

  * Robert gives his view on the core role of a Community Manager (by the way, we are [hiring community managers](http://stackexchange.com/about/hiring/community-manager-telecommute)!)

  * Jorge's team just terminated an experiment with crowdsourcing feature requests and ideas. It was the [Ubuntu Brainstorm](http://brainstorm.ubuntu.com/), and it was originally written by an enthusiast who just kind of decided that it should be done, and Ubuntu picked it up.

  * Side note: [You can't handle the Knuth](http://youcanthandletheknuth.com/).

  * To finish the Brainstorm story, last month it was decided that… it wasn't really working. The barrier to contributing to Ubuntu is getting lower and lower, so people with features to discuss can just show up to the Developer Summit. The moral of the story is that it's in the process of being shut down, but it's not ideal to just close all of the communication channels (because sometimes [users have great ideas](http://www.collegehumor.com/video/5941080/windows-7-parody)). We discuss the advantages and pitfalls of crowdsourced feature requests.

  * Jay bought [this](https://campaign.soylent.me/soylent-free-your-body) last week.

  * Anyway. The barrier to participate in Ubuntu is getting lower, so it's easier to get people_truly_ involved - instead of halfheartedly participating in the Brainstorm and _feeling_ like they're involved.

  * [Ask Ubuntu](http://askubuntu.com/) is one of our sites! It's our fourth biggest site by number of questions, with 140k questions, and 3rd for traffic with 231k visits per day. Jorge has been involved with it just about from the start, but he's not a moderator - just [a 20k user](http://askubuntu.com/users/235/jorge-castro).

  * One initial problem was the cyclical nature - every time a Ubuntu release came out, there was a flood of new users asking new questions and the answer rate plummeted to the bottom of the [list](http://stackexchange.com/sites). Then the review queue came and saved the world!

  * Jorge has a feature request: custom review queues. He even went through the proper channels and [proposed it on Meta](http://meta.stackoverflow.com/questions/156441/let-the-community-add-a-few-data-queries-to-the-review-queue)!

  * Robert walks us through Community Self-Evaluations. The system picks out a certain number of questions, and the community goes through and gauges whether or not the information available is better than the other information out there on the internet. We discuss it for a while.

  * So what's missing for Ask Ubuntu? What could we build that would make it work better? Jorge says the biggest problem the site is having right now is user confusion about what is a bug report and what's a configuration issue.

  *  Site launches! As of this recording, [Open Data](http://opendata.stackexchange.com/) and [Network Engineering](http://networkengineering.stackexchange.com/) are in public beta. Go check 'em out!

Thanks to [Jorge Castro](http://jorgecastro.org/) and Robert Cartaino for joining us, as well as the Usual Suspects (MINUS Producer Alex, who gets NO credit).


text:
// Copyright 2007-2011 The Apache Software Foundation.
//
// 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.
namespace Topshelf.Windows
{
	using System;
	using System.ComponentModel;
	using System.Diagnostics;
	using System.Reflection;
	using System.Security.Principal;
	using Logging;
	using Magnum.CommandLineParser;

	public static class WindowsUserAccessControl
	{
		static readonly ILog _log = Logger.Get("Topshelf.Windows.WindowsUserAccessControl");

		public static bool IsAdministrator
		{
			get
			{
				WindowsIdentity identity = WindowsIdentity.GetCurrent();

				if (null != identity)
				{
					var principal = new WindowsPrincipal(identity);
					return principal.IsInRole(WindowsBuiltInRole.Administrator);
				}

				return false;
			}
		}

		public static bool RerunAsAdministrator()
		{
			if (Environment.OSVersion.Version.Major == 6)
			{
				string commandLine = CommandLine.GetUnparsedCommandLine()
					.Replace("--sudo", "");

				var startInfo = new ProcessStartInfo(Assembly.GetEntryAssembly().Location,
				                                     commandLine)
					{
						Verb = "runas",
						UseShellExecute = true,
						CreateNoWindow = true
					};

				try
				{
					Logger.Shutdown();

					Process process = Process.Start(startInfo);
					process.WaitForExit();

					return true;
				}
				catch (Win32Exception ex)
				{
					_log.Debug("Process Start Exception", ex);
				}
			}

			return false;
		}
	}
}


text:
RemoteDebuggingServer::RemoteDebuggingServer(Profile* profile,
                                             const std::string& ip,
                                             int port,
                                             const std::string& frontend_url) {
  // Initialize DevTools data source.
  DevToolsUI::RegisterDevToolsDataSource(profile);

  devtools_http_handler_ =
      content::DevToolsHttpHandler::Start(ip,
                                          port,
                                          frontend_url,
                                          new BrowserListTabContentsProvider());
}

RemoteDebuggingServer::~RemoteDebuggingServer() {
  devtools_http_handler_->Stop();
}


text:
package test

import (
	"errors"

	"istio.io/mixer/pkg/adapter"
)

// Logger is a test struct that implements the application-logs and access-logs aspects.
type Logger struct {
	adapter.AccessLogsBuilder
	adapter.ApplicationLogsBuilder

	DefaultCfg     adapter.AspectConfig
	EntryCount     int
	Logs           []adapter.LogEntry
	AccessLogs     []adapter.LogEntry
	ErrOnNewAspect bool
	ErrOnLog       bool
}

// NewApplicationLogsAspect returns a new instance of the Logger aspect.
func (t *Logger) NewApplicationLogsAspect(e adapter.Env, m adapter.AspectConfig) (adapter.ApplicationLogsAspect, error) {
	if t.ErrOnNewAspect {
		return nil, errors.New("new aspect error")
	}
	return t, nil
}

// NewAccessLogsAspect returns a new instance of the accessLogger aspect.
func (t *Logger) NewAccessLogsAspect(e adapter.Env, m adapter.AspectConfig) (adapter.AccessLogsAspect, error) {
	if t.ErrOnNewAspect {
		return nil, errors.New("new aspect error")
	}
	return t, nil
}

// Name returns the official name of this builder.
func (t *Logger) Name() string { return "testLogger" }

// Description returns a user-friendly description of this builder.
func (t *Logger) Description() string { return "A test logger" }

// DefaultConfig returns a default configuration struct for this adapter.
func (t *Logger) DefaultConfig() adapter.AspectConfig { return t.DefaultCfg }

// ValidateConfig determines whether the given configuration meets all correctness requirements.
func (t *Logger) ValidateConfig(c adapter.AspectConfig) (ce *adapter.ConfigErrors) { return nil }

// Log simulates processing a batch of log entries.
func (t *Logger) Log(l []adapter.LogEntry) error {
	if t.ErrOnLog {
		return errors.New("log error")
	}
	t.EntryCount++
	t.Logs = append(t.Logs, l...)
	return nil
}

// LogAccess simulates processing a batch of access log entries.
func (t *Logger) LogAccess(l []adapter.LogEntry) error {
	if t.ErrOnLog {
		return errors.New("log access error")
	}
	t.EntryCount++
	t.AccessLogs = append(t.AccessLogs, l...)
	return nil
}

// Close does nothing at the moment.
func (t *Logger) Close() error { return nil }

// NewLogEntry creates an adapter.LogEntry instance.
func NewLogEntry(n string, l map[string]interface{}, ts string, s adapter.Severity, tp string, sp map[string]interface{}) adapter.LogEntry {
	return adapter.LogEntry{
		LogName:       n,
		Labels:        l,
		Timestamp:     ts,
		Severity:      s,
		TextPayload:   tp,
		StructPayload: sp,
	}
}


text:
<!DOCTYPE HTML>

		<title>Always Be My Maybe · Kevin Li</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<meta name="author" content="Kevin Li">
		<meta name="description" content="Personal Website, Portfolio, and Blog">
		<meta http-equiv="content-language" content="en-us" />

		<meta name="og:site_name" content="Kevin Li">
		<meta name="og:title" content="Always Be My Maybe">
		<meta name="og:url" content="http://kevinwli.com/tags/always-be-my-maybe/">
		<meta name="og:image" content="http://kevinwli.com/images/https://res.cloudinary.com/lilingkai/image/upload/s--tB1TDmk3--/c_scale,q_jpegmini:1,w_1600/v1492638792/Kevin_vk8jrp.jpg">

		<meta name="generator" content="Hugo 0.54.0" />

		<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		<link rel="stylesheet" href="http://kevinwli.com/css/main.css" />

		<link href="http://kevinwli.com/tags/always-be-my-maybe/index.xml" rel="alternate" type="application/rss+xml" title="Kevin Li" />
		<link href="http://kevinwli.com/tags/always-be-my-maybe/index.xml" rel="feed" type="application/rss+xml" title="Kevin Li" />

		<link rel="favicon" href="http://res.cloudinary.com/lilingkai/image/upload/v1480470082/favicon_v0tkdd.png">

Kevin Li
 Creator, Developer, Musician

Home

Resume

Blog

        Always Be My Maybe

<time datetime="2019-06-14 00:00:00 +0000 UTC">2019-06-14</time>

        Film Review

       Always Be My Maybe
       ·

       Nahnatchka Khan
       ·

       Ali Wong
       ·

       Randall Park
       ·

       Keanu Reeves
       ·

       Daniel Dae Kim
       ·

       James Saito
       ·

       PG-13
       ·

       2019
       ·

       PROJECT-FILM-52

Last month, Netflix released its much anticipated film, "Always Be My Maybe", and adds yet another notch to its growing list of original romantic comedies. While I always appreciate when a modern film is led by an Asian cast, I can't help but wish the film was more creative and cohesive.

GitHub

Linkedin

YouTube

Email

RSS

© Kevin Li

Design: HTML5 UP


text:
/* ###
 * IP: GHIDRA
 *
 * 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 ghidra.util.bytesearch;

/**
 * Represents a match of a DittedBitSequence at a given offset in a byte sequence.
 *
 * There is a hidden assumption that the sequence is actually a Pattern
 * that might have a ditted-bit-sequence, a set of match actions,
 * and post match rules/checks
 *
 */
public class Match {
	private DittedBitSequence sequence;	// Pattern that matched
	private long offset;			    // Offset within bytestream where the match occurred

	/**
	 * Construct a Match of a DittedBitSequence at an offset within a byte stream.
	 * Object normally used when a match occurs during a MemoryBytePatternSearch.
	 * @param sequence that matched
	 * @param offset from the start of byte stream where the matched occured
	 */
	public Match(DittedBitSequence sequence, long offset) {
		this.sequence = sequence;
		this.offset = offset;
	}

	/**
	 * If the sequence corresponds to a PatternPair, return the number of postbits
	 * @return the number of post bits
	 */
	public int getNumPostBits() {
		if (!(sequence instanceof Pattern)) {
			return 0;
		}
		int marked = ((Pattern) sequence).getMarkOffset();
		if (marked == 0) {
			return sequence.getNumFixedBits();
		}
		return sequence.getNumFixedBits() - sequence.getNumInitialFixedBits(marked);
	}

	/**
	 * @return actions associated with this match
	 */
	public MatchAction[] getMatchActions() {
		return ((Pattern) sequence).getMatchActions();
	}

	/**
	 * @return size in bytes of sequence
	 */
	public int getSequenceSize() {
		return sequence.getSize();
	}

	/**
	 * @return index of sequence in a possibly longer set of sequences
	 */
	public int getSequenceIndex() {
		return sequence.getIndex();
	}

	/**
	 * @return the offset of the match within a longer byte sequence
	 */
	public long getMarkOffset() {
		return offset + ((Pattern) sequence).getMarkOffset();
	}

	/**
	 * @return offset of match in sequence of bytes
	 */
	public long getMatchStart() {
		return offset;
	}

	/**
	 * Check that the possible post rules are satisfied
	 *
	 * @param streamoffset offset within from match location to check postrules.
	 *
	 * @return true if post rules are satisfied
	 */
	public boolean checkPostRules(long streamoffset) {
		long curoffset = streamoffset + offset;
		Pattern pattern = (Pattern) sequence;
		PostRule[] postRules = pattern.getPostRules();
		for (PostRule postRule : postRules) {
			if (!postRule.apply(pattern, curoffset)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @return ditted bit sequence as a string
	 */
	public String getHexString() {
		return sequence.getHexString();
	}

	/**
	 * @return the sequence that was matched
	 */
	public DittedBitSequence getSequence() {
		return sequence;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="shortcut icon" href="/static/img/favicon.ico{{ source_cache_key }}">
    <link rel="icon" type="image/png" href="/static/img/favicon.png{{ source_cache_key }}">
    <link rel="apple-touch-icon" href="/static/img/touch-icon-iphone.png{{ source_cache_key }}">
    <title data-ng-bind="lc.pageTitle()">RadiaSoft</title>
    <link href="/static/css/ext/bootstrap-3.3.7.min.css{{ source_cache_key }}" rel="stylesheet">
    <link href="/static/css/ext/bootstrap-colxl.css{{ source_cache_key }}" rel="stylesheet">
    <link href="/static/css/ext/bootstrap-toggle.min.css{{ source_cache_key }}" rel="stylesheet">
    <link href="/static/css/ext/cookieconsent.min.css{{ source_cache_key }}" rel="stylesheet">
    <link href="/static/css/landing-page.css{{ source_cache_key }}" rel="stylesheet">


text:
from __future__ import unicode_literals

from random import randint

from django.db import models
from django.db.models.aggregates import Count
from django.db.models.manager import Manager

class RandomGeoObjectManager(Manager):
    def _random_geo_object(self):
        count = self.aggregate(count=Count('id')).get('count')
        random_index = randint(0, count - 1)
        return self.all()[random_index]

    def country(self):
        geo_object = self._random_geo_object()
        return geo_object.name

    def capital(self):
        geo_object = self._random_geo_object()
        return geo_object.capital

class Country(models.Model):
    name = models.CharField(verbose_name=u"Cтрана", max_length=255, db_index=True)
    capital = models.CharField(verbose_name=u"Столица", max_length=255, db_index=True)
    random = RandomGeoObjectManager()
    objects = models.Manager()

    def __unicode__(self):
        return u"%s – %s" % (self.name, self.capital)


text:
[clappr](../../index.md) / [io.clappr.player.components](../index.md) / [Container](index.md) / [destroy](./destroy.md)

# destroy

`fun destroy(): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)


text:
extern ZCJoinSplit* params;

extern bool ReceivedBlockTransactions(
    const CBlock &block,
    CValidationState& state,
    const CChainParams& chainparams,
    CBlockIndex *pindexNew,
    const CDiskBlockPos& pos);

void ExpectOptionalAmount(CAmount expected, boost::optional<CAmount> actual) {
    EXPECT_TRUE((bool)actual);
    if (actual) {
        EXPECT_EQ(expected, *actual);
    }
}

// Fake an empty view
class FakeCoinsViewDB : public CCoinsView {
public:
    FakeCoinsViewDB() {}

    bool GetSproutAnchorAt(const uint256 &rt, SproutMerkleTree &tree) const {
        return false;
    }

    bool GetSaplingAnchorAt(const uint256 &rt, SaplingMerkleTree &tree) const {
        return false;
    }

    bool GetNullifier(const uint256 &nf, ShieldedType type) const {
        return false;
    }

    bool GetCoins(const uint256 &txid, CCoins &coins) const {
        return false;
    }

    bool HaveCoins(const uint256 &txid) const {
        return false;
    }

    uint256 GetBestBlock() const {
        uint256 a;
        return a;
    }

    uint256 GetBestAnchor(ShieldedType type) const {
        uint256 a;
        return a;
    }

    bool BatchWrite(CCoinsMap &mapCoins,
                    const uint256 &hashBlock,
                    const uint256 &hashSproutAnchor,
                    const uint256 &hashSaplingAnchor,
                    CAnchorsSproutMap &mapSproutAnchors,
                    CAnchorsSaplingMap &mapSaplingAnchors,
                    CNullifiersMap &mapSproutNullifiers,
                    CNullifiersMap saplingNullifiersMap) {
        return false;
    }

    bool GetStats(CCoinsStats &stats) const {
        return false;
    }
};

TEST(Validation, ContextualCheckInputsPassesWithCoinbase) {
    // Create fake coinbase transaction
    CMutableTransaction mtx;
    mtx.vin.resize(1);
    CTransaction tx(mtx);
    ASSERT_TRUE(tx.IsCoinBase());

    // Fake an empty view
    FakeCoinsViewDB fakeDB;
    CCoinsViewCache view(&fakeDB);

    for (int idx = Consensus::BASE_SPROUT; idx < Consensus::MAX_NETWORK_UPGRADES; idx++) {
        auto consensusBranchId = NetworkUpgradeInfo[idx].nBranchId;
        CValidationState state;
        PrecomputedTransactionData txdata(tx);
        EXPECT_TRUE(ContextualCheckInputs(tx, state, view, false, 0, false, txdata, Params(CBaseChainParams::MAIN).GetConsensus(), consensusBranchId));
    }
}

TEST(Validation, ReceivedBlockTransactions) {
    auto chainParams = Params();
    auto sk = libzcash::SproutSpendingKey::random();

    // Create a fake genesis block
    CBlock block1;
    block1.vtx.push_back(GetValidSproutReceive(*params, sk, 5, true));
    block1.hashMerkleRoot = block1.BuildMerkleTree();
    CBlockIndex fakeIndex1 {block1};

    // Create a fake child block
    CBlock block2;
    block2.hashPrevBlock = block1.GetHash();
    block2.vtx.push_back(GetValidSproutReceive(*params, sk, 10, true));
    block2.hashMerkleRoot = block2.BuildMerkleTree();
    CBlockIndex fakeIndex2 {block2};
    fakeIndex2.pprev = &fakeIndex1;

    CDiskBlockPos pos1;
    CDiskBlockPos pos2;

    // Set initial state of indices
    ASSERT_TRUE(fakeIndex1.RaiseValidity(BLOCK_VALID_TREE));
    ASSERT_TRUE(fakeIndex2.RaiseValidity(BLOCK_VALID_TREE));
    EXPECT_TRUE(fakeIndex1.IsValid(BLOCK_VALID_TREE));
    EXPECT_TRUE(fakeIndex2.IsValid(BLOCK_VALID_TREE));
    EXPECT_FALSE(fakeIndex1.IsValid(BLOCK_VALID_TRANSACTIONS));
    EXPECT_FALSE(fakeIndex2.IsValid(BLOCK_VALID_TRANSACTIONS));

    // Sprout pool values should not be set
    EXPECT_FALSE((bool)fakeIndex1.nSproutValue);
    EXPECT_FALSE((bool)fakeIndex1.nChainSproutValue);
    EXPECT_FALSE((bool)fakeIndex2.nSproutValue);
    EXPECT_FALSE((bool)fakeIndex2.nChainSproutValue);

    // Mark the second block's transactions as received first
    CValidationState state;
    EXPECT_TRUE(ReceivedBlockTransactions(block2, state, chainParams, &fakeIndex2, pos2));
    EXPECT_FALSE(fakeIndex1.IsValid(BLOCK_VALID_TRANSACTIONS));
    EXPECT_TRUE(fakeIndex2.IsValid(BLOCK_VALID_TRANSACTIONS));

    // Sprout pool value delta should now be set for the second block,
    // but not any chain totals
    EXPECT_FALSE((bool)fakeIndex1.nSproutValue);
    EXPECT_FALSE((bool)fakeIndex1.nChainSproutValue);
    {
        SCOPED_TRACE("ExpectOptionalAmount call");
        ExpectOptionalAmount(20, fakeIndex2.nSproutValue);
    }
    EXPECT_FALSE((bool)fakeIndex2.nChainSproutValue);

    // Now mark the first block's transactions as received
    EXPECT_TRUE(ReceivedBlockTransactions(block1, state, chainParams, &fakeIndex1, pos1));
    EXPECT_TRUE(fakeIndex1.IsValid(BLOCK_VALID_TRANSACTIONS));
    EXPECT_TRUE(fakeIndex2.IsValid(BLOCK_VALID_TRANSACTIONS));

    // Sprout pool values should now be set for both blocks
    {
        SCOPED_TRACE("ExpectOptionalAmount call");
        ExpectOptionalAmount(10, fakeIndex1.nSproutValue);
    }
    {
        SCOPED_TRACE("ExpectOptionalAmount call");
        ExpectOptionalAmount(10, fakeIndex1.nChainSproutValue);
    }
    {
        SCOPED_TRACE("ExpectOptionalAmount call");
        ExpectOptionalAmount(20, fakeIndex2.nSproutValue);
    }
    {
        SCOPED_TRACE("ExpectOptionalAmount call");
        ExpectOptionalAmount(30, fakeIndex2.nChainSproutValue);
    }
}


text:
'use strict';

const express = require('express');
const mongoose = require('mongoose');

const utils = require('../utils');

const SequenceElementModel = require('../../models/location');

exports.getSequenceElements = function(owner, callback) {
	SequenceElementModel.find({
		owner: owner
	}, function(err, sequenceElementObjects) {
		if (err) {
			if (typeof callback === 'function') {
				callback(err);
			}
		} else {
			let responseObjects = [];

			sequenceElementObjects.forEach(function(e) {
				const responseObj = {
					id: e._id,
					type: e.type,
					value: e.referenceID,
					day: e.dayID
				};
				responseObjects.push(responseObj);
			});

			if (typeof callback === 'function') {
				callback(null, {'sequence-elements': responseObjects});
			}
		}
	});
};

exports.getSequenceElement = function (sequenceElementID, owner, callback) {
	SequenceElementModel.findOne({
		_id: sequenceElementID,
		owner: owner
	}, function(err, sequenceElementObj) {
		if (err) {
			if (typeof callback === 'function') {
				callback(err);
			}
		} else {
			const responseObj = {
				id: sequenceElementObj._id,
				type: sequenceElementObj.type,
				value: sequenceElementObj.referenceID,
				day: sequenceElementObj.dayID
			};

			if (typeof callback === 'function') {
				callback(null, {'sequence-element': responseObj});
			}
		}
	});
};

exports.updateSequenceElement = function(sequenceElement, sequenceElementID, owner, callback) {
	const _sequenceElement = {
		id: sequenceElementID,
		type: sequenceElement.type,
		value: sequenceElement.referenceID,
		day: sequenceElement.dayID
	};

	SequenceElementModel.update({
		_id: sequenceElementID,
		owner: owner
	}, {
		$set: _sequenceElement
	}, function(err, sequenceElementObj) {
		if (err) {
			if (typeof callback === 'function') {
				callback(err);
			}
		} else {

			const responseObj = {
				id: sequenceElementObj._id,
				type: sequenceElementObj.type,
				value: sequenceElementObj.referenceID,
				day: sequenceElementObj.dayID
			};

			if (typeof callback === 'function') {
				callback(null, {'sequence-element': responseObj});
			}
		}
	});
};


text:
maintainer       "Bryan W. Berry"
maintainer_email "bryan.berry@gmail.com"
license          "Apache 2.0"
description      "Installs/Configures maven"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "0.3.1"

depends "java"
depends "ark"

%w{ debian ubuntu centos redhat fedora }.each do |os|
  supports os
end


text:
using Mono.Cecil;
using System.Collections.Generic;

namespace Harmony.Sdk
{
    /// <summary>
    /// Project is a set of assemblies which should be weaved in same scope
    /// </summary>
	public class FileDefinition
	{
	}
}


text:
package wavefrontexporter

// TODO: Add tests.


text:
title: 'Vmware Fusion, changer l'adressage des réseaux vmnet'
author: Jerome
layout: post
permalink: /vmware-fusion-changer-ladressage-des-reseaux-vmnet
lightboxoff:
  - 'false'
categories:
  - Virtulisation
---
Si comme moi, certains réseaux virtuel de Vmware Fusion sont les mêmes que des réseaux existant sur votre LAN, et que vous en avez assez de changer manuellement l'adresse IP de la carte vmnetx, alors ce tuto est fait pour vous !

Pour cela très simple, ouvrez un Terminal, puis executez les commandes suivantes :

cd /Library/Application\ Support/VMware\ Fusion/

Les deux fichiers à modifier sont « locations » et « networking » :

vim locations

Ensuite on change les occurences (ici on modifie l’adresse de la carte en 50.1 par 60.1)

:%s/192.168.50.1/192.168.60.1/g

Sans oublier d’enregistrer

:wq

On passe ensuite au réseau

sudo vim networking

On change également les occurences

:%s/192.168.50.0/192.168.60.0/g

Et on enregistre

:wq

Ensuite il suffit de relancer les services Vmware et c’est terminé.

sudo /Library/Application Support/VMware Fusion/boot.sh  --restart


text:
using System;
using System.Collections.Generic;
using System.Security.Claims;
using SimpleBasicAuthentication.Domain.Users;

namespace SimpleBasicAuthentication.Security.Users
{
	public class UserClaimsFactory
		: IUserClaimsFactory
	{
		public IEnumerable<Claim> Create(User user)
		{
			if (string.IsNullOrWhiteSpace(user.Username))
				throw new ArgumentNullException(nameof(user.Username), "Username is null");
			return new List<Claim>
			{
				new Claim(ClaimTypes.Name, user.Username),
				new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
			};
		}
	}
}


text:
export class TwitterApplicationComponent implements ng.IComponentOptions {
    public template: string = `

                    <button type="button"
                    class="navbar-toggle collapsed"
                    data-toggle="collapse"
                    data-target="#navbar"
                    aria-expanded="false"
                    aria-controls="navbar">
                        Toggle navigation

                    </button>
                    Tweet app

Tweets

About

`;
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

#pragma warning disable 1591

namespace Sitecore.Shell.Client.Metro.Layouts.Renderings.Buttons.MetroBreadcrumbs
{
  #region Designer generated code

  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
  public partial class MetroBreadcrumbRenderingModel : Sitecore.Mvc.Presentation.SpeakRenderingModel
  {
    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string AccessKey { get { return this.GetString("AccessKey"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Active { get { return this.GetString("Active"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Behaviors { get { return this.GetString("Behaviors"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string DisplayFieldName { get { return this.GetString("DisplayFieldName"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string IconFieldName { get { return this.GetString("IconFieldName"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Id { get { return this.GetString("Id"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public bool IsVisible { get { return this.GetBool("IsVisible", true); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string LinkFieldName { get { return this.GetString("LinkFieldName"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Size { get { return this.GetString("Size"); } }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("SitecoreRocks", "1.0.0.0")]
    public string Tooltip { get { return this.GetString("Tooltip"); } }
  }

  #endregion
}

#pragma warning restore 1591


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        {% if page_description %}<meta name="description" content="{{ page_description }}">{% endif %}
        {% if site_author %}<meta name="author" content="{{ site_author }}">{% endif %}
        {% if canonical_url %}<link rel="canonical" href="{{ canonical_url }}">{% endif %}
        {% if favicon %}<link rel="shortcut icon" href="{{ favicon }}">
        {% else %}<link rel="shortcut icon" href="/img/favicon.ico">{% endif %}

        <link rel="apple-touch-icon" href="img/apple-touch-icon.png">

   <title>Not Found - {{ site_name }}</title>
        <link href="/css/bootstrap-custom.css" rel="stylesheet">
        <link href="/css/font-awesome-4.5.css" rel="stylesheet">
        <link rel="stylesheet" href="/css/highlight.css">
        <link href="/css/base.css" rel="stylesheet">
        <link href="/css/gdc-common.css" rel="stylesheet">
        {%- for path in extra_css %}
        <link href="{{ path }}" rel="stylesheet">
        {%- endfor %}

        {% if google_analytics %}

        {% endif %}

            {% include "nav.html" %}

                {% include "search.html" %}

 Looking for the Requested Page...

                                Sorry the Page Cannot be Found!

                                Sorry, we couldn't find the page you were looking for. If you believe this is an error please contact us at
                                dcc-support@icgc.org.

                                Looks Like this Page Moved!

                                    We are redirecting you to the requested page in  seconds.

                                    Optionally you can also click on  to go there now.

                            Site Home
                            | Policies
                            | Accessibility
                            | FOIA

                            U.S. Department of Health and Human Services
                            | National Institutes of Health
                            | National Cancer Institute
                            | USA.gov

                            NIH... Turning Discovery Into Health ®

                        {% if config.extra.version %}

                            {{ site_name }} Version {{ config.extra.version }}

                        {% endif %}

            {%- for path in extra_javascript %}

            {%- endfor %}


text:
namespace OpenGLGUI {

	Brush::~Brush()
	{
	}

	void Brush::activate()
	{
		shader->enable();
	}

	void Brush::deactivate()
	{
		shader->disable();
	}

	void Brush::setUniform2f(const std::string & uniformName, glm::vec2 data)
	{
		shader->setUniform2f(uniformName, data);
	}
	void Brush::setUniform3f(const std::string & uniformName, glm::vec3 data)
	{
		shader->setUniform3f(uniformName, data);
	}
	void Brush::setUniform4f(const std::string & uniformName, glm::vec4 data)
	{
		shader->setUniform4f(uniformName, data);
	}
}


text:
import { format } from 'd3-format';

/**
 * Sprintf like function.
 * Replaces placeholders {0} in string with values from provided object.
 *
 * @param string formatted String containing placeholders.
 * @param object args Object with properties to replace placeholders in string.
 *
 * @return String
 */
export function formatStringWithObject(string, args) {
  let formattedString = string;

  Object.entries(args).forEach(([key, value]) => {
    formattedString = formattedString.replace(
      new RegExp(`\\{${key}\\}`, 'gi'),
      value,
    );
  });
  return formattedString;
}

/**
 * Return a classname if the specified date should be highlighted
 *
 * @param  int timestamp Unix timestamp of the current subDomain
 * @return String the highlight class
 */
export function getHighlightClassName(calendar, timestamp, options) {
  const { highlight, subDomain } = options;
  let classname = '';

  if (highlight.length > 0) {
    highlight.forEach((d) => {
      if (
        calendar.helpers.DateHelper.datesFromSameInterval(
          subDomain,
          +d,
          timestamp,
        )
      ) {
        classname = calendar.helpers.DateHelper.datesFromSameInterval(
          subDomain,
          +d,
        ) ?
          ' highlight-now' :
          ' highlight';
      }
    });
  }

  return classname;
}

/**
 * Expand a number of an array of numbers to an usable 4 values array
 *
 * @param  {integer|array} value
 * @return {array}        array
 */
export function expandMarginSetting(settings) {
  let value = settings;
  if (typeof value === 'number') {
    value = [value];
  }

  if (!Array.isArray(value) || !value.every((d) => typeof d === 'number')) {
    // eslint-disable-next-line no-console
    console.log('Margin only accepts an integer or an array of integers');
    value = [0];
  }

  switch (value.length) {
    case 1:
      return [value[0], value[0], value[0], value[0]];
    case 2:
      return [value[0], value[1], value[0], value[1]];
    case 3:
      return [value[0], value[1], value[2], value[1]];
    default:
      return value.slice(0, 4);
  }
}

export function getSubDomainTitle(calendar, d, options, connector) {
  if (d.v === null && !options.considerMissingDataAsZero) {
    return formatStringWithObject(options.subDomainTitleFormat.empty, {
      date: calendar.helpers.DateHelper.format(
        d.t,
        options.subDomainDateFormat,
      ),
    });
  }
  let value = d.v;
  // Consider null as 0
  if (value === null && options.considerMissingDataAsZero) {
    value = 0;
  }

  return formatStringWithObject(options.subDomainTitleFormat.filled, {
    count: format(',d')(value),
    name: options.itemName[value !== 1 ? 1 : 0],
    connector,
    date: calendar.helpers.DateHelper.format(d.t, options.subDomainDateFormat),
  });
}


text:
author: Herbert Ilhan Tanujaya
categories:
  - Digest
date: 2017-11-12T00:00:00.000Z
title: "Digest: Pivot Tables in SQL - Converting Rows to Columns"
tags:
  - SQL
  - pivot tables
url: /2017/11/digest-pivot-tables-in-sql-converting-rows-to-columns
aliases:
  - /2017/11/12/digest-pivot-tables-in-sql-converting-rows-to-columns
---

(This post is cross-posted from //herbert.id/2017/11/pivot-tables-in-sql/.)

A few weeks ago I gave a talk at NUS Hackers's Friday Hacks on some advanced
tips in using SQL. (It was my first technical talk, btw!) Here, I will elaborate
upon one of those tips in more detail.

# Background

I have been working on a website that hosts math olympiad contests monthly.
(Shameless plug - source code at https://github.com/donjar/kontes-terbuka,
website at https://ktom.tomi.or.id. Even though it is in Bahasa Indonesia,
Google Translate gives a good enough translation.) In each contest, there are
several structured questions that a contestant can solve.  The schema is
something like this:

Submissions:

- id: primary key
- user_id: foreign key to users
- problem_id: foreign key to problems
- score: integer

(There is some sample SQL data that can be found
[here](https://github.com/donjar/sql-wizardry). The file `dump.sql` is of your
interest; check out the `contest_scores` table. The file
`contest_pivot_table.sql` is the solution to the problem below. This repo was
originally made for my SQL Wizardry presentation.)

# Problem

Let's say the current data looks like this:
```
 id | user_id | problem_id | score
----+---------+------------+-------
  1 |       1 |          1 |     3
  2 |       1 |          2 |     8
  3 |       1 |          3 |     1
  4 |       2 |          1 |     7
  5 |       2 |          2 |     3
  6 |       2 |          3 |     3
  7 |       3 |          1 |     4
  8 |       3 |          2 |     2
  9 |       3 |          3 |     3
 10 |       4 |          1 |     7
 11 |       4 |          2 |     5
 12 |       5 |          1 |     4
 13 |       5 |          3 |     7
 14 |       6 |          2 |     3
 15 |       6 |          3 |     4
 16 |       7 |          1 |     4
 17 |       7 |          2 |     4
 18 |       7 |          3 |     9
 19 |       8 |          1 |     7
 20 |       8 |          2 |     2
 21 |       8 |          3 |     4
 22 |       9 |          1 |     8
 23 |       9 |          2 |     0
 24 |       9 |          3 |     4
 25 |      10 |          1 |     3
 26 |      10 |          2 |     3
 27 |      10 |          3 |     6
```

Obviously data like this is not suitable to be shown to the end user. What we
want is something like this:
```
 user_id | problem_1 | problem_2 | problem_3
---------+-----------+-----------+-----------
       1 |         3 |         8 |         1
       2 |         7 |         3 |         3
       3 |         4 |         2 |         3
       4 |         7 |         5 |
       5 |         4 |           |         7
       6 |           |         3 |         4
       7 |         4 |         4 |         9
       8 |         7 |         2 |         4
       9 |         8 |         0 |         4
      10 |         3 |         3 |         6
```

Notice that this involves converting rows of the table into columns: in this
case, the `problem_id` needs to be "split" into `problem_1`, `problem_2`, and
`problem_3`.

You can't do this with a normal SQL SELECT statement! Normally, when you select
columns, you can only select based on operations on the existing columns. There
are no operations that allow you to convert rows into columns in this way.

You can work around this with table joins though, for example:
```sql
WITH (
  SELECT
    user_id,
    problem_1 AS score
  FROM submissions
  WHERE
    problem_id = 1
) AS problem_1_table, (
  SELECT
    user_id,
    problem_2 AS score
  FROM submissions
  WHERE
    problem_id = 2
) AS problem_2_table, (
  SELECT
    user_id,
    problem_3 AS score
  FROM submissions
  WHERE
    problem_id = 3
) AS problem_3_table

SELECT
  problem_1_table.user_id,
  problem_1,
  problem_2,
  problem_3
FROM problem_1_table
FULL OUTER JOIN problem_2_table
ON problem_1_table.user_id = problem_2_table.user_id
FULL OUTER JOIN problem_3_table
ON problem_1_table.user_id = problem_3_table.user_id
```

Basically, `problem_1_table` is a table that contains the (`user_id`, `score`)
pair for submissions with `problem_id = 1`, and so on. Afterwards, we join with
them on the `user_id` to produce the table we want.

In fact, this was our original approach to the problem! The website was built
with Ruby on Rails, and we used a loop in Ruby to loop through all problems and
generate the corresponding SQL query. I would see SQL queries like this often:

```sql
SELECT user_contests.*, marks.short_mark, marks.long_mark, marks.total_mark,
case when marks.total_mark >= gold_cutoff then 'Emas' when marks.total_mark >=
silver_cutoff then 'Perak' when marks.total_mark >= bronze_cutoff then
'Perunggu' else '' end as award, "long_problem_marks_269"."problem_no_269",
"long_problem_marks_271"."problem_no_271",
"long_problem_marks_270"."problem_no_270",
"long_problem_marks_268"."problem_no_268", RANK() OVER(ORDER BY
marks.total_mark DESC) AS rank FROM "user_contests" INNER JOIN "contests" ON
"contests"."id" = "user_contests"."contest_id" INNER JOIN "users" ON
"users"."id" = "user_contests"."user_id" INNER JOIN (SELECT user_contests.*,
short_marks.short_mark, long_marks.long_mark, (short_marks.short_mark +
long_marks.long_mark) as total_mark FROM "user_contests" INNER JOIN (SELECT
user_contests.id as id, sum(case when short_submissions.answer =
short_problems.answer then 1 else 0 end) as short_mark FROM "user_contests"
LEFT OUTER JOIN "short_submissions" ON "short_submissions"."user_contest_id" =
"user_contests"."id" LEFT OUTER JOIN "short_submissions"
"short_submissions_user_contests_join" ON
"short_submissions_user_contests_join"."user_contest_id" = "user_contests"."id"
LEFT OUTER JOIN "short_problems" ON "short_problems"."id" =
"short_submissions_user_contests_join"."short_problem_id" WHERE
"user_contests"."contest_id" = 29 AND ("short_submissions"."short_problem_id" =
"short_problems"."id" OR ("short_submissions"."short_problem_id" IS NULL AND
"short_problems"."id" IS NULL)) GROUP BY "user_contests"."id") short_marks ON
"user_contests"."id" = "short_marks"."id" INNER JOIN (SELECT user_contests.id
as id, sum(coalesce(long_submissions.score, 0)) as long_mark FROM
"user_contests" LEFT OUTER JOIN "long_submissions" ON
"long_submissions"."user_contest_id" = "user_contests"."id" WHERE
"user_contests"."contest_id" = 29 GROUP BY "user_contests"."id") long_marks ON
"user_contests"."id" = "long_marks"."id" WHERE "user_contests"."contest_id" =
29) marks ON "user_contests"."id" = "marks"."id" LEFT OUTER JOIN (SELECT
user_contests.id as id, long_submissions.score as problem_no_269 FROM
"user_contests" LEFT OUTER JOIN "long_submissions" ON
"long_submissions"."user_contest_id" = "user_contests"."id" WHERE
"long_submissions"."long_problem_id" = 269) long_problem_marks_269 ON
"user_contests"."id" = "long_problem_marks_269"."id" LEFT OUTER JOIN (SELECT
user_contests.id as id, long_submissions.score as problem_no_271 FROM
"user_contests" LEFT OUTER JOIN "long_submissions" ON
"long_submissions"."user_contest_id" = "user_contests"."id" WHERE
"long_submissions"."long_problem_id" = 271) long_problem_marks_271 ON
"user_contests"."id" = "long_problem_marks_271"."id" LEFT OUTER JOIN (SELECT
user_contests.id as id, long_submissions.score as problem_no_270 FROM
"user_contests" LEFT OUTER JOIN "long_submissions" ON
"long_submissions"."user_contest_id" = "user_contests"."id" WHERE
"long_submissions"."long_problem_id" = 270) long_problem_marks_270 ON
"user_contests"."id" = "long_problem_marks_270"."id" LEFT OUTER JOIN (SELECT
user_contests.id as id, long_submissions.score as problem_no_268 FROM
"user_contests" LEFT OUTER JOIN "long_submissions" ON
"long_submissions"."user_contest_id" = "user_contests"."id" WHERE
"long_submissions"."long_problem_id" = 268) long_problem_marks_268 ON
"user_contests"."id" = "long_problem_marks_268"."id" WHERE
"user_contests"."contest_id" = 29 AND "users"."province_id" = 35  ORDER BY
"marks"."total_mark" DESC
```

It wasn't very pretty Ruby and SQL code, but hey, it works. But of course, this
does not sit really well with me - using Ruby to generate SQL and using that
generated code to query data seems weird, isn't it?

Of course we can just select all data in SQL and do the processing in Ruby on
Rails. However, as the saying goes - do the data processing in the database
level, where it is suitable for the job right?

Enter pivot tables.

# Pivot Tables

You might have heard about pivot tables from Microsoft Excel. To quote
Wikipedia:

> A pivot table is a table that summarizes data in another table, and is made
> by applying an operation such as sorting, averaging, or summing to data in
> the first table, typically including grouping of the data.

The "grouping of the data" is of interest here.

## Caveat

Pivot tables have different implementations across different databases. I am
only going to discuss how to do it in PostgreSQL, as that is the database I am
using in my application. You should be able to find implementations for other
databases by searching for something like "pivot tables MySQL".

## Crosstab

In PostgreSQL, the relevant function is called "crosstab". It is available as
an extension, and hence, you should install it first by running `CREATE
EXTENSION tablefunc;` as a superuser.

The relevant documentation can be found
[here](https://www.postgresql.org/docs/10/static/tablefunc.html). One thing you
might notice, though, is that there are actually four different crosstab
functions!

The functions are actually generating pivot tables, only with different
abstraction levels. I found that the `crosstab(text source_sql,
text category_sql)` function produces the result I needed. To quote the
documentation:

> `source_sql` is a SQL statement that produces the source set of data. This
> statement must return one `row_name` column, one category column, and one
> value column. It may also have one or more "extra" columns. The `row_name`
> column must be first. The category and value columns must be the last two
> columns, in that order. Any columns between `row_name` and category are
> treated as "extra". The "extra" columns are expected to be the same for all
> rows with the same `row_name` value.

So basically, `source_sql` is in the form:
```sql
SELECT key(s), categories, values FROM ...
```
and the `category_sql` matches the values that we want in the category to
separate.

An example will make these concepts clearer. Going to the example we discussed
previously, we notice that the key is the `user_id` - basically, this is the
column we want as our first column. The category is `problem_id`, since
this is what we want the next columns of the resulting pivot table to be. And
finally, the values to be filled in inside the resulting table would be `score`.
It is normal to use an `ORDER BY key` as well here, so that the resulting pivot
table is not jumbled. Combining all of them, we have this `source_sql` query:
```sql
SELECT user_id, problem_id, score FROM submissions ORDER BY user_id
```

For the category, we know that the problem IDs we want are 1, 2, and 3. Hence,
the corresponding `category_sql` is:
```sql
SELECT 1, 2, 3
```
(in reality we would want something like `SELECT id FROM problems ORDER BY id`).

And at the end, we would need to specify the columns to be generated as well,
with this format:
```sql
("column1" category1, "column2" category2, ...)
```

In this case, it would be:
```sql
("user_id" int, "problem_1" int, "problem_2" int, "problem_3" int)
```

Hence, the resulting SQL query is:
```sql
SELECT * FROM crosstab(
  'SELECT user_id, problem_id, score FROM submissions ORDER BY user_id',
  'SELECT 1, 2, 3'
) AS (
  "user_id" int,
  "problem_1" int,
  "problem_2" int,
  "problem_3" int
)
```

This will return just what we wanted!

## Problems

While this query is "cleaner" than the SQL joins "workaround" I wrote
previously, there are still some problems with this solution. Firstly, there
is a need to specify the columns in the resulting pivot table. While this can
also be generated with the underlying framework (with Ruby etc.), we still need
to query two times: once to get the column definitions (for example, `SELECT
id FROM problems`), and once to do the actual crosstab query. If I remember
correctly, this problem is not specific to PostgreSQL; other databases also have
this problem. This solution will not solve the problem of using the application
to craft SQL queries.

The other problem which might not be obvious is about ORMs - it is highly
unlikely that ORMs have support for pivot tables. This may cause problems with
using ORM tools - for example, while ActiveRecord (the ORM in Ruby on Rails)
has a `find_by_sql` method, chaining it with another ActiveRecord method can
cause bugs. In my case, `Submissions.find_by_sql(crosstab_query).count` does
not work (as I assume Rails doesn't know where to put the `COUNT` query).

With two queries running, performance might also be a problem. From my
observations, the SQL joins query takes around 70 ms, while these two queries
take around 50 ms in total; however, this does not account for network overheads
etc. A more systematic benchmarking is needed to confirm if this solution is
indeed faster than the joining solution.

# Conclusion

If you need to somehow convert rows into columns, and vice versa, to do
grouping/aggregation, pivot tables might be for you. While several problems
exist, I still believe that pivot table is the right tool for the job and the
resulting solution is "cleaner".


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ca.szc.keratin</groupId>
  <artifactId>keratin-bot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>Keratin Bot</name>
  <description>Keratin IRC Bot Framework</description>
  <url>https://github.com/ASzc/keratin-irc</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <licenses>
    <license>
      <name>MIT</name>
      <url>http://opensource.org/licenses/MIT</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <developers>
    <developer>
      <id>ASzc</id>
      <name>Alex Szczuczko</name>
      <email>alex@szc.ca</email>
      <url>http://szc.ca</url>
      <roles>
        <role>developer</role>
      </roles>
      <timezone>-5</timezone>
    </developer>
  </developers>

  <scm>
    <connection>scm:git:https://github.com/ASzc/keratin-irc.git</connection>
    <developerConnection>scm:git:ssh://git@github.com:ASzc/keratin-irc.git</developerConnection>
    <url>https://github.com/ASzc/keratin-irc</url>
  </scm>

  <issueManagement>
    <system>GitHub</system>
    <url>https://github.com/ASzc/keratin-irc/issues</url>
  </issueManagement>

  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
      <plugin>
        <groupId>com.mycila.maven-license-plugin</groupId>
        <artifactId>maven-license-plugin</artifactId>
        <version>1.9.0</version>
        <configuration>
          <header>license-header.txt</header>
          <strictCheck>true</strictCheck>
          <includes>
            <include>src/**</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>ca.szc.keratin</groupId>
      <artifactId>keratin-core</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.tinylog</groupId>
      <artifactId>tinylog</artifactId>
      <version>0.8</version>
    </dependency>
    <dependency>
      <groupId>eu.infomas</groupId>
      <artifactId>annotation-detector</artifactId>
      <version>3.0.4</version>
    </dependency>
  </dependencies>
</project>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <jakevin.com.jkcalendar_lib.ui.JKCalendar
        android:id="@+id/main_calendar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>


text:
AliAnalysisTaskSE* AddTaskZDCTree(Bool_t  applyPS = kTRUE,
				  TString outfname = "ZDCpPb",
				  Bool_t  isMC = kFALSE)
{

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if(!mgr){
    ::Error("AddTaskZDCPbPb", "No analysis manager to connect to.");
    return NULL;
  }

  AliVEventHandler *inputHandler = mgr->GetInputEventHandler();

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if(!inputHandler){
    ::Error("AddTaskZDCPbPb", "This task requires an input event handler");
    return NULL;
  }
  TString inputDataType = inputHandler->GetDataType(); // can be "ESD" or "AOD"

   // Configure analysis
   //===========================================================================
   AliAnalysisTaskZDCTreeMaker* task = new AliAnalysisTaskZDCTreeMaker("taskZDC");

   if(inputDataType.CompareTo("ESD")==0){
      task->SetInput(1);
      //printf("  AliAnalysisTaskZDCTreeMaker initialized for ESD analysis\n");
      //
      // apply physics selection
      if(applyPS) task->SelectCollisionCandidates();
   }
   else if(inputDataType.CompareTo("AOD")==0){
      task->SetInput(2);
      //printf("  AliAnalysisTaskZDCTreeMaker initialized for AOD analysis\n");
   }

   if(isMC==kTRUE) task->SetMCInput();

   mgr->AddTask(task);

   TString outputFileName = AliAnalysisManager::GetCommonFileName();

   AliAnalysisDataContainer *coutput  = mgr->CreateContainer(outfname.Data(),
   					TList::Class(),
					AliAnalysisManager::kOutputContainer,
					Form("%s:ZDCHistos", mgr->GetCommonFileName()));

   mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
   mgr->ConnectOutput (task, 1, coutput);

   return task;
}


text:
<?php
// LOGIN.PHP - Handles login form processing

// Start a session to store user data
session_start();
require_once "includes/functions.php"; // For getClientIP(), formRedirectBack(), sendVerifToken(), denyAccess()

if(isset($_POST['login'])) {
    $ip = getClientIP();
    $user_email = htmlspecialchars($_POST["log_email"]);
    $password = md5(htmlspecialchars($_POST["log_password"]));
    $login_success = 0;

    // Open DB connection ($link)
    require "db/main_db_open.php";

    // Check e-mail/password against database
    $query = "SELECT * FROM reg_users WHERE email='" . $user_email ."' AND password='" . $password . "';";
    $result = mysql_query($query);
    if(mysql_numrows($result) != 1) {
        // If the e-mail and password combination was not found in database
        denyAccess();
        $_SESSION['message'] = 'Incorrect e-mail or password. If you have forgot your password please click the "Forgot Password" link.';
        $header = "location: /register.html";
        header($header);
    }
    else {
        // Fetch user account status
        $user_stat = mysql_result($result, 0, "user_stat");

        if ($user_stat == 'X')
        {
            denyAccess();
            $_SESSION['message'] = 'The account registered under the e-mail ' . $user_email . ' has been banned. Please contact us for more information.';
            formRedirectBack();
        }
        else if($user_stat == 'U')
        {
            denyAccess();
            $_SESSION['message'] = 'The account registered under the e-mail ' . $user_email . ' has not been verified. The activation message has been resent - please check your e-mail inbox for the message containing a link to complete your registration.';

            // E-mail the verification link to the user. User must click the link in order to verify their e-mail address and use the site.
            sendVerifToken($user_email);
            formRedirectBack();
        }
        else
        {
            // Fetch rank
            $rank = mysql_result($result, 0, "rank");
            $token = generateToken($user_email);

            // Set session variables
            $_SESSION['userid'] = mysql_result($result, 0, "id");
            $_SESSION['firstname'] = mysql_result($result, 0, "first_name");
            $_SESSION['lastname'] = mysql_result($result, 0, "last_name");
            $_SESSION['email'] = mysql_result($result, 0, "email");
            $_SESSION['rank'] = $rank;
            $_SESSION['status'] = 1;
            $_SESSION['token'] = $token;
            $_SESSION['message'] = 'Login successful.';
            $_SESSION['current_task']['ct_task_id'] = mysql_result($result, 0, "current_task");
            $login_success = 1;

            // Set last_login
            $query = "UPDATE reg_users SET last_login='" . date('Y-m-d H:i:s') . "' WHERE email='" . $user_email . "';";
            mysql_query($query);

            // Set token
            $query = "UPDATE reg_users SET token='" . $token . "' WHERE email='" . $user_email . "';";
            mysql_query($query);

            // Set token_validity
            $query = "UPDATE reg_users SET token_validity='" . getTokenTimeout() . "' WHERE email='" . $user_email . "';";
            mysql_query($query);

            // Redirect back to referring page
            formRedirectBack();
        }
    }

    // Create login_attempt entry
    mysql_query("INSERT INTO reg_login_attempt(ip, email, login_success) VALUES ('$ip','$user_email', '$login_success')") or die("".mysql_error());

    // Close DB connection
    require "db/main_db_close.php";
}
else
{
    denyAccess();
    $_SESSION['message'] = 'Error logging in.';
    $header = "location: /register.html";
    header($header);
}

exit;
?>


text:
normal_exit=n
function my_die() {
	echo "ERROR occured: $*"
	normal_exit='y'
	exit 1
}

argument_input="$1"
shift
if ! [[ -r "$argument_input" ]] ; then my_die "Can not read input file ($argument_input)" ; fi

tempdir=''

function cleanup() {
	fname="$tempdir"
	if [[ $normal_exit != 'y' ]] ; then echo "Deleting ($fname)" ; fi
}
trap cleanup EXIT

tempdir=$(mktemp -d)
if [[ ! -d "$tempdir" ]] ; then my_die "Temp dir failed ($tempdir)" ; fi
chmod 700 "$tempdir" || my_die "Rights on temp dir failed ($tempdir)"

function change_one_setting() {
	N="$1" # name like CONFIG_EDAC_DEBUG
	V="$2" # value like 'y' ; sed -e "s/# $N is not set/$N=$V/"
	if ! [[ $N =~ [A-Z][A-Z0-1]* ]] ; then
			my_die "Bad name of option ($N)"
	fi

	if [[ -z "$V" ]] ; then echo "Warning: empty value used for option ($N)" ; fi
	if [[ "$V" == 'n' ]] ; then echo "Warning: value 'n' is used, if you want to configure option to No then set it to value '-' (minus sign). In option ($N)" ; fi
	if [[ "$V" == 'N' ]] ; then echo "Warning: value 'N' is used, if you want to configure option to No then set it to value '-' (minus sign). In option ($N)" ; fi

#	if [[ $V =~ .*\".* ]] ; then my_die "Do NOT use quotation markers in the value (sorry we do not support multi-word edits now yet, but it's easy to hack in just use function change_one_setting" ; fi

#	if [[ $V =~ .*\'.*\'* ]] ; then my_die "Do NOT use quotation markers in the value (sorry we do not support multi-word edits now yet, but it's easy to hack in just use function change_one_setting" ; fi
	# this above regexp is just: .*\'.* meaning .*'.* so any string that contains single-quote (') character, the additional string '* at end is just to fix some source code editors that get confused here (e.g. vim in debian 7)

	if [[ $V == '-' ]] ;
	then
		sed -e "s/^# $N is not set\$/# $N is not set/" < "$argument_input" > "$tempdir/new1"
		sed -e "s/^$N=.*\$/# $N is not set/" < "$tempdir/new1" > "$tempdir/new2"
	else
		sed -e "s/^# $N is not set\$/$N=$V/" < "$argument_input" > "$tempdir/new1"
		sed -e "s/^$N=.*\$/$N=$V/" < "$tempdir/new1" > "$tempdir/new2"
	fi

	# echo "Applying change $argument_input" "$tempdir/new2"

	egrep "^# $N is not set\$|^$N=" "$tempdir/new2" || { # nothing found - so we need to add that option then
		echo "Did not found option $N - so will append $V"
		if [[ $V == '-' ]] ;
		then
			echo "# $N is not set" >> "$tempdir/new2"
		else
			echo "$N=$V" >> "$tempdir/new2"
		fi
	}

	cp "$tempdir/new2" "$argument_input"
}

# change_one_setting 'CONFIG_EDAC_DEBUG' 'n'
# change_one_setting 'CONFIG_EDAC_DEBUG' ''
# change_one_setting 'FOO' 'y'
# change_one_setting 'FOO200' 'y'
# change_one_setting '' 'y'
# change_one_setting 'FOO' "aa'bb"

cp "$argument_input" "$tempdir/start"

for pair in "$@"
do
	# echo "REPLACE: ${pair}"
  # split line at "=" sign
	IFS_OLD="$IFS"
	IFS="="
	read -r VAR VAL <<< "${pair}"
	IFS="${IFS_OLD}"
	echo "Will change config: pair=$pair" ; echo "VAR=$VAR" ; echo "VAL=$VAL" # debug
	change_one_setting "$VAR" "$VAL"
done

echo "Changes to .config:"
diff "$tempdir/start" "$argument_input" # debug

normal_exit='y'


text:
The version 3 of Colourful comes with **significant breaking changes** that will require you to update your code if you intend to update from version 2.

## New color conversion engine

In v2, the way to convert between color spaces was via the single `ColourfulConverter` that could be configured via its properties.

In v3, the conversion engine was rebuilt from scratch. This is mainly to support the exensibility aspect, to be able to add many more color spaces in the future and allow conversion between all of them. This also allows consumers to implement their own color space.

**If you used the `ColourfulConverter`, you'll need to rewrite your code.** For more information on how to do that, see the [Conversion between color spaces
](topic-conversion.md) page.

## Channel range is not clamped by default

A major change is that the ranges of channel values are not automatically checked or clamped. For example, the typical range of channel values in the [RGB color space](spaces-rgb.md) is from 0 to 1. But now, you can end up with values outside of this space.

This is done mainly for these reasons:

- So we wouldn't lose the color information in case we're doing some processing and then converting the color to another color space.
- Because in different scenarios you might want to treat the outside values differently. For example, sometimes you might want to simply clamp them (i.e. if it's higher than 1, clamp it to 1, etc.), but in other scenarios, you might want to normalize the values (e.g. by finding the highest channel value, and then divide all channels by it, for RGB, see the `.NormalizeIntensity()` function).

For more information about this, see the [Ranges of channel values and clamping](topic-clamp.md) and [Conversion between color spaces
](topic-conversion.md) pages.

## New Jzazbz color space

There's now a new [Jzazbz color space](spaces-jzazbz.md) with its [cylindrical equivalent JzCzhz](topic-cylindrical-spaces.md) and new [ΔEz color difference algorithm](topic-color-difference.md).

## Deconstructors

All colors can now be deconstructed as follows:

```csharp
var myColor = new RGBColor(0.2, 0.205, 0.45445);

// ...

var (r2, g2, b2) = myColor; // deconstruct into three variables
```

This is utilizing the [tuple deconstruct feature from C# 7.0](https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct).

## Increased test coverage

Lots of automated tests have been added to increase the test coverage of the existing code.

## New documentation

As part of the v3 release, there was also a bigger focus on documentation. As a result of that, there are now more detailed documentation topics.

## Many new helper classes

There are now lots of new helpers, for example:

- `ClampHelper` for [clamping channel values](topic-clamp.md)
- `CylindricalFormulas` for [cylindrical color spaces](topic-cylindrical-spaces.md)
- `.NormalizeIntensity()` helper for [RGB colors](spaces-rgb.md)


text:
import { RendererFactory2 } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { SkyAppTestUtility } from '@skyux-sdk/testing';
import {
  SkyTheme,
  SkyThemeMode,
  SkyThemeService,
  SkyThemeSettings,
} from '@skyux/theme';

import { ModalViewkeptToolbarsComponent } from './modal-viewkept-toolbars.component';
import { ModalViewkeptToolbarsModule } from './modal-viewkept-toolbars.module';

describe('Modals with viewkept toolbars', () => {
  function closeModal(): void {
    getModalCloseButton().click();
    fixture.detectChanges();
  }

  function getModalCloseButton(): HTMLElement {
    return document.querySelector('#modal-viewkept-toolbars-modal-close');
  }

  function getModalContent(): HTMLElement {
    return document.querySelector('.sky-modal-content');
  }

  function getModalHeader(): HTMLElement {
    return document.querySelector('.sky-modal-header');
  }

  function getModalTrigger(): HTMLElement {
    return document.querySelector('#modal-viewkept-toolbars-modal-trigger');
  }

  function getToolbarContainers(): NodeListOf<HTMLElement> {
    return document.querySelectorAll(
      '.sky-modal-content .sky-toolbar-container'
    );
  }

  function openModal(): void {
    getModalTrigger().click();
    fixture.detectChanges;
  }

  async function scrollContentDown(): Promise<void> {
    getModalContent().scrollTo({
      top: 500,
    });
    SkyAppTestUtility.fireDomEvent(getModalContent(), 'scroll', {
      bubbles: false,
    });
    fixture.detectChanges();
    return fixture.whenStable();
  }

  let fixture: ComponentFixture<ModalViewkeptToolbarsComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        NoopAnimationsModule,
        RouterTestingModule,
        ModalViewkeptToolbarsModule,
      ],
      providers: [SkyThemeService],
    });

    fixture = TestBed.createComponent(ModalViewkeptToolbarsComponent);
    fixture.detectChanges();
  });

  afterEach(() => {
    closeModal();
  });

  describe('modern theme', () => {
    beforeEach(async () => {
      TestBed.inject(SkyThemeService).init(
        document.body,
        TestBed.inject(RendererFactory2).createRenderer(undefined, undefined),
        new SkyThemeSettings(
          SkyTheme.presets.modern,
          SkyThemeMode.presets.light
        )
      );

      await fixture.whenStable();
      openModal();
      fixture.detectChanges();
      await fixture.whenStable();
    });

    afterEach(() => {
      // Revert theme
      TestBed.inject(SkyThemeService).setTheme(
        new SkyThemeSettings(
          SkyTheme.presets.default,
          SkyThemeMode.presets.light
        )
      );
    });

    it('should not have a modal header box shadow when scroll is active', async () => {
      await scrollContentDown();
      expect(window.getComputedStyle(getModalHeader()).boxShadow).toBe('none');
    });

    it('should set the background color and padding correctly', async () => {
      await scrollContentDown();
      const toolbarContainers = getToolbarContainers();

      toolbarContainers.forEach((toolbar) => {
        const toolbarStyle = window.getComputedStyle(toolbar);
        expect(toolbarStyle.backgroundColor).toBe('rgb(255, 255, 255)');
        expect(toolbarStyle.paddingLeft).toBe('30px');
        expect(toolbarStyle.paddingRight).toBe('30px');
      });
    });
  });

  describe('default theme', () => {
    beforeEach(async () => {
      openModal();
      fixture.detectChanges();
      await fixture.whenStable();
    });

    it('should not set the padding', async () => {
      await scrollContentDown();
      const toolbarContainers = getToolbarContainers();

      toolbarContainers.forEach((toolbar) => {
        const toolbarStyle = window.getComputedStyle(toolbar);
        expect(toolbarStyle.paddingLeft).not.toBe('30px');
        expect(toolbarStyle.paddingRight).not.toBe('30px');
      });
    });
  });
});


text:
<ExpandableListView xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/expandablelistview_popup_details_info"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:paddingLeft="@dimen/popup_horizontal_margin"
              android:paddingRight="@dimen/popup_horizontal_margin"
              android:paddingTop="@dimen/popup_vertical_margin"
              android:paddingBottom="@dimen/popup_vertical_margin"/>


text:
namespace TwitterBackup.Services.Contracts
{
    using System.Collections.Generic;
    using TwitterBackup.Models;

    public interface IRetweetService
    {
        Retweet Save(long retweetId, long createdById, string screenName, long tweetOwnerId);

        int GetTotalRetweetsCount();

        ICollection<Retweet> GetRetweets();
    }
}