text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>util.SRA_File - sierra-php v1.1.3</title>

class SRA_File

    package util

  <form onsubmit="return false">

    Quick Search:

    <input id="quicksearch" type="text" onfocus="clearQsTips()" onblur="hideQsTips()" autocomplete="off" onclick="this.select()" />

class SRA_File

Class Information

Class Comments

Constants

Constant Details

Methods

Method Details

Other

Comment

 SRA_File Class. This class encapsulates the basic file system function. It
  wraps the functions suppressing normal PHP error reporting and insteads uses
  SRA_Error.

  Note: For debugging turn track_errors on in the php.ini. The error messages
  from this class will then be clearer because $php_errormsg is passed as part
  of the message.

  Current Methods:
  copy($src, $dest)
  rename($src, $dest)
  _mkdir($pathname, $mode)
  mkdir($path, $mode=0777, $parents=TRUE)
  chmod($pathname, $mode)
  unlink($file)
  symlink($target, $link)
  touch($file)
  _rmdir($dir)
  rmdir($dir, $children=FALSE)
  umask($mode)
  read($file, &$rBuffer)
  _write($file, &$rBuffer)
  write($file, &$rBuffer, $parents=TRUE, $mode=0777)
  fileMTime($file)
  compareMTimes($file1, $file2)
  parseIniFile($pathname, $processSections=FALSE)

Class Constants

public String

SRA_FILE_MIME_TYPE_FILE

 Specifies the mime type file to use. This must be specified in order to use the getMimeType method

public boolean

SRA_FILE_DEBUG

 Specifies whether or not the SRA_File class should operate in debug mode (outputs what it is doing to
  the active console window).

public String

SRA_FILE_CACHE_DIR

 The location where the cache csv arrays should be stored.

Class Methods

void

copy(string $src, string $dest, boolean $recursive=FALSE)

 used to copy a file from one location to another

string

findInPath(string $bin, mixed $addlPathDirs=NULL)

 looks for the program $bin in the $PATH environment variable. returns the
  absolute path to the program. returns NULL if $bin does not exist in the
  path

void

move(string $src, string $dest)

 move a file

TRUE on success. Err object on failure.

rename($src, $dest)

 Rename a file or directory. Hint: Use absolute paths if possible to avoid
  confustion of where src and dest are located.

private. TRUE on success. Err object on failure.

_mkdir($pathname, $mode)

 Create (make) a directory.

public TRUE on success. Err object on failure.

mkdir($path, $mode=0777, $parents=TRUE)

 This method makes one directory or recursively make directories in path.

boolean

chgrp(string $file, string $group, boolean $recursive=FALSE)

 changes the group ownership of $file to $group

boolean

chown(string $file, string $user, boolean $recursive=FALSE)

 changes the ownership of $file to $user

boolean

chmod(string $file, int $mode, boolean $recursive=FALSE)

 change the permissions of a file or directory

boolean

unlink(string $file)

 Delete a file or files. returns TRUE on success, FALSE otherwise (when
  $files is an array, FALSE will be returned if ANY of the files in that
  array could not be deleted)

TRUE on success. Err object on failure.

symlink($target, $link)

 Symbolically link a file to another name. Currently symlink is not
  implemented on Windows.
  Don't use if the application is to be portable.

TRUE on success. Err object on failure.

touch($file, $time=FALSE)

 Set the modification and access time on a file to the present time.

array on success. Err object on failure

dirlist($dir)

 Returns all file listings in a directory. This includes . and ..
  Errors can occur if $dir is not a directory, or if the directory cannot be opened (read permissions, file handles, etc)

TRUE on success. Err object on failure.

_rmdir($dir)

 Delete an empty directory.

TRUE on success. Err object on failure.

rmdir($dir, $children=FALSE)

 Delete an empty directory OR a directory and all of its contents.

TRUE on success. Err object on failure.

umask($mode)

 Set the umask for file and directory creation.

TRUE on success. Err object on failure.

read($file, $rBuffer)

 Reads a file and stores the data in the variable passed by reference.

TRUE on success. Err object on failure.

_write($file, $rBuffer)

 _write the passed buffer to filename. Overwrites existing file if any.

TRUE on success. Err object on failure.

write($file, $rBuffer, $parents=true, $mode=0777)

 Write() writes a file and makes directories in path if they don't
  exist. additionally, this method handle synchronization issues using a
  temp lock file. it will wait up to 30 seconds before generating an error
  object when the file is locked at the time this method is invoked

Int. Unix timestamp on success. Err object on failure.

fileMTime($file)

 Get the modified time for a file.

Int. 	1 if file1 is newer. -1 if file2 is newer. 0 if files have the same time. Err object on failure.

compareMTimes($file1, $file2)

 Compare the modified time of two files.

Associative array of values on success. Err object on failure.

parseIniFile($pathname, $processSections=FALSE)

 Proccess an ini file returning an array of values.

string[]

getFileList($path, string $pattern='*', boolean $recursive=FALSE, int $type=1)

 returns an array of paths to files names that meet the specified criteria

string

createRandomFile(string $dir=NULL, string $pre='', string $post='', string $base='', boolean $delete=FALSE, boolean $mkdir=FALSE)

 creates a temp file prefixed by $pre and postfixed by $post in $dir with
  the contents $base. if $base is a path to a local or remote file the
  SRA_File::copy method will be used to copy it into the created file and the
  created file extension will be the same as the original file. the absolute
  path to the random file created will be returned

void

deleteRandomFiles(string $file=NULL)

 deletes any random files created using SRA_File::createRandomFile when
  $delete is TRUE

string

&toString(string $file, int $err=SRA_ERROR_PROBLEM)

 this method converts a file to a string. it returns an SRA_Error object if
  it is unable to find or open the file

String

getMimeType($file)

 This method attempts to lookup the mime type for the file provided (based on the file extension)

string

getArchiveType(string $archive)

 returns the archive type identifier for the $archive specified

boolean

uncompress(string $archive, string $dest=NULL, boolean $delete=FALSE, string $archiveType=NULL)

 uncompresses an archive

mixed

compress(string $file, string $archiveType=SRA_FILE_ARCHIVE_TYPE_TAR_GZ, string $archive=NULL, string $directory=NULL)

 this method creates a compressed archive of $file. it returns the name of
  the of the compressed archive on success, FALSE otherwise

string

findFile(string $file, array $dirs)

 looks for $file in $dirs and returns the absolute path if it is found or
  NULL if it is not

String

&getContents($fp, $options)

 This method returns the contents of a file as a string limited by the parameters specified.
  It returns false if there are no more blocks in the file that meet the criteria.

String - false if not found

appendToFile($fileName, $data, $header=false, $chownUser=false)

 This method is used to append a data to a file. It is useful for such things as
  writing to data files such as csv files. If the file does not exist it is created.
  This is a static method of the SRA_File class. All data appened to the file will be
  followed by a newline.

public static String[]: An associative array containing the data

parseIni($fileName, $processSections=false)

 Load in the ini file specified in filename, and return
  the settings in an associative array. By setting the
  last $processSections parameter to true, you get a
  multidimensional array, with the section names and
  settings included. The default for processSections is
  false.

  This functions should replace php native parseIni_file which has too
  many shortcomings as of v 4.2.2.

private static boolean

arrayToFile($fileName, $arrayName, $array, $append=false)

 This method converts an array to a file.

public void

&fileToArray($file)

 Converts a file to an array. Similiar to the 'file' function but also
  strips out ending newlines

public static String

serialize($object, $file=false)

 Serializes an object to a file. Returns an SRA_Error object if any occur.

public static Object

&unserialize($file, $deleteFile=false)

 Unserializes an object from a file. Returns an SRA_Error object if any occur.

public static String[]

&propertiesArrayToFile($file, $data)

 This method performs the reverse of the propertiesFileToArray method. It writes an
  associative properties file array to a properties file.

public static String[]

&propertiesFileToArray($file, $keyCase, $languageCode='', boolean $cache=TRUE)

 This method converts a properties file to an associative array. It also performs
  caching of this data to temp files in the {SRA_DIR}/tmp/l10n directory.
  The property or key may also include imbedded php code through use of the
  php:: {code} ::php convention. The code itself should be a simple statement that
  returns a value. This value will be inserted into the key or property in the
  location in which they exist (multiple code segments may exist in various locations
  of a key or property).

private a two dimensional array representation of the csv file or FALSE  if the there is a problem with the file

&cvsToArray(String $file, mixed $indexCol=NULL, boolean $cache=TRUE, char $stringDelim='"')

 Used to convert a CSV file into a two dimensional array
  {@see SRA_Util#arrayToCsv(String[][], boolean)}
  This method maintains a cache

public static String or FALSE

findFirstMatchingPath($baseDirs, string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the first matching path using the following search algorithm
  	1) $baseDir1/$prefix[/$dir]/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) $baseDir1/$prefix[/$dir][/$file] (if $prefix specified)
  	3) $baseDir1[/$dir]/$postfix[/$file] (if $postfix specified)
  	4) $baseDir1[/$dir][/$file] (if exists)
 	... $baseDirN ...
 	4N + 1) FALSE

public static boolean

mergedFilesCached(mixed $files, int $obfuscate=FALSE, $removeWhiteSpace)

 returns TRUE if an invocation to SRA_File::renderMergedFiles will result
  in cached output

public static void

renderMergedFiles(mixed $files, int $obfuscate=FALSE, boolean $removeWhiteSpace=FALSE, boolean $processPhp=TRUE, string $search=NULL, string $replace=NULL)

 this method merges multiple static or dynamic files and outputs their
  contents. to increase performance, the $files are cached into a single
  temporary file first and the contents of that file are output. the
  temporary file is re-written automatically whenever any of the $files are
  subsequently modified

public static String or FALSE

getRelativePath(string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the full path for a app relative directory based on $dir
  using the following search order:
  	1) app directory/$prefix[/$dir]/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) app directory/$prefix[/$dir][/$file] (if $prefix specified)
  	3) app directory[/$dir]/$postfix[/$file] (if $postfix specified)
  	4) app directory[/$dir][/$file] (if exists)
  	5) SRA_File::getSysRelativePath($dir, $file, $prefix, $postfix) (otherwise)

public static String or FALSE

getSysRelativePath(string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the full path for the system relative directory based on $dir
  using the following search order:
  	1) SRA_DIR/$prefix/$dir/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) SRA_DIR/$prefix/$dir[/$file] (if $prefix specified)
  	3) SRA_DIR/$dir/$postfix[/$file] (if $postfix specified)
  	4) SRA_DIR/$dir[/$file] (if exists)
  	5) [$dir][/$file] (fixed path - if exists)
 	6) FALSE (otherwise)

int

getFileSize(string $file, boolean $useLs=FALSE)

 returns the size of $file in bytes

void

getFileSizeString($file, $useLs=FALSE, $decimals=2)

int

getUid(string $file)

 returns the uid of the owner of $file. this function works even if stat
  does not

int

getOwner(string $file)

 returns the name of the user that owns $file. this function works even if stat
  does not

int

getGid(string $file)

 returns the gid of the group owner of $file. this function works even if stat
  does not

int

getGroupOwner(string $file)

 returns the name of the group that owns $file. this function works even if stat
  does not

mixed

getPermissions(string $file, boolean $octal=FALSE)

 returns the octal permissions of $file (i.e. 775 or 664). this function
  works even if stat does not

mixed

&base64Decode(string $encoded, string $output=NULL)

 used the linux base64 command (if present) to decode $encoded. this
  function was created to avoid some unknown problems with the php
  base64_decode function

Constant Details

  Top

SRA_FILE_MIME_TYPE_FILE

public String SRA_FILE_MIME_TYPE_FILE = "/etc/mime.types"

 Specifies the mime type file to use. This must be specified in order to use the getMimeType method

SRA_FILE_DEBUG

public boolean SRA_FILE_DEBUG = false

 Specifies whether or not the SRA_File class should operate in debug mode (outputs what it is doing to
  the active console window).

SRA_FILE_CACHE_DIR

public String SRA_FILE_CACHE_DIR = SRA_DIR . "/tmp"

 The location where the cache csv arrays should be stored.

Method Details

  Top

copy

void function copy(string $src, string $dest, boolean $recursive=FALSE)

 used to copy a file from one location to another

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      src
      string

source path and name file to copy. this file may be  remote (http, https, ftp), and if it is, it will be downloaded using wget
  (wget must be installed)

      None
      No

      dest
      string

destination directory or directory + file name. if  $dest is a directory, the name of the file in $dest will be the same name
  as $src. if the $dest directory does not exist, it will be created

      None
      No

      recursive
      boolean

whether or not the copy should be recursive. does  not apply to remote $src files

      FALSE
      No

findInPath

string function findInPath(string $bin, mixed $addlPathDirs=NULL)

 looks for the program $bin in the $PATH environment variable. returns the
  absolute path to the program. returns NULL if $bin does not exist in the
  path

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      bin
      string

g $bin the name of the program to look for

      None
      No

      addlPathDirs
      mixed

an optional array of additional directories to  consider in the path search. this value can also be a single path or
  multiple paths represented as a single string each separated by :

      NULL
      No

move

void function move(string $src, string $dest)

 move a file

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      src
      string

source path and name file to copy

      None
      No

      dest
      string

destination path and name of new file

      None
      No

rename

TRUE on success. Err object on failure. function rename($src, $dest)

 Rename a file or directory. Hint: Use absolute paths if possible to avoid
  confustion of where src and dest are located.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      src
      Not Specified

No API comments

      None
      No

      dest
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

_mkdir

private. TRUE on success. Err object on failure. function _mkdir($pathname, $mode)

 Create (make) a directory.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      pathname
      Not Specified

No API comments

      None
      No

      mode
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

mkdir

public TRUE on success. Err object on failure. function mkdir($path, $mode=0777, $parents=TRUE)

 This method makes one directory or recursively make directories in path.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      path
      Not Specified

No API comments

      None
      No

      mode
      Not Specified

No API comments

      0777
      No

      parents
      Not Specified

No API comments

      TRUE
      No

author = Charlie Killian, charlie@tizac.com

chgrp

boolean function chgrp(string $file, string $group, boolean $recursive=FALSE)

 changes the group ownership of $file to $group

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to change the group ownership of

      None
      No

      group
      string

the name of the group to change group ownership to

      None
      No

      recursive
      boolean

whether or not to change the group permissions  recursively if $file is a directory

      FALSE
      No

chown

boolean function chown(string $file, string $user, boolean $recursive=FALSE)

 changes the ownership of $file to $user

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to change the ownership of

      None
      No

      user
      string

the name of the user to change ownership to

      None
      No

      recursive
      boolean

whether or not to change the permissions  recursively if $file is a directory

      FALSE
      No

chmod

boolean function chmod(string $file, int $mode, boolean $recursive=FALSE)

 change the permissions of a file or directory

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to change the permissions for

      None
      No

      mode
      int

the new mode (permissions) for $file. if using octal add  leading 0: i.e. 0777

      None
      No

      recursive
      boolean

whether or not to change the file permissions  recursively if $file is a directory

      FALSE
      No

unlink

boolean function unlink(string $file)

 Delete a file or files. returns TRUE on success, FALSE otherwise (when
  $files is an array, FALSE will be returned if ANY of the files in that
  array could not be deleted)

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

path and/or name of file to delete. if this is an  array, all of the files in the array will be deleted.

      None
      No

symlink

TRUE on success. Err object on failure. function symlink($target, $link)

 Symbolically link a file to another name. Currently symlink is not
  implemented on Windows.
  Don't use if the application is to be portable.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      target
      Not Specified

No API comments

      None
      No

      link
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

touch

TRUE on success. Err object on failure. function touch($file, $time=FALSE)

 Set the modification and access time on a file to the present time.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

      time
      Not Specified

No API comments

      FALSE
      No

author = Charlie Killian, charlie@tizac.com

dirlist

array on success. Err object on failure function dirlist($dir)

 Returns all file listings in a directory. This includes . and ..
  Errors can occur if $dir is not a directory, or if the directory cannot be opened (read permissions, file handles, etc)

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      Not Specified

String. Full path of the directory to get a listing for

      None
      No

author = Matthew Barlocker <mbarlocker@soleranetworks.com>

_rmdir

TRUE on success. Err object on failure. function _rmdir($dir)

 Delete an empty directory.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

rmdir

TRUE on success. Err object on failure. function rmdir($dir, $children=FALSE)

 Delete an empty directory OR a directory and all of its contents.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      Not Specified

No API comments

      None
      No

      children
      Not Specified

No API comments

      FALSE
      No

author = Charlie Killian, charlie@tizac.com

umask

TRUE on success. Err object on failure. function umask($mode)

 Set the umask for file and directory creation.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      mode
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

read

TRUE on success. Err object on failure. function read($file, $rBuffer)

 Reads a file and stores the data in the variable passed by reference.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

      rBuffer
      Not Specified

No API comments

      None
      Yes

author = Charlie Killian, charlie@tizac.com

_write

TRUE on success. Err object on failure. function _write($file, $rBuffer)

 _write the passed buffer to filename. Overwrites existing file if any.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

      rBuffer
      Not Specified

No API comments

      None
      Yes

author = Charlie Killian, charlie@tizac.com

write

TRUE on success. Err object on failure. function write($file, $rBuffer, $parents=true, $mode=0777)

 Write() writes a file and makes directories in path if they don't
  exist. additionally, this method handle synchronization issues using a
  temp lock file. it will wait up to 30 seconds before generating an error
  object when the file is locked at the time this method is invoked

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

      rBuffer
      Not Specified

No API comments

      None
      Yes

      parents
      Not Specified

No API comments

      true
      No

      mode
      Not Specified

No API comments

      0777
      No

author = Charlie Killian, charlie@tizac.com

fileMTime

Int. Unix timestamp on success. Err object on failure. function fileMTime($file)

 Get the modified time for a file.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

compareMTimes

Int. 	1 if file1 is newer. -1 if file2 is newer. 0 if files have the same time. Err object on failure.  function compareMTimes($file1, $file2)

 Compare the modified time of two files.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file1
      Not Specified

No API comments

      None
      No

      file2
      Not Specified

No API comments

      None
      No

author = Charlie Killian, charlie@tizac.com

parseIniFile

Associative array of values on success. Err object on failure. function parseIniFile($pathname, $processSections=FALSE)

 Proccess an ini file returning an array of values.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      pathname
      Not Specified

No API comments

      None
      No

      processSections
      Not Specified

No API comments

      FALSE
      No

author = Charlie Killian, charlie@tizac.com

getFileList

string[] function getFileList($path, string $pattern='*', boolean $recursive=FALSE, int $type=1)

 returns an array of paths to files names that meet the specified criteria

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      path
      Not Specified

No API comments

      None
      No

      pattern
      string

regular expression pattern or exact name to match.  use '*' to match all. default is '*'

      '*'
      No

      recursive
      boolean

whether or not the search should descend into  child directories

      FALSE
      No

      type
      int

bitmask identifying the file types to return where 1 is  files and 2 is directories (3=both files and directories). default is 1

      1
      No

createRandomFile

string function createRandomFile(string $dir=NULL, string $pre='', string $post='', string $base='', boolean $delete=FALSE, boolean $mkdir=FALSE)

 creates a temp file prefixed by $pre and postfixed by $post in $dir with
  the contents $base. if $base is a path to a local or remote file the
  SRA_File::copy method will be used to copy it into the created file and the
  created file extension will be the same as the original file. the absolute
  path to the random file created will be returned

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      string

the directory where the file should be created. if not  specified, the SRA_Controller::getAppTmpDir will be used

      NULL
      No

      pre
      string

a string to add to the beginning of the file. this  attribute is optional. The default is ''

      ''
      No

      post
      string

a string to add to the end of the file. this attribute  is optional. The default is ''.

      ''
      No

      base
      string

optional file contents or path to an existing file to  copy into the newly created random file

      ''
      No

      delete
      boolean

whether or not to delete this file automatically  upon termination of the current php process

      FALSE
      No

      mkdir
      boolean

whether or not the file should be created as a  directory

      FALSE
      No

deleteRandomFiles

void function deleteRandomFiles(string $file=NULL)

 deletes any random files created using SRA_File::createRandomFile when
  $delete is TRUE

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to delete, if NULL, the files will be deleted

      NULL
      No

toString

string function &toString(string $file, int $err=SRA_ERROR_PROBLEM)

 this method converts a file to a string. it returns an SRA_Error object if
  it is unable to find or open the file

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the absolute or relative path to the file

      None
      No

      err
      int

the level of the error that should be thrown if the file  cannot be found or opened. this value will correspond to one of the
  SRA_Error class error level constants. By default this value is
  SRA_ERROR_PROBLEM

      SRA_ERROR_PROBLEM
      No

author = Jason Read <jason@idir.org>

getMimeType

String function getMimeType($file)

 This method attempts to lookup the mime type for the file provided (based on the file extension)

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

author = Jason Read <jason@idir.org>

getArchiveType

string function getArchiveType(string $archive)

 returns the archive type identifier for the $archive specified

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      archive
      string

the name of the archive

      None
      No

uncompress

boolean function uncompress(string $archive, string $dest=NULL, boolean $delete=FALSE, string $archiveType=NULL)

 uncompresses an archive

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      archive
      string

the name of the archive to uncompress

      None
      No

      dest
      string

the destination path where $archive should be  uncompressed into. if not specified, the archive will be uncompressed into
  the parent directory of $archive

      NULL
      No

      delete
      boolean

whether or not $archive should be deleted after it  is uncompressed

      FALSE
      No

      archiveType
      string

the archive type (if $archive does not end with  one of the SRA_FILE_ARCHIVE_TYPE_* file extensions

      NULL
      No

compress

mixed function compress(string $file, string $archiveType=SRA_FILE_ARCHIVE_TYPE_TAR_GZ, string $archive=NULL, string $directory=NULL)

 this method creates a compressed archive of $file. it returns the name of
  the of the compressed archive on success, FALSE otherwise

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the path to the file or directory to compress

      None
      No

      archiveType
      string

the archive type to create. should be one of  the SRA_FILE_ARCHIVE_TYPE_* constants

      SRA_FILE_ARCHIVE_TYPE_TAR_GZ
      No

      archive
      string

the name of the archive to create. if not specified  the archive name will be the name $file plus the correct file extension
  based on the $archiveType specified and placed in the same directory as
  $file

      NULL
      No

      directory
      string

is $file is a directory, this parameter may be  used to specify the starting directory for the archive. if not specified,
  the archive will start at the root directory ('/')

      NULL
      No

findFile

string function findFile(string $file, array $dirs)

 looks for $file in $dirs and returns the absolute path if it is found or
  NULL if it is not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the name of the file to look for

      None
      No

      dirs
      array

the array of directories to look in

      None
      No

getContents

String function &getContents($fp, $options)

 This method returns the contents of a file as a string limited by the parameters specified.
  It returns false if there are no more blocks in the file that meet the criteria.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      fp
      Not Specified

- A reference to the file pointer for the file.

      None
      Yes

      options
      Not Specified

- A reference to a key based options array. The possible values for options are as follows:  			'start_string' => 	String that should appear at the start of a block of text to be parsed. This value will be
 								converted to an array if it contains a "&". In this case, all values in the array must exist in the line.
 								If this value contains a ':', the end string criteria will be converted to an array of arrays each containing
  								one set of strings that must be present for the end to have been found.
  			'start_line_num' => String that should appear at the start of a block of text to be parsed.
 					   			This option is overriden if 'start_string' is specified.
  			'end_string' => 	String that should appear at the end of a block of text to be parsed
 				   				(either this text or an EOF should exist). This value will be
 								converted to an array if it contains a "&". In this case, all values in the array must exist in the line.
 								If this value contains a ':', the end string criteria will be converted to an array of arrays each containing
  								one set of strings that must be present for the end to have been found.
  			'header_lines' => 	The # of lines that make up the file header. These lines will be ignored.
 								This value is only taken into consideration when at BOF.
  			'line_count' => 	The # of lines to be returned. This option is overriden if 'end_string' is specified.
  			'min_line_count' => This option specifies the minimum # of lines that should exist in a text block.

      None
      Yes

author = Jason Read <jason@idir.org>

appendToFile

String - false if not found function appendToFile($fileName, $data, $header=false, $chownUser=false)

 This method is used to append a data to a file. It is useful for such things as
  writing to data files such as csv files. If the file does not exist it is created.
  This is a static method of the SRA_File class. All data appened to the file will be
  followed by a newline.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      fileName
      Not Specified

No API comments

      None
      No

      data
      Not Specified

No API comments

      None
      No

      header
      Not Specified

No API comments

      false
      No

      chownUser
      Not Specified

No API comments

      false
      No

author = Jason Read <jason@idir.org>

parseIni

public static String[]: An associative array containing the data function parseIni($fileName, $processSections=false)

 Load in the ini file specified in filename, and return
  the settings in an associative array. By setting the
  last $processSections parameter to true, you get a
  multidimensional array, with the section names and
  settings included. The default for processSections is
  false.

  This functions should replace php native parseIni_file which has too
  many shortcomings as of v 4.2.2.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      fileName
      Not Specified

No API comments

      None
      No

      processSections
      Not Specified

No API comments

      false
      No

author = Array

arrayToFile

private static boolean function arrayToFile($fileName, $arrayName, $array, $append=false)

 This method converts an array to a file.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      fileName
      Not Specified

No API comments

      None
      No

      arrayName
      Not Specified

No API comments

      None
      No

      array
      Not Specified

No API comments

      None
      Yes

      append
      Not Specified

No API comments

      false
      No

author = Jason Read <jason@idir.org>

fileToArray

public void function &fileToArray($file)

 Converts a file to an array. Similiar to the 'file' function but also
  strips out ending newlines

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

: String - the path to the file to convert

      None
      No

serialize

public static String function serialize($object, $file=false)

 Serializes an object to a file. Returns an SRA_Error object if any occur.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      object
      Not Specified

: String - The object to serialize. An SRA_Error will be  			returned if this parameter is a scalar value.

      None
      No

      file
      Not Specified

: String - The file to serialize the object to. If this  			parameter is not specified, a random file will be created and
  			the name of that file returned.

      false
      No

author = Jason Read <jason@idir.org>

unserialize

public static Object function &unserialize($file, $deleteFile=false)

 Unserializes an object from a file. Returns an SRA_Error object if any occur.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

: String - The name of the file to unserialize.

      None
      No

      deleteFile
      Not Specified

: boolean - Whether or not the serialization file should 			be deleted if the object is unserialized successfully.

      false
      No

author = Jason Read <jason@idir.org>

propertiesArrayToFile

public static String[] function &propertiesArrayToFile($file, $data)

 This method performs the reverse of the propertiesFileToArray method. It writes an
  associative properties file array to a properties file.

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

: String -  The file to write to. Any existing data will be overwritten.

      None
      No

      data
      Not Specified

: String[] - An associative array of properties to write.

      None
      Yes

author = Jason Read <jason@idir.org>

propertiesFileToArray

public static String[] function &propertiesFileToArray($file, $keyCase, $languageCode='', boolean $cache=TRUE)

 This method converts a properties file to an associative array. It also performs
  caching of this data to temp files in the {SRA_DIR}/tmp/l10n directory.
  The property or key may also include imbedded php code through use of the
  php:: {code} ::php convention. The code itself should be a simple statement that
  returns a value. This value will be inserted into the key or property in the
  location in which they exist (multiple code segments may exist in various locations
  of a key or property).

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

: String - The file to convert. if this value is a string (and  not a file), it will be written to a temporary file, converted to a
  properties array, and returned

      None
      No

      keyCase
      Not Specified

: int - The key case to use. By default, this method will maintain  			the case used in the properties file (0). Optionally, you may specify -1
  			in this parameter for lowercase only keys, and 1 for uppercase only keys.

      None
      No

      languageCode
      Not Specified

: String - The language code

      ''
      No

      cache
      boolean

whether or not to cache files

      TRUE
      No

author = Jason Read <jason@idir.org>

cvsToArray

private a two dimensional array representation of the csv file or FALSE  if the there is a problem with the file
 function &cvsToArray(String $file, mixed $indexCol=NULL, boolean $cache=TRUE, char $stringDelim='"')

 Used to convert a CSV file into a two dimensional array
  {@see SRA_Util#arrayToCsv(String[][], boolean)}
  This method maintains a cache

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      String

- the name of the csv file to convert

      None
      No

      indexCol
      mixed

- if the returned array should be indexed by one of  the column values, this parameter should identify the 0-based index of that
  column. thus, if duplicate values exist in the database for that column,
  only a single instance of it will be returned (the last instance). this
  parameter may also be an array where the row indexes will be a concatendated
  value consisting of all of the values specified in that array where a
  numeric value will be pulled from the row and a string will be inserted into
  the key as-is.

      NULL
      No

      cache
      boolean

whether or not to cache the results

      TRUE
      No

      stringDelim
      char

- the string delimiter. strings may contain this  delimiter value, but it should be preceded by \ or the same delimiter when
  this occurs

      '"'
      No

findFirstMatchingPath

public static String or FALSE function findFirstMatchingPath($baseDirs, string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the first matching path using the following search algorithm
  	1) $baseDir1/$prefix[/$dir]/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) $baseDir1/$prefix[/$dir][/$file] (if $prefix specified)
  	3) $baseDir1[/$dir]/$postfix[/$file] (if $postfix specified)
  	4) $baseDir1[/$dir][/$file] (if exists)
 	... $baseDirN ...
 	4N + 1) FALSE

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      baseDirs
      Not Specified

No API comments

      None
      No

      dir
      string

- the directory name

      FALSE
      No

      file
      string

- an optional file to look for in the directory

      FALSE
      No

      prefix
      string

- a prefix to check in the app and SRA_DIR

      ''
      No

      postfix
      string

- a postfix to check in the app and SRA_DIR

      ''
      No

mergedFilesCached

public static boolean function mergedFilesCached(mixed $files, int $obfuscate=FALSE, $removeWhiteSpace)

 returns TRUE if an invocation to SRA_File::renderMergedFiles will result
  in cached output

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      files
      mixed

either an array of file names or a space separated list  of file names. if any file in this value is not valid, an error will be
  logged, but the rendering will continue

      None
      No

      obfuscate
      int

if the $files are javascript or css source code  files, whether or not those files should be obfuscated. obfuscation,
  removes all unnecessary comments and whitespace from the source files in
  order to reduce the file size. obfuscation depends on ext/phpJSO.php. use
  1 for javascript obfuscation and 2 for css obfuscation

      FALSE
      No

      removeWhiteSpace
      Not Specified

No API comments

      None
      No

renderMergedFiles

public static void function renderMergedFiles(mixed $files, int $obfuscate=FALSE, boolean $removeWhiteSpace=FALSE, boolean $processPhp=TRUE, string $search=NULL, string $replace=NULL)

 this method merges multiple static or dynamic files and outputs their
  contents. to increase performance, the $files are cached into a single
  temporary file first and the contents of that file are output. the
  temporary file is re-written automatically whenever any of the $files are
  subsequently modified

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      files
      mixed

either an array of file names or a space separated list  of file names. if any file in this value is not valid, an error will be
  logged, but the rendering will continue

      None
      No

      obfuscate
      int

if the $files are javascript or css source code  files, whether or not those files should be obfuscated. obfuscation,
  removes all unnecessary comments and whitespace from the source files in
  order to reduce the file size. obfuscation depends on ext/phpJSO.php. use
  1 for javascript obfuscation and 2 for css obfuscation

      FALSE
      No

      removeWhiteSpace
      boolean

whether or not to remove whitespace from  the merged files

      FALSE
      No

      processPhp
      boolean

whether or not to process php files (files that  end with the SRA_SYS_PHP_EXTENSION extension)

      TRUE
      No

      search
      string

an optional value to replace with $replace. this can  contain multiple values each separated by a pipe (|)

      NULL
      No

      replace
      string

the value to replace $search with. this can contain  multiple values each separated by a pipe (|)

      NULL
      No

getRelativePath

public static String or FALSE function getRelativePath(string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the full path for a app relative directory based on $dir
  using the following search order:
  	1) app directory/$prefix[/$dir]/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) app directory/$prefix[/$dir][/$file] (if $prefix specified)
  	3) app directory[/$dir]/$postfix[/$file] (if $postfix specified)
  	4) app directory[/$dir][/$file] (if exists)
  	5) SRA_File::getSysRelativePath($dir, $file, $prefix, $postfix) (otherwise)

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      string

- the base directory name (optional)

      FALSE
      No

      file
      string

- an optional file to look for in the directory. either  $dir or $file should be specified or the app directory will always be
  returned

      FALSE
      No

      prefix
      string

- a prefix to check in the app and SRA_DIR

      ''
      No

      postfix
      string

- a postfix to check in the app and SRA_DIR

      ''
      No

getSysRelativePath

public static String or FALSE function getSysRelativePath(string $dir=FALSE, string $file=FALSE, string $prefix='', string $postfix='')

 returns the full path for the system relative directory based on $dir
  using the following search order:
  	1) SRA_DIR/$prefix/$dir/$postfix[/$file] (if both $prefix and $postfix specified)
  	2) SRA_DIR/$prefix/$dir[/$file] (if $prefix specified)
  	3) SRA_DIR/$dir/$postfix[/$file] (if $postfix specified)
  	4) SRA_DIR/$dir[/$file] (if exists)
  	5) [$dir][/$file] (fixed path - if exists)
 	6) FALSE (otherwise)

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      dir
      string

- the directory name (optional)

      FALSE
      No

      file
      string

- an optional file to look for in the directory. either  $dir or $file should be specified or the SRA_DIR will always be returned

      FALSE
      No

      prefix
      string

- a prefix to check in the SRA_DIR

      ''
      No

      postfix
      string

- a postfix to check in the SRA_DIR

      ''
      No

getFileSize

int function getFileSize(string $file, boolean $useLs=FALSE)

 returns the size of $file in bytes

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the size of

      None
      No

      useLs
      boolean

whether or not to use the ls command instead of the  built in filesize php function

      FALSE
      No

getFileSizeString

void function getFileSizeString($file, $useLs=FALSE, $decimals=2)

No API comments

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      Not Specified

No API comments

      None
      No

      useLs
      Not Specified

No API comments

      FALSE
      No

      decimals
      Not Specified

No API comments

      2
      No

getUid

int function getUid(string $file)

 returns the uid of the owner of $file. this function works even if stat
  does not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the owner of

      None
      No

getOwner

int function getOwner(string $file)

 returns the name of the user that owns $file. this function works even if stat
  does not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the owner of

      None
      No

getGid

int function getGid(string $file)

 returns the gid of the group owner of $file. this function works even if stat
  does not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the owner of

      None
      No

getGroupOwner

int function getGroupOwner(string $file)

 returns the name of the group that owns $file. this function works even if stat
  does not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the owner of

      None
      No

getPermissions

mixed function getPermissions(string $file, boolean $octal=FALSE)

 returns the octal permissions of $file (i.e. 775 or 664). this function
  works even if stat does not

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      file
      string

the file to return the permissions for

      None
      No

      octal
      boolean

if TRUE, the return value will be an octal. otherwise  it will be an int

      FALSE
      No

base64Decode

mixed function &base64Decode(string $encoded, string $output=NULL)

 used the linux base64 command (if present) to decode $encoded. this
  function was created to avoid some unknown problems with the php
  base64_decode function

Method Parameters

      Name
      Type
      Comment
      Default Value
      By Reference?

      encoded
      string

the base64 encoded string to convert

      None
      Yes

      output
      string

an optional file path that the encoded contents  should be written to. if specified, the return value will be NULL

      NULL
      No

Other Information

    Source File
    /home/jread/www/sierra/lib/util/SRA_File.php

    author
    Jason Read <jason@idir.org>

  </form>

redpajama_set_name: RedPajamaGithub


text:
function BucketBuilder () {
  this.buckets = [];
}

BucketBuilder.prototype.before = function (a) {
  this.buckets.push('*~' + a);
  return this;
};

BucketBuilder.prototype.between = function (a, b) {
  this.buckets.push([a, b].join('~'));
  return this;
};

BucketBuilder.prototype.after = function (a) {
  this.buckets.push(a + '~*');
  return this;
};

BucketBuilder.prototype.build = function () {
  return this.buckets.join(':');
}

module.exports = BucketBuilder;


text:
<?php

namespace IndependentReserve\Object;

use Concise\TestCase;
use DateTime;
use IndependentReserve\Currency;

class FiatWithdrawalTest extends TestCase
{
    /**
     * @var FiatWithdrawal
     */
    protected $withdrawal;

    public function setUp()
    {
        parent::setUp();

        $obj = (object)[
            "FiatWithdrawalRequestGuid" => "2e9ad56c-1954-4b0f-b3d8-2ade7fad93ff",
            "AccountGuid" => "eda82a84-57fe-4ce6-9ee5-45a41063ee23",
            "Status" => "Pending",
            "CreatedTimestampUtc" => "2014-12-18T14:08:47.4032405Z",
            "TotalWithdrawalAmount" => 50.00,
            "FeeAmount" => 20.00,
            "Currency" => "Usd",
        ];

        $this->withdrawal = FiatWithdrawal::createFromObject($obj);
    }

    public function testFactorySetsGuid()
    {
        $this->assert($this->withdrawal->getGuid(), equals, '2e9ad56c-1954-4b0f-b3d8-2ade7fad93ff');
    }

    public function testFactorySetsAccountGuid()
    {
        $this->assert($this->withdrawal->getAccountGuid(), equals, 'eda82a84-57fe-4ce6-9ee5-45a41063ee23');
    }

    public function testFactorySetsStatus()
    {
        $this->assert($this->withdrawal->getStatus(), equals, 'Pending');
    }

    public function testCreatedTimestampIsADateTime()
    {
        $this->assert($this->withdrawal->getCreatedTimestamp(), instance_of, '\DateTime');
    }

    public function testFactorySetsCreatedTimestamp()
    {
        $this->assert($this->withdrawal->getCreatedTimestamp(), equals, new DateTime("2014-12-18T14:08:47.4032405Z"));
    }

    public function testFactorySetsTotalWithdrawalAmount()
    {
        $this->assert($this->withdrawal->getTotalWithdrawalAmount(), equals, 50.00);
    }

    public function testFactorySetsFeeAmount()
    {
        $this->assert($this->withdrawal->getFeeAmount(), equals, 20.00);
    }

    public function testFactorySetsCurrency()
    {
        $this->assert($this->withdrawal->getCurrency(), equals, Currency::USD);
    }
}


text:
#pragma once
#include <Windows.h>

namespace Syntax
{
	namespace Utility
	{
		//! A high resolution timer.
		/*!
			Uses high resolution performance counter to implement a timer. High precesion.
			All returned values are in seconds. You should only call Update once per frame.
			The LastFrameTime is always the amount of time between the last 2 calls to update.

			Generally use GetTotalTime and Reset to keep track of the amount of time of a single event.
			Use Update only when creating a frame rate type counter.
		*/
		class Timer
		{
		public:
			Timer(void);
			~Timer(void);
			//! Total time since timer was created or Reset was called
			/*!
				This will be set back to 0 every time Reset is called.
			*/
			inline double GetTotalTime() const {return totalTime;}
			//! Time between last 2 calls to Update
			/*!
				Don't use Reset if using this call and Update. Reset will set this back
				to 0, and it won't change from that until after the next Update call.
			*/
			inline double GetLastFrameTime() const {return timeLastFrame;}
			//! Reset the total time back to 0.
			void Reset(void);
			//! Next Frame. Update the LastFrameTime
			void Update(void);
		private:
			double timerFreqInv;
			double totalTime;
			double timeLastFrame;
			LARGE_INTEGER lastFrameQuery;
		};
	}
}


text:
#include <aws/events/model/UpdateConnectionApiKeyAuthRequestParameters.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace CloudWatchEvents
{
namespace Model
{

UpdateConnectionApiKeyAuthRequestParameters::UpdateConnectionApiKeyAuthRequestParameters() :
    m_apiKeyNameHasBeenSet(false),
    m_apiKeyValueHasBeenSet(false)
{
}

UpdateConnectionApiKeyAuthRequestParameters::UpdateConnectionApiKeyAuthRequestParameters(JsonView jsonValue) :
    m_apiKeyNameHasBeenSet(false),
    m_apiKeyValueHasBeenSet(false)
{
  *this = jsonValue;
}

UpdateConnectionApiKeyAuthRequestParameters& UpdateConnectionApiKeyAuthRequestParameters::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ApiKeyName"))
  {
    m_apiKeyName = jsonValue.GetString("ApiKeyName");

    m_apiKeyNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApiKeyValue"))
  {
    m_apiKeyValue = jsonValue.GetString("ApiKeyValue");

    m_apiKeyValueHasBeenSet = true;
  }

  return *this;
}

JsonValue UpdateConnectionApiKeyAuthRequestParameters::Jsonize() const
{
  JsonValue payload;

  if(m_apiKeyNameHasBeenSet)
  {
   payload.WithString("ApiKeyName", m_apiKeyName);

  }

  if(m_apiKeyValueHasBeenSet)
  {
   payload.WithString("ApiKeyValue", m_apiKeyValue);

  }

  return payload;
}

} // namespace Model
} // namespace CloudWatchEvents
} // namespace Aws


text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschränkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Squidex.Domain.Apps.Core;
using Squidex.Domain.Apps.Core.Schemas;
using Squidex.Domain.Apps.Entities.Schemas.Commands;
using Squidex.Infrastructure;

namespace Squidex.Domain.Apps.Entities.Schemas.Guards
{
    public static class GuardSchemaField
    {
        public static void CanAdd(Schema schema, AddField command)
        {
            Guard.NotNull(command, nameof(command));

            Validate.It(() => "Cannot add a new field.", e =>
            {
                if (!command.Name.IsPropertyName())
                {
                    e("Name must be a valid javascript property name.", nameof(command.Name));
                }

                if (command.Properties == null)
                {
                    e("Properties is required.", nameof(command.Properties));
                }
                else
                {
                    var errors = FieldPropertiesValidator.Validate(command.Properties);

                    errors.Foreach(x => x.WithPrefix(nameof(command.Properties)).AddTo(e));
                }

                if (command.ParentFieldId.HasValue)
                {
                    var arrayField = GuardHelper.GetArrayFieldOrThrow(schema, command.ParentFieldId.Value);

                    if (arrayField.FieldsByName.ContainsKey(command.Name))
                    {
                        e("A field with the same name already exists.");
                    }
                }
                else
                {
                    if (command.ParentFieldId == null && !command.Partitioning.IsValidPartitioning())
                    {
                        e("Partitioning is not valid.", nameof(command.Partitioning));
                    }

                    if (schema.FieldsByName.ContainsKey(command.Name))
                    {
                        e("A field with the same name already exists.");
                    }
                }
            });
        }

        public static void CanUpdate(Schema schema, UpdateField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (field.IsLocked)
            {
                throw new DomainException("Schema field is already locked.");
            }

            Validate.It(() => "Cannot update field.", e =>
            {
                if (command.Properties == null)
                {
                    e("Properties is required.", nameof(command.Properties));
                }
                else
                {
                    var errors = FieldPropertiesValidator.Validate(command.Properties);

                    errors.Foreach(x => x.WithPrefix(nameof(command.Properties)).AddTo(e));
                }
            });
        }

        public static void CanHide(Schema schema, HideField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (field.IsLocked)
            {
                throw new DomainException("Schema field is locked.");
            }

            if (field.IsHidden)
            {
                throw new DomainException("Schema field is already hidden.");
            }
        }

        public static void CanDisable(Schema schema, DisableField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (field.IsDisabled)
            {
                throw new DomainException("Schema field is already disabled.");
            }
        }

        public static void CanDelete(Schema schema, DeleteField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (field.IsLocked)
            {
                throw new DomainException("Schema field is locked.");
            }
        }

        public static void CanShow(Schema schema, ShowField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (!field.IsHidden)
            {
                throw new DomainException("Schema field is already visible.");
            }
        }

        public static void CanEnable(Schema schema, EnableField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (!field.IsDisabled)
            {
                throw new DomainException("Schema field is already enabled.");
            }
        }

        public static void CanLock(Schema schema, LockField command)
        {
            Guard.NotNull(command, nameof(command));

            var field = GuardHelper.GetFieldOrThrow(schema, command.FieldId, command.ParentFieldId);

            if (field.IsLocked)
            {
                throw new DomainException("Schema field is already locked.");
            }
        }
    }
}


text:
Humble koa generator

	<router-outlet></router-outlet>

Test Angular HMR in dev mode! Write some text in the input below, change code in Home folder, wait until project's rebuild is finished and see results!

		<input <% if(materialDesign) { %>matInput <% } %>[(ngModel)]="text"/>

You wrote: {{ text }}


text:
using Newtonsoft.Json;
using NUnit.Framework;
using SuccincT.JSON;
using SuccincT.Options;
using static Newtonsoft.Json.JsonConvert;
using static NUnit.Framework.Assert;

namespace SuccincTTests.SuccincT.JSON
{
    [TestFixture]
    public class SuccessConverterTests
    {
        [Test]
        public void WhenProvidedWithNoIsFailure_DeserializeFailsWithJsonException()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new SuccessConverter());

            _ = Throws<JsonException>(() => {
                _ = DeserializeObject<Success<int>>("{k:1, failure:2}", settings);
            });
        }

        [Test]
        public void WhenProvidedWithNoFailure_DeserializeFailsWithJsonException()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new SuccessConverter());

            _ = Throws<JsonException>(() => {
                _ = DeserializeObject<Success<int>>("{isFailure:true, k:2}", settings);
            });
        }

        [Test]
        public void ConvertingFailureToJsonAndBack_PreservesSuccessState()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new SuccessConverter());
            var failure = Success.CreateFailure("a");
            var json = SerializeObject(failure, settings);
            var newFailure = DeserializeObject<Success<string>>(json, settings);

            IsTrue(newFailure.IsFailure);
            AreEqual("a", newFailure.Failure);
        }

        [Test]
        public void ConvertingSuccessToJsonAndBack_PreservesSuccessState()
        {
            var settings = new JsonSerializerSettings();
            settings.Converters.Add(new SuccessConverter());
            var success = new Success<int>();
            var json = SerializeObject(success, settings);
            var newSuccess = DeserializeObject<Success<int>>(json, settings);

            IsFalse(newSuccess.IsFailure);
        }
    }
}


text:
/*
 * =====================================================================================
 *
 *       Filename:  uvisualstyle.h
 *
 *    Description:  visual styles
 *
 *        Version:  1.0
 *        Created:  2009-7-19 10:39:39
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  huys (hys), huys03@gmail.com
 *        Company:  hu
 *
 * =====================================================================================
 */
#define _WIN32_WINNT 0x0501

#include <windows.h>
#include <tchar.h>

#include "uvisualstyle.h"

#include "adt/ustring.h"

namespace VisualStyles
{

BOOL isAppThemed()
{
    return ::IsAppThemed();
}

BOOL isThemeActive()
{
    return ::IsThemeActive();
}

UTheme::UTheme()
{}

UTheme::~UTheme()
{
    if (m_hTheme)
    {
        close();
    }
}

BOOL UTheme::open(HWND hWnd, LPCWSTR pszClassList)
{
    m_hTheme = ::OpenThemeData(hWnd, pszClassList);
    return NULL != m_hTheme;
}

BOOL UTheme::close()
{
    return S_OK == ::CloseThemeData(m_hTheme);
}

BOOL UTheme::enable(BOOL fEnable)
{
    return S_OK == ::EnableTheming(fEnable);
}

BOOL UTheme::drawBackgroud(HDC hdc, int iPartId, int iStateId, const RECT *lpRect, const RECT *lpClipRect)
{
    return S_OK == ::DrawThemeBackground(m_hTheme, hdc, iPartId, iStateId, lpRect, lpClipRect);
}

BOOL UTheme::drawEdge( HDC dc, LPRECT lpRect, UINT uEdge /*= EDGE_BUMP*/, UINT uFlags /*= BF_RECT*/, int iPartID /*= BP_PUSHBUTTON*/, int iStateID /*= PBS_HOT*/, LPRECT lpClipRect /*= NULL*/ )
{
    return S_OK == ::DrawThemeEdge(m_hTheme, dc, iPartID, iStateID, lpRect, uEdge, uFlags, lpClipRect);
}

BOOL UTheme::getAppearance() const
{
    // For XP - Detect if the Window Style is Classic or XP
    OSVERSIONINFO osvi;
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

    GetVersionEx(&osvi);

    if (osvi.dwMajorVersion < 5)	// Earlier than XP
        return FALSE;

    /////////////////////////////////////////////////////

    HKEY	hKey;

    LPCTSTR szSubKey = _T("Control Panel\\Appearance");
    LPCTSTR	szCurrent = _T("Current");
    unsigned char szBuffer[512];
    DWORD dwSize = 512;

    if (::RegOpenKeyEx(HKEY_CURRENT_USER, szSubKey, 0L, KEY_READ, &hKey) != ERROR_SUCCESS)
    {
        // Can't find it
        return FALSE;
    }

    ::RegQueryValueEx(hKey, szCurrent, NULL, NULL, szBuffer, &dwSize);

    ::RegCloseKey(hKey);

    if (lstrcmp(_T("Windows Standard"), (LPCTSTR)szBuffer) ==0)
        return FALSE;

    return TRUE;
}

}; // namespace VisualStyles


text:
from textwrap import dedent
import inspect
from collections import OrderedDict
from clusterjob import JobScript
import pytest
import logging
try:
    from ConfigParser import Error as ConfigParserError
except ImportError:
    from configparser import Error as ConfigParserError
# built-in fixtures: tmpdir
# pytest-capturelog fixutres: caplog

def get_methods(obj):
    """Get list of methods of object or class"""
    return sorted([k for (k, v) in inspect.getmembers(obj, inspect.isroutine)])
    # isroutine works in Python 2 and Python 3, while ismethod does not work in
    # Python 3 if obj is a class (since the methods are not *bound*)

def get_attributes(obj, hidden=False):
    """Get list of attributes of object"""
    methods = get_methods(obj)
    attribs = sorted([k for k in obj.__dict__ if k not in methods])
    if hidden:
        return attribs
    else:
        return [attr for attr in attribs if not attr.startswith('_')]

def default_class_attr_val(attr):
    """Return the default value for the given class attribute"""
    defaults = JobScript._attributes.copy()
    defaults.update(JobScript._protected_attributes)
    try:
        return defaults[attr]
    except KeyError:
        if attr == 'resources':
            return OrderedDict()
        else:
            return None

def check_attributes(obj, expected):
    for key in expected:
        assert getattr(obj, key) == expected[key]

def check_resources(obj, expected):
    for key in expected:
        assert obj.resources[key] == expected[key]

def example_inidata():
    inidata = dedent(r'''
    [Attributes]

    remote = login.cluster.edu
    backend = pbs
    shell = /bin/sh
    cache_folder = cache
    prologue =
        ssh {remote} 'mkdir -p {rootdir}/{workdir}'
        rsync -av {workdir}/ {remote}:{rootdir}/{workdir}
    epilogue = rsync -av {remote}:{rootdir}/{workdir}/ {workdir}
    rootdir = ~/jobs/
    workdir = run001
    max_sleep_interval = 60
    # the following is a new attribute
    text = Hello World

    [Resources]

    queue = exec
    nodes = 1
    threads = 12
    mem = 10000
    ''')

    expected_attribs = {
        'remote': 'login.cluster.edu',
        'backend': 'pbs',
        'shell': '/bin/sh',
        'prologue' : "ssh {remote} 'mkdir -p {rootdir}/{workdir}'\n"
                        "rsync -av {workdir}/ {remote}:{rootdir}/{workdir}",
        'epilogue': "rsync -av {remote}:{rootdir}/{workdir}/ {workdir}",
        'rootdir': '~/jobs',
        'workdir': 'run001',
        'max_sleep_interval': 60,
        'text': "Hello World"
    }
    expected_resources = {
            'queue': 'exec',
            'nodes': 1,
            'threads': 12,
            'mem':  10000,
    }
    return inidata, expected_attribs, expected_resources

def test_read_inifile(tmpdir):
    p = tmpdir.join("default.ini")
    ini_filename = str(p)
    attribs = {}
    resources = {}
    def attr_setter(k,v):
        attribs[k] = v
    def rsrc_setter(k,v):
        resources[k] = v

    inidata = ''
    p.write(inidata)
    with pytest.raises(ConfigParserError) as exc_info:
        JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert "must contain at least one of the sections" in str(exc_info.value)

    inidata = dedent(r'''
    max_sleep_interval = 60
    ''')
    p.write(inidata)
    with pytest.raises(ConfigParserError) as exc_info:
        JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert "File contains no section headers" in str(exc_info.value)

    inidata = dedent(r'''
    [Attributes]
    max_sleep_interval = 60
    ''')
    p.write(inidata)
    JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert attribs['max_sleep_interval'] == 60

    inidata = dedent(r'''
    [Resources]
    threads = 2
    ''')
    p.write(inidata)
    JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert attribs['max_sleep_interval'] == 60
    assert resources['threads'] == 2

    inidata = dedent(r'''
    [Attributes]
    shell = /bin/bash

    [Resources]
    nodes = 1
    ''')
    p.write(inidata)
    JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert attribs['max_sleep_interval'] == 60
    assert attribs['shell'] == '/bin/bash'
    assert resources['threads'] == 2
    assert resources['nodes'] == 1

    # both section headers and keys are case sensitive
    inidata = dedent(r'''
    [Attributes]
    Max_Sleep_Interval = 120
    Shell = /bin/bash

    [Resources]
    Nodes = 1
    ''')
    p.write(inidata)
    JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert attribs['max_sleep_interval'] == 60
    assert attribs['Max_Sleep_Interval'] == '120' # no conversion to int!

    inidata = dedent(r'''
    [Attributes]
    shell = /bin/bash

    [Resources]
    nodes = 1

    [Schedulers]
    cluster = login.cluster.com
    ''')
    p.write(inidata)
    with pytest.raises(ConfigParserError) as exc_info:
        JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert "Invalid section 'Schedulers'" in str(exc_info.value)

    inidata = dedent(r'''
    [Attributes]
    resources = {1:2}
    ''')
    p.write(inidata)
    with pytest.raises(ConfigParserError) as exc_info:
        JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert "not allowed" in str(exc_info.value)

    # quotes are not stripped out!
    inidata = dedent(r'''
    [Attributes]
    text = "This is a text"
    ''')
    p.write(inidata)
    JobScript._read_inifile(ini_filename, attr_setter, rsrc_setter)
    assert attribs['text'] == '"This is a text"'

def test_read_defaults(caplog, tmpdir):
    JobScript.read_defaults() # reset
    caplog.setLevel(logging.DEBUG, logger='clusterjob')
    jobscript = JobScript(body="echo 'Hello'", jobname="test")
    assert get_attributes(jobscript) == ['aux_scripts', 'body', 'resources']
    assert get_attributes(jobscript.__class__) == ['backend', 'backends',
            'cache_folder', 'cache_prefix', 'epilogue', 'filename',
            'max_sleep_interval', 'prologue', 'remote', 'resources', 'rootdir',
            'scp', 'shell', 'ssh', 'workdir']
    for attr in get_attributes(jobscript.__class__):
        if attr not in ['resources', 'backends']:
            assert getattr(jobscript, attr) == default_class_attr_val(attr)

    inidata, expected_attribs, expected_resources = example_inidata()
    p = tmpdir.join("default.ini")
    p.write(inidata)
    ini_filename = str(p)

    # Setting class defaults before instantiation sets both the attributes and
    # the resources
    JobScript.read_defaults(ini_filename)
    jobscript = JobScript(body="echo '{text}'", jobname="test")
    assert get_attributes(jobscript) == ['aux_scripts', 'body', 'resources']
    check_attributes(jobscript, expected_attribs)
    check_resources(jobscript, expected_resources)
    assert str(jobscript) == dedent(r'''
    #!/bin/sh
    #PBS -l nodes=1:ppn=12
    #PBS -q exec
    #PBS -l mem=10000m
    #PBS -N test
    echo 'Hello World'
    ''').strip()

    # calling read_defaults without filename argument resets the class, and
    # thus also changes the attributes of an existing instance
    JobScript.read_defaults()
    check_resources(jobscript, expected_resources)
    for attr in get_attributes(jobscript.__class__):
        if attr not in ['resources', 'backends']:
            assert getattr(jobscript, attr) == default_class_attr_val(attr)
    with pytest.raises(KeyError) as exc_info:
        str(jobscript)
    assert "no matching attribute or resource entry" in str(exc_info.value)
    jobscript.text = 'Hello World' # instance attribute
    assert str(jobscript) == dedent(r'''
    #!/bin/bash
    #SBATCH --partition=exec
    #SBATCH --nodes=1
    #SBATCH --cpus-per-task=12
    #SBATCH --mem=10000
    #SBATCH --job-name=test
    echo 'Hello World'
    ''').strip()

    # Setting class defaults after instantiation sets the attributes, but not
    # the resources
    jobscript = JobScript(body="echo '{text}'", jobname="test")
    JobScript.read_defaults(ini_filename)
    assert str(jobscript) == dedent(r'''
    #!/bin/sh
    #PBS -N test
    echo 'Hello World'
    ''').strip()

def test_read_settings(caplog, tmpdir):
    JobScript.read_defaults() # reset
    caplog.setLevel(logging.DEBUG, logger='clusterjob')
    jobscript = JobScript(body="echo '{text}'", jobname="test")
    assert get_attributes(jobscript) == ['aux_scripts', 'body', 'resources']
    jobscript2 = JobScript(body="echo 'Hello'", jobname="test2")
    inidata, expected_attribs, expected_resources = example_inidata()
    p = tmpdir.join("job.ini")
    p.write(inidata)
    ini_filename = str(p)

    with pytest.raises(AttributeError) as excinfo:
        jobscript.read_settings(ini_filename)
    assert "'cache_folder' can only be set as a class attribute" \
           in str(excinfo.value)
    inidata = inidata.replace("cache_folder = cache\n", "")
    p.write(inidata)
    jobscript.read_settings(ini_filename)
    assert get_attributes(jobscript) == ['aux_scripts', 'backend', 'body',
            'epilogue', 'max_sleep_interval', 'prologue', 'remote',
            'resources', 'rootdir', 'shell', 'text', 'workdir']
    # class attributes remain unaffected
    for attr in get_attributes(JobScript):
        if attr not in ['resources', 'backends']:
            assert getattr(JobScript, attr) == default_class_attr_val(attr)
    assert str(jobscript) == dedent(r'''
    #!/bin/sh
    #PBS -l nodes=1:ppn=12
    #PBS -N test
    #PBS -q exec
    #PBS -l mem=10000m
    echo 'Hello World'
    ''').strip()

    # the second jobscript is unaffected
    assert str(jobscript2) == dedent(r'''
    #!/bin/bash
    #SBATCH --job-name=test2
    echo 'Hello'
    ''').strip()

def test_read_invalid_attribute(caplog, tmpdir):
    JobScript.read_defaults() # reset
    caplog.setLevel(logging.DEBUG, logger='clusterjob')
    jobscript = JobScript(body="echo '{text}'", jobname="test")

    inidata = dedent(r'''
    [Attributes]
    _remote = login.cluster.edu
    ''')
    p = tmpdir.join("job.ini")
    p.write(inidata)
    ini_filename = str(p)

    with pytest.raises(ConfigParserError) as exc_info:
        jobscript.read_settings(ini_filename)
    assert "Key '_remote' is invalid" in str(exc_info.value)

    inidata = dedent(r'''
    [Attributes]
    key with spaces = bla
    ''')
    p = tmpdir.join("job.ini")
    p.write(inidata)
    ini_filename = str(p)

    with pytest.raises(ConfigParserError) as exc_info:
        jobscript.read_settings(ini_filename)
    assert "Key 'key with spaces' is invalid" in str(exc_info.value)


text:
created: 2019-03-21
last updated: 2019-03-21
status: Implemented
title: Handling download failures
authors:
  - aehlig
---

# Abstract

We propose to add a new named argument `allow_fail` to the methods
`download` and `download_and_extract` of the repository context,
defaulting to `False`. If set to `True`, errors in the download will
not be fatal but only reported to the caller to decide on further
action.

# Background

## Repository Rules

While Bazel was originally designed with a mono repository in mind,
it became clear that not everybody organizes their code in this
way, and additional sources of source code had to be considered.
Also, occassionally, information about the host system are needed,
e.g., the location of the host `C` compiler.

Bazel's approach to all those "non-hermetic" operations is the
concept of external repositories. An external repository is a
collection of source files that are "fetched" once and then treated
in the same hermetic way like any other source file in the main
repository, under the `@nameofexternalrepo//` name space. During
the fetch, however, arbitrary operations, including calling out to
the network or reading not a-priori declared files from the host
system, can be performed.

## Repository Rules

To obtain flexibility (as Bazel cannot anticipate all version
control systems that might be used, or other needs for non-hermetic
actions), instructions for fetching a class of external repositories
(e.g., using a particular version-control system) are described by
a piece of Starlark code. Similar to regular rules, the Starlark
function of those so-called _repository rules_ expects a single
argument, in this case a _repository context_. This context provides
various functions needed to "fetch" an external repository. These
include basic write operations, e.g., functions to create a file
or a symbolic link. Then, it provides a `download` function to
download a file from a list of provided URLs and (optionally) verify
the file agains a known good hash. Finally, it provides with the
`execute` function a generic way to interact with the operating
system by allowing to execute arbitrary commands and inspect
`stdout`, `stderr`, and the exit code. Currently, arbitrary exit
codes of `execute`d commands can be handled by the rule, whereas
an unsucceful attempt to `download` a file results in the whole
external repository being considered failed.

## Repository Cache

The most common way of fetching external dependencies is to fetch
an archive, unpack it, and maybe patch it or add a `BUILD` file. As
Bazel needs to be aware of all dependencies, it is not uncommon, that
several workspaces have dependencies in common. To avoid refetching
the respective archives for every workspace, bazel has a cache,
indexed by the hash of the downloaded file. The hash specified
when downloading a file not only serves as means of verifying the
integrity of the download, it will also be used to avoid unnecessary
downloads, if the file is already in cache.

# Proposal

## Proposed Change

We propose to add an additional, named, parameter `allow_fail` to
`ctx.download` and `ctx.download_and_extract`. It will be boolean
and default to `False`. If set to `True`, failures to download the
specified file will not be fatal, i.e., not mark the "fetch" of the
external repository as failed. To allow the repository rule to act
depending on success or failure of the download, the returned struct
will contain an additional entry `success` indicating the success
of the download. Moreover, if (and only if) `allow_fail` is set to
`True`, the list of URLs provided may also be empty (resulting in
a pure cache probe).

## Use Case: Avoid uncessary credential requests

A recent [feature request](https://github.com/bazelbuild/bazel/issues/7635)
asked support cache probes. The reason for this feature request
is that files are used where some form of credential is needed to
download—and obtaining that may take time/user interaction/network
access. Now, if the file is already in cache, it would not be necessary
to obtain the credential, but this could not be benefitted from,
as it would require an ability to probe the cache. This proposal
obviously solves this problem, and, in fact, is the third option
in said feature request.

## Use Case: `http_archive` at head

With the introduction of [resolved
files](https://blog.bazel.build/2018/09/28/first-class-resolved-file.html),
it has become desirable to no only write reproducible rules fetching
sources, but also ones "following head". For version control systems,
this requires checking out the `master` branch and recording the
currently latest commit in this branch; both are tasks that can
easily be accomplished by `ctx.execute`. When following release
archives, however, the task of updating basically consists in probing
the (predictable) URL of the next release(s). To allow rules to
do this, an attempt to download is necessary, where a failure in
the download can be handled by the rule. It seems cleaner to add
this option to the `ctx.download` functionality, than relying on
constructs like `ctx.execute(["wget", ...])`; on the one hand, it
is more portable (which of `wget`, `curl`, `fetch`, etc, should be
assumed to be present) and on the other hand, upon success, the file
directly ends up in cache, without the need of a second download.

# Backward-compatibility

As long as the new `allow_fail` option is not explicitly set, the
behaviour of `ctx.download` and `ctx.download_and_extract` does not
change. The struct returned will have an additional entry `success`,
but a struct was choosen precisely as an extension interface to
allow returning additional information in the future.


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_EXPRESSIONS_TSVECDVECMULTEXPR_H_
#define _BLAZE_MATH_EXPRESSIONS_TSVECDVECMULTEXPR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <stdexcept>
#include <blaze/math/constraints/DenseVector.h>
#include <blaze/math/constraints/SparseVector.h>
#include <blaze/math/constraints/TransposeFlag.h>
#include <blaze/math/expressions/DenseVector.h>
#include <blaze/math/expressions/SparseVector.h>
#include <blaze/math/traits/MultTrait.h>
#include <blaze/util/logging/FunctionTrace.h>
#include <blaze/util/Types.h>
#include <blaze/util/typetraits/RemoveReference.h>

namespace blaze {

//=================================================================================================
//
//  GLOBAL BINARY ARITHMETIC OPERATORS
//
//=================================================================================================

//*************************************************************************************************
/*!\brief Multiplication operator for the scalar product (inner product) of a sparse and a
//        dense vector (\f$ s=\vec{a}*\vec{b} \f$).
// \ingroup sparse_vector
//
// \param lhs The left-hand side sparse vector for the inner product.
// \param rhs The right-hand side dense vector for the inner product.
// \return The scalar product.
// \exception std::invalid_argument Vector sizes do not match.
//
// This operator represents the scalar product (inner product) of a sparse vector and a dense
// vector:

   \code
   using blaze::columnVector;
   using blaze::rowVector;

   blaze::CompressedVector<double,rowVector> a;
   blaze::DynamicVector<double,columnVector> b;
   blaze::real res;
   // ... Resizing and initialization
   res = a * b;
   \endcode

// The operator returns a scalar value of the higher-order element type of the two involved
// vector element types \a T1::ElementType and \a T2::ElementType. Both vector types \a T1
// and \a T2 as well as the two element types \a T1::ElementType and \a T2::ElementType have
// to be supported by the MultTrait class template.\n
// In case the current sizes of the two given vectors don't match, a \a std::invalid_argument
// is thrown.
*/
template< typename T1    // Type of the left-hand side sparse vector
        , typename T2 >  // Type of the right-hand side dense vector
inline const typename MultTrait<typename T1::ElementType,typename T2::ElementType>::Type
   operator*( const SparseVector<T1,true>& lhs, const DenseVector<T2,false>& rhs )
{
   BLAZE_FUNCTION_TRACE;

   typedef typename T1::CompositeType           Lhs;            // Composite type of the left-hand side sparse vector expression
   typedef typename T2::CompositeType           Rhs;            // Composite type of the right-hand side dense vector expression
   typedef typename RemoveReference<Lhs>::Type  X1;             // Auxiliary type for the left-hand side composite type
   typedef typename RemoveReference<Rhs>::Type  X2;             // Auxiliary type for the right-hand side composite type
   typedef typename X1::ElementType             ET1;            // Element type of the left-hand side sparse vector expression
   typedef typename X2::ElementType             ET2;            // Element type of the right-hand side dense vector expression
   typedef typename MultTrait<ET1,ET2>::Type    MultType;       // Multiplication result type
   typedef typename X1::ConstIterator           ConstIterator;  // Iterator type of the left-hand sparse vector expression

   BLAZE_CONSTRAINT_MUST_BE_SPARSE_VECTOR_TYPE( T1 );
   BLAZE_CONSTRAINT_MUST_BE_DENSE_VECTOR_TYPE ( T2 );
   BLAZE_CONSTRAINT_MUST_BE_ROW_VECTOR_TYPE   ( T1 );
   BLAZE_CONSTRAINT_MUST_BE_COLUMN_VECTOR_TYPE( T2 );

   if( (~lhs).size() != (~rhs).size() )
      throw std::invalid_argument( "Vector sizes do not match" );

   if( (~lhs).nonZeros() == 0UL ) return MultType();

   Lhs left ( ~lhs );
   Rhs right( ~rhs );

   ConstIterator element( left.begin() );
   MultType sp( element->value() * right[ element->index() ] );
   ++element;

   for( ; element!=left.end(); ++element )
      sp += element->value() * right[ element->index() ];

   return sp;
}
//*************************************************************************************************

} // namespace blaze

#endif


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = detectBrowser;
// http://stackoverflow.com/questions/5899783/detect-safari-chrome-ie-firefox-opera-with-user-agent
var detectBrowserResult_ = null;

function detectBrowser() {
  if (detectBrowserResult_) {
    return detectBrowserResult_;
  }

  if (typeof navigator !== 'undefined') {
    var isExplorer = navigator.userAgent.indexOf('MSIE') > -1;
    var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
    var isOpera = navigator.userAgent.toLowerCase().indexOf('op') > -1;

    var isChrome = navigator.userAgent.indexOf('Chrome') > -1;
    var isSafari = navigator.userAgent.indexOf('Safari') > -1;

    if (isChrome && isSafari) {
      isSafari = false;
    }

    if (isChrome && isOpera) {
      isChrome = false;
    }

    detectBrowserResult_ = { isExplorer: isExplorer, isFirefox: isFirefox, isOpera: isOpera, isChrome: isChrome, isSafari: isSafari };
    return detectBrowserResult_;
  }

  detectBrowserResult_ = {
    isChrome: true,
    isExplorer: false,
    isFirefox: false,
    isOpera: false,
    isSafari: false
  };

  return detectBrowserResult_;
}


text:
namespace transducers {
    namespace details {
        template<typename _Rdr>
        class RepeatingReducer : public toolbox::base_reducing_function<_Rdr>
        {
            size_t const m_repetitionsRemaining;
        public:
            RepeatingReducer(size_t repetitions, _Rdr&& reducer) :
                m_repetitionsRemaining(repetitions),
                toolbox::base_reducing_function<_Rdr>(std::move(reducer)) {}

            template<typename _Re, typename _In>
            auto step(_Re&& reduction, _In&& input)
            {
                auto & reducer = toolbox::base_reducing_function<_Rdr>::m_rf;

                using result_type = decltype(reducer.step(std::forward<_Re>(reduction), std::declval<_In>()));
                result_type my_reduction = std::forward<_Re>(reduction);
                _In repeated = std::forward<_In>(input);

                for (auto i = 0; i < m_repetitionsRemaining; i++)
                {
                    my_reduction = reducer.step(my_reduction, repeated);

                    if (is_reduced(my_reduction))
                    {
                        break;
                    }
                }

                return my_reduction;
            }
        };

        class RepeatingTransducer
        {
            size_t m_repetitions;
        public:
            template<typename _InTyList>
            using output_typelist = _InTyList;

            RepeatingTransducer(size_t repetitions) : m_repetitions(repetitions) {}

            template<typename _Rdr>
            auto apply(_Rdr&& reducer) const
            {
                return RepeatingReducer<_Rdr>{m_repetitions, std::forward<_Rdr>(reducer)};
            }
        };
    }

    auto repeating(size_t repetitions)
    {
        return details::RepeatingTransducer{ repetitions };
    }
}


text:
<?php
session_start();
if(isset($_SESSION['apr']) )
{
  if($_SESSION['apr'] == 0)
  {
      header("location:./server/headerredirect.php?url=appr");
  }
}
if(isset($_SESSION['email']))
{
  if(strlen($_SESSION['email']) > 4 )
  {
    ?>
<!DOCTYPE html>

    <title>Update Blog</title>

       <link href="./__primg/ixon.png" rel="icon" type="image/png" />
        <link rel="stylesheet" type="text/css" href="./libs/css/materialize.min.css" />
       <link rel="stylesheet" type="text/css" href="./css/editorEdit.css" />
        <link rel="stylesheet" type="text/css" href="./styles/style_default.css" />
            <link rel="stylesheet" href="./css/webspin.css"/>

           <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

Profile

<a href="./@<?php echo $_SESSION['blogId']; ?>/" target="_blank" class="waves-effect waves-green">Visit Blog

New Post

Update Post

Sign out

<form class="form_hide" action="./editpost.php" method="post">
<input type="hidden" id="repl" value="" name="repl" />
<input type="hidden" id="idEd" value="" name="idEd" />
<input type="hidden" id="textContentToEdit" value="" name="txt" />
<input type="submit" id="sbmt_frm" class="form_hide" />
</form>

Update your Blog.

<?php

    include('./server/simple_html_dom.php');
    $blogId = $_SESSION['blogId'];
    $filePath = './@'.$blogId.'/index.php';
    $newButtons = '
'.'<button class="btn waves-effect waves-light orange darken-3 editPostListen"  >Edit post</button><button class="btn waves-effect waves-light deletePostListen deep-orange accent-4 left50 modal-trigger" href="#modal1" >Delete</button>
';

    $blogPostContent = file_get_html($filePath);
      foreach($blogPostContent->find('div') as $div)
      {
        if($div->class == 'postArea')
        {
          echo $div = str_replace('

',$newButtons,$div);
        }
      }
 ?>

            <svg class="spinner-container" width="65px" height="65px" viewBox="0 0 52 52">
              <circle class="path" cx="26px" cy="26px" r="20px" fill="none" stroke-width="4px"></circle>
            </svg>

Please Wait...

Post Deleted Succesfully !

                Close

<?php
    }
    else{
      header("location:./server/headerredirect.php?url=signin");
    }
}
else{
  header("location:./server/headerredirect.php?url=signin");
}

 ?>


text:
import {
  SUBMISSION_VIDEO,
  SUBMISSION_QUIZ,
  SUBMISSION_STATUS_PENDING,
  SUBMISSION_STATUS_SUBMITTED,
  REVIEW_STATUS_APPROVED,
  REVIEW_STATUS_REJECTED,
  REVIEW_STATUS_PENDING
} from "../constants"

import type { BootcampRun, BootcampRunEnrollment } from "./bootcampTypes"
import type { User } from "./authTypes"
import type { HttpResponse } from "./httpTypes"

export type Application = {
  id:               number,
  state:            string,
  created_on:       any,
  bootcamp_run:     BootcampRun,
  certificate_link: string,
  enrollment:       ?BootcampRunEnrollment,
  has_payments:     boolean,
}

export type ValidAppStepType = SUBMISSION_VIDEO | SUBMISSION_QUIZ

export type ApplicationRunStep = {
  id:              number,
  due_date:        string,
  step_order:      number,
  submission_type: ValidAppStepType
}

export type ValidReviewStatusType = REVIEW_STATUS_APPROVED | REVIEW_STATUS_REJECTED | REVIEW_STATUS_PENDING
export type ValidSubmissionStatusType = SUBMISSION_STATUS_PENDING | SUBMISSION_STATUS_SUBMITTED

export type ApplicationSubmission = {
  id:                      number,
  run_application_step_id: number,
  submitted_date:          ?string,
  submission_status:       ValidSubmissionStatusType,
  review_status:           ValidReviewStatusType,
  review_status_date:      ?string,
  interview_url:           ?string,
  take_interview_url:      ?string,
  interview_token:         ?string,
}

export type LegacyOrderPartial = {
  id:         number,
  status:     string,
  created_on: string,
  updated_on: string
}

export type ApplicationOrder = {
  total_price_paid: number,
  payment_method:   string
} & LegacyOrderPartial

export type ResumeLinkedInDetail = {
  resume_url:         ?string,
  linkedin_url:       ?string,
  resume_upload_date: ?string
}

export type ApplicationDetail = ResumeLinkedInDetail & {
  id:                    number,
  state:                 string,
  bootcamp_run:          BootcampRun,
  payment_deadline:      string,
  is_paid_in_full:       boolean,
  run_application_steps: Array<ApplicationRunStep>,
  submissions:           Array<ApplicationSubmission>,
  orders:                Array<ApplicationOrder>,
  created_on:            string,
  price:                 number,
  user:                  User,
  enrollment:            ?BootcampRunEnrollment,
}

export type SubmissionReview = {
  id: number,
  learner: User,
  review_status: ?string,
  interview_url: ?string,
  application_id: number,
}

export type ApplicationDetailState = {
  [string]: ApplicationDetail
}

export type SubmissionReviewState = {
  [string]: SubmissionReview
}

type BootcampFacetOption = {
  id:    number,
  title: string,
  start_date: string,
  end_date: string,
  count: number
}

type ReviewStatusFacetOption = {
  review_status: string,
  count:         number
}

export type FacetOption = BootcampFacetOption | ReviewStatusFacetOption

export type SubmissionFacetData = {
  bootcamp_runs:   Array<BootcampFacetOption>,
  review_statuses: Array<ReviewStatusFacetOption>
}

export type VideoInterviewResponse = {
  interview_link: string,
}

export type NewApplicationResponse = HttpResponse<Application>
export type ResumeLinkedInResponse = HttpResponse<ResumeLinkedInDetail>
export type ApplicationDetailResponse = HttpResponse<ApplicationDetail>


text:
@font-face {
	font-family: "Love Ya Like A Sister";
	font-style: normal;
	font-weight: 400;
	src: url("../fonts/LoveYaLikeASister.ttf");
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ProductBundle\Form\Type;

use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

/**
 * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk>
 */
final class ProductTranslationType extends AbstractResourceType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('name', TextType::class, [
                'label' => 'sylius.form.product.name',
            ])
            ->add('slug', TextType::class, [
                'label' => 'sylius.form.product.slug',
            ])
            ->add('description', TextareaType::class, [
                'required' => false,
                'label' => 'sylius.form.product.description',
            ])
            ->add('metaKeywords', TextType::class, [
                'required' => false,
                'label' => 'sylius.form.product.meta_keywords',
            ])
            ->add('metaDescription', TextType::class, [
                'required' => false,
                'label' => 'sylius.form.product.meta_description',
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix(): string
    {
        return 'sylius_product_translation';
    }
}


text:
<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
Yii::setAlias('@site', dirname(dirname(__DIR__)) . '/site');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('@web', '/');
Yii::setAlias('@webroot', '@site/web');
Yii::setAlias('@assets', dirname(dirname(__DIR__)) . '/site/assets/publish');
Yii::setAlias('@graphImgPath', '@webroot/charts');
Yii::setAlias('@graphImgUrl', '/charts');


text:
package org.apache.hadoop.yarn.server.resourcemanager.resource;

import static org.apache.hadoop.yarn.util.resource.Resources.*;
import static org.junit.Assert.*;
import org.junit.Test;

public class TestResources {
  @Test(timeout=1000)
  public void testFitsIn() {
    assertTrue(fitsIn(createResource(1, 1), createResource(2, 2)));
    assertTrue(fitsIn(createResource(2, 2), createResource(2, 2)));
    assertFalse(fitsIn(createResource(2, 2), createResource(1, 1)));
    assertFalse(fitsIn(createResource(1, 2), createResource(2, 1)));
    assertFalse(fitsIn(createResource(2, 1), createResource(1, 2)));
  }

  @Test(timeout=1000)
  public void testComponentwiseMin() {
    assertEquals(createResource(1, 1),
        componentwiseMin(createResource(1, 1), createResource(2, 2)));
    assertEquals(createResource(1, 1),
        componentwiseMin(createResource(2, 2), createResource(1, 1)));
    assertEquals(createResource(1, 1),
        componentwiseMin(createResource(1, 2), createResource(2, 1)));
  }
}


text:
"""broadclass URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r"^$", views.home, name="home")
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r"^$", Home.as_view(), name="home")
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r"^blog/", include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin

from .settings import DEBUG

from . import views

urlpatterns = [
    # provisional
    # url(r"^$", views.home, name="home"),
    # url(r"^dashboard/", include("dashboard.urls")),
    # url(r"^questions/", include("questions.urls")),
    # url(r"^get_csrf_token/$", views.get_csrf_token)
]

if DEBUG:
    urlpatterns.append(url(r"^admin/", include(admin.site.urls)))