text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- <property name="LOG_HOME" value="${logback.file.path}" /> -->
  <property resource="config.properties" />
<!--     <appender name="FILE" -->
<!--         class="ch.qos.logback.core.rolling.RollingFileAppender"> -->
<!--         <file>${logback.file.path}/xxfw.log</file> -->
<!--         <rollingPolicy -->
<!--             class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> -->
<!--             <fileNamePattern>${logback.file.path}/${logback.file.size.time.name.pattern} -->
<!--             </fileNamePattern> -->
<!--             <maxFileSize>100MB</maxFileSize> -->
<!--             <maxHistory>31</maxHistory> -->
<!--             <totalSizeCap>3GB</totalSizeCap> -->
<!--         </rollingPolicy> -->
<!--         <encoder> -->
<!--             <pattern>%-4r %d %-5level %logger{36} - %msg%n</pattern> -->
<!--         </encoder> -->
<!--     </appender> -->

<!--     <appender name="FILE" -->
<!--         class="ch.qos.logback.core.rolling.RollingFileAppender"> -->
<!--         <file>${logback.file.path}/xxfw.log</file> -->
<!--         <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy"> -->
<!--             <fileNamePattern>${logback.file.path}/${logback.file.zip.name.pattern}</fileNamePattern> -->
<!--             <minIndex>1</minIndex> -->
<!--             <maxIndex>21</maxIndex> -->
<!--         </rollingPolicy> -->
<!--         <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> -->
<!--             <maxFileSize>100MB</maxFileSize> -->
<!--         </triggeringPolicy> -->
<!--         <encoder> -->
<!--             <pattern>%-4r %d %-5level %logger{35} - %msg%n</pattern> -->
<!--         </encoder> -->
<!--     </appender> -->

    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logback.file.path}/${logback.file.name}</file>
        <rollingPolicy
            class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logback.file.path}/${logback.file.time.name.pattern}</fileNamePattern>
            <maxHistory>31</maxHistory>
            <totalSizeCap>3GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>%-4r %d %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%date %-5level %logger{35} - %msg%n</pattern>
        </encoder>
    </appender>

	<logger name="org.springframework.web.filter.CommonsRequestLoggingFilter" level="DEBUG"/>
	<!--   <logger name="java.sql" level="DEBUG" /> -->
	<!--   <logger name="org.hibernate.SQL" level="DEBUG" /> -->
	<!--   <logger name="org.hibernate.type" level="TRACE" /> -->
	<!--   <logger name="org.springframework.jdbc.core" level="DEBUG" /> -->
	<!--   <logger name="org.springframework.jdbc.core.namedparam" level="DEBUG" /> -->
	<!--   <logger name="org.springframework.web.filter.CommonsRequestLoggingFilter" level="DEBUG"/> -->

<!--     <root level="INFO"> -->
<!--         <appender-ref ref="FILE" /> -->
<!--     </root> -->
    <root level="INFO">
    	<appender-ref ref="STDOUT" />
    </root>
</configuration>


text:
// shoutout to pythoneer!
/// Adds ORM wrappers to a struct
#[macro_export]
macro_rules! def_model {
    (struct $name:ident {
        $($field_name:ident: $field_type:ty,)*
    }) => {
        #[derive(Debug)]
        pub struct $name {
            pub id: i32,
            $(pub $field_name: Option<$field_type>,)*
        }

        impl $name {
            /// Creates a new object
            pub fn new($($field_name: $field_type,)*) -> $name {
                $name {
                    id: 0,
                    $($field_name: Some($field_name),)*
                }
            }

            /// Creates the table for the object in the database
            pub fn migrate(conn: &rusqlite::Connection) -> Result<bool, String> {
                // Get all of the previous objects, or an error if it fails.
                /*let prev_objects = $name::select_all(conn);

                // If the object existed before
                if prev_objects.is_ok() {
                    // For now remove all the objects and the table
                    println!("fuck yo data");
                    $name::revert_migration(conn);
                    //println!("{:?}", prev_objects);
                    println!("{:?}", $name::get_db_columns(conn));
                }*/

                $name::get_db_columns(conn);

                let mut query = format!("CREATE TABLE {} ( \n", stringify!($name));
                query.push_str("id INTEGER PRIMARY KEY AUTOINCREMENT, \n");
                $(query.push_str(&format!("{} TEXT NOT NULL, \n",
                                 stringify!($field_name)));)*
                query.pop(); query.pop(); query.pop();
                query.push_str(")");
                let result = conn.execute(&query, &[]);

                // Now that the table is recreated, put the objects back in

                match result {
                    Result::Ok(..) => return Result::Ok(true),
                    Result::Err(err) => {
                        let msg = format!("Error during migration of {}. Possiby a bug in the framework.\n  SQLITE returned: {}",
                                          stringify!($name), err);

                        return Result::Err(msg);
                    }
                }
            }

            /// Removes the object table from the database
            pub fn revert_migration(conn: &rusqlite::Connection) {
                let query = format!("DROP TABLE {}", stringify!($name));
                conn.execute(&query, &[]);
            }

            /// Puts a new object in the database
            pub fn insert(&mut self, conn: &rusqlite::Connection) -> Result<bool, String> {
                let n_of_fields = $name::get_field_names().len();

                let mut query = format!("INSERT INTO {} (", stringify!($name));
                $(query.push_str(&format!("{}, ", stringify!($field_name)));)*
                query.pop(); query.pop();
                query.push_str(") \n");
                query.push_str("VALUES (");
                for i in 0..n_of_fields {
                    query.push_str(&format!("${}, ", i + 1))
                }
                query.pop(); query.pop();
                query.push_str(")");

                //println!("{}", query);

                let result = conn.execute(&query, &[$(self.$field_name.as_ref().unwrap(), )*]);

                match result {

                    Result::Ok(..) => {
                        self.id = $name::get_last_id(conn);
                        return Ok(true);
                    },
                    Result::Err(err) => {
                        let msg = format!("Error while inserting an instance of {} into the database. This might be an error in the framework.\n  SQLITE returned: {}",
                                          stringify!($name), err);

                        return Err(msg);
                    }
                }
            }

            /// Gets the ID of the last object saved
            // this is for internal use but we can't really scope that when using macros
            fn get_last_id(conn: &rusqlite::Connection) -> i32 {
                conn.query_row("SELECT last_insert_rowid()", &[], |row| {
                    row.get(0)
                }).unwrap()
            }

            /// Gets a list of columns inside the database
            fn get_db_columns(conn: &rusqlite::Connection) -> Vec<String> {
                let query = format!("PRAGMA table_info({})", stringify!($name));

                /*conn.query_row(&query, &[], |row| {
                    row.get(1)
                }).unwrap()*/

                let mut stmt = conn.prepare(&query).unwrap();
                let mut column_iter = stmt.query_map(&[], |row| -> String {
                    row.get(1)
                }).unwrap();

                let mut column_vec: Vec<String> = Vec::new();

                for column in column_iter {
                    column_vec.push(column.unwrap());
                }

                column_vec
                /*let column_vec: Vec<String> = Vec::new();

                for column in column_iter {
                    column_vec.push(column);
                }

                column_vec*/
            }

            /// Updates an existing object
            pub fn update(&self, conn: &rusqlite::Connection) {
                let mut query = format!("UPDATE {} SET ", stringify!($name));
                $(query.push_str(&format!("{} = {}, ", stringify!($field_name), self.$field_name.as_ref().unwrap()));)*
                query.pop(); query.pop();
                query.push_str(&format!(" WHERE id = {}", self.id));

                conn.execute(&query, &[]);
            }

            /// Gets all the objects meeting the criteria
            pub fn select_by(conn: &rusqlite::Connection, field: String, value: String) -> Result<Vec<$name>, rusqlite::Error> {
                pub fn inc_one(x: &mut i32) -> i32 {*x += 1; *x};

                let mut counter = 0;

                // Generate SQL query
                let mut query = format!("SELECT id, ");
                $(query.push_str(&format!("{}, ", stringify!($field_name)));)*
                query.pop(); query.pop();
                query.push_str(&format!(" FROM {}", stringify!($name)));
                query.push_str(&format!(" WHERE {}={}",field, value));

                let mut stmt = conn.prepare(&query).unwrap();
                let mut model_iter = try!(stmt.query_map(&[], |row| {
                    let out = $name {
                        id: row.get(0),
                        $($field_name: row.get(inc_one(&mut counter)), )*
                    };

                    // Reset the counter as we will be parsing the next object
                    counter = 0;

                    out
                }));

                let mut model_vec: Vec<$name> = Vec::new();

                for model in model_iter {
                    model_vec.push(try!(model));
                }

                Ok(model_vec)
            }

            /// Gets all instances of this object
            pub fn select_all(conn: &rusqlite::Connection) -> Result<Vec<$name>, rusqlite::Error> {
                pub fn inc_one(x: &mut i32) -> i32 {*x += 1; *x};

                let mut counter = 0;

                let mut query = format!("SELECT id, ");
                $(query.push_str(&format!("{}, ", stringify!($field_name)));)*
                query.pop(); query.pop();
                query.push_str(&format!(" FROM {}", stringify!($name)));
                //query.push_str(&format!(" WHERE {}={}",field, value));

                let mut stmt = conn.prepare(&query).unwrap();
                let mut model_iter = stmt.query_map(&[], |row| {
                    let out = $name {
                        id: row.get(0),
                        $($field_name: row.get_checked(inc_one(&mut counter)).ok(), )*
                    };

                    // Reset the counter as after this we will be getting the next object.
                    counter = 0;

                    out
                }).unwrap();

                let mut model_vec: Vec<$name> = Vec::new();

                for model in model_iter {
                    model_vec.push(try!(model));
                }

                Ok(model_vec)

            }

            pub fn get_field_names() -> Vec<&'static str> {
                vec![$(stringify!($field_name)),*]
            }
        }
    }
}

#[macro_export]
macro_rules! migrations {
    (&$conn:ident, $($name:ident),*) => {
        $(
            println!("Migrating {}", stringify!($name));
            let result = $name::migrate(&$conn);
            if result.is_err() {
                println!("Failed migrating {}, ERROR: {:?}", stringify!($name), result);
            }
        )*
    }
}

redpajama_set_name: RedPajamaGithub


text:
YUI.add('get', function(Y) {

/**
 * Provides a mechanism to fetch remote resources and
 * insert them into a document.
 * @module yui
 * @submodule get
 */

var ua = Y.UA,
    L = Y.Lang,
    TYPE_JS = 'text/javascript',
    TYPE_CSS = 'text/css',
    STYLESHEET = 'stylesheet';

/**
 * Fetches and inserts one or more script or link nodes into the document
 * @class Get
 * @static
 */
Y.Get = function() {

    /**
     * hash of queues to manage multiple requests
     * @property queues
     * @private
     */
    var _get, _purge, _track,

    queues = {},

    /**
     * queue index used to generate transaction ids
     * @property qidx
     * @type int
     * @private
     */
    qidx = 0,

    /**
     * interal property used to prevent multiple simultaneous purge
     * processes
     * @property purging
     * @type boolean
     * @private
     */
    purging,

    /**
     * Generates an HTML element, this is not appended to a document
     * @method _node
     * @param {string} type the type of element.
     * @param {string} attr the attributes.
     * @param {Window} win optional window to create the element in.
     * @return {HTMLElement} the generated node.
     * @private
     */
    _node = function(type, attr, win) {
        var w = win || Y.config.win,
            d = w.document,
            n = d.createElement(type),
            i;

        for (i in attr) {
            if (attr[i] && attr.hasOwnProperty(i)) {
                n.setAttribute(i, attr[i]);
            }
        }

        return n;
    },

    /**
     * Generates a link node
     * @method _linkNode
     * @param {string} url the url for the css file.
     * @param {Window} win optional window to create the node in.
     * @param {object} attributes optional attributes collection to apply to the
     * new node.
     * @return {HTMLElement} the generated node.
     * @private
     */
    _linkNode = function(url, win, attributes) {
        var o = {
            id: Y.guid(),
            type: TYPE_CSS,
            rel: STYLESHEET,
            href: url
        };
        if (attributes) {
            Y.mix(o, attributes);
        }
        return _node('link', o, win);
    },

    /**
     * Generates a script node
     * @method _scriptNode
     * @param {string} url the url for the script file.
     * @param {Window} win optional window to create the node in.
     * @param {object} attributes optional attributes collection to apply to the
     * new node.
     * @return {HTMLElement} the generated node.
     * @private
     */
    _scriptNode = function(url, win, attributes) {
        var o = {
            id: Y.guid(),
            type: TYPE_JS
        };

        if (attributes) {
            Y.mix(o, attributes);
        }

        o.src = url;

        return _node('script', o, win);
    },

    /**
     * Returns the data payload for callback functions.
     * @method _returnData
     * @param {object} q the queue.
     * @param {string} msg the result message.
     * @param {string} result the status message from the request.
     * @return {object} the state data from the request.
     * @private
     */
    _returnData = function(q, msg, result) {
        return {
                tId: q.tId,
                win: q.win,
                data: q.data,
                nodes: q.nodes,
                msg: msg,
                statusText: result,
                purge: function() {
                    _purge(this.tId);
                }
            };
    },

    /**
     * The transaction is finished
     * @method _end
     * @param {string} id the id of the request.
     * @param {string} msg the result message.
     * @param {string} result the status message from the request.
     * @private
     */
    _end = function(id, msg, result) {
        var q = queues[id], sc;
        if (q && q.onEnd) {
            sc = q.context || q;
            q.onEnd.call(sc, _returnData(q, msg, result));
        }
    },

    /*
     * The request failed, execute fail handler with whatever
     * was accomplished.  There isn't a failure case at the
     * moment unless you count aborted transactions
     * @method _fail
     * @param {string} id the id of the request
     * @private
     */
    _fail = function(id, msg) {
        Y.log('get failure: ' + msg, 'warn', 'get');

        var q = queues[id], sc;
        if (q.timer) {
            // q.timer.cancel();
            clearTimeout(q.timer);
        }

        // execute failure callback
        if (q.onFailure) {
            sc = q.context || q;
            q.onFailure.call(sc, _returnData(q, msg));
        }

        _end(id, msg, 'failure');
    },

    /**
     * The request is complete, so executing the requester's callback
     * @method _finish
     * @param {string} id the id of the request.
     * @private
     */
    _finish = function(id) {
        // Y.log("Finishing transaction " + id, "info", "get");
        var q = queues[id], msg, sc;
        if (q.timer) {
            // q.timer.cancel();
            clearTimeout(q.timer);
        }
        q.finished = true;

        if (q.aborted) {
            msg = 'transaction ' + id + ' was aborted';
            _fail(id, msg);
            return;
        }

        // execute success callback
        if (q.onSuccess) {
            sc = q.context || q;
            q.onSuccess.call(sc, _returnData(q));
        }

        _end(id, msg, 'OK');
    },

    /**
     * Timeout detected
     * @method _timeout
     * @param {string} id the id of the request.
     * @private
     */
    _timeout = function(id) {
        Y.log('Timeout ' + id, 'info', 'get');
        var q = queues[id], sc;
        if (q.onTimeout) {
            sc = q.context || q;
            q.onTimeout.call(sc, _returnData(q));
        }

        _end(id, 'timeout', 'timeout');
    },

    /**
     * Loads the next item for a given request
     * @method _next
     * @param {string} id the id of the request.
     * @param {string} loaded the url that was just loaded, if any.
     * @return {string} the result.
     * @private
     */
    _next = function(id, loaded) {
// Y.log("_next: " + id + ", loaded: " + (loaded || "nothing"), "info", "get");
        var q = queues[id], msg, w, d, h, n, url, s,
            insertBefore;

        if (q.timer) {
            // Y.log('cancel timer');
            // q.timer.cancel();
            clearTimeout(q.timer);
        }

        if (q.aborted) {
            msg = 'transaction ' + id + ' was aborted';
            _fail(id, msg);
            return;
        }

        if (loaded) {
            q.url.shift();
            if (q.varName) {
                q.varName.shift();
            }
        } else {
            // This is the first pass: make sure the url is an array
            q.url = (L.isString(q.url)) ? [q.url] : q.url;
            if (q.varName) {
                q.varName = (L.isString(q.varName)) ? [q.varName] : q.varName;
            }
        }

        w = q.win;
        d = w.document;
        h = d.getElementsByTagName('head')[0];

        if (q.url.length === 0) {
            _finish(id);
            return;
        }

        url = q.url[0];

        // if the url is undefined, this is probably a trailing comma
        // problem in IE.
        if (!url) {
            q.url.shift();
            Y.log('skipping empty url');
            return _next(id);
        }

        Y.log('attempting to load ' + url, 'info', 'get');

        if (q.timeout) {
            // Y.log('create timer');
            // q.timer = L.later(q.timeout, q, _timeout, id);
            q.timer = setTimeout(function() {
                _timeout(id);
            }, q.timeout);
        }

        if (q.type === 'script') {
            n = _scriptNode(url, w, q.attributes);
        } else {
            n = _linkNode(url, w, q.attributes);
        }

        // track this node's load progress
        _track(q.type, n, id, url, w, q.url.length);

        // add the node to the queue so we can return it to the user supplied
        // callback
        q.nodes.push(n);

        // add it to the head or insert it before 'insertBefore'.  Work around
        // IE bug if there is a base tag.
        insertBefore = q.insertBefore ||
                       d.getElementsByTagName('base')[0];

        if (insertBefore) {
            s = _get(insertBefore, id);
            if (s) {
                Y.log('inserting before: ' + insertBefore, 'info', 'get');
                s.parentNode.insertBefore(n, s);
            }
        } else {
            h.appendChild(n);
        }

        // Y.log("Appending node: " + url, "info", "get");

        // FireFox does not support the onload event for link nodes, so
        // there is no way to make the css requests synchronous. This means
        // that the css rules in multiple files could be applied out of order
        // in this browser if a later request returns before an earlier one.
        // Safari too.
        if ((ua.webkit || ua.gecko) && q.type === 'css') {
            _next(id, url);
        }
    },

    /**
     * Removes processed queues and corresponding nodes
     * @method _autoPurge
     * @private
     */
    _autoPurge = function() {
        if (purging) {
            return;
        }
        purging = true;

        var i, q;

        for (i in queues) {
            if (queues.hasOwnProperty(i)) {
                q = queues[i];
                if (q.autopurge && q.finished) {
                    _purge(q.tId);
                    delete queues[i];
                }
            }
        }

        purging = false;
    },

    /**
     * Saves the state for the request and begins loading
     * the requested urls
     * @method queue
     * @param {string} type the type of node to insert.
     * @param {string} url the url to load.
     * @param {object} opts the hash of options for this request.
     * @return {object} transaction object.
     * @private
     */
    _queue = function(type, url, opts) {
        opts = opts || {};

        var id = 'q' + (qidx++), q,
            thresh = opts.purgethreshold || Y.Get.PURGE_THRESH;

        if (qidx % thresh === 0) {
            _autoPurge();
        }

        queues[id] = Y.merge(opts, {
            tId: id,
            type: type,
            url: url,
            finished: false,
            nodes: []
        });

        q = queues[id];
        q.win = q.win || Y.config.win;
        q.context = q.context || q;
        q.autopurge = ('autopurge' in q) ? q.autopurge :
                      (type === 'script') ? true : false;

        q.attributes = q.attributes || {};
        q.attributes.charset = opts.charset || q.attributes.charset || 'utf-8';

        _next(id);

        return {
            tId: id
        };
    };

    /**
     * Detects when a node has been loaded.  In the case of
     * script nodes, this does not guarantee that contained
     * script is ready to use.
     * @method _track
     * @param {string} type the type of node to track.
     * @param {HTMLElement} n the node to track.
     * @param {string} id the id of the request.
     * @param {string} url the url that is being loaded.
     * @param {Window} win the targeted window.
     * @param {int} qlength the number of remaining items in the queue,
     * including this one.
     * @param {Function} trackfn function to execute when finished
     * the default is _next.
     * @private
     */
    _track = function(type, n, id, url, win, qlength, trackfn) {
        var f = trackfn || _next;

        // IE supports the readystatechange event for script and css nodes
        // Opera only for script nodes.  Opera support onload for script
        // nodes, but this doesn't fire when there is a load failure.
        // The onreadystatechange appears to be a better way to respond
        // to both success and failure.
        if (ua.ie) {
            n.onreadystatechange = function() {
                var rs = this.readyState;
                if ('loaded' === rs || 'complete' === rs) {
                    // Y.log(id + " onreadstatechange " + url, "info", "get");
                    n.onreadystatechange = null;
                    f(id, url);
                }
            };

        // webkit prior to 3.x is no longer supported
        } else if (ua.webkit) {
            if (type === 'script') {
                // Safari 3.x supports the load event for script nodes (DOM2)
                n.addEventListener('load', function() {
                    // Y.log(id + " DOM2 onload " + url, "info", "get");
                    f(id, url);
                });
            }

        // FireFox and Opera support onload (but not DOM2 in FF) handlers for
        // script nodes.  Opera, but not FF, supports the onload event for link
        // nodes.
        } else {
            n.onload = function() {
                // Y.log(id + " onload " + url, "info", "get");
                f(id, url);
            };

            n.onerror = function(e) {
                _fail(id, e + ': ' + url);
            };
        }
    };

    _get = function(nId, tId) {
        var q = queues[tId],
            n = (L.isString(nId)) ? q.win.document.getElementById(nId) : nId;
        if (!n) {
            _fail(tId, 'target node not found: ' + nId);
        }

        return n;
    };

    /**
     * Removes the nodes for the specified queue
     * @method _purge
     * @param {string} tId the transaction id.
     * @private
     */
    _purge = function(tId) {
        var n, l, d, h, s, i, node, attr, insertBefore,
            q = queues[tId];

        if (q) {
            n = q.nodes;
            l = n.length;
            d = q.win.document;
            h = d.getElementsByTagName('head')[0];

            insertBefore = q.insertBefore ||
                           d.getElementsByTagName('base')[0];

            if (insertBefore) {
                s = _get(insertBefore, tId);
                if (s) {
                    h = s.parentNode;
                }
            }

            for (i = 0; i < l; i = i + 1) {
                node = n[i];
                if (node.clearAttributes) {
                    node.clearAttributes();
                } else {
                    for (attr in node) {
                        if (node.hasOwnProperty(attr)) {
                            delete node[attr];
                        }
                    }
                }

                h.removeChild(node);
            }
        }
        q.nodes = [];
    };

    return {

        /**
         * The number of request required before an automatic purge.
         * Can be configured via the 'purgethreshold' config
         * property PURGE_THRESH
         * @static
         * @type int
         * @default 20
         * @private
         */
        PURGE_THRESH: 20,

        /**
         * Called by the the helper for detecting script load in Safari
         * @method _finalize
         * @static
         * @param {string} id the transaction id.
         * @private
         */
        _finalize: function(id) {
            Y.log(id + ' finalized ', 'info', 'get');
            setTimeout(function() {
                _finish(id);
            }, 0);
        },

        /**
         * Abort a transaction
         * @method abort
         * @static
         * @param {string|object} o Either the tId or the object returned from
         * script() or css().
         */
        abort: function(o) {
            var id = (L.isString(o)) ? o : o.tId,
                q = queues[id];
            if (q) {
                Y.log('Aborting ' + id, 'info', 'get');
                q.aborted = true;
            }
        },

        /**
         * Fetches and inserts one or more script nodes into the head
         * of the current document or the document in a specified window.
         *
         * @method script
         * @static
         * @param {string|string[]} url the url or urls to the script(s).
         * @param {object} opts Options:
         *

         *
onSuccess

         *

         * callback to execute when the script(s) are finished loading
         * The callback receives an object back with the following
         * data:
         *

         *
win

         *
the window the script(s) were inserted into

         *
data

         *
the data object passed in when the request was made

         *
nodes

         *
An array containing references to the nodes that were
         * inserted

         *
purge

         *
A function that, when executed, will remove the nodes
         * that were inserted

         *

         *

         *

         *
onTimeout

         *

         * callback to execute when a timeout occurs.
         * The callback receives an object back with the following
         * data:
         *

         *
win

         *
the window the script(s) were inserted into

         *
data

         *
the data object passed in when the request was made

         *
nodes

         *
An array containing references to the nodes that were
         * inserted

         *
purge

         *
A function that, when executed, will remove the nodes
         * that were inserted

         *

         *

         *

         *
onEnd

         *
a function that executes when the transaction finishes,
         * regardless of the exit path

         *
onFailure

         *

         * callback to execute when the script load operation fails
         * The callback receives an object back with the following
         * data:
         *

         *
win

         *
the window the script(s) were inserted into

         *
data

         *
the data object passed in when the request was made

         *
nodes

         *
An array containing references to the nodes that were
         * inserted successfully

         *
purge

         *
A function that, when executed, will remove any nodes
         * that were inserted

         *

         *

         *

         *
context

         *
the execution context for the callbacks

         *
win

         *
a window other than the one the utility occupies

         *
autopurge

         *

         * setting to true will let the utilities cleanup routine purge
         * the script once loaded
         *

         *
purgethreshold

         *

         * The number of transaction before autopurge should be initiated
         *

         *
data

         *

         * data that is supplied to the callback when the script(s) are
         * loaded.
         *

         *
insertBefore

         *
node or node id that will become the new node's nextSibling.
         * If this is not specified, nodes will be inserted before a base
         * tag should it exist.  Otherwise, the nodes will be appended to the
         * end of the document head.

         *

         *
charset

         *
Node charset, default utf-8 (deprecated, use the attributes
         * config)

         *
attributes

         *
An object literal containing additional attributes to add to
         * the link tags

         *
timeout

         *
Number of milliseconds to wait before aborting and firing
         * the timeout event

         *

         *   Y.Get.script(
         *   ["http://yui.yahooapis.com/2.5.2/build/yahoo/yahoo-min.js",
         *    "http://yui.yahooapis.com/2.5.2/build/event/event-min.js"],
         *   {
         *     onSuccess: function(o) {
         *       this.log("won't cause error because Y is the context");
         *       Y.log(o.data); // foo
         *       Y.log(o.nodes.length === 2) // true
         *       // o.purge(); // optionally remove the script nodes
         *                     // immediately
         *     },
         *     onFailure: function(o) {
         *       Y.log("transaction failed");
         *     },
         *     onTimeout: function(o) {
         *       Y.log("transaction timed out");
         *     },
         *     data: "foo",
         *     timeout: 10000, // 10 second timeout
         *     context: Y, // make the YUI instance
         *     // win: otherframe // target another window/frame
         *     autopurge: true // allow the utility to choose when to
         *                     // remove the nodes
         *     purgetheshold: 1 // purge previous transaction before
         *                      // next transaction
         *   });.
         *

         * @return {tId: string} an object containing info about the
         * transaction.
         */
        script: function(url, opts) {
            return _queue('script', url, opts);
        },

        /**
         * Fetches and inserts one or more css link nodes into the
         * head of the current document or the document in a specified
         * window.
         * @method css
         * @static
         * @param {string} url the url or urls to the css file(s).
         * @param {object} opts Options:
         *

         *
onSuccess

         *

         * callback to execute when the css file(s) are finished loading
         * The callback receives an object back with the following
         * data:
         *
win

         *
the window the link nodes(s) were inserted into

         *
data

         *
the data object passed in when the request was made

         *
nodes

         *
An array containing references to the nodes that were
         * inserted

         *
purge

         *
A function that, when executed, will remove the nodes
         * that were inserted

         *

         *

         *

         *
context

         *
the execution context for the callbacks

         *
win

         *
a window other than the one the utility occupies

         *
data

         *

         * data that is supplied to the callbacks when the nodes(s) are
         * loaded.
         *

         *
insertBefore

         *
node or node id that will become the new node's nextSibling

         *
charset

         *
Node charset, default utf-8 (deprecated, use the attributes
         * config)

         *
attributes

         *
An object literal containing additional attributes to add to
         * the link tags

         *

         *

         * Y.Get.css("http://localhost/css/menu.css");
         *

         *

         *   Y.Get.css(
         *   ["http://localhost/css/menu.css",
         *    "http://localhost/css/logger.css"], {
         *     insertBefore: 'custom-styles' // nodes will be inserted
         *                                   // before the specified node
         *   });.
         *

         * @return {tId: string} an object containing info about the
         * transaction.
         */
        css: function(url, opts) {
            return _queue('css', url, opts);
        }
    };
}();

}, '3.3.0' ,{requires:['yui-base']});


text:
#include <traits-unit.h>
#include <traits/traits.h>

/*
 * Declare features
 * Suppose saved on: features.h
 */
Feature(SignalsHandling);

/*
 * Describe our test case
 */
Describe("TraitsUnitFramework",
         Trait("ShouldPass",
               Run(SignalsHandling)
         )
)

/*
 * Define features
 * Suppose saved on: features.c
 */
Feature(SignalsHandling) {
    const size_t wrappedSignalsCounter = traitsUnit_getWrappedSignalsCounter();
    assert_equal(wrappedSignalsCounter, traitsUnit_getWrappedSignalsCounter());

    traitsUnit_wrap(SIGILL) {
        printf("Wrapping: %s. ", strsignal(SIGILL));
        raise(SIGILL);
    }
    assert_equal(wrappedSignalsCounter + 1, traitsUnit_getWrappedSignalsCounter());

    traitsUnit_wrap(SIGABRT) {
        printf("Wrapping: %s. ", strsignal(SIGABRT));
        abort();
    }
    assert_equal(wrappedSignalsCounter + 2, traitsUnit_getWrappedSignalsCounter());

    traitsUnit_wrap(SIGSEGV) {
        printf("Wrapping: %s. ", strsignal(SIGSEGV));
        raise(SIGSEGV);
    }
    assert_equal(wrappedSignalsCounter + 3, traitsUnit_getWrappedSignalsCounter());
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monogr. Uredin. (Lipsiae) 1(1): 129 (1902)

#### Original name
Puccinia otopappi P. Syd. & Syd.

### Remarks
null


text: * sur Kaggle : https://www.kaggle.com/rounakbanik/the-movies-dataset


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
I3DXML.XMLRepresentationDocument
</TITLE>

<META NAME="date" CONTENT="2013-10-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

igeo.io

Class I3DXML.XMLRepresentationDocument

java.lang.Object
  igeo.io.I3DXML.RepresentationDocument
      igeo.io.I3DXML.XMLRepresentationDocument

Enclosing class:
I3DXML

public static class I3DXML.XMLRepresentationDocument
extends I3DXML.RepresentationDocument

Field Summary

 java.util.ArrayList<I3DXML.VisualizationRepType>
representations

 I3DXML.VisualizationRepType
root

Fields inherited from class igeo.io.I3DXML.RepresentationDocument

filename

Constructor Summary

I3DXML.XMLRepresentationDocument()

Method Summary

 java.util.ArrayList<IMesh>
instantiatePolygon(IMatrix4 transform)

 java.util.ArrayList<ICurve>
instantiatePolyline(IMatrix4 transform)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

root

public I3DXML.VisualizationRepType root

representations

public java.util.ArrayList<I3DXML.VisualizationRepType> representations

Constructor Detail

I3DXML.XMLRepresentationDocument

I3DXML.XMLRepresentationDocument()

Method Detail

instantiatePolygon

public java.util.ArrayList<IMesh> instantiatePolygon(IMatrix4 transform)

Overrides:
instantiatePolygon in class I3DXML.RepresentationDocument

instantiatePolyline

public java.util.ArrayList<ICurve> instantiatePolyline(IMatrix4 transform)

Overrides:
instantiatePolyline in class I3DXML.RepresentationDocument

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php namespace Fungku\NetSuite\Classes;

class ItemCostingMethod {
	static $paramtypesmap = array(
	);
	const _average = "_average";
	const _fifo = "_fifo";
	const _lifo = "_lifo";
	const _lotNumbered = "_lotNumbered";
	const _serialized = "_serialized";
	const _standard = "_standard";
}


text:
import sys
# In case we are run from the source directory, we don't want to import numpy
# from there, we want to import the installed version:
sys.path.pop(0)

from optparse import OptionParser
parser = OptionParser("usage: %prog [options] -- [nosetests options]")
parser.add_option("-v", "--verbose",
                  action="count", dest="verbose", default=1,
                  help="increase verbosity")
parser.add_option("--doctests",
                  action="store_true", dest="doctests", default=False,
                  help="Run doctests in module")
parser.add_option("--coverage",
                  action="store_true", dest="coverage", default=False,
                  help="report coverage of NumPy code (requires 'coverage' module")
parser.add_option("-m", "--mode",
                  action="store", dest="mode", default="fast",
                  help="'fast', 'full', or something that could be "
                       "passed to nosetests -A [default: %default]")
(options, args) = parser.parse_args()

import numpy
result = numpy.test(options.mode,
                    verbose=options.verbose,
                    extra_argv=args,
                    doctests=options.doctests,
                    coverage=options.coverage)

if result.wasSuccessful():
    sys.exit(0)
else:
    sys.exit(1)


text:
'use strict';

var fs = require('fs');
var path = require('path');
var JSON5 = require('json5');
var browsersync = require('browser-sync').create();

module.exports = function (cwd) {
    var dest = './_docs';
    var loadconfig = function loadconfig(cwd) {
        var confPath = path.join(cwd, 'tdoc.config.json'),
            conf;
        if (fs.existsSync(confPath)) {
            try {
                conf = JSON5.parse(fs.readFileSync(confPath, 'utf-8'));
            } catch (e) {}
            return conf;
        } else {
            return conf;
        }
    };
    var config = loadconfig(cwd);
    if (config && config.dest) {
        dest = config.dest;
    }
    browsersync.init({
        port: 8001,
        startPath: dest + '/index.html', //默认打开的初始地址,可以不加
        server: {
            baseDir: './',
            directory: true
        }
    });
};

module.exports.usage = '启动服务';


text:
/* An object representing a tracking run. Holds parameters but also
   intermediate results collected on each step of tracking. For use in
   tracking algorithms that need to communicate with sub-components such as
   single-step tracking routine driven by a loop.
*/

#ifndef TRACKING_RUN_H
#define TRACKING_RUN_H

#include <optv/parameters.h>
#include <optv/tracking_frame_buf.h>

typedef struct {
    framebuf *fb;
    sequence_par *seq_par;
    track_par *tpar;
    volume_par *vpar;
    control_par *cpar;

    /* Intermediate calculations done in run setup phase and used in the loop: */
    double ymin, ymax, lmax;
} tracking_run;

void tr_init(tracking_run *tr, char *seq_par_fname, char *tpar_fname,
    char *vpar_fname, char *cpar_fname);
void tr_free(tracking_run *tr);

#endif


text:
package org.imos.ddb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 * In memory representation of the IMOS deployment database using JDBC.
 * This class uses a generic JDBC driver and connection string so is
 * database agnostic, allowing the deployment database to be hosted on any
 * JDBC supported database platform.
 *
 * This class should never be instantiated directly; use the static method
 * org.imos.ddb.DDB.getDDB.
 *
 * @author Gordon Keith <gordon.keith@csiro.au>
 * @author Peter Jansen <peter.jansen@csiro.au> - generic database schema changes
 *
 * @see http://java.sun.com/javase/6/docs/technotes/guides/jdbc/bridge.html
 */
public class JDBCDDB extends DDB {

	String identQuote = "'";

	/**The JDBC database driver*/
	private String driver;
	private String connection;
	private String user;
	private String password;

	/**
	 * Create a JDBC DDB object using the specified JDBC driver and database connection.
	 *
	 * @param driver Class name of JDBC database driver
	 * @param connection Database connection string, must include user and password if required by the database.
	 * @throws ClassNotFoundException If the specified Database driver can't be found
	 * @throws SQLException If an attempt to open a connection to the database fails
	 */
	protected JDBCDDB(String driver, String connection, String user, String password) throws ClassNotFoundException, SQLException {
		this.driver = driver;
		this.connection = connection;
		this.user = user;
		this.password = password;

		// Test connection - throws exception at creation if can't connect
		Class.forName(driver);

		Connection conn = DriverManager.getConnection(connection, user, password);

		// get the database's IdentifierQuote
		DatabaseMetaData dbmd = conn.getMetaData();
		identQuote = dbmd.getIdentifierQuoteString();

		conn.close();
	}

	/**
	 * Executes the given query, in the form:
	 *
	 *   select * from [tableName] where [fieldName] = '[fieldValue]'
	 *
	 * The rows are converted into object equivalents of the table, and returned
	 * in a List. If fieldName is null, the where clause is omitted, thus the
	 * entire table is returned.
	 *
	 * @param tableName The table to read.
	 *
	 * @param fieldName the name of the query field.
	 *
	 * @param fieldValue the query field value.
	 *
	 * @throws Exception on any error.
	 */
	public ArrayList<Object> executeQuery(
			String tableName,
			String fieldName,
			Object fieldValue)
					throws Exception {

		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		ArrayList<Object> results = null;

		try {

			//create ODBC database connection
			Class.forName(driver);

			conn = DriverManager.getConnection(connection, user, password);

			results = new ArrayList<Object>();

			//build the query
			String query = "SELECT * FROM " + identQuote + tableName + identQuote;
			if (fieldName != null) {

				if (fieldValue == null)
					throw new Exception("a fieldValue must be provided");

				//wrap strings in quotes
				if (fieldValue instanceof String)
					query += " WHERE " + identQuote + fieldName + identQuote + " = '" + fieldValue + "'";
				else
					query += " WHERE " + identQuote + fieldName + identQuote + " = " + fieldValue;
			}

			//execute the query
			try {
				stmt = conn.createStatement();
				rs = stmt.executeQuery(query);
			}
			catch (Exception e) {

				System.out.println("JDBCDDB::Exception Caught " + e);

				//Hack to accommodate DeploymentId and FieldTripID
				//types of number or text. Don't tell anyone
				if (fieldName != null && fieldValue instanceof String) {

					query = "SELECT * FROM " + identQuote + tableName + identQuote +
							" WHERE " + identQuote + fieldName + identQuote + " = " + fieldValue;

					System.out.println("JDBCDDB::Query : " + query);

					stmt = conn.createStatement();
					rs = stmt.executeQuery(query);
				}
				else throw e;
			}

			ResultSetMetaData rsmd = rs.getMetaData();
			int columnsNumber = rsmd.getColumnCount();
			//create an object for each row
			while (rs.next()) {

				ArrayList<Object> instance = new ArrayList<Object>();
				results.add(instance);

				for (int i = 1; i <= columnsNumber; i++) {

					DBObject db = new DBObject();

					db.name = rsmd.getColumnName(i);
					db.o = rs.getObject(i);

					//all numeric values must be doubles
					if (db.o instanceof Integer) {
						db.o = (double)((Integer)db.o).intValue();
					}

					instance.add(db);
				}
			}
		}

		//always close db connection
		finally {
			try {
				rs.close();
				stmt.close();
				conn.close();
				}
			catch (Exception e) {}}

		return results;
	}
}


text:
if [[ $(uname -s) == 'Darwin' ]]; then
    source $(brew --prefix)/share/antigen/antigen.zsh
else
    if [[ ! -f ~/.antigen.zsh ]]; then
        echo "Downloading Antigen"
        curl -L git.io/antigen > ~/.antigen.zsh
    fi
    source  ~/.antigen.zsh
fi

antigen use oh-my-zsh

if [[ $(uname -s) == 'Darwin' ]]; then
    antigen bundle macos
fi

antigen bundle bundler
antigen bundle colorize
antigen bundle common-aliases
antigen bundle docker
antigen bundle encode64
antigen bundle fasd
antigen bundle gem
antigen bundle git
antigen bundle git-extras
antigen bundle git-flow
antigen bundle jsontools
antigen bundle urltools
antigen bundle zsh-users/zsh-autosuggestions
antigen bundle zsh-users/zsh-completions
antigen bundle Aloxaf/fzf-tab
antigen bundle Tarrasch/zsh-bd
antigen bundle wfxr/forgit
antigen theme romkatv/powerlevel10k
antigen apply


text:
package collector

import (
	"errors"
	"io/ioutil"
	"os"
	"regexp"
	"strconv"
	"strings"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/common/log"
)

var (
	netLineRE  = regexp.MustCompile(`^net \d+ (\d+) (\d+) (\d+)$`)
	rpcLineRE  = regexp.MustCompile(`^rpc (\d+) (\d+) (\d+)$`)
	procLineRE = regexp.MustCompile(`^proc(\d+) \d+ (\d+( \d+)*)$`)

	nfsProcedures = map[string][]string{
		"2": []string{
			"null", "getattr", "setattr", "root", "lookup",
			"readlink", "read", "writecache", "write", "create",
			"remove", "rename", "link", "symlink", "mkdir",
			"rmdir", "readdir", "statfs",
		},
		"3": []string{
			"null", "getattr", "setattr", "lookup", "access",
			"readlink", "read", "write", "create", "mkdir",
			"symlink", "mknod", "remove", "rmdir", "rename",
			"link", "readdir", "readdirplus", "fsstat", "fsinfo",
			"pathconf", "commit",
		},
		"4": []string{
			"null", "read", "write", "commit", "open",
			"open_confirm", "open_noattr", "open_downgrade",
			"close", "setattr", "fsinfo", "renew", "setclientid",
			"setclientid_confirm", "lock", "lockt", "locku",
			"access", "getattr", "lookup", "lookup_root", "remove",
			"rename", "link", "symlink", "create", "pathconf",
			"statfs", "readlink", "readdir", "server_caps",
			"delegreturn", "getacl", "setacl", "fs_locations",
			"release_lockowner", "secinfo", "fsid_present",
			"exchange_id", "create_session", "destroy_session",
			"sequence", "get_lease_time", "reclaim_complete",
			"layoutget", "getdeviceinfo", "layoutcommit",
			"layoutreturn", "secinfo_no_name", "test_stateid",
			"free_stateid", "getdevicelist",
			"bind_conn_to_session", "destroy_clientid", "seek",
			"allocate", "deallocate", "layoutstats", "clone",
			"copy",
		},
	}

	nfsNetReadsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "net_reads"),
		"Number of reads at the network layer.",
		[]string{"protocol"},
		nil,
	)
	nfsNetConnectionsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "net_connections"),
		"Number of connections at the network layer.",
		[]string{"protocol"},
		nil,
	)

	nfsRpcOperationsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "rpc_operations"),
		"Number of RPCs performed.",
		nil,
		nil,
	)
	nfsRpcRetransmissionsDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "rpc_retransmissions"),
		"Number of RPC transmissions performed.",
		nil,
		nil,
	)
	nfsRpcAuthenticationRefreshesDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "rpc_authentication_refreshes"),
		"Number of RPC authentication refreshes performed.",
		nil,
		nil,
	)

	nfsProceduresDesc = prometheus.NewDesc(
		prometheus.BuildFQName(Namespace, "nfs", "procedures"),
		"Number of NFS procedures invoked.",
		[]string{"version", "procedure"},
		nil,
	)
)

type nfsCollector struct{}

func init() {
	Factories["nfs"] = NewNfsCollector
}

func NewNfsCollector() (Collector, error) {
	return &nfsCollector{}, nil
}

func (c *nfsCollector) Update(ch chan<- prometheus.Metric) (err error) {
	statsFile := procFilePath("net/rpc/nfs")
	content, err := ioutil.ReadFile(statsFile)
	if err != nil {
		if os.IsNotExist(err) {
			log.Debugf("Not collecting NFS statistics, as %s does not exist: %s", statsFile)
			return nil
		}
		return err
	}

	for _, line := range strings.Split(string(content), "\n") {
		if fields := netLineRE.FindStringSubmatch(line); fields != nil {
			value, _ := strconv.ParseFloat(fields[1], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsNetReadsDesc, prometheus.CounterValue,
				value, "udp")

			value, _ = strconv.ParseFloat(fields[2], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsNetReadsDesc, prometheus.CounterValue,
				value, "tcp")

			value, _ = strconv.ParseFloat(fields[3], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsNetConnectionsDesc, prometheus.CounterValue,
				value, "tcp")
		} else if fields := rpcLineRE.FindStringSubmatch(line); fields != nil {
			value, _ := strconv.ParseFloat(fields[1], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsRpcOperationsDesc,
				prometheus.CounterValue, value)

			value, _ = strconv.ParseFloat(fields[2], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsRpcRetransmissionsDesc,
				prometheus.CounterValue, value)

			value, _ = strconv.ParseFloat(fields[3], 64)
			ch <- prometheus.MustNewConstMetric(
				nfsRpcAuthenticationRefreshesDesc,
				prometheus.CounterValue, value)
		} else if fields := procLineRE.FindStringSubmatch(line); fields != nil {
			version := fields[1]
			for procedure, count := range strings.Split(fields[2], " ") {
				value, _ := strconv.ParseFloat(count, 64)
				ch <- prometheus.MustNewConstMetric(
					nfsProceduresDesc,
					prometheus.CounterValue,
					value,
					version,
					nfsProcedures[version][procedure])
			}
		} else if line != "" {
			return errors.New("Failed to parse line: " + line)
		}
	}
	return nil
}


text:
"""Tools for manipulating of large commutative expressions. """

from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.basic import Basic
from sympy.core.sympify import sympify
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.coreerrors import NonCommutativeExpression

def decompose_power(expr):
    """
    Decompose power into symbolic base and integer exponent.

    Example
    =======

    >>> from sympy.core.exprtools import decompose_power
    >>> from sympy.abc import x, y

    >>> decompose_power(x)
    (x, 1)
    >>> decompose_power(x**2)
    (x, 2)
    >>> decompose_power(x**(2*y))
    (x**y, 2)
    >>> decompose_power(x**(2*y/3))
    (x**(y/3), 2)

    """
    base, exp = expr.as_base_exp()

    if exp.is_Number:
        if exp.is_Rational:
            if not exp.is_Integer:
                base = Pow(base, Rational(1, exp.q))

            exp = exp.p
        else:
            base, exp = expr, 1
    else:
        exp, tail = exp.as_coeff_mul()

        if exp.is_Rational:
            if not exp.is_Integer:
                tail += (Rational(1, exp.q),)

            base, exp = Pow(base, Mul(*tail)), exp.p
        else:
            base, exp = expr, 1

    return base, exp

class Factors(object):
    """Efficient representation of ``f_1*f_2*...*f_n``. """

    __slots__ = ['factors', 'gens']

    def __init__(self, factors=None):
        if factors is None:
            factors = {}

        self.factors = factors
        self.gens = frozenset(factors.keys())

    def __hash__(self):
        return hash((tuple(self.factors), self.gens))

    def __repr__(self):
        return "Factors(%s)" % self.factors

    def as_expr(self):
        return Mul(*[ factor**exp for factor, exp in self.factors.iteritems() ])

    def normal(self, other):
        self_factors = dict(self.factors)
        other_factors = dict(other.factors)

        for factor, self_exp in self.factors.iteritems():
            try:
                other_exp = other.factors[factor]
            except KeyError:
                continue

            exp = self_exp - other_exp

            if not exp:
                del self_factors[factor]
                del other_factors[factor]
            else:
                if exp > 0:
                    self_factors[factor] = exp
                    del other_factors[factor]
                else:
                    del self_factors[factor]
                    other_factors[factor] = -exp

        return Factors(self_factors), Factors(other_factors)

    def mul(self, other):
        factors = dict(self.factors)

        for factor, exp in other.factors.iteritems():
            if factor in factors:
                exp = factors[factor] + exp

                if not exp:
                    del factors[factor]
                    continue

            factors[factor] = exp

        return Factors(factors)

    def div(self, other):
        quo, rem = dict(self.factors), {}

        for factor, exp in other.factors.iteritems():
            if factor in quo:
                exp = quo[factor] - exp

                if exp <= 0:
                    del quo[factor]

                if exp >= 0:
                    if exp:
                        quo[factor] = exp

                    continue

                exp = -exp

            rem[factor] = exp

        return Factors(quo), Factors(rem)

    def quo(self, other):
        return self.div(other)[0]

    def rem(self, other):
        return self.div(other)[1]

    def pow(self, other):
        if type(other) is int and other >= 0:
            factors = {}

            if other:
                for factor, exp in self.factors.iteritems():
                    factors[factor] = exp*other

            return Factors(factors)
        else:
            raise ValueError("expected non-negative integer, got %s" % other)

    def gcd(self, other):
        factors = {}

        for factor, exp in self.factors.iteritems():
            if factor in other.factors:
                exp = min(exp, other.factors[factor])
                factors[factor] = exp

        return Factors(factors)

    def lcm(self, other):
        factors = dict(self.factors)

        for factor, exp in other.factors.iteritems():
            if factor in factors:
                exp = max(exp, factors[factor])

            factors[factor] = exp

        return Factors(factors)

    def __mul__(self, other):
        if isinstance(other, Factors):
            return self.mul(other)
        else:
            return NotImplemented

    def __divmod__(self, other):
        if isinstance(other, Factors):
            return self.div(other)
        else:
            return NotImplemented

    def __div__(self, other):
        if isinstance(other, Factors):
            return self.quo(other)
        else:
            return NotImplemented

    __truediv__ = __div__

    def __mod__(self, other):
        if isinstance(other, Factors):
            return self.rem(other)
        else:
            return NotImplemented

    def __pow__(self, other):
        if type(other) is int:
            return self.pow(other)
        else:
            return NotImplemented

    def __eq__(self, other):
        return self.factors == other.factors

    def __ne__(self, other):
        return not self.__eq__(other)

class Term(object):
    """Efficient representation of ``coeff*(numer/denom)``. """

    __slots__ = ['coeff', 'numer', 'denom']

    def __init__(self, term, numer=None, denom=None):
        if numer is None and denom is None:
            if not term.is_commutative:
                raise NonCommutativeExpression('commutative expression expected')

            coeff, factors = term.as_coeff_mul()
            numer, denom = {}, {}

            for factor in factors:
                base, exp = decompose_power(factor)

                if base.is_Add:
                    cont, base = base.primitive()
                    coeff *= cont**exp

                if exp > 0:
                    numer[base] = exp
                else:
                    denom[base] = -exp

            numer = Factors(numer)
            denom = Factors(denom)
        else:
            coeff = term

            if numer is None:
                numer = Factors()

            if denom is None:
                denom = Factors()

        self.coeff = coeff
        self.numer = numer
        self.denom = denom

    def __hash__(self):
        return hash((self.coeff, self.numer, self.denom))

    def __repr__(self):
        return "Term(%s, %s, %s)" % (self.coeff, self.numer, self.denom)

    def as_expr(self):
        return self.coeff*(self.numer.as_expr()/self.denom.as_expr())

    def mul(self, other):
        coeff = self.coeff*other.coeff
        numer = self.numer.mul(other.numer)
        denom = self.denom.mul(other.denom)

        numer, denom = numer.normal(denom)

        return Term(coeff, numer, denom)

    def inv(self):
        return Term(1/self.coeff, self.denom, self.numer)

    def quo(self, other):
        return self.mul(other.inv())

    def pow(self, other):
        if other < 0:
            return self.inv().pow(-other)
        else:
            return Term(self.coeff **  other,
                        self.numer.pow(other),
                        self.denom.pow(other))

    def gcd(self, other):
        return Term(self.coeff.gcd(other.coeff),
                    self.numer.gcd(other.numer),
                    self.denom.gcd(other.denom))

    def lcm(self, other):
        return Term(self.coeff.lcm(other.coeff),
                    self.numer.lcm(other.numer),
                    self.denom.lcm(other.denom))

    def __mul__(self, other):
        if isinstance(other, Term):
            return self.mul(other)
        else:
            return NotImplemented

    def __div__(self, other):
        if isinstance(other, Term):
            return self.quo(other)
        else:
            return NotImplemented

    __truediv__ = __div__

    def __pow__(self, other):
        if type(other) is int:
            return self.pow(other)
        else:
            return NotImplemented

    def __eq__(self, other):
        return (self.coeff == other.coeff and
                self.numer == other.numer and
                self.denom == other.denom)

    def __ne__(self, other):
        return not self.__eq__(other)

def _gcd_terms(terms):
    """Helper function for :func:`gcd_terms`. """
    if isinstance(terms, Basic):
        terms = Add.make_args(terms)

    if len(terms) <= 1:
        if not terms:
            return S.Zero, S.Zero, S.One
        else:
            return terms[0], S.One, S.One

    terms = map(Term, terms)
    cont = terms[0]

    for term in terms[1:]:
        cont = cont.gcd(term)

    for i, term in enumerate(terms):
        terms[i] = term.quo(cont)

    denom = terms[0].denom

    for term in terms[1:]:
        denom = denom.lcm(term.denom)

    numers = []

    for term in terms:
        numer = term.numer.mul(denom.quo(term.denom))
        numers.append(term.coeff*numer.as_expr())

    cont = cont.as_expr()
    numer = Add(*numers)
    denom = denom.as_expr()

    if numer.is_Add:
        _cont, numer = numer.primitive()
        cont *= _cont

    return cont, numer, denom

def gcd_terms(terms):
    """
    Compute the GCD of ``terms`` and put them together.

    Example
    =======

    >>> from sympy.core import gcd_terms
    >>> from sympy.abc import x, y

    >>> gcd_terms((x + 1)**2*y + (x + 1)*y**2)
    y*(x + 1)*(x + y + 1)

    """
    from sympy.polys.polytools import _keep_coeff

    cont, numer, denom = _gcd_terms(sympify(terms))
    coeff, factors = cont.as_coeff_Mul()
    return _keep_coeff(coeff, factors*numer/denom)


text:
title: Markdown or LaTeX?
date: '2013-10-19'
slug: markdown-or-latex
---

> What happens if you ask for too much power from Markdown?

> ![Duck bites](https://db.yihui.org/imgur/vGwGF7s.gif)

R Markdown is one of the document formats that **knitr** supports, and it is
probably the most popular one. I have been asked many times about the choice
between Markdown and LaTeX, so I think I'd better wrap up my opinions in a
blog post. These two languages (do you really call Markdown a _language_?)
are kind of at the two extremes: Markdown is super easy to learn and type,
but it is primarily targeted at HTML pages, and you do not have fine control
over typesetting (
[really?](http://cran.r-project.org/web/packages/knitr/vignettes/docco-classic.html)
[really?](http://cran.r-project.org/web/packages/knitr/vignettes/docco-linear.html)),
because you only have a very limited number of HTML tags in the output;
LaTeX is relatively difficult to learn and type, but it allows you to do
precise typesetting (you have control over anything, and that is probably
why a lot of time can be wasted).

## What is the problem?

What is the root problem? I think one word answers everything: **page**! Why
do we need pages? **Printing** is the answer.

In my eyes, the biggest challenge for typesetting is to arrange elements
properly with the restriction of pages. This restriction seems trivial, but
it is really the root of all "evil". Without having to put things on pages,
life can be much easier in writing.

What is the root of this root problem in LaTeX? One concept: _floating
environments_. If everything comes in a strictly linear fashion, writing
will be just writing; typesetting should be no big deal. Because a graph
cannot be broken over two pages, it is hard to find a place to put it. By
default, it can float to unexpected places. The same problem can happen to
tables (see the end of [a previous post](/en/2012/10/lyx-vs-latex/)). You
may have to add or delete some words to make sure they float to proper
places. That is endless trouble in LaTeX.

There is no such a problem in HTML/Markdown, because there is no page. You
just keep writing, and everything appears linearly.

## Can I have both HTML and PDF output?

There is no fault being greedy, and it is natural to ask the question
whether one can have both HTML and PDF output from a single source document.
The answer is maybe yes: you can go from LaTeX to HTML, or from Markdown to
LaTeX/PDF.

- [pandoc](http://johnmacfarlane.net/pandoc/) can convert Markdown to almost anything
- [many tools](http://enc.com.au/docs/latexhtml/) to convert LaTeX to HTML

But remember, Markdown was designed for HTML, and LaTeX was for PDF and
related output formats. If you ask for more power from either language, the
result is not likely be ideal, otherwise one of them must die.

## How to make the decision?

If your writing does not involve complicated typesetting and primarily
consists of text (especially no floating environments), go with Markdown. I
cannot think of a reason why you must use LaTeX to write a novel. See
Hadley's new book [Advanced R programming](http://adv-r.had.co.nz) for an
excellent example of Markdown + **knitr** + other tools: the typesetting
elements in this book are very simple -- section headers, paragraphs, and
code/output. That is pretty much it. Eventually it should be relatively easy
to convert those Markdown files to LaTeX via Pandoc, and publish a PDF using
the LaTeX class from Chapman & Hall.

For the rest of you, what I'd recommend is to think early and make a
decision in the beginning; avoid having both HTML and PDF in mind. Ask
yourself only one question: must I print the results nicely on paper? If the
answer is yes, go with LaTeX; otherwise just choose whatever makes you
comfortable. The book [Text Analysis with
R](http://www.matthewjockers.net/2013/09/03/tawr/) authored by [Matthew
Jockers](http://www.matthewjockers.net/) is an example of LaTeX + **knitr**.
Matt also asked me this question about Markdown vs LaTeX last week while he
was here at Iowa State. For this particular book, I think Markdown is
probably OK, although I'm not quite sure about a few environments in the
book, such as the chapter abstracts.

It is not obvious whether we must print certain things. I think we are just
too used to printing. For example, dear professors, must we print our
homework? (apparently [Jenny](http://www.stat.ubc.ca/~jenny/STAT545A/) does
not think so; I saw her grade homework on [RPubs.com](http://rpubs.com)!) Or
dear customers, must we submit reports in PDF? ... In this era, you have
laptops, iPad, Kindle, tablets and all kinds of electronic devices that can
show rich media, why must you print everything (in black and white)?

For those who are still reading this post, let me finish with a side story:
Matt, a LaTeX novice, taught himself LaTeX a few months ago, and he has
finished the draft of a book with LaTeX! Why are you still hesitating about
the choice of tools? Shouldn't you just go ahead and get the * done?
Although all roads lead to Rome, some people die at the starting line
instead of on the roads.


text:
let path = require('path');

let themePath = '../themes/';

let config = {
  themePath: path.resolve(__dirname, themePath),
  defaultTheme: path.resolve(__dirname, themePath, 'default/index.html')
};

/**
 * This module contains some magic strings and other
 * configuration values
 */
module.exports = config;


text:
<?php

namespace SphinxSearchTest\Db\Sql;

use SphinxSearch\Db\Sql\Predicate\Match;
use SphinxSearch\Query\QueryExpression;

/**
 * Class MatchTest
 */
class MatchTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Match
     */
    protected $match;

    /**
     * @testdox Constructor
     */
    public function test__constuctor()
    {
        // Assume that '?' is the placeholder
        $match = new Match('?', ['param']);

        $queryExpression = $match->getQuery();
        $this->assertInstanceOf('\SphinxSearch\Query\QueryExpression', $queryExpression);

        $this->assertEquals(['param'], $queryExpression->getParameters());
        $this->assertEquals('?', $queryExpression->getExpression());

        $queryExpression = new QueryExpression();
        $match = new Match($queryExpression);
        $this->assertSame($queryExpression, $match->getQuery());

        // Test invalid argument
        $this->setExpectedException('\SphinxSearch\Db\Sql\Exception\InvalidArgumentException');
        new Match(new \stdClass());

    }

    /**
     * @testdox Setter and getter query
     */
    public function testSetGetQuery()
    {
        $match = new Match();

        $queryExpression = new QueryExpression('test');

        $this->assertInstanceOf('\SphinxSearch\Db\Sql\Predicate\Match', $match->setQuery($queryExpression));
        $this->assertSame($queryExpression, $match->getQuery());

        $this->assertEquals(
            [
                ['MATCH(%1$s)', ['test'], [Match::TYPE_VALUE]]
            ],
            $match->getExpressionData()
        );
    }

    /**
     * @testdox Setter and getter specificaton
     */
    public function testSetGetSpecification()
    {
        $match = new Match();

        // Test default specification
        $this->assertEquals('MATCH(%1$s)', $match->getSpecification());

        $this->assertInstanceOf('\SphinxSearch\Db\Sql\Predicate\Match', $match->setSpecification('TEST_SPECIFICATION'));
        $this->assertEquals('TEST_SPECIFICATION', $match->getSpecification());

        $this->assertEquals(
            [
                ['TEST_SPECIFICATION', [''], [Match::TYPE_VALUE]]
            ],
            $match->getExpressionData()
        );
    }

    /**
     * @testdox Get expression data
     */
    public function testGetExpressionData()
    {
        $match = new Match('foo');
        $this->assertEquals(
            [[$match->getSpecification(), ['foo'], [Match::TYPE_VALUE]]],
            $match->getExpressionData()
        );
    }

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp()
    {
        $this->match = new Match();
    }
}


text:
namespace CGAL {

namespace VoronoiDiagram_2 { namespace Internal {

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

struct Rejector_base
{
  inline void clear() {}
  inline void swap(Rejector_base&) {}
  inline bool is_valid() const { return true; }
};

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

template<class DG>
struct Identity_edge_rejector
  : public Rejector_base
{
  typedef DG                  Delaunay_graph;
  typedef bool                result_type;

  typedef typename Delaunay_graph::Edge                   Edge;
  typedef typename Delaunay_graph::Face_handle            Face_handle;
  typedef typename Delaunay_graph::Edge_circulator        Edge_circulator;
  typedef typename Delaunay_graph::All_edges_iterator     All_edges_iterator;
  typedef typename Delaunay_graph::Finite_edges_iterator  Finite_edges_iterator;

  bool operator()(const Delaunay_graph& ,
		  const Face_handle& , int ) const {
    return false;
  }

  bool operator()(const Delaunay_graph& , const Edge& ) const {
    return false;
  }

  bool operator()(const Delaunay_graph& ,
		  const All_edges_iterator& ) const {
    return false;
  }

  bool operator()(const Delaunay_graph& ,
		  const Finite_edges_iterator& ) const {
    return false;
  }

  bool operator()(const Delaunay_graph& ,
		  const Edge_circulator& ) const {
    return false;
  }
};

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

template<class DG>
struct Identity_face_rejector
  : public Rejector_base
{
  typedef DG                  Delaunay_graph;
  typedef bool                result_type;

  typedef typename Delaunay_graph::Vertex_handle  Vertex_handle;

  bool operator()(const Delaunay_graph&, const Vertex_handle&) const {
    return false;
  }
};

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

} } //namespace VoronoiDiagram_2::Internal

} //namespace CGAL

#endif // CGAL_VORONOI_DIAGRAM_2_IDENTITY_REJECTORS_H


text:
require 'spec_helper'

describe Roo::LibreOffice do
  describe '.new' do
    subject {
      Roo::LibreOffice.new('test/files/numbers1.ods')
    }

    it 'creates an instance' do
      expect(subject).to be_a(Roo::LibreOffice)
    end
  end
end

describe Roo::Libreoffice do
  it 'is an alias of LibreOffice' do
    expect(Roo::Libreoffice).to eq(Roo::LibreOffice)
  end
end


text:
package network::extreme::snmp::mode::memory;

use base qw(centreon::plugins::templates::counter);

use strict;
use warnings;

sub custom_usage_perfdata {
    my ($self, %options) = @_;

    $self->{output}->perfdata_add(
        label => 'used', unit => 'B',
        instances => $self->use_instances(extra_instance => $options{extra_instance}) ? $self->{result_values}->{display} : undef,
        value => $self->{result_values}->{used},
        warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $self->{thlabel}, total => $self->{result_values}->{total}, cast_int => 1),
        critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $self->{thlabel}, total => $self->{result_values}->{total}, cast_int => 1),
        min => 0, max => $self->{result_values}->{total}
    );
}

sub custom_usage_threshold {
    my ($self, %options) = @_;

    my $exit = $self->{perfdata}->threshold_check(value => $self->{result_values}->{prct_used}, threshold => [ { label => 'critical-' . $self->{thlabel}, exit_litteral => 'critical' }, { label => 'warning-' . $self->{thlabel}, exit_litteral => 'warning' } ]);
    return $exit;
}

sub custom_usage_output {
    my ($self, %options) = @_;

    my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{total});
    my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{used});
    my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => $self->{result_values}->{free});

    my $msg = sprintf("Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)",
                      $total_size_value . " " . $total_size_unit,
                      $total_used_value . " " . $total_used_unit, $self->{result_values}->{prct_used},
                      $total_free_value . " " . $total_free_unit, $self->{result_values}->{prct_free});
    return $msg;
}

sub custom_usage_calc {
    my ($self, %options) = @_;

    $self->{result_values}->{display} = $options{new_datas}->{$self->{instance} . '_display'};
    $self->{result_values}->{total} = $options{new_datas}->{$self->{instance} . '_total'};
    $self->{result_values}->{used} = $options{new_datas}->{$self->{instance} . '_total'} - $options{new_datas}->{$self->{instance} . '_free'};
    $self->{result_values}->{free} = $options{new_datas}->{$self->{instance} . '_free'};
    $self->{result_values}->{prct_free} = $self->{result_values}->{free} * 100 / $self->{result_values}->{total};
    $self->{result_values}->{prct_used} = $self->{result_values}->{used} * 100 / $self->{result_values}->{total};
    return 0;
}

sub set_counters {
    my ($self, %options) = @_;

    $self->{maps_counters_type} = [
        { name => 'memory', type => 1, cb_prefix_output => 'prefix_memory_output', message_multiple => 'All memory usages are ok' }
    ];

    $self->{maps_counters}->{memory} = [
        { label => 'usage', set => {
                key_values => [ { name => 'display' }, { name => 'free' }, { name => 'total' } ],
                closure_custom_calc => $self->can('custom_usage_calc'),
                closure_custom_output => $self->can('custom_usage_output'),
                closure_custom_perfdata => $self->can('custom_usage_perfdata'),
                closure_custom_threshold_check => $self->can('custom_usage_threshold'),
            }
        },
    ];
}

sub prefix_memory_output {
    my ($self, %options) = @_;

    return "Memory '" . $options{instance_value}->{display} . "' ";
}

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $options{options}->add_options(arguments => {
    });

    return $self;
}

my $mapping = {
    extremeMemoryMonitorSystemFree      => { oid => '.1.3.6.1.4.1.1916.1.32.2.2.1.3' },
    extremeMemoryMonitorSystemTotal     => { oid => '.1.3.6.1.4.1.1916.1.32.2.2.1.2' },
};

sub manage_selection {
    my ($self, %options) = @_;

    $self->{memory} = {};
    my $oid_extremeMemoryMonitorSystemEntry = '.1.3.6.1.4.1.1916.1.32.2.2.1';
    my $snmp_result = $options{snmp}->get_table(
        oid => $oid_extremeMemoryMonitorSystemEntry,
        nothing_quit => 1
    );
    foreach my $oid (keys %$snmp_result) {
        next if ($oid !~ /^$mapping->{extremeMemoryMonitorSystemFree}->{oid}\.(\d+)/);
        my $instance = $1;
        my $result = $options{snmp}->map_instance(mapping => $mapping, results => $snmp_result, instance => $instance);

        $self->{memory}->{$instance} = {
            display => $instance,
            free => $result->{extremeMemoryMonitorSystemFree} * 1024,
            total =>  $result->{extremeMemoryMonitorSystemTotal} * 1024
        };
    }
}

1;

__END__

=head1 MODE

Check memory usages.

=over 8

=item B<--warning-usage>

Threshold warning (in percent).

=item B<--critical-usage>

Threshold critical (in percent).

=back

=cut


text:
#ifndef _H_BUF_BLOCK_H_
#define _H_BUF_BLOCK_H_

#ifdef __cplusplus
extern "C" {
#endif

#include <string.h>
#include <assert.h>
#include "platform_config.h"
#include "buf/buf_info.h"

#ifndef min
#define min(a, b)	(((a) < (b)) ? (a) : (b))
#endif

/* block buffer */
struct block {
	int read;
	volatile int write;
	int process_pos;		/* process pos. */
	int maxsize;
	struct block *next;
	char buf[0];
};

static inline void block_init(struct block *self, int size) {
	assert(self != NULL);
	assert(size > (int)sizeof(struct block));
	self->read = 0;
	self->write = 0;
	self->process_pos = 0;
	self->maxsize = size - (int)sizeof(struct block);
	self->next = NULL;
}

/*
 * ================================================================================
 * reader interface.
 * ================================================================================
 */
static inline struct buf_info block_get_do_process(struct block *self) {
	struct buf_info pinfo;

	assert(self != NULL);
	assert(self->maxsize >= self->write);
	assert(self->write >= self->read);
	assert(self->write >= self->process_pos);

	pinfo.buf = NULL;
	pinfo.len = 0;
	if (self->write > self->process_pos) {
		pinfo.len = self->write - self->process_pos;
		pinfo.buf = &self->buf[self->process_pos];
		assert(pinfo.len > 0);
		assert(self->write >= pinfo.len);

		self->process_pos += pinfo.len;
		assert(self->write >= self->process_pos);
		assert(self->maxsize >= self->process_pos);
	}
	return pinfo;
}

static inline bool block_is_read_over(struct block *self) {
	assert(self != NULL);
	assert(self->maxsize > 0);
	return (self->read == self->maxsize);
}

static inline bool block_is_write_over(struct block *self) {
	assert(self != NULL);
	assert(self->maxsize > 0);
	return (self->write == self->maxsize);
}

static inline int block_get_readsize(struct block *self) {
	assert(self != NULL);
	assert(self->write >= self->read);
	return (self->write - self->read);
}

static inline char *block_get_readbuf(struct block *self) {
	assert(self != NULL);
	assert(self->write >= self->read);
	assert(self->maxsize > self->read);
	return &self->buf[self->read];
}

static inline void block_add_read(struct block *self, int len) {
	assert(self != NULL);
	assert(len >= 0);
	assert(self->write >= (self->read + len));
	self->read += len;
}

static inline int block_get(struct block *self, void *data, int len) {
	int readsize;
	assert(self != NULL);
	assert(self->write >= self->read);
	assert(data != NULL);
	assert(len != 0);
	readsize = min(block_get_readsize(self), len);
	memcpy(data, &self->buf[self->read], readsize);
	self->read += readsize;
	assert(self->read <= self->write);
	return readsize;
}

/*
 * ================================================================================
 * writer interface.
 * ================================================================================
 */
static inline int block_get_writesize(struct block *self) {
	assert(self != NULL);
	assert(self->maxsize >= self->write);
	return (self->maxsize - self->write);
}

static inline char *block_get_writebuf(struct block *self) {
	assert(self != NULL);
	assert(self->maxsize > self->write);
	return &self->buf[self->write];
}

static inline void block_add_write(struct block *self, int len) {
	assert(self != NULL);
	assert(len >= 0);
	assert(self->maxsize >= (self->write + len));
	self->write += len;
}

static inline int block_put(struct block *self, void *data, int len) {
	int writesize;
	assert(self != NULL);
	assert(self->maxsize > self->write);
	assert(data != NULL);
	assert(len != 0);
	writesize = min(block_get_writesize(self), len);
	memcpy(&self->buf[self->write], data, writesize);
	self->write += writesize;
	assert(self->write <= self->maxsize);
	return writesize;
}

#ifdef __cplusplus
}
#endif
#endif


text:
require 'seaside/seaside_spec_helper'

module Seaside
  module Pages
    class OralHistPage < BasePage
      include Capybara::DSL
      include CapybaraErrorIntel::DSL

      def on_page?
        super &&
          has_videos? &&
          has_video_titles? &&
          on_valid_url?
      end

      def on_valid_url?
        current_url == File.join(Capybara.app_host, 'essays/oral-histories') || File.join(Capybara.app_host, "essays/oral-histories#")
      end

      def has_videos?
        within('.article') do
          all('iframe.player', count: 9).each(&:visible?)
        end
      end

      def has_video_titles?
        within('.article') do
          all('hgroup.movie-title', count: 9).each(&:visible?)
        end
      end
    end
  end
end


text:
package org.apache.hadoop.fs.local;

import java.io.IOException;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.fs.FsServerDefaults;
import org.apache.hadoop.util.DataChecksum;

/**
 * This class contains constants for configuration keys used
 * in the local file system, raw local fs and checksum fs.
 *
 * Note that the settings for unimplemented features are ignored.
 * E.g. checksum related settings are just place holders. Even when
 * wrapped with {@link ChecksumFileSystem}, these settings are not
 * used.
 */

@InterfaceAudience.Private
@InterfaceStability.Unstable
public class LocalConfigKeys extends CommonConfigurationKeys {
  public static final String BLOCK_SIZE_KEY = "file.blocksize";
  public static final long BLOCK_SIZE_DEFAULT = 64*1024*1024;
  public static final String  REPLICATION_KEY = "file.replication";
  public static final short REPLICATION_DEFAULT = 1;
  public static final String STREAM_BUFFER_SIZE_KEY = "file.stream-buffer-size";
  public static final int STREAM_BUFFER_SIZE_DEFAULT = 4096;
  public static final String BYTES_PER_CHECKSUM_KEY = "file.bytes-per-checksum";
  public static final int BYTES_PER_CHECKSUM_DEFAULT = 512;
  public static final String CLIENT_WRITE_PACKET_SIZE_KEY =
                                                "file.client-write-packet-size";
  public static final int CLIENT_WRITE_PACKET_SIZE_DEFAULT = 64*1024;
  public static final boolean ENCRYPT_DATA_TRANSFER_DEFAULT = false;
  public static final long FS_TRASH_INTERVAL_DEFAULT = 0;
  public static final DataChecksum.Type CHECKSUM_TYPE_DEFAULT =
      DataChecksum.Type.CRC32;
  public static final String KEY_PROVIDER_URI_DEFAULT = "";
  private static final boolean QUOTA_ENABLED = true;

  public static FsServerDefaults getServerDefaults() throws IOException {
    return new FsServerDefaults(
        BLOCK_SIZE_DEFAULT,
        BYTES_PER_CHECKSUM_DEFAULT,
        CLIENT_WRITE_PACKET_SIZE_DEFAULT,
        REPLICATION_DEFAULT,
        STREAM_BUFFER_SIZE_DEFAULT,
        ENCRYPT_DATA_TRANSFER_DEFAULT,
        FS_TRASH_INTERVAL_DEFAULT,
        CHECKSUM_TYPE_DEFAULT,
        KEY_PROVIDER_URI_DEFAULT,
        QUOTA_ENABLED);
  }
}


text:
var util        = require('util')
  , devices     = require('./../../core/device')
  , steward     = require('./../../core/steward')
  , utility     = require('./../../core/utility')
  , climate     = require('./../device-climate')
  , sensor      = require('./../device-sensor')
  ;

// var logger = climate.logger;

var Sensor = exports.Device = function(deviceID, deviceUID, info) {
  var self = this;

  self.whatami = info.deviceType;
  self.deviceID = deviceID.toString();
  self.deviceUID = deviceUID;
  self.name = info.device.name;
  self.getName();

  self.status = self.initInfo(info.params);
  sensor.update(self.deviceID, info.params);
  self.changed();

  utility.broker.subscribe('actors', function(request, taskID, actor, perform, parameter) {
    if (actor !== ('device/' + self.deviceID)) return;

    if (request === 'perform') return devices.perform(self, taskID, perform, parameter);
  });
};
util.inherits(Sensor, climate.Device);
Sensor.prototype.perform = devices.perform;

Sensor.prototype.update = function(self, params, status) {
  var updateP = false;

  if ((!!status) && (status !== self.status)) {
    self.status = status;
    updateP = true;
  }
  if (self.updateInfo(params)) updateP = true;

  if (updateP) {
    self.changed();
    sensor.update(self.deviceID, params);
  }
};

exports.start = function() {
  steward.actors.device.climate['oregon-scientific'] = steward.actors.device.climate['oregon-scientific'] ||
      { $info     : { type: '/device/climate/oregon-scientific' } };

  steward.actors.device.climate['oregon-scientific'].meteo =
      { $info     : { type       : '/device/climate/oregon-scientific/meteo'
                    , observe    : [ ]
                    , perform    : [ ]
                    , properties : { name          : true
                                   , status        : [ 'present' ]
                                   , lastSample    : 'timestamp'
                                   , temperature   : 'celsius'
                                   , humidity      : 'percentage'
                                   , batteryLevel  : 'percentage'
                                   , rssi          : 's8'
                                   }
                    }
      , $validate : { perform    : devices.validate_perform
                    }
      };
  steward.actors.device.climate['oregon-scientific'].rain =
      { $info     : { type       : '/device/climate/oregon-scientific/rain'
                    , observe    : [ ]
                    , perform    : [ ]
                    , properties : { name          : true
                                   , status        : [ 'present' ]
                                   , lastSample    : 'timestamp'
                                   , rainRate      : 'mm/h'
                                   , rainTotal     : 'mm'
                                   }
                    }
      , $validate : { perform    : devices.validate_perform
                    }
      };
  steward.actors.device.climate['oregon-scientific'].wind =
      { $info     : { type       : '/device/climate/oregon-scientific/wind'
                    , observe    : [ ]
                    , perform    : [ ]
                    , properties : { name          : true
                                   , status        : [ 'present' ]
                                   , lastSample    : 'timestamp'
                                   , windAverage   : 'm/s'
                                   , windGust      : 'm/s'
                                   , windDirection : 'degrees'
                                   }
                    }
      , $validate : { perform    : devices.validate_perform
                    }
      };
  devices.makers['/device/climate/oregon-scientific/meteo'] = Sensor;
  devices.makers['/device/climate/oregon-scientific/rain'] = Sensor;
  devices.makers['/device/climate/oregon-scientific/wind'] = Sensor;
};


text:
function solve(args) {
    let width = +args[0],
    height = +args[1],
    area = width * height,
    perimeter = 2*(width+height);

    console.log(`${area} ${perimeter}`);
}

// old es

function solve2(args) {
    var width = +args[0],
    height = +args[1],
    area = width * height,
    perimeter = 2*(width+height);

    console.log(area.toFixed(2) + ' ' + perimeter.toFixed(2));
}


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-03-15"
---

<!-- Common attributes used in the template are defined as follows: -->
{:new_window: target="\_blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Stato del servizio
{: #service_status}

Il dashboard [IBM Watson IoT Service Health ![icona link esterno](../../icons/launch-glyph.svg)](https://status.internetofthings.ibmcloud.com){: new_window} fornisce le informazioni sullo stato corrente di {{site.data.keyword.iot_full}} e di altri servizi Watson IoT in {{site.data.keyword.Bluemix_notm}}.
{:shortdesc}

## Aggiornamenti e disponibilità del servizio
{: #service_up}
Per scoprire lo stato di tutti i prossimi aggiornamenti di manutenzione del servizio pianificati per le API del servizio {{site.data.keyword.iotelectronics}} in {{site.data.keyword.Bluemix_notm}}, vai alla seguente pagina dello stato del servizio e fai clic su **Soluzioni**.

http://status.internetofthings.ibmcloud.com/

## Novità su Twitter
{: #twitter_feed}

![Feed Twitter https://twitter.com/ibmiotf](images/twitter_logo.png "Feed Twitter di IBM Watson IoT Platform")

Puoi anche ottenere le ultime novità e aggiornamenti su {{site.data.keyword.iot_short_notm}} e sui servizi associati seguendo il nostro [feed Twitter](https://twitter.com/ibmiotf).


text:
#include <aws/cloudfront/model/GeoRestrictionType.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace CloudFront
  {
    namespace Model
    {
      namespace GeoRestrictionTypeMapper
      {

        static const int blacklist_HASH = HashingUtils::HashString("blacklist");
        static const int whitelist_HASH = HashingUtils::HashString("whitelist");
        static const int none_HASH = HashingUtils::HashString("none");

        GeoRestrictionType GetGeoRestrictionTypeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == blacklist_HASH)
          {
            return GeoRestrictionType::blacklist;
          }
          else if (hashCode == whitelist_HASH)
          {
            return GeoRestrictionType::whitelist;
          }
          else if (hashCode == none_HASH)
          {
            return GeoRestrictionType::none;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<GeoRestrictionType>(hashCode);
          }

          return GeoRestrictionType::NOT_SET;
        }

        Aws::String GetNameForGeoRestrictionType(GeoRestrictionType enumValue)
        {
          switch(enumValue)
          {
          case GeoRestrictionType::blacklist:
            return "blacklist";
          case GeoRestrictionType::whitelist:
            return "whitelist";
          case GeoRestrictionType::none:
            return "none";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return "";
          }
        }

      } // namespace GeoRestrictionTypeMapper
    } // namespace Model
  } // namespace CloudFront
} // namespace Aws


text:
'use strict';

/**
 * Repair instances of native constructors.
 *
 * @param {Mixed} src Object or array source.
 * @returns {Mixed} Repaired source.
 * @api public
 */
var repair = module.exports = function repair(src) {
  var t = repair.type(src);

  if (src && src.iterator || 'object' === t || 'array' === t) {
    Object.keys(src).forEach(function (key) {
      src[key] = repair(src[key]);
    });
  }

  return t in repair ? repair[t](src) : src;
};

/**
 * Extended version of typeof check.
 *
 * @param {Mixed} value Instance of constructor.
 * @returns {String} typeof instance.
 * @api private
 */
repair.type = function type(value) {
  return {}.toString.call(value).match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};

/**
 * Repair RegExp.
 *
 * @param {RegExp} value
 * @returns {RegExp}
 * @api private
 */
repair.regexp = function regexp(value) {
  if (value instanceof RegExp) return value;

  value = value.toString().split('/');
  return new RegExp(value[1], value.pop());
};

/**
 * Repair Date.
 *
 * @param {Date} value
 * @returns {Date}
 * @api private
 */
repair.date = function date(value) {
  return value instanceof Date ? value : new Date(value.toString());
};


text:
function [circlespace,meshX,meshY] = make_circlespace(r)

global window screenRect white black grey xc yc meshX meshY circlespace correct incorrect wrong_key  stim_pixels visual_angle_in_degrees dist_to_screen_cm

% Obtain screen size and pixel info
[screen_size_mm(1), screen_size_mm(2)] = Screen('DisplaySize', 0);
screen_width_cm = screen_size_mm(1)/10;
screen_height_cm = screen_size_mm(2)/10;
[screen_width_pixels,screen_height_pixels] = Screen('WindowSize', 0);
screen_pixel_density = screen_width_pixels/screen_width_cm;
stim_width = 2*dist_to_screen_cm*tan((visual_angle_in_degrees/2)*(pi/180));
stim_pixels = stim_width*screen_pixel_density;
stim_radius = ceil(stim_pixels/2);

% create an appropriate circlespace matrix
h = 2*stim_radius+1;
circlespace = zeros(h,h);
center_point = stim_radius+1;
for i = 1:h
   for j = 1:h
        if (((i-center_point)^2 + (j-center_point)^2) <= stim_radius^2)
             circlespace(i,j) = 1;
        end
   end
end
[meshX,meshY] = meshgrid(1:h,1:h);


text:
module.exports = angular.module('trafficPortal.header', [])
    .controller('HeaderController', require('./HeaderController'));