text:
<?php

/**
 * Class for parsing MIME messages
 *
 * @package    Framework
 * @subpackage Storage
 * @author     Thomas Bruederli <roundcube@gmail.com>
 * @author     Aleksander Machniak <alec@alec.pl>
 */
class rcube_mime
{
    private static $default_charset;

    /**
     * Object constructor.
     */
    function __construct($default_charset = null)
    {
        self::$default_charset = $default_charset;
    }

    /**
     * Returns message/object character set name
     *
     * @return string Characted set name
     */
    public static function get_charset()
    {
        if (self::$default_charset) {
            return self::$default_charset;
        }

        if ($charset = rcube::get_instance()->config->get('default_charset')) {
            return $charset;
        }

        return RCUBE_CHARSET;
    }

    /**
     * Parse the given raw message source and return a structure
     * of rcube_message_part objects.
     *
     * It makes use of the PEAR:Mail_mimeDecode library
     *
     * @param string  The message source
     * @return object rcube_message_part The message structure
     */
    public static function parse_message($raw_body)
    {
        $mime = new Mail_mimeDecode($raw_body);
        $struct = $mime->decode(array('include_bodies' => true, 'decode_bodies' => true));
        return self::structure_part($struct);
    }

    /**
     * Recursive method to convert a Mail_mimeDecode part into a rcube_message_part object
     *
     * @param object  A message part struct
     * @param int     Part count
     * @param string  Parent MIME ID
     *
     * @return object rcube_message_part
     */
    private static function structure_part($part, $count=0, $parent='')
    {
        $struct = new rcube_message_part;
        $struct->mime_id          = $part->mime_id ?: (empty($parent) ? (string)$count : "$parent.$count");
        $struct->headers          = $part->headers;
        $struct->mimetype         = $part->ctype_primary . '/' . $part->ctype_secondary;
        $struct->ctype_primary    = $part->ctype_primary;
        $struct->ctype_secondary  = $part->ctype_secondary;
        $struct->ctype_parameters = $part->ctype_parameters;

        if ($part->headers['content-transfer-encoding']) {
            $struct->encoding = $part->headers['content-transfer-encoding'];
        }

        if ($part->ctype_parameters['charset']) {
            $struct->charset = $part->ctype_parameters['charset'];
        }

        $part_charset = $struct->charset ?: self::get_charset();

        // determine filename
        if (($filename = $part->d_parameters['filename']) || ($filename = $part->ctype_parameters['name'])) {
            $struct->filename = rcube_mime::decode_mime_string($filename, $part_charset);
        }

        $struct->body        = $part->body;
        $struct->size        = strlen($part->body);
        $struct->disposition = $part->disposition;

        foreach ((array)$part->parts as $child_part) {
            $struct->parts[] = self::structure_part($child_part, ++$count, $struct->mime_id);
        }

        return $struct;
    }

    /**
     * Split an address list into a structured array list
     *
     * @param string  $input    Input string
     * @param int     $max      List only this number of addresses
     * @param boolean $decode   Decode address strings
     * @param string  $fallback Fallback charset if none specified
     * @param boolean $addronly Return flat array with e-mail addresses only
     *
     * @return array Indexed list of addresses
     */
    static function decode_address_list($input, $max = null, $decode = true, $fallback = null, $addronly = false)
    {
        $a   = self::parse_address_list($input, $decode, $fallback);
        $out = array();
        $j   = 0;

        // Special chars as defined by RFC 822 need to in quoted string (or escaped).
        $special_chars = '[\(\)\<\>\\\.\[\]@,;:"]';

        if (!is_array($a))
            return $out;

        foreach ($a as $val) {
            $j++;
            $address = trim($val['address']);

            if ($addronly) {
                $out[$j] = $address;
            }
            else {
                $name = trim($val['name']);
                if ($name && $address && $name != $address)
                    $string = sprintf('%s <%s>', preg_match("/$special_chars/", $name) ? '"'.addcslashes($name, '"').'"' : $name, $address);
                else if ($address)
                    $string = $address;
                else if ($name)
                    $string = $name;

                $out[$j] = array('name' => $name, 'mailto' => $address, 'string' => $string);
            }

            if ($max && $j==$max)
                break;
        }

        return $out;
    }

    /**
     * Decode a message header value
     *
     * @param string  $input         Header value
     * @param string  $fallback      Fallback charset if none specified
     *
     * @return string Decoded string
     */
    public static function decode_header($input, $fallback = null)
    {
        $str = self::decode_mime_string((string)$input, $fallback);

        return $str;
    }

    /**
     * Decode a mime-encoded string to internal charset
     *
     * @param string $input    Header value
     * @param string $fallback Fallback charset if none specified
     *
     * @return string Decoded string
     */
    public static function decode_mime_string($input, $fallback = null)
    {
        $default_charset = !empty($fallback) ? $fallback : self::get_charset();

        // rfc: all line breaks or other characters not found
        // in the Base64 Alphabet must be ignored by decoding software
        // delete all blanks between MIME-lines, differently we can
        // receive unnecessary blanks and broken utf-8 symbols
        $input = preg_replace("/\?=\s+=\?/", '?==?', $input);

        // encoded-word regexp
        $re = '/=\?([^?]+)\?([BbQq])\?([^\n]*?)\?=/';

        // Find all RFC2047's encoded words
        if (preg_match_all($re, $input, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
            // Initialize variables
            $tmp   = array();
            $out   = '';
            $start = 0;

            foreach ($matches as $idx => $m) {
                $pos      = $m[0][1];
                $charset  = $m[1][0];
                $encoding = $m[2][0];
                $text     = $m[3][0];
                $length   = strlen($m[0][0]);

                // Append everything that is before the text to be decoded
                if ($start != $pos) {
                    $substr = substr($input, $start, $pos-$start);
                    $out   .= rcube_charset::convert($substr, $default_charset);
                    $start  = $pos;
                }
                $start += $length;

                // Per RFC2047, each string part "MUST represent an integral number
                // of characters . A multi-octet character may not be split across
                // adjacent encoded-words." However, some mailers break this, so we
                // try to handle characters spanned across parts anyway by iterating
                // through and aggregating sequential encoded parts with the same
                // character set and encoding, then perform the decoding on the
                // aggregation as a whole.

                $tmp[] = $text;
                if(isset($matches[$idx+1]))
                {
                    if ($next_match = $matches[$idx+1]) {
                        if ($next_match[0][1] == $start
                            && $next_match[1][0] == $charset
                            && $next_match[2][0] == $encoding
                        ) {
                            continue;
                        }
                    }
                }

                $count = count($tmp);
                $text  = '';

                // Decode and join encoded-word's chunks
                if ($encoding == 'B' || $encoding == 'b') {
                    // base64 must be decoded a segment at a time
                    for ($i=0; $i<$count; $i++)
                        $text .= base64_decode($tmp[$i]);
                }
                else { //if ($encoding == 'Q' || $encoding == 'q') {
                    // quoted printable can be combined and processed at once
                    for ($i=0; $i<$count; $i++)
                        $text .= $tmp[$i];

                    $text = str_replace('_', ' ', $text);
                    $text = quoted_printable_decode($text);
                }

                $out .= rcube_charset::convert($text, $charset);
                $tmp = array();
            }

            // add the last part of the input string
            if ($start != strlen($input)) {
                $out .= rcube_charset::convert(substr($input, $start), $default_charset);
            }

            // return the results
            return $out;
        }

        // no encoding information, use fallback
        return rcube_charset::convert($input, $default_charset);
    }

    /**
     * Decode a mime part
     *
     * @param string $input    Input string
     * @param string $encoding Part encoding
     *
     * @return string Decoded string
     */
    public static function decode($input, $encoding = '7bit')
    {
        switch (strtolower($encoding)) {
        case 'quoted-printable':
            return quoted_printable_decode($input);
        case 'base64':
            return base64_decode($input);
        case 'x-uuencode':
        case 'x-uue':
        case 'uue':
        case 'uuencode':
            return convert_uudecode($input);
        case '7bit':
        default:
            return $input;
        }
    }

    /**
     * Split RFC822 header string into an associative array
     */
    public static function parse_headers($headers)
    {
        $a_headers = array();
        $headers = preg_replace('/\r?\n(\t| )+/', ' ', $headers);
        $lines = explode("\n", $headers);
        $c = count($lines);

        for ($i=0; $i<$c; $i++) {
            if ($p = strpos($lines[$i], ': ')) {
                $field = strtolower(substr($lines[$i], 0, $p));
                $value = trim(substr($lines[$i], $p+1));
                if (!empty($value))
                    $a_headers[$field] = $value;
            }
        }

        return $a_headers;
    }

    /**
     * @access private
     */
    private static function parse_address_list($str, $decode = true, $fallback = null)
    {
        // remove any newlines and carriage returns before
        $str = preg_replace('/\r?\n(\s|\t)?/', ' ', $str);

        // extract list items, remove comments
        $str = self::explode_header_string(',;', $str, true);
        $result = array();

        // simplified regexp, supporting quoted local part
        $email_rx = '(\S+|("\s*(?:[^"\f\n\r\t\v\b\s]+\s*)+"))@\S+';

        foreach ($str as $key => $val) {
            $name    = '';
            $address = '';
            $val     = trim($val);

            if (preg_match('/(.*)<('.$email_rx.')>$/', $val, $m)) {
                $address = $m[2];
                $name    = trim($m[1]);
            }
            else if (preg_match('/^('.$email_rx.')$/', $val, $m)) {
                $address = $m[1];
                $name    = '';
            }
            // special case (#1489092)
            else if (preg_match('/(\s*<MAILER-DAEMON>)$/', $val, $m)) {
                $address = 'MAILER-DAEMON';
                $name    = substr($val, 0, -strlen($m[1]));
            }
            else if (preg_match('/('.$email_rx.')/', $val, $m)) {
                $name = $m[1];
            }
            else {
                $name = $val;
            }

            // dequote and/or decode name
            if ($name) {
                if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
                    $name = substr($name, 1, -1);
                    $name = stripslashes($name);
                }
                if ($decode) {
                    $name = self::decode_header($name, $fallback);
                    // some clients encode addressee name with quotes around it
                    if ($name[0] == '"' && $name[strlen($name)-1] == '"') {
                        $name = substr($name, 1, -1);
                    }
                }
            }

            if (!$address && $name) {
                $address = $name;
                $name    = '';
            }

            if ($address) {
                $address      = self::fix_email($address);
                $result[$key] = array('name' => $name, 'address' => $address);
            }
        }

        return $result;
    }

    /**
     * Explodes header (e.g. address-list) string into array of strings
     * using specified separator characters with proper handling
     * of quoted-strings and comments (RFC2822)
     *
     * @param string $separator       String containing separator characters
     * @param string $str             Header string
     * @param bool   $remove_comments Enable to remove comments
     *
     * @return array Header items
     */
    public static function explode_header_string($separator, $str, $remove_comments = false)
    {
        $length  = strlen($str);
        $result  = array();
        $quoted  = false;
        $comment = 0;
        $out     = '';

        for ($i=0; $i<$length; $i++) {
            // we're inside a quoted string
            if ($quoted) {
                if ($str[$i] == '"') {
                    $quoted = false;
                }
                else if ($str[$i] == "\\") {
                    if ($comment <= 0) {
                        $out .= "\\";
                    }
                    $i++;
                }
            }
            // we are inside a comment string
            else if ($comment > 0) {
                if ($str[$i] == ')') {
                    $comment--;
                }
                else if ($str[$i] == '(') {
                    $comment++;
                }
                else if ($str[$i] == "\\") {
                    $i++;
                }
                continue;
            }
            // separator, add to result array
            else if (strpos($separator, $str[$i]) !== false) {
                if ($out) {
                    $result[] = $out;
                }
                $out = '';
                continue;
            }
            // start of quoted string
            else if ($str[$i] == '"') {
                $quoted = true;
            }
            // start of comment
            else if ($remove_comments && $str[$i] == '(') {
                $comment++;
            }

            if ($comment <= 0) {
                $out .= $str[$i];
            }
        }

        if ($out && $comment <= 0) {
            $result[] = $out;
        }

        return $result;
    }

    /**
     * Interpret a format=flowed message body according to RFC 2646
     *
     * @param string $text Raw body formatted as flowed text
     * @param string $mark Mark each flowed line with specified character
     *
     * @return string Interpreted text with unwrapped lines and stuffed space removed
     */
    public static function unfold_flowed($text, $mark = null)
    {
        $text    = preg_split('/\r?\n/', $text);
        $last    = -1;
        $q_level = 0;
        $marks   = array();

        foreach ($text as $idx => $line) {
            if (preg_match('/^(>+)/', $line, $m)) {
                // remove quote chars
                $q    = strlen($m[1]);
                $line = preg_replace('/^>+/', '', $line);
                // remove (optional) space-staffing
                $line = preg_replace('/^ /', '', $line);

                // The same paragraph (We join current line with the previous one) when:
                // - the same level of quoting
                // - previous line was flowed
                // - previous line contains more than only one single space (and quote char(s))
                if ($q == $q_level
                    && isset($text[$last]) && $text[$last][strlen($text[$last])-1] == ' '
                    && !preg_match('/^>+ {0,1}$/', $text[$last])
                ) {
                    $text[$last] .= $line;
                    unset($text[$idx]);

                    if ($mark) {
                        $marks[$last] = true;
                    }
                }
                else {
                    $last = $idx;
                }
            }
            else {
                $q = 0;
                if ($line == '-- ') {
                    $last = $idx;
                }
                else {
                    // remove space-stuffing
                    $line = preg_replace('/^ /', '', $line);

                    if (isset($text[$last]) && $line
                        && $text[$last] != '-- '
                        && isset($text[$last][strlen($text[$last])-1])
                        && $text[$last][strlen($text[$last])-1] == ' '
                    ) {
                        $text[$last] .= $line;
                        unset($text[$idx]);

                        if ($mark) {
                            $marks[$last] = true;
                        }
                    }
                    else {
                        $text[$idx] = $line;
                        $last = $idx;
                    }
                }
            }
            $q_level = $q;
        }

        if (!empty($marks)) {
            foreach (array_keys($marks) as $mk) {
                $text[$mk] = $mark . $text[$mk];
            }
        }

        return implode("\r\n", $text);
    }

    /**
     * Wrap the given text to comply with RFC 2646
     *
     * @param string $text    Text to wrap
     * @param int    $length  Length
     * @param string $charset Character encoding of $text
     *
     * @return string Wrapped text
     */
    public static function format_flowed($text, $length = 72, $charset=null)
    {
        $text = preg_split('/\r?\n/', $text);

        foreach ($text as $idx => $line) {
            if ($line != '-- ') {
                if (preg_match('/^(>+)/', $line, $m)) {
                    // remove quote chars
                    $level  = strlen($m[1]);
                    $line   = preg_replace('/^>+/', '', $line);
                    // remove (optional) space-staffing and spaces before the line end
                    $line   = preg_replace('/(^ | +$)/', '', $line);
                    $prefix = str_repeat('>', $level) . ' ';
                    $line   = $prefix . self::wordwrap($line, $length - $level - 2, " \r\n$prefix", false, $charset);
                }
                else if ($line) {
                    $line = self::wordwrap(rtrim($line), $length - 2, " \r\n", false, $charset);
                    // space-stuffing
                    $line = preg_replace('/(^|\r\n)(From| |>)/', '\\1 \\2', $line);
                }

                $text[$idx] = $line;
            }
        }

        return implode("\r\n", $text);
    }

    /**
     * Improved wordwrap function with multibyte support.
     * The code is based on Zend_Text_MultiByte::wordWrap().
     *
     * @param string $string      Text to wrap
     * @param int    $width       Line width
     * @param string $break       Line separator
     * @param bool   $cut         Enable to cut word
     * @param string $charset     Charset of $string
     * @param bool   $wrap_quoted When enabled quoted lines will not be wrapped
     *
     * @return string Text
     */
    public static function wordwrap($string, $width=75, $break="\n", $cut=false, $charset=null, $wrap_quoted=true)
    {
        // Note: Never try to use iconv instead of mbstring functions here
        //       Iconv's substr/strlen are 100x slower (#1489113)

        if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) {
            mb_internal_encoding($charset);
        }

        // Convert \r\n to \n, this is our line-separator
        $string       = str_replace("\r\n", "\n", $string);
        $separator    = "\n"; // must be 1 character length
        $result       = array();

        while (($stringLength = mb_strlen($string)) > 0) {
            $breakPos = mb_strpos($string, $separator, 0);

            // quoted line (do not wrap)
            if ($wrap_quoted && $string[0] == '>') {
                if ($breakPos === $stringLength - 1 || $breakPos === false) {
                    $subString = $string;
                    $cutLength = null;
                }
                else {
                    $subString = mb_substr($string, 0, $breakPos);
                    $cutLength = $breakPos + 1;
                }
            }
            // next line found and current line is shorter than the limit
            else if ($breakPos !== false && $breakPos < $width) {
                if ($breakPos === $stringLength - 1) {
                    $subString = $string;
                    $cutLength = null;
                }
                else {
                    $subString = mb_substr($string, 0, $breakPos);
                    $cutLength = $breakPos + 1;
                }
            }
            else {
                $subString = mb_substr($string, 0, $width);

                // last line
                if ($breakPos === false && $subString === $string) {
                    $cutLength = null;
                }
                else {
                    $nextChar = mb_substr($string, $width, 1);

                    if ($nextChar === ' ' || $nextChar === $separator) {
                        $afterNextChar = mb_substr($string, $width + 1, 1);

                        // Note: mb_substr() does never return False
                        if ($afterNextChar === false || $afterNextChar === '') {
                            $subString .= $nextChar;
                        }

                        $cutLength = mb_strlen($subString) + 1;
                    }
                    else {
                        $spacePos = mb_strrpos($subString, ' ', 0);

                        if ($spacePos !== false) {
                            $subString = mb_substr($subString, 0, $spacePos);
                            $cutLength = $spacePos + 1;
                        }
                        else if ($cut === false) {
                            $spacePos = mb_strpos($string, ' ', 0);

                            if ($spacePos !== false && ($breakPos === false || $spacePos < $breakPos)) {
                                $subString = mb_substr($string, 0, $spacePos);
                                $cutLength = $spacePos + 1;
                            }
                            else if ($breakPos === false) {
                                $subString = $string;
                                $cutLength = null;
                            }
                            else {
                                $subString = mb_substr($string, 0, $breakPos);
                                $cutLength = $breakPos + 1;
                            }
                        }
                        else {
                            $cutLength = $width;
                        }
                    }
                }
            }

            $result[] = $subString;

            if ($cutLength !== null) {
                $string = mb_substr($string, $cutLength, ($stringLength - $cutLength));
            }
            else {
                break;
            }
        }

        if ($charset && $charset != RCUBE_CHARSET && function_exists('mb_internal_encoding')) {
            mb_internal_encoding(RCUBE_CHARSET);
        }

        return implode($break, $result);
    }

    /**
     * A method to guess the mime_type of an attachment.
     *
     * @param string $path      Path to the file or file contents
     * @param string $name      File name (with suffix)
     * @param string $failover  Mime type supplied for failover
     * @param boolean $is_stream   Set to True if $path contains file contents
     * @param boolean $skip_suffix Set to True if the config/mimetypes.php mappig should be ignored
     *
     * @return string
     * @author Till Klampaeckel <till@php.net>
     * @see    http://de2.php.net/manual/en/ref.fileinfo.php
     * @see    http://de2.php.net/mime_content_type
     */
    public static function file_content_type($path, $name, $failover = 'application/octet-stream', $is_stream = false, $skip_suffix = false)
    {
        static $mime_ext = array();

        $mime_type  = null;
        $config     = rcube::get_instance()->config;
        $mime_magic = $config->get('mime_magic');

        if (!$skip_suffix && empty($mime_ext)) {
            foreach ($config->resolve_paths('mimetypes.php') as $fpath) {
                $mime_ext = array_merge($mime_ext, (array) @include($fpath));
            }
        }

        // use file name suffix with hard-coded mime-type map
        if (!$skip_suffix && is_array($mime_ext) && $name) {
            if ($suffix = substr($name, strrpos($name, '.')+1)) {
                $mime_type = $mime_ext[strtolower($suffix)];
            }
        }

        // try fileinfo extension if available
        if (!$mime_type && function_exists('finfo_open')) {
            // null as a 2nd argument should be the same as no argument
            // this however is not true on all systems/versions
            if ($mime_magic) {
                $finfo = finfo_open(FILEINFO_MIME, $mime_magic);
            }
            else {
                $finfo = finfo_open(FILEINFO_MIME);
            }

            if ($finfo) {
                if ($is_stream)
                    $mime_type = finfo_buffer($finfo, $path);
                else
                    $mime_type = finfo_file($finfo, $path);
                finfo_close($finfo);
            }
        }

        // try PHP's mime_content_type
        if (!$mime_type && !$is_stream && function_exists('mime_content_type')) {
            $mime_type = @mime_content_type($path);
        }

        // fall back to user-submitted string
        if (!$mime_type) {
            $mime_type = $failover;
        }
        else {
            // Sometimes (PHP-5.3?) content-type contains charset definition,
            // Remove it (#1487122) also "charset=binary" is useless
            $mime_type = array_shift(preg_split('/[; ]/', $mime_type));
        }

        return $mime_type;
    }

    /**
     * Get mimetype => file extension mapping
     *
     * @param string Mime-Type to get extensions for
     *
     * @return array List of extensions matching the given mimetype or a hash array
     *               with ext -> mimetype mappings if $mimetype is not given
     */
    public static function get_mime_extensions($mimetype = null)
    {
        static $mime_types, $mime_extensions;

        // return cached data
        if (is_array($mime_types)) {
            return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
        }

        // load mapping file
        $file_paths = array();

        if ($mime_types = rcube::get_instance()->config->get('mime_types')) {
            $file_paths[] = $mime_types;
        }

        // try common locations
        if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
            $file_paths[] = 'C:/xampp/apache/conf/mime.types.';
        }
        else {
            $file_paths[] = '/etc/mime.types';
            $file_paths[] = '/etc/httpd/mime.types';
            $file_paths[] = '/etc/httpd2/mime.types';
            $file_paths[] = '/etc/apache/mime.types';
            $file_paths[] = '/etc/apache2/mime.types';
            $file_paths[] = '/etc/nginx/mime.types';
            $file_paths[] = '/usr/local/etc/httpd/conf/mime.types';
            $file_paths[] = '/usr/local/etc/apache/conf/mime.types';
        }

        foreach ($file_paths as $fp) {
            if (@is_readable($fp)) {
                $lines = file($fp, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
                break;
            }
        }

        $mime_types = $mime_extensions = array();
        $regex = "/([\w\+\-\.\/]+)\s+([\w\s]+)/i";
        foreach((array)$lines as $line) {
             // skip comments or mime types w/o any extensions
            if ($line[0] == '#' || !preg_match($regex, $line, $matches))
                continue;

            $mime = $matches[1];
            foreach (explode(' ', $matches[2]) as $ext) {
                $ext = trim($ext);
                $mime_types[$mime][] = $ext;
                $mime_extensions[$ext] = $mime;
            }
        }

        // fallback to some well-known types most important for daily emails
        if (empty($mime_types)) {
            foreach (rcube::get_instance()->config->resolve_paths('mimetypes.php') as $fpath) {
                $mime_extensions = array_merge($mime_extensions, (array) @include($fpath));
            }

            foreach ($mime_extensions as $ext => $mime) {
                $mime_types[$mime][] = $ext;
            }
        }

        // Add some known aliases that aren't included by some mime.types (#1488891)
        // the order is important here so standard extensions have higher prio
        $aliases = array(
            'image/gif'      => array('gif'),
            'image/png'      => array('png'),
            'image/x-png'    => array('png'),
            'image/jpeg'     => array('jpg', 'jpeg', 'jpe'),
            'image/jpg'      => array('jpg', 'jpeg', 'jpe'),
            'image/pjpeg'    => array('jpg', 'jpeg', 'jpe'),
            'image/tiff'     => array('tif'),
            'message/rfc822' => array('eml'),
            'text/x-mail'    => array('eml'),
        );

        foreach ($aliases as $mime => $exts) {
            $mime_types[$mime] = array_unique(array_merge((array) $mime_types[$mime], $exts));

            foreach ($exts as $ext) {
                if (!isset($mime_extensions[$ext])) {
                    $mime_extensions[$ext] = $mime;
                }
            }
        }

        return $mimetype ? $mime_types[$mimetype] : $mime_extensions;
    }

    /**
     * Detect image type of the given binary data by checking magic numbers.
     *
     * @param string $data  Binary file content
     *
     * @return string Detected mime-type or jpeg as fallback
     */
    public static function image_content_type($data)
    {
        $type = 'jpeg';
        if      (preg_match('/^\x89\x50\x4E\x47/', $data)) $type = 'png';
        else if (preg_match('/^\x47\x49\x46\x38/', $data)) $type = 'gif';
        else if (preg_match('/^\x00\x00\x01\x00/', $data)) $type = 'ico';
    //  else if (preg_match('/^\xFF\xD8\xFF\xE0/', $data)) $type = 'jpeg';

        return 'image/' . $type;
    }

    /**
     * Try to fix invalid email addresses
     */
    public static function fix_email($email)
    {
        $parts = rcube_utils::explode_quoted_string('@', $email);
        foreach ($parts as $idx => $part) {
            // remove redundant quoting (#1490040)
            if ($part[0] == '"' && preg_match('/^"([a-zA-Z0-9._+=-]+)"$/', $part, $m)) {
                $parts[$idx] = $m[1];
            }
        }

        return implode('@', $parts);
    }
}


text:
import os
import numpy as np

from transformers import (
    AutoTokenizer,
    EvalPrediction,
    Trainer,
    TrainingArguments,
    default_data_collator
)

from trainer import model, metadata, utils

def compute_metrics(p: EvalPrediction):
    preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions
    preds = np.argmax(preds, axis=1)
    return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()}

def train(args, model, train_dataset, test_dataset):
    """Create the training loop to load pretrained model and tokenizer and
    start the training process

    Args:
      args: read arguments from the runner to set training hyperparameters
      model: The neural network that you are training
      train_dataset: The training dataset
      test_dataset: The test dataset for evaluation
    """

    # initialize the tokenizer
    tokenizer = AutoTokenizer.from_pretrained(
        metadata.PRETRAINED_MODEL_NAME,
        use_fast=True,
    )

    # set training arguments
    training_args = TrainingArguments(
        evaluation_strategy="epoch",
        learning_rate=args.learning_rate,
        per_device_train_batch_size=args.batch_size,
        per_device_eval_batch_size=args.batch_size,
        num_train_epochs=args.num_epochs,
        weight_decay=args.weight_decay,
        output_dir=os.path.join("/tmp", args.model_name)
    )

    # initialize our Trainer
    trainer = Trainer(
        model,
        training_args,
        train_dataset=train_dataset,
        eval_dataset=test_dataset,
        data_collator=default_data_collator,
        tokenizer=tokenizer,
        compute_metrics=compute_metrics
    )

    # training
    trainer.train()
    return trainer

def run(args):
    """Load the data, train, evaluate, and export the model for serving and
     evaluating.

    Args:
      args: experiment parameters.
    """
    # Open our dataset
    train_dataset, test_dataset = utils.load_data(args)

    label_list = train_dataset.unique("label")
    num_labels = len(label_list)

    # Create the model, loss function, and optimizer
    text_classifier = model.create(num_labels=num_labels)

    # Train / Test the model
    trainer = train(args, text_classifier, train_dataset, test_dataset)

    # Export the trained model
    trainer.save_model(os.path.join("/tmp", args.model_name))

    # Save the model to GCS
    if args.job_dir:
        utils.save_model(args)

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Neighborly::Balanced::Bankaccount::DelayedPayment do
  let(:customer)     { double('::Balanced::Customer') }
  let(:contribution) { double('Contribution', value: 1234).as_null_object }
  let(:bank_account) { double('::Balanced::BankAccount', uri: '/ABANK') }
  let(:attributes)   { { pay_fee: '1', use_bank: bank_account.uri } }
  subject do
    described_class.new('balanced-bankaccount',
                        customer,
                        contribution,
                        attributes)
  end

  describe 'checkout' do
    it 'authorizes payment of contribution' do
      expect(contribution).to receive(:wait_confirmation!)
      subject.checkout!
    end

    it 'defines given engine\'s name as payment method of the contribution' do
      contribution.should_receive(:update_attributes).
                   with(hash_including(payment_method: 'balanced-bankaccount'))
      subject.checkout!
    end

    it 'saves paid fees on contribution object' do
      calculator = double('FeeCalculator', fees: 0.42).as_null_object
      subject.stub(:fee_calculator).and_return(calculator)
      contribution.should_receive(:update_attributes).
                   with(hash_including(payment_service_fee: 0.42))
      subject.checkout!
    end

    it 'saves who paid the fees' do
      calculator = double('FeeCalculator', fees: 0.42).as_null_object
      subject.stub(:fee_calculator).and_return(calculator)
      contribution.should_receive(:update_attributes).
                   with(hash_including(payment_service_fee_paid_by_user: '1'))
      subject.checkout!
    end
  end

  describe 'status' do
    context 'after checkout' do
      before do
        subject.checkout!
      end

      it 'is succeeded' do
        expect(subject.status).to eql(:succeeded)
        expect(subject).to        be_successful
      end
    end

    context 'before checkout' do
      it 'is nil' do
        expect(subject.status).to be_nil
      end

      it 'is not succeeded' do
        expect(subject).to_not be_successful
      end
    end
  end
end


text:
<!DOCTYPE html>

<meta charset=utf-8 />

<title>Arduino UNO Example</title>

Arduino Uno Test Example

pot value:

heading:

button:

button:


text:
using UnityEngine;
using UnityEditor;

namespace Kino
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(Motion))]
    public class MotionEditor : Editor
    {
        MotionGraphDrawer _graph;

        SerializedProperty _shutterAngle;
        SerializedProperty _sampleCount;
        SerializedProperty _frameBlending;

        [SerializeField] Texture2D _blendingIcon;

        static GUIContent _textStrength = new GUIContent("Strength");

        void OnEnable()
        {
            _shutterAngle = serializedObject.FindProperty("_shutterAngle");
            _sampleCount = serializedObject.FindProperty("_sampleCount");
            _frameBlending = serializedObject.FindProperty("_frameBlending");
        }

        public override void OnInspectorGUI()
        {
            if (_graph == null) _graph = new MotionGraphDrawer(_blendingIcon);

            serializedObject.Update();

            EditorGUILayout.LabelField("Shutter Speed Simulation", EditorStyles.boldLabel);

            #if SHOW_GRAPHS
            _graph.DrawShutterGraph(_shutterAngle.floatValue);
            #endif

            EditorGUILayout.PropertyField(_shutterAngle);
            EditorGUILayout.PropertyField(_sampleCount);

            EditorGUILayout.Space();

            EditorGUILayout.LabelField("Multiple Frame Blending", EditorStyles.boldLabel);

            #if SHOW_GRAPHS
            _graph.DrawBlendingGraph(_frameBlending.floatValue);
            #endif

            EditorGUILayout.PropertyField(_frameBlending, _textStrength);

            serializedObject.ApplyModifiedProperties();
        }
    }
}


text:
using System;
using KitchenPC.Ingredients;

namespace KitchenPC.Data.DTO
{
   public class IngredientForms
   {
      public Guid IngredientFormId { get; set; }
      public Guid IngredientId { get; set; }
      public short ConvMultiplier { get; set; }
      public float FormAmount { get; set; }
      public Units UnitType { get; set; }
      public string UnitName { get; set; }
      public Units FormUnit { get; set; }
      public string FormDisplayName { get; set; }

      public static IngredientForm ToIngredientForm(IngredientForms dtoForm)
      {
         return new IngredientForm
         {
            FormId = dtoForm.IngredientFormId,
            FormUnitType = dtoForm.UnitType,
            ConversionMultiplier = dtoForm.ConvMultiplier,
            FormDisplayName = dtoForm.FormDisplayName,
            FormUnitName = dtoForm.UnitName,
            IngredientId = dtoForm.IngredientId,
            FormAmount = new Amount(dtoForm.FormAmount, dtoForm.FormUnit)
         };
      }
   }
}


text:
package com.laytonsmith.tools.docgen;

import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscovery;
import com.laytonsmith.PureUtilities.ClassLoading.ClassDiscoveryCache;
import com.laytonsmith.PureUtilities.ClassLoading.DynamicClassLoader;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.annotations.api;
import com.laytonsmith.commandhelper.CommandHelperFileLocations;
import com.laytonsmith.core.events.Event;
import com.laytonsmith.core.functions.Function;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author cgallarno
 */
public class ExtensionDocGen {

	private static final String NL = StringUtils.nl();
	private static final Pattern WIKI_LINK = Pattern.compile("\\[([a-zA-Z]+://[^ ]+) ([^\\]]+)]");

	public static void generate(File inputExtension, OutputStream outputStream) throws InstantiationException, IllegalAccessException, MalformedURLException, IOException {
		ClassDiscovery customDiscovery = new ClassDiscovery();
		ClassDiscoveryCache cache = new ClassDiscoveryCache(CommandHelperFileLocations.getDefault().getCacheDirectory());
		customDiscovery.setClassDiscoveryCache(cache);
		URL url = new URL("jar:" + inputExtension.toURI().toURL() + "!/");
		customDiscovery.addDiscoveryLocation(url);
		customDiscovery.setDefaultClassLoader(ExtensionDocGen.class.getClassLoader());
		StringBuilder fdocs = new StringBuilder();
		DynamicClassLoader classloader = new DynamicClassLoader();
		classloader.addJar(url);
		//functions
		HashMap<Class<?>, ArrayList<Class<? extends Function>>> functionMap = new HashMap<>();
		for(Class<? extends Function> cf : customDiscovery.loadClassesWithAnnotationThatExtend(api.class, Function.class, classloader, true)) {
			Class enclosing = cf.getEnclosingClass();
			if(functionMap.containsKey(enclosing)) {
				functionMap.get(enclosing).add(cf);
			} else {
				functionMap.put(enclosing, new ArrayList<Class<? extends Function>>());
				functionMap.get(enclosing).add(cf);
			}
		}
		ArrayList<Entry<Class<?>, ArrayList<Class<? extends Function>>>> functionEntryList = new ArrayList<>(functionMap.entrySet());
		Collections.sort(functionEntryList, new Comparator<Entry<Class<?>, ArrayList<Class<? extends Function>>>>() {
			@Override
			public int compare(Entry<Class<?>, ArrayList<Class<? extends Function>>> o1,
					Entry<Class<?>, ArrayList<Class<? extends Function>>> o2) {
				return o1.getKey().getName().compareTo(o2.getKey().getName());
			}
		});
		for(Entry<Class<?>, ArrayList<Class<? extends Function>>> e : functionEntryList) {
			Collections.sort(e.getValue(), new Comparator<Class<? extends Function>>() {
				@Override
				public int compare(Class<? extends Function> o1, Class<? extends Function> o2) {
					return o1.getName().compareTo(o2.getName());
				}
			});
		}
		if(!functionEntryList.isEmpty()) {
			fdocs.append("# Functions").append(NL);
		}
		for(Entry<Class<?>, ArrayList<Class<? extends Function>>> entry : functionEntryList) {
			Class enclosingClass = entry.getKey();
			String[] split = enclosingClass.getName().split("\\.");
			fdocs.append("## ").append(split[split.length - 1]).append(NL);
			try {
				Method docsMethod = enclosingClass.getMethod("docs", (Class[]) null);
				Object o = enclosingClass.newInstance();
				fdocs.append((String) docsMethod.invoke(o, (Object[]) null)).append(NL).append(NL);
			} catch (NoSuchMethodException
					| SecurityException
					| InstantiationException
					| IllegalAccessException
					| IllegalArgumentException
					| InvocationTargetException exception) {
			}
			for(Class<? extends Function> cf : entry.getValue()) {
				Function f = cf.newInstance();
				if(f.appearInDocumentation()) {
					DocGen.DocInfo di = new DocGen.DocInfo(f.docs());
					String d = "### " + markdownEscape(di.ret) + " " + markdownEscape(f.getName()) + "(" + markdownEscape(di.originalArgs) + "):" + NL
							+ convertWiki(di.topDesc != null ? di.topDesc : di.desc) + NL
							+ convertWiki(di.extendedDesc != null ? NL + di.extendedDesc + NL : "");
					fdocs.append(d).append(NL);
				}
			}
		}
		//events
		HashMap<Class<?>, ArrayList<Class<? extends Event>>> eventMap = new HashMap<>();
		for(Class<? extends Event> ce : customDiscovery.loadClassesWithAnnotationThatExtend(api.class, Event.class, classloader, true)) {
			Class<?> enclosing = ce.getEnclosingClass();
			if(eventMap.containsKey(enclosing)) {
				eventMap.get(enclosing).add(ce);
			} else {
				eventMap.put(enclosing, new ArrayList<Class<? extends Event>>());
				eventMap.get(enclosing).add(ce);
			}
		}
		ArrayList<Entry<Class<?>, ArrayList<Class<? extends Event>>>> eventEntryList = new ArrayList<>(eventMap.entrySet());
		Collections.sort(eventEntryList, new Comparator<Entry<Class<?>, ArrayList<Class<? extends Event>>>>() {
			@Override
			public int compare(Entry<Class<?>, ArrayList<Class<? extends Event>>> o1,
					Entry<Class<?>, ArrayList<Class<? extends Event>>> o2) {
				return o1.getKey().getName().compareTo(o2.getKey().getName());
			}
		});
		for(Entry<Class<?>, ArrayList<Class<? extends Event>>> e : eventEntryList) {
			Collections.sort(e.getValue(), new Comparator<Class<? extends Event>>() {
				@Override
				public int compare(Class<? extends Event> o1, Class<? extends Event> o2) {
					return o1.getName().compareTo(o2.getName());
				}
			});
		}
		if(!eventEntryList.isEmpty()) {
			fdocs.append("# Events").append(NL);
		}
		for(Entry<Class<?>, ArrayList<Class<? extends Event>>> entry : eventEntryList) {
			Class enclosingClass = entry.getKey();
			String[] split = enclosingClass.getName().split("\\.");
			fdocs.append("## ").append(split[split.length - 1]).append(NL);
			try {
				Method docsMethod = enclosingClass.getMethod("docs", (Class[]) null);
				Object o = enclosingClass.newInstance();
				fdocs.append((String) docsMethod.invoke(o, (Object[]) null)).append(NL).append(NL);
			} catch (NoSuchMethodException
					| SecurityException
					| InstantiationException
					| IllegalAccessException
					| IllegalArgumentException
					| InvocationTargetException exception) {
			}
			for(Class<? extends Event> ce : entry.getValue()) {
				Event e = ce.newInstance();
				Pattern p = Pattern.compile("\\{(.*?)\\} *?(.*?) *?\\{(.*?)\\} *?\\{(.*?)\\}");
				Matcher m = p.matcher(e.docs());
				if(m.find()) {
					String name = e.getName();
					String description = m.group(2).trim();
					String prefilter = DocGen.PrefilterData.Get(m.group(1).split("\\|"), DocGen.MarkupType.MARKDOWN);
					String eventData = DocGen.EventData.Get(m.group(3).split("\\|"), DocGen.MarkupType.MARKDOWN);
					String mutability = DocGen.MutabilityData.Get(m.group(4).split("\\|"), DocGen.MarkupType.MARKDOWN);
					//String manualTrigger = ManualTriggerData.Get(m.group(5).split("\\|"), DocGen.MarkupType.MARKDOWN);
					//String since = e.since().toString();
					fdocs.append("### ").append(markdownEscape(name)).append(NL);
					fdocs.append(description).append(NL);
					fdocs.append("#### Prefilters").append(NL).append(prefilter).append(NL);
					fdocs.append("#### Event Data").append(NL).append(eventData).append(NL);
					fdocs.append("#### Mutable Fields").append(NL).append(mutability).append(NL);
				}
			}
		}
		outputStream.write(fdocs.toString().getBytes("UTF-8"));
	}

	/**
	 * Converts selected wiki markup into markdown.
	 *
	 * @param input
	 * @return
	 */
	private static String convertWiki(String input) {
		String output = input;
		Matcher m = WIKI_LINK.matcher(input);
		if(m.find()) {
			output = m.replaceAll("[$2]($1)");
		}
		return output;
	}

	private static String markdownEscape(String input) {
		return input.replace("*", "\\*")
				.replace("_", "\\_");
	}
}


text:
<?php

namespace Cole\IntranetBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class TutoriasType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            //->add('fecha', 'text', array('required' => true,'label' => 'Fecha','attr' => array('class' => 'form-control input-inline datetimepicker','data-provide' => 'datepicker','data-format' => 'dd-mm-yyyy HH:ii')))
            ->add('fecha','date',array('widget' => 'text','required'=> true))
            ->add('hora','time',array('widget' => 'text','required'=> true))
            ->add('grupo','entity',array('mapped' => false, 'class' => 'BackendBundle:Grupo','query_builder' => function (\Cole\BackendBundle\Entity\GrupoRepository $er) {return $er->createQueryBuilder('u')->orderBy('u.curso','ASC')->addOrderBy('u.letra', 'ASC');}, 'empty_data' => null,'empty_value'=> 'Seleccione un grupo','required'=> true))
            ->add('profesor','entity',array('class' => 'BackendBundle:Profesor','query_builder' => function (\Cole\BackendBundle\Entity\ProfesorRepository $er) {return $er->createQueryBuilder('u')->where('u.activo IN(:act)')->setParameter(':act', 1)->orderBy('u.nombre','ASC');}, 'empty_data' => null,'empty_value'=> 'Seleccione un profesor','required'=> true))
            ->add('alumno','entity',array('class' => 'BackendBundle:Alumno','query_builder' => function (\Cole\BackendBundle\Entity\AlumnoRepository $er) {return $er->createQueryBuilder('u')->where('u.activo IN(:act)')->setParameter(':act', 1)->orderBy('u.nombre','ASC');}, 'empty_data' => null,'empty_value'=> 'Seleccione un alumno','required'=> false))
            ->add('responsable','entity',array('class' => 'BackendBundle:Padres','query_builder' => function (\Cole\BackendBundle\Entity\PadresRepository $er) {return $er->createQueryBuilder('u')->where('u.activo IN(:act)')->setParameter(':act', 1)->orderBy('u.nombre','ASC');}, 'empty_data' => null,'empty_value'=> 'Seleccione un responsable','required'=> false))
            ->add('seguimiento','entity',array('class' => 'IntranetBundle:Seguimiento','query_builder' => function (\Cole\IntranetBundle\Entity\SeguimientoRepository $er) {return $er->createQueryBuilder('u')->where('u.tipo IN(:act)')->setParameter(':act', 1)->orderBy('u.id','ASC');}, 'empty_data' => null,'empty_value'=> 'Seleccione una consulta','required'=> false))
            ->add('tipo', 'choice', array('mapped' => false,'choices' => array('1' => 'Profesor', '0' =>'Alumno'),'required'=> true, 'expanded'=>true, 'multiple'=>false))
            ->add('descripcion','textarea',array('mapped' => false, 'label' => 'Descripción', 'attr' => array('type'=>'textarea')))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Cole\IntranetBundle\Entity\Tutorias'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'cole_intranetbundle_tutorias';
    }
}


text:
require 'cucumber_characteristics/configuration'
require 'cucumber_characteristics/cucumber_common_step_patch'
if Cucumber::VERSION < '2.0.0'
  require 'cucumber_characteristics/cucumber_1x_step_patch'
else
  require 'cucumber_characteristics/cucumber_2x_step_patch'
end
require 'cucumber_characteristics/exporter'
require 'cucumber_characteristics/formatter'
require 'cucumber_characteristics/profile_data'

module CucumberCharacteristics
  class << self
    attr_writer :configuration
  end

  def self.configuration
    @configuration ||= Configuration.new
  end

  def self.reset
    @configuration = Configuration.new
  end

  def self.configure
    yield(configuration)
  end
end


text:
find_package(Sphinx REQUIRED)

dawn_export_package(
  NAME Sphinx
  FOUND ${SPHINX_FOUND}
  VERSION ${SPHINX_VERSION}
  EXECUTABLE ${SPHINX_EXECUTABLE}
)


text:
from unittest import mock
import contexts
import asynqp
from asynqp import spec
from asynqp import protocol
from asynqp.exceptions import ConnectionLostError
from .base_contexts import MockDispatcherContext, MockServerContext
from .util import testing_exception_handler

class WhenInitiatingProceedings(MockServerContext):
    def when_i_send_the_protocol_header(self):
        self.protocol.send_protocol_header()

    def it_should_write_the_correct_header(self):
        self.server.should_have_received_bytes(b'AMQP\x00\x00\x09\x01')

class WhenAWholeFrameArrives(MockDispatcherContext):
    def establish_the_frame(self):
        self.raw = b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'
        method = spec.ConnectionOpenOK('')
        self.expected_frame = asynqp.frames.MethodFrame(0, method)
        self.protocol.heartbeat_monitor = mock.Mock(spec=protocol.HeartbeatMonitor)

    def because_the_whole_frame_arrives(self):
        self.protocol.data_received(self.raw)
        self.tick()

    def it_should_dispatch_the_method(self):
        self.dispatcher.dispatch.assert_called_once_with(self.expected_frame)

    def it_should_reset_the_heartbeat_timeout(self):
        assert self.protocol.heartbeat_monitor.heartbeat_received.called

class WhenAFrameDoesNotEndInFrameEnd(MockServerContext):
    def establish_the_bad_frame(self):
        self.raw = b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCD'

    def because_the_bad_frame_arrives(self):
        self.exception = contexts.catch(self.server.send_bytes, self.raw)

    def it_MUST_close_the_connection(self):
        assert self.transport.closed

    def it_should_raise_an_exception(self):
        assert isinstance(self.exception, asynqp.AMQPError)

class WhenHalfAFrameArrives(MockDispatcherContext):
    @classmethod
    def examples_of_incomplete_frames(cls):
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00'  # cut off half way through the payload
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00'  # cut off right before the frame end byte
        yield b'\x01\x00'  # cut off before the end of the header

    def because_some_of_a_frame_arrives(self, raw):
        self.protocol.data_received(raw)
        self.tick()

    def it_should_not_dispatch_the_method_yet(self):
        assert not self.dispatcher.dispatch.called

class WhenAFrameArrivesInTwoParts(MockDispatcherContext):
    @classmethod
    def examples_of_broken_up_frames(cls):
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A', b'\x00\x29\x00\xCE'  # cut off half way through the payload
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00', b'\xCE'  # cut off right before the frame end byte
        yield b'\x01\x00', b'\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'  # cut off before the end of the header

    def establish_the_frame(self):
        method = spec.ConnectionOpenOK('')
        self.expected_frame = asynqp.frames.MethodFrame(0, method)

    def because_the_whole_frame_eventually_arrives(self, raw1, raw2):
        self.protocol.data_received(raw1)
        self.tick()
        self.protocol.data_received(raw2)
        self.tick()

    def it_should_dispatch_the_method(self):
        self.dispatcher.dispatch.assert_called_once_with(self.expected_frame)

class WhenMoreThanAWholeFrameArrives(MockDispatcherContext):
    def establish_the_frame(self):
        self.raw = b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE\x01\x00\x00\x00\x00\x00\x05\x00\x0A'
        method = spec.ConnectionOpenOK('')
        self.expected_frame = asynqp.frames.MethodFrame(0, method)

    def because_more_than_a_whole_frame_arrives(self):
        self.protocol.data_received(self.raw)
        self.tick()

    def it_should_dispatch_the_method_once(self):
        self.dispatcher.dispatch.assert_called_once_with(self.expected_frame)

class WhenTwoFramesArrive(MockDispatcherContext):
    def establish_the_frame(self):
        self.raw = b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'
        method = spec.ConnectionOpenOK('')
        self.expected_frame = asynqp.frames.MethodFrame(0, method)

    def because_more_than_a_whole_frame_arrives(self):
        self.protocol.data_received(self.raw)
        self.tick()

    def it_should_dispatch_the_method_twice(self):
        self.dispatcher.dispatch.assert_has_calls([mock.call(self.expected_frame), mock.call(self.expected_frame)])

class WhenTwoFramesArrivePiecemeal(MockDispatcherContext):
    @classmethod
    def examples_of_broken_up_frames(cls):
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE', b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00', b'\x29\x00\xCE'
        yield b'\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE\x01\x00', b'\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'
        yield b'\x01', b'\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE\x01\x00\x00\x00\x00\x00\x05\x00\x0A\x00\x29\x00\xCE'
        yield b'\x01', b'\x00\x00\x00\x00\x00\x05\x00', b'\x0A\x00\x29\x00', b'\xCE\x01\x00\x00\x00\x00\x00\x05\x00', b'\x0A\x00\x29\x00\xCE', b''

    def establish_what_we_expected(self):
        method = spec.ConnectionOpenOK('')
        self.expected_frame = asynqp.frames.MethodFrame(0, method)

    def because_two_frames_arrive_in_bits(self, fragments):
        for fragment in fragments:
            self.protocol.data_received(fragment)
            self.tick()

    def it_should_dispatch_the_method_twice(self):
        self.dispatcher.dispatch.assert_has_calls([mock.call(self.expected_frame), mock.call(self.expected_frame)])

class WhenTheConnectionIsLost(MockServerContext):
    def given_an_exception_handler(self):
        self.connection_lost_error_raised = False
        self.loop.set_exception_handler(self.exception_handler)

    def exception_handler(self, loop, context):
        exception = context.get('exception')
        if type(exception) is ConnectionLostError:
            self.connection_lost_error_raised = True
        else:
            self.loop.default_exception_handler(context)

    def when_the_connection_is_closed(self):
        self.loop.call_soon(self.protocol.connection_lost, Exception)
        self.tick()

    def it_should_raise_a_connection_lost_error(self):
        assert self.connection_lost_error_raised is True

    def cleanup(self):
        self.loop.set_exception_handler(testing_exception_handler)


text:
<?php
namespace Hooloovoo\ORM;

use Hooloovoo\DatabaseMapping\Table;
use Hooloovoo\DataObjects\DataObjectInterface;

/**
 * Interface ComponentManagerInterface
 */
interface ComponentManagerInterface
{
    /**
     * @return Table
     */
    public function getTableMapping() : Table ;

    /**
     * @param int[] $primaryKeys
     * @return DataObjectInterface[]
     */
    public function getByPrimaryKeys(array $primaryKeys) : array ;
}


text:
{if !$instances}

{foreach from=$instances item=instance}

{$instance->username} : username_sys_user}">Modifica

{/foreach}

{else}

NON CI SONO sys_user_sys_group

{/if}


text:
package com.beyondsw.lib.widget.rebound;

/**
 * Data structure for storing spring configuration.
 */
public class SpringConfig {
  public double friction;
  public double tension;

  public static SpringConfig defaultConfig = SpringConfig.fromOrigamiTensionAndFriction(40, 7);

  /**
   * constructor for the SpringConfig
   * @param tension tension value for the SpringConfig
   * @param friction friction value for the SpringConfig
   */
  public SpringConfig(double tension, double friction) {
    this.tension = tension;
    this.friction = friction;
  }

  /**
   * A helper to make creating a SpringConfig easier with values mapping to the Origami values.
   * @param qcTension tension as defined in the Quartz Composition
   * @param qcFriction friction as defined in the Quartz Composition
   * @return a SpringConfig that maps to these values
   */
  public static SpringConfig fromOrigamiTensionAndFriction(double qcTension, double qcFriction) {
    return new SpringConfig(
        OrigamiValueConverter.tensionFromOrigamiValue(qcTension),
        OrigamiValueConverter.frictionFromOrigamiValue(qcFriction)
    );
  }

  /**
   * Map values from the Origami POP Animation patch, which are based on a bounciness and speed
   * value.
   * @param bounciness bounciness of the POP Animation
   * @param speed speed of the POP Animation
   * @return a SpringConfig mapping to the specified POP Animation values.
   */
  public static SpringConfig fromBouncinessAndSpeed(double bounciness, double speed) {
    BouncyConversion bouncyConversion = new BouncyConversion(speed, bounciness);
    return fromOrigamiTensionAndFriction(
        bouncyConversion.getBouncyTension(),
        bouncyConversion.getBouncyFriction());
  }
}


text:
cask 'ripple-wallet' do
  version '1.4.1'
  sha256 '7e892b427f8c7fb52797c6e1faa32f1ef8e7c5bf5910f4a4ab341d0b72a039d6'

  # s3.amazonaws.com/static.rippex.net/client was verified as official when first introduced to the cask
  url "https://s3.amazonaws.com/static.rippex.net/client/ripple-wallet-osx64-#{version}.zip"
  appcast 'https://github.com/rippex/ripple-client-desktop/releases.atom'
  name 'Ripple Wallet'
  homepage 'https://rippex.net/carteira-ripple.php#/'

  app "Ripple-Wallet-osx64-#{version}.app"
end


text:
class MakingHostTagsARealArModel < ActiveRecord::Migration[4.2]
  def change
    add_column :hosts_tags, :id, :primary_key
  end

end


text:
//
// Copyright (c) 2014, nebland software, LLC
//
// All rights reserved.
//
// liboadr20a ("this software") is licensed under BSD 3-Clause license.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// *  Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.
//
// *  Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// *  Neither the name of nebland software nor the names of its contributors may
//    be used to endorse or promote products derived from this software without
//    specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
//

#include "ISO8601Duration.h"
#include <cstdlib>

ISO8601Duration::ISO8601Duration() {
	// TODO Auto-generated constructor stub

}

/********************************************************************************/

ISO8601Duration::~ISO8601Duration() {
	// TODO Auto-generated destructor stub
}

/********************************************************************************/

bool ISO8601Duration::parse(string duration){

	char* p;
	char c;
	int timeFlag = 0;		//Flag thrown when encountering T in string
	int monthFlag = 0;
	int dayFlag = 0;
	int hourFlag = 0;
	int minuteFlag = 0;
	int secondFlag = 0;
	double decimalBuffer = 0;

	//Reset all variables
	m_Years = 0;
	m_Months = 0;
	m_Days = 0;
	m_Hours = 0;
	m_Minutes = 0;
	m_Seconds = 0;

	//Sets p to beginning of the string
	p = &duration[0];

	//Loop through the string and parse the time units
	c = *p;

	if(c != 'P') {
		return false;
	}

	//Test if P is last character in string
	p++;

	if(*p == '\0')
		return false;

	c = *p;

	while (c != '\0')
	{

		//Set flag so 'M' after this point means minutes
		if(c == 'T')
		{
			timeFlag = 1;

			if (hourFlag == 1 || minuteFlag == 1 || secondFlag == 1)
				return false;

			// if T is the end of the string, the string is invalid
			if (*(p + 1) == '\0')
				return false;
		}
		else
		{

			char *pNew = p;

			//Store the decimal, move p to after decimal
			decimalBuffer = strtod(p, &pNew);

			//If the end of string is reached now, there wasn't a number, character pair
			if(*pNew == '\0')
				return false;

			//strtod did not find a decimal
			if(pNew == p)
			{
				return false;
			}

			//Get the next char
			c = *pNew;

			p = pNew;

			//Assign d to proper variable according to c's value
			if(c == 'Y')
			{
				m_Years = decimalBuffer;

				if (timeFlag == 1 || hourFlag == 1 || minuteFlag == 1 || secondFlag == 1 || monthFlag == 1 || dayFlag == 1)
					return false;

			}
			else if (c == 'M' && timeFlag == 0)
			{
				m_Months = decimalBuffer;

				if (monthFlag == 1 || hourFlag == 1 || minuteFlag == 1 || secondFlag == 1 || dayFlag == 1)
					return false;

				monthFlag = 1;
			}
			else if (c == 'M' && timeFlag == 1)
			{
				m_Minutes = decimalBuffer;

				if (secondFlag == 1 || minuteFlag == 1)
					return false;

				minuteFlag = 1;
			}
			else if(c == 'D')
			{
				m_Days = decimalBuffer;

				if (dayFlag == 1 || timeFlag == 1 || hourFlag == 1 || minuteFlag == 1 || secondFlag == 1)
					return false;

				dayFlag = 1;
			}
			else if(c == 'H')
			{
				m_Hours = decimalBuffer;

				if (hourFlag == 1 || minuteFlag == 1 || secondFlag == 1)
						return false;

				hourFlag = 1;
			}
			else if (c == 'S')
			{
				m_Seconds = decimalBuffer;

				if(secondFlag == 1)
					return false;

				secondFlag = 1;
			}
			else if (c == '\0')
			{
				continue;
			}
			else
			{
				return false;
			}

		}

		//Advance pointer
		p++;
		c = *p;

	}

	return true;
}

/********************************************************************************/

//The following return their respective variables
double ISO8601Duration::getYears()
{
	return m_Years;
}

/********************************************************************************/

double ISO8601Duration::getMonths()
{
	return m_Months;
}

/********************************************************************************/

double ISO8601Duration::getDays()
{
	return m_Days;
}

/********************************************************************************/

double ISO8601Duration::getHours()
{
	return m_Hours;
}

/********************************************************************************/

double ISO8601Duration::getMinutes()
{
	return m_Minutes;
}

/********************************************************************************/

double ISO8601Duration::getSeconds()
{
	return m_Seconds;
}

/********************************************************************************/
//The following functions assume exactly 365 days per year and 30 days per month

double ISO8601Duration::getTotalSeconds()
{
	return (m_Years * 31536000) + (m_Months * 2592000) + (m_Days * 86400) + (m_Hours * 3600) + (m_Minutes * 60) + m_Seconds;
}

/********************************************************************************/

double ISO8601Duration::getTotalMinutes()
{
	return (m_Years * 525600) + (m_Months * 4320) + (m_Days * 1440) + (m_Hours * 60) + (m_Minutes * 1) + (m_Seconds / 60 );
}

/********************************************************************************/

double ISO8601Duration::getTotalHours()
{
	return (m_Years * 8760) + (m_Months * 720) + (m_Days * 24) + (m_Hours * 1) + (m_Minutes / 60) + (m_Seconds / 3600 );
}


text:
#ifndef WAVEFUNCTION_HH
#define WAVEFUNCTION_HH

#include "function.hh"
#include "polynomial.hh"

inline double factorial(int n)
{
  if (n < 0)
    throw std::logic_error("Factorial of negative number");
  if (n == 0)
    return 1.;
  return double(n) * factorial(n - 1);
}

inline double choose(int n, int k)
{
  return factorial(n) / (factorial(k) * factorial(n - k));
}

class Orbital : public Function<3,std::complex<double> >
{
public:
  Orbital(int Z_, int N_, int L_, int M_,
          bool real_, bool diff_, bool square_);
  double radial_part(double r) const;
  double theta_part(double sin_theta, double cos_theta) const;
  std::complex<double> operator()(const Vector<3> &x) const;
  const int Z, N, L, M;
  const bool real; // If true, add values for +/-M and divide by root 2
  const bool diff; // If true, real wave function is a difference of
  //                  wave functions for +/-M. If false, sum.
  const bool square; // If true, square magnitude of the function
  bool operator==(const Orbital &rhs);
  bool operator!=(const Orbital &rhs) { return !(*this == rhs); }
  double radius() const;
  double radialIntegral() const;

private:
  double radial_constant;
  double radial_exponential_constant;
  Polynomial radial_polynomial;

  double angular_constant;
  Polynomial cos_theta_polynomial;

  double normalization_constant;
};

#endif


text:
$(function() {

  // TODO: Have this update only when conversions are recorded, if possible.  Use Server-Sent Events.
  // Update the revenue in the nav bar every 5 minutes
  $navbarRevenue = $('#navbar-revenue');
  setInterval(function() {
    $navbarRevenue.load($navbarRevenue.data('path'));
  }, 5 * 60 * 1000);
});


text:
namespace Google.Cloud.ServiceDirectory.V1.Snippets
{
    // [START servicedirectory_v1_generated_RegistrationService_CreateEndpoint_sync_flattened_resourceNames]
    using Google.Cloud.ServiceDirectory.V1;

    public sealed partial class GeneratedRegistrationServiceClientSnippets
    {
        /// <summary>Snippet for CreateEndpoint</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void CreateEndpointResourceNames()
        {
            // Create client
            RegistrationServiceClient registrationServiceClient = RegistrationServiceClient.Create();
            // Initialize request argument(s)
            ServiceName parent = ServiceName.FromProjectLocationNamespaceService("[PROJECT]", "[LOCATION]", "[NAMESPACE]", "[SERVICE]");
            Endpoint endpoint = new Endpoint();
            string endpointId = "";
            // Make the request
            Endpoint response = registrationServiceClient.CreateEndpoint(parent, endpoint, endpointId);
        }
    }
    // [END servicedirectory_v1_generated_RegistrationService_CreateEndpoint_sync_flattened_resourceNames]
}


text:
Den mest vanlige opplevelsen mens man skriver kode er desverre at ting ikke funker fordi man har gjort en feil ett eller annet sted. Dette er omtrent som å skrive en stil i norsk, du kommer alltids til å ha en eller annen skrivefeil her eller der. Akkurat som i norsk, er det viktig å huske på en ting: dette er helt vanlig! Selv om du har norsk som morsmål så vil du fortsatt av og til stave noe feil. Selv om du har programmert i flere tiår, vi du forsatt gjøre små feil. Slik er det bare.

## Innhold

* [Feilmarkeringer i Arduino IDE](#feilmarkeringer-i-arduino-ide)
* [En feil om gangen](#en-feil-om-gangen)
* [Vanlige feil](#vanlige-feil)
  * [For hyppig klikk på Upload-knappen](#for-hyppig-klikk-på-upload-knappen)
  * [Bruk av annen `COM`-port](#bruk-av-annen-com-port)
  * [Manglende Semikolon](#manglende-semikolon)
  * [Manglende lukkende parentes](#manglende-lukkende-parentes)
  * [Feilstavelser i navn](#feilstavelser-i-navn)
  * [Bruk av variabler utenfor scope](#bruk-av-variabler-utenfor-scope)

## Feilmarkeringer i Arduino IDE

Akkurat som læreren din i språkfag er også datamaskinen veldig nøye med hvordan du skriver koden din. Slike feil er forholdsvis enkle feil, siden datamaskinen oppdager feilstavelser når du laster opp programmet ditt til Arduinoen. Så selv om dette kanskje er plagsomt, så vil datamaskinen i det minste ikke få Arduinoen til gjøre noe helt fullstendig galt. I slike tilfeller vil Arduino IDE også vise hvor feilen ligger og si hva som er feil.

Ta for eksempel denne koden:

``` cpp
int counter;

void setup() {
  counter = 0
}
```

Ser du feilen? Om du klikker på `Verify`-knappen til venstre over teksten kan du verifisere at koden er rett og vise feil som datamaskinen kan oppdage.

![Verifiser kode][missing-semicolon]

I bildet over ser du også at Arduino IDE fremhever linjen der feilen oppsto med rød bakgrunn. Feilen oppsto ifølge Arduino IDE i linje 5.

I feilmeldingen under teksteditoren skriver Arduino IDE dessuten også ut en forklaring av feilen:

> Arduino: 1.8.5 (Windows 10), Board: "Arduino/Genuino Uno"
>
> C:\Users\Fredrik\Documents\Arduino\sketch_nov14a\sketch_nov14a.ino: In
> function 'void setup()':
>
> sketch_nov14a:5: error: expected ';' before '}' token
>
>  }
>
>  ^
>
> exit status 1
> expected ';' before '}' token

Første linjen i feilmeldingen viser versjonen til Arduinoe IDE og hvilken type Arduino vi programmerer med.

Så kommer filnavnet og i hvilken del av programmet feilen oppsto. I dette tilfellet oppsto feilen i filen `C:\Users\Fredrik\Documents\Arduino\sketch_nov14a\sketch_nov14a.ino` og der i funksjonen `void setup()`, altså i `setup`-funksjonen vår.

Så kommer en liste med alle feil i denne funksjonen. I dette tilfellet er det bare én feil. Først kommer navnet av filen, så et kolon, og så linjenummeret (*5*). Etter dette kommer selve feilmeldingen:

> error: expected ';' before '}' token

Arduino IDE klager på at det mangler ett semikolon (`;`) ett eller annet sted **før** den lukkende klammerparantesen i linje 5. Og det er jo helt rett, fordi vi har glemt å avslutte instruksjonen i linje 4 med et semikolon.

``` cpp
int counter;

void setup() {
  counter = 0;
}
```

**Så husk**: Ofte ligger feilen ikke nøyaktig der hvor Arduino IDE sier at den oppsto, men gjerne i linjen over. Dette kommer av at datamaskinen prøver så godt den kan og skjønne hva du vil gjøre. Derfor oppstår feilen først der hvor datamaskinen må gi opp og si at det er noe feil.

## En feil om gangen

Nå du skriver et større program med mye kode kan det fort skje at du får mange feil, og noen av disse kan også påvirke hverandre. Da blir feilsøking gjerne litt vanskelig og feilmeldingene blir mer og mer kryptisk. En tommelfingerregel er å verifisere koden så ofte som mulig etter hvert småsteg du tar i programmeringen.

Når du finner feil koden din, lønner det seg å alltids rette opp en og en feil og verifisere koden mellom hver rettelse. Feil lager ofte følgefeil, som da plutselig forsvinner. *Se for deg et stort regnestykke. Om du har ett tall feil helt i begynnelsen blir alt etter det feil, men om du bare retter opp feilen helt i begynnelsen, så blir gjerne alle følgende regnestykkene rett igjen.*

## Vanlige feil

Akkurat som små stavefeil i norsk, gjør vi også veldig vanlige feil som går igjen hele tiden når vi skriver kode. Her er noen av de mest vanlige feilene:

### For hyppig klikk på Upload-knappen

Arduinoen er litt sårbar akkurat mens du laster opp kode til den ved å trykke på `Upload`-knappen i Arduino IDE. Når du trykker på `Upload`-knappen burde du helst vente til Arduino IDE enten har fullført å laste opp koden din, eller at den gir deg en feilmelding.

Om du trykker på `Upload`-knappen mens det allerede er en opplastning underveis, kan det oppstå veldig rare feilmeldinger som kommer av at bare deler av et faktisk Arduino program havner på Arduinoen. Detter er ikke farlig, du må bare prøve igjen og neste gang vente til opplastingen er ferdig.

### Bruk av annen `COM`-Port

På siden [Konfigurasjon av Arduino IDE][config-ide] vises det hvordan du setter opp Arduino IDE til å bruke rett `COM`-port for å snakke med Arduinoen over USB-ledningen. Om du ved en senere anledning plugger inn Arduinoen i en annen USB-port på datamaskinen din, eller plugger inn en annen Arduino, må du huske å velge rett `COM`-port på nytt, slik det står beskrevet i guiden.

### Manglende Semikolon

Instruksjoner i C++ må avsluttes med semikolon. Om du glemmer semikolon vil det oppstå en feil i linjen **etter** der du glemte semikolon. Feilmeldingen ser da slik ut:

> expected ';' before <tegn> token

*<tegn> kan være hva som helst som kommer etter linjen der du glemte semikolon.

I noen tilfeller vil feilmeldingen si at den forventet noe annet enn ';' som her:

``` cpp
void setup() {
  int x;
  int c
  x = 0;
  c = 1;
}
```

Feilmelding:

> sketch.ino:4: error: expected initializer before 'x'

Igjen her mangler det noe (et semikolon) **før** `x` i linje 4.

### Manglende lukkende parentes

Parenteser kommer alltid i par. For hver parentes du åpner må du også lukke den igjen. Dette gjelder for vanlige parenteser (`(`, `)`), krøllparenteser (`{`, `}`) og firkant-parenteser (`[`, `]`).

For manglende lukkende krøllparanteser `}` vil du se mange rare feilmeldinger og helt til slutt denne:

> error: expected '}' at end of input

For manglende lukkende parenteser (`)`) vil du se mange rare feilmeldinger og blant dem denne. Det samme gjelder for manglende lukkende firkant-parenteser (`]`):

> error: expected ')' before ...

### Feilstavelser i navn

Datamaskinen er **veldig** nøye når det gjelder navn på funksjoner og variabler. Husk at stor- og små-bokstaver er forskjellige for datamaskinen:

``` cpp
void setup() {
  int intger;
  integer = 42;
}
```

Feilmeldingen ser da slik ut:

> sketch.ino:3: error: 'integer' was not declared in this scope

### Bruk av variabler utenfor scope

Når du skriver et sett med krøllparenteser (`{`, `}`) så introduserer du det vi kaller et *scope* i koden din. Dette skjer altså for hver funksjon, if-setning, eller løkke du skriver. Det som er viktig å huske på med et scope er at variabler du deklarerer inni dette scopet kun *lever* til koden møter den matchende lukkende krøllparentesen. La oss se på dette:

``` cpp
void loop() {
  do {
    int error = sensor.read();
  } while (error < 0);
}
```

I eksemplet over ser du en `do`-`while`-løkke. Inni denne deklarer vi variabelen `error` og setter dens verdi lik resultatet av en avlesning av sensor. **Men**: vi skjekker verdien til denne variabelen i betingelsen til `do`-`while`-løkken (i `(error < 0)`). Med den lukkende krøllparentesen foran `while`-kodeordet har variabelen `error` sluttet å eksistere, så `Arduino IDE` kommer til å klage med følgende feilmelding:

> sketch.ino:4: error: 'error' was not declared in this scope

For å løse dette problemet må du deklarere variabelen i scopet utenfor løkken, som vist under. Merk at vi forsatt setter variabelens verdi *inni* løkken.

``` cpp
void loop() {
  int error;
  do {
    error = sensor.read();
  } while (error < 0);
}
```

Merk også at indre scopes har kjennskap til alle overordnete scopes. Dvs. `error` kjennes til både i scopet til `loop` funksjonen og inni scopet til `do`-`while`-løkken, siden den ligger inni scopet til `loop` funksjonen. Derimot så kan yttre scopes ikke ha kjennskap til ting som ligger i et indre scope, dvs. variabler inni `do`-`while`-løkken kommer ikke til å eksistere utenfor denne løkken.

-----

## Gå tilbake

↑ [Gå til: **Guider**][guides]

[guides]: airbit-Guider
[config-ide]: Konfigurasjon-av-Arduino-IDE

[missing-semicolon]: Arduino-IDE-Missing-Semicolon.png


text:
#ifndef UNICODE_SUPPORT_H_INCLUDED
#define UNICODE_SUPPORT_H_INCLUDED

#include <stdio.h>
#include <sys/stat.h>

#define WIN_UNICODE 1

char *utf16_to_utf8(const wchar_t *input);
char *utf16_to_ansi(const wchar_t *input);
wchar_t *utf8_to_utf16(const char *input);
void init_commandline_arguments_utf8(int *argc, char ***argv);
void free_commandline_arguments_utf8(int *argc, char ***argv);
FILE *fopen_utf8(const char *filename_utf8, const char *mode_utf8);
int stat_utf8(const char *path_utf8, struct _stat *buf);
int unlink_utf8(const char *path_utf8);
void init_console_utf8(void);
void uninit_console_utf8(void);

#endif


text: filtres


text:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTcms.Common;
using System.Security.Cryptography;
using System.Text;

namespace DTcms.Web.admin
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                txtUserName.Text = Utils.GetCookie("DTRememberName");
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string userName = txtUserName.Text.Trim();
            string userPwd = txtPassword.Text.Trim();

            if (userName.Equals("") || userPwd.Equals(""))
            {
                msgtip.InnerHtml = "请输入用户名或密码";
                return;
            }
            if (Session["AdminLoginSun"] == null)
            {
                Session["AdminLoginSun"] = 1;
            }
            else
            {
                Session["AdminLoginSun"] = Convert.ToInt32(Session["AdminLoginSun"]) + 1;
            }
            //判断登录错误次数
            if (Session["AdminLoginSun"] != null && Convert.ToInt32(Session["AdminLoginSun"]) > 5)
            {
                msgtip.InnerHtml = "错误超过5次,关闭浏览器重新登录!";
                return;
            }
            BLL.manager bll = new BLL.manager();
            Model.manager model = bll.GetModel(userName, userPwd, true);
            if (model == null)
            {
                msgtip.InnerHtml = "用户名或密码有误,请重试!";
                return;
            }
            Session[DTKeys.SESSION_ADMIN_INFO] = model;
            Session.Timeout = 45;
            //写入登录日志
            Model.siteconfig siteConfig = new BLL.siteconfig().loadConfig();
            if (siteConfig.logstatus > 0)
            {
                new BLL.manager_log().Add(model.id, model.user_name, DTEnums.ActionEnum.Login.ToString(), "用户登录");
            }
            //写入Cookies
            Utils.WriteCookie("DTRememberName", model.user_name, 14400);
            Utils.WriteCookie("AdminName", "DTcms", model.user_name);
            Utils.WriteCookie("AdminPwd", "DTcms", model.password);
            Response.Redirect("index.aspx");
            return;
        }

    }
}


text:
package checklog

import (
	"os"
	"syscall"
)

func init() {
	defaultSignal = syscall.SIGTERM
}

func detectInode(fi os.FileInfo) uint {
	if stat, ok := fi.Sys().(*syscall.Stat_t); ok {
		return uint(stat.Ino)
	}
	return 0
}


text:
require 'spec_helper'

describe Mongo::Session do
  min_server_fcv '3.6'
  require_topology :replica_set, :sharded

  let(:session) do
    authorized_client.start_session(options)
  end

  let(:options) do
    {}
  end

  describe '#initialize' do

    context 'when options are provided' do

      it 'duplicates and freezes the options' do
        expect(session.options).not_to be(options)
        expect(session.options.frozen?).to be(true)
      end
    end

    it 'sets a server session with an id' do
      expect(session.session_id).to be_a(BSON::Document)
    end

    it 'sets the cluster time to nil' do
      expect(session.cluster_time).to be(nil)
    end

    it 'sets the cluster' do
      expect(session.cluster).to be(authorized_client.cluster)
    end
  end

  describe '#inspect' do

    it 'includes the Ruby object_id in the formatted string' do
      expect(session.inspect).to include(session.object_id.to_s)
    end

    it 'includes the session_id in the formatted string' do
      expect(session.inspect).to include(session.session_id.to_s)
    end

    context 'when options are provided' do

      let(:options) do
        { causal_consistency: true }
      end

      it 'includes the options in the formatted string' do
        expect(session.inspect).to include({ implicit: false,
                                             causal_consistency: true }.to_s)
      end
    end
  end

  describe '#advance_cluster_time' do

    let(:new_cluster_time) do
      { 'clusterTime' => BSON::Timestamp.new(0, 5) }
    end

    context 'when the session does not have a cluster time' do

      before do
        session.advance_cluster_time(new_cluster_time)
      end

      it 'sets the new cluster time' do
        expect(session.cluster_time).to eq(new_cluster_time)
      end
    end

    context 'when the session already has a cluster time' do

      context 'when the original cluster time is less than the new cluster time' do

        let(:original_cluster_time) do
          Mongo::ClusterTime.new('clusterTime' => BSON::Timestamp.new(0, 1))
        end

        before do
          session.instance_variable_set(:@cluster_time, original_cluster_time)
          session.advance_cluster_time(new_cluster_time)
        end

        it 'sets the new cluster time' do
          expect(session.cluster_time).to eq(new_cluster_time)
        end
      end

      context 'when the original cluster time is equal or greater than the new cluster time' do

        let(:original_cluster_time) do
          Mongo::ClusterTime.new('clusterTime' => BSON::Timestamp.new(0, 6))
        end

        before do
          session.instance_variable_set(:@cluster_time, original_cluster_time)
          session.advance_cluster_time(new_cluster_time)
        end

        it 'does not update the cluster time' do
          expect(session.cluster_time).to eq(original_cluster_time)
        end
      end
    end
  end

  describe '#advance_operation_time' do

    let(:new_operation_time) do
      BSON::Timestamp.new(0, 5)
    end

    context 'when the session does not have an operation time' do

      before do
        session.advance_operation_time(new_operation_time)
      end

      it 'sets the new operation time' do
        expect(session.operation_time).to eq(new_operation_time)
      end
    end

    context 'when the session already has an operation time' do

      context 'when the original operation time is less than the new operation time' do

        let(:original_operation_time) do
          BSON::Timestamp.new(0, 1)
        end

        before do
          session.instance_variable_set(:@operation_time, original_operation_time)
          session.advance_operation_time(new_operation_time)
        end

        it 'sets the new operation time' do
          expect(session.operation_time).to eq(new_operation_time)
        end
      end

      context 'when the original operation time is equal or greater than the new operation time' do

        let(:original_operation_time) do
          BSON::Timestamp.new(0, 6)
        end

        before do
          session.instance_variable_set(:@operation_time, original_operation_time)
          session.advance_operation_time(new_operation_time)
        end

        it 'does not update the operation time' do
          expect(session.operation_time).to eq(original_operation_time)
        end
      end
    end
  end

  describe 'ended?' do

    context 'when the session has not been ended' do

      it 'returns false' do
        expect(session.ended?).to be(false)
      end
    end

    context 'when the session has been ended' do

      before do
        session.end_session
      end

      it 'returns true' do
        expect(session.ended?).to be(true)
      end
    end
  end

  describe 'end_session' do

    let!(:server_session) do
      session.instance_variable_get(:@server_session)
    end

    let(:cluster_session_pool) do
      session.cluster.session_pool
    end

    it 'returns the server session to the cluster session pool' do
      session.end_session
      expect(cluster_session_pool.instance_variable_get(:@queue)).to include(server_session)
    end

    context 'when #end_session is called multiple times' do

      before do
        session.end_session
      end

      it 'returns nil' do
        expect(session.end_session).to be_nil
      end
    end
  end

  describe '#retry_writes?' do

    context 'when the option is set to true' do

      let(:client) do
        authorized_client_with_retry_writes
      end

      it 'returns true' do
        expect(client.start_session.retry_writes?).to be(true)
      end
    end

    context 'when the option is set to false' do

      let(:client) do
        authorized_client.with(retry_writes: false)
      end

      it 'returns false' do
        expect(client.start_session.retry_writes?).to be(false)
      end
    end

    context 'when the option is not defined' do
      require_no_retry_writes

      let(:client) do
        authorized_client
      end

      it 'returns false' do
        expect(client.start_session.retry_writes?).to be(false)
      end
    end
  end

  describe '#session_id' do
    it 'returns a BSON::Document' do
      expect(session.session_id).to be_a(BSON::Document)
    end

    context 'ended session' do
      before do
        session.end_session
      end

      it 'raises SessionEnded' do
        expect do
          session.session_id
        end.to raise_error(Mongo::Error::SessionEnded)
      end
    end

    context "when the sesion is not materialized" do
      let(:session) { authorized_client.get_session(implicit: true) }

      before do
        expect(session.materialized?).to be false
      end

      it "raises SessionNotMaterialized" do

        expect do
          session.session_id
        end.to raise_error(Mongo::Error::SessionNotMaterialized)
      end
    end
  end

  describe '#txn_num' do
    it 'returns an integer' do
      expect(session.txn_num).to be_a(Integer)
    end

    context 'ended session' do
      before do
        session.end_session
      end

      it 'raises SessionEnded' do
        expect do
          session.txn_num
        end.to raise_error(Mongo::Error::SessionEnded)
      end
    end
  end

  describe '#next_txn_num' do
    it 'returns an integer' do
      expect(session.next_txn_num).to be_a(Integer)
    end

    it 'increments transaction number on each call' do
      expect(session.next_txn_num).to eq(1)
      expect(session.next_txn_num).to eq(2)
    end

    context 'ended session' do
      before do
        session.end_session
      end

      it 'raises SessionEnded' do
        expect do
          session.next_txn_num
        end.to raise_error(Mongo::Error::SessionEnded)
      end
    end
  end

  describe '#start_session' do
    context 'when block doesn\'t raise an error' do
      it 'closes the session after the block' do
        block_session = nil
        authorized_client.start_session do |session|
          expect(session.ended?).to be false
          block_session = session
        end
        expect(block_session.ended?).to be true
      end
    end

    context 'when block raises an error' do
      it 'closes the session after the block' do
        block_session = nil
        expect do
          authorized_client.start_session do |session|
            block_session = session
            raise 'This is an error!'
          end
        end.to raise_error(StandardError, 'This is an error!')
        expect(block_session.ended?).to be true
      end
    end

    context 'when block returns value' do
      it 'is returned by the function' do
        res = authorized_client.start_session do |session|
          4
        end
        expect(res).to be 4
      end
    end

    it 'returns a session with session id' do
      session = authorized_client.start_session
      session.session_id.should be_a(BSON::Document)
    end
  end
end


text:
module UsaliaBot
  module Events
    module Ready
      extend Discordrb::EventContainer

      ready do |event|
        event.bot.game = 'Disgaea 5'
      end
    end
  end
end


text:
package org.dataalgorithms.chap06.secondarysort;

import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Partitioner;

import org.dataalgorithms.chap06.TimeSeriesData;

/**
 * NaturalKeyPartitioner
 *
 * This custom partitioner allow us to distribute how
 * outputs from the map stage are sent to the reducers.
 * The NaturalKeyPartitioner partitions the data output
 * from the map phase (SortByMRF_MovingAverageMapper)
 * before it is sent through the shuffle phase. Since
 * we want a single reducer to receive all time series
 * data for a single "name", we partition data output
 * of the map phase by only the natural key component
 * ("name").
 *
 * @author Mahmoud Parsian
 *
 */
public class NaturalKeyPartitioner implements
        Partitioner<CompositeKey, TimeSeriesData> {

    @Override
    public int getPartition(CompositeKey key,
            TimeSeriesData value,
            int numberOfPartitions) {
        return Math.abs((int) (hash(key.getName()) % numberOfPartitions));
    }

    @Override
    public void configure(JobConf jobconf) {
    }

    /**
     * adapted from String.hashCode()
     */
    static long hash(String str) {
        long h = 1125899906842597L; // prime
        int length = str.length();
        for (int i = 0; i < length; i++) {
            h = 31 * h + str.charAt(i);
        }
        return h;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder" xmlns:g="urn:import:com.google.gwt.user.client.ui">

	<ui:style>
		.container {
			width: 100%;
		}
	</ui:style>

	<g:VerticalPanel addStyleNames="{style.container}">
		<g:SimplePanel ui:field="targetsToLunsDiscoverPanel" />
		<g:SimplePanel ui:field="targetsListPanel" />
	</g:VerticalPanel>

</ui:UiBinder>


text:
from distutils.core import setup
import py2exe
import os, os.path, sys
import glob
#adding lib directory to module search path
libpath = os.path.abspath(os.path.dirname(sys.argv[0])) + "/lib"
sys.path.append(os.path.abspath(libpath))

includes = ["encodings", "encodings.latin_1",]
#options = {"py2exe": {"compressed": 1,
#                      "optimize": 2,
#                      "ascii": 1,
#                      "bundle_files": 1,
#                      "includes":includes}},

################################################################
# A program using wxPython

# The manifest will be inserted as resource into test_wx.exe.  This
# gives the controls the Windows XP appearance (if run on XP ;-)
#
# Another option would be to store if in a file named
# test_wx.exe.manifest, and probably copy it with the data_files
# option.
#
manifest_template = '''
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<assemblyIdentity
    version="5.0.0.0"
    processorArchitecture="x86"
    name="%(prog)s"
    type="win32"
/>
<description>%(prog)s Program</description>
<dependency>
    <dependentAssembly>
        <assemblyIdentity
            type="win32"
            name="Microsoft.Windows.Common-Controls"
            version="6.0.0.0"
            processorArchitecture="X86"
            publicKeyToken="6595b64144ccf1df"
            language="*"
        />
    </dependentAssembly>
</dependency>
</assembly>
'''

RT_MANIFEST = 24

################################################################
# arguments for the setup() call

pyTray = dict(
    script = "pytray.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog="pyTray"))],
    dest_base = r"pyTray",
    icon_resources = [(1,"files/images/icon.ico")])

zipfile = r"lib\shardlib"

options = {"py2exe": {"compressed": 1,
                      "optimize": 2}}

################################################################
import os

class InnoScript:
    def __init__(self,
                 name,
                 lib_dir,
                 dist_dir,
                 windows_exe_files = [],
                 lib_files = [],
                 version = "1.0"):
        self.lib_dir = lib_dir
        self.dist_dir = dist_dir
        if not self.dist_dir[-1] in "\\/":
            self.dist_dir += "\\"
        self.name = name
        self.version = version
        self.windows_exe_files = [self.chop(p) for p in windows_exe_files]
        self.lib_files = [self.chop(p) for p in lib_files]

    def chop(self, pathname):
        assert pathname.startswith(self.dist_dir)
        return pathname[len(self.dist_dir):]

    def create(self, pathname="dist\\pytray.iss"):
        self.pathname = pathname
        ofi = self.file = open(pathname, "w")
        print >> ofi, "; WARNING: This script has been created by py2exe. Changes to this script"
        print >> ofi, "; will be overwritten the next time py2exe is run!"
        print >> ofi, r"[Setup]"
        print >> ofi, r"AppName=%s" % self.name
        print >> ofi, r"AppVerName=%s %s" % (self.name, self.version)
        print >> ofi, r"DefaultDirName={pf}\%s" % self.name
        print >> ofi, r"DefaultGroupName=%s" % self.name
        print >> ofi

        print >> ofi, r"[Files]"
        for path in self.windows_exe_files + self.lib_files:
            print >> ofi, r'Source: "%s"; DestDir: "{app}\%s"; Flags: ignoreversion' % (path, os.path.dirname(path))
        print >> ofi

        print >> ofi, r"[Icons]"
        for path in self.windows_exe_files:
            print >> ofi, r'Name: "{group}\%s"; Filename: "{app}\%s"' % \
                  (self.name, path)
        print >> ofi, 'Name: "{group}\Uninstall %s"; Filename: "{uninstallexe}"' % self.name

    def compile(self):
        try:
            import ctypes
        except ImportError:
            try:
                import win32api
            except ImportError:
                import os
                os.startfile(self.pathname)
            else:
                print "Ok, using win32api."
                win32api.ShellExecute(0, "compile",
                                                self.pathname,
                                                None,
                                                None,
                                                0)
        else:
            print "Cool, you have ctypes installed."
            res = ctypes.windll.shell32.ShellExecuteA(0, "compile",
                                                      self.pathname,
                                                      None,
                                                      None,
                                                      0)
            if res < 32:
                raise RuntimeError, "ShellExecute failed, error %d" % res

################################################################

from py2exe.build_exe import py2exe

class build_installer(py2exe):
    # This class first builds the exe file(s), then creates a Windows installer.
    # You need InnoSetup for it.
    def run(self):
        # First, let py2exe do it's work.
        py2exe.run(self)

        lib_dir = self.lib_dir
        dist_dir = self.dist_dir

        # create the Installer, using the files py2exe has created.
        script = InnoScript("pytray",
                            lib_dir,
                            dist_dir,
                            self.windows_exe_files,
                            self.lib_files)
        print "*** creating the inno setup script***"
        script.create()
        print "*** compiling the inno setup script***"
        script.compile()
        # Note: By default the final setup.exe will be in an Output subdirectory.

################################################################

setup(
    description='Cryallization Management Software',
    options = options,
    # The lib directory contains everything except the executables and the python dll.
    zipfile = zipfile,
    windows = [pyTray],
    # use out build_installer class as extended py2exe build command
    cmdclass = {"py2exe": build_installer},
    data_files=[(r"files", glob.glob(r"files/*.*")),
                (r"files/test", glob.glob(r"files/test/*.*")),
                (r"files/Dtd", glob.glob(r"files/Dtd/*.*")),
                (r"files/fonts", glob.glob(r"files/fonts/*.*")),
                (r"files/images", glob.glob(r"files/images/*.*")),
                ],
    author='Thomas Schalch',
    author_email='schalch@cshl.edu',
    packages = ["gui","dataStructures","util","test"],
   )