text:
<!doctype html>

      <meta charset="utf-8">
      <title>2014-FR-20</title>
    <link class="module" rel="stylesheet" href="../../../_common/modules/pemFioi/taskStyles-0.1.css" id="http://www.france-ioi.org/modules/pemFioi/taskStyles-0.1.css">

Terminal

         Vous disposez d'une application permettant de manipuler des fichiers avec les commandes suivantes :

ls affiche le nom et la taille de tous les fichiers présents. Par exemple,
            l'affichage zora  50 ko indique qu'il y a un fichier nommé « zora » de taille 50 ko.

rm permet de supprimer un fichier. Par exemple,
                rm titi supprime le fichier nommé « titi ».

Votre objectif est de trouver les deux fichiers ayant les plus grandes tailles et de supprimer ces deux fichiers et uniquement ceux-là.

ls affiche le nom et la taille (en ko) de tous les fichiers présents.

rm permet de supprimer un fichier. Par exemple,
                rm titi supprime le fichier nommé « titi ».

mv permet de renommer un fichier. Par exemple,
                mv titi toto renomme le fichier « titi » avec le nom « toto ».

cp permet de copier un fichier. Par exemple,
                cp titi toto crée une copie du fichier « titi » portant le nom « toto ».

            Vous disposez de deux fichiers :

            Votre objectif est d'échanger les noms des deux fichiers, pour obtenir :

momo         50 ko
zora         90 ko

momo         90 ko
zora         50 ko

<textarea class="shell" disabled id="shell_output" rows="8" cols="80" style="overflow-y: scroll"></textarea>

Commande :
              <input type="text" id="shell_input" maxlength="50" size="50">
              <input type="button" onclick="task.executeInput()" value="Exécuter">

Solution

Il faut tout d'abord découvrir combien de fichiers existent et quels sont leurs tailles. La commande ls le permet.

$ ls
      bibi         90 ko
      momo         30 ko
      toto         70 ko
      zora         50 ko

On observe alors que les deux fichiers les plus gros sont : « bibi » et « toto ». Commençons par supprimer
          le premier, à l'aide de la commande rm.

$ rm bibi
Le fichier a été supprimé.

On peut ensuite supprimer le second, en utilisant à nouveau la commande rm.

$ rm toto
Le fichier a été supprimé.

On peut alors exécuter ls afin de vérifier qu'il reste bien les deux plus petits fichiers.

$ ls
      momo         30 ko
      zora         50 ko

Une approche qui ne fonctionne pas serait de d'abord essayer de renommer le fichier « momo » en « zora » puis de renommer « zora » en « momo ». En effet, à la suite de la première étape on aurait deux fichiers différents portant le même nom « zora », ce que le système n'autorise pas.

Pour pouvoir échanger les noms des deux fichiers, il faut utiliser un troisième nom, utilisé de manière temporaire. Ce nom peut être choisi comme on veut, prenons par exemple « temp ». On va donc procéder en trois étapes :

on renomme « momo » en « temp »,

on renomme « zora » en « momo »,

on renomme « temp » en « zora ».

Pour effectuer chacun des trois renommages, on utilise la commande mv.

$ mv momo temp
Le fichier a été renommé.

$ mv zora momo
Le fichier a été renommé.

$ mv temp zora
Le fichier a été renommé.

On peut alors exécuter ls afin de vérifier qu'on a bien obtenu le résultat souhaité.

$ ls
      momo         90 ko
      zora         50 ko

C'est de l'informatique !

Tous les ordinateurs se basent sur des « systèmes de fichiers ». Même si l'on ne le voit pas toujours, tous les appareils photos numériques, les tablettes, et les téléphones de type « smartphone » s'appuient également sur des fichiers.

         Un fichier contient des données (par exemple du texte, une image, etc…) ou bien les instructions d'un programme. Chaque fichier porte un nom. Ce nom est parfois choisi automatiquement, comme lorsqu'on prend une photo avec un appareil photo numérique, mais il peut également être spécifié par l'utilisateur, comme lorsqu'on enregistre un document créé avec un traitement de texte.

La plupart des systèmes modernes permettent de « renommer » un fichier (changer son nom) à travers ce que l'on appelle une « interface graphique », dans laquelle on peut voir le nom du fichier, cliquer dessus, modifier le nom, puis valider. Cependant, aux débuts de l'informatique, les interfaces graphiques n'existaient pas. La seule manière de renommer, déplacer, copier, ou supprimer des fichiers consistait à utiliser des interfaces en « ligne de commande », comme il fallait le faire dans ce sujet.

         Les interfaces en « ligne de commande » existent toujours dans les systèmes actuels, même si elles sont souvent cachées. Dans certains cas, l'interface en ligne de commande permet d'effectuer des opérations complexes plus rapidement qu'avec une interface graphique. Surtout, les actions effectuées en ligne de commande peuvent être facilement effectuées de nouveau de manière automatique, ce qui permet de « programmer » des manipulations de fichiers.


text:
from django.contrib.auth.models import Group
from django.urls import reverse

from workshops.models import Event, Organization, Person, Tag
from workshops.tests.base import TestBase, consent_to_all_required_consents

class TestAdminDashboard(TestBase):
    """Tests for the admin dashboard."""

    def setUp(self):
        self._setUpEvents()
        self._setUpUsersAndLogin()

        # assign an upcoming event to the logged in user
        self.assigned_upcoming_event = Event.objects.active().upcoming_events().first()
        self.assigned_upcoming_event.assigned_to = self.admin
        self.assigned_upcoming_event.save()

        # assign an unpublished event to the logged in user
        self.assigned_unpublished_event = (
            Event.objects.active().unpublished_events().first()
        )
        self.assigned_unpublished_event.assigned_to = self.admin
        self.assigned_unpublished_event.save()

    def test_has_upcoming_events(self):
        """Test that the admin dashboard is passed some
        upcoming_events in the context."""

        # clear out assigned_to to avoid the default filtering
        response = self.client.get(f"{reverse('admin-dashboard')}?assigned_to=")

        # This will fail if the context variable doesn't exist
        events = response.context["current_events"]

        # all unassigned current events should be shown
        num_current_events = (
            Event.objects.current_events().filter(assigned_to=None).count()
        )
        self.assertEqual(len(events), num_current_events)

        # They should all be labeled 'upcoming'.
        assert all([("upcoming" in e.slug or "ongoing" in e.slug) for e in events])

    def test_no_inactive_events(self):
        """Make sure we don't display stalled or completed events on the
        dashboard."""
        stalled_tag = Tag.objects.get(name="stalled")
        unresponsive_tag = Tag.objects.get(name="unresponsive")
        cancelled_tag = Tag.objects.get(name="unresponsive")

        stalled = Event.objects.create(
            slug="stalled-event",
            host=Organization.objects.first(),
        )
        stalled.tags.add(stalled_tag)

        unresponsive = Event.objects.create(
            slug="unresponsive-event",
            host=Organization.objects.first(),
        )
        unresponsive.tags.add(unresponsive_tag)

        cancelled = Event.objects.create(
            slug="cancelled-event",
            host=Organization.objects.first(),
        )
        cancelled.tags.add(cancelled_tag)

        completed = Event.objects.create(
            slug="completed-event", completed=True, host=Organization.objects.first()
        )

        # stalled event appears in unfiltered list of events
        self.assertNotIn(stalled, Event.objects.unpublished_events())
        self.assertNotIn(unresponsive, Event.objects.unpublished_events())
        self.assertNotIn(cancelled, Event.objects.unpublished_events())
        self.assertNotIn(completed, Event.objects.unpublished_events())

        response = self.client.get(f"{reverse('admin-dashboard')}?assigned_to=")
        self.assertNotIn(stalled, response.context["unpublished_events"])
        self.assertNotIn(unresponsive, response.context["unpublished_events"])
        self.assertNotIn(cancelled, response.context["unpublished_events"])
        self.assertNotIn(completed, response.context["unpublished_events"])

    def test_events_default(self):
        """The admin dashboard shows the events assigned to the current logged in
        user by default (when the url is /dashboard/admin/)."""
        upcoming_event = Event.objects.upcoming_events().first()
        upcoming_event.assigned_to = self.admin
        upcoming_event.save()

        unpublished_event = Event.objects.active().unpublished_events().first()
        unpublished_event.assigned_to = self.admin
        unpublished_event.save()

        response = self.client.get(reverse("admin-dashboard"))

        # This will fail if the context variable doesn't exist
        current_events = response.context["current_events"]
        unpublished_events = response.context["unpublished_events"]
        assigned_to = response.context["assigned_to"]

        self.assertEqual(list(current_events), [upcoming_event])
        self.assertEqual(list(unpublished_events), [unpublished_event])
        self.assertEqual(assigned_to, self.admin)

    def test_events_assigned_to_none(self):
        """The admin dashboard shows all events if assigned to is None
        (when the url is /dashboard/admin/?assigned_to=)."""
        response = self.client.get(reverse("admin-dashboard"))

        # This will fail if the context variable doesn't exist
        current_events = response.context["current_events"]
        unpublished_events = response.context["unpublished_events"]
        assigned_to = response.context["assigned_to"]

        self.assertEqual(list(current_events), [self.assigned_upcoming_event])
        self.assertEqual(list(unpublished_events), [self.assigned_unpublished_event])
        self.assertEqual(assigned_to, self.admin)

    def test_events_assigned_to_another_user(self):
        """The admin dashboard shows all events assigned to a particular user
        if that user is specified in the assigned_to
        (when the url is /dashboard/admin/?assigned_to=other_user)."""
        other_admin = Person.objects.create_superuser(
            username="other_admin",
            personal="OtherSuper",
            family="User",
            email="other_sudo@example.org",
            password="admin",
        )
        consent_to_all_required_consents(other_admin)

        # Add an upcoming event to the logged in admin (self.admin)
        # and one to other_admin
        upcoming_event = (
            Event.objects.active()
            .filter(assigned_to__isnull=True)
            .upcoming_events()
            .first()
        )
        upcoming_event.assigned_to = other_admin
        upcoming_event.save()

        # Add an unpublished event to logged in admin (self.admin)
        # and another to other_admin
        unpublished_event = (
            Event.objects.active()
            .filter(assigned_to__isnull=True)
            .unpublished_events()
            .first()
        )
        unpublished_event.assigned_to = other_admin
        unpublished_event.save()

        response = self.client.get(
            f"{reverse('admin-dashboard')}?assigned_to={other_admin.id}"
        )

        # This will fail if the context variable doesn't exist
        current_events = response.context["current_events"]
        unpublished_events = response.context["unpublished_events"]
        assigned_to = response.context["assigned_to"]

        self.assertEqual(list(current_events), [upcoming_event])
        self.assertEqual(list(unpublished_events), [unpublished_event])
        self.assertEqual(assigned_to, other_admin)

class TestDispatch(TestBase):
    """Test that the right dashboard (instructor or admin dashboard) is displayed
    after logging in."""

    def test_superuser_logs_in(self):
        person = Person.objects.create_superuser(
            username="admin",
            personal="",
            family="",
            email="admin@example.org",
            password="pass",
        )
        consent_to_all_required_consents(person)

        rv = self.client.post(
            reverse("login"), {"username": "admin", "password": "pass"}, follow=True
        )

        self.assertEqual(rv.resolver_match.view_name, "admin-dashboard")

    def test_mentor_logs_in(self):
        mentor = Person.objects.create_user(
            username="user",
            personal="",
            family="",
            email="mentor@example.org",
            password="pass",
        )
        admins = Group.objects.get(name="administrators")
        mentor.groups.add(admins)
        self.person_consent_required_terms(mentor)

        rv = self.client.post(
            reverse("login"), {"username": "user", "password": "pass"}, follow=True
        )

        self.assertEqual(rv.resolver_match.view_name, "admin-dashboard")

    def test_steering_committee_member_logs_in(self):
        mentor = Person.objects.create_user(
            username="user",
            personal="",
            family="",
            email="user@example.org",
            password="pass",
        )
        steering_committee = Group.objects.get(name="steering committee")
        mentor.groups.add(steering_committee)
        self.person_consent_required_terms(mentor)

        rv = self.client.post(
            reverse("login"), {"username": "user", "password": "pass"}, follow=True
        )

        self.assertEqual(rv.resolver_match.view_name, "admin-dashboard")

    def test_trainee_logs_in(self):
        self.trainee = Person.objects.create_user(
            username="trainee",
            personal="",
            family="",
            email="trainee@example.org",
            password="pass",
        )
        self.person_consent_required_terms(self.trainee)

        rv = self.client.post(
            reverse("login"), {"username": "trainee", "password": "pass"}, follow=True
        )

        self.assertEqual(rv.resolver_match.view_name, "instructor-dashboard")

redpajama_set_name: RedPajamaGithub


text:
package org.keycloak.storage.ldap.idm.model;

import org.jboss.logging.Logger;

import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;

/**
 * @author Marek Posolda
 */
public class LDAPObject {

    private static final Logger logger = Logger.getLogger(LDAPObject.class);

    private String uuid;
    private LDAPDn dn;

    // In most cases, there is single "rdnAttributeName" . Usually "uid" or "cn"
    private final List<String> rdnAttributeNames = new LinkedList<>();

    private final List<String> objectClasses = new LinkedList<>();

    // NOTE: names of read-only attributes are lower-cased to avoid case sensitivity issues
    private final List<String> readOnlyAttributeNames = new LinkedList<>();

    private final Map<String, Set<String>> attributes = new HashMap<>();

    // Copy of "attributes" containing lower-cased keys
    private final Map<String, Set<String>> lowerCasedAttributes = new HashMap<>();

    // range attributes are always read from 0 to max so just saving the top value
    private final Map<String, Integer> rangedAttributes = new HashMap<>();

    // consumer to be executed when mandatory attributes are set
    private Consumer<LDAPObject> consumerOnMandatoryAttributesComplete;

    // mandatory attributes defined for the entry
    private Set<String> mandatoryAttributeNames;

    // mandatory attributes that remain not set
    private Set<String> mandatoryAttributeNamesRemaining;

    public void executeOnMandatoryAttributesComplete(Set<String> mandatoryAttributeNames, Consumer<LDAPObject> consumer) {
        this.consumerOnMandatoryAttributesComplete = consumer;
        this.mandatoryAttributeNames = new LinkedHashSet<>();
        this.mandatoryAttributeNamesRemaining = new LinkedHashSet<>();
        // initializes mandatory attributes
        if (mandatoryAttributeNames != null) {
            for (String name : mandatoryAttributeNames) {
                name = name.toLowerCase();
                this.mandatoryAttributeNames.add(name);
                Set<String> values = lowerCasedAttributes.get(name);
                if (values == null || values.isEmpty()) {
                    this.mandatoryAttributeNamesRemaining.add(name);
                }
            }
        }
        executeConsumerOnMandatoryAttributesComplete();
    }

    public boolean isWaitingForExecutionOnMandatoryAttributesComplete() {
        return consumerOnMandatoryAttributesComplete != null;
    }

    public Set<String> getMandatoryAttributeNamesRemaining() {
        return mandatoryAttributeNamesRemaining;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public LDAPDn getDn() {
        return dn;
    }

    public void setDn(LDAPDn dn) {
        this.dn = dn;
    }

    public List<String> getObjectClasses() {
        return objectClasses;
    }

    public void setObjectClasses(Collection<String> objectClasses) {
        this.objectClasses.clear();
        this.objectClasses.addAll(objectClasses);
    }

    public List<String> getReadOnlyAttributeNames() {
        return readOnlyAttributeNames;
    }

    public void addReadOnlyAttributeName(String readOnlyAttribute) {
        readOnlyAttributeNames.add(readOnlyAttribute.toLowerCase());
    }

    public void removeReadOnlyAttributeName(String readOnlyAttribute) {
        readOnlyAttributeNames.remove(readOnlyAttribute.toLowerCase());
    }

    public List<String> getRdnAttributeNames() {
        return rdnAttributeNames;
    }

    /**
     * Useful when single value will be used as the "RDN" attribute. Which will be most of the cases
     */
    public void setRdnAttributeName(String rdnAttributeName) {
        this.rdnAttributeNames.clear();
        this.rdnAttributeNames.add(rdnAttributeName);
    }

    public void setRdnAttributeNames(List<String> rdnAttributeNames) {
        this.rdnAttributeNames.clear();
        this.rdnAttributeNames.addAll(rdnAttributeNames);
    }

    public void addRdnAttributeName(String rdnAttributeName) {
        this.rdnAttributeNames.add(rdnAttributeName);
    }

    public void setSingleAttribute(String attributeName, String attributeValue) {
        Set<String> asSet = new LinkedHashSet<>();
        if (attributeValue != null) {
            asSet.add(attributeValue);
        }
        setAttribute(attributeName, asSet);
    }

    public void setAttribute(String attributeName, Set<String> attributeValue) {
        attributes.put(attributeName, attributeValue);
        attributeName = attributeName.toLowerCase();
        lowerCasedAttributes.put(attributeName, attributeValue);
        if (consumerOnMandatoryAttributesComplete != null) {
            if (!attributeValue.isEmpty()) {
                mandatoryAttributeNamesRemaining.remove(attributeName);
            } else if (mandatoryAttributeNames.contains(attributeName)) {
                mandatoryAttributeNamesRemaining.add(attributeName);
            }
            executeConsumerOnMandatoryAttributesComplete();
        }
    }

    // Case-insensitive
    public String getAttributeAsString(String name) {
        Set<String> attrValue = lowerCasedAttributes.get(name.toLowerCase());
        if (attrValue == null || attrValue.size() == 0) {
            return null;
        } else if (attrValue.size() > 1) {
            logger.warnf("Expected String but attribute '%s' has more values '%s' on object '%s' . Returning just first value", name, attrValue, dn);
        }

        return attrValue.iterator().next();
    }

    // Case-insensitive. Return null if there is not value of attribute with given name or set with all values otherwise
    public Set<String> getAttributeAsSet(String name) {
        Set<String> values = lowerCasedAttributes.get(name.toLowerCase());
        return (values == null) ? null : new LinkedHashSet<>(values);
    }

    public boolean isRangeComplete(String name) {
        return !rangedAttributes.containsKey(name);
    }

    public int getCurrentRange(String name) {
        return rangedAttributes.get(name);
    }

    public boolean isRangeCompleteForAllAttributes() {
        return rangedAttributes.isEmpty();
    }

    public void addRangedAttribute(String name, int max) {
        Integer current = rangedAttributes.get(name);
        if (current == null || max > current) {
            rangedAttributes.put(name, max);
        }
    }

    public void populateRangedAttribute(LDAPObject obj, String name) {
        Set<String> newValues = obj.getAttributes().get(name);
        if (newValues != null && attributes.containsKey(name)) {
            attributes.get(name).addAll(newValues);
            if (!obj.isRangeComplete(name)) {
                addRangedAttribute(name, obj.getCurrentRange(name));
            } else {
                rangedAttributes.remove(name);
            }
        }
    }

    public Map<String, Set<String>> getAttributes() {
        return attributes;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (!getClass().isInstance(obj)) {
            return false;
        }

        LDAPObject other = (LDAPObject) obj;

        return getUuid() != null && other.getUuid() != null && getUuid().equals(other.getUuid());
    }

    @Override
    public int hashCode() {
        int result = getUuid() != null ? getUuid().hashCode() : 0;
        result = 31 * result + (getUuid() != null ? getUuid().hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "LDAP Object [ dn: " + dn + " , uuid: " + uuid + ", attributes: " + attributes +
                ", readOnly attribute names: " + readOnlyAttributeNames + ", ranges: " + rangedAttributes + " ]";
    }

    private void executeConsumerOnMandatoryAttributesComplete() {
        if (mandatoryAttributeNamesRemaining.isEmpty()) {
            final Consumer<LDAPObject> consumer = consumerOnMandatoryAttributesComplete;
            consumerOnMandatoryAttributesComplete = null;
            mandatoryAttributeNames = null;
            mandatoryAttributeNamesRemaining = null;
            consumer.accept(this);
        }
    }
}


text:
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
        Toggle navigation

      </button>

Guides

Reference

 GitHub


text:
<?php
//views/profiles/view.php
$this->load->view($this->config->item('theme') . 'header');

echo '
' . $profile['first_name'] . " " . $profile['last_name'] . '
';
echo $profile['email'];
echo '
' . anchor('profile/', 'Back to Profiles List') . '
';

$this->load->view($this->config->item('theme') . 'footer');


text:
define(['marionette',
    'collections/autoprocattachments',
    'modules/dc/views/autoprocattachments',
    'views/log',
    'utils'], function(Marionette,
        AutoProcAttachments, AutoProcAttachmentsView,
        LogView, utils) {

    return Marionette.ItemView.extend({
        modelEvents: { 'change': 'render' },

        events: {
            'click .logf': 'showLog',
            'click a.pattach': 'showAttachments',
            'click .dll': utils.signHandler,
        },

        showAttachments: function(e) {
            e.preventDefault()

            this.attachments = new AutoProcAttachments()
            this.attachments.queryParams.AUTOPROCPROGRAMID = this.model.get('AID')
            this.attachments.fetch()

            app.dialog.show(new DialogView({
                title: 'Attachments: '+this.model.escape('TYPE'),
                view: new AutoProcAttachmentsView({ collection: this.attachments, idParam: 'AUTOPROCPROGRAMATTACHMENTID' }),
                autosize: true
            }))
        },

        showLog: function(e) {
            e.preventDefault()
            var url = $(e.target).attr('href')
            var self = this
            utils.sign({
                url: url,
                callback: function(resp) {
                    app.dialog.show(new LogView({ title: self.model.get('TYPE') + ' Log File', url: url+'?token='+resp.token }))
                }
            })
        },
    })

})


text:
#ifndef _CCB_CCMENULOADER_H_
#define _CCB_CCMENULOADER_H_

#include "CCLayerLoader.h"

NS_CC_EXT_BEGIN

/* Forward declaration. */
class CCBReader;
/**
 *  @js NA
 *  @lua NA
 */
class CCMenuLoader : public CCLayerLoader {
    public:
        virtual ~CCMenuLoader() {};
        CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CCMenuLoader, loader);

    protected:
        CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CCMenu);
};

NS_CC_EXT_END

#endif


text:
<?php
/**
 * Created by PhpStorm.
 * User: Joseph
 * Date: 14-5-20
 * Time: 下午2:11
 */

namespace Controller\Log;

class IndexTest extends \PHPUnit_Framework_TestCase {
    function test_tset(){
        $data =array("tst"=>1);
        $this->assertTrue(is_array($data));
    }
}


text:
<?php

/**
 * Represents current transaction state of a connection.
 */
final class AphrontDatabaseTransactionState extends Phobject {

  private $depth           = 0;
  private $readLockLevel   = 0;
  private $writeLockLevel  = 0;

  public function getDepth() {
    return $this->depth;
  }

  public function increaseDepth() {
    return ++$this->depth;
  }

  public function decreaseDepth() {
    if ($this->depth == 0) {
      throw new Exception(
        pht(
          'Too many calls to %s or %s!',
          'saveTransaction()',
          'killTransaction()'));
    }

    return --$this->depth;
  }

  public function getSavepointName() {
    return 'Aphront_Savepoint_'.$this->depth;
  }

  public function beginReadLocking() {
    $this->readLockLevel++;
    return $this;
  }

  public function endReadLocking() {
    if ($this->readLockLevel == 0) {
      throw new Exception(
        pht(
          'Too many calls to %s!',
          __FUNCTION__.'()'));
    }
    $this->readLockLevel--;
    return $this;
  }

  public function isReadLocking() {
    return ($this->readLockLevel > 0);
  }

  public function beginWriteLocking() {
    $this->writeLockLevel++;
    return $this;
  }

  public function endWriteLocking() {
    if ($this->writeLockLevel == 0) {
      throw new Exception(
        pht(
          'Too many calls to %s!',
          __FUNCTION__.'()'));
    }
    $this->writeLockLevel--;
    return $this;
  }

  public function isWriteLocking() {
    return ($this->writeLockLevel > 0);
  }

  public function __destruct() {
    if ($this->depth) {
      throw new Exception(
        pht(
          'Process exited with an open transaction! The transaction '.
          'will be implicitly rolled back. Calls to %s must always be '.
          'paired with a call to %s or %s.',
          'openTransaction()',
          'saveTransaction()',
          'killTransaction()'));
    }
    if ($this->readLockLevel) {
      throw new Exception(
        pht(
          'Process exited with an open read lock! Call to %s '.
          'must always be paired with a call to %s.',
          'beginReadLocking()',
          'endReadLocking()'));
    }
    if ($this->writeLockLevel) {
      throw new Exception(
        pht(
          'Process exited with an open write lock! Call to %s '.
          'must always be paired with a call to %s.',
          'beginWriteLocking()',
          'endWriteLocking()'));
    }
  }

}


text:
from __future__ import print_function, unicode_literals, absolute_import

import os
import os.path
import shutil
import errno
import logging

logger = logging.getLogger(__name__)

COLOR_CODES = {
    "reset": "\033[0m",
    "black": "\033[1;30m",
    "red": "\033[1;31m",
    "green": "\033[1;32m",
    "yellow": "\033[1;33m",
    "blue": "\033[1;34m",
    "magenta": "\033[1;35m",
    "cyan": "\033[1;36m",
    "white": "\033[1;37m",
    "bgred": "\033[1;41m",
    "bggrey": "\033[1;100m",
}

def color_msg(color, msg):
    return COLOR_CODES[color] + msg + COLOR_CODES["reset"]

def check_extension(filename):
    """Check if the file extension is in the allowed extensions

    The `fnmatch` module can also get the suffix:
        patterns = ["*.md", "*.mkd", "*.markdown"]
        fnmatch.filter(files, pattern)
    """

    allowed_extensions = (".md", ".mkd", ".mdown", ".markdown")
    return os.path.splitext(filename)[1] in allowed_extensions

def copytree(src, dst, symlinks=False, ignore=None):
    """Copy from source directory to destination"""

    if not os.path.exists(dst):
        os.makedirs(dst)
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)

def emptytree(directory, exclude_list=None):
    """Delete all the files and dirs under specified directory"""

    if not isinstance(directory, unicode):
        directory = unicode(directory, 'utf-8')
    if not exclude_list:
        exclude_list = []
    for p in os.listdir(directory):
        if p in exclude_list:
            continue
        fp = os.path.join(directory, p)
        if os.path.isdir(fp):
            try:
                shutil.rmtree(fp)
                logger.debug("Delete directory %s", fp)
            except OSError as e:
                logger.error("Unable to delete directory %s: %s",
                             fp, unicode(e))
        elif os.path.isfile(fp):
            try:
                logging.debug("Delete file %s", fp)
                os.remove(fp)
            except OSError as e:
                logger.error("Unable to delete file %s: %s", fp, unicode(e))
        else:
            logger.error("Unable to delete %s, unknown filetype", fp)

def mkdir_p(path):
    """Make parent directories as needed, like `mkdir -p`"""
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

def listdir_nohidden(path):
    """List not hidden files or directories under path"""
    for f in os.listdir(path):
        if isinstance(f, str):
            f = unicode(f, "utf-8")
        if not f.startswith('.'):
            yield f

if __name__ == "__main__":
    print(color_msg("black", "Black"))
    print(color_msg("red", "Red"))
    print(color_msg("green", "Green"))
    print(color_msg("yellow", "Yellow"))
    print(color_msg("blue", "Blue"))
    print(color_msg("magenta", "Magenta"))
    print(color_msg("cyan", "Cyan"))
    print(color_msg("white", "White"))
    print(color_msg("bgred", "Background Red"))
    print(color_msg("bggrey", "Background Grey"))


text:
/*Generated by KISSY Module Compiler*/
config({
'resizable': {requires: ['node','rich-base','dd/base']}
});


text:
(function() {

	'use strict';

	define(['angular','ngResource'],function(angular) {

		var services = angular.module('account.services', ['ngResource']);

		services.factory('accountsService', function($resource) {
			return $resource("./../api/accounts", {}, {
				query : {method : 'GET', isArray : true},
				create : {method : 'POST'}
			});
		});

		services.factory('accountService', function($resource) {
			return $resource("./../api/accounts/:id", {}, {
				detail : {method : 'GET'},
				update : {method : 'PUT', params : {id: "@id"}},
				remove : {method : 'DELETE'}
			});
		});
	});
})();


text:
<?php

namespace PhraseanetSDK\Entity;

use PhraseanetSDK\Annotation\ApiField as ApiField;
use PhraseanetSDK\Annotation\ApiRelation as ApiRelation;
use PhraseanetSDK\Annotation\Id as Id;

class QuarantineSession
{

    public static function fromList(array $values)
    {
        $sessions = array();

        foreach ($values as $value) {
            $sessions[$value->id] = self::fromValue($value);
        }

        return $sessions;
    }

    public static function fromValue(\stdClass $value)
    {
        return new self($value);
    }

    /**
     * @var \stdClass
     */
    protected $source;

    /**
     * @var User
     */
    protected $user;

    /**
     * @param \stdClass $source
     */
    public function __construct(\stdClass $source)
    {
        $this->source = $source;
    }

    /**
     * The session id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->source->id;
    }

    /**
     * The user id
     *
     * @return integer
     */
    public function getUser()
    {
        return $this->user ?: $this->user = User::fromValue($this->source->user);
    }
}


text:
require 'spec_helper'

RSpec.describe ::GeoConcerns::VectorWorkShowPresenter do
  let(:solr_document) { SolrDocument.new(attributes) }
  let(:ability) { nil }

  describe "delegated methods" do
    let(:attributes)  { { "geo_mime_type_tesim" => ['application/zip; ogr-format="ESRI Shapefile"'] } }
    subject { described_class.new(solr_document, ability) }

    describe "#first" do
      it "delegates to solr document" do
        expect(subject.first('geo_mime_type_tesim')).to eq('application/zip; ogr-format="ESRI Shapefile"')
      end
    end

    describe "#has?" do
      it "delegates to solr document" do
        expect(subject.has?('geo_mime_type_tesim')).to be_truthy
      end
    end
  end

  describe "file presenters" do
    let(:obj) { FactoryGirl.create(:vector_work_with_vector_and_metadata_file) }
    let(:attributes) { obj.to_solr }
    subject { described_class.new(solr_document, ability) }

    describe "#geo_file_set_presenters" do
      it "returns only vector file set presenters" do
        expect(subject.geo_file_set_presenters.count).to eq 1
      end
    end

    describe "#external_metadata_file_set_presenters" do
      it "returns only external_metadata_file_set_presenters" do
        expect(subject.external_metadata_file_set_presenters.count).to eq 1
      end
    end
  end
end


text:
using System.Xml;

namespace PlaySharp
{
    /// <summary>
    ///     Represents a playable video in PlayOn.
    /// </summary>
    public class PlayOnVideo : PlayOnItem
    {
        private string _airDate;
        private string _artUrlLarge;
        private string _description;
        private bool _loadedDetails;
        private string _mediaTitle;
        private string _mediaUrl;
        private string _playLaterName;
        private string _playLaterUrl;
        private string _runTime;
        private string _series;

        public PlayOnVideo(IPlayOn api) : base(api)
        {
            _loadedDetails = false;
        }

        /// <summary>
        ///     A relative PlayOn URL for the large image for this video item.
        /// </summary>
        public string ArtUrlLarge
        {
            get
            {
                LoadDetails();
                return _artUrlLarge;
            }
            set => _airDate = value;
        }

        /// <summary>
        ///     The date string representing the date this video item originally aired.
        /// </summary>
        public string AirDate
        {
            get
            {
                LoadDetails();
                return _airDate;
            }
            set => _airDate = value;
        }

        /// <summary>
        ///     The full description for this video item.
        /// </summary>
        public string Description
        {
            get
            {
                LoadDetails();
                return _description;
            }
            set => _description = value;
        }

        /// <summary>
        ///     The full media title for this video item.
        /// </summary>
        public string MediaTitle
        {
            get
            {
                LoadDetails();
                return _mediaTitle;
            }
            set => _mediaTitle = value;
        }

        /// <summary>
        ///     A relative PlayOn URL for streaming the video of this item.
        /// </summary>
        public string MediaUrl
        {
            get
            {
                LoadDetails();
                return _mediaUrl;
            }
            set => _mediaUrl = value;
        }

        /// <summary>
        ///     The name of the PlayLater instance associated with the connected server.
        /// </summary>
        public string PlayLaterName
        {
            get
            {
                LoadDetails();
                return _playLaterName;
            }
            set => _playLaterName = value;
        }

        /// <summary>
        ///     A relative PlayOn URL for queueing this video in PlayLater.
        /// </summary>
        public string PlayLaterUrl
        {
            get
            {
                LoadDetails();
                return _playLaterUrl;
            }
            set => _playLaterUrl = value;
        }

        /// <summary>
        ///     The runtime of this video item.
        /// </summary>
        public string RunTime
        {
            get
            {
                LoadDetails();
                return _runTime;
            }
            set => _runTime = value;
        }

        /// <summary>
        ///     The series name associated with this video item.
        /// </summary>
        public string Series
        {
            get
            {
                LoadDetails();
                return _series;
            }
            set => _series = value;
        }

        public override void LoadFromNode(XmlNode node)
        {
            base.LoadFromNode(node);

            if (!node.HasChildNodes)
                return;

            _artUrlLarge = Util.GetChildNodeAttributeValue(node, "media", "art");
            _airDate = Util.GetChildNodeAttributeValue(node, "date", "name");
            _description = Util.GetChildNodeAttributeValue(node, "description", "name");
            _mediaTitle = Util.GetChildNodeAttributeValue(node, "media_title", "name");
            _mediaUrl = Util.GetChildNodeAttributeValue(node, "media", "src");
            _playLaterName = Util.GetChildNodeAttributeValue(node, "media_playlater", "name");
            _playLaterUrl = Util.GetChildNodeAttributeValue(node, "media_playlater", "src");
            _runTime = Util.GetChildNodeAttributeValue(node, "time", "name");
            _series = Util.GetChildNodeAttributeValue(node, "series", "name");
        }

        private void LoadDetails()
        {
            if (_loadedDetails)
                return;
            PlayOn.LoadItemDetails(this);
            _loadedDetails = true;
        }
    }
}


text:
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <title>Moya Bootstrap</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">

        <link href="assets/css/bootstrap.css" rel="stylesheet">
        <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
        <link href="assets/css/custom.css" rel="stylesheet">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".doc-navbar-collapse">
                Toggle navigation

              </button>
              Moya Documentation

                        Reference

                        Tags

                        Tutorial

            ← 4. Moya Blog

            6. Moya Comments →

Moya Bootstrap

Moya Bootstrap is a media-only library which contains the Twitter Bootstrap CSS framework.

NOTE The long name of this library (moya.twitter.bootstrap) reflects the fact that although it was packaged in Moya, the author is Twitter.

Installation ¶

You may import Moya Twitter Bootstrap with the following:

<import py="moya.libs.bootstrap" />

And you can install it with:

<install name="bootstrap" lib="moya.twitter.bootstrap" />

This library has no views, and does not need to be mounted.

Introduction ¶

The Twitter Bootstrap CSS framework is the most popular HTML, CSS and JS framework for developing responsive, mobile first projects on the web.

Moya uses Bootstrap in its built in libraries, since without a CSS framework, your newly created site would be aesthetically challenged. One advantage of Bootstrap is that it is easy to customize, and there are many drop-in themes available.

NOTE Moya doesn't require Bootstrap. It's just used to give you a head start with designing stylesheets.

Media ¶

Moya Bootstrap provides a number of media files, which you can list with the following command:

$ moya fs media --tree bootstrap-media

The simplest way to include the Bootstrap CSS would be to add it to your base template:

<link href="{% media 'css/bootstrap.css' from 'twitter.bootstrap' %}" rel="stylesheet">

If you built a Moya project with moya.start, the CSS will have been included for you in the base template. The following command will display the base template in the terminal:

$ moya fs templates --cat moya.twitter.bootstrap/starter.html

            ← 4. Moya Blog

            6. Moya Comments →

Installation

Introduction

Media

Moya is © 2014 Moya Software Foundation.


text:
[![Circle CI](https://circleci.com/gh/bonusbits/bonusbits_library/tree/master.svg?style=shield)](https://circleci.com/gh/bonusbits/bonusbits_library/tree/master)
[![Chef cookbook](https://img.shields.io/badge/cookbook-v1.1.1-blue.svg)](https://github.com/bonusbits/bonusbits_library)
[![Join the chat at https://gitter.im/bonusbits](https://badges.gitter.im/bonusbits/bonusbits.svg)](https://gitter.im/bonusbits?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Bonusbits Shared Ruby Libraries and Custom Resources Cookbook.

## Supported Platforms
* Linux
* Windows

## Resources

### Setup DevOps Workstation
* [Setup Mac DevOps Workstation](http://www.bonusbits.com/wiki/Reference:Mac_OS_DevOps_Workstation_Setup_Check_List)
* [Setup Ubuntu DevOps Workstation](http://www.bonusbits.com/wiki/Reference:Ubuntu_DevOps_Workstation_Setup_Check_List)
* [Setup Windows DevOps Workstation](http://www.bonusbits.com/wiki/Reference:Windows_DevOps_Workstation_Setup_Check_List)

### Test Kitchen
* [Setup Test Kitchen](https://www.bonusbits.com/wiki/HowTo:Setup_Test_Kitchen)
* [Test Kitchen Usage](https://www.bonusbits.com/wiki/Reference:Test_Kitchen)
* [Setup Test Kitchen for AWS EC2 Support](https://www.bonusbits.com/wiki/HowTo:Setup_Test_Kitchen_for_AWS_EC2_Support)
* [Test Kitchen Usage](https://www.bonusbits.com/wiki/Reference:Test_Kitchen)


text:
(function(f, define){
    define([ "./kendo.core", "./kendo.userevents" ], f);
})(function(){

(function ($, undefined) {
    var kendo = window.kendo,
        support = kendo.support,
        document = window.document,
        Class = kendo.Class,
        Widget = kendo.ui.Widget,
        Observable = kendo.Observable,
        UserEvents = kendo.UserEvents,
        proxy = $.proxy,
        extend = $.extend,
        getOffset = kendo.getOffset,
        draggables = {},
        dropTargets = {},
        dropAreas = {},
        lastDropTarget,
        elementUnderCursor = kendo.elementUnderCursor,
        KEYUP = "keyup",
        CHANGE = "change",

        // Draggable events
        DRAGSTART = "dragstart",
        HOLD = "hold",
        DRAG = "drag",
        DRAGEND = "dragend",
        DRAGCANCEL = "dragcancel",

        // DropTarget events
        DRAGENTER = "dragenter",
        DRAGLEAVE = "dragleave",
        DROP = "drop";

    function contains(parent, child) {
        try {
            return $.contains(parent, child) || parent == child;
        } catch (e) {
            return false;
        }
    }

    function numericCssPropery(element, property) {
        return parseInt(element.css(property), 10) || 0;
    }

    function within(value, range) {
        return Math.min(Math.max(value, range.min), range.max);
    }

    function containerBoundaries(container, element) {
        var offset = getOffset(container),
            minX = offset.left + numericCssPropery(container, "borderLeftWidth") + numericCssPropery(container, "paddingLeft"),
            minY = offset.top + numericCssPropery(container, "borderTopWidth") + numericCssPropery(container, "paddingTop"),
            maxX = minX + container.width() - element.outerWidth(true),
            maxY = minY + container.height() - element.outerHeight(true);

        return {
            x: { min: minX, max: maxX },
            y: { min: minY, max: maxY }
        };
    }

    function checkTarget(target, targets, areas) {
        var theTarget, theFilter, i = 0,
            targetLen = targets && targets.length,
            areaLen = areas && areas.length;

        while (target && target.parentNode) {
            for (i = 0; i < targetLen; i ++) {
                theTarget = targets[i];
                if (theTarget.element[0] === target) {
                    return { target: theTarget, targetElement: target };
                }
            }

            for (i = 0; i < areaLen; i ++) {
                theFilter = areas[i];
                if (support.matchesSelector.call(target, theFilter.options.filter)) {
                    return { target: theFilter, targetElement: target };
                }
            }

            target = target.parentNode;
        }

        return undefined;
    }

    var TapCapture = Observable.extend({
        init: function(element, options) {
            var that = this,
                domElement = element[0];

            that.capture = false;

            if (domElement.addEventListener) {
                $.each(kendo.eventMap.down.split(" "), function() {
                    domElement.addEventListener(this, proxy(that._press, that), true);
                });
                $.each(kendo.eventMap.up.split(" "), function() {
                    domElement.addEventListener(this, proxy(that._release, that), true);
                });
            } else {
                $.each(kendo.eventMap.down.split(" "), function() {
                    domElement.attachEvent(this, proxy(that._press, that));
                });
                $.each(kendo.eventMap.up.split(" "), function() {
                    domElement.attachEvent(this, proxy(that._release, that));
                });
            }

            Observable.fn.init.call(that);

            that.bind(["press", "release"], options || {});
        },

        captureNext: function() {
            this.capture = true;
        },

        cancelCapture: function() {
            this.capture = false;
        },

        _press: function(e) {
            var that = this;
            that.trigger("press");
            if (that.capture) {
                e.preventDefault();
            }
        },

        _release: function(e) {
            var that = this;
            that.trigger("release");

            if (that.capture) {
                e.preventDefault();
                that.cancelCapture();
            }
        }
    });

    var PaneDimension = Observable.extend({
        init: function(options) {
            var that = this;
            Observable.fn.init.call(that);

            that.forcedEnabled = false;

            $.extend(that, options);

            that.scale = 1;

            if (that.horizontal) {
                that.measure = "offsetWidth";
                that.scrollSize = "scrollWidth";
                that.axis = "x";
            } else {
                that.measure = "offsetHeight";
                that.scrollSize = "scrollHeight";
                that.axis = "y";
            }
        },

        makeVirtual: function() {
            $.extend(this, {
                virtual: true,
                forcedEnabled: true,
                _virtualMin: 0,
                _virtualMax: 0
            });
        },

        virtualSize: function(min, max) {
            if (this._virtualMin !== min || this._virtualMax !== max) {
                this._virtualMin = min;
                this._virtualMax = max;
                this.update();
            }
        },

        outOfBounds: function(offset) {
            return offset > this.max || offset < this.min;
        },

        forceEnabled: function() {
            this.forcedEnabled = true;
        },

        getSize: function() {
            return this.container[0][this.measure];
        },

        getTotal: function() {
            return this.element[0][this.scrollSize];
        },

        rescale: function(scale) {
            this.scale = scale;
        },

        update: function(silent) {
            var that = this,
                total = that.virtual ? that._virtualMax : that.getTotal(),
                scaledTotal = total * that.scale,
                size = that.getSize();

            if (total === 0) {
                return; // we are not visible.
            }

            that.max = that.virtual ? -that._virtualMin : 0;
            that.size = size;
            that.total = scaledTotal;
            that.min = Math.min(that.max, size - scaledTotal);
            that.minScale = size / total;
            that.centerOffset = (scaledTotal - size) / 2;

            that.enabled = that.forcedEnabled || (scaledTotal > size);

            if (!silent) {
                that.trigger(CHANGE, that);
            }
        }
    });

    var PaneDimensions = Observable.extend({
        init: function(options) {
            var that = this;

            Observable.fn.init.call(that);

            that.x = new PaneDimension(extend({horizontal: true}, options));
            that.y = new PaneDimension(extend({horizontal: false}, options));
            that.container = options.container;
            that.forcedMinScale = options.minScale;
            that.maxScale = options.maxScale || 100;

            that.bind(CHANGE, options);
        },

        rescale: function(newScale) {
            this.x.rescale(newScale);
            this.y.rescale(newScale);
            this.refresh();
        },

        centerCoordinates: function() {
            return { x: Math.min(0, -this.x.centerOffset), y: Math.min(0, -this.y.centerOffset) };
        },

        refresh: function() {
            var that = this;
            that.x.update();
            that.y.update();
            that.enabled = that.x.enabled || that.y.enabled;
            that.minScale = that.forcedMinScale || Math.min(that.x.minScale, that.y.minScale);
            that.fitScale = Math.max(that.x.minScale, that.y.minScale);
            that.trigger(CHANGE);
        }
    });

    var PaneAxis = Observable.extend({
        init: function(options) {
            var that = this;
            extend(that, options);
            Observable.fn.init.call(that);
        },

        outOfBounds: function() {
            return this.dimension.outOfBounds(this.movable[this.axis]);
        },

        dragMove: function(delta) {
            var that = this,
                dimension = that.dimension,
                axis = that.axis,
                movable = that.movable,
                position = movable[axis] + delta;

            if (!dimension.enabled) {
                return;
            }

            if ((position < dimension.min && delta < 0) || (position > dimension.max && delta > 0)) {
                delta *= that.resistance;
            }

            movable.translateAxis(axis, delta);
            that.trigger(CHANGE, that);
        }
    });

    var Pane = Class.extend({

        init: function(options) {
            var that = this,
                x,
                y,
                resistance,
                movable;

            extend(that, {elastic: true}, options);

            resistance = that.elastic ? 0.5 : 0;
            movable = that.movable;

            that.x = x = new PaneAxis({
                axis: "x",
                dimension: that.dimensions.x,
                resistance: resistance,
                movable: movable
            });

            that.y = y = new PaneAxis({
                axis: "y",
                dimension: that.dimensions.y,
                resistance: resistance,
                movable: movable
            });

            that.userEvents.bind(["move", "end", "gesturestart", "gesturechange"], {
                gesturestart: function(e) {
                    that.gesture = e;
                    that.offset = that.dimensions.container.offset();
                },

                gesturechange: function(e) {
                    var previousGesture = that.gesture,
                        previousCenter = previousGesture.center,

                        center = e.center,

                        scaleDelta = e.distance / previousGesture.distance,

                        minScale = that.dimensions.minScale,
                        maxScale = that.dimensions.maxScale,
                        coordinates;

                    if (movable.scale <= minScale && scaleDelta < 1) {
                        // Resist shrinking. Instead of shrinking from 1 to 0.5, it will shrink to 0.5 + (1 /* minScale */ - 0.5) * 0.8 = 0.9;
                        scaleDelta += (1 - scaleDelta) * 0.8;
                    }

                    if (movable.scale * scaleDelta >= maxScale) {
                        scaleDelta = maxScale / movable.scale;
                    }

                    var offsetX = movable.x + that.offset.left,
                        offsetY = movable.y + that.offset.top;

                    coordinates = {
                        x: (offsetX - previousCenter.x) * scaleDelta + center.x - offsetX,
                        y: (offsetY - previousCenter.y) * scaleDelta + center.y - offsetY
                    };

                    movable.scaleWith(scaleDelta);

                    x.dragMove(coordinates.x);
                    y.dragMove(coordinates.y);

                    that.dimensions.rescale(movable.scale);
                    that.gesture = e;
                    e.preventDefault();
                },

                move: function(e) {
                    if (e.event.target.tagName.match(/textarea|input/i)) {
                        return;
                    }

                    if (x.dimension.enabled || y.dimension.enabled) {
                        x.dragMove(e.x.delta);
                        y.dragMove(e.y.delta);
                        e.preventDefault();
                    } else {
                        e.touch.skip();
                    }
                },

                end: function(e) {
                    e.preventDefault();
                }
            });
        }
    });

    var TRANSFORM_STYLE = support.transitions.prefix + "Transform",
        translate;

    if (support.hasHW3D) {
        translate = function(x, y, scale) {
            return "translate3d(" + x + "px," + y +"px,0) scale(" + scale + ")";
        };
    } else {
        translate = function(x, y, scale) {
            return "translate(" + x + "px," + y +"px) scale(" + scale + ")";
        };
    }

    var Movable = Observable.extend({
        init: function(element) {
            var that = this;

            Observable.fn.init.call(that);

            that.element = $(element);
            that.element[0].style.webkitTransformOrigin = "left top";
            that.x = 0;
            that.y = 0;
            that.scale = 1;
            that._saveCoordinates(translate(that.x, that.y, that.scale));
        },

        translateAxis: function(axis, by) {
            this[axis] += by;
            this.refresh();
        },

        scaleTo: function(scale) {
            this.scale = scale;
            this.refresh();
        },

        scaleWith: function(scaleDelta) {
            this.scale *= scaleDelta;
            this.refresh();
        },

        translate: function(coordinates) {
            this.x += coordinates.x;
            this.y += coordinates.y;
            this.refresh();
        },

        moveAxis: function(axis, value) {
            this[axis] = value;
            this.refresh();
        },

        moveTo: function(coordinates) {
            extend(this, coordinates);
            this.refresh();
        },

        refresh: function() {
            var that = this,
                x = that.x,
                y = that.y,
                newCoordinates;

            if (that.round) {
                x = Math.round(x);
                y = Math.round(y);
            }

            newCoordinates = translate(x, y, that.scale);

            if (newCoordinates != that.coordinates) {
                if (kendo.support.browser.msie && kendo.support.browser.version < 10) {
                    that.element[0].style.position = "absolute";
                    that.element[0].style.left = that.x + "px";
                    that.element[0].style.top = that.y + "px";

                } else {
                    that.element[0].style[TRANSFORM_STYLE] = newCoordinates;
                }
                that._saveCoordinates(newCoordinates);
                that.trigger(CHANGE);
            }
        },

        _saveCoordinates: function(coordinates) {
            this.coordinates = coordinates;
        }
    });

    var DropTarget = Widget.extend({
        init: function(element, options) {
            var that = this;

            Widget.fn.init.call(that, element, options);

            var group = that.options.group;

            if (!(group in dropTargets)) {
                dropTargets[group] = [ that ];
            } else {
                dropTargets[group].push( that );
            }
        },

        events: [
            DRAGENTER,
            DRAGLEAVE,
            DROP
        ],

        options: {
            name: "DropTarget",
            group: "default"
        },

        destroy: function() {
            var groupName = this.options.group,
                group = dropTargets[groupName] || dropAreas[groupName],
                i;

            if (group.length > 1) {
                Widget.fn.destroy.call(this);

                for (i = 0; i < group.length; i++) {
                    if (group[i] == this) {
                        group.splice(i, 1);
                        break;
                    }
                }
            } else {
                DropTarget.destroyGroup(groupName);
            }
        },

        _trigger: function(eventName, e) {
            var that = this,
                draggable = draggables[that.options.group];

            if (draggable) {
                return that.trigger(eventName, extend({}, e.event, {
                           draggable: draggable,
                           dropTarget: e.dropTarget
                       }));
            }
        },

        _over: function(e) {
            this._trigger(DRAGENTER, e);
        },

        _out: function(e) {
            this._trigger(DRAGLEAVE, e);
        },

        _drop: function(e) {
            var that = this,
                draggable = draggables[that.options.group];

            if (draggable) {
                draggable.dropped = !that._trigger(DROP, e);
            }
        }
    });

    DropTarget.destroyGroup = function(groupName) {
        var group = dropTargets[groupName] || dropAreas[groupName],
            i;

        if (group) {
            for (i = 0; i < group.length; i++) {
                Widget.fn.destroy.call(group[i]);
            }

            group.length = 0;
            delete dropTargets[groupName];
            delete dropAreas[groupName];
        }
    };

    DropTarget._cache = dropTargets;

    var DropTargetArea = DropTarget.extend({
        init: function(element, options) {
            var that = this;

            Widget.fn.init.call(that, element, options);

            var group = that.options.group;

            if (!(group in dropAreas)) {
                dropAreas[group] = [ that ];
            } else {
                dropAreas[group].push( that );
            }
        },

        options: {
            name: "DropTargetArea",
            group: "default",
            filter: null
        }
    });

    var Draggable = Widget.extend({
        init: function (element, options) {
            var that = this;

            Widget.fn.init.call(that, element, options);

            that._activated = false;

            that.userEvents = new UserEvents(that.element, {
                global: true,
                allowSelection: true,
                filter: that.options.filter,
                threshold: that.options.distance,
                start: proxy(that._start, that),
                hold: proxy(that._hold, that),
                move: proxy(that._drag, that),
                end: proxy(that._end, that),
                cancel: proxy(that._cancel, that),
                select: proxy(that._select, that)
            });

            that._afterEndHandler = proxy(that._afterEnd, that);
            that._captureEscape = proxy(that._captureEscape, that);
        },

        events: [
            HOLD,
            DRAGSTART,
            DRAG,
            DRAGEND,
            DRAGCANCEL
        ],

        options: {
            name: "Draggable",
            distance: 5,
            group: "default",
            cursorOffset: null,
            axis: null,
            container: null,
            filter: null,
            ignore: null,
            holdToDrag: false,
            dropped: false
        },

        cancelHold: function() {
            this._activated = false;
        },

        _captureEscape: function(e) {
            var that = this;

            if (e.keyCode === kendo.keys.ESC) {
                that._trigger(DRAGCANCEL, { event: e });
                that.userEvents.cancel();
            }
        },

        _updateHint: function(e) {
            var that = this,
                coordinates,
                options = that.options,
                boundaries = that.boundaries,
                axis = options.axis,
                cursorOffset = that.options.cursorOffset;

            if (cursorOffset) {
               coordinates = { left: e.x.location + cursorOffset.left, top: e.y.location + cursorOffset.top };
            } else {
               that.hintOffset.left += e.x.delta;
               that.hintOffset.top += e.y.delta;
               coordinates = $.extend({}, that.hintOffset);
            }

            if (boundaries) {
                coordinates.top = within(coordinates.top, boundaries.y);
                coordinates.left = within(coordinates.left, boundaries.x);
            }

            if (axis === "x") {
                delete coordinates.top;
            } else if (axis === "y") {
                delete coordinates.left;
            }

            that.hint.css(coordinates);
        },

        _shouldIgnoreTarget: function(target) {
            var ignoreSelector = this.options.ignore;
            return ignoreSelector && $(target).is(ignoreSelector);
        },

        _select: function(e) {
            if (!this._shouldIgnoreTarget(e.event.target)) {
                e.preventDefault();
            }
        },

        _start: function(e) {
            var that = this,
                options = that.options,
                container = options.container,
                hint = options.hint;

            if (this._shouldIgnoreTarget(e.touch.initialTouch) || (options.holdToDrag && !that._activated)) {
                that.userEvents.cancel();
                return;
            }

            that.currentTarget = e.target;
            that.currentTargetOffset = getOffset(that.currentTarget);

            if (hint) {
                if (that.hint) {
                    that.hint.stop(true, true).remove();
                }

                that.hint = kendo.isFunction(hint) ? $(hint.call(that, that.currentTarget)) : hint;

                var offset = getOffset(that.currentTarget);
                that.hintOffset = offset;

                that.hint.css( {
                    position: "absolute",
                    zIndex: 20000, // the Window's z-index is 10000 and can be raised because of z-stacking
                    left: offset.left,
                    top: offset.top
                })
                .appendTo(document.body);

                that.angular("compile", function(){
                    that.hint.removeAttr("ng-repeat");
                    return {
                        elements: that.hint.get(),
                        scopeFrom: e.target
                    };
                });
            }

            draggables[options.group] = that;

            that.dropped = false;

            if (container) {
                that.boundaries = containerBoundaries(container, that.hint);
            }

            if (that._trigger(DRAGSTART, e)) {
                that.userEvents.cancel();
                that._afterEnd();
            }

            $(document).on(KEYUP, that._captureEscape);
        },

        _hold: function(e) {
            this.currentTarget = e.target;

            if (this._trigger(HOLD, e)) {
                this.userEvents.cancel();
            } else {
                this._activated = true;
            }
        },

        _drag: function(e) {
            var that = this;

            e.preventDefault();

            that._withDropTarget(e, function(target, targetElement) {
                if (!target) {
                    if (lastDropTarget) {
                        lastDropTarget._trigger(DRAGLEAVE, extend(e, { dropTarget: $(lastDropTarget.targetElement) }));
                        lastDropTarget = null;
                    }
                    return;
                }

                if (lastDropTarget) {
                    if (targetElement === lastDropTarget.targetElement) {
                        return;
                    }

                    lastDropTarget._trigger(DRAGLEAVE, extend(e, { dropTarget: $(lastDropTarget.targetElement) }));
                }

                target._trigger(DRAGENTER, extend(e, { dropTarget: $(targetElement) }));
                lastDropTarget = extend(target, { targetElement: targetElement });
            });

            that._trigger(DRAG, extend(e, { dropTarget: lastDropTarget }));

            if (that.hint) {
                that._updateHint(e);
            }
        },

        _end: function(e) {
            var that = this;

            that._withDropTarget(e, function(target, targetElement) {
                if (target) {
                    target._drop(extend({}, e, { dropTarget: $(targetElement) }));
                    lastDropTarget = null;
                }
            });

            that._trigger(DRAGEND, e);
            that._cancel(e.event);
        },

        _cancel: function() {
            var that = this;

            that._activated = false;

            if (that.hint && !that.dropped) {
                setTimeout(function() {
                    that.hint.stop(true, true).animate(that.currentTargetOffset, "fast", that._afterEndHandler);
                }, 0);

            } else {
                that._afterEnd();
            }
        },

        _trigger: function(eventName, e) {
            var that = this;

            return that.trigger(
                eventName, extend(
                {},
                e.event,
                {
                    x: e.x,
                    y: e.y,
                    currentTarget: that.currentTarget,
                    dropTarget: e.dropTarget
                }
            ));
        },

        _withDropTarget: function(e, callback) {
            var that = this,
                target, result,
                options = that.options,
                targets = dropTargets[options.group],
                areas = dropAreas[options.group];

            if (targets && targets.length || areas && areas.length) {

                target = elementUnderCursor(e);

                if (that.hint && contains(that.hint[0], target)) {
                    that.hint.hide();
                    target = elementUnderCursor(e);
                    // IE8 does not return the element in iframe from first attempt
                    if (!target) {
                        target = elementUnderCursor(e);
                    }
                    that.hint.show();
                }

                result = checkTarget(target, targets, areas);

                if (result) {
                    callback(result.target, result.targetElement);
                } else {
                    callback();
                }
            }
        },

        destroy: function() {
            var that = this;

            Widget.fn.destroy.call(that);

            that._afterEnd();

            that.userEvents.destroy();

            that.currentTarget = null;
        },

        _afterEnd: function() {
            var that = this;

            if (that.hint) {
                that.hint.remove();
            }

            delete draggables[that.options.group];

            that.trigger("destroy");
            $(document).off(KEYUP, that._captureEscape);
        }
    });

    kendo.ui.plugin(DropTarget);
    kendo.ui.plugin(DropTargetArea);
    kendo.ui.plugin(Draggable);
    kendo.TapCapture = TapCapture;
    kendo.containerBoundaries = containerBoundaries;

    extend(kendo.ui, {
        Pane: Pane,
        PaneDimensions: PaneDimensions,
        Movable: Movable
    });

 })(window.kendo.jQuery);

return window.kendo;

}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });


text:
package net.violet.platform.datamodel;

import java.sql.SQLException;
import java.util.List;

import net.violet.db.records.ObjectRecord;
import net.violet.db.records.SQLKey;
import net.violet.db.records.SQLObjectSpecification;
import net.violet.db.records.associations.SingleAssociationNotNull;
import net.violet.platform.datamodel.factories.Factories;

public class TtsVoiceImpl extends ObjectRecord<TtsVoice, TtsVoiceImpl> implements TtsVoice {

	public static final SQLObjectSpecification<TtsVoiceImpl> SPECIFICATION = new SQLObjectSpecification<TtsVoiceImpl>("ttsvoice", TtsVoiceImpl.class, new SQLKey("ttsvoice_id"));

	private final SingleAssociationNotNull<TtsVoice, Lang, LangImpl> mLang;

	protected TtsVoiceImpl(long id) throws SQLException {
		init(id);
		this.mLang = new SingleAssociationNotNull<TtsVoice, Lang, LangImpl>(this, "ttsvoice_lang", LangImpl.SPECIFICATION);
	}

	protected TtsVoiceImpl() {
		this.mLang = new SingleAssociationNotNull<TtsVoice, Lang, LangImpl>(this, "ttsvoice_lang", LangImpl.SPECIFICATION);
	}

	protected long ttsvoice_id;
	protected String ttsvoice_libelle;
	protected long ttsvoice_lang;
	protected String ttsvoice_command;
	protected String ttsvoice_str;
	protected int ttsvoice_flags;

	@Override
	public Long getId() {
		return getTtsvoice_id();
	}

	@Override
	public SQLObjectSpecification<TtsVoiceImpl> getSpecification() {
		return TtsVoiceImpl.SPECIFICATION;
	}

	public final long getTtsvoice_id() {
		return this.ttsvoice_id;
	}

	public final String getTtsvoice_libelle() {
		return this.ttsvoice_libelle;
	}

	public final long getTtsvoice_lang() {
		return this.ttsvoice_lang;
	}

	public final String getTtsvoice_command() {
		return this.ttsvoice_command;
	}

	public final String getTtsvoice_str() {
		return this.ttsvoice_str;
	}

	public final boolean isDefault() {
		return (this.ttsvoice_flags & TtsVoice.FLAG_DEFAULT) != 0;
	}

	/**
	 * récupère les options d'une voix de tts par son nom (ttsvoice_str)
	 *
	 * @param inName : ex => Claire
	 * @return l'enregistrement (ou null).
	 */
	public static TtsVoice findByName(String inName) {
		return TtsVoice.ALL_VOICES_BY_STR.get(inName);
	}

	/**
	 * récupère les options d'une voix de tts par sa commande (ttsvoice_command)
	 *
	 * @param inCommand : ex => Claire22s
	 * @return l'enregistrement (ou null).
	 */
	public static TtsVoice findByCommand(String inCommand) {
		return TtsVoice.ALL_VOICES_BY_COMMAND.get(inCommand);
	}

	/**
	 * récupère les options d'une voix de tts par sa commande ou par nom
	 * (ttsvoice_command, ttsvoice_str) Si enregitrement null alors retourne
	 * l'enregistrement par défaut ( 0 = laura22k)
	 *
	 * @param inValue : ex => Claire22s ou Claire
	 * @param defaultLang : la langue du user par défaut
	 * @return l'enregistrement (ou null).
	 */
	public static TtsVoice findByCommandOrName(String inValue, long defaultLang) {
		TtsVoice theResult;
		theResult = TtsVoiceImpl.findByName(inValue);
		if (theResult == null) {
			theResult = TtsVoiceImpl.findByCommand(inValue);
		}
		if (theResult == null) {
			theResult = Factories.TTSVOICE.findByLang(defaultLang);
		}
		return theResult;
	}

	/**
	 * récupère les différentes voix proposé par le tts
	 *
	 * @return les enregistrements.
	 */
	public static List<TtsVoice> getAllVoices() {
		return TtsVoice.ALL_VOICES;
	}

	public Lang getLang() {
		return this.mLang.get(this.ttsvoice_lang);
	}

}


text:
<?php
namespace Admin\Controller;

use Think\Controller;

class PublicController extends Controller
{

}


text:
package org.apache.tinkerpop.gremlin.process.traversal.step.map;

import org.apache.tinkerpop.gremlin.process.computer.KeyValue;
import org.apache.tinkerpop.gremlin.process.computer.MapReduce;
import org.apache.tinkerpop.gremlin.process.computer.traversal.TraversalVertexProgram;
import org.apache.tinkerpop.gremlin.process.computer.util.StaticMapReduce;
import org.apache.tinkerpop.gremlin.process.traversal.Traversal;
import org.apache.tinkerpop.gremlin.process.traversal.Traverser;
import org.apache.tinkerpop.gremlin.process.traversal.step.MapReducer;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement;
import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.TraverserSet;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.util.function.ConstantSupplier;

import java.io.Serializable;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.Set;
import java.util.function.BiFunction;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public final class CountGlobalStep<S> extends ReducingBarrierStep<S, Long> implements MapReducer {

    private static final Set<TraverserRequirement> REQUIREMENTS = EnumSet.of(TraverserRequirement.BULK);

    public CountGlobalStep(final Traversal.Admin traversal) {
        super(traversal);
        this.setSeedSupplier(new ConstantSupplier<>(0L));
        this.setBiFunction(CountBiFunction.<S>instance());
    }

    @Override
    public Set<TraverserRequirement> getRequirements() {
        return REQUIREMENTS;
    }

    @Override
    public MapReduce<MapReduce.NullObject, Long, MapReduce.NullObject, Long, Long> getMapReduce() {
        return CountGlobalMapReduce.instance();
    }

    ///////////

    private static class CountBiFunction<S> implements BiFunction<Long, Traverser<S>, Long>, Serializable {

        private static final CountBiFunction INSTANCE = new CountBiFunction();

        private CountBiFunction() {

        }

        @Override
        public Long apply(final Long mutatingSeed, final Traverser<S> traverser) {
            return mutatingSeed + traverser.bulk();
        }

        public final static <S> CountBiFunction<S> instance() {
            return INSTANCE;
        }
    }

    ///////////

    private static class CountGlobalMapReduce extends StaticMapReduce<MapReduce.NullObject, Long, MapReduce.NullObject, Long, Long> {

        private static CountGlobalMapReduce INSTANCE = new CountGlobalMapReduce();

        private CountGlobalMapReduce() {

        }

        @Override
        public boolean doStage(final MapReduce.Stage stage) {
            return true;
        }

        @Override
        public void map(final Vertex vertex, final MapEmitter<NullObject, Long> emitter) {
            vertex.<TraverserSet<?>>property(TraversalVertexProgram.HALTED_TRAVERSERS).ifPresent(traverserSet -> traverserSet.forEach(traverser -> emitter.emit(traverser.bulk())));
        }

        @Override
        public void combine(final NullObject key, final Iterator<Long> values, final ReduceEmitter<NullObject, Long> emitter) {
            this.reduce(key, values, emitter);
        }

        @Override
        public void reduce(final NullObject key, final Iterator<Long> values, final ReduceEmitter<NullObject, Long> emitter) {
            long count = 0l;
            while (values.hasNext()) {
                count = count + values.next();
            }
            emitter.emit(count);
        }

        @Override
        public String getMemoryKey() {
            return REDUCING;
        }

        @Override
        public Long generateFinalResult(final Iterator<KeyValue<NullObject, Long>> keyValues) {
            return keyValues.hasNext() ? keyValues.next().getValue() : 0L;
        }

        public static final CountGlobalMapReduce instance() {
            return INSTANCE;
        }

    }

}


text:
#ifndef ZOO_LEADER_H_
#define ZOO_LEADER_H_

#include <nan.h>
#include <v8.h>
#include <zookeeper.h>

#include <map>

#include "topology_watcher.h"

typedef enum {
  LOG_LEVEL_FATAL,
  LOG_LEVEL_ERROR,
  LOG_LEVEL_WARN,
  LOG_LEVEL_INFO,
  LOG_LEVEL_DEBUG,
  LOG_LEVEL_TRACE
} LogLevel;

#define log_fatal(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_FATAL) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_FATAL, __FILE__, __LINE__, __func__, __VA_ARGS__)
#define log_error(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_ERROR) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_ERROR, __FILE__, __LINE__, __func__, __VA_ARGS__)
#define log_warn(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_WARN) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_WARN, __FILE__, __LINE__, __func__, __VA_ARGS__)
#define log_info(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_INFO) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_INFO, __FILE__, __LINE__, __func__, __VA_ARGS__)
#define log_debug(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_DEBUG) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_DEBUG, __FILE__, __LINE__, __func__, __VA_ARGS__)
#define log_trace(zoo_leader, ...) if (zoo_leader->log_level() >= LOG_LEVEL_TRACE) \
  zoo_leader->ZooLogFormat(LOG_LEVEL_TRACE, __FILE__, __LINE__, __func__, __VA_ARGS__)

typedef std::map<const char*, TopologyWatcher*, TopologyNameComparator> TopologyWatcherMap;
typedef std::map<const char*, TopologyWatcher*, TopologyNameComparator>::iterator TopologyWatcherIt;

class ZooLeader : public Nan::ObjectWrap {
 public:
  static NAN_MODULE_INIT(Init);

  void ZooLogFormat(LogLevel log_level, const char* filename, int line,
      const char* function_name, const char* format, ...);

  void ZooEmitEvent(const char* event, const char* value);
  void ChannelEmitTopology(const char* channel, char** topology, int topology_size);
  void ChannelEmitZNode(const char* channel, const char* znode);
  void ChannelEmitError(const char* channel, const char* error);
  void ZooEmitError(const char* message);

  /*
   * Wrappers for ZooKeeper functions.
   */
  int ZkState();

  int ZkGetChildren(const char* path, watcher_fn watcher, void* watcherContext,
      strings_completion_t cb, void* completionContext);

  int ZkCreate(const char* path, const char* value, int value_len, int flags,
      string_completion_t cb, void* completionContext);

  inline LogLevel log_level() const {
    return log_level_;
  }

 private:
  explicit ZooLeader(
      int session_timeout,
      char* quorum,
      LogLevel log_level);
  virtual ~ZooLeader();

  zhandle_t* ZooInit();
  void ZooClose();
  void ZooInterest();
  inline void ZooEnsureInterest() {
    // Should be called after any ZooKeeper operation to ensure that we register
    // an I/O callback for a write event in case the ZooKeeper operation was
    // initially blocked on a `send()`.
    this->ZooInterest();
  }

  void AddTopologyWatcher(TopologyWatcher* topology_watcher);
  void ZooLog(const char* message, LogLevel level);
  char* BuildChannelEventName(const char* channel, const char* event);

  static NAN_METHOD(New);
  static NAN_METHOD(Connect);
  static NAN_METHOD(RegisterTopologyWatcher);
  static NAN_METHOD(RemoveTopologyWatcher);
  static NAN_METHOD(Close);
  static NAN_METHOD(GetTopologyWatcherState);
  static NAN_METHOD(GetTopologyWatcherZNode);
  static NAN_METHOD(GetClientSessionId);
  static NAN_METHOD(SetLogLevel);

  static void ZkLogCb(const char* message, int log_level, void* context);
  static const char* ZkStateStr(int state);
  static void ZkWatcher(zhandle_t* zh, int type, int state, const char* path,
      void* context);
  static void ZkIoCb(uv_poll_t* zk_poll_handle, int status, int events);
#if (NODE_MODULE_VERSION > 0x000B)
  static void ZkTimerCb(uv_timer_t* zk_timer_handle);
#else
  static void ZkTimerCb(uv_timer_t* zk_timer_handle, int status);
#endif

  static Nan::Persistent<v8::Function> constructor;

  zhandle_t* zh_;
  int session_timeout_;
  char* quorum_;
  LogLevel log_level_;
  uv_poll_t zk_poll_handle_;
  uv_timer_t zk_timer_handle_;
  TopologyWatcherMap topology_watchers_;
};

#endif  // ZOO_LEADER_H_


text:
"""As an optional feature, we can try to keep track of the assets used. This
makes it easier to run a manual rebuild.

In the future, it can also help deciding when an asset needs an automatic
update. For instance:
    - We might auto update when the hash changes, wheras the old hash to
      compare against will be stored by the tracker.
    - We might use the tracked assets to compare timestamps if that turns
      out to be faster than a stat() call.
    - Right now, if asset properties like the applied filters or the list
      of source files change, without causing the source timestamp to
      change, the update will not be automatically picked up. As those
      information could be tracked and then be used to detect changes.
"""

from conf import settings

def get_tracker(name=None):
    """Return a callable(output, sources) that returns True if the file
    ``output``, based on the files in the list ``sources`` needs to be
    recreated.

    See the ``TRACK_ASSETS`` setting for more information.
    """
    if not name:
        name = settings.TRACK_ASSETS

    try:
        return {
            None: None,
            False: None,
            "model": track_via_model,
            "cache": track_via_cache,
            }[name]
    except KeyError:
        raise ValueError('Tracking option "%s" is not valid.' % name)

def track_via_model(sourcefiles, outputfile, filter_name):
    raise NotImplementedError()
    """touched_time = current_ts()
    asset, created = Asset.objects.get_or_create(outputfile,
                    [sourcefiles, filter_name, touched_time])
    if not created:
        asset.sourcefiles = sourcefiles
        asset.filter_name = filter_name
        asset.touched_mtime = touched_time
        asset.save()"""

def track_via_cache(sourcefiles, outputfile, filter_name):
    raise NotImplementedError()


text:
set -ex

retry() {
    "$@" ||
        (sleep 2 && "$@") ||
        (sleep 5 && "$@");
}

[[ $# -eq 10 ]] || (echo "./deploy.sh HAIL_PIP_VERSION HAIL_VERSION GIT_VERSION REMOTE WHEEL GITHUB_OAUTH_HEADER_FILE HAIL_GENETICS_HAIL_IMAGE HAIL_GENETICS_HAILTOP_IMAGE WHEEL_FOR_AZURE WEBSITE_TAR" ; exit 1)

HAIL_PIP_VERSION=$1
HAIL_VERSION=$2
GIT_VERSION=$3
REMOTE=$4
WHEEL=$5
GITHUB_OAUTH_HEADER_FILE=$6
HAIL_GENETICS_HAIL_IMAGE=$7
HAIL_GENETICS_HAILTOP_IMAGE=$8
WHEEL_FOR_AZURE=$9
WEBSITE_TAR=${10}

retry skopeo inspect $HAIL_GENETICS_HAIL_IMAGE || (echo "could not pull $HAIL_GENETICS_HAIL_IMAGE" ; exit 1)
retry skopeo inspect $HAIL_GENETICS_HAILTOP_IMAGE || (echo "could not pull $HAIL_GENETICS_HAILTOP_IMAGE" ; exit 1)

if git ls-remote --exit-code --tags $REMOTE $HAIL_PIP_VERSION
then
    echo "tag $HAIL_PIP_VERSION already exists"
    exit 0
fi

if [ ! -f $WHEEL ]
then
    echo "wheel not found at $WHEEL"
    exit 1
fi

pip_versions_file=$(mktemp)
pip install hail== 2>&1 \
    | head -n 1 \
    | sed 's/.*versions: //' \
    | sed 's/)//' \
    | sed 's/ //g' \
    | tr ',' '\n' \
         > $pip_versions_file

if grep -q -e $HAIL_PIP_VERSION $pip_versions_file
then
    echo "package $HAIL_PIP_VERSION already exists"
    exit 1
fi

if curl -sf https://api.github.com/repos/hail-is/hail/releases/tags/$HAIL_PIP_VERSION >/dev/null
then
    echo "release $HAIL_PIP_VERSION already exists"
    exit 1
fi

# push git tag
git tag $HAIL_PIP_VERSION -m "Hail version $HAIL_PIP_VERSION."
git push origin $HAIL_PIP_VERSION

# make GitHub release
curl -XPOST -H @$GITHUB_OAUTH_HEADER_FILE https://api.github.com/repos/hail-is/hail/releases -d '{
  "tag_name": "'$HAIL_PIP_VERSION'",
  "target_commitish": "main",
  "name": "'$HAIL_PIP_VERSION'",
  "body": "Hail version '$HAIL_PIP_VERSION'\n\n[Change log](https://hail.is/docs/0.2/change_log.html#version-'${HAIL_PIP_VERSION//[\.]/-}')",
  "draft": false,
  "prerelease": false
}'

retry skopeo copy $HAIL_GENETICS_HAIL_IMAGE docker://docker.io/hailgenetics/hail:$HAIL_PIP_VERSION
retry skopeo copy $HAIL_GENETICS_HAIL_IMAGE docker://us-docker.pkg.dev/hail-vdc/hail/hailgenetics/hail:$HAIL_PIP_VERSION
retry skopeo copy $HAIL_GENETICS_HAILTOP_IMAGE docker://docker.io/hailgenetics/hailtop:$HAIL_PIP_VERSION
retry skopeo copy $HAIL_GENETICS_HAILTOP_IMAGE docker://us-docker.pkg.dev/hail-vdc/hail/hailgenetics/hailtop:$HAIL_PIP_VERSION

# deploy to PyPI
twine upload $WHEEL

# deploy wheel for Azure HDInsight
wheel_for_azure_url=gs://hail-common/azure-hdinsight-wheels/$(basename $WHEEL_FOR_AZURE)
gsutil cp $WHEEL_FOR_AZURE $wheel_for_azure_url
gsutil -m retention temp set $wheel_for_azure_url

# update docs sha
cloud_sha_location=gs://hail-common/builds/0.2/latest-hash/cloudtools-5-spark-2.4.0.txt
printf "$GIT_VERSION" | gsutil cp  - $cloud_sha_location
gsutil acl set public-read $cloud_sha_location

# deploy datasets (annotation db) json
datasets_json_url=gs://hail-common/annotationdb/$HAIL_VERSION/datasets.json
gsutil cp python/hail/experimental/datasets.json $datasets_json_url
gsutil -m retention temp set $datasets_json_url

# Publish website
website_url=gs://hail-common/website/$HAIL_PIP_VERSION/www.tar.gz
gsutil cp $WEBSITE_TAR $website_url
gsutil -m retention temp set $website_url

# Create pull request to update Terra and AoU Hail versions
terra_docker_dir=$(mktemp -d)
update_terra_image_py="$(cd "$(dirname "$0")" && pwd)/update-terra-image.py"
git clone https://github.com/DataBiosphere/terra-docker $terra_docker_dir
pushd $terra_docker_dir
git config user.name hail
git config user.email hail@broadinstitute.org

make_pr_for() {
    branch_name=update-$1-to-hail-$HAIL_PIP_VERSION
    git checkout -B $branch_name
    python3 $update_terra_image_py $HAIL_PIP_VERSION $1
    git commit -m "Update $1 to Hail version $HAIL_PIP_VERSION" -- config/conf.json $1
    git push -f origin HEAD
    echo "{
  \"head\": \"$branch_name\",
  \"base\": \"master\",
  \"title\": \"Update $1 to Hail $HAIL_PIP_VERSION\"
}"
    curl -XPOST -H @$GITHUB_OAUTH_HEADER_FILE https://api.github.com/repos/DataBiosphere/terra-docker/pulls -d "{
  \"head\": \"$branch_name\",
  \"base\": \"master\",
  \"title\": \"Update $1 to Hail $HAIL_PIP_VERSION\"
}"
    git reset --hard HEAD
    git checkout master
}

make_pr_for terra-jupyter-hail
make_pr_for terra-jupyter-aou


text:
from .schemas import ZohoResponse

from xml.etree.ElementTree import Element, tostring

import requests

class ZohoException(Exception):
    pass

class Properties(object):

    # Set properties
    @property
    def user(self):
        try:
            return self._user
        except AttributeError:
            self._user = None
            return self._user

    @user.setter
    def user(self, value):
        self._user = value

    @property
    def password(self):
        try:
            return self._password
        except AttributeError:
            self._password = None
            return self._password

    @password.setter
    def password(self, value):
        self._password = value

    @property
    def scope(self):
        try:
            return self._scope
        except AttributeError:
            self._scope = "ZohoCRM/crmapi"
            return self._scope

    @scope.setter
    def scope(self, value):
        self._scope = value

    @property
    def app_name(self):
        try:
            return self._app_name
        except AttributeError:
            self._app_name = None
            return self._app_name

    @app_name.setter
    def app_name(self, value):
        self._app_name = value

    @property
    def authToken(self):
        try:
            return self._authToken
        except AttributeError:
            self._authToken = None
            return self._authToken

    @authToken.setter
    def authToken(self, value):
        self._authToken = value

    @property
    def module(self):
        try:
            return self._module
        except AttributeError:
            self._module = None
            return self._module

    @module.setter
    def module(self, value):
        self._module = value

class Connection(Properties):

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

        self.tokenURL = "https://accounts.zoho.com/apiauthtoken/nb/create?SCOPE={scope}&EMAIL_ID={user}&PASSWORD={password}&DISPLAY_NAME={app_name}"
        self.url = "https://crm.zoho.com/crm/private/json/{module}/{action}?{params}"

        super(Connection, self).__init__()

    def _valid_mandatory_fields(self, authToken=None, scope=None, module=None):

        if authToken is not None:
            self.authToken = authToken
        elif authToken is None and self.authToken is None:
            raise ZohoException("You have to assing an authToken")

        if scope is not None:
            self.scope = scope
        elif scope is None and self.scope is None:
            raise ZohoException("You have to assing a scope")

        if module is not None:
            self.module = module
        elif module is None and self.module is None:
            raise ZohoException("You have to assing a module")

    def _valid_data_login(self):
        if self.user is None:
            raise AttributeError("You need to set a Username/EmailID")
        elif self.password is None:
            raise AttributeError("You need to set a Password")
        elif self.app_name is None:
            raise AttributeError("You need to set an ApplicationName")

    def _options_to_params(self, authToken=None, scope=None, xml=[], options={}):
        params_string = "authtoken={}&scope={}&".format(authToken, scope)

        for k, v in options.items():

            if type(v) is list:
                params_string += "{}={}(".format(k, self.module)
                for i in v:
                    params_string += i
                params_string = params_string[:-1]
                params_string += ")&"

            else:
                params_string += "{}={}&".format(k, v)

        if xml:
            params_string += "xmlData={}".format(xml)
        else:
            params_string = params_string[:-1]

        return params_string

    def _getPost(self, module=None, xml=None, action=None, options={}):
        params = self._options_to_params(
            authToken=self.authToken,
            scope=self.scope, options=options)

        url = self.url.format(module=module, action=action, params=params)

        response_json = requests.post(url, data={'xmlData': xml}).json()

        return ZohoResponse(many=False).load(response_json.get('response')).data

    def createAuthToken(self):
        try:
            self._valid_data_login()
        except AttributeError as e:
            raise e
        else:
            url = self.tokenURL.format(
                scope=self.scope,
                user=self.user,
                password=self.password,
                app_name=self.app_name)

            zoho_response = requests.get(url)

            zoho_authToken = [z for z in zoho_response.text.split("\n") if "AUTHTOKEN" in z]
            zoho_authToken = zoho_authToken[0].replace("AUTHTOKEN=", "")

            if "CAUSE" in zoho_authToken:
                raise ZohoException("Exceeded Maximum Allowed AuthTokens")
            self.authToken = zoho_authToken
        return zoho_authToken

    def prepare_xml(self, module, leads):
        root = Element(module)
        for i, lead in enumerate(leads):
            row = Element("row", no=str(i + 1))
            if type(lead) == dict:
                for key, value in lead.items():
                    fl = Element("FL", val=key)
                    if type(value) == str:
                        if value.isdigit():
                            fl.text = int(value)
                        else:
                            fl.text = value
                    else:
                        fl.text = value
                    row.append(fl)
            root.append(row)

        # response = tostring(root, encoding='UTF-8').replace('\n', '').replace('\r', '')
        response = tostring(root, encoding='UTF-8')

        return response


text:
import $ from 'jquery';
import axios from '~/lib/utils/axios_utils';

describe('Mock auto-injection', () => {
  describe('mocks', () => {
    let failMock;
    beforeEach(() => {
      failMock = jest.spyOn(global, 'fail').mockImplementation();
    });

    it('~/lib/utils/axios_utils', () => {
      return Promise.all([
        expect(axios.get('http://gitlab.com')).rejects.toThrow('Unexpected unmocked request'),
        setImmediate(() => {
          expect(failMock).toHaveBeenCalledTimes(1);
        }),
      ]);
    });

    it('jQuery.ajax()', () => {
      expect($.ajax).toThrow('Unexpected unmocked');
      expect(failMock).toHaveBeenCalledTimes(1);
    });
  });
});