text:
package splice.ga;

import java.util.Comparator;

import splice.InitializeComponent;
import splice.RandomUtil;

/**
 * Base class for chromosomes, it doesn't support the mutator/crossover
 * interfaces. You may find it easier to customize the behavior of a single
 * individual using this class as you have to implement by yourself the logic
 * behind the crossover and mutation. It is also good when you need a better
 * performance as it makes fewer abstractions than its derivatives.
 * Besides the fitness value, by default no other
 * value is hold by this class.
 *
 * @author Igor Almeida
 *
 */
public abstract class BasicChromosome implements Comparable<BasicChromosome>, InitializeComponent, Cloneable {
	double fitness = Double.MIN_VALUE;
    private long fitnessBits;
	private boolean calculated = false;

	/**
	 * Implementation of the fitness function
	 *
	 * @return the fitness for the chromosome
	 */
    protected abstract double fitness();

	/**
	 * Implementation of the chromosome's mutation logic
	 */
	protected abstract void mutate();

	/**
	 * Performs the chromosome's crossover with a given chromosome
	 *
	 * @param chromosome other chromosome to make crossover with
	 * @return one child of the crossover operation
	 */
	public abstract BasicChromosome crossover(BasicChromosome chromosome);

    public BasicChromosome clone() {
        try {
            return (BasicChromosome)super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

	/**
	 * Calculate the chromosome's fitness
	 * @return fitness value as calculated by #{fitness()}
	 */
	public final double calculateFitness() {
		if (calculated)
			return fitness;

        fitness = fitness();

		// checks if is a NaN
		if (fitness != fitness)
			throw new NumberFormatException("The fitness can't be a NaN");

        fitnessBits = Double.doubleToLongBits(fitness);
		calculated = true;

		return fitness;
	}

	public double getFitness() {
		return fitness;
	}

    public long getFitnessBits() {
        return fitnessBits;
    }

    public void resetFitness() {
        fitness = Double.MIN_VALUE;
    }

	@Override
	public void initialize() { }

	@Override
	public int compareTo(BasicChromosome o) {
		if (fitness == o.fitness)
			return 0;
		if (fitness > o.fitness)
			return 1;
		return -1;
	}

	public Comparator<BasicChromosome> getComparator() {
		return new ChromosomeFitnessComparator(fitness);
	}

	/**
	 * Mutates the chromosome with a given probability
	 * @param chance the probability of mutation
	 */
	public void mutate(double chance) {
		if (RandomUtil.getRandom().nextDouble() < chance)
			mutate();
	}

    public String toString() {
        return Double.toString(fitness());
    }
}


text:
mod tests;

use maths::Vec3D;
use utils::{UniqueVec3DGenerator, UnitVec3DGenerator};
use collisions::CollisionData;
use collisions::shapes::{Direction, SupportMap};
use collisions::detection::gjkepa::{GJKSimplex, MinkowskiDifference};

#[derive(Clone, Debug)]
pub struct ContactTracker {
    simplex: GJKSimplex,
}

impl ContactTracker {
    pub fn new(data_0: &CollisionData, data_1: &CollisionData) -> ContactTracker {
        let diff = MinkowskiDifference(data_0, data_1);
        let mut generator = UnitVec3DGenerator::new();

        let mut counter = 0;
        while counter < 1000 {
            let unique_vertices_iter = UniqueVec3DGenerator::new(|| {
                let guess = Direction::from(generator.gen_next());

                diff.support_points_iter(guess).next().unwrap()
            });

            let unique_vertices: Vec<Vec3D> = unique_vertices_iter.take(4).collect();

            if let Ok(simplex) = GJKSimplex::from_vertices(unique_vertices[0], unique_vertices[1], unique_vertices[2], unique_vertices[3]) {
                return ContactTracker {
                    simplex: simplex,
                };
            }

            counter += 1;
        }

        panic!("took more than 1000 iterations to construct a GJKSimplex");
    }

    #[inline(always)]
    pub fn simplex(&self) -> &GJKSimplex {
        &self.simplex
    }

    #[inline(always)]
    pub fn simplex_mut(&mut self) -> &mut GJKSimplex {
        &mut self.simplex
    }
}

redpajama_set_name: RedPajamaGithub


text:
var _curry2 = require('./internal/_curry2');

/**
 * Creates a new list out of the two supplied by pairing up
 * equally-positioned items from both lists.  The returned list is
 * truncated to the length of the shorter of the two input lists.
 * Note: `zip` is equivalent to `zipWith(function(a, b) { return [a, b] })`.
 *
 * @func
 * @memberOf R
 * @since v0.1.0
 * @category List
 * @sig [a] -> [b] -> [[a,b]]
 * @param {Array} list1 The first array to consider.
 * @param {Array} list2 The second array to consider.
 * @return {Array} The list made by pairing up same-indexed elements of `list1` and `list2`.
 * @example
 *
 *      R.zip([1, 2, 3], ['a', 'b', 'c']); //=> [[1, 'a'], [2, 'b'], [3, 'c']]
 */
module.exports = _curry2(function zip(a, b) {
  var rv = [];
  var idx = 0;
  var len = Math.min(a.length, b.length);
  while (idx < len) {
    rv[idx] = [a[idx], b[idx]];
    idx += 1;
  }
  return rv;
});


text:
/**
 * LibUser class
 * fetchs and renders a user's library
 * @author adrienjoly, whyd
 **/

var config = require('../models/config.js');
var userModel = require('../models/user.js');
var followModel = require('../models/follow.js');
var postModel = require('../models/post.js');
var feedTemplate = require('../templates/feed.js');

const playlistRenderer = require('./LibUserPlaylist.js');
const profileRenderer = require('./LibUserProfile.js');

// DATA FETCHING HELPERS

function fetchPlaylists(options) {
  return new Promise((resolve) =>
    userModel.fetchPlaylists(options.user, {}, function (playlists) {
      resolve(playlists);
    })
  );
}

function fetchLikes(options, callback) {
  postModel.countLovedPosts(options.user.id, function (count) {
    options.user.nbLikes = count;
    callback();
  });
}

function fetchStats(options, callback) {
  followModel.countSubscriptions(options.user.id, function (nbSubscriptions) {
    followModel.countSubscribers(options.user.id, function (nbSubscribers) {
      options.subscriptions = {
        nbSubscriptions: nbSubscriptions,
        nbSubscribers: nbSubscribers,
      };
      followModel.get(
        { uId: options.loggedUser.id, tId: options.user.id },
        function (err, res) {
          options.user.isSubscribed = !!res;
          callback();
        }
      );
    });
  });
}

function fetchNbTracks(options, callback) {
  postModel.countUserPosts(options.user.id, function (nbPosts) {
    options.user.nbTracks =
      nbPosts > 9999 ? Math.floor(nbPosts / 1000) + 'k' : nbPosts;
    callback();
  });
}

// PAGE RENDERING

function generateMixpanelCode(options) {
  return /*options.uid == options.loggedUser.id ? "" :*/ [
    '<script>',
    ' window.Whyd.tracking.log("Visit profile", "' + options.uid + '");',
    '</script>',
  ].join('\n');
}

var bareFormats = new Set(['json', 'links']);

function fetchAndRender(options, callback) {
  options.bodyClass = '';

  populatePaginationParameters(options);

  const renderer = options.playlistId ? playlistRenderer : profileRenderer;
  renderer.fetchAndRender(options, (err, posts) => {
    if (err) return callback(err);
    if (bareFormats.has(options.format)) return callback(posts);
    if (!options.format && !options.embedW) {
      renderer.prepareTemplate(options);
    }
    feedTemplate.renderFeedAsync(posts, options, callback);
  });
}

// MAIN FUNCTION

var LNK_URL_PREFIX = {
  fb: 'facebook.com/',
  tw: 'twitter.com/',
  sc: 'soundcloud.com/',
  yt: 'youtube.com/user/',
  igrm: 'instagram.com/',
};

function populatePaginationParameters(options) {
  options.fetchParams = {
    after: options.after,
    before: options.before,
    limit: options.limit,
  };
  if (options.embedW)
    options.fetchParams.limit = config.nbTracksPerPlaylistEmbed;
  else if (options.limit && typeof options.limit !== 'number') {
    if (typeof options.limit === 'string')
      options.fetchParams.limit = parseInt(options.limit);
    else if (typeof options.limit === 'object' && options.limit.push)
      options.fetchParams.limit = parseInt(options.limit.pop());
    // keep only the last value
    // see https://github.com/openwhyd/openwhyd/issues/89
  }
}

function renderUserLinks(lnk) {
  // clean social links
  for (let i in lnk) lnk[i] = ('' + lnk[i]).trim();

  // for each social link, detect username and rebuild URL
  for (let i in LNK_URL_PREFIX)
    if (lnk[i]) {
      var parts = lnk[i].split('?').shift().split('/');
      lnk[i] = ''; // by default, if no username was found
      var username = '';
      while (!(username = parts.pop()));
      //for (let j=parts.length-1; j>-1; --j)
      //	if (parts[j]) {
      lnk[i] = LNK_URL_PREFIX[i] + username; //parts[j];
      //break;
      //	}
    }

  // make sure URLs are valid
  for (let i in lnk)
    if (lnk[i]) {
      var lnkBody = '//' + lnk[i].split('//').pop();
      if (i == 'home') {
        var isHttps = lnk[i].match(/^https:\/\//);
        lnk[i] = (isHttps ? 'https' : 'http') + ':' + lnkBody;
      } else {
        lnk[i] = lnkBody;
      }
    } else delete lnk[i];

  if (lnk.home)
    lnk.home = {
      url: lnk.home,
      renderedUrl: lnk.home.split('//').pop().split('/').shift(), //uiSnippets.shortenURLs(lnk.home).replace("...", "")
    };
}

function renderResponse(feed, options, lib, user) {
  if (options.callback) {
    var safeCallback = options.callback.replace(/[^a-z0-9_]/gi, '');
    const data = options.showPlaylists ? options.playlists : feed;
    lib.renderOther(
      safeCallback + '(' + JSON.stringify(data) + ')',
      'application/javascript'
    );
  } else if (options.format == 'links') {
    lib.renderOther(
      feed
        .map(function (p) {
          return config.translateEidToUrl((p || {}).eId);
        })
        .join('\n'),
      'text/text'
    );
  } else if (options.showPlaylists && options.format == 'json') {
    lib.renderJson(options.playlists);
  } else if (options.format == 'json') {
    lib.renderJson(feed);
  } else if (!feedTemplate.shouldRenderWholeProfilePage(options)) {
    lib.render({ html: feed });
  } else
    lib.renderPage(
      user,
      null /*sidebarHtml*/,
      generateMixpanelCode(options) + feed
    );
}

async function renderUserLibrary(lib, user) {
  var options = lib.options;

  if (user == null) return lib.render({ errorCode: 'USER_NOT_FOUND' });

  options.pageUrl = options.pageUrl.replace(
    '/' + user.handle,
    '/u/' + user._id
  );

  options.uid = '' + user._id;
  options.user = user;
  options.displayPlaylistName = !options.playlistId;

  if (options.user && options.user.lnk) renderUserLinks(options.user.lnk);

  // prepend required fetching operations in head of the call chain
  if (feedTemplate.shouldRenderWholeProfilePage(options)) {
    options.user.pl = await fetchPlaylists(options);
    await new Promise((resolve) => fetchStats(options, resolve));
    await new Promise((resolve) => fetchLikes(options, resolve));
    await new Promise((resolve) => fetchNbTracks(options, resolve));
  }
  const feed = await new Promise((resolve) => fetchAndRender(options, resolve));
  renderResponse(feed, options, lib, user);
}

exports.render = renderUserLibrary;


text:
require 'rubygems'
require './lib/dianxin'

@dianxin = Dianxin::Base.new('apid', 'key', 'productid')
puts @dianxin.inspect
@dianxin.sms('phone number', '你好')


text:
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// WARNING: This test was generated by generate_feature_test_macro_components.py
// and should not be edited manually.

// <string_view>

// Test the feature test macros defined by <string_view>

/*  Constant                    Value
    __cpp_lib_char8_t           201811L [C++2a]
    __cpp_lib_constexpr_misc    201811L [C++2a]
    __cpp_lib_string_view       201606L [C++17]
*/

#include <string_view>
#include "test_macros.h"

#if TEST_STD_VER < 14

# ifdef __cpp_lib_char8_t
#   error "__cpp_lib_char8_t should not be defined before c++2a"
# endif

# ifdef __cpp_lib_constexpr_misc
#   error "__cpp_lib_constexpr_misc should not be defined before c++2a"
# endif

# ifdef __cpp_lib_string_view
#   error "__cpp_lib_string_view should not be defined before c++17"
# endif

#elif TEST_STD_VER == 14

# ifdef __cpp_lib_char8_t
#   error "__cpp_lib_char8_t should not be defined before c++2a"
# endif

# ifdef __cpp_lib_constexpr_misc
#   error "__cpp_lib_constexpr_misc should not be defined before c++2a"
# endif

# ifdef __cpp_lib_string_view
#   error "__cpp_lib_string_view should not be defined before c++17"
# endif

#elif TEST_STD_VER == 17

# ifdef __cpp_lib_char8_t
#   error "__cpp_lib_char8_t should not be defined before c++2a"
# endif

# ifdef __cpp_lib_constexpr_misc
#   error "__cpp_lib_constexpr_misc should not be defined before c++2a"
# endif

# ifndef __cpp_lib_string_view
#   error "__cpp_lib_string_view should be defined in c++17"
# endif
# if __cpp_lib_string_view != 201606L
#   error "__cpp_lib_string_view should have the value 201606L in c++17"
# endif

#elif TEST_STD_VER > 17

# if defined(__cpp_char8_t)
#   ifndef __cpp_lib_char8_t
#     error "__cpp_lib_char8_t should be defined in c++2a"
#   endif
#   if __cpp_lib_char8_t != 201811L
#     error "__cpp_lib_char8_t should have the value 201811L in c++2a"
#   endif
# else
#   ifdef __cpp_lib_char8_t
#     error "__cpp_lib_char8_t should not be defined when defined(__cpp_char8_t) is not defined!"
#   endif
# endif

# if !defined(_LIBCPP_VERSION)
#   ifndef __cpp_lib_constexpr_misc
#     error "__cpp_lib_constexpr_misc should be defined in c++2a"
#   endif
#   if __cpp_lib_constexpr_misc != 201811L
#     error "__cpp_lib_constexpr_misc should have the value 201811L in c++2a"
#   endif
# else // _LIBCPP_VERSION
#   ifdef __cpp_lib_constexpr_misc
#     error "__cpp_lib_constexpr_misc should not be defined because it is unimplemented in libc++!"
#   endif
# endif

# ifndef __cpp_lib_string_view
#   error "__cpp_lib_string_view should be defined in c++2a"
# endif
# if __cpp_lib_string_view != 201606L
#   error "__cpp_lib_string_view should have the value 201606L in c++2a"
# endif

#endif // TEST_STD_VER > 17

int main(int, char**) { return 0; }


text:
"""A frame ranger parser

A frame ranger parser that parses, adds and removes frame ranges

Classes
-------
Frange
    A class that represents a frame range
FrangeError
    Syntax error when parsing a frame range

Examples
--------
    >>> # create an instance of Frange
    >>> from dpa.frange import Frange
    >>> f = Frange("-2-8:2")
    >>> print f
    [-2-8:2]

    >>> # add a frame range
    >>> f.add("3, 5")
    >>> print f
    [-2-2:2, 3-6, 8]

    >>> # remove a frame range
    >>> f.remove("4-8")
    >>> print f5
    [-2-2:2, 3]

"""

# -----------------------------------------------------------------------------
# Imports:
# -----------------------------------------------------------------------------

import re
import sys

# -----------------------------------------------------------------------------
# Public Classes: (if there are any)
# -----------------------------------------------------------------------------
class Frange(object):
    """A frame range parser that identifies and parses frame ranges

    A frange range parser that
        * identify a frame range syntax. (f.e. start-end:step)
        * support negative frames
        * parse a list of integers to a frame range syntax.ex. 2,4,6,8 >> 2-8:2
        * parse a frame range syntax into list of integers 3-12:3 >> 3,6,9,12
        * support tuples of frame ranges and collapsing them into condensed
          ranges

    """

    # -------------------------------------------------------------------------
    # Class attributes:
    # -------------------------------------------------------------------------
    _pattern = re.compile("^(\-?[0-9]+)\-?(\-?[0-9]+)?:?(\-?[0-9]+)?$")

    """ _pattern : the regular expression for each valid syntax """

    # -------------------------------------------------------------------------
    # Special methods:
    # -------------------------------------------------------------------------
    def __init__(self, input_range=None):
        """Constructor.

        :arg str inputRange: The frame range to initialize the object with

        """
        super(Frange, self).__init__()
        self._frames = list()
        if (input_range is not None):
            self.add(input_range)

    def __str__(self):
        """ print the frame range out in its most compact form """
        _ordered_frames = sorted(self._frames)
        compact_frames = []
        i = 0

        if (len(_ordered_frames) < 3):
            return ",".join(str(f) for f in _ordered_frames)
        else:
            i = 0
            while (i < len(_ordered_frames) - 1):
                step = _ordered_frames[i+1] - _ordered_frames[i]
                length = 1
                while (i < len(_ordered_frames) - 1 and (_ordered_frames[i+1] - _ordered_frames[i] == step) ):
                    i += 1
                    length += 1
                if (length > 2):
                    start = str(_ordered_frames[i - length + 1])
                    end = str(_ordered_frames[i])
                    if (step == 1):
                        compact_frames.append(start + "-" + end)
                    else:
                        compact_frames.append(start + "-" + end + ":" + str(step))
                    i += 1
                    if (i == len(_ordered_frames) - 1):
                        compact_frames.append(_ordered_frames[i])
                else:
                    compact_frames.append(_ordered_frames[i-1])
                    if (i == len(_ordered_frames) - 1):
                        compact_frames.append(_ordered_frames[i])

            return ",".join(str(f) for f in compact_frames)

    # -------------------------------------------------------------------------
    # Instance methods:
    # -------------------------------------------------------------------------
    def add(self, frames):
        """ Add specified frames to the range

        :arg str frames: The frame range to add

        """

        matched = False
        if isinstance(frames, basestring):
            parts = frames.split(',')
            for i in range(len(parts)):
                #print "".join(parts[i].split())
                self._add_single_range(parts[i].strip())
        else:
            for i in range(len(frames)):
                part = str(frames[i])
                self._add_single_range(part.strip())

    def remove(self, frames):
        """ Remove specified frames from the range

        :arg str frames: The frame range to remove

        """
        matched = False
        if isinstance(frames, basestring):
            parts = frames.split(',')
            for i in range(len(parts)):
                self._remove_single_range(parts[i].strip())

        else:
            for i in range(len(frames)):
                part = str(frames[i])
                self._remove_single_range(part.strip())

    # -------------------------------------------------------------------------
    # Properties:
    # -------------------------------------------------------------------------
    @property
    def start(self):
        """first frame in the sorted range"""
        _ordered_frames = sorted(self._frames)

        if (len(_ordered_frames) == 0):
            return None
        return _ordered_frames[0]

    @property
    def end(self):
        """last frame in the sorted range"""
        _ordered_frames = sorted(self._frames)

        if (len(_ordered_frames) == 0):
            return None
        return _ordered_frames[len(_ordered_frames)-1]

    @property
    def first(self):
        """first frame in the range"""
        if (len(self._frames) == 0):
            return None
        return self._frames[0]

    @property
    def last(self):
        """last frame in the range"""
        if (len(self._frames) == 0):
            return None
        return self._frames[len(self._frames)-1]

    @property
    def step(self):
        """the frame step if there is a consistent one, None otherwise"""
        _ordered_frames = sorted(self._frames)

        if (len(_ordered_frames) == 0):
            return None

        if (len(_ordered_frames) == 1):
            return 1

        if (len(_ordered_frames) > 1):
            step = _ordered_frames[1] - _ordered_frames[0]

            if (len(_ordered_frames) == 2):
                return step
            else:
                for i in range(2, len(_ordered_frames)):
                    if (not int(_ordered_frames[i] - _ordered_frames[i-1]) == step):
                        return None
                return step

    @property
    def frames(self):
        """a generator for each frame in the range in order"""
        return self._frames

    @property
    def count(self):
        """the total number of frames"""
        return len(self._frames)

    @property
    def sorted(self):
        """the frames in order"""
        _ordered_frames = str(sorted(self._frames)).strip('[]')
        return Frange(_ordered_frames)

    # -------------------------------------------------------------------------
    # Private methods:
    # -------------------------------------------------------------------------
    def _parse_single_range(self, single_range):
        """Parse a single frame range.

        Parse a single frame range within an input frame range.
        Examples:
            1-10
            2
            1-20:2

        If valid, return the parsed range; raises FrangeError exception otherwise.

        """
        match = self._pattern.match(single_range)

        if match:
            return match.groups()
        else:
            raise FrangeError(" invalid syntax for frame range")

    def _add_single_range(self, single_range):
        """ Add a single frame range.

            Call _parsesingle_range to parse the frame range and add valid
            frame range.
        """
        groups = self._parse_single_range(single_range)
        length = len(groups)

        if groups[1] == None:
            frames = [int(groups[0])]

        elif groups[2] == None:
            frames = xrange(int(groups[0]), int(groups[1])+1)

        else:
            start = int(groups[0])
            end = int(groups[1])
            step = int(groups[2])
            frames = xrange(start, end+1, step)

        _f = [f for f in frames if f not in self._frames]
        self._frames.extend(_f)

    def _remove_single_range(self, single_range):
        """ Remove a single frame range.

            Call _parsesingle_range to parse the frame range and remove valid
            frame range.
        """
        groups = self._parse_single_range(single_range)
        length = len(groups)

        if groups[1] == None:
            frames = [int(groups[0])]

        elif groups[2] == None:
            frames = xrange(int(groups[0]), int(groups[1])+1)

        else:
            start = int(groups[0])
            end = int(groups[1])
            step = int(groups[2])
            frames = xrange(start, end+1, step)

        self._frames = [f for f in self.frames if f not in frames]

# -----------------------------------------------------------------------------
# Exceptions:
# -----------------------------------------------------------------------------
class FrangeError(Exception):
    """Invalid frame range syntax

    """
    pass


text:
angular.module('headcount.accounts', [])

.controller('AccountsController', function ($scope, $window, $location, $http) {

  $scope.initialize = function() {
    var currentUser = sessionStorage.getItem('user') || JSON.parse(localStorage.getItem('currentUser'));
    console.log(currentUser);
    return $http({
      method: 'POST',
      url: 'users/accountinfo',
      data: {
        username: currentUser,
      }
    })
    .then(function (resp) {
      user = resp.data;
      $scope.username = user.username || '';
      $scope.firstname = user.firstName || '';
      $scope.lastname = user.lastName || '';
      $scope.email = user.email || '';
    });
  };
  $scope.initialize();

  $scope.accountUpdate = function() {
    console.log('updating account');
    var currentUser = window.sessionStorage.getItem('user') || JSON.parse(window.localStorage.getItem('currentUser'));
    var data = {};
    data.username = $scope.username;
    data.firstName = $scope.firstname;
    data.lastName = $scope.lastname;
    data.email = $scope.email;
    return $http({
      method: 'POST',
      url: 'users/accountupdate',
      data: data
    })
    .then(function (resp) {
      console.log('account updated');
    });
  };

  /**
   * Checks if user has already authorized his/her Venmo account
   */
  $scope.checkVenmoDetails = function(){

    var currentUser = window.sessionStorage.getItem('user') || JSON.parse(window.localStorage.getItem('currentUser'));
    return $http({
      method: 'POST',
      url : '/users/checkUser',
      data : {'username': currentUser}
    })
    .then(function(resp){
      console.log(resp.data);
      var hasVenmoInfo = resp.data.hasVenmoInfo;

      if (!hasVenmoInfo) {
        console.log('You have not authorized your Venmo account yet!');
      }

      $scope.shouldNotBeClickable = !hasVenmoInfo;
    });
  };

  $scope.checkVenmoDetails();

  /**
   * Handles Venmo button submittal.
   * Gets Connect account creation redirect url from server and manually sets href.
   */
  $scope.authorize = function() {
    var currentUser = window.sessionStorage.getItem('user') || JSON.parse(window.localStorage.getItem('currentUser'));

    return $http({
      method: 'POST',
      url: '/authorize',
      data: {
        username: currentUser
      }
    })
    .then(function (resp) {
      console.log(resp);
      $window.location.href = resp.data;
    });
  };

});


text:
/*
 * $Id: XSLProcessorVersion.src 468640 2006-10-28 06:53:53Z minchau $
 */
package org.apache.xalan.processor;

/**
 * Administrative class to keep track of the version number of
 * the Xalan release.
 *
See also: org/apache/xalan/res/XSLTInfo.properties

 * @deprecated To be replaced by org.apache.xalan.Version.getVersion()
 * @xsl.usage general
 */
public class XSLProcessorVersion
{

  /**
   * Print the processor version to the command line.
   *
   * @param argv command line arguments, unused.
   */
  public static void main(String argv[])
  {
    System.out.println(S_VERSION);
  }

  /**
   * Constant name of product.
   */
  public static final String PRODUCT = "Xalan";

  /**
   * Implementation Language.
   */
  public static final String LANGUAGE = "Java";

  /**
   * Major version number.
   * Version number. This changes only when there is a
   *          significant, externally apparent enhancement from
   *          the previous release. 'n' represents the n'th
   *          version.
   *
   *          Clients should carefully consider the implications
   *          of new versions as external interfaces and behaviour
   *          may have changed.
   */
  public static final int VERSION = 2;

  /**
   * Release Number.
   * Release number. This changes when:
   *            -  a new set of functionality is to be added, eg,
   *               implementation of a new W3C specification.
   *            -  API or behaviour change.
   *            -  its designated as a reference release.
   */
  public static final int RELEASE = 7;

  /**
   * Maintenance Drop Number.
   * Optional identifier used to designate maintenance
   *          drop applied to a specific release and contains
   *          fixes for defects reported. It maintains compatibility
   *          with the release and contains no API changes.
   *          When missing, it designates the final and complete
   *          development drop for a release.
   */
  public static final int MAINTENANCE = 1;

  /**
   * Development Drop Number.
   * Optional identifier designates development drop of
   *          a specific release. D01 is the first development drop
   *          of a new release.
   *
   *          Development drops are works in progress towards a
   *          compeleted, final release. A specific development drop
   *          may not completely implement all aspects of a new
   *          feature, which may take several development drops to
   *          complete. At the point of the final drop for the
   *          release, the D suffix will be omitted.
   *
   *          Each 'D' drops can contain functional enhancements as
   *          well as defect fixes. 'D' drops may not be as stable as
   *          the final releases.
   */
  public static final int DEVELOPMENT = 0;

  /**
   * Version String like "Xalan Language
   * v.r[.dd| Dnn]".
   *
Semantics of the version string are identical to the Xerces project.

   */
  public static final String S_VERSION = PRODUCT+" "+LANGUAGE+" "
                                   +VERSION+"."+RELEASE+"."
                                   +(DEVELOPMENT > 0 ? ("D"+DEVELOPMENT)
                                     : (""+MAINTENANCE));

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:paddingLeft="10dp"
            android:text="Vaccine name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvVaccName"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="vaccine name"
            android:paddingLeft="10dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:paddingLeft="10dp"
            android:text="For"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvReason"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="for"
            android:paddingLeft="10dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" >
        </TextView>
    </LinearLayout>

    <TextView
        android:id="@+id/tvVaccineID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1.5"
            android:paddingLeft="10dp"
            android:text="Address"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvAddress"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="address"
            android:paddingLeft="10dp"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="10dp"
            android:text="Date"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvVaccDate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="date"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:paddingLeft="10dp"
            android:text="Time"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=":"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvVaccTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="time"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />
    </LinearLayout>

    <ImageView
        android:id="@+id/showvaccalarm"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:layout_gravity="right"
        android:layout_marginRight="10dp"
        android:layout_marginTop="-70dp"
        android:contentDescription="@string/app_name"
        android:src="@drawable/bell"
        android:visibility="gone" />

</LinearLayout>


text:
"use strict";
const TypeReaderResult = require("../results/TypeReaderResult.js");
const TypeReader = require("../structures/TypeReader.js");
const StringReader = new TypeReader({type: "string"});

StringReader.default = true;
StringReader.read = input => TypeReaderResult.fromSuccess(input);
module.exports = StringReader;


text:
import { BrowserDetectService } from './core/browser-detect/browser-detect.service';
import { PrettyFocusService } from './core/pretty-focus/pretty-focus.service';
import { WebfontsService } from './core/webfonts/webfonts.service';
import { TranslationsService } from './core/translations/translations.service';
import { DataService } from './core/data/data.service';
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { TranslateService } from '@ngx-translate/core';
import { of } from 'rxjs';

class MockBrowserDetectService {
  init () {}
}

class MockPrettyFocusService {
  init () {}
}

class MockWebfontsService {
  init () {}
}

class MockTranslationsService {
  init () {}
}

class MockTranslateService {
  get(key: any): any {
    of(key);
  }
}

class MockDataService {}

describe('AppComponent', () => {
  let component: AppComponent;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [
        AppComponent,
        { provide: TranslateService, useClass: MockTranslateService },
        { provide: BrowserDetectService, useClass: MockBrowserDetectService },
        { provide: PrettyFocusService, useClass: MockPrettyFocusService },
        { provide: WebfontsService, useClass: MockWebfontsService },
        { provide: TranslationsService, useClass: MockTranslationsService },
        { provide: DataService, useClass: MockDataService},
      ],
    });
    component = TestBed.get(AppComponent);
  });

  it('should create component', () => {
    expect(component).toBeDefined();
  });
});


text:
Pattern: Malformed whitespace after `!` of declaration

Issue: -

## Description

Require a single space or disallow whitespace after the bang of declarations.

## Examples

### `"always"`

There *must always* be a single space after the bang.

The following patterns are considered violations:

```css
a { color: pink !important; }
```

```css
a { color: pink      !important; }
```

The following patterns are *not* considered violations:

```css
a { color: pink ! important; }
```

```css
a { color: pink! important; }
```

### `"never"`

There *must never* be whitespace after the bang.

The following patterns are considered violations:

```css
a { color: pink ! important; }
```

```css
a { color: pink! important; }
```

The following patterns are *not* considered violations:

```css
a { color: pink !important; }
```

```css
a { color:pink!important; }
```

## Further Reading

* [stylelint - declaration-bang-space-after](https://stylelint.io/user-guide/rules/declaration-bang-space-after)


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Clinica;

/**
 * ClinicaSearch represents the model behind the search form about `app\models\Clinica`.
 */
class ClinicaSearch extends Clinica
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'ativo'], 'integer'],
            [['cnpj', 'nome', 'razaoSocial', 'cadastro'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Clinica::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'cadastro' => $this->cadastro,
            'ativo' => $this->ativo,
        ]);

        $query->andFilterWhere(['like', 'cnpj', $this->cnpj])
            ->andFilterWhere(['like', 'nome', $this->nome])
            ->andFilterWhere(['like', 'razaoSocial', $this->razaoSocial]);

        return $dataProvider;
    }
}


text:
function parsave(fname, data2save, datastr, opts)
% inputs:
% fname is the fullpath filename
% data is the variable to save
% datastr is the name of the variable to save
% opts are options for saving
% lix(its.lix@outlook.com) retrieved from amgordon/eegfmri

if ~exist('opts', 'var')
    opts = '-mat';
end

dir_ = fileparts(fname);
if ~exist(dir_, 'dir');
    mkdir(dir_);
end

data = data2save;
eval([datastr '= data;']);
save(fname, datastr, opts);


text:
package com.mozidev.newskeeper.domain.common;

import android.content.Context;
import android.provider.Settings;

import com.mozidev.newskeeper.data.APIDataProviderImpl;
import com.mozidev.newskeeper.domain.categories.Category;
import com.mozidev.newskeeper.domain.publishers.Publisher;
import com.mozidev.newskeeper.presentation.injection.DomainModule;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import io.realm.Realm;
import rx.Observable;
import rx.Scheduler;

public class SaveFiltersInteractor extends Interactor<Object, Object> {

    APIDataProviderImpl provider;
    Context context;
    Realm realm;

    @Inject
    public SaveFiltersInteractor(@Named(DomainModule.IO) Scheduler jobScheduler, @Named(DomainModule.UI) Scheduler uiScheduler, APIDataProviderImpl provider, Context context, Realm realm) {
        super(jobScheduler, uiScheduler);
        this.provider = provider;
        this.context = context;
        this.realm = realm;
    }

    @Override
    protected Observable<Object> buildObservable(Object obj) {
        String id = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ANDROID_ID);

        List<Integer> publishers_ids = new ArrayList<>();
        List<Publisher> publishers = realm.where(Publisher.class)
                .equalTo("checked", true)
                .findAll();
        for (Publisher publisher : publishers) {
            if (publisher.isChecked()) publishers_ids.add(publisher.getId());
        }

        List<Integer> categories_ids = new ArrayList<>();
        List<Category> categories = realm.where(Category.class)
                .equalTo("checked", true)
                .findAll();
        for (Category category : categories) {
            if (category.isChecked()) categories_ids.add(category.getId());
        }

        return provider.postSelectedFilters(id, publishers_ids, categories_ids);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Lichenol. 86: 177 (2003)

#### Original name
Cryptothecia granularis Sipman

### Remarks
null


text:
package container_test

import (
	"errors"

	"github.com/cloudfoundry-incubator/ducati-daemon/container"
	"github.com/cloudfoundry-incubator/ducati-daemon/executor/commands"
	"github.com/cloudfoundry-incubator/ducati-daemon/fakes"
	"github.com/cloudfoundry-incubator/ducati-daemon/lib/namespace"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Delete", func() {
	var (
		deletor         container.Deletor
		executor        *fakes.Executor
		containerNS     namespace.Namespace
		namespaceOpener *fakes.Opener
	)

	BeforeEach(func() {
		executor = &fakes.Executor{}

		namespaceOpener = &fakes.Opener{}
		containerNS = &fakes.Namespace{NameStub: func() string { return "container ns sentinel" }}
		namespaceOpener.OpenPathReturns(containerNS, nil)

		deletor = container.Deletor{
			Executor:        executor,
			NamespaceOpener: namespaceOpener,
		}
	})

	It("should open the container namespace", func() {
		err := deletor.Delete("some-interface-name", "/path/to/container/namespace", "sandbox-name", "some-vxlan")
		Expect(err).NotTo(HaveOccurred())
		Expect(namespaceOpener.OpenPathCallCount()).To(Equal(1))
		Expect(namespaceOpener.OpenPathArgsForCall(0)).To(Equal("/path/to/container/namespace"))
	})

	Context("when opening the container namespace fails", func() {
		BeforeEach(func() {
			namespaceOpener.OpenPathReturns(nil, errors.New("POTATO"))
		})

		It("should return a meaningful error", func() {
			err := deletor.Delete("some-interface-name", "/path/to/container/namespace", "sandbox-name", "some-vxlan")
			Expect(err).To(MatchError("open container netns: POTATO"))
		})
	})

	It("should construct the correct command sequence", func() {
		err := deletor.Delete("some-interface-name", "/path/to/container/namespace", "sandbox-name", "some-vxlan")
		Expect(err).NotTo(HaveOccurred())

		Expect(executor.ExecuteCallCount()).To(Equal(1))
		Expect(executor.ExecuteArgsForCall(0)).To(Equal(
			commands.All(
				commands.InNamespace{
					Namespace: containerNS,
					Command: commands.DeleteLink{
						LinkName: "some-interface-name",
					},
				},

				commands.CleanupSandbox{
					SandboxName:     "sandbox-name",
					VxlanDeviceName: "some-vxlan",
				},
			),
		))
	})

	Context("when executing fails", func() {
		BeforeEach(func() {
			executor.ExecuteReturns(errors.New("boom"))
		})

		It("should return the error", func() {
			err := deletor.Delete("some-interface-name", "/path/to/container/namespace", "sandbox-name", "some-vxlan")
			Expect(err).To(MatchError("boom"))
		})
	})
})


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__char_console_printf_52c.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-52c.tmpl.c
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: console Read input from the console
 * GoodSource: Copy a fixed string into data
 * Sinks: printf
 *    GoodSink: printf with "%s" as the first argument and data as the second
 *    BadSink : printf with only data as an argument
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#ifndef OMITBAD

void CWE134_Uncontrolled_Format_String__char_console_printf_52c_badSink(char * data)
{
    /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
    printf(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__char_console_printf_52c_goodG2BSink(char * data)
{
    /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
    printf(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__char_console_printf_52c_goodB2GSink(char * data)
{
    /* FIX: Specify the format disallowing a format string vulnerability */
    printf("%s\n", data);
}

#endif /* OMITGOOD */


text: Õppeaine Võrgurakendused I raames tehtod repo


text:
Docker images for the [dogescript](http://dogescript.io/) language

## Usage

```bash
# repl
docker run -it dogescript/dogescript:latest
# transpiler
docker run -v ${PWD}/samples:/samples dogescript/dogescript:latest /samples/fizzbuzz.djs --beautify > fizzbuzz.js
# interpreter
docker run -v ${PWD}/samples:/samples dogescript/dogescript:latest /samples/fizzbuzz.djs --run
```

## Extending

### Sample Express

This sample uses `express` and a small app written in dogescript to launch a containerized app

_app.djs_
```dogescript
so express

very app is plz express
very port is 3000

app dose get with '/' much req res
  res dose send with 'Wow we are running dogescript in a container'
wow&

such listenMsg
  console dose loge with 'dogexpress http://localhost:3000'
wow

app dose listen with 3000 listenMsg
```

```Dockerfile
FROM dogescript/dogescript:2.4.0

RUN npm i express
COPY app.djs /app.djs

ENTRYPOINT ["dogescript", "/app.djs", "--run"]
```

Build and run!
```bash
docker build . -t myapp
docker run -p 3000:3000 myapp
```


text:
var http = require('http');
var request = require('request');
var fs = require('fs');
var jsdom = require('jsdom'), html5 = require('html5');

var article_1 = {
	id : 1,
	url : "http://www.bbc.co.uk/news/science-environment-18716300",
	title :  "1South Korea unveils 'scientific' whaling proposal",
	author: "Richard Black",
	published_date : "4 July 2012",
	host : "http://www.bbc.co.uk",
	path : "/news/science-environment-18716300.html",
	uploaded_by : "Catherine Tan",
	uploaded_on : "May 6 2012,  12:30 PM PST"
}

var article_2 = {
	id : 2,
	url : "http://blog.spoongraphics.co.uk/tutorials/how-to-create-an-abstract-geometric-mosaic-text-effect",
	title :  "How To Create an Abstract Geometric Mosaic Text Effect",
	author: "Chris Spooner",
	published_date : "4 July 2012",
	host : "http://blog.spoongraphics.co.uk",
	path : "/news/how-to-create-an-abstract-geometric-mosaic-text-effect.html",
	uploaded_by : "Catherine Tan",
	uploaded_on : "Jun 6 2012,  12:30 PM PST"
}

var article_3 = {
	id : 3,
	url : "http://www.bbc.co.uk/news/science-environment-18716300",
	title :  "3South Korea unveils 'scientific' whaling proposal",
	author: "Richard Black",
	published_date : "4 July 2012",
	host : "http://www.bbc.co.uk",
	path : "/news/science-environment-18716300.html",
	uploaded_by : "Catherine Tan",
	uploaded_on : "July 12 2012,  12:30 PM PST"
}

var article_4 = {
	id : 4,
	url : "http://www.bbc.co.uk/news/science-environment-18716300",
	title :  "4South Korea unveils 'scientific' whaling proposal",
	author: "Richard Black",
	published_date : "4 July 2012",
	host : "http://www.bbc.co.uk",
	path : "/news/science-environment-18716300.html",
	uploaded_by : "Catherine Tan",
	uploaded_on : "July 12 2012,  12:30 PM PST"
}

var article_5 = {
	id : 5,
	url : "http://www.forbes.com/sites/victorlipman/2012/06/28/how-to-interview-effectively",
	title :  "How To Interview Effectively",
	author: "Victor Lipman",
	published_date : "28 June 2012",
	host : "http://www.forbes.com",
	path : "/news/how-to-interview-effectively.html",
	uploaded_by : "Catherine Tan",
	uploaded_on : "July 15 2012,  12:30 PM PST",
	course: "cmpt120",
	week : "3",

}

var articles = [article_1,  article_2,  article_3,  article_4,  article_5]

var userobject = {
	name : "Catherine Tan",
	id : 301078676,
	courses : {
		"CMPT 120" : [article_1, article_2],
		"BUS 100" : [article_4],
		"IAT 200" : [article_3, article_5, article_1]
		}
	}

function mediaPath(path, host){
	if (path.charAt(0)== "/"){
		return "http://" + host + path;
	}
	else return path;
}

function walk(node, cb) {

	var check = false;
	if (node.nodeType !== node.ELEMENT_NODE) {
		return;
	}

	for(var i = 0; i < node.childNodes.length; ++i){
		if (node.childNodes[i].tagName === 'SCRIPT' || node.childNodes[i].tagName === 'NOSCRIPT') {
			node.removeChild(node.childNodes[i]);
		}
		else if (node.childNodes[i].textContent.length/node.textContent.length > 0.55) {
			walk(node.childNodes[i], cb);
			check = true;
		}
	}

	if (!check) {
		cb(node);
	}
}

function listTypes(node) {
	var article = null

	walk(node, function(node) {
		for (var j = 0; j < node.childNodes.length; ++j) {
			var current = node.childNodes[j];
			//console.log('child node: '+current)
			if (current.nodeType === current.ELEMENT_NODE) {
				current.removeAttribute('class');
				current.removeAttribute('id');
				current.removeAttribute('style');
			}
		}
		article = node;
	})
	return article;
}

/*
function articlize(document) {
	var article = listTypes(document.documentElement)
}
*/

function get_article(document, name) {

	var stream = fs.createWriteStream("./public/news/"+name+".xml");
	stream.once('open', function(fd) {

		stream.write('<title>'+document.querySelector('H1').textContent+'</title>\n')
		stream.write('<content>'+html5.serialize(listTypes(document.documentElement))+'</content>');

	})
/*
	//for testing----------------
	return document.querySelectorAll(tag).map(function(node) {
		return "<p>"+node.textContent+"</p>";
	}).join("");
	//---------------------------
*/
}

exports.index = function(req, res){

	if (!req.body.article_url) {
		var error = "";
		if (req.method === 'POST') {
			error ="please enter an URL" ;
		}
		res.render("index", { 	title: "SFU ENGAGE",
							user :  userobject,
							status : "logged in",
							errormsg : error })
		return;
	}

	//var pathname = req.body.article_url.substring(0,pathname.lastIndexOf("/"));
	//console.log(req.body.article_url.split("/"));
	var parse_url = req.body.article_url.split("/");

	request(req.body.article_url, function (error, response, body) {
		if (response.statusCode == 200) {
			var
				window = jsdom.jsdom(null, null, {
					parser: html5,
					features: {
						QuerySelector: true
					}
				}).createWindow(),
				parser = new html5.Parser({document: window.document});

			parser.parse(body);

			get_article(window.document, parse_url[parse_url.length-1]);

		}

		res.render("index", { 	title: "SFU ENGAGE",
								user :  userobject,
								status : "logged in",
								errormsg : error })
	});
};

exports.article_view = function(req, res){
	var pickedArticle = articles[req.params.id - 1];

	res.render("article", { title: "SFU ENGAGE",
							article : pickedArticle,
							user :  userobject,
							status : "logged in"	 })
}


text:
import IconCancel from "binary-ui-icons/binary/Cancel";
import IconDone from "binary-ui-icons/binary/Done";
import React from "react";
import { Dimensions } from "react-native";

import { storiesOf } from "@storybook/react-native";
import { action } from "@storybook/addon-actions";

import StackPage from "../../lib";
import StackBodySearchCards from "../../lib/components/StackBodySearchCards";

const { height, width } = Dimensions.get("window");

storiesOf("Examples", module).add("stack body cards empty actions", () => (
  <StackPage
    bodyStyle={{
      backgroundColor: "#eeeae5"
    }}
    headerButtonLeft={{
      renderIcon: props => <IconCancel {...props} />,
      onPress: action()
    }}
    headerButtonRight={{
      renderIcon: props => <IconDone {...props} />,
      onPress: action()
    }}
    headerStyle={{
      backgroundColor: "#eeeae5"
    }}
    headerTitle={{
      children: "Stack with active buttons"
    }}
    pageHeight={height}
    searchValue=""
    onOpenDone={() => {}}
    onCloseDone={() => {}}
  >
    <StackBodySearchCards
      cardHeight={234}
      cardsLength={0}
      pageHeight={height}
      pageWidth={width}
      searchPlaceholder="Search stack"
      searchValue=""
      onSearchValueChange={action()}
    />
  </StackPage>
));


text:
/* --- AUTOGENERATED FILE -----------------------------
* If you make changes to this file delete this comment.
* Otherwise the file may be overwritten in the future.
* --------------------------------------------------- */

const { mergeLocMatchGroups } = require('../lib/matching/utils');
const { regexMatchLocs } = require('../lib/matching/regexMatch');

const allSetSrc = {
  type: 'website',
  url: 'https://resources.allsetlearning.com/chinese/grammar/ASG8KUHG',
  name: 'AllSet Chinese Grammar Wiki',
};

module.exports = {
  id: 'expressingAlwaysWithConglai',
  structures: ['Subj. + 从来 + 都 + Predicate'],
  description:
    'Although perhaps more often used in the negative to mean "never," 从来 (cónglái) can be used with 都 (dōu) to mean "always" or "have always (done)."',
  sources: [allSetSrc],
  match: sentence => mergeLocMatchGroups([regexMatchLocs(sentence.text, /(从来都)/)]),
  examples: [
    {
      zh: '我从来都一个人住,已经习惯了。',
      en: "I have always lived alone; I'm used to it already.",
      src: allSetSrc,
    },
    {
      zh: '她从来都这么自私。',
      en: "She's always been this selfish.",
      src: allSetSrc,
    },
    {
      zh: '我们下棋,他从来都是赢的。',
      en: 'He always wins when we play chess.',
      src: allSetSrc,
    },
    {
      zh: '他说话从来都很大声。',
      en: 'He always speaks very loudly.',
      src: allSetSrc,
    },
    {
      zh: '她找男朋友从来都是要长得帅的。',
      en: 'She always wants those good-looking guys when she looks for boyfriend.',
      src: allSetSrc,
    },
    {
      zh: '他工作从来都很努力。',
      en: 'He always works very hard.',
      src: allSetSrc,
    },
    {
      zh: '我的学生从来都这么有自信。',
      en: 'My students are always so confident.',
      src: allSetSrc,
    },
    {
      zh: '他的电影从来都是最受欢迎的。',
      en: 'His movies are always the most popular ones.',
      src: allSetSrc,
    },
    {
      zh: '成功从来都要靠自己努力。',
      en: "Success always depends on one's own efforts.",
      src: allSetSrc,
    },
  ],
};


text:
import unittest
import os
from datetime import datetime, timedelta, tzinfo
import binascii
import json
import subprocess
import re
import requests
import time
from rdflib import (
    Namespace,
    URIRef,
    Graph,
    Literal,
)
from rdflib.namespace import RDF, XSD, SKOS  # , RDFS
import base64
import sys

settings = dict(
    rpcuser="fuguecoinrpcuser",
    rpcpassword="fuguecoinrpcuserpassword",
    host="127.0.0.1",
    port=9088,
    rpcport=9089,
    min_height=0,
    max_height=2374500,
    netmagic=0xf9beb4d4,
    genesis=0x0000008625534e38467b29078ed2868c2ec43eb024c4a2e7ff2f6480f283656b,
    input="/home/gjh/minkiz/fabshop/FugueCoinWork/fuguecoin/datadir/blocks",
    output="/home/gjh/minkiz/fabshop/FugueCoinWork/fuguecoin-0.8.6/datadir/bootstrap.dat",
    hashlist="hashlist.txt",
    split_year=5,
    out_of_order_cache_sz = 100000000
)

# Switch endian-ness
def hex_switchEndian(s):
    """ Switches the endianness of a hex string (in pairs of hex chars) """
    pairList = [s[i:i + 2].encode() for i in range(0, len(s), 2)]
    return b''.join(pairList[::-1]).decode()

class RPCHost(object):
    def __init__(self, url):
        self._session = requests.Session()
        self._url = url
        self._headers = {'content-type': 'application/json'}

    def call(self, rpcMethod, *params):
        payload = json.dumps({"method": rpcMethod, "params": list(params), "jsonrpc": "2.0"})
        tries = 10
        hadConnectionFailures = False
        while True:
            # print("{url} {headers} {data}".format(url=self._url, headers=self._headers, data=payload))
            try:
                response = self._session.get(self._url, headers=self._headers, data=payload)
            except requests.exceptions.ConnectionError:
                tries -= 1
                if tries == 0:
                    raise Exception('Failed to connect for remote procedure call.')
                hadConnectionFailures = True
                print("Couldn't connect for remote procedure call, will sleep for ten seconds and then try again ({} more tries)".format(tries))
                time.sleep(10)
            else:
                if hadConnectionFailures:
                    print('Connected for remote procedure call after retry.')
                break
        if response.status_code not in (200, 500):
            raise Exception('RPC connection failure: ' + str(response.status_code) + ' ' + response.reason)
        responseJSON = response.json()
        if 'error' in responseJSON and responseJSON['error'] is not None:
            raise Exception('Error in RPC call: ' + str(responseJSON['error']))
        return responseJSON['result']

class TestMyView(unittest.TestCase):
    def setUp(self):
        self.serverurl = 'http://{}:{}@localhost:{}/'.format(
            settings.get('rpcuser'), settings.get('rpcpassword'), settings.get('rpcport'))
        self.amerpc = RPCHost(self.serverurl)

    @unittest.skip("Passed, skipping")
    def test_get_block_hashes(self):
        with open('/home/gjh/minkiz/fabshop/FugueCoinWork/fuguecoin-0.8.6/contrib/linearize/fuguehashes.txt', 'w') as fp:
            for height in range(0, 2374500):
                res = hex_switchEndian(self.amerpc.call('getblockhash', height))
                fp.write("{}\n".format(res))
            fp.close()

    def test_get_unswitch(self):
        with open(
            '/home/gjh/minkiz/fabshop/FugueCoinWork/fuguecoin-0.8.6/contrib/linearize/fuguehashes.txt', 'r') as fin, open(
            '/home/gjh/minkiz/fabshop/FugueCoinWork/fuguecoin-0.8.6/contrib/linearize/hashlist.txt', 'w') as fout:
            for l in fin.readlines():
                res = hex_switchEndian(l[:-1])
                fout.write("{}\n".format(res))
            fout.close()

if __name__ == "__main__":
    unittest.main()


text:
#ifndef AV1_ENCODER_PICKRST_H_
#define AV1_ENCODER_PICKRST_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "av1/encoder/encoder.h"

struct yv12_buffer_config;
struct AV1_COMP;

void av1_pick_filter_restoration(const YV12_BUFFER_CONFIG *sd, AV1_COMP *cpi,
                                 LPF_PICK_METHOD method);

#ifdef __cplusplus
}  // extern "C"
#endif

#endif  // AV1_ENCODER_PICKRST_H_


text:
param($installPath, $toolsPath, $package, $project)

$file = Join-Path $toolsPath 'chromedriver.exe' | Get-ChildItem

$project.ProjectItems.AddFromFile($file.FullName);
$pi = $project.ProjectItems.Item($file.Name);
$pi.Properties.Item("BuildAction").Value = [int]2;
$pi.Properties.Item("CopyToOutputDirectory").Value = [int]2;

$project.ProjectItems.Item('chromedriver-license.txt').Properties.Item("CopyToOutputDirectory").Value = [int]2;


text:
    <pagination [totalItems]="total" [(ngModel)]="currentPage" (pageChanged)="pageChanged($event)"
                [maxSize]="maxSize" [rotate]="true"
                [boundaryLinks]="true"></pagination>

{{quote.title}}

{{quote.quote}}

Published on {{quote.published}}


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <mqueue.h>
#include <fcntl.h>
#include <sys/types.h>
#include <task_manager/task_manager.h>
#include "task_manager_internal.h"

/****************************************************************************
 * task_manager_unicast
 ****************************************************************************/
int task_manager_unicast(int handle, tm_msg_t *send_msg, tm_msg_t *reply_msg, int timeout)
{
	int status = TM_OUT_OF_MEMORY;
	tm_request_t request_msg;
	tm_response_t response_msg;

	if (IS_INVALID_HANDLE(handle) || timeout < TM_RESPONSE_WAIT_INF || (reply_msg != NULL && timeout == TM_NO_RESPONSE) || send_msg == NULL) {
		return TM_INVALID_PARAM;
	}

	memset(&request_msg, 0, sizeof(tm_request_t));
	if (send_msg->msg != NULL) {
		if (send_msg->msg_size == 0) {
			return TM_INVALID_PARAM;
		}
		request_msg.data = (void *)TM_ALLOC(sizeof(tm_internal_msg_t));
		if (request_msg.data == NULL) {
			return TM_OUT_OF_MEMORY;
		}
		((tm_internal_msg_t *)request_msg.data)->msg = (void *)TM_ALLOC(send_msg->msg_size);
		if (((tm_internal_msg_t *)request_msg.data)->msg == NULL) {
			goto errout_with_free2;
		}
		memcpy(((tm_internal_msg_t *)request_msg.data)->msg, send_msg->msg, send_msg->msg_size);
		((tm_internal_msg_t *)request_msg.data)->msg_size = send_msg->msg_size;
	}

	/* Set the request msg */
	if (reply_msg == NULL) {
		request_msg.cmd = TASKMGRCMD_UNICAST_ASYNC;
	} else {
		request_msg.cmd = TASKMGRCMD_UNICAST_SYNC;
	}
	request_msg.handle = handle;
	request_msg.caller_pid = getpid();
	request_msg.timeout = timeout;

	if (timeout != TM_NO_RESPONSE) {
		TM_ASPRINTF(&request_msg.q_name, "%s%d", TM_PRIVATE_MQ, request_msg.caller_pid);
		if (request_msg.q_name == NULL) {
			goto errout_with_free1;
		}
	}

	status = taskmgr_send_request(&request_msg);
	if (status < 0) {
		if (request_msg.q_name != NULL) {
			TM_FREE(request_msg.q_name);
		}
		goto errout_with_free1;
	}

	if (timeout != TM_NO_RESPONSE) {
		status = taskmgr_receive_response(request_msg.q_name, &response_msg, timeout);
		TM_FREE(request_msg.q_name);
		if (reply_msg != NULL) {
			reply_msg->msg_size = ((tm_msg_t *)response_msg.data)->msg_size;
			reply_msg->msg = TM_ALLOC(reply_msg->msg_size);
			if (reply_msg->msg == NULL) {
				status = TM_OUT_OF_MEMORY;
				goto errout_with_free1;
			}
			memcpy(reply_msg->msg, ((tm_msg_t *)response_msg.data)->msg, reply_msg->msg_size);
			TM_FREE(((tm_msg_t *)response_msg.data)->msg);
			TM_FREE(response_msg.data);
		}
	}
	return status;

errout_with_free1:
	TM_FREE(((tm_internal_msg_t *)request_msg.data)->msg);
errout_with_free2:
	TM_FREE(request_msg.data);
	return status;
}

/****************************************************************************
 * task_manager_reply_unicast
 ****************************************************************************/
int task_manager_reply_unicast(tm_msg_t *reply_msg)
{
	int ret = ERROR;
	mqd_t reply_mqfd;
	struct mq_attr attr;
	tm_msg_t *data;

	if (reply_msg == NULL) {
		return TM_INVALID_PARAM;
	}
	data = (tm_msg_t *)TM_ALLOC(sizeof(tm_msg_t));
	if (data == NULL) {
		return TM_OUT_OF_MEMORY;
	}
	data->msg = TM_ALLOC(reply_msg->msg_size);
	if (data->msg == NULL) {
		TM_FREE(data);
		return TM_OUT_OF_MEMORY;
	}
	data->msg_size = reply_msg->msg_size;
	memcpy(data->msg, reply_msg->msg, reply_msg->msg_size);

	attr.mq_maxmsg = CONFIG_TASK_MANAGER_MAX_MSG;
	attr.mq_msgsize = sizeof(tm_msg_t);
	attr.mq_flags = 0;

	reply_mqfd = mq_open(TM_UNICAST_MQ, O_WRONLY | O_CREAT, 0666, &attr);
	if (reply_mqfd == (mqd_t)ERROR) {
		TM_FREE(data->msg);
		TM_FREE(data);
		tmdbg("mq_open failed!\n");
		return TM_COMMUCATION_FAIL;
	}

	ret = mq_send(reply_mqfd, (char *)data, sizeof(tm_msg_t), TM_MQ_PRIO);
	if (ret != 0) {
		mq_close(reply_mqfd);
		TM_FREE(data->msg);
		TM_FREE(data);
		tmdbg("mq_send failed! %d\n", errno);
		return TM_COMMUCATION_FAIL;
	}

	ret = mq_close(reply_mqfd);
	if (ret != OK) {
		tmdbg("mq_close failed! ret %d, errno %d\n", ret, errno);
	}

	TM_FREE(data);

	return ret;
}


text:
using Assets.Scripts.Helpers;
using UnityEngine;

public class StarlightScript : MonoBehaviour
{
    public GameObject Star;
    public GameObject Starlight;
    public float Radius = 10000;
    public float Quantity = 100;

    void Start()
    {
        for (int i = 0; i < Quantity; i++)
        {
            var position = Geometry.GetRandomPointOnCircle(Radius);
            Instantiate(Starlight, position, Quaternion.identity);
        }
    }

    void Update()
    {

    }
}


text:
UPapp.controller('Administracion_Generales_becas', function ($scope, adminService, $modal) {
    $scope.Posteriores = function (html) {
        $modal.open({
            templateUrl: 'partials/administrador/administracion/generales/modal/' + html + '.html?ver='+app_version,
            controller: 'ModalInstanceCtrl',
            size: 'lg',
            resolve: {
                custom_data: function () {
                    return false;
                }
            }
        });
    };
    $scope.NuevaBeca = function (html) {
        $modal.open({
            templateUrl: 'partials/administrador/administracion/generales/modal/' + html + '.html?ver='+app_version,
            controller: 'ModalInstanceCtrl',
            size: 'md',
            resolve: {
                custom_data: function () {
                    return false;
                }
            }
        });
    };
    $scope.model_file = [];
    $scope.upload_xls_file = function () {
        $scope.isBusy = true;
        adminService.addBecasByFile($scope.model_file.file).then(function (data) {
            $scope.isBusy = false;
            //console.log(data);
            $scope.alerts = [
                {type: 'success', msg: 'Los Becas del archivo fueron validados correctamente.'}
            ];
        });
    };
});

UPapp.controller('Administracion_Generales_reporte_becas', function ($scope, adminService, $modal) {
    $scope.model = [];
    $scope.carreras = [];
    $scope.sub_conceptos = [];
    $scope.descripcion_sc = [];
    $scope.sort_reporte = [];
    $scope.sort_title = [];
    $scope.format = 'dd-MMMM-yyyy';
    var adeudos = [];
    var key_service;

    $scope.isBusy = true;
    var found = [];
    adminService.getPeriodos().then(function (data) {
        $scope.isBusy = false;
        $scope.periodos = data;
        data.forEach(function (val, key) {
            if (val.actual == 1) {
                $scope.model.periodo = $scope.periodos[key];
            }
        });
    }, function (err) {
    });
    $scope.$watchCollection('model.fecha_desde', function (newNames, oldNames) {
        $scope.minDate = $scope.minDate ? null : newNames;
    });
    $scope.openfrom = function ($event) {
        $scope.model.datefrom = [];
        $event.preventDefault();
        $event.stopPropagation();
        $scope.model.datefrom.opened = true;
    };
    $scope.opento = function ($event) {
        $scope.model.dateto = [];
        $event.preventDefault();
        $event.stopPropagation();
        $scope.model.dateto.opened = true;
    };

    $scope.make_filters = function () {
        $scope.found = $filter('getAllObjectsBySubProperty')('adeudos', 'descripcion_sc', $scope.model.filter.descripcion_sc, angular.copy($scope.adeudos));
        $scope.found = $filter('getAllObjectsBySubProperty')('adeudos', 'sub_concepto', $scope.model.filter.sub_concepto, $scope.found);
        $scope.found = $filter('getAllObjectsByProperty')('carrera', $scope.model.filter.carrera, $scope.found);

        render_excel_table();
    };

    $scope.columns = [
        {m_select: true, field: "asignada_por", title: "Asignada Por", width: 200},
        {m_select: true, field: "importe", title: "Monto", width: 200},
        {m_select: true, field: "tipo_cobro", title: "Tipo Monto", width: 150},
        {m_select: true, field: "abreviatura", aggregates: ["count"],groupHeaderTemplate: "Beca: #= value # (Cantidad: #= count#)", title: "Beca", width: 150,
            filterable: {
                ui: function (element) {
                    element.removeAttr("data-bind");
                    element.kendoMultiSelect({
                        dataSource: $scope.filters_dd.abreviatura,
                        change: function (e) {
                            var filter = {logic: "or", filters: []};
                            var values = this.value();
                            angular.forEach(values, function (v) {
                                filter.filters.push({field: "abreviatura", operator: "eq", value: v});
                            });
                            $scope.data_alumnos.filter(filter);
                        }
                    });
                },
                extra: false
            }},
        {m_select: true, field: "descripcion", aggregates: ["count"],groupHeaderTemplate: "Descripcion Beca: #= value # (Cantidad: #= count#)", title: "Descripcion Beca", width: 200,
            filterable: {
                ui: function (element) {
                    element.removeAttr("data-bind");
                    element.kendoMultiSelect({
                        dataSource: $scope.filters_dd.descripcion,
                        change: function (e) {
                            var filter = {logic: "or", filters: []};
                            var values = this.value();
                            angular.forEach(values, function (v) {
                                filter.filters.push({field: "descripcion", operator: "eq", value: v});
                            });
                            $scope.data_alumnos.filter(filter);
                        }
                    });
                },
                extra: false
            }},
        {m_select: true, field: "matricula", title: "Matricula", width: 150,
            filterable: {
                ui: function (element) {
                    element.removeAttr("data-bind");
                    element.kendoMultiSelect({
                        dataSource: $scope.filters_dd.matricula,
                        change: function (e) {
                            var filter = {logic: "or", filters: []};
                            var values = this.value();
                            angular.forEach(values, function (v) {
                                filter.filters.push({field: "matricula", operator: "eq", value: v});
                            });
                            $scope.data_alumnos.filter(filter);
                        }
                    });
                },
                extra: false
            }},
        {m_select: true, field: "nom", title: "Nombre", width: 200},
        {m_select: true, field: "appat", title: "Apellido Paterno", width: 200},
        {m_select: true, field: "apmat", title: "Apellido Materno", width: 200},
        {m_select: true, field: "carrera", title: "Carrera", width: 100,
            filterable: {
                ui: function (element) {
                    element.removeAttr("data-bind");
                    element.kendoMultiSelect({
                        dataSource: $scope.filters_dd.carrera,
                        change: function (e) {
                            var filter = {logic: "or", filters: []};
                            var values = this.value();
                            angular.forEach(values, function (v) {
                                filter.filters.push({field: "carrera", operator: "eq", value: v});
                            });
                            $scope.data_alumnos.filter(filter);
                        }
                    });
                },
                extra: false
            }},
        {m_select: true, field: "grado", title: "Grado", width: 50},
        {m_select: true, field: "grupo", title: "Grupo", width: 50},
        {m_select: true, field: "periodo", title: "Periodo", width: 150},
        {m_select: true, field: "cancelada_por", title: "Cancelada Por", width: 200},
        {m_select: true, field: "cancelada_fecha", title: "Fecha Cancelacion", width: 200},
        {m_select: true, field: "cancelada_motivo", title: "Motivo Cancelacion", width: 200}
    ];

    /*
     *  $scope.filters_dd = {
     "carrera": [],
     "descripcion": [],
     "abreviatura": [],
     "matricula": []
     };
     *
     *
     * abreviatura: "BECA100"
     apmat: "MAGDALENO"
     appat: "MARTÍNEZ"
     carrera: "INGENIERÍA INDUSTRIAL"
     clave: "IND06B"
     created_at: "2014-11-27 21:10:23"
     curp: "MAML950324MASRGR09"
     descripcion: "BECA DEPORTIVA 100%"
     estatus_admin: "ACTIVO"
     fecha_nac: "1995-03-24"
     grado: "6"
     grupo: "B"
     id: 4
     idperiodo: "153"
     idpersonas: "5915"
     importe: 100
     matricula: "UP130549"
     nc: "IND"
     nom: "LAURA IMELDA"
     pe: "2010"
     periodo: 153
     subcidios_id: 1
     tipo_cobro: "PORCENTAJE"
     tipo_importe_id: 1
     tipobeca: null
     updated_at: "2014-11-27 21:10:23"
     */

    $scope.test_function = function (test) {
        console.log(test);
    };
    $scope.mainGridOptions = {
        toolbar: ["excel"],
        excel: {
            allPages: true
        },
        columnMenu: true,
        selectable: "multiple cell",
        allowCopy: true,
        sortable: true,
        reorderable: true,
        filterable: {
            messages: {
                info: "Elementos con valor que: ",
                and: "Y",
                or: "O",
                filter: "Aplicar Filtros",
                clear: "Limpiar Filtros"
            },
            operators: {
                string: {
                    eq: "Igual a",
                    startswith: "Empieza Con",
                    contains: "Contiene",
                    neq: "No Igaul a",
                    doesnotcontain: "No Contiene",
                    endswith: "Termina Con"
                },
                number: {
                    eq: "Igual a",
                    startswith: "Empieza Con",
                    contains: "Contiene",
                    neq: "No Igaul a",
                    doesnotcontain: "No Contiene",
                    endswith: "Termina Con"
                }
            }
        },
        messages: {
            commands: {
                excel: "Exportar Excel"
            }
        },
        groupable: {
            messages: {
                empty: "Arrastra columnas para Agrupar"
            },
            showFooter: true
        },
        scrollable: {
            virtual: true
        },
        height: 543,
        pageable: {
            info: true,
            numeric: false,
            previousNext: false
        },
        columnMenu: {
            messages: {
                sortAscending: "Ascendente",
                sortDescending: "Descendente",
                filter: "Filtrar",
                columns: "Columnas"
            }
        }

    };
    $scope.filters_dd = {
        "carrera": [],
        "descripcion": [],
        "abreviatura": [],
        "matricula": []
    };

    $scope.obtener_becas_periodo = function () {
        console.log($scope.model.periodo.idperiodo);
        $scope.isBusy = true;
        adminService.getAlumnosBecaPeriodo($scope.model.periodo.idperiodo)
                .then(function (data) {
                    $scope.isBusy = false;

                    angular.forEach(data.respuesta.data, function (v, k) {
                        if ($scope.filters_dd.carrera.indexOf(v.carrera) == -1) {
                            if (v.carrera !== null) {
                                $scope.filters_dd.carrera.push(v.carrera);
                            }
                        }
                        if ($scope.filters_dd.descripcion.indexOf(v.descripcion) == -1) {
                            if (v.carrera !== null) {
                                $scope.filters_dd.descripcion.push(v.descripcion);
                            }
                        }
                        if ($scope.filters_dd.abreviatura.indexOf(v.abreviatura) == -1) {
                            if (v.abreviatura !== null) {
                                $scope.filters_dd.abreviatura.push(v.abreviatura);
                            }
                        }
                        if ($scope.filters_dd.matricula.indexOf(v.matricula) == -1) {
                            if (v.matricula !== null) {
                                $scope.filters_dd.matricula.push(v.matricula);
                            }
                        }
                    });
                    $scope.data_alumnos = new kendo.data.DataSource({
                        data: data.respuesta.data,
                        pageSize: 20,
                        aggregate: [
                            {field: "abreviatura", aggregate: "count"},
                            {field: "descripcion", aggregate: "count"}
                        ]
                    });
                });
    };

    $scope.obtener_adeudos_periodo = function () {
        $scope.isBusy = true;
        $scope.model.status = 0;
        adminService.getAdeudosReporteOrdenadoPeriodo($scope.model).then(function (data) {
            $scope.isBusy = false;
            $scope.datos_filtros = [];
            key_service = data.respuesta.data.key;
            console.log(data);
            $scope.data_alumnos = {
                data: [],
                pageSize: 20, aggregate: [
                    {field: "beca", aggregate: "sum"},
                    {field: "descuento", aggregate: "sum"},
                    {field: "recargo", aggregate: "sum"},
                    {field: "total", aggregate: "sum"},
                    {field: "importe", aggregate: "sum"}
                ]
            };

            /*
             *
             *  {m_select: true, field: "abreviatura", title: "Abreviatura", width: 200},
             {m_select: true, field: "descripcion", title: "Descripcion", width: 200},
             {m_select: true, field: "matricula", title: "Matricula", width: 150, groupable: false},
             {m_select: true, field: "nom", title: "Nombre", width: 200, groupable: false},
             {m_select: true, field: "appat", title: "Apellido Paterno", width: 200, groupable: false},
             {m_select: true, field: "apmat", title: "Apellido Materno", width: 200, groupable: false},
             {m_select: true, field: "carrera", title: "Carrera", width: 100},
             {m_select: true, field: "grado", title: "Grado", width: 50, groupable: false},
             {m_select: true, field: "grupo", title: "Grupo", width: 50, groupable: false},
             {m_select: true, field: "periodo", title: "Periodo", width: 150},
             {m_select: true, field: "tipo_cobro", title: "Tipo Cobro", width: 150}
             */

        });
    };

});


text:
require 'argon2'
require 'active_record'
require 'active_support/all'

module AttrDigest
  extend ActiveSupport::Concern

  class Error < ::StandardError
  end

  class NoDigestException < Error
  end

  class InvalidMemoryCost < Error
  end

  class InvalidTimeCost < Error
  end

  class << self
    attr_accessor :time_cost
    attr_accessor :memory_cost
    attr_accessor :secret
  end

  self.time_cost = 2 # 1..10
  self.memory_cost = 16 # 1..31

  module ClassMethods
    def attr_digest(meth, *args, &block)
      attribute_sym = meth.to_sym
      attr_reader attribute_sym

      options = {
        validations: true,
        protected: false,
        case_sensitive: true,
        confirmation: true,
        time_cost: AttrDigest.time_cost,
        memory_cost: AttrDigest.memory_cost,
        secret: AttrDigest.secret
      }
      options.merge! args[0] unless args.blank?

      if options[:validations]
        add_confirmation_validation(attribute_sym) if options[:confirmation]
        validates attribute_sym, presence: true, on: :create
        before_create { raise "#{attribute_sym}_digest missing on new record" if send("#{attribute_sym}_digest").blank? }
      end

      if options[:format]
        add_format_validation(attribute_sym, options)
      end

      if options[:length]
        add_length_validation(attribute_sym, options)
      end

      define_setter(attribute_sym, options)
      protect_setter(attribute_sym) if options[:protected]
      define_authenticate_method(attribute_sym, options)
    end

    def add_confirmation_validation(attribute_sym)
      validates attribute_sym, confirmation: true, if: lambda { |m| m.send(attribute_sym).present? }
      validates "#{attribute_sym}_confirmation".to_sym, presence: true, if: lambda { |m| m.send(attribute_sym).present? }
    end

    def add_format_validation(attribute_sym, options)
      validates attribute_sym, format: options[:format], if: lambda { |m| m.send(attribute_sym).present? }
    end

    def add_length_validation(attribute_sym, options)
      validates attribute_sym, length: options[:length], if: lambda { |m| m.send(attribute_sym).present? }
    end

    def define_setter(attribute_sym, options)
      define_method "#{attribute_sym.to_s}=" do |unencrypted_value|
        if options[:memory_cost] < 1 || options[:memory_cost] > 31
          raise InvalidMemoryCost.new("Invalid memory cost, min 1 and max 31")
        end

        if options[:time_cost] < 1 || options[:time_cost] > 31
          raise InvalidTimeCost.new("Invalid time cost, min 1 and max 10")
        end

        password = if options[:secret]
          Argon2::Password.new(t_cost: options[:time_cost], m_cost: options[:memory_cost], secret: options[:secret])
        else
          Argon2::Password.new(t_cost: options[:time_cost], m_cost: options[:memory_cost])
        end

        if options[:validations] == true
          unless unencrypted_value.blank?
            instance_variable_set("@#{attribute_sym.to_s}".to_sym, unencrypted_value)
            send("#{attribute_sym.to_s}_digest=".to_sym, password.create(options[:case_sensitive] ? unencrypted_value : unencrypted_value.downcase))
          end
        else
          instance_variable_set("@#{attribute_sym.to_s}".to_sym, "#{unencrypted_value}")
          send("#{attribute_sym.to_s}_digest=".to_sym, password.create(options[:case_sensitive] ? "#{unencrypted_value}" : "#{unencrypted_value}".downcase))
        end
      end
    end

    def protect_setter(attribute_sym)
      define_method "#{attribute_sym}_digest=" do |value|
        write_attribute "#{attribute_sym}_digest".to_sym, value
      end
      protected "#{attribute_sym}_digest=".to_sym
    end

    def define_authenticate_method(attribute_sym, options)
      define_method "authenticate_#{attribute_sym}" do |value|
        digest = send("#{attribute_sym}_digest")
        if digest.blank?
          raise NoDigestException.new("Digest for #{attribute_sym} is nil, there is nothing to authenticate with.")
        end
        if options[:secret]
          Argon2::Password.verify_password((options[:case_sensitive] ? "#{value}" : "#{value}".downcase), digest, options[:secret])
        else
          Argon2::Password.verify_password((options[:case_sensitive] ? "#{value}" : "#{value}".downcase), digest)
        end
      end
    end

    protected :attr_digest
    protected :add_confirmation_validation
    protected :add_format_validation
    protected :add_length_validation
    protected :define_setter
    protected :protect_setter
    protected :define_authenticate_method
  end
end

ActiveRecord::Base.send :include, AttrDigest


text:
"""Command which launches both the MPF core engine and MPF-MC."""

from importlib import import_module
import multiprocessing

def _start_mpf(mpf_path, machine_path, args):
    module = import_module('mpf.commands.game')
    module.Command(mpf_path, machine_path, args)

def _start_mc(mpf_path, machine_path, args):
    module = import_module('mpfmc.commands.mc')
    module.Command(mpf_path, machine_path, args + ["--both"])

class Command:

    """Command which runs game and mc."""

    def __init__(self, mpf_path, machine_path, args):
        """Run game and mc."""
        multiprocessing.set_start_method('spawn')
        mc = multiprocessing.Process(target=_start_mc,
                                     args=(mpf_path, machine_path, args))
        mc.start()
        _start_mpf(mpf_path, machine_path, args)
        mc.join()


text:
/* Ross Baehr
   R@M 2017
   ross.baehr@gmail.com
*/

#ifndef _EXAMPLE_BLINK_H_
#define _EXAMPLE_BLINK_H_

#include "include/task_constants.h"
#include "lib/include/rgb.h"

// FreeRTOS
#include <FreeRTOS.h>
#include <queue.h>
#include <task.h>
#include <semphr.h>

// Tiva
#include <stdbool.h>
#include <stdint.h>
#include <inc/hw_memmap.h>
#include <inc/hw_types.h>
#include <driverlib/gpio.h>
#include <driverlib/pin_map.h>
#include <driverlib/rom.h>
#include <driverlib/sysctl.h>
#include <driverlib/uart.h>
#include <utils/uartstdio.h>

#define RED_LED   GPIO_PIN_1
#define BLUE_LED  GPIO_PIN_2
#define GREEN_LED GPIO_PIN_3

static void example_blink_task(void *params);

bool example_blink_init(void);

#endif


text:
// Load modules
var express = require('express');
var requirejs = require('requirejs');

// We want to load with requirejs for consistency with the front-end
// We pass in node's require here, so we can fall back to that if requirejs fails
requirejs.config({
    nodeRequire: require,
});

// Load config and server
var Config = requirejs("./config"); // We assume config.js is in the same folder
var LoomisServer = requirejs(Config.LOOMIS_SERVER_PATH);

// Create the API with routing, so we can bind it to a port
/** @var {express} api */
var LoomisAPI = express();

/**
 * Fetch the markup for a component
 */
LoomisAPI.get('/componentMarkup', function(request, response) {
	/** @var {string} componentType */
	var componentType = request.query.componentType;
	/** @var {object} props */
	var props = JSON.parse(request.query.props || '{}');
	/** @var {object} renderOptions */
	var renderOptions = JSON.parse(request.query.renderOptions || '{}');
	/** @var {string} componentMarkup */
	var componentMarkup = LoomisServer.getComponentMarkup(componentType, props, renderOptions);

	response.send(componentMarkup);
});

/**
 * Fetch the Component Library entry for a component
 */
LoomisAPI.get('/componentLibraryEntry', function(request, response) {
	/** @var {string} componentType */
	var componentType = request.query.componentType;
	/** @var {object} libraryEntry */
	var componentEntry = LoomisServer.getComponentLibraryEntry(componentType);

	response.send(JSON.stringify(componentEntry));
});

/**
 * Fetch a component library's category
 */
LoomisAPI.get('/componentLibraryCategory', function(request, response) {
	/** @var {sting} libraryRef */
	var libraryRef = request.query.libraryRef;
	/** @var {sting} categoryRef */
	var categoryRef = request.query.categoryRef;
	/** @var {object} categoryData */
	var categoryData = LoomisServer.getComponentLibraryCategory(libraryRef, categoryRef);

	response.send(JSON.stringify(categoryData));
});

/**
 * Fetch an entire component library
 */
LoomisAPI.get('/componentLibrary', function(request, response) {
	/** @var {sting} libraryRef */
	var libraryRef = request.query.libraryRef;
	/** @var {object} libraryData */
	var libraryData = LoomisServer.getComponentLibrary(libraryRef);

	response.send(JSON.stringify(libraryData));
});

// Bind to port
LoomisAPI.listen(Config.LOOMIS_SERVER_PORT);


text:
RobotHandler::RobotHandler(QString serialPort, int bitRate, QObject *parent) : QObject(parent)
{
    m_serialPortName = serialPort;
    m_bitRate = bitRate;
    // Try to open
    m_serialPort.setBaudRate(bitRate == 9600 ? QSerialPort::Baud9600 : bitRate);
    m_serialPort.setPortName(serialPort);
    m_portOpen = m_serialPort.open(QIODevice::ReadWrite);
    connect( &m_serialPort, SIGNAL(readyRead()), this, SLOT(GetResponses()) );
    if (m_portOpen)
    {
        connect( &m_serialPort, SIGNAL(dataTerminalReadyChanged(bool)), this, SLOT(dataTerminalReadyChanged(bool)) );
        connect( &m_serialPort, SIGNAL(error(QSerialPort::SerialPortError)), this, SLOT(error(QSerialPort::SerialPortError)) );
        connect( &m_serialPort, SIGNAL(flowControlChanged(QSerialPort::FlowControl)), this, SLOT(flowControlChanged(QSerialPort::FlowControl)) );
        connect( &m_serialPort, SIGNAL(requestToSendChanged(bool)), this, SLOT(requestToSendChanged(bool)) );
    }
}

RobotHandler::~RobotHandler()
{
    if (m_portOpen)
    {
        m_serialPort.close();
        m_portOpen = false;
    }
}

bool RobotHandler::SendCmd(QString s)
{
    if (!m_portOpen) return false;
    GetResponses();
    emit ShowMsg(m_serialPortName + ": sending " + s);
    if (m_requiresAck)
    {
        m_serialPort.setRequestToSend(true);
    }
    int bytesWritten = m_serialPort.write(s.toLocal8Bit());
    m_serialPort.flush();
    if (m_requiresAck)
    {
        //m_serialPort.setRequestToSend(false);
        //m_serialPort.setDataTerminalReady(true);
    }
    if (bytesWritten != s.length()) emit ShowMsg("Error: send " + s + "failed");
    return bytesWritten == s.length();
}

QString RobotHandler::Read(int timeout)
{
    if (!m_portOpen) return QString();
    if (!m_serialPort.waitForReadyRead(timeout))
    {
        //emit ShowMsg(QString().sprintf("Read(%d) timeout elapsed", timeout));
        return QString();
    }
    return m_serialPort.readAll();
}

void RobotHandler::GetResponses()
{
    if (!m_portOpen) return;
    QString s;
    while (!m_serialPort.atEnd())
    {
        s = Read(250);
        if (s.isEmpty()) break;
        emit ShowMsg(m_serialPortName + ": " + s);
    }
}

void	RobotHandler::dataTerminalReadyChanged(bool set)
{
    //emit ShowMsg(m_serialPortName + " DTR changed");
}

void	RobotHandler::error(QSerialPort::SerialPortError error)
{
    switch (error)
    {
    case QSerialPort::UnsupportedOperationError:
    case QSerialPort::TimeoutError:
        return;
    }

    emit ShowMsg(m_serialPortName + QString().sprintf(" error %d: ", error)  + m_serialPort.errorString());
}

void	RobotHandler::flowControlChanged(QSerialPort::FlowControl flow)
{
    //emit ShowMsg(m_serialPortName + " flow changed");
}

void	RobotHandler::requestToSendChanged(bool set)
{
    //emit ShowMsg(m_serialPortName + " rts changed");
}


text:
extern "C" {
#endif

  bool init_model(char fname[], int type);
  void fakeusb_send(int ep, unsigned char data[], size_t length);
  void fakeusb_receive(int ep, unsigned char data[], size_t length, size_t *read, int timeout);
  void close_model();
  void print_packet(unsigned char data[], size_t length);

#ifdef __cplusplus
}

#include <string>
#include <vector>
#include <queue>
#include <iostream>
#include <sstream>
#include <fstream>

typedef std::vector<unsigned char> packet_t;

//Reads-in input packets from the specified file
//
class input_data
{
 public:
  input_data(std::string fname) :
    f(fname.c_str(), std::fstream::in){};
  bool read_next(packet_t &data);
 private:
  std::ifstream f;
  std::istringstream is;
  std::string str;
};

class device_model
{
 public:
  device_model(std::string fname) : inp_data(fname){};
  virtual ~device_model(){};
  virtual bool send_packet(int ep, unsigned char packet[], size_t length) = 0;
  virtual bool receive_packet(int ep, unsigned char packet[], size_t length,
                              size_t *read, int timeout) = 0;
  size_t pkt_buf_size(){return packet_buffer.size();};
  void print_packet(int ep, unsigned char data[], size_t length);
 protected:
  size_t packet2data(const packet_t packet, unsigned char data[], size_t length);
  void data2packet(const unsigned char data[], const size_t length, packet_t &packet);
  void enqueue_packet(const unsigned char data[], const size_t length);
  void enqueue_packet(const packet_t &packet);
  input_data inp_data;
  std::queue<packet_t> packet_buffer;
};

class tir5v3 : public device_model
{
 public:
  tir5v3(std::string fname);
  virtual ~tir5v3(){};
  virtual bool send_packet(int ep, unsigned char packet[], size_t length);
  virtual bool receive_packet(int ep, unsigned char packet[], size_t length,
                              size_t *read, int timeout);
 private:
  int state;
  bool camera_on;
  virtual bool change_state(unsigned char new_state);
  virtual bool get_config();
  virtual bool report_state();
  virtual bool set_register(unsigned char v0, unsigned char v1,
                            unsigned char v2, unsigned char v3);
  bool camera_off();
  int deobfuscate_command(unsigned char packet[], unsigned char command[]);
};

class smartnav3 : public device_model
{
 public:
  smartnav3(std::string fname);
  virtual ~smartnav3(){};
  virtual bool send_packet(int ep, unsigned char packet[], size_t length);
  virtual bool receive_packet(int ep, unsigned char packet[], size_t length,
                              size_t *read, int timeout);
 protected:
  virtual void video_on(){video_on_flag = true; camera_on_flag = true;};
  virtual void video_off(){video_on_flag = false;};
  virtual void camera_off(){camera_on_flag = false;};
  virtual void set_leds(unsigned char leds, unsigned char mask);
  virtual void get_config();
  virtual void set_threshold(int thr);

  bool video_on_flag;
  bool camera_on_flag;
  bool led_r, led_g, led_b, led_ir;
  int threshold;
};

class tir4 : public smartnav3
{
 public:
  tir4(std::string fname);
  virtual ~tir4(){};
  virtual bool send_packet(int ep, unsigned char packet[], size_t length);
 protected:
  virtual void get_config();
  virtual void get_status();
  virtual void do_whatever();
  virtual void load_firmware(const unsigned char data[], const size_t length);

  bool firmware_loaded;
  unsigned int firmware_csum;
  bool firmware_active;
};

class smartnav4 : public tir4
{
 public:
  smartnav4(std::string fname);
  virtual ~smartnav4(){};
 private:
  virtual void get_config();
  virtual void do_whatever();
};

class tir5: public tir4
{
 public:
  tir5(std::string fname);
  virtual ~tir5(){};
 private:
  virtual void get_config();
  virtual void do_whatever();
};

#endif

#endif


text:
package course.examples.UI.CheckBox;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;

public class CheckBoxActivity extends Activity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Get a reference to the CheckBox
		final CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);

		// Set an OnClickListener on the CheckBox
		checkbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				// Check whether CheckBox is currently checked
				// Set CheckBox text accordingly
				if (checkbox.isChecked()) {
					checkbox.setText("I'm checked");
				} else {
					checkbox.setText("I'm not checked");
				}
			}
		});

		// Get a reference to the Hide CheckBox Button
		final Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				// Toggle the CheckBox's visibility state
				// Set the Button text accordingly
				if (checkbox.isShown()) {
					checkbox.setVisibility(View.INVISIBLE);
					button.setText("Unhide CheckBox");
				} else {
					checkbox.setVisibility(View.VISIBLE);
					button.setText("Hide CheckBox");
				}
			}
		});
	}
}


text:
<!DOCTYPE HTML>

    <title>SIMILE Widgets | Exhibit | Examples | Election 08</title>
    <link rel='stylesheet' href='http://www.simile-widgets.org/styles/common.css' type='text/css' />

    <link rel="exhibit/data" href="us-state-borders-coarse.json" />
    <link rel="exhibit/data" href="vote-for.json" />

    <link rel="exhibit-extension" href="../api/extensions/map/map-extension.js" data-ex-apikey="AIzaSyCDO3EXWKJms5T38db48czFJZDunhYIzn8" />

SIMILE Widgets

Exhibit

Election 08

Election 08

                    McCain
                    Obama
                    Tossup
                    Leaning McCain
                    Leaning Obama
                    Unknown

                <div data-ex-role="view"
                    data-ex-view-class = "Map"
                    data-ex-polygon=".border"
                    data-ex-border-color="white"
                    data-ex-border-width="3"
                    data-ex-border-opacity="1"
                    data-ex-center="36.498367,-94.618156"
                    data-ex-map-height="600"
                    data-ex-latlng-pair-separator="|"
                    data-ex-color-key=".vote-for"
                    data-ex-color-coder="vote-for-colors"
                    data-ex-zoom="4"
                    >