text:
<?php

namespace Isssr\CoreBundle\Services;

use Isssr\CoreBundle\Entity\UserInGoal;
use Isssr\CoreBundle\Entity\User;
use Isssr\CoreBundle\Entity\Goal;
use Isssr\CoreBundle\Entity\Question;

use Doctrine\ORM\EntityManager;
use Doctrine\Common\Collections\ArrayCollection;

class NotifierManager
{
    private $em;
    private $mailer;

    public function __construct(EntityManager $em, $mailer){
        $this->em = $em;
        $this->mailer = $mailer;
    }

    public function askSupersForValidation(Goal $goal)
    {
        $supers = $goal->getSupers();
        $body = null;
        if ($goal->editable()) $body = $this->bodySuperFirstSent($goal);
        else $body = $this->bodySuperOtherSent($goal);
        foreach ($supers as $super)
        {
            $this->sendMessage($body, $super);
        }
    }

    public function notifyOwnerSuperAcceptance(Goal $goal, User $super)
    {
        $body = $this->bodySuperAccept($super, $goal);
        $this->sendMessage($body, $goal->getOwner());
    }

    public function notifyOwnerSuperRejection(Goal $goal, User $super)
    {
        $body = $this->bodySuperReject($super, $goal);
        $this->sendMessage($body, $goal->getOwner());
    }

    public function askEnactorForValidation(Goal $goal)
    {
        $enactor = $goal->getEnactor();
        $body = $this->bodyEnactor($goal);

        $this->sendMessage($body, $enactor);
    }

    public function notifyOwnerEnactorAcceptance(Goal $goal, User $enactor)
    {
        $body = $this->bodyEnactorAccept($enactor, $goal);
        $this->sendMessage($body, $goal->getOwner());
    }

    public function notifyOwnerEnactorRejection(Goal $goal, User $enactor)
    {
        $body = $this->bodyEnactorReject($enactor, $goal);
        $this->sendMessage($body, $goal->getOwner());
    }

    public function notifyOtherRoles(UserInGoal $role)
    {
        $body = null;
        if ($role->getRole() == UserInGoal::ROLE_MMDM) $body = $this->bodyMmdm($role->getGoal());
        else if ($role->getRole() == UserInGoal::ROLE_QS) $body = $this->bodyQs($role->getGoal());
        $this->sendMessage($body, $role->getUser());
    }

    public function notifyQssNewMeasure(Goal $goal)
    {
    	$body = $this->bodyNewMeasure($goal);
    	$qss = $goal->getQss();
    	foreach ($qss as $qs) $this->sendMessage($body, $qs);
    }

    public function questionAccepted(Question $question)
    {
    	$goal = $question->getCreator()->getGoal();
    	$user = $question->getCreator()->getUser();
    	$text = $question->getQuestion();
    	$body = $this->bodyQuestionAccepted($goal, $user, $text);
    	$this->sendMessage($body, $user);
    }

    public function questionRejected(Question $question)
    {
    	$goal = $question->getCreator()->getGoal();
    	$user = $question->getCreator()->getUser();
    	$text = $question->getQuestion();
    	$motivation = $question->getRejectform()->getText();
    	$body = $this->bodyQuestionRejected($goal, $user, $text, $motivation);
    	$this->sendMessage($body, $user);
    }

    public function questionSetClosed(Goal $goal)
    {
    	$qss = $goal->getQss();
    	$body = $this->bodyQuestionSetClosed($goal);
    	foreach ($qss as $qs)
    		$this->sendMessage($body, $qs);
    }

    private function sendMessage($body, User $receiver)
    {
        $message = \Swift_Message::newInstance()

            ->setSubject('ISSSR Notifier')

            ->setFrom('isssr@isssr.org')

            ->setTo($receiver->getEmail())

            ->setBody(

                $body

            );

        $this->mailer->send($message);
    }

    private function bodySuperFirstSent(Goal $goal)
    {
        return 'We are kindly informing you that you are now a Goal Super Owner of the goal '.$goal->getTitle();
    }

    private function bodySuperOtherSent(Goal $goal)
    {
        return 'The Goal '.$goal->getTitle().', which some super owner previously refused, has been modified, Validate it agan, please';
    }

    private function bodySuperAccept(User $user, Goal $goal)
    {
        return 'The Goal Super Owner '.$user->getUsername().' did accept the goal '.$goal->getTitle();
    }

    private function bodySuperReject(User $user, Goal $goal)
    {
        return 'The Goal Super Owner '.$user->getUsername().' did reject the goal '.$goal->getTitle();
    }

    private function bodyEnactor(Goal $goal)
    {
        return "The Goal owner ".$goal->getOwner()." selected you as the Enactor for the Goal ".$goal->getTitle().".";
    }

    private function bodyEnactorAccept(User $user, Goal $goal)
    {
        return 'The proposed Goal Enactor '.$goal->getEnactor()->getUsername().' for the Goal '.$goal->getTitle().' did accept your proposal.';
    }

    private function bodyEnactorReject(User $user, Goal $goal)

    {

        return 'The proposed Goal Enactor '.$goal->getEnactor()->getUsername().' for the Goal '.$goal->getTitle().' did reject your proposal.';

    }

    private function bodyMmdm(Goal $goal)
    {
        return 'The goal enactor '.$goal->getEnactor()->getUsername().' included you in the MMDMs for the goal '.$goal->getTitle().'.';
    }

    private function bodyQs(Goal $goal)
    {
        return "We are kindly informing you that ".$goal->getEnactor()->getUsername().", as enactor of the goal ".$goal->getTitle().", did define you as a Question Stakeholder for that goal";
    }

    private function bodyQuestionAccepted(Goal $goal, User $user, $text)
    {
    	return 'Dear '.$user->getUsername().', the goal enactor '.$goal->getEnactor()->getUsername().' accepted your question "'.$text.'" concerning the goal '.$goal->getTitle().'.';
    }

    private function bodyQuestionRejected(Goal $goal, User $user, $text, $motivation)
    {
    	return 'Dear '.$user->getUsername().', the goal enactor '.$goal->getEnactor()->getUsername().' did reject your question "'.$text.'" concerning the goal '.$goal->getTitle().' with motivation: '.$motivation.'.';
    }

    private function bodyQuestionSetClosed(Goal $goal)
    {
    	return 'The set of the questions for the goal '.$goal->getTitle().' has been accepted by the goal enactor '.$goal->getEnactor()->getUsername();
    }

    private function bodyNewMeasure(Goal $goal)
    {
    	return 'A new Measure has been provided for the goal '.$goal->getTitle();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- zame:layout_yWeight = 1 - 0.075 -->
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:zame="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rate_game_wrap"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    zame:layout_heightWeight="0.075"
    zame:layout_x="0dp"
    zame:layout_yWeight="0.925"
    android:background="#080"
    android:visibility="gone"
>
    <TextView
        android:fontFamily="gloomy"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textColor="#FFF"
        android:gravity="center"
        android:textSize="@dimen/gloomy_menu_textsize"
        android:text="@string/menu_rate_game"
    />
</FrameLayout>

redpajama_set_name: RedPajamaGithub


text:
// @flow
/* eslint-env mocha */
/* global suite, benchmark */

import subMilliseconds from '.'
import moment from 'moment'

suite('subMilliseconds', function () {
  benchmark('date-fns', function () {
    return subMilliseconds(this.date, 800)
  })

  benchmark('Moment.js', function () {
    return this.moment.subtract(800, 'milliseconds')
  })
}, {
  setup: function () {
    this.date = new Date()
    this.moment = moment()
  }
})


text:
<?php

namespace Haverkamp87\UserBundle\Command;

use Doctrine\ORM\EntityManager;
use Haverkamp87\UserBundle\Entity\LanguageInterface;
use Haverkamp87\UserBundle\Entity\User;
use Haverkamp87\UserBundle\Entity\UserGroup;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoder;

/**
 * Class CreateUserCommand
 * @package Haverkamp87\UserBundle\Command
 */
class CreateUserCommand extends ContainerAwareCommand
{

    /**
     * {@inheritdoc}
     */
	protected function configure()
	{
		$this
			->setName('haverkamp87_user:create_user')
			->setDescription('Create a new user');
	}

    /**
     * {@inheritdoc}
     */
	protected function execute(InputInterface $input, OutputInterface $output)
	{
	    /** @var EntityManager $entityManager */
		$entityManager = $this->getContainer()
			->get('doctrine')
			->getManager();

        // style the output
        $io = new SymfonyStyle($input, $output);
        $io->title('Create a new user');

        // get the user repository
        $userRepository = $entityManager->getRepository('Haverkamp87UserBundle:User');

        // check if the user exists (by email)
        $user = $userRepository->findOneBy(array(
            'email' => ($email = $io->ask('What is the email address?')),
        ));

        // there is already a user with this email address
        if ($user instanceof User) {
            $io->error(sprintf("There is already a user with email address '%s'.", $email));
            return 1;
        }

        // gather the remaining (non-unique) data
        $password       = $io->askHidden('What is the password?');
        $gender         = $io->choice('What is the gender?', array('male', 'female'));
        $firstName      = $io->ask('What is the first name?');
        $lastName       = $io->ask('What is the last name?');

        // convert date of birth to \DateTime object
        $dateOfBirth = \DateTime::createFromFormat(
            'd/m/Y',
            $io->ask('What is the date of birth? (DD/MM/YYYY)')
        );

        // get the user group repository
        $userGroupRepository = $entityManager->getRepository('Haverkamp87UserBundle:UserGroup');
        $userGroups = $userGroupRepository->findBy(array(
            'active' => true,
        ), array(
            'name' => 'ASC'
        ));

        // get active user groups
        $availableUserGroups = array();
        foreach ($userGroups as $userGroup) {
            /** @var UserGroup $userGroup */

            $availableUserGroups[] = $userGroup->getName();
        }

        // get the language repository
        $languageRepository = $entityManager->getRepository('Haverkamp87UserBundle:LanguageInterface');
        $languages = $languageRepository->findBy(array(
            'active' => true,
        ), array(
            'name' => 'ASC'
        ));

        // get active languages
        $availableLanguages = array();
        foreach ($languages as $language) {
            /** @var LanguageInterface $language */

            $availableLanguages[] = $language->getName();
        }

        // get user group by name
        $userGroup  = $userGroupRepository->findOneBy(array(
            'name' => $io->choice('What is the user group?', $availableUserGroups),
        ));

        // get language by name
        $language   = $languageRepository->findOneBy(array(
            'name' => $io->choice('What is the language?', $availableLanguages),
        ));

        $active     = $io->confirm('Would you like to activate your new user?');

        // create new user
        $user = new User();
        $user->setGender($gender);
        $user->setFirstName($firstName);
        $user->setLastName($lastName);
        $user->setDateOfBirth($dateOfBirth);
        $user->setEmail($email);
        $user->setUserGroup($userGroup);
        $user->setLanguage($language);
        $user->setActive($active);

        // encode the given password
        if (!empty($password)) {

            /** @var UserPasswordEncoder $encoder */
            $encoder = $this->getContainer()
                ->get('security.password_encoder');

            $user->setHash(
                $encoder->encodePassword($user, $password)
            );
        }

        /** @var ValidatorInterface $validator */
        $validator = $this->getContainer()
            ->get('validator');

        // validate the user
        $errors = $validator->validate($user);
        if (count($errors) > 0) {
            // output error message(s)
            foreach ($errors as $error) {
                $io->error($error->getMessage());
            }

            return 1;
        } else {
            // save the new user
            $entityManager->persist($user);
            $entityManager->flush();

            $io->success(sprintf("A new user '%s' is created.", (string) $user));
            return 0;
        }
	}

}


text:
/*	CFBase.c
	Copyright (c) 1998-2009, Apple Inc. All rights reserved.
	Responsibility: Christopher Kane
*/

#ifndef THIRD_PARTY_APPLE_APSL_CFBASE_H_
#define THIRD_PARTY_APPLE_APSL_CFBASE_H_

#include "CFRuntime.h"

struct ChromeCFAllocator9and10 {
    ChromeCFRuntimeBase _base;
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED
    size_t (*size)(struct _malloc_zone_t *zone, const void *ptr); /* returns the size of a block or 0 if not in this zone; must be fast, especially for negative answers */
    void *(*malloc)(struct _malloc_zone_t *zone, size_t size);
    void *(*calloc)(struct _malloc_zone_t *zone, size_t num_items, size_t size); /* same as malloc, but block returned is set to zero */
    void *(*valloc)(struct _malloc_zone_t *zone, size_t size); /* same as malloc, but block returned is set to zero and is guaranteed to be page aligned */
    void (*free)(struct _malloc_zone_t *zone, void *ptr);
    void *(*realloc)(struct _malloc_zone_t *zone, void *ptr, size_t size);
    void (*destroy)(struct _malloc_zone_t *zone); /* zone is destroyed and all memory reclaimed */
    const char	*zone_name;
    unsigned (*batch_malloc)(struct _malloc_zone_t *zone, size_t size, void **results, unsigned num_requested); /* given a size, returns pointers capable of holding that size; returns the number of pointers allocated (maybe 0 or less than num_requested) */
    void (*batch_free)(struct _malloc_zone_t *zone, void **to_be_freed, unsigned num_to_be_freed); /* frees all the pointers in to_be_freed; note that to_be_freed may be overwritten during the process */
    struct malloc_introspection_t	*introspect;
    void	*reserved5;
#endif
    CFAllocatorRef _allocator;
    CFAllocatorContext _context;
};

// TODO(avi): update upon source release; http://crbug.com/74589
struct ChromeCFAllocator11 {
  ChromeCFRuntimeBase _base;
  // CFAllocator in Darwin 9 included a complete copy of _malloc_zone_t. The
  // version in Darwin 10 had an abbreviated _malloc_zone_t that ended after the
  // version/"reserved" field (see above). Darwin 11 appears to have a truncated
  // _malloc_zone_t as well, but two fields larger than 9/10.
  void* presumedSizeFunctionPtr;
  void* presumedMallocFunctionPtr;
  void* presumedCallocFunctionPtr;
  void* presumedVallocFunctionPtr;
  void* presumedFreeFunctionPtr;
  void* presumedReallocFunctionPtr;
  void* presumedDestroyFunctionPtr;
  const char *zone_name;
  void* presumedBatchMallocFunctionPtr;
  void* presumedBatchFreeFunctionPtr;
  void* presumedIntrospectStructPtr;
  void* presumedReservedSlashVersion;  // always 6 in CFAllocators
  void* presumedMemalignFunctionPtr;
  void* presumedFreeDefiniteSizeFunctionPtr;
  CFAllocatorRef _allocator;
  CFAllocatorContext _context;
};

#endif  // THIRD_PARTY_APPLE_APSL_CFBASE_H_


text:
namespace base {

// Helper for methods which perform file system operations and which may fail.
// Objects of this type can take on EITHER a base::File::Error value OR a result
// value of the specified type.
template <typename ValueType>
class FileErrorOr {
 public:
  // These constructors are intentionally not marked `explicit` for cleaner code
  // at call sites.
  FileErrorOr(File::Error error) : value_or_error_(unexpected(error)) {}
  FileErrorOr(ValueType&& value) : value_or_error_(std::move(value)) {}
  FileErrorOr(const FileErrorOr&) = default;
  FileErrorOr(FileErrorOr&&) = default;
  FileErrorOr& operator=(const FileErrorOr&) = default;
  FileErrorOr& operator=(FileErrorOr&&) = default;
  ~FileErrorOr() = default;

  bool is_error() const { return !value_or_error_.has_value(); }
  File::Error error() const { return value_or_error_.error(); }

  bool is_value() const { return value_or_error_.has_value(); }
  ValueType& value() { return value_or_error_.value(); }
  const ValueType& value() const { return value_or_error_.value(); }

  ValueType* operator->() { return &value(); }
  const ValueType* operator->() const { return &value(); }

 private:
  expected<ValueType, File::Error> value_or_error_;
};

}  // namespace base

#endif  // BASE_FILES_FILE_ERROR_OR_H_


text:
  <mat-form-field>
    <input matInput placeholder="group search" [(ngModel)]="organisationFilter" (keyup.enter)="Refresh()">
    <button mat-button *ngIf="organisationFilter" matSuffix mat-icon-button aria-label="clear"
      (click)="organisationFilter='';Refresh()">
      <mat-icon>close</mat-icon>
    </button>
  </mat-form-field>

  <button mat-stroked-button matTooltip="refresh group membership list" (click)="Refresh()">
    search
    <mat-icon>search</mat-icon>
  </button>

Select an organisation

  {{ organisation.organisationName }}

    Loading...

  {{ message }}

  {{ error }}


text:
body {
    font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, sans-serif;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<alpha android:duration="667" android:fromAlpha="0.2" android:toAlpha="1.0"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
package christophedelory.playlist.xspf;

/**
 * A string container.
 * @version $Revision: 92 $
 * @author Christophe Delory
 * @castor.class xml="text" ns-uri="http://xspf.org/ns/0/"
 */
public class StringContainer
{
    /**
     * The string itself.
     */
    private String _text = null;

    /**
     * Returns the string itself.
     * @return a string. May be null.
     * @see #setText
     * @castor.field
     *  get-method="getText"
     *  set-method="setText"
     * @castor.field-xml
     *  node="text"
     */
    public String getText()
    {
        return _text;
    }

    /**
     * Initializes the string itself.
     * @param text a string. May be null.
     * @see #getText
     */
    public void setText(final String text)
    {
        _text = text;
    }
}


text:
- Edit `/etc/dhcpcd.conf`
- Add the following to the end of the file;
```
interface eth0
static ip_address=192.168.0.1/24
```
- reboot
	- `sudo reboot`
- check ip address. It should match the static address in the .conf file
	- `ifconfig eth0`

## Setup uv4l

- `curl http://www.linux-projects.org/listing/uv4l_repo/lrkey.asc | sudo apt-key add -`
- Add `deb http://www.linux-projects.org/listing/uv4l_repo/raspbian/ jessie main` to `/etc/apt/sources.list`
- `sudo apt-get update`
- `sudo apt-get install uv4l uv4l-raspicam uv4l-server uv4l-raspicam-extras`
- Update`/etc/uv4l/uv4l-raspicam.conf`
	- Uncomment and set
		- encoding = mjpeg
		- width = 1296
		- height = 976
		- framerate = 24
		- quality = 10
		- nopreview = yes
	- Restart the service with `sudo service u4vl_raspicam restart`

## Miscellaneous

- `sudo pip3 install adafruit-pca9685`
- `sudo apt-get install vim`
- `sudo apt-get install netatalk`
- `sudo pip3 pymongo`
- `sudo apt-get install i2c-tools`
- setup .ssh directory on Raspberry Pi
```
cd ~
install -d -m 700 ~/.ssh
```
- Send ssh key to Pi from client machine
```
cat ~/.ssh/id_rsa.pub | ssh <USERNAME>@<IP-ADDRESS> 'cat >> .ssh/authorized_keys'
```

## I2C Addresses

### Sense Hat

- [Python Library Source](https://github.com/RPi-Distro/python-sense-hat)
- [RTIMULib Source](https://github.com/RPi-Distro/RTIMULib)

| id      | Chip     | Role |
| ------- | ----     | ---- |
| 1C      | LSM9DS1  | IMU - Magnetometer            |
| 46 (UU) | LED2472G | LEDs                          |
| 5C      | LPS25H   | Pressure/Temperature Sensor   |
| 5F      | HTS221   | Humidity/Temperature Sensor   |
| 6A      | LSM9DS1  | IMU - Accelerometer/Gyroscope |


text:
"""
Unit Tests for the Swinging Wild problem
for Google Code Jam 2012
Round 2

Link to problem description:
http://code.google.com/codejam/contest/1842485/dashboard#s=p0

Author:
  Chris Nitsas
  (nitsas)

Language:
  Python 3(.3)

Date:
  May, 2012

Usage:
  python3 test_runme.py
"""

import io
import sys
import unittest
# modules I've written:
import runme

class TestRunme(unittest.TestCase):
    """
    Unit Tests for the Swinging Wild problem
    for Google Code Jam 2012
    Round 2
    """

    # define if needed
    #def setUp(self):
    #    pass

    # define if needed
    #def tearDown(self):
    #    pass

    #def test_something(self):
    #    # use self.assertEqual(), self.assertTrue() or self.assertRaises()
    #    pass

    def test_main_on_sample_in(self):
        # call runme.main and get it's output into from_main
        with io.StringIO() as target_output_stream:
            # redirect stdout to an io.StringIO object to run main
            sys.stdout, old_stdout = target_output_stream, sys.stdout
            runme.main('sample.in')
            from_main = target_output_stream.getvalue()
            # get original stdout back
            sys.stdout = old_stdout
        # get the 'sample.out' file's contents
        with open('sample.out', 'r', encoding='utf-8') as sample_out:
            from_sample_out = sample_out.read()
        # compare runme.main's results with sample.out's contents
        self.assertEqual(from_main, from_sample_out)

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


text:
layout: id-ID/default
title: Contributing to Rust — language, compiler, and the standard library · The Rust Programming Language
---

# Contributing to Rust — language, compiler, and the standard library

The source code to the compiler and standard library are in the main
repository, and as their maintenance is the primary objective of that
repository, many labels on the issue tracker relate to it. Some of
the more fruitful labels include [A-codegen], for translation of
Rust to LLVM IR; [A-debuginfo], generation of metadata used by debuggers;
[A-diagnostics], the feedback the compiler provides on errors; [A-libs],
issues with the standard library; [A-macros] and [A-syntaxext], both
related to syntax extensions; and [A-typesystem], on the topic of types.

There is no well-maintained guide to the architecture of the compiler,
but [there is a small overview in-tree][rustc-guide]. The [API
documentation for the crates that make up the
compiler][internals-docs] can help with navigating the code, as can
the source code browser [Rust DXR]. The [guide to the Rust test
suite][testsuite] will teach you how to exercise the Rust build system
effectively, as will running [`make tips`][tips] at the command line.

For the foreseable future, one of the major thrusts of Rust compiler
development is converting its internals from operating directly off
the AST to working with an [intermediate representation called
MIR][mir]. This work is expected to open up many new possibilities by
simplifying the compiler and help is needed to e.g. create a MIR-based
translation pass, add MIR-based optimizations, and implement
incremental compilation. There is yet no single source for information
on work needed here, but ask on [internals.rust-lang.org] or
[#rust-internals] for guidance.

[It's embarrasing when our compiler crashes][ice] — the
dreaded 'internal compiler error' (ICE). The [I-ICE] label
tracks these, and they are often plentiful. These are usually
good bugs to start with because it's easy to know when you've fixed
them, and they're often relatively self-contained.

The performance of Rust code is one of its great advantages; and the
performance of the Rust compiler one of its great weaknesses. Any
improvements to either runtime or — especially — compiletime performance
are widely celebrated. The [I-slow] and [A-optimization] labels deal
with runtime performance, and [I-compiletime] with compiletime. We have
a [site that tracks compiletime performance][rustc-perf] on a number
of workloads. The `-Z time-passes` compiler flag can help debug
compiler performance, and Rust code can be profiled with standard
profilers like `perf` on Linux.

Major new features go through a [Request for Comments (RFC)][rfc]
process, by which the design is agreed upon. Though it is open to all,
it is a social process between developers who already have various
amounts of experience working together, and it is recommended to get
involved slowly — submitting a hasty RFC without understanding
the historical, technical, or social context is an easy way
to make a poor impression and come away disappointed. Read the
aforelinked readme file to understand best how it all works. Many
ideas have been debated in Rust's history, some rejected, some
postponed until the future, and the RFC [issue tracker][rfc-issues]
catalogs some wishlist ideas that have yet to make headway into the
language. Shortly before an RFC is accepted for implementation it
enters 'final comment period', indicated by the [final-comment-period
label on the rust-lang/rfcs repository][rfc-fcp]. Likewise, before a
feature is enabled in the stable compiler (called 'ungating') it
enters [final-comment-period in the rust-lang/rust
repository][issue-fcp]. Both FCPs are critical moments to get involved
and express opinions on the direction of the language, and are
advertised in the weekly subteam reports on [internals.rust-lang.org].

Meet other Rust compiler engineers in [#rustc], language
designers in [#rust-lang], and library designers in [#rust-libs].

<!--
TODO: guide to compile-time benchmarking
TODO: using the triage bot?
TODO: some of this RFC description could probably go in the RFC readme
-->

[#rust-internals]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-internals
[#rust-lang]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-lang
[#rust-libs]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rust-libs
[#rustc]: https://client00.chat.mibbit.com/?server=irc.mozilla.org&channel=%23rustc
[A-codegen]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-codegen
[A-debuginfo]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-debuginfo
[A-diagnostics]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-diagnostics
[A-libs]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-libs
[A-macros]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-macros
[A-optimization]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-optimization
[A-syntaxext]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-syntaxext
[A-typesystem]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AA-typesystem
[I-ICE]: https://github.com/rust-lang/rust/labels/I-ICE
[I-compiletime]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AI-compiletime
[I-slow]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AI-slow
[Rust DXR]: https://dxr.mozilla.org/rust/source/src
[ice]: https://users.rust-lang.org/t/glacier-a-big-ol-pile-of-ice/3380
[internals-docs]: https://manishearth.github.io/rust-internals-docs
[internals.rust-lang.org]: https://internals.rust-lang.org/
[issue-fcp]: https://github.com/rust-lang/rust/issues?q=is%3Aopen+is%3Aissue+label%3AB-unstable+label%3Afinal-comment-period
[mir]: https://github.com/rust-lang/rust/issues/27840
[rfc-fcp]: https://github.com/rust-lang/rfcs/pulls?q=is%3Aopen+is%3Apr+label%3Afinal-comment-period
[rfc-issues]: https://github.com/rust-lang/rfcs/issues
[rfc]: https://github.com/rust-lang/rfcs#table-of-contents
[rustc-guide]: https://github.com/rust-lang/rust/blob/master/src/librustc/README.md
[rustc-perf]: http://ncameron.org/perf-rustc/
[testsuite]: https://github.com/rust-lang/rust-wiki-backup/blob/master/Note-testsuite.md
[tips]: https://github.com/rust-lang/rust/blob/3d1f3c9d389d46607ae28c51cc94c1f43d65f3f9/Makefile.in#L48


text:
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using RMV.Awesome.UWP;
using RMV.Awesome.UWP.Models;

namespace RMV.Awesome.UWP
{
    public static partial class BranchExtensions
    {
        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        public static IList<RMVBranch> GetBranchList(this IBranch operations)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IBranch)s).GetBranchListAsync();
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public static async Task<IList<RMVBranch>> GetBranchListAsync(this IBranch operations, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<RMV.Awesome.UWP.Models.RMVBranch>> result = await operations.GetBranchListWithOperationResponseAsync(cancellationToken).ConfigureAwait(false);
            return result.Body;
        }

        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        /// <param name='lat'>
        /// Required.
        /// </param>
        /// <param name='lng'>
        /// Required.
        /// </param>
        public static IList<RMVBranch> GetBranchListDistance(this IBranch operations, double lat, double lng)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IBranch)s).GetBranchListDistanceAsync(lat, lng);
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        /// <param name='lat'>
        /// Required.
        /// </param>
        /// <param name='lng'>
        /// Required.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public static async Task<IList<RMVBranch>> GetBranchListDistanceAsync(this IBranch operations, double lat, double lng, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<RMV.Awesome.UWP.Models.RMVBranch>> result = await operations.GetBranchListDistanceWithOperationResponseAsync(lat, lng, cancellationToken).ConfigureAwait(false);
            return result.Body;
        }

        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        public static bool GetRefreshTimes(this IBranch operations)
        {
            return Task.Factory.StartNew((object s) =>
            {
                return ((IBranch)s).GetRefreshTimesAsync();
            }
            , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
        }

        /// <param name='operations'>
        /// Reference to the RMV.Awesome.UWP.IBranch.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        public static async Task<bool> GetRefreshTimesAsync(this IBranch operations, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
        {
            Microsoft.Rest.HttpOperationResponse<bool> result = await operations.GetRefreshTimesWithOperationResponseAsync(cancellationToken).ConfigureAwait(false);
            return result.Body;
        }
    }
}


text:
namespace blink {

// Implementation of cc::RenderFrameMetadataObserver which exists in the
// renderer and observers frame submission. It then notifies the
// cc::mojom::RenderFrameMetadataObserverClient, which is expected to be in the
// browser process, of the metadata associated with the frame.
//
// BindToCurrentThread should be called from the Compositor thread so that the
// Mojo pipe is properly bound.
//
// Subsequent usage should only be from the Compositor thread.
class PLATFORM_EXPORT RenderFrameMetadataObserverImpl
    : public cc::RenderFrameMetadataObserver,
      public cc::mojom::blink::RenderFrameMetadataObserver {
 public:
  RenderFrameMetadataObserverImpl(
      mojo::PendingReceiver<cc::mojom::blink::RenderFrameMetadataObserver>
          receiver,
      mojo::PendingRemote<cc::mojom::blink::RenderFrameMetadataObserverClient>
          client_remote);
  ~RenderFrameMetadataObserverImpl() override;

  // cc::RenderFrameMetadataObserver:
  void BindToCurrentThread() override;
  void OnRenderFrameSubmission(
      const cc::RenderFrameMetadata& render_frame_metadata,
      viz::CompositorFrameMetadata* compositor_frame_metadata,
      bool force_send) override;

  // mojom::RenderFrameMetadataObserver:
#if BUILDFLAG(IS_ANDROID)
  void ReportAllRootScrolls(bool enabled) override;
#endif
  void ReportAllFrameSubmissionsForTesting(bool enabled) override;

 private:
  friend class RenderFrameMetadataObserverImplTest;

  // Certain fields should always have their changes reported. This will return
  // true when there is a difference between |rfm1| and |rfm2| for those fields.
  // These fields have a low frequency rate of change.
  // |needs_activation_notification| indicates whether the browser process
  // expects notification of activation of the assoicated CompositorFrame from
  // Viz.
  bool ShouldSendRenderFrameMetadata(const cc::RenderFrameMetadata& rfm1,
                                     const cc::RenderFrameMetadata& rfm2,
                                     bool* needs_activation_notification) const;

  void SendLastRenderFrameMetadata();

#if BUILDFLAG(IS_ANDROID)
  // When true this will notify |render_frame_metadata_observer_client_| of all
  // frame submissions that involve a root scroll offset change.
  bool report_all_root_scrolls_enabled_ = false;
#endif

  // When true this will notify |render_frame_metadata_observer_client_| of all
  // frame submissions.
  bool report_all_frame_submissions_for_testing_enabled_ = false;

  uint32_t last_frame_token_ = 0;
  absl::optional<cc::RenderFrameMetadata> last_render_frame_metadata_;

  // These are destroyed when BindToCurrentThread() is called.
  mojo::PendingReceiver<cc::mojom::blink::RenderFrameMetadataObserver>
      receiver_;
  mojo::PendingRemote<cc::mojom::blink::RenderFrameMetadataObserverClient>
      client_remote_;

  mojo::Receiver<cc::mojom::blink::RenderFrameMetadataObserver>
      render_frame_metadata_observer_receiver_{this};
  mojo::Remote<cc::mojom::blink::RenderFrameMetadataObserverClient>
      render_frame_metadata_observer_client_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_COMPOSITING_RENDER_FRAME_METADATA_OBSERVER_IMPL_H_


text:
var shell = require('shelljs');

shell.exec('npm install -g grunt-cli', function(code, output) {
	shell.echo('\n npm install -g grunt-cli \n');
	shell.echo(output);
});

shell.exec('npm install -g grunt-init', function(code, output) {
	shell.echo('\n npm install -g grunt-init \n');
	shell.echo(output);
});

shell.exec('npm install', function(code, output) {
	shell.echo('\n npm install \n');
	shell.echo(output);

	shell.echo("replace path.resolve('node_modules') to path.resolve('..', 'node_modules')");

	shell.sed('-i', "path.resolve('node_modules')", "path.resolve('..', 'node_modules')", "node_modules/grunt/lib/grunt/task.js");
});


text:
description("Test to make sure queryCommandState returns correct values.")

var testContainer = document.createElement("div");
testContainer.contentEditable = true;
document.body.appendChild(testContainer);

function testQueryCommandState(command, contents, selector, expectedState)
{
    testContainer.innerHTML = contents;
    var selected = selector(testContainer);
    var actualState = document.queryCommandState(command);
    var actualValue = document.queryCommandValue(command);
    var action = 'queryCommandState("' + command + '") returns ' + actualState + ' when selecting ' + selected + ' of "' + contents + '"';
    if (actualState != expectedState)
        testFailed(action + ', expected ' + expectedState + '');
    else if (actualValue != actualState.toString())
        testFailed(action + ' but queryCommandValue returned ' + actualValue);
    else
        testPassed(action);
}

function selectAll(container) {
    window.getSelection().selectAllChildren(container);
    return 'all';
}

function selectSecondWord(container) {
    window.getSelection().setPosition(container, 0);
    window.getSelection().modify('move', 'forward', 'word');
    window.getSelection().modify('move', 'forward', 'word');
    window.getSelection().modify('move', 'backward', 'word');
    window.getSelection().modify('extend', 'forward', 'word');
    return 'second word';
}

function selectFirstTwoWords(container) {
    window.getSelection().setPosition(container, 0);
    window.getSelection().modify('move', 'forward', 'word');
    window.getSelection().modify('extend', 'forward', 'word');
    window.getSelection().modify('extend', 'forward', 'word');
    return 'first two words';
}

function runTests(editingBehavior) {
    if (window.internals)
        internals.settings.setEditingBehavior(editingBehavior);
    debug('Tests for ' + editingBehavior)

    testQueryCommandState("bold", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("bold", 'hello world', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello world WebKit', selectSecondWord, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello world WebKit', selectSecondWord, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello hello WebKit', selectSecondWord, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello hello WebKit', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("bold", '
hello hello WebKit
', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("bold", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("bold", 'hello world WebKit', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("bold", 'hello world', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("bold", '
hello

 WebKit
', selectAll, {'mac': true, 'win': true}[editingBehavior]);

    testQueryCommandState("italic", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("italic", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("italic", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("italic", 'hello world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("italic", 'hello world', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("italic", '
hello world
', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("italic", '
hello hello
', selectAll, {'mac': true, 'win': false}[editingBehavior]);

    testQueryCommandState("subscript", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("subscript", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("subscript", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("subscript", 'hello world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("subscript", 'hello world', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("subscript", '
hello world
', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("subscript", 'hello world WebKit', selectSecondWord, {'mac': true, 'win': false}[editingBehavior]);

    testQueryCommandState("superscript", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("superscript", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("superscript", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("superscript", 'hello world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("superscript", 'hello world', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("superscript", 'helloworld', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("superscript", 'helloworld', selectAll, {'mac': false, 'win': false}[editingBehavior]);

    testQueryCommandState("underline", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", '<s>hello</s>', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", 'hello', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("underline", 'hello world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", 'hello world', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", '
hello world
', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("underline", '<s>
hello world WebKit
</s>', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("underline", '<s>hello world</s> WebKit', selectSecondWord, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", '<s>hello</s> world WebKit', selectSecondWord, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("underline", '<s>hello world</s> WebKit', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);

    testQueryCommandState("strikeThrough", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("strikeThrough", 'hello', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("strikeThrough", '<s>hello</s>', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("strikeThrough", '<s>hello</s> world', selectAll, {'mac': true, 'win': false}[editingBehavior]);
    testQueryCommandState("strikeThrough", 'hello <s>world</s>', selectAll, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("strikeThrough", '<s>
hello world
</s>', selectAll, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("strikeThrough", '<s>
hello world WebKit
</s>', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("strikeThrough", '<s>hello</s> world WebKit', selectSecondWord, {'mac': false, 'win': false}[editingBehavior]);
    testQueryCommandState("strikeThrough", 'hello <s>world WebKit</s>', selectSecondWord, {'mac': true, 'win': true}[editingBehavior]);
    testQueryCommandState("strikeThrough", 'hello <s>world WebKit</s>', selectFirstTwoWords, {'mac': false, 'win': true}[editingBehavior]);
}

runTests('win');
debug('')
runTests('mac');

//document.body.removeChild(testContainer);
var successfullyParsed = true;


text:
<?php namespace Models;
  class Noticias{

    private $id;
    private $titulo;
    private $contenido;
    private $con;

    //metodos

    public function __construct()
    {
      $this->con = new Conexion();
    }
    public function set($atributo, $contenido)
    {
      $this->$atributo = $contenido;
    }
    public function get($atributo){
      return $this->$atributo;
    }

    public function listar()
    {
      $sql = "select * from noticias";
      $datos = $this->con->consultaRetorno($sql);
      return $datos;
    }

    public function add(){
      $sql = "insert into noticias(titulo, contenido) VALUES('{$this->titulo}','{$this->contenido}')";
      //echo $sql;
      $this->con->consultaSimple($sql);
    }
    public function edit(){
      $sql = "updte noticias SET titulo = '{$this->titulo}', contenido = {$this->conenido} where id_noticia= {$this->id_noticia}";
      $this->con->consultaSimple($sql);
    }
    public function delete(){
      $sql = "delete from noticias where id_noticia = {$this->id_noticia}";
      $this->con->consultaSimple($sql);
    }
    public function view()
    {
      $sql = "select * from noticias WHERE id_noticia = '{$this->id_noticia}'";
      $datos = $this->con->consultaRetorno($sql);
      $row = $datos->fetch(\PDO::FETCH_ASSOC);
      return $row;
      }
    }
?>


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
<meta charset="utf-8">
<title>phpDocumentor » \Xazure\Css\Plugin\Callback\Callback</title>
<meta name="author" content="Mike van Riel">
<meta name="description" content="">
<link href="../css/template.css" rel="stylesheet" media="all">
<link rel="shortcut icon" href="../img/favicon.ico">
<link rel="apple-touch-icon" href="../img/apple-touch-icon.png">
<link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png">

phpDocumentor

                                    API Documentation

Namespaces

 Xazure

                                    Charts

 Class hierarchy diagram

                                    Reports

 Errors
                0

 Markers

todo
                2

 Deprecated elements
                0

Back to top

                            Javascript is disabled; several features are only available
                            if Javascript is enabled.

<button class="btn public active" title="Show public elements">Public</button><button class="btn protected" title="Show protected elements">Protected</button><button class="btn private" title="Show private elements">Private</button><button class="btn inherited active" title="Show inherited elements">Inherited</button>

<button class="btn details" title="Show descriptions and method names"></button><button class="btn simple" title="Show only method names"></button>

 Methods

Constructor.
__construct()

Gives the callback as a string for easy printing.
__toString()

Get the callback.
getCallback()

Get the element class string.
getElementClass()

Given an Element, it should indicate if this matches the callback.
isMatch()

Given an Element, it should run the callback against it and
return the results of the Callback.
run()

» Protected

Converts a callback to a string.
callbackToString()

 Properties

» Protected

$callback

$elementClass

\

Xazure

\Css

\Plugin

\Callback

\Callback

The base Callback which all other plugin callbacks should extends.

This is an abstract class and cannot be used directly.

 Methods

Constructor.

__construct(string $elementClass, callable $callback)

Parameters

$elementClass

string
The full class the tested elements must be an instance of.

$callback

callable
The callback to call when this callback is run.

Gives the callback as a string for easy printing.

__toString() : string

Returns

string

Get the callback.

getCallback() : callable

Returns

callable

Get the element class string.

getElementClass() : string

Returns

string

Given an Element, it should indicate if this matches the callback.

isMatch(\Xazure\Css\Element\ElementInterface $element) : Boolean

Parameters

$element

\Xazure\Css\Element\ElementInterface

Returns

Boolean

Given an Element, it should run the callback against it and
return the results of the Callback.

run(\Xazure\Css\Element\ElementInterface $element) : \Xazure\Css\Element\ElementInterface

The callback should return an ElementInterface.

If more than one Element needs to be returned, return them in an ElementGroup.

Parameters

$element

\Xazure\Css\Element\ElementInterface

Returns

\Xazure\Css\Element\ElementInterface

Converts a callback to a string.

callbackToString(callable $callback) : string

Parameters

$callback

callable

Returns

string

 Properties

$callback : callable

$elementClass : string

            Template is built using Twitter Bootstrap 2 and icons provided by Glyphicons.

            Documentation is powered by phpDocumentor 2.0.0a12 and

            generated on 2012-12-11T00:02:19-08:00.


text:
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved.
// Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using NBench.Metrics;
using NBench.Reporting;

namespace NBench.Sdk
{
    /// <summary>
    ///     Executor class for running a single <see cref="PerfBenchmarkAttribute" />
    ///     Exposes the <see cref="BenchmarkContext" />, which allows developers to register custom
    ///     metrics and counters for the use of their personal benchmarks.
    /// </summary>
    public class Benchmark
    {
        private readonly int _warmupCount;
        protected readonly BenchmarkBuilder Builder;

        /// <summary>
        ///     Stopwatch used by the <see cref="Benchmark" />. Exposed only for testing purposes.
        /// </summary>
        public readonly Stopwatch StopWatch = new Stopwatch();

        private BenchmarkRun _currentRun;

        /// <summary>
        ///     Indicates if we're in warm-up mode or not
        /// </summary>
        private bool _isWarmup = true;

        private int _pendingIterations;
        protected WarmupData WarmupData = WarmupData.PreWarmup;

        /// <summary>
        /// Backwards-compatible constructor for NBench 0.1.6 and earlier.
        /// </summary>
        /// <param name="settings">The settings for this benchmark.</param>
        /// <param name="invoker">The invoker used to execute benchmark and setup / cleanup methods.</param>
        /// <param name="writer">The output target this benchmark will write to.</param>
        /// <remarks>Uses the <see cref="DefaultBenchmarkAssertionRunner"/> to assert benchmark data.</remarks>
        public Benchmark(BenchmarkSettings settings, IBenchmarkInvoker invoker, IBenchmarkOutput writer)
            : this(settings, invoker, writer, DefaultBenchmarkAssertionRunner.Instance) { }

        /// <summary>
        /// Backwards-compatible constructor for NBench 0.1.6 and earlier.
        /// </summary>
        /// <param name="settings">The settings for this benchmark.</param>
        /// <param name="invoker">The invoker used to execute benchmark and setup / cleanup methods.</param>
        /// <param name="writer">The output target this benchmark will write to.</param>
        /// <param name="benchmarkAssertions">The assertion engine we'll use to perform BenchmarkAssertions against benchmarks.</param>
        public Benchmark(BenchmarkSettings settings, IBenchmarkInvoker invoker, IBenchmarkOutput writer, IBenchmarkAssertionRunner benchmarkAssertions)
        {
            Settings = settings;
            _warmupCount = _pendingIterations = Settings.NumberOfIterations;
            Invoker = invoker;
            Output = writer;
            CompletedRuns = new Queue<BenchmarkRunReport>(Settings.NumberOfIterations);
            Builder = new BenchmarkBuilder(Settings);
            BenchmarkAssertionRunner = benchmarkAssertions;
        }

        public RunMode RunMode => Settings.RunMode;
        public Queue<BenchmarkRunReport> CompletedRuns { get; }
        public BenchmarkSettings Settings { get; }
        public bool ShutdownCalled { get; private set; }
        protected IBenchmarkInvoker Invoker { get; }
        protected IBenchmarkOutput Output { get; }
        protected IBenchmarkTrace Trace => Settings.Trace;
        protected IBenchmarkAssertionRunner BenchmarkAssertionRunner { get; }

        /// <summary>
        /// Returns <c>true</c> if <see cref="Finish"/> was called and all BenchmarkAssertions passed,
        /// or if it was never called.
        /// </summary>
        public bool AllAssertsPassed { get; private set; }

        /// <summary>
        /// The name of this benchmark
        /// </summary>
        public string BenchmarkName => Invoker.BenchmarkName;

        /// <summary>
        ///     Warmup phase
        /// </summary>
        private void WarmUp()
        {
            Trace.Debug($"Beginning Warmups for {BenchmarkName}");
            var warmupStopWatch = new Stopwatch();
            var targetTime = Settings.RunTime;
            Contract.Assert(targetTime != TimeSpan.Zero);
            var runCount = 0L;
            var runTime = 0L;

            /* Pre-Warmup */

            Trace.Debug("----- BEGIN PRE-WARMUP -----");
            /* Estimate */
            Allocate(); // allocate all collectors needed
            PreRun();

            try
            {
                if (Settings.RunMode == RunMode.Throughput)
                {
                    Trace.Debug(
                        $"Throughput mode: estimating how many invocations of {BenchmarkName} will take {targetTime.TotalSeconds}s");

                    var estimateCount = 3;
                    var runEstimates = new long[estimateCount];
                    var timeEstimates = new long[estimateCount];
                    for (var i = 0; i <= estimateCount; i++)
                    {
                        warmupStopWatch.Start();
                        while (warmupStopWatch.ElapsedTicks < targetTime.Ticks)
                        {
                            Invoker.InvokeRun(_currentRun.Context);
                            runCount++;
                        }
                        warmupStopWatch.Stop();

                        if (i > 0)
                        {
                            runEstimates[i - 1] = runCount;
                            timeEstimates[i - 1] = warmupStopWatch.ElapsedTicks;

                        }

                        runCount = 0;
                        warmupStopWatch.Reset();
                    }

                    runCount = (long)Math.Ceiling(runEstimates.Average());
                    runTime = (long) Math.Ceiling(timeEstimates.Average());

                    Trace.Debug(
                        $"Throughput mode: executed {runCount} instances of {BenchmarkName} in roughly {targetTime.TotalSeconds}s. Using that figure for benchmark.");
                }
                else
                {
                    warmupStopWatch.Start();
                    Invoker.InvokeRun(_currentRun.Context);
                    runCount++;
                    warmupStopWatch.Stop();

                    // elapsed time
                    runTime = warmupStopWatch.ElapsedTicks;
                }
            }
            catch (Exception ex)
            {
                HandleBenchmarkRunException(ex, $"Error occurred during ${BenchmarkName} RUN.");
            }

            PostRun();
            Complete(true);

            // check to see if pre-warmup threw an exception
            var faulted = _currentRun.IsFaulted;

            if (faulted)
            {
                Trace.Error($"Error occurred during pre-warmup. Exiting and producing dump...");
                /*
                 * Normally we don't ever queue up the warmup into the final stats, but we do it
                 * in failure cases so we can capture the exception thrown during warmup into
                 * the final report we're going to deliver to the end-user.
                 */
                CompletedRuns.Enqueue(_currentRun.ToReport(TimeSpan.Zero));

                return;
            }

            Trace.Debug("----- END PRE-WARMUP -----");

            WarmupData = new WarmupData(runTime, runCount);

            if (!Settings.SkipWarmups)
            {
                Trace.Debug("----- BEGIN WARMUPS -----");
                var i = _warmupCount;

                /* Warmup to force CPU caching */
                while (i > 0 && !_currentRun.IsFaulted)
                {
                    RunSingleBenchmark();
                    i--;
                }

                Trace.Debug("----- END WARMUPS -----");
            }
            else
            {
                Trace.Debug("----- SKIPPING WARMUPS -----");
            }
        }

        /// <summary>
        ///     Pre-allocate all of the objects we're going to need for this benchmark
        /// </summary>
        private void Allocate()
        {
            _currentRun = Builder.NewRun(WarmupData);
        }

        public void Run()
        {
            WarmUp();
            // disable further warmups
            _isWarmup = false;

            while (_pendingIterations > 0 && !_currentRun.IsFaulted)
            {
                RunSingleBenchmark();
            }

            // Bailing out if the benchmark was faulted
            if (_currentRun.IsFaulted)
            {
                Output.Warning($"Error during previous run of {BenchmarkName}. Aborting run...");
            }

        }

        public void Shutdown()
        {
            ShutdownCalled = true;
        }

        private void RunSingleBenchmark()
        {
            Allocate(); // allocate all collectors needed
            // reset the stopwatch before each run
            StopWatch.Reset();
            PreRun();
            try
            {
                RunBenchmark();
            }
            catch (Exception ex)
            {
                HandleBenchmarkRunException(ex, $"Error occurred during ${BenchmarkName} RUN.");
            }
            PostRun();
            Complete(); // release previous collectors
        }

        protected void PreRun()
        {
            Trace.Info($"Invoking setup for {BenchmarkName}");
            try
            {
                if (RunMode == RunMode.Throughput)
                {
                    // Need to pass in the # of estimated runs per second in order to compile
                    // the invoker with an inlined loop
                    Invoker.InvokePerfSetup(WarmupData.EstimatedRunsPerSecond, _currentRun.Context);
                }
                    else
                {
                    // Invoke user-defined setup method, if any
                    Invoker.InvokePerfSetup(_currentRun.Context);
                }

                PrepareForRun();
            }
            catch (Exception ex)
            {
                HandleBenchmarkRunException(ex, $"Error occurred during ${BenchmarkName} SETUP.");
            }
        }

        private void HandleBenchmarkRunException(Exception ex, string formatMsg)
        {
            var nbe = new NBenchException(formatMsg, ex);
            _currentRun.WithException(nbe);
            Output.Error(ex, nbe.Message);
        }

        /// <summary>
        /// Performs any final GC needed before we start a test run
        /// </summary>
        public static void PrepareForRun()
        {
            // Force a full garbage collection
            GC.Collect();

            // Wait for pending finalizers
            GC.WaitForPendingFinalizers();

            // One more time for good measure
            GC.Collect();
        }

        protected void RunBenchmark()
        {
            Trace.Info($"Invoking {BenchmarkName}");
            _currentRun.Sample(StopWatch.ElapsedTicks);
            StopWatch.Start();
            Invoker.InvokeRun(_currentRun.Context);
            StopWatch.Stop();
            _currentRun.Sample(StopWatch.ElapsedTicks); //add a tick just to ensure no collision
        }

        /// <summary>
        ///     NOTE: We don't reset the <see cref="Stopwatch" /> on purpose here, so we can
        ///     collect the value of it and use it for auto-tuning and reporting.
        ///     It'll be started at the beginning of the next run.
        /// </summary>
        protected void PostRun()
        {
            Trace.Info($"Invoking cleanup for {BenchmarkName}");
            try
            {
                // Invoke user-defined cleanup method, if any
                Invoker.InvokePerfCleanup(_currentRun.Context);
            }
            catch (Exception ex)
            {
                HandleBenchmarkRunException(ex, $"Error occurred during ${BenchmarkName} CLEANUP.");
            }
        }

        /// <summary>
        /// Helper method for printing out the correct label to trace
        /// </summary>
        private static string PrintWarmupOrRun(bool isWarmup)
        {
            return isWarmup ? "warmup" : "run";
        }

        /// <summary>
        /// Complete the current run
        /// </summary>
        private void Complete(bool isEstimate = false)
        {
            _currentRun.Dispose();
            Trace.Info($"Generating report for {PrintWarmupOrRun(_isWarmup)} {1 + Settings.NumberOfIterations - _pendingIterations} of {BenchmarkName}");
            var report = _currentRun.ToReport(StopWatch.Elapsed);
            if(!isEstimate)
                Output.WriteRun(report, _isWarmup);

            // Change runs, but not on warmup
            if (!_isWarmup)
            {
                // Decrease the number of pending iterations
                _pendingIterations--;

                CompletedRuns.Enqueue(report);
            }
        }

        /// <summary>
        /// Compiles all of the completed <see cref="BenchmarkRun"/>s into reports
        /// </summary>
        /// <returns>The full set of aggregate results</returns>
        public BenchmarkResults CompileResults()
        {
            return new BenchmarkResults(Invoker.BenchmarkName, Settings, CompletedRuns.ToList());
        }

        public BenchmarkFinalResults AssertResults(BenchmarkResults result)
        {
            var assertionResults = BenchmarkAssertionRunner.RunAssertions(Settings, result);
            return new BenchmarkFinalResults(result, assertionResults);
        }

        /// <summary>
        /// Complete the benchmark
        /// </summary>
        public void Finish()
        {
            var results = CompileResults();

            var finalResults = AssertResults(results);
            AllAssertsPassed = finalResults.AssertionResults.All(x => x.Passed) && !finalResults.Data.IsFaulted;
            Output.WriteBenchmark(finalResults);
        }
    }
}


text:
set -ex

# Parse command line arguments.
prompt_notice=true
if [[ "$1" == "--prompt"* ]]; then
  if [[ "$1" == "--prompt=false" ]]; then
    prompt_notice=false
  fi
  shift
fi

flavor=$1

base_image=vitess/base
make_target=docker_base
lite_image=vitess/lite
dockerfile=Dockerfile
tag=latest
if [[ -n "$flavor" ]]; then
  base_image=vitess/base:$flavor
  make_target=docker_base_$flavor
  lite_image=vitess/lite:$flavor
  dockerfile=Dockerfile.$flavor
  tag=$flavor
else
  echo "Flavor not specified as first argument. Building default image."
fi

# Abort if base image does not exist.
if ! docker inspect $base_image &>/dev/null; then
  echo "ERROR: Dependent image $base_image does not exist. Run 'make $make_target' to build it locally or 'docker pull $base_image' to fetch it from Docker Hub (if it is published)."
  exit 1
fi

# Educate the user that they have to build or pull vitess/base themselves.
if [[ "$prompt_notice" = true ]]; then
  cat <<END

This script is going to repack and copy the existing *local* base image '$base_image' into a smaller image '$lite_image'.

It does NOT recompile the Vitess binaries. For that you will have to rebuild or pull the base image.

The 'docker images' output below shows you how old your local base image is:

$(docker images vitess/base | grep -E "(CREATED|$tag)")

If you need a newer base image, you will have to manually run 'make $make_target' to build it locally
or 'docker pull $base_image' to fetch it from Docker Hub.

Press ENTER to continue building '$lite_image' or Ctrl-C to cancel.
END
  read
fi

# cleanup both temporary folders when exiting, even in case of errors
function cleanup {
  rm -rf $PWD/base $PWD/lite
}
trap cleanup EXIT

# Extract files from vitess/base image
mkdir base
# Ignore permission errors. They occur for directories we do not care e.g. ".git".
# (Copying them fails because they are owned by root and not $UID and have stricter permissions.)
docker run --rm -v $PWD/base:/base -u $UID $base_image bash -c 'cp -R /vt /base/ 2>&1 | grep -v "Permission denied"' || true

# Grab only what we need
lite=$PWD/lite
vttop=vt/src/vitess.io/vitess
mkdir -p $lite/vt/vtdataroot

mkdir -p $lite/vt/bin
(cd base/vt/bin; cp mysqlctld vtctld vtctlclient vtgate vttablet vtworker $lite/vt/bin/)

mkdir -p $lite/$vttop/web
cp -R base/$vttop/web/vtctld $lite/$vttop/web/
mkdir $lite/$vttop/web/vtctld2
cp -R base/$vttop/web/vtctld2/app $lite/$vttop/web/vtctld2/

mkdir -p $lite/$vttop/config
cp -R base/$vttop/config/* $lite/$vttop/config/
ln -s /$vttop/config $lite/vt/config

# remove the base folder now -- not needed for the final build
rm -rf $PWD/base

# Fix permissions for AUFS workaround
chmod -R o=g lite

# Build vitess/lite image
docker build --no-cache -f $dockerfile -t $lite_image .


text:
<?php
declare(strict_types=1);

namespace DelayedJobs\DelayedJob\Exception;

use Exception;

/**
 * Class JobDataException
 */

class JobDataException extends Exception
{
}


text:
NEW_TEAM_MODAL = {
    title : 'Create New Team',
    template : Template._meteor_os_settings_team_management_new_team,
    removeOnHide: true,
    buttons: {
        create : {
            label : 'Create',
            class : 'btn-success',
        },
        cancel : {
            label : 'Cancel',
            class : 'btn-default'
        }
    }
};


text:
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Owin;
using DNS.Task.Core.Models;
using DNS.Task.Core.Store;

namespace DNS.Task.Web.Controllers
{
    public class TreeController : Controller
    {
	    public ICrudStore<Node> Store
	    {
		    get { return Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<ICrudStore<Node>>(); }
	    }

	    // GET: Tree
        public ActionResult Index()
        {
            return View();
        }

        // GET: Tree/Details/5
        public async Task<JsonResult> Details(int id)
        {
            return Json(await Store.GetAsync(id, CancellationToken.None), JsonRequestBehavior.AllowGet);
        }

        // POST: Tree/Create
        [HttpPost]
        public async Task<JsonResult> Create(Node node)
        {
	        try
	        {
		        if (ModelState.IsValid)
		        {
			        node.Id = await Store.AddAsync(node, CancellationToken.None);
			        return Json(new {success = true, result = node});
		        }
		        return Json(new {success = false, reslt = "Invalid object!"}, JsonRequestBehavior.AllowGet);
	        }
	        catch (Exception)
	        {
				Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IUnitOfWork>().Rollback();
		        return Json(new {success = false});
	        }
        }

        // POST: Tree/Edit/5
        [HttpPost]
        public async Task<JsonResult> Edit(int id, Node node)
        {
	        try
	        {
		        if (ModelState.IsValid)
		        {
			        node.Id = id;
			        await Store.UpdateAsync(node, CancellationToken.None)
				        .ConfigureAwait(true);
			        return Json(new {success = true, result = node}, JsonRequestBehavior.AllowGet);
		        }
		        return Json(new
		        {
			        success = false,
			        result = "Invalid object!"
		        }, JsonRequestBehavior.AllowGet);
	        }
	        catch (Exception)
	        {
				Request.GetOwinContext().GetAutofacLifetimeScope().Resolve<IUnitOfWork>().Rollback();
		        return Json(new {success = false});
	        }
        }

        // GET: Tree/Delete/5
        public async Task<JsonResult> Delete(int id)
        {
	        return Json(new {success = await Store.ForceDeleteAsync(id, CancellationToken.None)}, JsonRequestBehavior.AllowGet);
        }

	    public async Task<JsonResult> GetList(int? parentId)
	    {
		    var result = await Store.GetListAsync(new GetNodesRequest(parentId), CancellationToken.None);
			return Json(result.Select(i => new
			{
				key = i.Id,
				title = i.Title,
				isFolder = i.NodeType == NodeType.Folder,
				hasChildren = i.NodeType == NodeType.Folder,
				isLazy = i.NodeType == NodeType.Folder,
				data = i
			}), JsonRequestBehavior.AllowGet);
	    }
    }
}


text:
package main;

import main.model.Model;
import main.presenter.DrawablesRegister;
import main.presenter.MenuBarController;
import main.view.View;

public class RunThis {

	public static void main (String[] args) {

		Model m = new Model();
		DrawablesRegister drawables = new DrawablesRegister(m.hexes(), m.presenter());
		MenuBarController mbc = new MenuBarController(m);

        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                @SuppressWarnings("unused")
				View v = new View(drawables, mbc);
            }
        });

	}
}


text:
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2014
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion

using System.Web.UI;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Tokens;

namespace DotNetNuke.UI.Modules.Html5
{
    public class Html5ModuleTokenReplace : HtmlTokenReplace
    {
        public Html5ModuleTokenReplace(Page page, string html5File, ModuleInstanceContext moduleContext, ModuleActionCollection moduleActions)
            : base(page)
        {
            AccessingUser = moduleContext.PortalSettings.UserInfo;
            DebugMessages = moduleContext.PortalSettings.UserMode != Entities.Portals.PortalSettings.Mode.View;
            ModuleId = moduleContext.ModuleId;
            PortalSettings = moduleContext.PortalSettings;

            PropertySource["moduleaction"] = new ModuleActionsPropertyAccess(moduleContext, moduleActions);
            PropertySource["resx"] = new ModuleLocalizationPropertyAccess(moduleContext, html5File);
            PropertySource["modulecontext"] = new ModuleContextPropertyAccess(moduleContext);
        }
    }
}


text:
<?php

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) exit;

class Revisr_DB {

	/**
	 * The backup directory.
	 * @var string
	 */
	protected $backup_dir;

	/**
	 * The WordPress database class.
	 * @var WPDB
	 */
	protected $wpdb;

	/**
	 * Constructs the class.
	 * @access public
	 */
	public function __construct() {

		// Make WPDB available to the class.
		global $wpdb;
		$this->wpdb = $wpdb;

		$upload_dir = wp_upload_dir();

		$this->backup_dir = $upload_dir['basedir'] . '/revisr-backups/';

		// Set up the "revisr_backups" directory if necessary.
		$this->setup_env();

	}

	/**
	 * Runs an action on all tracked database tables.
	 *
	 * @access private
	 * @param  string 			$action 	The action to perform.
	 * @param  array 			$tables 	The tables to run on (optional).
	 * @param  string|array 	$args 		Any arguements to pass through (optional).
	 * @return boolean
	 */
	private function run( $action, $tables = array(), $args = '' ) {

		// An empty status array to update later.
		$status 	= array();

		// Whether we're using MySQL, WPDB, or maybe even something else.
		$driver 	= $this->get_driver();

		// Builds the name of the class to construct.
		$class 		= 'Revisr_DB_' . $action;

		// Builds the name of the method to call.
		$method 	= $action . '_table_' . $driver;

		// The tables we want to run the action on.
		$tables 	= $tables ? $tables : $this->get_tracked_tables();

		if ( is_callable( array( $class, $method ) ) ) {

			// Construct the class.
			$class = new $class;

			/**
			 * Loop through the tracked tables,
			 * storing the results in the status array.
			 */
			foreach ( $tables as $table ) {
				$status[$table] = $class->$method( $table, $args );
			}

			// Fire off the callback.
			return $class->callback( $status );

		}

	}

	/**
	 * Returns the database method being used.
	 * @access private
	 * @return string
	 */
	private function get_driver() {
		return revisr()->git->get_config( 'revisr', 'db-driver' ) ? revisr()->git->get_config( 'revisr', 'db-driver' ) : 'mysql';
	}

	/**
	 * Returns the path to MySQL.
	 * @access protected
	 * @return string
	 */
	protected function get_path() {
		return revisr()->git->get_config( 'revisr', 'mysql-path' ) ? revisr()->git->get_config( 'revisr', 'mysql-path' ) : '';
	}

	/**
	 * Returns an array of tables in the database.
	 * @access public
	 * @return array
	 */
	public function get_tables() {
		$tables = $this->wpdb->get_col( 'SHOW TABLES' );
		return $tables;
	}

	/**
	 * Returns an array containing the size of each database table.
	 * @access public
	 * @return array
	 */
	public function get_sizes() {
		$sizes 	= array();
		$tables = $this->wpdb->get_results( 'SHOW TABLE STATUS', ARRAY_A );

		if ( is_array( $tables ) ) {

			foreach ( $tables as $table ) {
				$size = round( $table['Data_length'] / 1024 / 1024, 2 );
				$sizes[$table['Name']] = sprintf( __( '(%s MB)', 'revisr' ), $size );
			}

		}

		return $sizes;
	}

	/**
	 * Returns a list of tables that are in the "revisr-backups" directory,
	 * but not in the database. Necessary for importing tables that could
	 * not be added to the tracked tables due to them not existing.
	 * @access public
	 * @return array
	 */
	public function get_tables_not_in_db() {
		$backup_tables	= array();
		$db_tables 		= $this->get_tables();

		foreach ( scandir( $this->backup_dir ) as $file ) {

			if ( 'revisr_' !== substr( $file, 0, 7 ) ) {
				continue;
			}

			// Remove the prefix and extension.
	        $backup_tables[] 	= substr( substr( $file, 7 ), 0, -4 );
    	}

    	$new_tables = array_diff( $backup_tables, $db_tables );
    	return $new_tables;
	}

	/**
	 * Returns the array of tables that are to be tracked.
	 * @access public
	 * @return array
	 */
	public function get_tracked_tables() {

		// Get our saved tracking preferences from the .git/config.
		$db_tracking 	= revisr()->git->get_config( 'revisr', 'db-tracking' );
		$stored_tables 	= revisr()->git->run( 'config', array( '--get-all', 'revisr.tracked-tables' ) );

		// Determine which tables we want to track.
		if ( 'all_tables' == $db_tracking ) {
			$tracked_tables = $this->get_tables();
		} elseif ( 'custom' == $db_tracking && is_array( $stored_tables ) ) {
			$tracked_tables = array_intersect( $stored_tables, $this->get_tables() );
		} elseif ( 'none' == $db_tracking) {
			$tracked_tables = array();
		} else {
			$tracked_tables = $this->get_tables();
		}

		// Return an array of tables we should track.
		return $tracked_tables;
	}

	/**
	 * Adds a table to version control.
	 * @access private
	 * @param  string $table The table to add.
	 */
	protected function add_table( $table ) {
		revisr()->git->run( 'add', array( $this->backup_dir . 'revisr_' . $table. '.sql' ) );
	}

	/**
	 * Builds the connection string to use with MySQL.
	 * @access protected
	 * @param  string $table Optionally pass the table to use.
	 * @return string
	 */
	protected function build_conn( $table = '' ) {

		// Allow using the port or socket from the DB_HOST constant.
		$port_or_socket = $this->check_port_or_socket( DB_HOST );
		$add_port 		= '';
		$add_socket 	= '';
		$db_host 		= DB_HOST;

		if ( false !== $port_or_socket ) {

			if ( null !== $port_or_socket['socket'] ) {
				$socket 	= $port_or_socket['socket'];
				$add_socket = " --socket=$socket";
				$temp 		= strlen( $socket ) * -1 - 1;
			} else {
				$port 		= $port_or_socket['port'];
				$add_port 	= " --port=$port";
				$temp 		= strlen( $port ) * -1 - 1;
			}

			$db_host = substr( DB_HOST, 0, $temp );

		}

		// Maybe connect to a specific table.
		if ( '' !== $table ) {
			$table = ' ' . Revisr_Admin::escapeshellarg( $table );
		}

		// Workaround for compatibility between UNIX and Windows.
		if ( '' !== DB_PASSWORD ) {
			$conn = "-u " . Revisr_Admin::escapeshellarg( DB_USER ) . " -p" . Revisr_Admin::escapeshellarg( DB_PASSWORD ) . " " . DB_NAME . $table . " --host " . $db_host . $add_port . $add_socket;
		} else {
			$conn = "-u " . Revisr_Admin::escapeshellarg( DB_USER ) . " " . DB_NAME . $table . " --host " . $db_host . $add_port . $add_socket;
		}

		// Return the connection string.
		return $conn;
	}

	/**
	 * Creates the backup folder and adds the .htaccess if necessary.
	 * @access private
	 */
	private function setup_env() {
		// Check if the backups directory has already been created.
		if ( is_dir( $this->backup_dir ) ) {
			return true;
		} else {
			// Make the backups directory.
			mkdir( $this->backup_dir );

			// Add .htaccess to prevent direct access.
			$htaccess_content = '<FilesMatch "\.sql">' .
			PHP_EOL . 'Order allow,deny' .
			PHP_EOL . 'Deny from all' .
			PHP_EOL . 'Satisfy All' .
			PHP_EOL . '</FilesMatch>';
			file_put_contents( $this->backup_dir . '/.htaccess', $htaccess_content );

			// Add index.php to prevent directory listing.
			$index_content = '<?php // Silence is golden' . PHP_EOL;
			file_put_contents( $this->backup_dir . '/index.php', $index_content );
		}
	}

	/**
	 * Checks if a given DB_HOST parameter is using a port or socket.
	 *
	 * Adapated from WordPress core.
	 *
	 * @access public
	 * @param  string $url The URL to check.
	 * @return array|boolean
	 */
	public function check_port_or_socket( $url ) {

		// Initialize the defaults.
		$port 			= null;
		$socket 		= null;
		$host 			= $url;
		$port_or_socket = strrchr( $host, ':' );

		if ( ! empty( $port_or_socket ) ) {

			$port_or_socket = substr( $port_or_socket, 1);

			if ( 0 !== strpos( $port_or_socket, '/' ) ) {

				$port 			= intval( $port_or_socket );
				$maybe_socket 	= strstr( $port_or_socket, ':' );

				if ( ! empty( $maybe_socket ) ) {
					$socket = substr( $maybe_socket, 1 );
				}
			} else {
				$socket = $port_or_socket;
			}
		}

		if ( null === $port && null === $socket ) {
			return false;
		}

		return array( 'port' => $port, 'socket' => $socket );
	}

	/**
	 * Mimics the mysql_real_escape_string function. Adapted from a post by 'feedr' on php.net.
	 * @link   http://php.net/manual/en/function.mysql-real-escape-string.php#101248
	 * @access public
	 * @param  string $input The string to escape.
	 */
	public function mysql_escape_mimic( $input ) {

	    if ( is_array( $input ) ) {
	        return array_map( __METHOD__, $input );
	    }

	    if( ! empty( $input ) && is_string( $input ) ) {
	        return str_replace( array( '\\', "\0", "\n", "\r", "'", '"', "\x1a" ), array( '\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z' ), $input );
	    }

	    return $input;
	}

	/**
	 * Callback for database backups (AJAX button and via New Commit)
	 * @access public
	 * @param  string  $commit_msg A commit message to pass to $this->commit_db() (optional)
	 * @param  boolean $commit_db  Whether or not to commit the DB immediately.
	 * @return boolean
	 */
	public function backup( $commit_msg = '', $commit_db = true ) {

		// Get the tables to backup.
		$tables = $this->get_tracked_tables();
		if ( empty( $tables ) ) {
			$tables = $this->get_tables();
		}

		// Run the backup.
		if ( $this->run( 'backup', $tables ) ) {

			// Commit the backed up database tables if necessary.
			if ( true === $commit_db ) {
				$this->commit_db( $commit_msg );
			}

			return true;
		}

		return false;
	}

	/**
	 * Reverts all tracked tables to an earlier commit.
	 * @access public
	 * @param  boolean $redirect Whether or not to redirect via PHP.
	 */
	public function restore( $redirect = true ) {

		// Make sure we really want to do this.
		if ( ! wp_verify_nonce( $_REQUEST['revisr_revert_nonce'], 'revisr_revert_nonce' ) ) {
			wp_die( __( 'Cheatin’ uh?', 'revisr' ) );
		}

		$commit = $_REQUEST['db_hash'];

		/**
		 * Backup the database and store the resulting commit hash
		 * in memory so we can use it to create the revert link later.
		 */
		$msg = sprintf( __( 'Database backup before revert to #%s.', 'revisr' ), $commit );
		$this->backup( $msg );
		$current_temp = revisr()->git->current_commit();

		if ( $current_temp ) {

			/**
			 * If the backup was successful and we have the resulting commit hash,
			 * run a revert on the sql files for the tracked tables and import them.
			 */
			$tables 	= $this->get_tracked_tables();
			$checkout 	= array();

			foreach ( $tables as $table ) {
				$checkout[$table] = revisr()->git->run( 'checkout', array( $commit, "{$this->backup_dir}revisr_$table.sql" ) );
			}

			if ( ! in_array( 1, $checkout ) ) {

				$import = $this->import();

				if ( $import ) {

					// Create a link to undo the revert if necessary.
					$undo_nonce = wp_nonce_url( admin_url( "admin-post.php?action=process_revert&revert_type=db&db_hash=" . $current_temp ), 'revisr_revert_nonce', 'revisr_revert_nonce' );
					$undo_msg 	= sprintf( __( 'Successfully reverted the database to a previous commit. Undo', 'revisr' ), $undo_nonce );

					// Store the undo link and alert the user.
					Revisr_Admin::log( $undo_msg, 'revert' );
					Revisr_Admin::alert( $undo_msg );

				}

			} else {

				// There was an error importing the database.
				$msg = __( 'Error reverting one or more database tables.', 'revisr' );
				Revisr_Admin::log( $msg, 'error' );
				Revisr_Admin::alert( $msg, true );

			}

			// Redirect if necessary.
			if ( $redirect !== false ) {
				wp_redirect( get_admin_url() . 'admin.php?page=revisr' );
				exit();
			}

		} else {
			wp_die( __( 'Something went wrong. Check your settings and try again.', 'revisr' ) );
		}

	}

	/**
	 * Runs an import of all tracked tables, importing any new tables
	 * if tracking all_tables, or providing a link to import new tables
	 * if necessary.
	 * @access public
	 * @param  array $tables The tables to import.
	 * @return boolean
	 */
	public function import( $tables = array() ) {
		// The tables currently being tracked.
		$tracked_tables = $this->get_tracked_tables();

		// Tables that have import files but aren't in the database.
		$new_tables 	= $this->get_tables_not_in_db();

		// All tables.
		$all_tables		= array_unique( array_merge( $new_tables, $tracked_tables ) );

		// The URL to replace during import.
		$replace_url 	= revisr()->git->get_config( 'revisr', 'dev-url' ) ? revisr()->git->get_config( 'revisr', 'dev-url' ) : '';

		if ( empty( $tables ) ) {

			if ( ! empty( $new_tables ) ) {
				// If there are new tables that were imported.
				if ( isset( revisr()->options['db_tracking'] ) && revisr()->options['db_tracking'] == 'all_tables' ) {
					// If the user is tracking all tables, import all tables.
					$import = $this->run( 'import', $all_tables, $replace_url );
				} else {
					// Import only tracked tables, but provide a warning and import link.
					$import = $this->run( 'import', $tracked_tables, $replace_url );
					$url = wp_nonce_url( get_admin_url() . 'admin-post.php?action=revisr_import_tables_form&TB_iframe=true&width=400&height=225', 'import_table_form', 'import_nonce' );
					$msg = sprintf( __( 'New database tables detected. Click here to view and import.', 'revisr' ), $url );
					Revisr_Admin::log( $msg, 'db' );
				}
			} else {
				// If there are no new tables, go ahead and import the tracked tables.
				$import = $this->run( 'import', $tracked_tables, $replace_url );
			}

		} else {
			// Import the provided tables.
			$import = $this->run( 'import', $tables, $replace_url );
		}

		return $import;
	}

	/**
	 * Commits the database to the repository and pushes if needed.
	 * @access public
	 * @param  string $commit_msg A custom commit message.
	 */
	public function commit_db( $commit_msg = '' ) {

		if ( '' === $commit_msg ) {
			$commit_msg  = __( 'Backed up the database with Revisr.', 'revisr' );
		}

		// Allow for overriding default commit message through the "New Commit" screen.
		if ( isset( $_REQUEST['post_title'] ) && $_REQUEST['post_title'] !== '' ) {
			$commit_msg = $_REQUEST['post_title'];
		}

		// Make the commit.
		revisr()->git->commit( $commit_msg );

		// Push changes if necessary.
		revisr()->git->auto_push();
	}

	/**
	 * Verifies a backup for a table.
	 * @access public
	 * @param  string $table The table to check.
	 * @return boolean
	 */
	public function verify_backup( $table ) {
		if ( ! file_exists( "{$this->backup_dir}revisr_$table.sql" ) || filesize( "{$this->backup_dir}revisr_$table.sql" ) < 100 ) {
			return false;
		}
		return true;
	}

}


text:
from flask import Flask, jsonify, render_template, request, redirect
from twilio import twiml
from twilio.rest import TwilioRestClient
import random
import os
import sendText
import re

url_params = {}
url_params['term'] = 'date'
url_params['limit'] = 10
url_params['sort'] = 0

app = Flask(__name__)
app.config.from_pyfile('local_settings.py')

@app.route("/respond", methods=['POST'])
def respond():
    """Respond to incoming requests."""
    resp = twiml.Response()
    body = request.form['Body']
    num = request.values.get('From', None)
    if "done" in body.lower():
        resp.sms("Hope you enjoyed your date! Thank you for using PlanDate!")
    else:
        resp.sms("Fill out the form at: http://plandate.herokuapp.com/")
    return str(resp)

@app.route('/_print_info')
def print_info():
    """returns the data"""
    phone = request.args.get('phone_id')
    add = request.args.get('address')
    radius = request.args.get('distance')
    activityLevel = request.args.get('activity')

    if activityLevel == 3:
        url_params['category_filter'] = 'active'
    elif activityLevel == 2:
        activities = ['bars','nightlife','arts','restaurants','fashion','artsandcrafts','zoos','skatingrinks','beaches']
        url_params['category_filter'] = activities[random.randint(0,len(activities)-1)]
    else:
        activities = ['arts','restaurants','artsandcrafts','fashion']
        url_params['category_filter'] = activities[random.randint(0,len(activities)-1)]

    url_params['location'] = add
    url_params['radius_filter'] = radius
    """sends the text given 'phone'"""
    response = sendText.requester('api.yelp.com', '/v2/search', url_params, '0px8qDLNaYLpwVHlGeyNzQ', 'VYdp1bHYoPayFF9Mp0Q4RP328n0','RoXmcii1RiXkAoFh1uwMZpC6_5k2iVyq', '0bbsAocDgcBsua5WvOzxU6NxGUY')
    venueName = ''
    venueLocation = []
    for key, value in response["businesses"][random.randint(0,4)].iteritems():
        if key == 'name':
            venueName = value
        if key == 'location':
            for i in range(0,len(value['display_address'])):
                venueLocation.append(value['display_address'][i])
    venue = ''
    account_sid = "ACfe656ed49f19a12b8440cb191158f0c9"
    auth_token = "8d29d5cc81e4062e1521237983c39b21"
    client = TwilioRestClient(account_sid, auth_token)
    message = client.messages.create(to=phone, from_="+15162724635",body="Welcome to PlanDate! You should go to:\n" + venueName +"\n"+ "\n".join(venueLocation) + "\n Reply 'next' for next plan, 'done' if finished.")
    return jsonify(result = phone)

@app.route("/")
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run()


text:
/**
 * Module dependencies
 */
var _ = require('underscore'),
	path = require('path'),
	rode = require('rode');

var rootPath = rode.getRootPath() || path.resolve(__dirname, '../') + '/';

var config = {
	baseUri: 'http://localhost',
	port: process.env.PORT || 3000,

	// Config your directories and views
	srcDir: 'src',
	statics: {
		dir: 'public',
		images: 'images',
		js: 'js',
		css: 'css'
	},
	views: {
		dir: 'views',
		engine: '{ViewsTemplate}'
	},

	css: '{css}',
	mongo: {
		uri: 'mongodb://localhost/app_name',
		options: {},
		autoconnect: true
	},
	db: process.env.MONGOHQ_URL,
	favicon: rode.express.favicon(),
	bodyParser: true,
	errorHandler: true
};

module.exports = function (env) {
	if (!env) {
		env = process.env.NODE_ENV || 'development';
	}
	_.extend(config, require(rootPath + 'config/' + env) || {});
	rode.env = env;

	return config;
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 334955 $ -->
<refentry xml:id="function.geoip-netspeedcell-by-name" xmlns="http://docbook.org/ns/docbook">
 <refnamediv>
  <refname>geoip_netspeedcell_by_name</refname>
  <refpurpose>Get the Internet connection speed</refpurpose>
 </refnamediv>
 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>string</type><methodname>geoip_netspeedcell_by_name</methodname>
   <methodparam><type>string</type><parameter>hostname</parameter></methodparam>
  </methodsynopsis>

  <para>
   The <function>geoip_netspeedcell_by_name</function> function will return the Internet
   connection type and speed corresponding to a hostname or an IP address.
  </para>
  <para>
   This function is only available if using GeoIP Library version 1.4.8 or newer.
  </para>
  <para>
   This function is currently only available to users who have bought a commercial
   GeoIP NetSpeedCell Edition. A warning will be issued if the proper database cannot be
   located.
  </para>
  <para>
   The return value is a string, common values are:
  </para>
  <para>
   <itemizedlist>
    <listitem>
     <simpara>
      Cable/DSL
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      Dialup
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      Cellular
     </simpara>
    </listitem>
    <listitem>
     <simpara>
      Corporate
     </simpara>
    </listitem>
   </itemizedlist>
  </para>

 </refsect1>
 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>hostname</parameter></term>
     <listitem>
      <para>
       The hostname or IP address.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>
 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns the connection speed on success, or &false; if the address
   cannot be found in the database.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title>A <function>geoip_netspeedcell_by_name</function> example</title>
    <para>
     This will output the connection speed of the host example.com.
    </para>
    <programlisting role="php">
<![CDATA[
<?php
$netspeed = geoip_netspeedcell_by_name('www.example.com');

if ($netspeed) {
    echo 'The connection type is: '. $netspeed;
}
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
The connection type is: Corporate
]]>
    </screen>
   </example>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unlink.common.HttpClient;

/**
 *
 * @author Unlink
 */
public class BasicNameValuePair {
    private final String aKey;
    private final String aValue;

    public BasicNameValuePair(String aKey, String aValue) {
        this.aKey = aKey;
        this.aValue = aValue;
    }

    /**
     * Vráti kľúč
     * @return
     */
    public String getKey() {
        return aKey;
    }

    /**
     * Vráti hodnotu
     * @return
     */
    public String getValue() {
        return aValue;
    }
}


text:
<?php
mysql_connect("localhost","laabus_varini","Mylife@GOD432") or die(mysql_error());
mysql_select_db("laabus_varini") or die(mysql_error());

$sql = "select * from admin limit 1";
$res = mysql_query($sql);
$rows = mysql_fetch_array($res);
print_r($rows);
?>


text:
package fi.thl.example.model;

public final class Address extends SecureString {
	protected static String pattern = ".*";

	public Address(String s) {
		super(s, pattern);
	}
}


text:
import {FunctionCallDeserializer} from "../../../src/common/function/function-call-deserializer";
import {ISerializedFunctionCall} from "../../../src/common/function/serialized-function-call";
import {functionId, IFunctionId} from "../../../src/common/function/function-id";
describe("FunctionCallDeserializer", function () {

    let getFunctionSpy: jasmine.Spy;
    let deserializer: FunctionCallDeserializer;

    beforeEach(function () {
        getFunctionSpy = jasmine.createSpy("functionLookupTable.getFunction");
        deserializer = new FunctionCallDeserializer({ getFunction: getFunctionSpy } as any);
    });

    describe("deserializeFunctionCall", function () {
        it("returns a function", function () {
            // arrange
            const serializedCall: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 0),
                parameters: []
            };

            getFunctionSpy.and.returnValue(function () { return 2; });

            // act
            const func = deserializer.deserializeFunctionCall(serializedCall);

            // assert
            expect(typeof func).toBe("function");
        });

        it("throws if the function is not in the registry", function () {
            // arrange
            const serializedCall: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 0),
                parameters: []
            };

            getFunctionSpy.and.returnValue(undefined);

            // act, assert
            expect(() => deserializer.deserializeFunctionCall(serializedCall)).toThrowError("The function with the id test-0 could not be retrieved while deserializing the function call. Is the function correctly registered?");
        });

        it("the returned function calls the deserialized function and passes the serialized params", function () {
            // arrange
            const serializedCall: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 0),
                parameters: [2]
            };

            getFunctionSpy.and.returnValue(function (x: number) { return x; });

            // act
            const func = deserializer.deserializeFunctionCall(serializedCall);

            // assert
            expect(func()).toBe(2);
        });

        it("passes the additional parameters to the deserialized function", function () {
            // arrange
            const serializedCall: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 0),
                parameters: [2]
            };

            getFunctionSpy.and.returnValue(function (x: number, y: number) { return x + y; });

            // act
            const func = deserializer.deserializeFunctionCall(serializedCall);

            // assert
            expect(func(5)).toBe(7);
        });

        it("deserializes the serialized function calls in the params, if deserializeParams is true", function () {
            // arrange
            const serializedParam: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 0),
                parameters: [2]
            };

            const serializedCall: ISerializedFunctionCall = {
                ______serializedFunctionCall: true,
                functionId: functionId("test", 1),
                parameters: [serializedParam]
            };

            getFunctionSpy.and.callFake(function (funcId: IFunctionId): Function | undefined {
                if (funcId.identifier === "test-0") {
                    return (x: number) => x;
                } else if (funcId.identifier === "test-1") {
                    return (x: Function) => x();
                }
                return undefined;
            });

            // act
            const func = deserializer.deserializeFunctionCall(serializedCall, true);

            // assert
            expect(func()).toBe(2);
        });
    });
});