text:
// Copyright 2012 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import BreakState from 'BreakState.js';
import {
  BreakStatement,
  ContinueStatement,
  DoWhileStatement,
  ForOfStatement,
  ForStatement,
  SwitchStatement,
  WhileStatement
} from '../../syntax/trees/ParseTrees.js';
import ContinueState from 'ContinueState.js';
import ParseTreeTransformer from '../ParseTreeTransformer.js';
import StateMachine from '../../syntax/trees/StateMachine.js';

/**
 * @param {BreakStatement|ContinueStatement} tree
 * @return {string}
 */
function safeGetLabel(tree) {
  return tree.name ? tree.name.value : null;
}

/**
 * Converts statements which do not contain a yield, to a state machine. Always called from a
 * context where the containing block contains a yield. Normally this just wraps the statement into
 * a single state StateMachine. However, if the statement contains a break or continue which
 * exits the statement, then the non-local break/continue must be converted into state machines.
 *
 * Note that parents of non-local break/continue statements are themselves translated into
 * state machines by the caller.
 */
export class BreakContinueTransformer extends ParseTreeTransformer {
  /**
   * @param {StateAllocator} stateAllocator
   */
  constructor(stateAllocator) {
    super();
    this.transformBreaks_ = true;
    this.stateAllocator_ = stateAllocator;
  }

  /** @return {number} */
  allocateState_() {
    return this.stateAllocator_.allocateState();
  }

  /**
   * @param {State} newState
   * @return {StateMachibneTree}
   */
  stateToStateMachine_(newState) {
    // TODO: this shouldn't be required, but removing it requires making consumers resilient
    // TODO: to a machine with INVALID fallThroughState
    var fallThroughState = this.allocateState_();
    return new StateMachine(newState.id, fallThroughState, [newState], []);
  }

  /**
   * @param {BreakStatement} tree
   * @return {ParseTree}
   */
  transformBreakStatement(tree) {
    return this.transformBreaks_ ?
        this.stateToStateMachine_(new BreakState(this.allocateState_(), safeGetLabel(tree))) :
        tree;
  }

  /**
   * @param {ContinueStatement} tree
   * @return {ParseTree}
   */
  transformContinueStatement(tree) {
    return this.stateToStateMachine_(new ContinueState(this.allocateState_(), safeGetLabel(tree)));
  }

  /**
   * @param {DoWhileStatement} tree
   * @return {ParseTree}
   */
  transformDoWhileStatement(tree) {
    return tree;
  }

  /**
   * @param {ForOfStatement} tree
   * @return {ParseTree}
   */
  transformForOfStatement(tree) {
    return tree;
  }

  /**
   * @param {ForStatement} tree
   * @return {ParseTree}
   */
  transformForStatement(tree) {
    return tree;
  }

  /**
   * @param {FunctionDeclaration|FunctionExpression} tree
   * @return {ParseTree}
   */
  transformFunction(tree) {
    return tree;
  }

  /**
   * @param {StateMachine} tree
   * @return {ParseTree}
   */
  transformStateMachine(tree) {
    return tree;
  }

  /**
   * @param {SwitchStatement} tree
   * @return {ParseTree}
   */
  transformSwitchStatement(tree) {
    var oldState = this.transformBreaks_;
    this.transformBreaks = false;
    var result = super.transformSwitchStatement(tree);
    this.transformBreaks_ = oldState;
    return result;
  }

  /**
   * @param {WhileStatement} tree
   * @return {ParseTree}
   */
  transformWhileStatement(tree) {
    return tree;
  }
}


text:
"use strict";

var LmdbQueue = require('../'),
    Topic = LmdbQueue.Topic;

var topic = new Topic({ path: __dirname + '/test-data', topic: 'test' });
console.log(topic.status());

redpajama_set_name: RedPajamaGithub


text:
1. npm install
2. webpack
3. npm run serve
4. Now application can be accessed on localhost:8080


text:
import * as eta from "eta-lib";

import * as express from "express";

export class Model implements eta.Model {
    public render(req: express.Request, res: express.Response, callback: (env: { [key: string]: any }) => void): void {
        let sql: string = `
            SELECT
                Person.username,
                Person.firstName,
                Person.lastName,
                Position.name AS position,
                Employee.biography
            FROM
                Person
                    LEFT JOIN Employee ON
                        Person.id = Employee.id
                    LEFT JOIN EmployeePosition ON
                        Person.id = EmployeePosition.id
                    LEFT JOIN Position ON
                        EmployeePosition.position = Position.id
                    LEFT JOIN Center ON
                        Position.center = Center.id
            WHERE
                Employee.current = 1 AND
                EmployeePosition.start <= CURDATE() AND
                (
                    EmployeePosition.end >= CURDATE() OR
                    EmployeePosition.end IS NULL
                ) AND
                Center.department = 1 AND
                Position.visible = 1
            ORDER BY
                Position.name,
                Person.lastName,
                Person.firstName`;
        eta.db.query(sql, [], (err: eta.DBError, rows: any[]) => {
            if (err) {
                eta.logger.dbError(err);
                callback({ errcode: eta.http.InternalError });
                return;
            }
            let rawLevels: { [key: string]: any[] } = {};
            for (let i: number = 0; i < rows.length; i++) {
                if (!rawLevels[rows[i].position]) {
                    rawLevels[rows[i].position] = [];
                }
                rawLevels[rows[i].position].push({
                    "biography": rows[i].biography,
                    "username": rows[i].username,
                    "firstName": rows[i].firstName,
                    "lastName": rows[i].lastName
                });
            }
            let levels: {
                name: string;
                employees: any[]
            }[] = [];
            for (let level in rawLevels) {
                rawLevels[level].sort((a: any, b: any): number => {
                    if (a.lastName == b.lastName) {
                        return a.firstName.localeCompare(b.firstName);
                    }
                    return a.lastName.localeCompare(b.lastName);
                });
                levels.push({
                    "name": level,
                    "employees": rawLevels[level]
                });
            }
            levels.sort((a: any, b: any): number => {
                return a.name.localeCompare(b.name);
            });
            callback({
                "levels": levels
            });
        });
    }
}


text:
package ru.abelov.search;

import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Test of class FindAction.
 * @author Aleksandr Belov
 * @since 02.02.2017
 */

public class FindActionTest {

    /**
     * Test of methods writeToStringBuilder() and getResult().
     * @throws IOException while problems with I/O system.
     */

    @Test
    public void whenOneMethodCreatesStringBuilderThenOtherReturnsCorrectString() throws IOException {
        FindAction findAction = new FindAction();
        File file = new File("pom.xml");
        findAction.writeToStringBuilder(file);
        findAction.writeToStringBuilder(file);
        final String result = String.format("%s%s%s%s", file.getCanonicalPath(), System.getProperty("line.separator"), file.getCanonicalPath(), System.getProperty("line.separator"));
        assertThat(result, is(findAction.getResult()));
    }

    /**
     * Test of method fillActions(), select() and inner class findByName.
     * @throws IOException while problems with I/O system.
     */

    @Test
    public void whenClassFindFileByFullNameThenReturnsItPath() throws IOException {
        File directorySearch = new File(System.getProperty("user.dir"));
        File file = new File(String.format("%s/%s", System.getProperty("user.dir"), "pom.xml"));
        String searchCriteria = "pom.xml";
        FindAction findAction = new FindAction(directorySearch, searchCriteria);
        findAction.fillActions();
        findAction.select("-f");
        final String result = findAction.getResult();
        assertThat(result, is(String.format("%s%s", file.getCanonicalPath(), System.getProperty("line.separator"))));
    }

    /**
     * Test of inner class findByMask.
     * @throws IOException while problems with I/O system.
     */

    @Test
    public void whenClassFindFileByMaskThenReturnsItPath() throws IOException {
        File directorySearch = new File(System.getProperty("user.dir"));
        File file = new File(String.format("%s/%s", System.getProperty("user.dir"), "pom.xml"));
        String searchCriteria = "p*.?m?";
        FindAction findAction = new FindAction(directorySearch, searchCriteria);
        findAction.fillActions();
        findAction.select("-m");
        final String result = findAction.getResult();
        assertThat(result, is(String.format("%s%s", file.getCanonicalPath(), System.getProperty("line.separator"))));
    }

    /**
     * Test of inner class findByRegularExpression.
     * @throws IOException while problems with I/O system.
     */

    @Test
    public void whenClassFindFileByRegularExpressionThenReturnsItPath() throws IOException {
        File directorySearch = new File(System.getProperty("user.dir"));
        File file = new File(String.format("%s/%s", System.getProperty("user.dir"), "pom.xml"));
        String searchCriteria = "^p.*l$";
        FindAction findAction = new FindAction(directorySearch, searchCriteria);
        findAction.fillActions();
        findAction.select("-r");
        final String result = findAction.getResult();
        assertThat(result, is(String.format("%s%s", file.getCanonicalPath(), System.getProperty("line.separator"))));
    }
}


text: export { default } from './IntegerInput'


text:
<!DOCTYPE html>

    <title>three-mesh-bvh - BVH Inspector</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

		BVH inspector showing the number of traversals at a given pixel, various BVH construction stats, and basic raycast benchmark.

		Pixels with traversal counts above the "traversalTreshold" are highlighted in red.


text:
\documentclass{article}
\usepackage{fullpage}
%\usepackage{psfig}
\usepackage{epsf}

\begin{document}

\subsection{Accelerometer}

The accelerometers available for the 2003 6.270 competition are Analog
Devices ADXL202E dual-axis, surface-micromachined IC accelerometers
premounted on small ADXL202EB evaluation boards, on which can be
mounted a few external components which set the application properties
of the accelerometer.  Each measurement axis has a +/-2gee range and
can measure accelerations from dc (such as the force of gravity) to
several KHz, with a user-settable low-pass filter available on each
axis.

\subsubsection{What's It Good For?}

The most important application of the XL202 in the 2003 competition
will probably be tilt sensing,since the game surface contains both
sloped and level terrain. Accelerometers measure tilt by measuring the
acceleration due to gravity as the sensing axis tilts from horizontal
(0gee) to vertical (1gee), (a sinusiodal function of angle).  It is
also possible to use the accelerometer to measure speed (by
integrating acceleration in the direction of motion) or impact.  These
are probably less useful to robots, but the fact that they are
possible points up the fact that virtually all motions of the robot
are potential error sources in tilt measurement, and steps must be
taken to minimize their effects.

\subsubsection{How Is It Used?}

The XL202 is powered from a single power supply in the range of 3V to
6V, so it will work directly from the Handyboard's 5V.  Each axis
output consists of a periodic rectangular logic waveform (Figure
\ref{outputwave})
whose duty cycle (ratio of pulse width to period) is a measure of
acceleration at a nominal scale factor of 12.5\%/gee, with 50\% nominal
duty cycle (squarewave) at 0gee.  These outputs are easily read by the
"input capture" function of the Handyboard 68HC11 MCU's
Timer/Counters.  Software drivers are available which support
continuous measurement of one or two axes' pulse widths and periods
into C variables.  (The design of the XL202 is such that the output
period is common to both axes, but the drivers make separate
measurements.)

\epsfysize=2.0 in
\begin{figure}[htbp]
\begin{center}
\epsfbox{outputwave.eps}
%\centerline{psfig{file=./outputwave.eps}}
\caption{Output of XL202}
\label{outputwave}
\end{center}
\end{figure}

The unusual output format of the XL202 was chosen to permit
high-resolution measurements, such as tilt, to be accomplished without
requiring a high-resolution A/D converter.  To see this, consider what
would happen if the device instead had an analog voltage output which
could be measured by the 8-bit A/D converter present in the 'HC11.  If
the XL202's +/-2gee span were mapped into the converter's full
256-count range, then each count would represent an increment of about
15.6 milligee (mgee), which corresponds to about 1.1deg of tilt for
small angles.  For an application such as the 2003 6.270 competition,
where the tilt angle can range from 0 to about 6.5 degrees, this would
clearly be a very low-resolution measurement.

The resolution obtainable with the duty-cycle outputs is dependent
upon the period of the output signal (which is user-selectable with a
resistor), the clock speed of the counter used to measure the duty
cycle, and the resolution of the counter. The Handyboard MCU's
counter/timers are 16 bits long with 0.5us resolution, and a good
XL202 setup for use with that would be an output period of 10ms.  With
this period, the nominal output "hi" time of either XL202 axis will be
5ms at 50\% duty cycle (0gee).  The 0.5us counter/timer can resolve
this pulsewidth to one
count in 10,000, and 1gee, at 12.5\%/gee, will occupy 2500 counts.  In
this world, a 6.5 degree tilt measurement range will span about 285
counts (approx. 23mdeg/count), a far better result than the 6 counts
that would be had using the 8-bit A/D.

\subsubsection{Noise and Bandwidth}

The XL202 has a nominal output noise of about 0.25mgee(rms)/sqrtHz of
bandwidth.  If the measurement bandwidth is set large enough, the
total noise over that bandwidth may be enough to corrupt the
measurement.  In the example above, using a 16-bit timer/counter to
measure the output, each count represents about 0.4mgee, so, even at a
1Hz bandwidth, device noise will cause the output to flicker by a few
counts since, taking a ratio (for white noise) of 3:1 peak to rms, the
XL202 will output 1.5mgee pk-pk noise in 1Hz, or roughly +/-2 counts.
This really wouldn't be an issue in the 6.270 application, since there
is much more counter resolution than can be meaningfully used to
measure tilt, and, in fact, if the bandwidth were opened up to 10Hz,
resulting in sqrt(10) times more noise, the resolution would still be
adequate.

\subsubsection{Aliasing}

The XL202's user-settable lowpass filters on each channel can be used
to reduce the effects of aliasing in applications where it is
important.  The duty-cycle output can be thought of as a sampler at
the rate of the output period.  At the 10ms period mentioned above,
the sampling rate is 100Hz, so theory says that any signals (or noise)
of frequency greater than 50Hz (the Nyquist frequency) will appear in
the (sampled) output to be signals of 50Hz and below; that is,
indistinguishable (and inseparable) from real in-band (lower than 50Hz) signals.
The filter pins on the XL202 precede the duty-cycle modulators, and
therefore the sampling process, and can be used to filter out
high-frequency signals that might alias with the chosen output period.
Since the filters are only single-pole, they offer only 20dB of
attenuation per decade, so they should be set for a much lower corner
frequency than the Nyquist frequency (= half the output rate).

As a practical matter, though, aliasing is usually not a serious
application concern.   In tilt sensing, for example, only near-dc
signals are of interest, and out-of-band signals like transients are
lost to the filter or to sample averaging.  Only an unwanted signal
with sustained frequency components at integer multiples of the
Nyquist rate would be mistaken for dc, and such signals are rare.
There may be many disturbances of the readings of a robot's tilt
sensor (impacts, acceleration, bounce) but they are as likely to be
within the chosen measurement band as they are to be aliasing into it.
So it is usually sufficient to set the filters for an acceptable noise
floor and not give further consideration to aliasing unless experience
shows that it is an issue.

\subsubsection{Configuring the XL202}

The XL202EB evaluation board contains mounting locations for:
\begin{itemize}
\item
 A resistor to set the period of the output waveforms (only one
   for both axes),
\item
 Two capacitors, C2 to set the bandwidth of the X axis and C3 for
   the Y axis.
\end{itemize}

The resistor has the value 124Megohm x period (seconds).  Thus a
1.24Meg resistor will set the 10ms period used in the examples above.
The resistor does not have to be particularly accurate, since the
period is not very critical, and can be measured by the software if
necessary (more on this later).  (NOTE: The supplied drivers require
that the output period be no longer than 32ms.  Please see the section
on drivers below.)  The capacitors have the value 4.7uF/BW (Hz), so
that a 0.47uf capacitor will set the 10Hz bandwidth used in the
examples.  (There are 2200pf capacitors on the board in parallel with
the user-supplied capacitor locations, but they can be ignored for the
small bandwidths that will be needed for robot work).  Either polar
(like tantalum) or non-polar (such as ceramic) capacitors can be used,
but in the case of a polar type the "+" end must be connected to the
pads closest to the accelerometer on the board.  Aluminum electrolytic
capacitors should be avoided, as they tend to corrupt readings in
terrible ways.

\subsubsection{Connecting the XL202}

There are three digital inputs with counter/timer capability on the
68HC11 used on the Handyboard.  Timer/counter TIC1 is used by the
on-board infrared receiver, leaving TIC2/PA1 and TIC3/PA0 free for use
with the XL202.  These inputs are available whether or not the
expansion board is used.  Both inputs have 47Kohm pullup resistors
which are not necessary for the XL202, but do no harm and can be left
in place.  A single timer/counter can be used for one axis of
measurement, or both channels can be used to read both axes.  The
location of the timer/counter inputs on the Handyboard is shown in
Figure \ref{HBinput} and the appropriate wiring for the ADXL202EB is shown in
Figure \ref{XLwiring}.  The ribbon cable supplies +5V power and ground from one of
the TIC channels; the connector for the other channel connects only
the channel signal.

\epsfysize=1.0 in
\begin{figure}[htbp]
\begin{center}
\epsfbox{HBinput.eps}
\caption{Timer and counter inputs on Handyboard}
\label{HBinput}
\end{center}
\end{figure}

%\begin{figure}[htbp]
%\centerline{psfig{file=./HBinput.eps}}
%\caption{Timer and counter inputs on Handyboard}
%\label{HBinput}
%\end{figure}

\epsfysize=2.0in
\begin{figure}[htbp]
\begin{center}
\epsfbox{XLwiring.eps}
\caption{Wiring diagram for XL202}
\label{XLwiring}
\end{center}
\end{figure}

%\begin{figure}[htbp]
%\centerline{psfig{file=./XLwiring.eps}}
%\caption{Wiring diagram for XL202}
%\label{XLwiring}
%\end{figure}

Figure \ref{sensingaxes} shows a component-side view of the ADXL202EB
and indicates
the axes of sensing and the locations for user-installed components.
Since the accelerometer uses the acceleration due to gravity to sense
tilt, the output of the appropriate axis will increase (longer
pulsewidth) when the + end of that axis is elevated with respect to
the - end.

\epsfysize=2.0in
\begin{figure}[htbp]
\begin{center}
\epsfbox{sensingaxes.eps}
\caption{Component view showing the sensing axes of the XL202}
\label{sensingaxes}
\end{center}
\end{figure}

%\begin{figure}[htbp]
%\centerline{psfig{file=./sensingaxes.eps}}
%\caption{Component view showing the sensing axes of the XL202}
%\label{sensingaxes}
%\end{figure}

\subsubsection{Calibration and measurement details}

The outputs of the XL202 are duty-cycle outputs, so the correct way to
read an axis is to read a pulsewidth and divide it by the period
obtained at the same time.  In practice, though, the division is
usually unnecessary, since the period is quite stable with power
supply and temperature.  In fact, since the period measurement also
has a small amount of noise, dividing by the period actually adds
noise to the measurement.  The divide operation also consumes CPU
resources and takes time.  For all these reasons, it is common to
obtain the scale factor that relates output duty cycle to applied
acceleration by a calibration routine using the earth's gravity as a
1gee test signal.  This calibration will be useful even if the
duty-cycle division is done, since it will remove the accelerometer's
sensitivity tolerance of +/-20\%.

Offset should be calibrated first.  Since each axis of the XL202 can
have up to +/-1gee of offset, it is necessary to perform a calibration
before its output can be meaningful in an absolute sense.  This is
easily accomplished in software by running a routine, with zero
acceleraion or tilt present, which stores the output values of the
accelerometer under those conditions.  To minimize the effect of
noise, it might be useful to average 10 or 16 readings.  The resulting
offset calibration constants are then used to correct all subsequent
readings simply by subtracting the appropriate (X or Y) calibration
constant from the reading.  Since offset calibration can be performed
with the robot in its normal orientation and quiescent, it can be done
even at the time of the contest.

Once offset is calibrated out, sensitivity can be calibrated if
desired.  Using a test routine which corrects readings by subtracting
the offset calibration numbers, orient the robot to point the + axis
of each axis away from the earth in turn, noting the offset-corrected
readings.  These are the values that correspond to 1 gee.
Software scale factors that convert the offset-corrected output
readings into gees can be calculated from these readings.  Note that
the orientations of the sensor for these calibrations need not be
perfect:  sensitivity to tilt is very small near vertical due to the
sinusoidal relationship between tilt and output.

\subsubsection{Mounting and Orientation}

To measure tilt, the ADXL202EB board should be mounted horizontally
(maximum tilt sensitivity occurs at small angles).  To minimize
mounting resonances which may turn small shocks into long-term ringing
disturbances, make the mounting as stiff as possible, and highly
damped.  Sticking the bottom of the board to a structural LEGO
component such as a beam with double-sticky tape, leaving the pins in
the clear, is probably the best strategy.  You will probably want to
mount the board so that the axes of the sensor correspond to the axes
of the robot, to make two-axis tilt measurements meaningful.  An
alternative strategy is to mount the board "on edge", using the two
axis outputs to measure tilt in one direction, but allowing 360 degree
measurement.  This will probably not be a useful strategy for 6.270
robots.

\subsubsection{Using the Drivers}

Software drivers are provided for two-axis measurements using both
Timer/Counter 2 and Timer/Counter 3, and for single-axis applications
using either Timer/Counter 2 or Timer/Counter 3.  These drivers are
named, respectively, accelxy.icb, accel2.icb and accel3.icb, and need
only be loaded (preferably before the C routines that use their
outputs) to be used.  Corresponding .asm files are provided for each.
The drivers provide several routines which can be invoked from C and
one routine (initialize\_module) which runs whenever a reset occurs.
The actual measurements of the accelerometer outputs are
interrupt-driven (at the rate of the accelerometer's user-set output
period) so there is no routine to explicitly make a measurement:
measurements are made continuously and the appropriate C-accessible
variables are updated in the background.

The routines callable from C (in every version of the drivers) are:
\begin{description}
  \item{start\_accel}, which turns on the background measurement process, and
  \item{stop\_accel}, which turns it off.
\end{description}

The C variables in which the measurement results appear have different
names for the two-axis and one-axis cases.  For the two-axis driver
accelxy.icb, the variables are:
\begin{description}
  \item{xpw and ypw}, the x and y pulsewidths, respectively, and
  \item{xperiod and yperiod}, the period measurements obtained during each
  axis measurement.
\end{description}

As mentioned above, the XL202 outputs really have a common period, but
the drivers don't take advantage of that.

For the single-axis drivers accel2.icb and accel3.icb, the variables are:
\begin{description}
  \item{pw}, the pulsewidth
  \item{period}, the period.
\end{description}

The units of these outputs are time, 16 bits long with the least
significant bit representing 0.5us.  The drivers are greatly
simplified by the assumption that the period of the waveform will not
exceed 32ms, the length of the Counter/Timers.  Users must therefore
not select a period-setting resistor for the ADXL202EB of more than
about 3.3Mohm if the supplied drivers are to be used.

The drivers do not do any calibration upon reset; they simply set up
the necessary interrupt mechanisms.  Once the interrupts are enabled by
start\_accel, the routines wait for positive and negative edges alternately
and do the subtractions necessary to obtain pulse width and period.

The interrupt routines take 100us of processor time per axis per accel
output period.  So if the period is set to 10ms, then these routines
take 1\% of the processor's time for one axis, or 2\% for two axes.  If
this is not acceptable, and processor time is saved by turning the
measurement process (interrupts) off and on as needed, remember that
there will be a one-period latency before the data can be trusted.
Waiting out this interval for each reading may be more inefficient
than leaving the measurement process on.

\end{document}


text:
import os
import csv

import pymongo
import yaml

def get_config(config_filename=None):
    if config_filename is None:
        config_filename = os.path.join('configs', 'prod.yml')
    with open(config_filename) as config_file:
        return yaml.safe_load(config_file.read())

def create_view_with_first_dates(config_filename=None):
    print('FIRST DATES BEGIN.')
    VIEW_NAME = 'view_with_first_dates'
    config = get_config(config_filename)
    db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']]
    if VIEW_NAME not in db.collection_names():
        db.command('create', VIEW_NAME,
            viewOn='urls',
            pipeline=[
                {
                    '$group':
                        {
                            '_id': '$channel',
                            'first_date':
                                {
                                    '$min': '$ts'
                                }
                        }
                }
            ]
        )
    print('FIRST DATES END.')

def ensure_index(config_filename=None):
    print('ENSURE INDEX BEGIN.')
    config = get_config(config_filename)
    db = pymongo.MongoClient(host=config['db']['host'])[config['db']['name']]
    stats = db['stats']
    stats.create_index([('channel', pymongo.ASCENDING), ('ts', pymongo.ASCENDING)])
    urls = db['urls']
    urls.create_index([('channel', pymongo.ASCENDING), ('url', pymongo.ASCENDING)])
    contents = db['contents']
    contents.create_index([('channel', pymongo.ASCENDING), ('md5_sum', pymongo.ASCENDING)])
    errors = db['errors']
    errors.create_index([('channel', pymongo.ASCENDING), ('url', pymongo.ASCENDING)])
    settings = db['settings']
    settings.create_index([('setting', pymongo.ASCENDING)])
    channels = db['channels']
    channels.create_index([('channel', pymongo.ASCENDING)])
    channels.create_index([('submodule', pymongo.ASCENDING)])
    print('ENSURE INDEX END.')

def set_tags():
    with open(os.path.join('utils', 'tag_list.tsv')) as master_tags_file:
        for line in csv.DictReader(master_tags_file, fieldnames=('submodule', 'channel', 'tags'), delimiter='\t'):
            if line['submodule'].strip() == 'SUBMODULE':
                continue
            with open(os.path.join('channels', line['submodule'].strip(), 'tags.txt'), 'w') as local_tags_file:
                local_tags_file.write(line['tags'].strip())

def main():
    ensure_index()
    # create_view_with_first_dates()
    # set_tags()

if __name__ == '__main__':
    main()


text:
#ifndef _BF_RT_PORT_TABLE_DATA_IMPL_HPP
#define _BF_RT_PORT_TABLE_DATA_IMPL_HPP

#include <unordered_set>
#include "bf_rt_port/bf_rt_port_mgr_intf.hpp"
#include "bf_rt_common/bf_rt_table_data_impl.hpp"
#include "bf_rt_common/bf_rt_table_impl.hpp"

namespace bfrt {

class BfRtPortCfgTableData : public BfRtTableDataObj {
 public:
  BfRtPortCfgTableData(const BfRtTableObj *tbl_obj,
                       const std::vector<bf_rt_id_t> &fields)
      : BfRtTableDataObj(tbl_obj) {
    set_active_fields(fields);
  }
  ~BfRtPortCfgTableData() = default;
  bf_status_t setValue(const bf_rt_id_t &field_id, const uint64_t &value);

  bf_status_t setValue(const bf_rt_id_t &field_id,
                       const uint8_t *value,
                       const size_t &size);

  bf_status_t setValue(const bf_rt_id_t &field_id, const bool &value);

  bf_status_t setValue(const bf_rt_id_t &field_id, const std::string &str);

  bf_status_t getValue(const bf_rt_id_t &field_id, uint64_t *value) const;

  bf_status_t getValue(const bf_rt_id_t &field_id,
                       const size_t &size,
                       uint8_t *value) const;

  bf_status_t getValue(const bf_rt_id_t &field_id, bool *value) const;

  bf_status_t getValue(const bf_rt_id_t &field_id, std::string *str) const;

  bf_status_t reset(const std::vector<bf_rt_id_t> &fields) override final;
  bf_status_t reset() override final;

  // unexposed API
  const std::unordered_set<bf_rt_id_t> &getActiveDataFields() const {
    return activeFields;
  }
  const std::unordered_map<bf_rt_id_t, bool> &getBoolFieldDataMap() const {
    return boolFieldData;
  }
  const std::unordered_map<bf_rt_id_t, uint32_t> &getU32FieldDataMap() const {
    return u32FieldData;
  }
  const std::unordered_map<bf_rt_id_t, std::string> &getStrFieldDataMap()
      const {
    return strFieldData;
  }

 private:
  bf_status_t setU32ValueInternal(const bf_rt_id_t &field_id,
                                  const uint64_t &value,
                                  const uint8_t *value_ptr,
                                  const size_t &s);
  bf_status_t getU32ValueInternal(const bf_rt_id_t &field_id,
                                  uint64_t *value,
                                  uint8_t *value_ptr,
                                  const size_t &s) const;
  bf_status_t set_active_fields(const std::vector<bf_rt_id_t> &fields);
  bool checkFieldActive(const bf_rt_id_t &field_id,
                        const DataType &dataType) const;
  bool all_fields_set;
  std::set<bf_rt_id_t> fieldPresent;
  std::unordered_map<bf_rt_id_t, bool> boolFieldData;
  std::unordered_map<bf_rt_id_t, uint32_t> u32FieldData;
  std::unordered_map<bf_rt_id_t, std::string> strFieldData;
  std::unordered_set<bf_rt_id_t> activeFields;
};

class BfRtPortStatTableData : public BfRtTableDataObj {
 public:
  BfRtPortStatTableData(const BfRtTableObj *tbl_obj,
                        const std::vector<bf_rt_id_t> &fields)
      : BfRtTableDataObj(tbl_obj) {
    std::memset(u64FieldDataArray, 0, BF_PORT_NUM_COUNTERS * sizeof(uint64_t));
    set_active_fields(fields);
  }
  ~BfRtPortStatTableData() = default;
  bf_status_t setValue(const bf_rt_id_t &field_id, const uint64_t &value);

  bf_status_t setValue(const bf_rt_id_t &field_id,
                       const uint8_t *value,
                       const size_t &size);

  bf_status_t getValue(const bf_rt_id_t &field_id, uint64_t *value) const;

  bf_status_t getValue(const bf_rt_id_t &field_id,
                       const size_t &size,
                       uint8_t *value) const;

  bf_status_t reset(const std::vector<bf_rt_id_t> &fields) override final;
  bf_status_t reset() override final;

  // unexposed API
  void setAllValues(const uint64_t *stats);
  const std::vector<bf_rt_id_t> &getActiveDataFields() const {
    return activeFields;
  }
  const uint64_t *getU64FieldData() const { return u64FieldDataArray; }
  const uint32_t &getAllStatsBoundry() const { return AllStatsBoundry; }

 private:
  bf_status_t set_active_fields(const std::vector<bf_rt_id_t> &fields);
  bf_status_t setU64ValueInternal(const bf_rt_id_t &field_id,
                                  const uint64_t &value,
                                  const uint8_t *value_ptr,
                                  const size_t &s);
  bf_status_t getU64ValueInternal(const bf_rt_id_t &field_id,
                                  uint64_t *value,
                                  uint8_t *value_ptr,
                                  const size_t &s) const;
  bool all_fields_set;
  std::set<bf_rt_id_t> fieldPresent;
  uint64_t u64FieldDataArray[BF_PORT_NUM_COUNTERS];
  std::vector<bf_rt_id_t> activeFields;
  const uint32_t AllStatsBoundry = 20;
};

}  // bfrt
#endif  // _BF_RT_PORT_TABLE_DATA_IMPL_HPP


text:
using process::Process;

using std::cerr;
using std::endl;

namespace mesos {
namespace internal {
namespace tests {

const char HttpServerTestHelper::NAME[] = "HttpServer";

class HttpServer : public Process<HttpServer>
{
public:
  HttpServer()
    : ProcessBase(process::ID::generate("http-server")) {}
};

HttpServerTestHelper::Flags::Flags()
{
  add(&Flags::ip,
      "ip",
      "IP address to listen on.");

  add(&Flags::port,
      "port",
      "Port to listen on.");
}

int HttpServerTestHelper::execute()
{
  os::setenv("LIBPROCESS_IP", flags.ip);
  os::setenv("LIBPROCESS_PORT", stringify(flags.port));

  HttpServer* server = new HttpServer();

  process::spawn(server);
  process::wait(server->self());

  delete server;

  return EXIT_SUCCESS;
}

} // namespace tests {
} // namespace internal {
} // namespace mesos {


text:
function create_task_{{name}}(moduleData) {
	{{#js}}
	try {
		{{{fileData}}}
	} catch(err) {
		console.error('Failed to load file: {{fileName}}, from task {{../name}} (task_module.html)', err, err.stack);
	}
	{{/js}}
}


text:
package com.andlu6.teacup.adapter;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.andlu6.teacup.R;
import com.andlu6.teacup.model.HomeFloorData;
import com.andlu6.teacup.model.ProductData;
import com.andlu6.teacup.noscrollview.NoScrollGridView;
import com.mtxc.universallistview.UniversalAdapter;
import com.mtxc.universallistview.ViewHolder;

import java.util.List;

/**
 * Created by Administrator on 2016.02.25.
 *
 * 首页ListView的适配器
 */
public class HomeListAdapter extends UniversalAdapter<HomeFloorData> {

    public HomeListAdapter(Context context, List<HomeFloorData> datas, int itemLayoutId) {
        super(context, datas, itemLayoutId);
    }

    @Override
    public void updateItem(ViewHolder viewHolder, HomeFloorData homeFloorData) {
        ((TextView) viewHolder.getView(R.id.item_home_tv_floor)).setText(homeFloorData.getFloor());
        if (homeFloorData.getProducts() != null) {
            NoScrollGridView gridView = (NoScrollGridView) viewHolder.getView(R.id.item_home_grid);
            HomeGridAdapter adapter = new HomeGridAdapter(context, homeFloorData.getProducts(), R.layout.item_home_grid);
            gridView.setAdapter(adapter);
            // 设置商品的点击事件
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ProductData product = (ProductData) parent.getItemAtPosition(position);
                    Log.d(String.valueOf(getClass()), product.getId() + "");
                }
            });
        }
    }
}


text:
export function includes(target, elem, start) {
  return (target && target.includes(elem, start)) || false;
}

export function arrayFrom() {
  return Array.from.apply(Array, arguments);
}

export function find(arr, pred, thisArg) {
  return arr && arr.find(pred, thisArg);
}

export function findIndex(arr, pred, thisArg) {
  return arr && arr.findIndex(pred, thisArg);
}


text:
<!DOCTYPE html>

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

  <title>Feliz año nuevo</title>
  <meta name="description" content="Las Cosas son como deben, no como deberían Ser.">
  <meta name="author" content="Mauricio Navarro Miranda">
  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <meta name="twitter:card" content="summary">
  <meta name="twitter:title" content="El rincón de mautemático">
  <meta name="twitter:description" content="Las Cosas son como deben, no como deberían Ser.">

  <meta property="og:type" content="article">
  <meta property="og:title" content="El rincón de mautemático">
  <meta property="og:description" content="Las Cosas son como deben, no como deberían Ser.">

  <link rel="apple-touch-icon" sizes="57x57" href="/images/favicons/apple-touch-icon-57x57.png">
  <link rel="apple-touch-icon" sizes="60x60" href="/images/favicons/apple-touch-icon-60x60.png">
  <link rel="apple-touch-icon" sizes="72x72" href="/images/favicons/apple-touch-icon-72x72.png">
  <link rel="apple-touch-icon" sizes="76x76" href="/images/favicons/apple-touch-icon-76x76.png">
  <link rel="apple-touch-icon" sizes="114x114" href="/images/favicons/apple-touch-icon-114x114.png">
  <link rel="apple-touch-icon" sizes="120x120" href="/images/favicons/apple-touch-icon-120x120.png">
  <link rel="apple-touch-icon" sizes="144x144" href="/images/favicons/apple-touch-icon-144x144.png">
  <link rel="apple-touch-icon" sizes="152x152" href="/images/favicons/apple-touch-icon-152x152.png">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicons/apple-touch-icon-180x180.png">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-32x32.png" sizes="32x32">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-194x194.png" sizes="194x194">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-96x96.png" sizes="96x96">
  <link rel="icon" type="image/png" href="/images/favicons/android-chrome-192x192.png" sizes="192x192">
  <link rel="icon" type="image/png" href="/images/favicons/favicon-16x16.png" sizes="16x16">
  <link rel="manifest" href="/images/favicons/manifest.json">
  <link rel="shortcut icon" href="/images/favicons/favicon.ico">
  <meta name="msapplication-TileColor" content="#ffc40d">
  <meta name="msapplication-TileImage" content="/images/favicons/mstile-144x144.png">
  <meta name="theme-color" content="#ffffff">

  <link rel="stylesheet" href="/css/main.css">
  <link rel="canonical" href="https://blog.mautematico.com//2014/feliz-ano-nuevo.html">
  <link rel="alternate" type="application/rss+xml" title="El rincón de mautemático" href="/feed.xml">

El rincón de mautemático

Las Cosas son como deben, no como deberían Ser.

Blog

                  Twitter

                  GitHub

                  Email

                RSS

      <time datetime="1 Mar 2014" class="post-meta__date date">1 Mar 2014</time> • on

Feliz año nuevo

Un poco sin querer, he encontrado el pretexto perfecto. Ahora que lo he notado, me di cuenta que había estado esperando el día sin motivo aparente.

A lo largo y ancho* de la historia la humanidad ha usado multitud de calendarios distintos, a veces porque el año solar no era manejable, y otras por otras razones.

Ahí tenemos los calendarios maya, chino, lunar, revolucionario soviético, y otros más populares como el juliano y el gregoriano. Omito las mayúsculas a propósito porque me gustan las minúsculas y el exceso de mayúsculas en medio me causa una sensación extraña; además si las omito parejo podría salvarme de una furiosa tormenta de arena en mi contra en días venideros.

Hablando de calendarios no tan populares, hay un dato gracioso sobre el calendario revolucionario soviético [0]:

A partir del día 1 de octubre de 1929, se comenzó a usar una versión más racionalizada del calendario. En esta versión, todos los meses tenían 30 días, y los 5 días restantes, se añadían entre medias, sin pertenecer a ningún mes ni a ninguna semana. Estos días eran:

Día de Lenin, un día después del 30 de enero.

Días del trabajo, dos días después del 30 de abril.

Días de la Industria, dos días después del 7 de noviembre.

En los años bisiestos, un día extra después del 30 de febrero.

Cuando sea grande tendré mi propio calendario con días extras. Uno de ellos será el día de Mauricio.

Algo chistoso que ocurre con el calendario chino [1] es que en el extranjero se le llama calendario lunar, nombre adecuado porque refleja un dato importante: El calendario chino usa la Luna y el Sol como referencia, y no sólo el Sol, como hacen otros. Además es un nombre políticamente correcto: Hace días fue el año nuevo chino [2], y en particular el comienzo del año del caballo. Pero ¿qué pasa si tienes un amigo que vive en un país que no es china y en el que también se festeja el inicio del año del caballo? O, peor aún ¿qué tal si tu amigo vive en un país que tiene conflictos diplomáticos con china, o la religión de tu amigo y las tradiciones chinas se llavan mal?

Como sea, otra forma de referirse al calendario chino es calendario lunar.

No sé cuantos calendarios estén en uso en la actualidad, aunque me gustaría conocer el motivo de su diseño y el caos que ocasionaron al comenzar a utilizarse.

En otros temas: los días pasados he estado poniendo un poco en orden algunos de los asuntos que tenía pendientes: Lavar ropa, visitar familiares y amigos, limpiar la casa y hasta hacer tarea de la universidad. ¡Que no se me olviden los que siguen! Ponerme al día con un par de asuntos de Mozilla y las Olimpiadas, revivir proyectos interesantes de negocios y dormir bien. Borrar el spam en mi blog.

Todavía me faltan varios asuntos de gran importancia, que no puedo contar por el caracter de “clasificado” que tienen.

En fin, una de las cosas chistosas del calendario gregoriano [3] (usado en gran parte del mundo de forma oficial) es febrero:

Treinta días tiene noviembre

con abril, junio y septiembre.

Los demás son treinta y uno

menos febrero mocho

que sólo trae vientiocho.

Para no hacer el cuento largo, el gregoriano vino a sustituir al juliano [4], que a su vez reemplazaba al romano, en el que el mes quinto se llamaba Quintilis, y no Julio (como Julio César); mientras que el mes sexto se llamaba Sextilis y no Agosto (como Octavio Augusto), además de tener treinta días y no treinta y uno. Y aún con tanto poder, Augusto no podía hacer aparecer días de la nada, así que el senado romano trasladó uno de los días del último mes al mes sexto.

Si hacemos las cuentas (que no es lo mismo que hacer la matemática), encontraremos que febrero era el mes después de enero y antes de Martius, que era el primero.

Lo chistoso del calendario de Mauricio es que festeja el año nuevo el primero de marzo, nomás porque así sí tiene sentido que febero tenga 28 días (y a veces 29): Se me acabaron y ya no alcanzaban. Además tiene juegos de azar y mujerzuelas.

En otros temas: Soy Mauricio y no estaba muerto, he despertado de mi letargo**.

Feliz maurimarzo (¿?). Feliz año nuevo.

[0] http://es.wikipedia.org/wiki/Calendario_revolucionario_sovi%C3%A9tico

[1] [2] http://es.wikipedia.org/wiki/A%C3%B1o_Nuevo_chino

[3] http://es.wikipedia.org/wiki/Calendario_gregoriano

[4] http://es.wikipedia.org/wiki/Calendario_juliano

*  Me gusta perder el tiempo pensando en universos paralelos y realidades alternativas.

** No confundir con leotardo.

  © 2020 Mauricio Navarro Miranda. All rights reserved.


text:
package org.kuali.kra.protocol.actions.print;

import org.kuali.coeus.sys.framework.rule.KcBusinessRule;
import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase;
import org.kuali.kra.infrastructure.KeyConstants;

public class ProtocolActionPrintRule extends KcTransactionalDocumentRuleBase implements KcBusinessRule<ProtocolActionPrintEvent> {
    private static final String PROTOCOL_PRINT_TYPE_FIELD = "actionHelper.reportType";

    public boolean processRules(ProtocolActionPrintEvent event) {

        boolean valid = true;

        if (!event.getFullReport() && !event.getSummaryReport() && !event.getHistoryReport() && !event.getReviewCommentsReport()) {
                reportError(PROTOCOL_PRINT_TYPE_FIELD, KeyConstants.ERROR_COMMITTEE_ACTION_PRINT_REPORT_NOT_SPECIFIED);
                valid = false;
        }

        return valid;
    }
}


text:
#include "mitkPluginActivator.h"
#include "QmitkMeasurementView.h"
#include "QmitkImageStatisticsView.h"

#include <QtPlugin>

namespace mitk {

void PluginActivator::start(ctkPluginContext* context)
{
  BERRY_REGISTER_EXTENSION_CLASS(QmitkMeasurementView, context)
  BERRY_REGISTER_EXTENSION_CLASS(QmitkImageStatisticsView, context)
}

void PluginActivator::stop(ctkPluginContext* context)
{
  Q_UNUSED(context)
}

}

Q_EXPORT_PLUGIN2(org.mitk.gui.qt.measurementtoolbox, mitk::PluginActivator)


text:
<?php

namespace Silex\Provider;

use Silex\Application;
use Silex\ServiceProviderInterface;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\DefaultCsrfProvider;
use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\Extension\Validator\ValidatorExtension as FormValidatorExtension;
use Symfony\Component\Form\Extension\Csrf\CsrfExtension;

/**
 * Symfony Form component Provider.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 */
class FormServiceProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['form.secret'] = md5(__DIR__);

        $app['form.factory'] = $app->share(function () use ($app) {
            $extensions = array(
                new CoreExtension(),
                new CsrfExtension($app['form.csrf_provider']),
            );

            if (isset($app['validator'])) {
                $extensions[] = new FormValidatorExtension($app['validator']);

                if (isset($app['translator'])) {
                    $r = new \ReflectionClass('Symfony\Component\Form\Form');
                    $app['translator']->addResource('xliff', dirname($r->getFilename()).'/Resources/translations/validators.'.$app['locale'].'.xlf', $app['locale'], 'validators');
                }
            }

            return new FormFactory($extensions);
        });

        $app['form.csrf_provider'] = $app->share(function () use ($app) {
            if (isset($app['session'])) {
                return new SessionCsrfProvider($app['session'], $app['form.secret']);
            }

            return new DefaultCsrfProvider($app['form.secret']);
        });
    }

    public function boot(Application $app)
    {
        // BC: to be removed before 1.0
        if (isset($app['form.class_path'])) {
            throw new \RuntimeException('You have provided the form.class_path parameter. The autoloader has been removed from Silex. It is recommended that you use Composer to manage your dependencies and handle your autoloading. If you are already using Composer, you can remove the parameter. See http://getcomposer.org for more information.');
        }
    }
}


text:
using System.Threading.Tasks;
namespace Autodash.Core
{
    public interface IUnitTestRunner
    {
        string TestRunnerName { get; }
        Task<UnitTestBrowserResult> Run(TestRunContext context);
    }
}


text:
require 'twilio-ruby'

response = Twilio::TwiML::VoiceResponse.new
response.dial do |dial|
  dial.sip('sip:jack@example.com?x-mycustomheader=foo&x-myotherheader=bar')
end

puts response


text:
import {
    _hostDOMElms,
    _render
} from "./habitat";

const habitat = Widget => {
    // Widget represents the Preact component we need to mount
    let widget = Widget;
    // in case DOM has fired multipled readystate events, redner only once
    let hasRendered = false;
    // preact root render helper
    let root = null;

    let render = ({name = "data-widget", value = null, inline = true, clean = true} = {}) => {
        let elements = _hostDOMElms({name, value, inline, clean});
        if (!hasRendered && elements.length > 0) {
            hasRendered = true;
            return _render(widget, elements, root);
        }
        // document is not ready - subscurib to readystatechange event
        document.addEventListener('DOMContentLoaded', (e) => {
            let elements = _hostDOMElms({name, value, inline, clean});
            if (!hasRendered && elements.length > 0) {
                hasRendered = true;
                return _render(widget, elements, root);
            }
        })
    };

    return {render};
};

export default habitat;


text:
"""Functionality for uploading files to the server and managing them.
This is an extension of :mod:`lino.modlib.uploads`.

It currently works only when you also have coaching installed, but
that dependency should not be very difficult to remove.

.. autosummary::
   :toctree:

    models
    fixtures.std
    fixtures.demo2

"""

from lino.modlib.uploads import Plugin

class Plugin(Plugin):

    extends_models = ['UploadType', 'Upload']

    # needs_plugins = ['lino_xl.lib.clients']

    def setup_main_menu(config, site, user_type, m):
        mg = site.plugins.office
        m = m.add_menu(mg.app_label, mg.verbose_name)
        m.add_action('uploads.MyExpiringUploads')
        m.add_action('uploads.MyUploads')


text:
package com.jom;

import cern.colt.matrix.tdouble.DoubleFactory2D;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import cern.jet.math.tdouble.DoubleFunctions;

import java.util.HashSet;
import java.util.LinkedHashMap;

class _FUNCTION_ACOS extends Expression
{
	private final Expression a;
	private final boolean    isConstant;
	private final boolean    isLinear;

	_FUNCTION_ACOS(OptimizationProblem model, Expression a)
	{
		super(model);

		this.resize(a.getSize());

		this.isLinear = a.isConstant();
		this.isConstant = isLinear;
		if (isLinear)
		{
			/* change (destroy) the constant data in Expression a. This object keeps no reference to Expression a, but the data remains since we
			 * keep reference to the affine expression object of a, now modified by this function */
			double[] data = a.getAffineExpression().getConstantCoefArray();
			for (int cont = 0; cont < data.length; cont++) data[cont] = Math.acos(data[cont]);
			this.affineExp = new _INTERNAL_AffineExpressionCoefs(model, a.getSize(), data); //a.getAffineExpression();
		}
		this.a = (this.isLinear()) ? null : a; // if linear do not store the expressions. This info is already in the linear coefs matrix
	}

	@Override
	DoubleMatrixND nl_evaluate(double[] valuesDVs)
	{
		DoubleMatrix1D aValue = a.evaluate_internal(valuesDVs).elements();
		return new DoubleMatrixND(this.getSize(), aValue.assign(DoubleFunctions.acos));
	}

	@Override
	DoubleMatrix2D nl_evaluateJacobian(double[] valuesDVs)
	{
		DoubleMatrix1D a_value = a.evaluate_internal(valuesDVs).elements();
		DoubleMatrix2D a_jacobian = a.evaluateJacobian_internal(valuesDVs);
		return DoubleFactory2D.sparse.diagonal(a_value.assign(DoubleFunctions.square).assign(DoubleFunctions.neg).assign(DoubleFunctions.plus(1))
				.assign(DoubleFunctions.sqrt).assign(DoubleFunctions.inv).assign(DoubleFunctions.neg)).zMult(a_jacobian, null);
	}

	/* (non-Javadoc)
	 * @see Expression#isLinear()
	 */
	@Override
	boolean isLinear()
	{
		return isLinear;
	}

	/* (non-Javadoc)
	 * @see Expression#isConstant()
	 */
	@Override
	boolean isConstant()
	{
		return isConstant;
	}

	/* (non-Javadoc)
	 * @see Expression#getActiveVarIds()
	 */
	@Override
	LinkedHashMap<Integer, HashSet<Integer>> nl_getActiveVarIds()
	{
		return a.getActiveVarIds();
	}

}


text:
<META http-equiv="content-type" content="text/html;charset=iso-8859-9"/><meta name="viewport" content="width=device-width, initial-scale=1"><title>ac</title> <link rel="stylesheet"  href="css/jquery.mobile-1.2.0.css" />

MUHAMMED BÝN ABDULLAH EL-MÜRÞÝDÝ

Geri

Evliyanýn büyüklerinden, fýkýh ve kýraat alimi. Ýsmi, Muhammed bin Abdullah bin
Ebü'l-Mecd Ýbrahim el-Mürþidi olup, künyesi Ebu Abdullah'dýr. 1337 (H.738) senesi
Ramazan-ý
þerif ayýnda Münye'de vefat etti. Cenaze namazý çok kalabalýk oldu.

Muhammed el-Mürþidi, fýkýh ilmini Ziya bin Abdürrahim'den, kýraat ilmini et-Taki
es-Saig'den öðrendi. Þafii mezhebinde olan Muhammed el-Mürþidi, zühd ve takva sahibi idi.
Çok kerametleri görüldü. Münye'deki Beni Mürþid dergahýna çekilip, orada ibadetle meþgul
oldu. Ziyaretine gelenlere bizzat hizmet edip, yemek ikram ederdi. Gelen az olsun, çok olsun,
kimin hatýrýndan hangi yemek geçti ise getirip önlerine koyardý. Dergahýndaki mutfaðýna
kendisinden baþka kimse girmezdi. Hizmet ve ikramý karþýlýðýnda kimseden birþey kabul
etmezdi.

Zehebi onun hakkýnda; "Muhammed el-Mürþidi, haller ve kerametler sahibi idi. Misafirlerine
yemek ikram eder, canlarý ne istedi ise hemen getirirdi. Bu hizmeti kendisi yapardý.
Kimseden birþey kabul etmezdi. Ýtikadý saðlam ve çok ibadet ederdi" demektedir.

El-Ýmam el-Münavi þöyle anlatýr: "Muhammed el-Mürþidi, Mýsýr'daki alimlerin, velilerin
önderidir. Herkese iyilik eder, yemek yedirirdi. Kimseden birþey kabul etmezdi. Bir gecede,
misafirleri için yüz dinar kýymetinde lezzetli yemekler ikram etti. Hatta peþi peþine üç gece,
bin dinar kýymetinde olan yemekler hazýrladý. Kendisine nereden ve nasýl geldiði
anlaþýlmayan ve oralarda hiç olmayan yiyecek ve içeceklerle misafirlerine ikramda
bulunurdu. Onun kerametine inanmýyanlar, kendisini gördüklerinde, o fikirlerinden vazgeçip
talebe oldular. Dergahta namaz vakti girdiðinde, oraya gelenlerden tanýmadýðý birine ezan
okumasýný, diðerine imam olmasýný, baþkasýna da vaz ve nasihat etmesini emrederdi.
Yakýþýklý, yüzü nurlu, heybetli, güzel ahlak sahibi idi. Çok Kur'an-ý kerim okurdu. Hatýrýna
geleni söyler, en küçük bir yanlýþ yapmazdý. Ýtikadý düzgün olup, herkes tarafýndan hürmet ve
saygý görürdü. Kendisinin söz ve halleri bir baþkasýnda görülmedi."

Hatib Muhammed bin Merzuk et-Tilmsani þöyle anlatýr: "Babamýn hocalarýndan birisi de,
Muhammed el-Mürþidi idi. Bir yolculuðumuzda, on dokuz yaþýnda iken babam beni onun

dergahýna götürdü. Cuma günü idi. Pekçok alim, fakih, hatib orada toplanmýþtý. Namaz vakti
yaklaþýnca, alimler birbirine bakýp kim öne geçecek diye bekleþtiler. O esnada Muhammed
el-Mürþidi, kaldýðý odadan çýkýp, saða ve sola baktý. Babamýn arkasýnda olduðum halde,
nazarý bana eriþti ve; "Ey Muhammed yaklaþ!" buyurdu. Beni alýp kendi odasýna götürdü.
Orada, farz, sünnet ve namaz ile ilgili bazý bilgilerden anlattý. Kalkýp güzel bir abdest aldým.
Beraberce mescide çýktýk. Bana minberi gösterip; "Ey Muhammed, þimdi minbere çýk,
insanlara hutbe oku, nasihat et" buyurdu. Ben heyecanla; "Orada ne söylenir bilmem." diye
arzettiðimde; "Minbere çýk." buyurup, hatiblerin hutbede eline alýp dayandýklarý bir kýlýç
verdi. Müezzin ezaný bitirinceye kadar, ben kýlýca dayalý olarak ne söyliyeceðimi düþünmeye
baþladým. Ezan bitince, ayaða kalkýp Besmele okudum. Arkasýndan fasih bir þekilde hutbe
okumaya baþladým. Daha önce bilmediðim, duymadýðým þeyleri söyledim. Vazýmýn tesiri ile
cemaat büyük bir huþu' ve dikkat ile bana bakýyorlardý. Nihayet, hutbemi tamamlayýp
mimberden indim. Namazdan sonra Muhammed el-Mürþidi bana yaklaþýp; "Çok güzel bir
hutbe okudun. Tebrik ederim. Seni hutbe okumak ile vazifelendirdim" buyurdu. Daha sonra
oradan ayrýlýp babamla hacca gittik. Babam Mekke'de kalarak, benim geri dönmemi ve
Muhammed el-Mürþidi'ye uðrayýp duasýný almamý söyledi. Dönüþte Muhammed
el-Mürþidi'nin huzuruna çýktým. O, babamý sordu. Ben de; "Efendim, size selamý var.
Ellerinizden öpüyor." dedim. Bana; "Yaklaþ, þu hurma aðacýna dayan, zira Ebu Midyen
Abdullah, onun yanýnda üç sene kaldý." buyurdu ve sonra özel odasýna girdi. Bir müddet
sonra dýþarý çýktý ve bana oturmamý emretti. "Ey Muhammed! Biz senin babaný severiz. O,
bizim kardeþlerimizdendir. Ancak sen. Ancak sen..." buyurdu. Onun bu sözünden, ehl-i
dünya ile çok görüþüp bu sebeple zararda olduðumu anladým. Sonra bana; "Ey Muhammed!
Þu anda babanýn hasta olduðu vehmindesin. Halbuki baban sýhhat ve afiyettedir. O þimdi
Resulullah efendimizin mimberi þeriflerinin sað tarafýndadýr. Onun saðýnda Halil-ül-Maliki,
solunda Mekke kadýsý Ahmed bulunuyor. Memleketin Tlemsan'da da." deyip, yere bir daire
çizdi, etrafýnda dönüp; "Allahü teala orada, senin yakýnlarýný, akrabalarýný tehlikeden korudu,
himaye etti." dedikten sonra; "Yavrum, sen hatiblik yap. Ýleride Garbi Camiinde hatiblik
yapacaksýn. O cami, Ýskenderiyye'nin en büyük camisidir." buyurdu. Daha sonra yanýma,
yiyecek, içecek koyup, beni yolcu etti. Daha sonra Tlemsan'da hýsým ve akrabalarýmýn
korunduðu haberini aldým. Muhammed el-Mürþidi, tasarrufu kuvvetli bir zat idi. Onun
duasýnýn bereketiyle, iþlerimiz buyurduðu gibi oldu."

Muhammed el-Mürþidi, birgün etraftaki köylere haber gönderip, dergaha çaðýrdý. Köylülerin
hepsi geldi. O, odasýna girip uzun müddet kaldý. Gelenler ne olacaðýný merakla beklediler.
Fakat o, odasýndan çýkmadý. Nihayet merakla odasýna girildiðinde, vefat etmiþ olduðu
görüldü. Halbuki odasýna girerken hiçbir þeyi yoktu. Gelenler cenazesini yýkayýp namazýný
kýlýp, dergahýna defnettiler.

ÝBN-Ý BATTUTA
Ýbn-i Battuta þöyle anlatýr: "Ýskenderiyye'ye uðradýðýmda, Muhammed el-Mürþidi'nin
ziyaretine gittim. Dergahýna selam verip girdim. Beni kucakladý. Daha sonra namaz vakti
gelince, beni öne geçirip imam yaptý. Misafir gelenlerden birini imam yapmak adeti imiþ.
Yatma vakti geldiðinde, bana dergahýn damýna çýkýp orada uyumamý tenbih etti. Dama çýkýp
orada uyudum. Rüyamda, kanatlanýp, kýble istikametine doðru uçtuðumu gördüm. Bu rüya
sebebiyle hayrete düþtüm. Muhammed el-Mürþidi, sabah namazýnda beni tekrar imam yaptý.
Sonra da rüyamý
þöyle tabir etti: "Sen hacca gideceksin, Resul-i ekremin ravda-i
mutahheralarýný ziyaret edip, Yemen, Irak, Horasan, Hindistan taraflarýna gidip, uzun seneler
oralarda kalacaksýn. Dilþar Hindi adlý kardeþin, seni bazý tehlikelerden koruyacak." Daha
sonra bana biraz azýk ve para verip, beni yolcu etti. Aynen buyurduðu gibi oldu. Dualarýndan
çok istifade ettim. O, salih, abid (çok ibadet eden) bir zat idi. Ýnsanlarla az görüþür ve onlara

yemek ikram ederdi. Keþf ve keramet sahibi olup, evliyanýn önde gelenlerinden idi.
Münye'de Beni Mürþid Dergahýnda yaþadý. Kendisinin bir hizmetçisi yoktu. Kerametlerini ve
üstünlüðünü iþitenler, ziyaretine koþtu. Devlet adamlarý, komutanlar ve halktan birçok kimse
kafileler halinde onu ziyaret için dergahýna geldiler. Hergün dergahý dolup taþtý. Her birinin
hatýrýndan geçen yemeði önüne getirip ikram etti. Mutfaðýna ondan baþkasý girmezdi."

1) Tabakat-ül-Evliya; s.568

2) El-Vafi bil-Vefeyat; c.3, s.272

3) Ed-Dürer-ül-Kamine; c.3, s.462

4) Tabakat-üþ-Þafiiyye; c.9, s.154

5) Hüsn-ül-Muhadara; c.1, s.525

6) Þezerat-üz-Zeheb; c.6, s.116

7) Mir'at-ül-Cinan; c.4, s.292

8) En-Nücum-üz-Zahire; c.9, s.313

9) Camiu Keramat-il-Evliya; c.1, s.140

10) El-Bidaye ven-Nihaye; c.14, s.179

11) Ýslam Alimleri Ansiklopedisi; c.10, s.300


text:
import java.util.*;

class Test {

  private String returnStatement(String in) {
    return (Optional.ofNullable<caret>(in).orElse("foo"));
  }

  private void assignment(String in) {
    String out = null;
    out = (Optional.ofNullable((in)).orElse("foo"));
  }

  private void declaration(String in) {
    String out = (Optional.ofNullable(in).orElse("foo"));
  }

  private void statement(String in) {
    (Optional.ofNullable(in).ifPresent(v -> System.out.println(v)));
  }

  private void statementWithResult(String in) {
    (Optional.of(in).orElse("foo"));
  }

  private String partialChain(Optional<String> optional) {
    return optional.orElse("foo");
  }
}


text:
module ActsAsXls
  class Engine < Rails::Engine

    #initializer 'usefull_table.helper' do |app|
    #  ActiveSupport.on_load(:action_controller) do
    #    include UsefullTableHelper
    #  end
    #  ActiveSupport.on_load(:action_view) do
    #    include UsefullTableHelper
    #  end
    #
    #end
  end
end

require "acts_as_xls/renderer"
require "acts_as_xls/base"


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Polarity</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Polarity: whether the word can be or is negated

In Turkish verbs are negated with the suffix -mA (and its allomorphs).
Only exception is the verb/particle değil which functions as an auxiliary or copula
(it is the main means of negating a copular clause, but it can also be used to negate a verbal clause).
değil is marked as Negative=Neg when it is used as a copula or auxiliary.
We use the POS tag particle when değil is used for negating non-predicates,
in which case we use the feature PronType for marking its negativity.

In Turkish adjectives are normally negated by forming adjectival
clauses with copula ol-, e.g., verimli olmayan "unproductive"
(lit: "(something) that is not productive").
A non-productive prefix (of Arabic origin), na-, can be used for negating a lexicalized set of adjectives, e.g., namüsait "not suitable".
We (currently) do not mark adjectives for the Polarity feature.

Pos: positive, affirmative

Examples

Okuyacak "he/she will read"

Ali doktor "Ali is a doctor"

Neg: negative

Examples

Okumayacak "he/she will not read"

Ali doktor değil "Ali is not a doctor"

Polarity in other languages:

[bej]

[bg]

[bm]

[cs]

[el]

[et]

[fi]

[fr]

[ga]

[gd]

[gub]

[hy]

[pcm]

[qpm]

[ru]

[sl]

[sv]

[tr]

[tt]

[u]

[uk]

[urj]

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
namespace net {

namespace {

class DefaultRandom : public QuicRandom {
 public:
  static DefaultRandom* GetInstance();

  // QuicRandom implementation
  void RandBytes(void* data, size_t len) override;
  uint64_t RandUint64() override;
  void Reseed(const void* additional_entropy, size_t entropy_len) override;

 private:
  DefaultRandom() {}
  ~DefaultRandom() override {}

  friend struct base::DefaultSingletonTraits<DefaultRandom>;
  DISALLOW_COPY_AND_ASSIGN(DefaultRandom);
};

DefaultRandom* DefaultRandom::GetInstance() {
  return base::Singleton<DefaultRandom>::get();
}

void DefaultRandom::RandBytes(void* data, size_t len) {
  crypto::RandBytes(data, len);
}

uint64_t DefaultRandom::RandUint64() {
  uint64_t value;
  RandBytes(&value, sizeof(value));
  return value;
}

void DefaultRandom::Reseed(const void* additional_entropy, size_t entropy_len) {
  // No such function exists in crypto/random.h.
}

}  // namespace

// static
QuicRandom* QuicRandom::GetInstance() {
  return DefaultRandom::GetInstance();
}

}  // namespace net


text:
package us.vistacore.vxsync.vler;

import com.codahale.metrics.annotation.Timed;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicLong;

@Path("/vler")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class VxVlerResource {
    private final String template;
    private final String defaultName;
    private final AtomicLong counter;

    public VxVlerResource(String template, String defaultName) {
        this.template = template;
        this.defaultName = defaultName;
        this.counter = new AtomicLong();
    }

    @POST
    @Timed
    public String process(String testData) {
        return testData;
    }
}


text:
<?php
namespace Craft;

/**
 *
 */
class ElementType
{
	const Asset       = 'Asset';
	const Entry       = 'Entry';
	const GlobalSet   = 'GlobalSet';
	const MatrixBlock = 'MatrixBlock';
	const Tag         = 'Tag';
	const User        = 'User';
}


text:
package com.rarchives.ripme.tst.ripper.rippers;

import java.io.IOException;
import java.net.URL;

import com.rarchives.ripme.ripper.rippers.video.StickyXXXRipper;
// import com.rarchives.ripme.tst.ripper.rippers.RippersTest;
import com.rarchives.ripme.utils.Utils;

public class StickyXXXRipperTest extends RippersTest {

    public void testStickyXXXVideo() throws IOException {
        // This test fails on the CI - possibly due to checking for a file before it's written - so we're skipping it
        if (Utils.getConfigBoolean("test.run_flaky_tests", false)) {
            StickyXXXRipper ripper = new StickyXXXRipper(new URL("http://www.stickyxxx.com/a-very-intense-farewell/"));
            testRipper(ripper);
        }
    }

}


text:
<?php
namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Admin\AdminController;
use App\Models\SysConfig;
use Illuminate\Support\Facades\Cache;

class SysConfigController extends AdminController
{
	public function newEntity(array $attributes = [])
	{
		// TODO: Implement newEntity() method.
		return new SysConfig($attributes);
	}

	/**
	* Display a listing of the resource.
	*
	* @return  \Illuminate\Http\Response
	*/
	public function index()
	{
		//
		return view('admin.sys-config.index');
	}

	/**
	* Show the form for creating a new resource.
	*
	* @return  \Illuminate\Http\Response
	*/
	public function create()
	{
		return view('admin.sys-config.create');
	}

	/**
	* Display the specified resource.
	*
	* @param    int  $id
	* @return  \Illuminate\Http\Response
	*/
	public function edit($id)
	{
		$entity = SysConfig::find($id);
		return view('admin.sys-config.edit', ['entity' => $entity]);
	}

	/**
	* Display the specified resource.
	*
	* @param    int  $id
	* @return  \Illuminate\Http\Response
	*/
	public function show($id)
	{
		//
	}

	/**
	 * @param  Request $request
	 * @param  array $searchCols
	 * @param array $with
	 * @param null $conditionCall
	 * @param bool $all_columns
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function pagination(Request $request, $searchCols = [], $with=[], $conditionCall = null, $all_columns = false){
		$searchCols = ["desc","name","value"];
		return parent::pagination($request, $searchCols);
	}

	protected function afterSave($model){
		Cache::forget($model->name);
	}

}


text:
"""MNIST handwritten digits dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python.keras.utils.data_utils import get_file
from tensorflow.python.util.tf_export import tf_export

@tf_export('keras.datasets.mnist.load_data')
def load_data(path='mnist.npz'):
  """Loads the MNIST dataset.

  Arguments:
      path: path where to cache the dataset locally
          (relative to ~/.keras/datasets).

  Returns:
      Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
  """
  path = get_file(
      path,
      origin='https://s3.amazonaws.com/img-datasets/mnist.npz',
      file_hash='8a61469f7ea1b51cbae51d4f78837e45')
  f = np.load(path)
  x_train, y_train = f['x_train'], f['y_train']
  x_test, y_test = f['x_test'], f['y_test']
  f.close()
  return (x_train, y_train), (x_test, y_test)


text:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Common;
using NuGet.ProjectModel;

namespace Microsoft.DotNet.Cli.Utils
{
    public static class LockFileFormatExtensions
    {
        public static async Task<LockFile> ReadWithLock(this LockFileFormat subject, string path)
        {
            return await ConcurrencyUtilities.ExecuteWithFileLockedAsync(
                path,
                lockedToken =>
                {
                    if (!File.Exists(path))
                    {
                        throw new GracefulException(string.Join(
                            Environment.NewLine,
                            string.Format(LocalizableStrings.FileNotFound, path),
                            LocalizableStrings.ProjectNotRestoredOrRestoreFailed));
                    }

                    var lockFile = FileAccessRetrier.RetryOnFileAccessFailure(() => subject.Read(path));

                    return lockFile;
                },
                CancellationToken.None);
        }
    }
}


text:
{{name}}

    Click on a row to toggle expand/collapse.

    SCROLL TO:
    {{percent}}%


text:
//--------------------------------------
// XerialJ
//
// VariableLengthInteger.java
// Since: 2005/07/21 14:59:45
//
// $URL$
// $Author$
//--------------------------------------
package org.xerial.db;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.Vector;

import org.xerial.core.XerialException;
import org.xerial.db.cache.Buffer;
import org.xerial.db.cache.BufferWriter;
import org.xerial.db.datatype.TypeInformation;

/**
 * Variable length number representation.
 * When the most significant bit (MSB) of a byte is 0, it means the termination of the value,
 * when the MSB of a byte is 1, its following bytes must be read to compute the value.
 *
 * 0XXXXXXX                     :   [0, 127 (= M1 - 1)]
 * 1XXXXXXX 0XXXXXXX            :   [M1, M1 + 127 * 2^7 + 127 (= M2-1)]
 * 1XXXXXXX 1XXXXXXX 0XXXXXXX   :   [M2, M2 + 127 * 2^14 + 127 * 2^7 + 127]
 *
 * [0, 0 + (2 ^ 7 - 1) = 127]
 * [128, 128 + (2^14 - 1) = 16511]
 * [16512, 16512 + (2^21 - 1) = 2113663]
 * @author leo
 *
 */
public class VariableLengthInteger
{
    static private int[] upperBoundByByteSize;
    static
    {
        Vector<Integer> upperBoundArray = new Vector<Integer>();
        BigInteger previousMaximum = BigInteger.ZERO;
        BigInteger intMax = BigInteger.valueOf(Integer.MAX_VALUE);

        int byteSize = 1;
        BigInteger valueRange = BigInteger.ZERO;
        while(previousMaximum.compareTo(intMax) < 0)
        {
            valueRange = BigInteger.ZERO.setBit(byteSize++ * 7);
            previousMaximum = previousMaximum.add(valueRange);
            if(previousMaximum.compareTo(intMax) > 0)
                break;
            upperBoundArray.add(previousMaximum.subtract(BigInteger.ONE).intValue());
        }

        upperBoundByByteSize = new int[upperBoundArray.size()];
        int i = 0;
        for(int val : upperBoundArray)
        {
            upperBoundByByteSize[i++] = val;
        }
    }

    byte[] _binaryRepresentation = null;
    public VariableLengthInteger(int value)
    {
        translate(value);
    }

    public VariableLengthInteger(byte[] byteArray, int offset) throws DBException
    {
        translate(byteArray, offset);
    }

    public byte[] getByte()
    {
        assert _binaryRepresentation != null;
        return _binaryRepresentation;
    }
    public int size()
    {
        assert _binaryRepresentation != null;
        return _binaryRepresentation.length;
    }

    public int intValue()
    {
        assert _binaryRepresentation != null;
        int value = 0;
        for(int i=0; i<_binaryRepresentation.length; i++)
        {
            value <<= 7;
            value |= _binaryRepresentation[i] & 0x7F;
        }
        if(_binaryRepresentation.length > 1)
        value += upperBoundByByteSize[_binaryRepresentation.length - 2] + 1;
        return value;
    }

    private void translate(int value)
    {
        int byteSize;
        for(byteSize = 1; byteSize <= upperBoundByByteSize.length; byteSize++)
        {
            if(value <= upperBoundByByteSize[byteSize-1])
                break;
        }

        if(byteSize > 1)
            value -= upperBoundByByteSize[byteSize-2] + 1;   // subtract offset

        _binaryRepresentation = new byte[byteSize];
        int mask = 0x7F << ((byteSize - 1) * 7);
        for(int i=0; i<byteSize; i++)
        {
            _binaryRepresentation[i] = (byte) ((value & mask) >> ((byteSize - (i + 1)) * 7));
            mask >>= 7;
        }
        for(int i=0; i<_binaryRepresentation.length-1; i++)
        {
            _binaryRepresentation[i] |= 0x80;
        }

    }

    public static int byteSize(byte[] buffer, int offset) throws DBException
    {
        int byteLength = 1;
        int index = offset;
        while((buffer[index++] & 0x80) != 0)
        {
            byteLength++;
            if(byteLength > upperBoundByByteSize.length)
            {
                throw new DBException(DBErrorCode.InvalidDataFormat, "cannot read the variable length integer whose bite size is larger than " + upperBoundByByteSize.length);
            }
        }
        return byteLength;

    }

    /**
     * Gets the byte size of the value as an variable length integer
     * @param value
     * @return
     */
    public static int byteSize(int value)
    {
        int byteSize;
        for(byteSize = 1; byteSize <= upperBoundByByteSize.length; byteSize++)
        {
            if(value <= upperBoundByByteSize[byteSize-1])
                break;
        }
        return byteSize;
    }

    public static int readFrom(byte[] buffer, int offset) throws DBException
    {
        int value = 0;
        int byteLength = byteSize(buffer, offset);
        if(byteLength > TypeInformation.INT_SIZE)
        {
            if(!(byteLength == (TypeInformation.INT_SIZE + 1) && (buffer[offset] > 0x87)))  // 1000 0111
                throw new DBException(DBErrorCode.InvalidDataFormat, "value larger than 2^31-1 cannot be read");
        }

        for(int i=0; i<byteLength; i++)
        {
            value <<= 7;
            value |= buffer[offset+i] & 0x7F;
        }

        return value;
    }

    public static VariableLengthInteger readFrom(ByteArrayInputStream buffer) throws DBException
    {
        byte[] byteArray = new byte[upperBoundByByteSize.length];
        int size = 0, b;
        while(((b = buffer.read()) & 0x80) != 0)
        {
            byteArray[size++] = (byte) b;
        }
        return new VariableLengthInteger(byteArray, 0);
    }

    private void translate(byte[] byteArray, int offset) throws DBException
    {
        int index = offset;
        while(index < byteArray.length)
        {
            if(((int) byteArray[index] & 0x80) == 0)
            {
                int byteSize = index - offset + 1;
                _binaryRepresentation = new byte[byteSize];
                for(int i=0; i<byteSize; i++)
                    _binaryRepresentation[i] = byteArray[offset+i];
                return;
            }
            index++;
        }
        throw new DBException(DBErrorCode.InvalidDataFormat, "invalid code");
    }

    public int writeTo(BufferWriter writer)
    {
        for(int i=0; i<_binaryRepresentation.length; i++)
        {
            writer.writeByte(_binaryRepresentation[i]);
        }
        return _binaryRepresentation.length;
    }

}


text:
from threading import Thread

import rospy

# import Aldebaran API (must be in PYTHONPATH):
try:
    from naoqi import ALProxy
except ImportError:
    raise RuntimeError("Error importing NaoQI. Please make sure that Aldebaran's NaoQI API is in your PYTHONPATH.")

class NaoqiNode(Thread):
    """
    A ROS Node wrapper that can help you connect to NAOqi and deal with ROS shutdown
    To start your node, just call:
    my_node = MyNode('my_node')
    my_node.start() # that will spawn your node in a thread (and run whatever is in the run() function
    rospy.spin()
    # when killing ROS, the node will automatically stop its main loop, exit, and then unsubscribe from ALMemory events
    # and call whatever you have in unsubscribe()
    Then, if your node needs to process data, you just needs to have a run function:

    def run(Self):
        #do some initialization
        while self.is_looping():
            # do something
        # do some post processing
    """
    def __init__(self, name):
        """
        :param name: the name of the ROS node
        """
        super(NaoqiNode, self).__init__()

        # A distutils.version.LooseVersion that contains the current verssion of NAOqi we're connected to
        self.__naoqi_version = None
        self.__name = name

        ## NAOqi stuff
        # dict from a modulename to a proxy
        self.__proxies = {}

        # Initialize ros, before getting parameters.
        rospy.init_node(self.__name)

        # If user has set parameters for ip and port use them as default
        default_ip = rospy.get_param("~pip", "127.0.0.1")
        default_port = rospy.get_param("~pport", 9559)

        # get connection from command line:
        from argparse import ArgumentParser
        parser = ArgumentParser()
        parser.add_argument("--pip", dest="pip", default=default_ip,
                          help="IP/hostname of parent broker. Default is 127.0.0.1.", metavar="IP")
        parser.add_argument("--pport", dest="pport", default=default_port, type=int,
                          help="port of parent broker. Default is 9559.", metavar="PORT")

        import sys
        args, unknown = parser.parse_known_args(args=rospy.myargv(argv=sys.argv)[1:])
        self.pip = args.pip
        self.pport = args.pport

        ## ROS stuff
        self.__stop_thread = False
        # make sure that we unregister from everything when the module dies
        rospy.on_shutdown(self.__on_ros_shutdown)

    def __on_ros_shutdown(self):
        """
        Callback function called whenever rospy.spin() stops
        """
        rospy.loginfo('Stopping ' + self.__name)

        self.__stop_thread = True
        # wait for the thread to be done
        if self.is_alive():
            self.join()

        rospy.loginfo(self.__name + ' stopped')

    def run(self):
        """
        This is a virtual method that corresponds to the code of the Node that runs continuously
        It should have a while loop calling the self.is_looping() function
        """
        """
        # code example
        #do some initialization
        while self.is_looping():
            # do something
        # do some post processing
        """
        raise NotImplementedError('Implement the run function of your NaoNode !')

    def is_looping(self):
        """
        :return: whether the thread is supposed to be running
        """
        return not self.__stop_thread

    def get_proxy(self, name, warn=True):
        """
        Returns a proxy to a specific module. If it has not been created yet, it is created
        :param name: the name of the module to create a proxy for
        :return: a proxy to the corresponding module
        """
        if name in self.__proxies and self.__proxies[name] is not None:
            return self.__proxies[name]

        proxy = None
        try:
            proxy = ALProxy(name,self.pip,self.pport)
        except RuntimeError,e:
            if warn:
                rospy.logerr("Could not create Proxy to \"%s\". \nException message:\n%s",name, e)

        self.__proxies[name] = proxy
        return proxy

    def get_version(self):
        """
        Returns the NAOqi version.
        A proxy for ALMemory is automatically created if needed as self.memProxy.
        You can then simply have code that runs or not depending on the NAOqi version.
        E.g. if distutils.version.LooseVersion('1.6') < get_version()    ....
        :return: a distutils.version.LooseVersion object with the NAOqi version
        """
        if self.__naoqi_version is None:
            proxy = self.get_proxy('ALMemory')
            if proxy is None:
                # exiting is bad but it should not happen
                # except maybe with NAOqi versions < 1.6 or future ones
                # in which case we will adapt that code to call the proper
                # version function
                exit(1)

            from distutils.version import LooseVersion
            self.__naoqi_version = LooseVersion(proxy.version())

        return self.__naoqi_version