text:
'use strict';

angular.module('NeoLearning.student', ['oitozero.ngSweetAlert'])
.controller('StudentCtrl', ['$scope', '$state', '$stateParams', '$location', '$window', '$filter', 'UserService', 'CourseService', 'SweetAlert', function($scope, $state, $stateParams, $location, $window, $filter, UserService, CourseService, SweetAlert) {
  $scope.itemsByPage=7;
  $scope.validRole=false;

  $scope.studentId = $stateParams.id;

  UserService.api('user/'+ $scope.studentId).get().$promise
  .then(function(result){
     if(result.success){
       $scope.userSelected= result.data;
     }else{
       //ERROR
     }
   })
   UserService.api('user/'+ $scope.studentId +'/course').get().$promise
   .then(function(result){
      if(result.success){
         console.log('resultSudent', result);
        $scope.userSelectedCourse= result.data.studentCourses;
        $scope.rowCourses = result.data.studentCourses;
      }else{
        //ERROR
      }
    })

  // GET USER INFO
  var user = UserService.getUser($window.sessionStorage.token);
  if(user){
      $scope.userName = user.firstName;
  }

  var userRoleListRequest = UserService.api('role').get();
  userRoleListRequest.$promise.then(function(result){
    if(result.success){
      $scope.userRoleList = result.data;
    }
  })

  $scope.format = 'd!/M!/yyyy';
  $scope.altInputFormats = ['M!/d!/yyyy'];

  $scope.popup1 = {
    opened: false
  };

  $scope.open1 = function() {
    $scope.popup1.opened = true;
  };

  $scope.displayedUsers = [];
  var usersRequest = UserService.api('user').get();
  usersRequest.$promise.then(function(result){
    if(result.success){
      $scope.displayedUsers = result.data;
      $scope.rowUsers = result.data;
    }else{
      //ERROR
    }
  })

  $scope.checkFormInput = function(){
    $scope.submitted = true;
    if (!$scope.userIdRole){
      $scope.invalidRole = true;
      $('#roleListInput').addClass('has-error');
      return;
    }
    $scope.addUser();
  }

  $scope.checkRoleValue = function(){
    if(!!$scope.userIdRole){
      $scope.invalidRole = false;
      $('#roleListInput').removeClass('has-error');
    }
  }

  $scope.addUser = function(){
    var user = {
                firstName: $scope.userFirstName, lastName: $scope.userLastName,
                email: $scope.userEmail, password: $scope.userPassword, city: $scope.userCity,
                phone: $scope.userPhone, address: $scope.userAddress, idRole: $scope.userIdRole.idRole,
                birthdate: $scope.userBirthdate
               }
    console.log('birthdate' , $scope.userBirthdate);
    Object.keys(user).forEach(function(key){
      if(!user[key]) {
        delete user[key];
      }else{
        if(key == "birthdate"){
          new Date(user[key]);
        }
      }
    })

    var userAddRequest = UserService.api('user').post(user);
    userAddRequest.$promise.then(function(result){
      if(result.success){
        $('#newModalUser').modal('hide');
        user.idUser = result.data;
        $scope.displayedUsers.push(user);
        $scope.rowUsers.push(user);
        console.log('addedUser', user);
        SweetAlert.swal("L'utilisateur " + user.firstName + " " + user.lastName + " à été ajouté avec succès !", "", "success");
      }else{
        $('#newModalUser').modal('hide');
        SweetAlert.swal("Une erreur est survenue (" + result.message + ")", "", "error");
      }
      $('#newModalUser').modal('hide');
    })
  }

  $scope.openEditUserModal = function(selectedEditableUser){
    $scope.userFirstName = selectedEditableUser;
    $scope.userIdRole = null;
    $scope.userLastName = null;
    $scope.courseDescription = null;
    $scope.userEmail = null;
    $scope.userPassword = null;
    $scope.userCity = null;
    $scope.userPhone = null;
    $scope.userAddress = null;
    $scope.userBirthdate = null;
    $scope.registeredStudentCount = null;
    $scope.addedStudentsTxt = null;
    console.log(selectedEditableUser);
    if(selectedEditableUser.birthdate){
      selectedEditableUser.birthdate = selectedEditableUser.birthdate.toString().substring(0,10);
    }
    $scope.selectedEditableUser = selectedEditableUser;
    $scope.editableRole = selectedEditableUser.idRole;
    $('#selectedUserBirthdate').val(selectedEditableUser.birthdate);
    setTimeout(function(){$('#editUserRole').val($scope.selectedEditableUser.idRole);}, 1);
    $('#editModalUser').modal('show');
  }

  $scope.editUser = function(){

    var user = {
                firstName: $scope.selectedEditableUser.firstName, lastName: $scope.selectedEditableUser.lastName,
                password: $scope.editedPassword, city: $scope.selectedEditableUser.city,
                phone: $scope.selectedEditableUser.phone, address: $scope.selectedEditableUser.address, idRole: $('#editUserRole').val(),
                birthdate: $scope.selectedEditableUser.birthdate
               }

    Object.keys(user).forEach(function(key){
      if(!user[key]) {
        delete user[key];
      }
    })

    UserService.api('user/' + $scope.selectedEditableUser.idUser ).update(user).
    $promise.then(function(result){
       if(result.success){
         SweetAlert.swal("Utilisateur édité avec succès !", "", "success");
       }
      $('#editModalUser').modal('hide');
    })
  }

  $scope.openNewModalUser = function(){
    $scope.userIdRole = null;
    $scope.userFirstName = null;
    $scope.userLastName = null;
    $scope.courseDescription = null;
    $scope.userEmail = null;
    $scope.userPassword = null;
    $scope.userCity = null;
    $scope.userPhone = null;
    $scope.userAddress = null;
    $scope.userBirthdate = null;
    $scope.registeredStudentCount = null;
    $scope.addedStudentsTxt = null;
    $(".selectable-row").removeClass("st-selected");
    $('#newModalUser').modal('show');
  }

  $scope.removeUser = function(user){
    SweetAlert.swal({
          title: "Êtes-vous sûr de vouloir supprimer l'utilisateur " + user.firstName + " " + user.lastName + "?",
          text: "Il le sera définitivement !",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "Oui, supprimer l'utilisateur!",
          cancelButtonText: "Annuler",
          closeOnConfirm: false,
          closeOnCancel: false
      },
      function(isConfirm){
          if(isConfirm){
            var userDeleteRequest = CourseService.api('user/' + user.idUser).remove();
            userDeleteRequest.$promise.then(function(result){
              if(result.success){
                var index = $scope.rowUsers.indexOf(user);
                  if(index !== -1){
                    $scope.rowUsers.splice(index, 1);
                  }
                  SweetAlert.swal("Utilisateur supprimé !", "", "success");
              }
              else
              {
                SweetAlert.swal("Erreur lors de la suppression!");
              }
            })
          }
           else
          {
              SweetAlert.swal("Utilisateur conservé!");
          }
      });
  }

  $scope.goToStudentDetail = function(user) {
    $state.go("student", { id: user.idUser });
  };
}]);


text: <link type="text/css" rel="stylesheet" href="css/msa.css" />

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.jzb.execution.infrastructure.persistence.lucene;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.lucene.document.*;
import org.apache.lucene.facet.FacetField;
import org.apache.lucene.facet.FacetsConfig;
import org.jzb.execution.domain.Enlist;
import org.jzb.execution.domain.EnlistFeedback;
import org.jzb.execution.domain.operator.Operator;
import org.jzb.execution.domain.repository.EnlistFeedbackRepository;
import org.slf4j.Logger;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.stream.Stream;

import static org.apache.commons.lang3.StringUtils.isBlank;

/**
 * @author jzb
 */
@ApplicationScoped
public class EnlistLucene extends AbstractBaseLucene<Enlist> {

    @Inject
    private Logger log;
    @Inject
    private EnlistFeedbackRepository enlistFeedbackRepository;

    @Override
    protected FacetsConfig _facetsConfig() {
        FacetsConfig result = new FacetsConfig();
        result.setMultiValued("tags", true);
        result.setIndexFieldName("tags", "tags");
        result.setMultiValued("relate_operator", true);
        result.setIndexFieldName("relate_operator", "relate_operator");
        return result;
    }

    @Override
    public Document document(Enlist o) {
        Document doc = new Document();
        doc.add(new StringField("id", o.getId(), Field.Store.YES));

        doc.add(new TextField("title", o.getTitle(), Field.Store.NO));
        if (!isBlank(o.getContent())) {
            doc.add(new TextField("content", o.getContent(), Field.Store.NO));
        }
        doc.add(new LongPoint("start_date", o.getStartDate().getTime()));
        doc.add(new NumericDocValuesField("start_date", o.getStartDate().getTime()));
        doc.add(new LongPoint("end_date", o.getEndDate().getTime()));
        doc.add(new NumericDocValuesField("end_date", o.getEndDate().getTime()));
        doc.add(new StringField("status", o.getStatus().name(), Field.Store.NO));

        doc.add(new LongPoint("create_date", o.getCreateDateTime().getTime()));
        doc.add(new NumericDocValuesField("create_date", o.getCreateDateTime().getTime()));
        doc.add(new LongPoint("modify_date", o.getModifyDateTime().getTime()));
        doc.add(new NumericDocValuesField("modify_date", o.getModifyDateTime().getTime()));

        CollectionUtils.emptyIfNull(o.getTags())
                .parallelStream()
                .flatMap(it -> {
                    final StringField stringField = new StringField("tags", it, Field.Store.YES);
                    final FacetField facetField = new FacetField("tags", it);
                    return Stream.of(stringField, facetField);
                })
                .forEach(doc::add);

        Stream<Operator> operatorStream1 = enlistFeedbackRepository.queryBy(o)
                .map(EnlistFeedback::getCreator);
        Stream<Operator> operatorStream2 = CollectionUtils.emptyIfNull(o.getPaymentMerchant().getManagers()).stream();
        Stream.concat(operatorStream1, operatorStream2)
                .parallel()
                .distinct()
                .flatMap(it -> {
                    final String itId = it.getId();
                    final StringField stringField = new StringField("relate_operator", itId, Field.Store.NO);
                    final FacetField facetField = new FacetField("relate_operator", itId);
                    return Stream.of(stringField, facetField);
                })
                .forEach(doc::add);
        return doc;
    }

}


text:
package au.com.mineauz.minigames.backend.sqlite;

import au.com.mineauz.minigames.backend.BackendImportCallback;
import au.com.mineauz.minigames.backend.ExportNotifier;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Maps;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public class FlatFileExporter {
    private final File file;
    private final FileConfiguration config;
    private final ExportNotifier notifier;
    private final BackendImportCallback callback;

    private SetMultimap<String, UUID> completions;

    private Map<String, Integer> minigameIds;
    private int nextMinigameId;

    private String notifyState;
    private int notifyCount;
    private long notifyTime;

    public FlatFileExporter(File file, BackendImportCallback callback, ExportNotifier notifier) {
        this.file = file;
        this.callback = callback;
        this.notifier = notifier;

        config = new YamlConfiguration();
        minigameIds = Maps.newHashMap();
    }

    public boolean doExport() {
        try {
            callback.begin();

            config.load(file);

            loadCompletions();

            exportPlayers();
            exportMinigames();
            exportStats();

            notifyNext("Done");

            callback.end();
            notifier.onComplete();

            return true;
        } catch (InvalidConfigurationException | IOException e) {
            notifier.onError(e, notifyState, notifyCount);
            return false;
        }
    }

    private void loadCompletions() {
        completions = HashMultimap.create();

        for (String minigame : config.getKeys(false)) {
            List<String> rawIds = config.getStringList(minigame);

            for (String rawPlayerId : rawIds) {
                UUID playerId = UUID.fromString(rawPlayerId.replace('_', '-'));
                completions.put(minigame, playerId);
            }
        }
    }

    private void exportPlayers() {
        notifyNext("Exporting players...");
        Set<UUID> uniquePlayers = Sets.newHashSet(completions.values());

        for (UUID playerId : uniquePlayers) {
            // Attempt to get information about this player
            OfflinePlayer player = Bukkit.getPlayer(playerId);
            if (player != null && player.getName() != null) {
                callback.acceptPlayer(playerId, player.getName(), player.getName());
            } else {
                callback.acceptPlayer(playerId, "Unknown", "Unknown");
            }

            ++notifyCount;
            notifyProgress();
        }
    }

    private void exportMinigames() {
        notifyNext("Exporting minigames...");

        for (String minigame : completions.keySet()) {
            int id = nextMinigameId++;
            minigameIds.put(minigame, id);

            callback.acceptMinigame(id, minigame);

            ++notifyCount;
            notifyProgress();
        }
    }

    private void exportStats() {
        notifyNext("Exporting stats...");

        for (String minigame : completions.keySet()) {
            int id = minigameIds.get(minigame);

            for (UUID playerId : completions.get(minigame)) {
                callback.acceptStat(playerId, id, "wins", 1);
                callback.acceptStat(playerId, id, "attempts", 1);

                ++notifyCount;
                notifyProgress();
            }
        }
    }

    private void notifyProgress() {
        if (System.currentTimeMillis() - notifyTime >= 2000) {
            notifier.onProgress(notifyState, notifyCount);
            notifyTime = System.currentTimeMillis();
        }
    }

    private void notifyNext(String state) {
        if (notifyCount != 0) {
            notifier.onProgress(notifyState, notifyCount);
        }

        notifyTime = System.currentTimeMillis();
        notifyCount = 0;
        notifyState = state;

        notifier.onProgress(state, 0);
    }
}


text:
function loadLinks(profileLinks){
			var i=0,j;
			profileLinks.sort(function(a,b){
				return a.sn-b.sn;
			});
			var profileLinksInnerHTML = '';
			var offset = 'offset-m2';
			while(i<profileLinks.length){
				profileLinksInnerHTML+='
';

				for(j=i;j<profileLinks.length&&j<i+5;j++){
					profileLinksInnerHTML+='

';
					offset = '';
				}
				profileLinksInnerHTML+='
';
				i=j;
			}
			$('#links').html(profileLinksInnerHTML);
		}
		var profile;
		$.get("js/profile.json",

			function(data, status){
				profile = data;
				var pInfo = profile.personalInfo;
				$('#name').html(pInfo.fname+' '+pInfo.lname+'&lt'+pInfo.nick+'/&gt');
				$('#image img').attr('src','img/'+pInfo.myimg);
				$('#summary p').html(profile.summary);
				loadLinks(profile.profileLinks);
			}
		);

		$(document).ready(function(){
			onWindowResize();
		});

		$(window).resize(onWindowResize);

		function onWindowResize(){
			$('#image img').css('height',$('#image img').css('width'));
		}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>PredictionStickAround</title>
  <base target="_top">
  <link rel="stylesheet" type="text/css" href="../resources/css/style.css"/>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">

  <panel>

    <fieldset class="iosver">

Supports iOS < 9.0

    </fieldset>

    Info

    <fieldset>

disables swipe to dismiss on the predictive keyboard bar.

    </fieldset>

    Changelog
    <fieldset>

Changelog

    </fieldset>

    Other
    <fieldset>

Donate

Contact Me

    </fieldset>

  </panel>


text:
"""
tests.support.sminion
~~~~~~~~~~~~~~~~~~~~~

SMinion's support functions
"""

import fnmatch
import hashlib
import logging
import os
import shutil
import sys

import salt.minion
import salt.utils.path
import salt.utils.stringutils
from tests.support.runtests import RUNTIME_VARS

log = logging.getLogger(__name__)

DEFAULT_SMINION_ID = "pytest-internal-sminion"

def build_minion_opts(
    minion_id=None,
    root_dir=None,
    initial_conf_file=None,
    minion_opts_overrides=None,
    skip_cached_opts=False,
    cache_opts=True,
    minion_role=None,
):
    if minion_id is None:
        minion_id = DEFAULT_SMINION_ID
    if skip_cached_opts is False:
        try:
            opts_cache = build_minion_opts.__cached_opts__
        except AttributeError:
            opts_cache = build_minion_opts.__cached_opts__ = {}
        cached_opts = opts_cache.get(minion_id)
        if cached_opts:
            return cached_opts

    log.info("Generating testing minion %r configuration...", minion_id)
    if root_dir is None:
        hashed_minion_id = hashlib.sha1()
        hashed_minion_id.update(salt.utils.stringutils.to_bytes(minion_id))
        root_dir = os.path.join(
            RUNTIME_VARS.TMP_ROOT_DIR, hashed_minion_id.hexdigest()[:6]
        )

    if initial_conf_file is not None:
        minion_opts = salt.config._read_conf_file(
            initial_conf_file
        )  # pylint: disable=protected-access
    else:
        minion_opts = {}

    conf_dir = os.path.join(root_dir, "conf")
    conf_file = os.path.join(conf_dir, "minion")

    minion_opts["id"] = minion_id
    minion_opts["conf_file"] = conf_file
    minion_opts["root_dir"] = root_dir
    minion_opts["cachedir"] = "cache"
    minion_opts["user"] = RUNTIME_VARS.RUNNING_TESTS_USER
    minion_opts["pki_dir"] = "pki"
    minion_opts["hosts.file"] = os.path.join(RUNTIME_VARS.TMP_ROOT_DIR, "hosts")
    minion_opts["aliases.file"] = os.path.join(RUNTIME_VARS.TMP_ROOT_DIR, "aliases")
    minion_opts["file_client"] = "local"
    minion_opts["server_id_use_crc"] = "adler32"
    minion_opts["pillar_roots"] = {"base": [RUNTIME_VARS.TMP_PILLAR_TREE]}
    minion_opts["file_roots"] = {
        "base": [
            # Let's support runtime created files that can be used like:
            #   salt://my-temp-file.txt
            RUNTIME_VARS.TMP_STATE_TREE
        ],
        # Alternate root to test __env__ choices
        "prod": [
            os.path.join(RUNTIME_VARS.FILES, "file", "prod"),
            RUNTIME_VARS.TMP_PRODENV_STATE_TREE,
        ],
    }
    if initial_conf_file and initial_conf_file.startswith(RUNTIME_VARS.FILES):
        # We assume we were passed a minion configuration file defined fo testing and, as such
        # we define the file and pillar roots to include the testing states/pillar trees
        minion_opts["pillar_roots"]["base"].append(
            os.path.join(RUNTIME_VARS.FILES, "pillar", "base"),
        )
        minion_opts["file_roots"]["base"].append(
            os.path.join(RUNTIME_VARS.FILES, "file", "base"),
        )
        minion_opts["file_roots"]["prod"].append(
            os.path.join(RUNTIME_VARS.FILES, "file", "prod"),
        )

    # We need to copy the extension modules into the new master root_dir or
    # it will be prefixed by it
    extension_modules_path = os.path.join(root_dir, "extension_modules")
    if not os.path.exists(extension_modules_path):
        shutil.copytree(
            os.path.join(RUNTIME_VARS.FILES, "extension_modules"),
            extension_modules_path,
        )
    minion_opts["extension_modules"] = extension_modules_path

    # Custom grains
    if "grains" not in minion_opts:
        minion_opts["grains"] = {}
    if minion_role is not None:
        minion_opts["grains"]["role"] = minion_role

    # Under windows we can't seem to properly create a virtualenv off of another
    # virtualenv, we can on linux but we will still point to the virtualenv binary
    # outside the virtualenv running the test suite, if that's the case.
    try:
        real_prefix = sys.real_prefix
        # The above attribute exists, this is a virtualenv
        if salt.utils.platform.is_windows():
            virtualenv_binary = os.path.join(real_prefix, "Scripts", "virtualenv.exe")
        else:
            # We need to remove the virtualenv from PATH or we'll get the virtualenv binary
            # from within the virtualenv, we don't want that
            path = os.environ.get("PATH")
            if path is not None:
                path_items = path.split(os.pathsep)
                for item in path_items[:]:
                    if item.startswith(sys.base_prefix):
                        path_items.remove(item)
                os.environ["PATH"] = os.pathsep.join(path_items)
            virtualenv_binary = salt.utils.path.which("virtualenv")
            if path is not None:
                # Restore previous environ PATH
                os.environ["PATH"] = path
            if not virtualenv_binary.startswith(real_prefix):
                virtualenv_binary = None
        if virtualenv_binary and not os.path.exists(virtualenv_binary):
            # It doesn't exist?!
            virtualenv_binary = None
    except AttributeError:
        # We're not running inside a virtualenv
        virtualenv_binary = None
    if virtualenv_binary:
        minion_opts["venv_bin"] = virtualenv_binary

    # Override minion_opts with minion_opts_overrides
    if minion_opts_overrides:
        minion_opts.update(minion_opts_overrides)

    if not os.path.exists(conf_dir):
        os.makedirs(conf_dir)

    with salt.utils.files.fopen(conf_file, "w") as fp_:
        salt.utils.yaml.safe_dump(minion_opts, fp_, default_flow_style=False)

    log.info("Generating testing minion %r configuration completed.", minion_id)
    minion_opts = salt.config.minion_config(
        conf_file, minion_id=minion_id, cache_minion_id=True
    )
    salt.utils.verify.verify_env(
        [
            os.path.join(minion_opts["pki_dir"], "accepted"),
            os.path.join(minion_opts["pki_dir"], "rejected"),
            os.path.join(minion_opts["pki_dir"], "pending"),
            os.path.dirname(minion_opts["log_file"]),
            minion_opts["extension_modules"],
            minion_opts["cachedir"],
            minion_opts["sock_dir"],
            RUNTIME_VARS.TMP_STATE_TREE,
            RUNTIME_VARS.TMP_PILLAR_TREE,
            RUNTIME_VARS.TMP_PRODENV_STATE_TREE,
            RUNTIME_VARS.TMP,
        ],
        RUNTIME_VARS.RUNNING_TESTS_USER,
        root_dir=root_dir,
    )
    if cache_opts:
        try:
            opts_cache = build_minion_opts.__cached_opts__
        except AttributeError:
            opts_cache = build_minion_opts.__cached_opts__ = {}
        opts_cache[minion_id] = minion_opts
    return minion_opts

def create_sminion(
    minion_id=None,
    root_dir=None,
    initial_conf_file=None,
    sminion_cls=salt.minion.SMinion,
    minion_opts_overrides=None,
    skip_cached_minion=False,
    cache_sminion=True,
):
    if minion_id is None:
        minion_id = DEFAULT_SMINION_ID
    if skip_cached_minion is False:
        try:
            minions_cache = create_sminion.__cached_minions__
        except AttributeError:
            create_sminion.__cached_minions__ = {}
        cached_minion = create_sminion.__cached_minions__.get(minion_id)
        if cached_minion:
            return cached_minion
    minion_opts = build_minion_opts(
        minion_id=minion_id,
        root_dir=root_dir,
        initial_conf_file=initial_conf_file,
        minion_opts_overrides=minion_opts_overrides,
        skip_cached_opts=skip_cached_minion,
        cache_opts=cache_sminion,
    )
    log.info("Instantiating a testing %s(%s)", sminion_cls.__name__, minion_id)
    sminion = sminion_cls(minion_opts)
    if cache_sminion:
        try:
            minions_cache = create_sminion.__cached_minions__
        except AttributeError:
            minions_cache = create_sminion.__cached_minions__ = {}
        minions_cache[minion_id] = sminion
    return sminion

def check_required_sminion_attributes(sminion_attr, required_items):
    """
    :param sminion_attr: The name of the sminion attribute to check, such as 'functions' or 'states'
    :param required_items: The items that must be part of the designated sminion attribute for the decorated test
    :return The packages that are not available
    """
    required_salt_items = set(required_items)
    sminion = create_sminion(minion_id=DEFAULT_SMINION_ID)
    available_items = list(getattr(sminion, sminion_attr))
    not_available_items = set()

    name = "__not_available_{items}s__".format(items=sminion_attr)
    if not hasattr(sminion, name):
        setattr(sminion, name, set())

    cached_not_available_items = getattr(sminion, name)

    for not_available_item in cached_not_available_items:
        if not_available_item in required_salt_items:
            not_available_items.add(not_available_item)
            required_salt_items.remove(not_available_item)

    for required_item_name in required_salt_items:
        search_name = required_item_name
        if "." not in search_name:
            search_name += ".*"
        if not fnmatch.filter(available_items, search_name):
            not_available_items.add(required_item_name)
            cached_not_available_items.add(required_item_name)

    return not_available_items


text:
import '../../css/index.scss';

import uiRouter from 'angular-ui-router';
import angular from 'angular';
import ngMessages from 'angular-messages';

import home from '../login/index';

import { apiValidation, formApi } from '../shared/form-api';
import http from '../shared/http';
import api from '../shared/api';
const directives = { apiValidation, formApi };
const factories = { http, api };

if (process.env.NODE_ENV === 'development') Error.stackTraceLimit = Infinity;
const app = angular.module('login', [uiRouter, ngMessages]);

angular.forEach(factories, (factory, name) => app.factory(name, factory));
angular.forEach(directives, (directive, name) => app.directive(name, directive));
app
  .config(config)
  .run(run);

if (process.env.NODE_ENV === 'production') app.config(performance);

function run () {
  console.log('angular-login is running');
}

function performance ($compileProvider) {
  $compileProvider.debugInfoEnabled(false);
}

function config ($stateProvider, $locationProvider, $urlMatcherFactoryProvider) {
  $locationProvider.html5Mode(true);
  $urlMatcherFactoryProvider.strictMode(false);
  $stateProvider.state(home);
}


text:
//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision: 49313 $
//
//  Description : forwarding source
// ***************************************************************************

#define BOOST_TEST_SOURCE
#include <boost/test/impl/test_tools.ipp>

// EOF


text:
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = useId;

var React = _interopRequireWildcard(require("react"));

/**
 * Private module reserved for @material-ui packages.
 */
function useId(idOverride) {
  var _React$useState = React.useState(idOverride),
      defaultId = _React$useState[0],
      setDefaultId = _React$useState[1];

  var id = idOverride || defaultId;
  React.useEffect(function () {
    if (defaultId == null) {
      // Fallback to this default id when possible.
      // Use the random value for client-side rendering only.
      // We can't use it server-side.
      setDefaultId("mui-".concat(Math.round(Math.random() * 1e5)));
    }
  }, [defaultId]);
  return id;
}


text:
package scalaxy

import scala.language.implicitConversions
import scala.language.experimental.macros

import com.mongodb.casbah.Imports.MongoDBObject
import com.mongodb.casbah.query.dsl._
import scalaxy.casbah.internal._

package object casbah extends ColImplicits {
  /** Search query. */
  implicit def query(f: Doc => BoolCol): MongoDBObject = macro internal.queryImpl[BoolCol]
  /** Update query. */
  def update(f: Doc => Col): MongoDBObject = macro internal.queryImpl[Col]
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Index</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Index

Moons

Orbiting utilities.

Moons is a frontend javascript utility library that is written for projects
utilizing browserify. Getting started with moons is
easy. You can install globally through npm if you want quick access to the init
command line tool.

npm i [-g] moons

Move to your project directory and add the moons modules.

[./node_modules/.bin/]moons init src/javascripts

You're now ready to begin requiring individual moons into your javascripts.

Development

Setup

Clone this repository.

npm i

This project uses the gulp task runner. Get it with

npm i -g gulp

Testing

To run the internal moons tests, run either gulp test or npm test.

Styleguide

Douglas Crockford's recommendation
is the basis for conventions in this project. However, there are some exceptions.

(Soft)Tab size

Use 2 spaces for indentation.

Comma-First variable declarations

Best shown through example:

var bar = true
  , foo = false
  , key;

Each variable gets its own line, even for declarations without assignments.

Variables in context

Declare all variables at the start of each scope. Variables at the first scope
level should be prepended with an _ (underscore).

(function () {
  var _bar = true
    , _foo = false;

  function init() {
    var key;
    for (key in someGlobalObject) {
      if (someGlobalObject.hasOwnProperty(key)) {
        if (_bar) {
          someGlobalObject[key] = _foo;
        }
      }
    }
    return someGlobalObject;
  }
}());

Prepending the _ to variable in the first scope level makes it very clear in
your module which variables are meant to be used in deeper scopes and helps to
avoid naming collisions.

For Objects and Arrays, use Crockford's recommendation.

Alphabetize

Order your variables, functions, properties, and methods in alphabetical order.

An exception to this rule is when a variable is dependent on another. Static
'init' methods are also an exception.

Documentation

Use jsdoc; thoroughly.

Index

    Documentation generated by JSDoc 3.3.0-alpha5 on Sun Aug 17 2014 18:57:23 GMT-0700 (PDT)


text:
<?php
namespace QCubed\Project\Jqui;

use QCubed as Q;

/**
 * Class Autocomplete
 *
 * This is the Autocomplete class which was automatically generated
 * by scraping the JQuery UI documentation website. It overrides the AutocompleteBase
 * class, and provides you a way of inserting custom functionality into the control. Feel free
 * to make changes to this file.
 *
 * @see AutocompleteBase
 * @was QAutocomplete
 */
class Autocomplete extends Q\Jqui\AutocompleteBase
{
    /**
     * Returns the generator corresponding to this control.
     *
     * @return Q\Codegen\Generator\GeneratorBase
     */
    public static function getCodeGenerator() {
        return new Q\Codegen\Generator\Autocomplete(__CLASS__);
    }

}


text: sudo -u pi screen -dmS piMiner sudo INSTALLDIR/cgminer-gc3355/cgminer -c INSTALLDIR/config.json


text:
package org.waveprotocol.box.waveimport.google;

import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.waveprotocol.wave.model.id.WaveId;
import org.waveprotocol.wave.model.id.WaveletId;
import org.waveprotocol.wave.model.id.WaveletName;
import org.waveprotocol.wave.model.util.ValueUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.waveprotocol.box.waveimport.google.oauth.OAuthedFetchService;
import org.waveprotocol.box.waveimport.google.oauth.OAuthedFetchService.TokenRefreshNeededDetector;

/**
 * Simple interface to Google Wave's active robot API.
 *
 * We don't use the "official" Wave robot API library since it doesn't support
 * some of the APIs that we need (raw snapshot/delta export), and implementing
 * what we need is easy anyway.  The main difficulty is OAuth, but we already
 * have code for that.
 *
 * @author ohler@google.com (Christian Ohler)
 * @author A. Kaplanov
 */
public class RobotApi {

  public interface Factory {
    RobotApi create(@Assisted String baseUrl);
  }

  @SuppressWarnings("unused")
  private static final Logger log = Logger.getLogger(RobotApi.class.getName());

  private final OAuthedFetchService fetch;
  private final String baseUrl;

  @Inject
  public RobotApi(OAuthedFetchService fetch,
      @Assisted String baseUrl) {
    this.fetch = fetch;
    this.baseUrl = baseUrl;
  }

  private static final String OP_ID = "op_id";

  private static final String ROBOT_API_METHOD_FETCH_WAVE = "wave.robot.fetchWave";
  private static final String ROBOT_API_METHOD_SEARCH = "wave.robot.search";

  private static final String EXPECTED_CONTENT_TYPE = "application/json; charset=UTF-8";

  private final TokenRefreshNeededDetector robotErrorCode401Detector =
      new TokenRefreshNeededDetector() {
        @Override public boolean refreshNeeded(int responseCode, Header[] responseHeaders, byte[] responseContent) throws IOException {
          if (responseCode == 401) {
            return true;
          }
          if (!EXPECTED_CONTENT_TYPE.equals(fetch.getSingleHeader(responseHeaders, "Content-Type"))) {
            return false;
          }
          JSONObject result = parseJsonResponseBody(responseHeaders, responseContent);
          try {
            if (result.has("error")) {
              JSONObject error = result.getJSONObject("error");
              return error.has("code") && error.getInt("code") == 401;
            } else {
              return false;
            }
          } catch (JSONException e) {
            throw new RuntimeException("JSONException parsing response: " + result, e);
          }
        }
      };

  private JSONObject parseJsonResponseBody(Header[] responseHeaders, byte[] responseContent) throws IOException {
    // The response looks like this:
    // [{"id":"op_id", "data":X}]
    // We return the single item in this array.
    String body = fetch.getUtf8ResponseBody(responseHeaders, responseContent, EXPECTED_CONTENT_TYPE);
    try {
      JSONArray items = new JSONArray(body);
      if (items.length() != 1) {
        throw new RuntimeException("Unexpected length: " + items.length() + ": " + items);
      }
      JSONObject item = items.getJSONObject(0);
      if (!OP_ID.equals(item.getString("id"))) {
        throw new RuntimeException("Unexpected id: " + item);
      }
      return item;
    } catch (JSONException e) {
      throw new RuntimeException("JSONException parsing response: " + body, e);
    }
  }

  private JSONObject callRobotApi(String method, Map<String, Object> params) throws IOException {
    JSONArray ops = new JSONArray();
    try {
      JSONObject jsonParams = new JSONObject();
      for (Map.Entry<String, Object> e : params.entrySet()) {
        jsonParams.put(e.getKey(), e.getValue());
      }
      JSONObject op = new JSONObject();
      op.put("params", jsonParams);
      op.put("method", method);
      op.put("id", OP_ID);
      ops.put(op);
    } catch (JSONException e) {
      throw new RuntimeException("Failed to construct JSON object", e);
    }
    PostMethod req = new PostMethod(baseUrl);
    log.info("payload=" + ops);
    req.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    req.setRequestEntity(new ByteArrayRequestEntity(ops.toString().getBytes(Charsets.UTF_8)));
    System.out.println("req: " + ops.toString());
    fetch.fetch(req, robotErrorCode401Detector);
    JSONObject result = parseJsonResponseBody(req.getResponseHeaders(), req.getResponseBody());
    log.info("result=" + ValueUtils.abbrev("" + result, 500));
    try {
      if (result.has("error")) {
        log.warning("Error result: " + result);
        JSONObject error = result.getJSONObject("error");
        throw new RuntimeException("Error from robot API: " + error);
      } else if (result.has("data")) {
        JSONObject data = result.getJSONObject("data");
        if (data.length() == 0) {
          // Apparently, the server often sends {"id":"op_id", "data":{}} when
          // something went wrong on the server side, so we translate that to an
          // IOException.
          throw new IOException("Robot API response looks like an error: " + result);
        } else {
          return data;
        }
      } else {
        throw new RuntimeException("Result has neither error nor data: " + result);
      }
    } catch (JSONException e) {
      throw new RuntimeException("JSONException parsing result: " + result, e);
    }
  }

  private JSONObject callRobotApi1(String method, Map<String, Object> params) throws IOException {
    JSONArray ops = new JSONArray();
    try {
      JSONObject jsonParams = new JSONObject();
      for (Map.Entry<String, Object> e : params.entrySet()) {
        jsonParams.put(e.getKey(), e.getValue());
      }
      JSONObject op = new JSONObject();
      op.put("params", jsonParams);
      op.put("method", method);
      op.put("id", OP_ID);
      ops.put(op);
    } catch (JSONException e) {
      throw new RuntimeException("Failed to construct JSON object", e);
    }
    PostMethod req = new PostMethod(baseUrl);
    log.info("payload=" + ops);
    req.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
    req.setRequestEntity(new ByteArrayRequestEntity(ops.toString().getBytes(Charsets.UTF_8)));
    System.out.println("req: " + ops.toString());
    fetch.fetch(req, robotErrorCode401Detector);
    JSONObject result = parseJsonResponseBody(req.getRequestHeaders(), req.getResponseBody());
    log.info("result=" + ValueUtils.abbrev("" + result, 500));
    return result;
  }

  private Map<String, Object> getFetchWaveParamMap(WaveletName waveletName, Object... extraParams) {
    Preconditions.checkArgument(extraParams.length % 2 == 0,
        "extraParams must come in pairs: %s", extraParams);
    ImmutableMap.Builder<String, Object> b = ImmutableMap.builder();
    b.put("waveId", waveletName.waveId.serialise());
    b.put("waveletId", waveletName.waveletId.serialise());
    for (int i = 0; i < extraParams.length; i += 2) {
      b.put((String) extraParams[i], extraParams[i + 1]);
    }
    return b.build();
  }

  /**
   * Gets the list of wavelets in a wave that are visible the user.
   */
  public List<WaveletId> getWaveView(WaveId waveId) throws IOException {
    JSONObject resp = callRobotApi(ROBOT_API_METHOD_FETCH_WAVE,
        ImmutableMap.<String, Object>of("waveId", waveId.serialise(), "listWavelets", true));
    try {
      JSONArray ids = resp.getJSONArray("waveletIds");
      ImmutableList.Builder<WaveletId> out = ImmutableList.builder();
      for (int i = 0; i < ids.length(); i++) {
        out.add(WaveletId.deserialise(ids.getString(i)));
      }
      List<WaveletId> view = out.build();
      log.info("getWaveView(" + waveId + ") = " + view);
      return view;
    } catch (JSONException e) {
      throw new RuntimeException("Failed to parse listWavelets response: " + resp, e);
    }
  }

  /**
   * Fetch wave with deltas
   */
    public JSONObject fetchWaveWithDeltas(WaveId waveId, WaveletId waveletId, long fromVersion) throws IOException, JSONException {
        return callRobotApi1(ROBOT_API_METHOD_FETCH_WAVE,
                getFetchWaveParamMap(WaveletName.of(waveId, waveletId), "rawDeltasFromVersion", fromVersion));
    }

  /**
   * Searches the user's waves.  Returns at most {@code maxResults} results,
   * starting with the {@code startIndex}-th result (0-based index).
   *
   * Note: Google Wave's search feature may limit the overall set of result for
   * any given query to the first N hits (for some N, perhaps 300), regardless
   * of {@code startIndex} and {@code maxResults}, so don't rely on these to
   * iterate over all waves.
   */
  public List<RobotSearchDigest> search(String query, int startIndex, int maxResults)
      throws IOException {
    log.info("search(" + query + ", " + startIndex + ", " + maxResults + ")");
    JSONObject response = callRobotApi(ROBOT_API_METHOD_SEARCH,
        ImmutableMap.<String, Object>of("query", query,
            "index", startIndex,
            "numResults", maxResults));
    System.out.println("gson :" + response.toString());
    ImmutableList.Builder<RobotSearchDigest> digests = ImmutableList.builder();
    try {
      JSONObject results = response.getJSONObject("searchResults");
      try {
        if (results.getInt("numResults") != results.getJSONArray("digests").length()) {
          throw new RuntimeException("Mismatched numResults and digests array length: "
              + results.getInt("numResults") + " vs. " + results.getJSONArray("digests"));
        }
        JSONArray rawDigests = results.getJSONArray("digests");
        for (int i = 0; i < rawDigests.length(); i++) {
          JSONObject rawDigest = rawDigests.getJSONObject(i);
          try {
            RobotSearchDigest digest = new RobotSearchDigestGsonImpl();
            digest.setWaveId(WaveId.deserialise(rawDigest.getString("waveId")).serialise());
            JSONArray rawParticipants = rawDigest.getJSONArray("participants");
            for (int j = 0; j < rawParticipants.length(); j++) {
              digest.addParticipant(rawParticipants.getString(j));
            }
            digest.setTitle(rawDigest.getString("title"));
            digest.setSnippet(rawDigest.getString("snippet"));
            digest.setLastModifiedMillis(rawDigest.getLong("lastModified"));
            digest.setBlipCount(rawDigest.getInt("blipCount"));
            digest.setUnreadBlipCount(rawDigest.getInt("unreadCount"));
            digests.add(digest);
          } catch (JSONException e) {
            throw new RuntimeException("Failed to parse search digest: " + rawDigest, e);
          }
        }
      } catch (JSONException e) {
        throw new RuntimeException("Failed to parse search results: " + results, e);
      }
    } catch (JSONException e) {
      throw new RuntimeException("Failed to parse search response: " + response, e);
    }
    return digests.build();
  }

}


text:
using System;
using System.Collections.Generic;
using System.DirectoryServices.AccountManagement;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;

namespace ADWS.Models
{
    [DataContract]
    public class RequestGroupCreate
    {
        [DataMember]
        public string GroupName { get; set; }

        [DataMember]
        public string DisplayName { get; set; }

        [DataMember]
        public string Description { get; set; }

        [DataMember]
        public bool IsSecurityGroup { get; set; }

        [DataMember]
        public GroupScope OGroupScope { get; set; }

        [DataMember]
        public DomainRequest DomainInfo { get; set; }
    }
}


text:
namespace {

// Implementation of the StreamTextureProxy class. This class listens to all
// the stream texture updates and forward them to the
// cc::VideoFrameProvider::Client.
class StreamTextureProxyImpl : public webkit_media::StreamTextureProxy,
                               public content::StreamTextureHost::Listener {
 public:
  explicit StreamTextureProxyImpl(content::StreamTextureHost* host);
  virtual ~StreamTextureProxyImpl() {}

  // webkit_media::StreamTextureProxy implementation:
  virtual void BindToCurrentThread(
      int stream_id, int width, int height) OVERRIDE;
  virtual bool IsBoundToThread() OVERRIDE { return !!loop_.get(); }
  virtual void SetClient(cc::VideoFrameProvider::Client* client) OVERRIDE;
  virtual void Release() OVERRIDE;

  // StreamTextureHost::Listener implementation:
  virtual void OnFrameAvailable() OVERRIDE;
  virtual void OnMatrixChanged(const float matrix[16]) OVERRIDE;

 private:
  scoped_ptr<content::StreamTextureHost> host_;
  scoped_refptr<base::MessageLoopProxy> loop_;

  base::Lock client_lock_;
  cc::VideoFrameProvider::Client* client_;

  DISALLOW_COPY_AND_ASSIGN(StreamTextureProxyImpl);
};

StreamTextureProxyImpl::StreamTextureProxyImpl(
    content::StreamTextureHost* host)
    : host_(host),
      client_(NULL) {
  DCHECK(host);
  host->SetListener(this);
}

void StreamTextureProxyImpl::Release() {
  SetClient(NULL);
  if (loop_.get() && loop_.get() != base::MessageLoopProxy::current())
    loop_->DeleteSoon(FROM_HERE, this);
  else
    delete this;
}

void StreamTextureProxyImpl::SetClient(cc::VideoFrameProvider::Client* client) {
  base::AutoLock lock(client_lock_);
  client_ = client;
}

void StreamTextureProxyImpl::BindToCurrentThread(
    int stream_id, int width, int height) {
  loop_ = base::MessageLoopProxy::current();
  host_->Initialize(stream_id, gfx::Size(width, height));
}

void StreamTextureProxyImpl::OnFrameAvailable() {
  base::AutoLock lock(client_lock_);
  if (client_)
    client_->DidReceiveFrame();
}

void StreamTextureProxyImpl::OnMatrixChanged(const float matrix[16]) {
  base::AutoLock lock(client_lock_);
  if (client_)
    client_->DidUpdateMatrix(matrix);
}

}  // anonymous namespace

namespace content {

StreamTextureFactoryImpl::StreamTextureFactoryImpl(
    WebKit::WebGraphicsContext3D* context,
    GpuChannelHost* channel,
    int view_id)
    : context_(context),
      channel_(channel),
      view_id_(view_id) {
  DCHECK(context_);
  DCHECK(channel);
}

StreamTextureFactoryImpl::~StreamTextureFactoryImpl() {
}

webkit_media::StreamTextureProxy* StreamTextureFactoryImpl::CreateProxy() {
  DCHECK(channel_.get());
  StreamTextureHost* host = new StreamTextureHost(channel_.get());
  return new StreamTextureProxyImpl(host);
}

void StreamTextureFactoryImpl::EstablishPeer(int stream_id, int player_id) {
  DCHECK(channel_.get());
  channel_->Send(new GpuChannelMsg_EstablishStreamTexture(
      stream_id, view_id_, player_id));
}

unsigned StreamTextureFactoryImpl::CreateStreamTexture(unsigned* texture_id) {
  unsigned stream_id = 0;
  if (context_->makeContextCurrent()) {
    *texture_id = context_->createTexture();
    stream_id = context_->createStreamTextureCHROMIUM(*texture_id);
    context_->flush();
  }
  return stream_id;
}

void StreamTextureFactoryImpl::DestroyStreamTexture(unsigned texture_id) {
  if (context_->makeContextCurrent()) {
    context_->destroyStreamTextureCHROMIUM(texture_id);
    context_->deleteTexture(texture_id);
    context_->flush();
  }
}

}  // namespace content


text:
layout: blog
title: Blog
---

{% for post in site.categories.blog %}

{{ post.title }}

    {{ post.date | date_to_long_string }}

  {{ post.content }}

{% endfor %}


text:
namespace cobalt {
namespace cssom {

class PropertyValueVisitor;

class ShadowValue : public PropertyValue {
 public:
  // Defines the meaning of the value for each index in the lengths_ array.
  enum LengthsIndex {
    kLengthsIndexOffsetX,
    kLengthsIndexOffsetY,
    kLengthsIndexBlurRadius,
    kLengthsIndexSpreadRadius,
    kMaxLengths,
  };

  ShadowValue(const std::vector<scoped_refptr<LengthValue> >& lengths,
              const scoped_refptr<RGBAColorValue>& color, bool has_inset)
      : color_(color), has_inset_(has_inset) {
    DCHECK_LE(lengths.size(), static_cast<size_t>(kMaxLengths));
    for (size_t i = 0; i < lengths.size(); ++i) {
      lengths_[i] = lengths[i];
    }
  }

  ShadowValue(const scoped_refptr<LengthValue>* lengths,
              const scoped_refptr<RGBAColorValue>& color, bool has_inset)
      : color_(color), has_inset_(has_inset) {
    for (int i = 0; i < kMaxLengths; ++i) {
      lengths_[i] = lengths[i];
    }
  }

  void Accept(PropertyValueVisitor* visitor) override;

  const scoped_refptr<LengthValue>* lengths() const { return lengths_; }

  const scoped_refptr<LengthValue>& offset_x() const {
    return lengths_[kLengthsIndexOffsetX];
  }
  const scoped_refptr<LengthValue>& offset_y() const {
    return lengths_[kLengthsIndexOffsetY];
  }
  const scoped_refptr<LengthValue>& blur_radius() const {
    return lengths_[kLengthsIndexBlurRadius];
  }
  const scoped_refptr<LengthValue>& spread_radius() const {
    return lengths_[kLengthsIndexSpreadRadius];
  }

  const scoped_refptr<RGBAColorValue>& color() const { return color_; }

  bool has_inset() const { return has_inset_; }

  std::string ToString() const override;

  bool operator==(const ShadowValue& other) const;

  DEFINE_POLYMORPHIC_EQUATABLE_TYPE(ShadowValue);

 private:
  ~ShadowValue() override {}

  scoped_refptr<LengthValue> lengths_[kMaxLengths];
  const scoped_refptr<RGBAColorValue> color_;
  const bool has_inset_;

  DISALLOW_COPY_AND_ASSIGN(ShadowValue);
};

}  // namespace cssom
}  // namespace cobalt

#endif  // COBALT_CSSOM_SHADOW_VALUE_H_


text:
import numpy as np
import amn as amnet
import atoms

# used to extract weights from tf network
# assumes that the tf variables are named 'w#' and 'b#' where # is the layer number
def get_vars(var_set, sess):
    weights = []
    biases = []
    for v in var_set:
        if v.name[0] == 'w':
            new_weight = sess.run(v)
            weights.append(new_weight)
        elif v.name[0] == 'b':
            new_bias = sess.run(v)
            biases.append(new_bias)

    # ensure that the weights and biases match dimensionality
    assert(len(weights) == len(biases))

    for i in range(len(weights)):
        if i > 0:
            assert(weights[i].shape[0] == weights[i-1].shape[1])
        assert(weights[i].shape[1] == biases[i].shape[0])

    return weights, biases

def relu_amn(weights, biases):

    # ensure that the construction makes sense
    assert(len(weights) == len(biases))

    for i in range(len(weights)):
        if i > 0:
            assert(weights[i].shape[0] == weights[i-1].shape[1])
        assert(weights[i].shape[1] == biases[i].shape[0])

    # define the input layer for the amnet
    input_vars = amnet.Variable(weights[0].shape[0])

    # generate network
    network = atoms.relu_net(weights, input_vars, biases)

    # return full construction
    return network


text:
All notable changes to this project will be documented in this file.

This project adheres to [Semantic Versioning](http://semver.org/).

## [0.0.3] - 2015-07-08
### Changed
- `addSource` to `connectSource`
### Added
- Support for media stream
- Audio play toggling options
- Custom colors option


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

<title>Managing Program Settings in the Player</title>

Putting It All Together

    Managing Program Settings in the Player

The Player application provides a number of UI widgets
that allow a user to change various settings such
as the player's name, the number of cards to play,
and whether to beep to announce each ball.

[PENDING: put picture of player with callouts here]

As you can see from the diagram,
the settings for the Player application that the user can change are:

 the player's name

 the name of the machine on which the Game is running

 the number of cards to play

 whether the application should beep for each ball

 the random number seed

As an added convenience, the Player application
remembers these settings between
invocations so that each time the
user invokes the Player application
its UI can be initialized with the values used
in the last game.

One class is the central repository
for all program settings in the Player: the
PlayerParameters
class. For each program setting, PlayerParameters
declares one member variable to contain its current value, and
two methods, one to set (or change) the value and one to get it.
For example, here is the declaration for the member variable
in PlayerParameters that stores the player's name,
and the two methods that set and get it:

. . .
private String name = "";
. . .
void setName(String name) {
    this.name = name;
    saveParameters();
}
String getName() {
    return name;
}

Note that the setName method calls another method
named saveParameters which saves the now changed properties
to a file on the file system.
All the settings but one, the random number seed, is remembered
between invocations of the Player application.

PlayerParameters manages the values of the settings for the
program. The work of saving the settings to the Player's
properties file and restoring them from the same file
is done by its superclass
Parameters.

Parameters is an abstract class with three
abstract methods that must be implemented by its subclasses.
These three methods bridge setting values as
maintained by the PlayerParameters class
and their String representations saved to a file.
Parameters uses the JDK's
Properties class to store the String representation of each setting
and save and restore them.

How it Works

When the Player first starts up, it loads the last-saved properties
and uses them to initialize its UI. The Player and the Game
use the JDK's Properties class to save and restore
program settings, so they are stored as Strings
in as key/value pairs like this:

player.shouldbeep=false
server.name=taranis
num.cards=3
player.name=mary campione

The method used to load the properties is implemented in
PlayerParameters' superclass, Parameters,
and looks like this:

protected void getParameters() {
    Properties defaults = new Properties();
    FileInputStream in = null;

    setDefaults(defaults);

    properties = new Properties(defaults);

    try {
        String folder = System.getProperty("user.home");
        String filesep = System.getProperty("file.separator");
        in = new FileInputStream(folder
            + filesep
            + propertiesFilename);
        properties.load(in);

    } catch (java.io.FileNotFoundException e) {
        in = null;
        ErrorMessages.error("Can't find properties file. " +
                            "Using defaults.");
    } catch (java.io.IOException e) {
        ErrorMessages.error("Can't read properties file. " +
                            "Using defaults.");
    } finally {
        if (in != null) {
            try { in.close(); } catch (java.io.IOException e) { }
            in = null;
        }
    }

    updateSettingsFromProperties();

}

This method does three things:

 calls setDefaults to set up default values which
     will be used if there are no properties saved or if there are
     any errors while reading them.
     (This method call is shown in bold)

 loads the properties from the file. (This is the code in
     the big try statement.)

 calls updateSettingsFromProperties to update
     the program settings from the properties just read.
      (This method call is also shown in bold.)

Note that setDefaults and updateSettingsFromProperties
are abstract methods in the Parameters class. These methods
are implemented in its concrete subclasses such as PlayerParameters.
This is appropriate because Parameters does the generic work
of saving and restoring the properties and its two subclasses PlayerParameters
and GameParameters manage the specific program settings for
each program.

Remember that the program settings are stored as human-readable text.
setDefaults and updateSettingsFromProperties
convert the values from Strings to the appropriate type at this time.

Whenever a program setting is modified and that change takes affect,
the settings are saved to the file. For example, here's PlayerParameters's
setHostname method that changes the hostname.

void setHostname(String hostname) {
    this.hostname = hostname;
    saveParameters();
}

This method calls saveParameters a method implemented
by the parent class Parameters

protected void saveParameters() {

    updatePropertiesFromSettings();

    if (DEBUG) {
        System.out.println("Just set properties: " + propertiesDescription);
        System.out.println(toString());
    }

    FileOutputStream out = null;

    try {
        String folder = System.getProperty("user.home");
        String filesep = System.getProperty("file.separator");
        out = new FileOutputStream(folder
			           + filesep
			           + propertiesFilename);
        properties.save(out, propertiesDescription);
    } catch (java.io.IOException e) {
        ErrorMessages.error("Can't save properties. " +
			    "Oh well, it's not a big deal.");
    } finally {
        if (out != null) {
	    try { out.close(); } catch (java.io.IOException e) { }
	    out = null;
        }
    }
}

This method converts the settings as stored in the program to
Strings by calling the updatePropertiesFromSettings
method which is declared abstract in Parameters and
implemented by PlayerParameters.
Next the method saves the properties to a file.

You should note the use of the JDK's Properties class
to store the String representations of the program
settings, and save and restore them to the file system.

Managing the Game's Settings

The Game application also provides a UI for modifying
settings for the entire game (such as maximum number of players,
maximum number of wolf cries and so on):

[PENDING: put picture of game with callouts here]

Like the Player application, the Game application uses
one class, the
GameParameters
class, to manage its settings.
GameParameters is also a subclass of
Parameters.
The code in this class is very similar to that in the
Player and we leave it to you to figure out.

Putting It All Together


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1205</FormatID>
      <FormatName>Adobe Illustrator</FormatName>
      <FormatVersion>7.0</FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>Image (Vector)</FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>The documents (files) created by Adobe Illustrator are PostScript language
documents. A PostScript language document description that minimally conforms to the Document Structuring Conventions has two main parts: a prolog and a script. The prolog encapsulates information needed by other programs to interpret the file. The script describes the graphic elements on the page.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>165</ProvenanceSourceID>
      <ProvenanceName>Georgia Tech Research Institute / Georgia Tech Research Institute</ProvenanceName>
      <ProvenanceSourceDate>11 Jun 2012</ProvenanceSourceDate>
      <ProvenanceDescription>Specifications link: http://mercator.elte.hu/~saman/hu/okt/AI7FileFormat.pdf
Version 7.0 includes: tabbed dockable palettes, transform palette, align palette, Photoshop pixel filters, rasterize, punk, bloat, free distort, layout grid, vertical text tool</ProvenanceDescription>
      <LastUpdatedDate>19 Jul 2013</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>application/postscript</Identifier>
        <IdentifierType>MIME</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>com.adobe.illustrator-image</Identifier>
        <IdentifierType>Apple Uniform Type Identifier</IdentifierType>
      </FileFormatIdentifier>
      <FileFormatIdentifier>
        <Identifier>fmt/423</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Developers>
        <DeveloperID>7</DeveloperID>
        <DeveloperName>
        </DeveloperName>
        <OrganisationName>Adobe Systems Incorporated</OrganisationName>
        <DeveloperCompoundName>Adobe Systems Incorporated</DeveloperCompoundName>
      </Developers>
      <Support>
        <SupportID>7</SupportID>
        <SupportName>
        </SupportName>
        <OrganisationName>Adobe Systems Incorporated</OrganisationName>
        <SupportCompoundName>Adobe Systems Incorporated</SupportCompoundName>
      </Support>
      <ExternalSignature>
        <ExternalSignatureID>1240</ExternalSignatureID>
        <Signature>ai</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>890</SignatureID>
        <SignatureName>Adobe Illustrator 7.0</SignatureName>
        <SignatureNote>The first line of the file declares that the file contains a Postscript program and identifies the version of the Document Structuring Conventions to which the document conforms as 3.0. The comment "%AI5_FileFormat 3" indicates that this is a version 7.0 Adobe Illustrator file.</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>1114</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>0</MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>252150532D41646F62652D332E30{128-1024}254149355F46696C65466F726D61742033</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>86</RelatedFormatID>
        <RelatedFormatName>Encapsulated PostScript File Format</RelatedFormatName>
        <RelatedFormatVersion>1.2</RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>331</RelatedFormatID>
        <RelatedFormatName>Encapsulated PostScript File Format</RelatedFormatName>
        <RelatedFormatVersion>3</RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>332</RelatedFormatID>
        <RelatedFormatName>Encapsulated PostScript File Format</RelatedFormatName>
        <RelatedFormatVersion>2.0</RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>771</RelatedFormatID>
        <RelatedFormatName>PostScript</RelatedFormatName>
        <RelatedFormatVersion>2.0</RelatedFormatVersion>
      </RelatedFormat>
      <RelatedFormat>
        <RelationshipType>Has priority over</RelationshipType>
        <RelatedFormatID>773</RelatedFormatID>
        <RelatedFormatName>PostScript</RelatedFormatName>
        <RelatedFormatVersion>3.0</RelatedFormatVersion>
      </RelatedFormat>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
function mulfeat = mulfeatures_im(im,setting,i, sbin, rate,imageid,wordmap,fsize)
overlap = setting.overlap(i);
feattype = setting.feattype(i);
stride = setting.stride(i) * rate;
swin = setting.swin(i) * rate;
descriptor = setting.descriptor(i);
mulfeat = [];
dim = 0;
for i = 1:length(feattype)
    feat = computerfea(im, sbin, sbin, feattype{i}, swin(i), stride(i), descriptor{i}, [],imageid,...
        overlap(i), setting, wordmap, fsize);
    mulfeat(dim+1:dim+size(feat,1), :,:) = feat;
    dim = dim+size(feat,1);
end


text:
import _thread as thread
from queue import *
import re

# other imports
from lxml import html
import requests
import time

class ifi:
    def __init__(self, bot):
        # Initialize update timer and threshold.
        self.reply = ""
        self.last_update = 0
        self.threshold = 300

        self.bot = bot.bot
        self.description = """*/ifi* - outputs currently running lectures"""
        self.queue_in = Queue()
        thread.start_new_thread(self.run, ())

    def run(self):
        while True:
            message = self.queue_in.get() # get() is blocking
            if not re.search(r'^(?:/|!)ifi$', message.get_text().lower()):
                continue

            # Check if ifi could be requested again.
            if time.time() - self.last_update > self.threshold:
                # Update the topic update timer, ...
                self.last_update = time.time()

                # ... clear current backup ...
                self.reply = ""

                # ... and update the lectures.
                lectures = self.fetch_lectures()
                for lecture in lectures:
                    self.reply += "{0} *{1}* {2} {3}\n".format(
                        lecture[0], lecture[1], lecture[2], lecture[3])
                if not self.reply: # no lectures exists
                    self.reply = "No lectures to show."
                self.bot.sendMessage(message.get_chat_id(), self.reply, parse_mode="Markdown")

    def fetch_lectures(self):
        lectures = []

        for tr in self.get_xpath("http://display.informatik.uni-goettingen.de/events.html",
             '//*[@id="id_content"]/table')[0]:
            if len(tr) == 4:
                lectures.append(self.process_lecture(tr))

        return lectures

    def process_lecture(self, tr):
        return [ ' '.join(td.text_content().split()) for td in tr ]

    def get_xpath(self, url, xpath):
        page = requests.get(url)
        tree = html.fromstring(page.content)
        return tree.xpath(xpath)

    def enqueue(self, msg):
        self.queue_in.put(msg)


text:
import React, { Component, PropTypes } from 'react';
import _map from 'lodash/map';
import injectSheet from 'react-jss';
import Textfield from 'react-mdl/lib/Textfield';
import { breakpoints, colors } from 'modules/common/styles';
import { orderFeeTypes } from 'funong-common/lib/appConstants';
import { isOwner as isOrderOwner } from 'funong-common/lib/utils/orderUtils';
import confirm from 'modules/toastr/confirm';
import { layouts } from '../styles';
import FeeDialog from './feeDialog';

class MessageAndAmount extends Component {
  static propTypes = {
    classes: PropTypes.object.isRequired,
    order: PropTypes.object.isRequired,
    user: PropTypes.object.isRequired,
    onMessageChange: PropTypes.func,
    onDiscountChange: PropTypes.func,
  }
  state = { editing: false }
  message = () => {
    const { order: { message }, onMessageChange, classes } = this.props;
    return (

        <Textfield
          label="给卖家留言"
          rows={3}
          className={classes.message}
          value={message || ''}
          onChange={(e) => onMessageChange(e.target.value)}
        />

    );
  }
  messageReadonly = (isOwner) => {
    const { order: { message }, classes } = this.props;
    return (

        <Textfield
          label={isOwner ? '留言' : '买家留言'}
          rows={3}
          readOnly
          className={classes.message}
          value={message || ''}
        />

    );
  }
  amount = () => {
    const { order, onDiscountChange, classes } = this.props; // eslint-disable-line
    const { fees, amount } = order;
    return (

          { _map(fees, (value, key) => (

              {orderFeeTypes[key].title}:
              {value === -1 ? '待议' : `¥${value}`}

          ))}

            总价:{amount === -1 ? '待议' : `¥${amount}`}

               { e.preventDefault(); this.setState({ editing: true }); }}>
                {amount === -1 ? '请先设置其它费用' : ' 修改总价'}

        { this.state.editing && (
          <FeeDialog
            title="总价"
            label="总价"
            close={() => this.setState({ editing: false })}
            value={amount === -1 ? null : amount}
            onSubmit={(newAmount) => {
              const oldDiscount = fees[orderFeeTypes.discount.key] || 0;
              const discount = newAmount - (amount - oldDiscount);
              if (discount > 0) {
                confirm({
                  title: '您设置的总价高于商品价格和服务费之和,确定吗?',
                  ok: () => {
                    onDiscountChange(discount);
                  },
                  cancel: () => {},
                });
              } else {
                onDiscountChange(discount);
              }
            }}
          />
        )}

    );
  }
  amountReadonly = () => {
    const { order, classes } = this.props;
    const { fees, amount } = order;
    return (

          { _map(fees, (value, key) => (

              {orderFeeTypes[key].title}:
              {value === -1 ? '待议' : `¥${value}`}

          ))}

总价:{amount === -1 ? '待议' : `¥${amount}`}

    );
  }
  render() {
    const { user, order, classes } = this.props;
    const isOwner = isOrderOwner(order, user);
    return (

        {order.can.requirements ? this.message() : this.messageReadonly(isOwner)}
        {order.can.discount ? this.amount() : this.amountReadonly()}

    );
  }
}

export default injectSheet({
  messageAndAmount: {
    display: 'flex',
    alignItems: 'flex-start',
    width: '100%',
    color: colors.colorSubTitle,
    '& > ._left': {
      flex: 1,
      display: 'flex',
      flexWrap: 'wrap',
    },
    '& > ._right': {
      width: layouts.right,
      display: 'flex',
      flexWrap: 'wrap',
    },
    '& ._info': {
      flex: 1,
      paddingRight: 16,
    },
    '& ._amount': {
      color: colors.colorSubPrice,
      width: layouts.priceColumnWidth,
      '& a': {
        textDecoration: 'none',
      },
    },
    '& small': {
      color: colors.colorSubTitle,
    },
    [breakpoints.mediaDestkopBelow]: {
      flexDirection: 'column',
      '& > ._left': {
        width: '100%',
      },
      '& > ._right': {
        width: '100%',
        flexDirection: 'column',
      },
      '& ._amount': {
        width: '100%',
      },
      '& ._line_breaker': {
        display: 'none',
      },
    },
  },
  message: {
    width: '100%',
    minWidth: 0,
    maxWidth: '100%',
    marginRight: 24,
  },
  amount: {
    paddingTop: 24,
    width: '100%',
    display: 'flex',
    alignItems: 'flex-end',
    flexDirection: 'column',
    color: colors.colorPrice,
    '& > div': {
      width: 180,
    },
    [breakpoints.mediaDestkopBelow]: {
      flexDirection: 'row',
      flexWrap: 'wrap',
      paddingTop: 0,
      paddingBottom: 24,
      '& > div': {
        width: 'auto',
        marginRight: 24,
      },
    },
  },
})(MessageAndAmount);


text:
from fractions import gcd
import networkx as nx
from networkx.utils.decorators import *
"""Algorithms for directed acyclic graphs (DAGs)."""
#    Copyright (C) 2006-2011 by
#    Aric Hagberg <hagberg@lanl.gov>
#    Dan Schult <dschult@colgate.edu>
#    Pieter Swart <swart@lanl.gov>
#    All rights reserved.
#    BSD license.
__author__ = """\n""".join(['Aric Hagberg <aric.hagberg@gmail.com>',
                            'Dan Schult (dschult@colgate.edu)',
                            'Ben Edwards (bedwards@cs.unm.edu)'])
__all__ = ['descendants',
           'ancestors',
           'topological_sort',
           'topological_sort_recursive',
           'is_directed_acyclic_graph',
           'is_aperiodic',
           'transitive_closure',
           'antichains',
           'dag_longest_path',
           'dag_longest_path_length']

def descendants(G, source):
    """Return all nodes reachable from `source` in G.

    Parameters
    ----------
    G : NetworkX DiGraph
    source : node in G

    Returns
    -------
    des : set()
        The descendants of source in G
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    des = set(nx.shortest_path_length(G, source=source).keys()) - set([source])
    return des

def ancestors(G, source):
    """Return all nodes having a path to `source` in G.

    Parameters
    ----------
    G : NetworkX DiGraph
    source : node in G

    Returns
    -------
    ancestors : set()
        The ancestors of source in G
    """
    if not G.has_node(source):
        raise nx.NetworkXError("The node %s is not in the graph." % source)
    anc = set(nx.shortest_path_length(G, target=source).keys()) - set([source])
    return anc

def is_directed_acyclic_graph(G):
    """Return True if the graph G is a directed acyclic graph (DAG) or
    False if not.

    Parameters
    ----------
    G : NetworkX graph
        A graph

    Returns
    -------
    is_dag : bool
        True if G is a DAG, false otherwise
    """
    if not G.is_directed():
        return False
    try:
        topological_sort(G, reverse=True)
        return True
    except nx.NetworkXUnfeasible:
        return False

def topological_sort(G, nbunch=None, reverse=False):
    """Return a list of nodes in topological sort order.

    A topological sort is a nonunique permutation of the nodes
    such that an edge from u to v implies that u appears before v in the
    topological sort order.

    Parameters
    ----------
    G : NetworkX digraph
        A directed graph

    nbunch : container of nodes (optional)
        Explore graph in specified order given in nbunch

    reverse : bool, optional
        Return postorder instead of preorder if True.
        Reverse mode is a bit more efficient.

    Raises
    ------
    NetworkXError
        Topological sort is defined for directed graphs only. If the
        graph G is undirected, a NetworkXError is raised.

    NetworkXUnfeasible
        If G is not a directed acyclic graph (DAG) no topological sort
        exists and a NetworkXUnfeasible exception is raised.

    Notes
    -----
    This algorithm is based on a description and proof in
    The Algorithm Design Manual [1]_ .

    See also
    --------
    is_directed_acyclic_graph

    References
    ----------
    .. [1] Skiena, S. S. The Algorithm Design Manual  (Springer-Verlag, 1998).
        http://www.amazon.com/exec/obidos/ASIN/0387948600/ref=ase_thealgorithmrepo/
    """
    if not G.is_directed():
        raise nx.NetworkXError(
            "Topological sort not defined on undirected graphs.")

    # nonrecursive version
    seen = set()
    order = []
    explored = set()

    if nbunch is None:
        nbunch = G.nodes_iter()
    for v in nbunch:     # process all vertices in G
        if v in explored:
            continue
        fringe = [v]   # nodes yet to look at
        while fringe:
            w = fringe[-1]  # depth first search
            if w in explored:  # already looked down this branch
                fringe.pop()
                continue
            seen.add(w)     # mark as seen
            # Check successors for cycles and for new nodes
            new_nodes = []
            for n in G[w]:
                if n not in explored:
                    if n in seen:  # CYCLE !!
                        raise nx.NetworkXUnfeasible("Graph contains a cycle.")
                    new_nodes.append(n)
            if new_nodes:   # Add new_nodes to fringe
                fringe.extend(new_nodes)
            else:           # No new nodes so w is fully explored
                explored.add(w)
                order.append(w)
                fringe.pop()    # done considering this node
    if reverse:
        return order
    else:
        return list(reversed(order))

def topological_sort_recursive(G, nbunch=None, reverse=False):
    """Return a list of nodes in topological sort order.

    A topological sort is a nonunique permutation of the nodes such
    that an edge from u to v implies that u appears before v in the
    topological sort order.

    Parameters
    ----------
    G : NetworkX digraph

    nbunch : container of nodes (optional)
        Explore graph in specified order given in nbunch

    reverse : bool, optional
        Return postorder instead of preorder if True.
        Reverse mode is a bit more efficient.

    Raises
    ------
    NetworkXError
        Topological sort is defined for directed graphs only. If the
        graph G is undirected, a NetworkXError is raised.

    NetworkXUnfeasible
        If G is not a directed acyclic graph (DAG) no topological sort
        exists and a NetworkXUnfeasible exception is raised.

    Notes
    -----
    This is a recursive version of topological sort.

    See also
    --------
    topological_sort
    is_directed_acyclic_graph

    """
    if not G.is_directed():
        raise nx.NetworkXError(
            "Topological sort not defined on undirected graphs.")

    def _dfs(v):
        ancestors.add(v)

        for w in G[v]:
            if w in ancestors:
                raise nx.NetworkXUnfeasible("Graph contains a cycle.")

            if w not in explored:
                _dfs(w)

        ancestors.remove(v)
        explored.add(v)
        order.append(v)

    ancestors = set()
    explored = set()
    order = []

    if nbunch is None:
        nbunch = G.nodes_iter()

    for v in nbunch:
        if v not in explored:
            _dfs(v)

    if reverse:
        return order
    else:
        return list(reversed(order))

def is_aperiodic(G):
    """Return True if G is aperiodic.

    A directed graph is aperiodic if there is no integer k > 1 that
    divides the length of every cycle in the graph.

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    aperiodic : boolean
        True if the graph is aperiodic False otherwise

    Raises
    ------
    NetworkXError
        If G is not directed

    Notes
    -----
    This uses the method outlined in [1]_, which runs in O(m) time
    given m edges in G. Note that a graph is not aperiodic if it is
    acyclic as every integer trivial divides length 0 cycles.

    References
    ----------
    .. [1] Jarvis, J. P.; Shier, D. R. (1996),
       Graph-theoretic analysis of finite Markov chains,
       in Shier, D. R.; Wallenius, K. T., Applied Mathematical Modeling:
       A Multidisciplinary Approach, CRC Press.
    """
    if not G.is_directed():
        raise nx.NetworkXError(
            "is_aperiodic not defined for undirected graphs")

    s = next(G.nodes_iter())
    levels = {s: 0}
    this_level = [s]
    g = 0
    l = 1
    while this_level:
        next_level = []
        for u in this_level:
            for v in G[u]:
                if v in levels:  # Non-Tree Edge
                    g = gcd(g, levels[u] - levels[v] + 1)
                else:  # Tree Edge
                    next_level.append(v)
                    levels[v] = l
        this_level = next_level
        l += 1
    if len(levels) == len(G):  # All nodes in tree
        return g == 1
    else:
        return g == 1 and nx.is_aperiodic(G.subgraph(set(G) - set(levels)))

@not_implemented_for('undirected')
def transitive_closure(G):
    """ Returns transitive closure of a directed graph

    The transitive closure of G = (V,E) is a graph G+ = (V,E+) such that
    for all v,w in V there is an edge (v,w) in E+ if and only if there
    is a non-null path from v to w in G.

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    TC : NetworkX DiGraph
        Graph

    Raises
    ------
    NetworkXNotImplemented
        If G is not directed

    References
    ----------
    .. [1] http://www.ics.uci.edu/~eppstein/PADS/PartialOrder.py

    """
    TC = nx.DiGraph()
    TC.add_nodes_from(G.nodes_iter())
    TC.add_edges_from(G.edges_iter())
    for v in G:
        TC.add_edges_from((v, u) for u in nx.dfs_preorder_nodes(G, source=v)
                          if v != u)
    return TC

@not_implemented_for('undirected')
def antichains(G):
    """Generates antichains from a DAG.

    An antichain is a subset of a partially ordered set such that any
    two elements in the subset are incomparable.

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    antichain : generator object

    Raises
    ------
    NetworkXNotImplemented
        If G is not directed

    NetworkXUnfeasible
        If G contains a cycle

    Notes
    -----
    This function was originally developed by Peter Jipsen and Franco Saliola
    for the SAGE project. It's included in NetworkX with permission from the
    authors. Original SAGE code at:

    https://sage.informatik.uni-goettingen.de/src/combinat/posets/hasse_diagram.py

    References
    ----------
    .. [1] Free Lattices, by R. Freese, J. Jezek and J. B. Nation,
       AMS, Vol 42, 1995, p. 226.
    """
    TC = nx.transitive_closure(G)
    antichains_stacks = [([], nx.topological_sort(G, reverse=True))]
    while antichains_stacks:
        (antichain, stack) = antichains_stacks.pop()
        # Invariant:
        #  - the elements of antichain are independent
        #  - the elements of stack are independent from those of antichain
        yield antichain
        while stack:
            x = stack.pop()
            new_antichain = antichain + [x]
            new_stack = [
                t for t in stack if not ((t in TC[x]) or (x in TC[t]))]
            antichains_stacks.append((new_antichain, new_stack))

@not_implemented_for('undirected')
def dag_longest_path(G):
    """Returns the longest path in a DAG

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    path : list
        Longest path

    Raises
    ------
    NetworkXNotImplemented
        If G is not directed

    See also
    --------
    dag_longest_path_length
    """
    dist = {}  # stores [node, distance] pair
    for node in nx.topological_sort(G):
        # pairs of dist,node for all incoming edges
        pairs = [(dist[v][0] + 1, v) for v in G.pred[node]]
        if pairs:
            dist[node] = max(pairs)
        else:
            dist[node] = (0, node)
    node, (length, _) = max(dist.items(), key=lambda x: x[1])
    path = []
    while length > 0:
        path.append(node)
        length, node = dist[node]
    return list(reversed(path))

@not_implemented_for('undirected')
def dag_longest_path_length(G):
    """Returns the longest path length in a DAG

    Parameters
    ----------
    G : NetworkX DiGraph
        Graph

    Returns
    -------
    path_length : int
        Longest path length

    Raises
    ------
    NetworkXNotImplemented
        If G is not directed

    See also
    --------
    dag_longest_path
    """
    path_length = len(nx.dag_longest_path(G)) - 1
    return path_length


text:
#!/usr/bin/env php
<?php

require_once './abstract.php';

/**
 * Mageflow_Connect_Last_Access_Time
 * outputs last access time. It reads it from
 * mageflow_connect/system_info_performance model. It can be either
 * admin or frontend!
 *
 * @category   MFX
 * @package    Mageflow_Connect
 * @subpackage Shell
 * @author     Prototypely Ltd, Estonia <info@prototypely.com>
 * @copyright  Copyright © 2017 Prototypely Ltd, Estonia (http://prototypely.com)
 * @license MIT Copyright (c) 2017 Prototypely Ltd
 * @link       http://mageflow.com/
 */
class Mageflow_Connect_Last_Access_Time extends Mage_Shell_Abstract
{

    /**
     * Shell script business method
     */
    public function run()
    {
        echo $this->getLastAccessTime() . "\n";
    }

    /**
     * Public method that returns last access time of this magento instance
     * @return int
     */
    public function getLastAccessTime()
    {
        $helper = Mage::helper('mageflow_connect');
        if ($helper instanceof Mageflow_Connect_Helper_Data) {
            return $helper->getLastAccessTime();
        }
    }
}

$shell = new Mageflow_Connect_Last_Access_Time();
$shell->run();


text:
Oro\Bundle\CurrencyBundle\OroCurrencyBundle
===================================================

Description:
------------

This bundle provides a way to handle prices and currencies.

Bundle responsibilities:
------------------------

Bundle provides forms for setting price with currency to another objects (for example product).
Also it includes available currencies management from System configuration.

Expected dependencies:
----------------------

Oro\Bundle\ConfigBundle\Config\ConfigManager
Oro\Bundle\ConfigBundle\DependencyInjection\SettingsBuilder
Oro\Bundle\LocaleBundle\Formatter\NumberFormatter
Oro\Bundle\LocaleBundle\Model\LocaleSettings
Oro\Bundle\TestFrameworkBundle\Test\DependencyInjection\ExtensionTestCase
Symfony\Component\Config\Definition\Builder\TreeBuilder
Symfony\Component\Config\Definition\ConfigurationInterface
Symfony\Component\Config\FileLocator
Symfony\Component\DependencyInjection\ContainerBuilder
Symfony\Component\DependencyInjection\Loader
Symfony\Component\Form
Symfony\Component\HttpKernel\Bundle\Bundle
Symfony\Component\HttpKernel\DependencyInjection\Extension
Symfony\Component\Intl\Intl
Symfony\Component\OptionsResolver\Options
Symfony\Component\OptionsResolver\OptionsResolverInterface
Symfony\Component\PropertyAccess\PropertyAccess
Symfony\Component\Validator\Validation
Twig_SimpleFilter
Intl


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.synapse.generated;

import com.azure.core.util.Context;

/** Samples for SqlPoolSensitivityLabels ListRecommended. */
public final class SqlPoolSensitivityLabelsListRecommendedSamples {
    /*
     * x-ms-original-file: specification/synapse/resource-manager/Microsoft.Synapse/stable/2021-06-01/examples/ListSqlPoolSensitivityLabelsWithSourceRecommended.json
     */
    /**
     * Sample code: Gets the recommended sensitivity labels of a given SQL Analytics pool.
     *
     * @param manager Entry point to SynapseManager.
     */
    public static void getsTheRecommendedSensitivityLabelsOfAGivenSQLAnalyticsPool(
        com.azure.resourcemanager.synapse.SynapseManager manager) {
        manager
            .sqlPoolSensitivityLabels()
            .listRecommended("myRG", "myServer", "myDatabase", null, null, null, Context.NONE);
    }
}


text:
class VatPeriodJob < ApplicationJob
  queue_as :vat_period_jobs

  def perform(vat_period_id, job_name)
    vat_period = VatPeriod.find(vat_period_id)
    if VatPeriod::VALID_JOBS.include?(job_name)
      Rails.logger.info "will execute #{job_name} on #{vat_period.id}"
      vat_period.send(job_name)
    else
      Rails.logger.info "** Job::VatPeriodJob unknown job_name(#{job_name})"
    end
  rescue ActiveRecord::RecordNotFound
    Rails.logger.info '** Job::VatPeriodJob could not find ' \
      "object with id #{vat_period_id}"
  end
end


text:
var classorg_1_1onosproject_1_1net_1_1config_1_1impl_1_1NetworkConfigManagerTest_1_1MockSubjectFactory =
[
    [ "MockSubjectFactory", "classorg_1_1onosproject_1_1net_1_1config_1_1impl_1_1NetworkConfigManagerTest_1_1MockSubjectFactory.html#a3f6786d1e385fccbc6403fd8b5c94bd1", null ],
    [ "createSubject", "classorg_1_1onosproject_1_1net_1_1config_1_1impl_1_1NetworkConfigManagerTest_1_1MockSubjectFactory.html#a409bb72f56db7f6b2bd57e507d075a85", null ]
];


text:
.. currentmodule:: motor.motor_tornado

Motor Tailable Cursor Example
=============================

By default, MongoDB will automatically close a cursor when the client has
exhausted all results in the cursor. However, for capped collections you may
use a tailable cursor that remains open after the client exhausts the results
in the initial cursor.

The following is a basic example of using a tailable cursor to tail the oplog
of a replica set member:

.. code-block:: python

    from asyncio import sleep
    from pymongo.cursor import CursorType

    async def tail_oplog_example():
        oplog = client.local.oplog.rs
        first = await oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
        print(first)
        ts = first['ts']

        while True:
            # For a regular capped collection CursorType.TAILABLE_AWAIT is the
            # only option required to create a tailable cursor. When querying the
            # oplog, the oplog_replay option enables an optimization to quickly
            # find the 'ts' value we're looking for. The oplog_replay option
            # can only be used when querying the oplog. Starting in MongoDB 4.4
            # this option is ignored by the server as queries against the oplog
            # are optimized automatically by the MongoDB query engine.
            cursor = oplog.find({'ts': {'$gt': ts}},
                                cursor_type=CursorType.TAILABLE_AWAIT,
                                oplog_replay=True)
            while cursor.alive:
                async for doc in cursor:
                    ts = doc['ts']
                    print(doc)
                # We end up here if the find() returned no documents or if the
                # tailable cursor timed out (no new documents were added to the
                # collection for more than 1 second).
                await sleep(1)

.. seealso:: `Tailable cursors <http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/>`_


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 1: 105 (1957)

#### Original name
Meliola crenata var. bunchosiae Hansf.

### Remarks
null


text:
when: generateAfter
---
echo 'hello from bash in shell collection' >> $DOCUMENT_OUTPATH.html


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

namespace Microsoft.Azure.Commands.Scheduler.Models
{
    using Microsoft.Azure.Management.Scheduler.Models;

    public class PSJobActionParams
    {
        /// <summary>
        /// Gets or sets job action type.
        /// </summary>
        public JobActionType JobActionType { get; set; }

        /// <summary>
        /// Gets or sets job http action.
        /// </summary>
        public PSHttpJobActionParams HttpJobAction { get; set; }

        /// <summary>
        /// Gets or sets job storage action.
        /// </summary>
        public PSStorageJobActionParams StorageJobAction { get; set; }

        /// <summary>
        /// Gets or sets service bus action.
        /// </summary>
        public PSServiceBusParams ServiceBusAction { get; set; }
    }
}


text:
namespace aura {
class WindowTreeHost;
}  // namespace aura

namespace base {
class RunLoop;
}  // namespace base

namespace content {
class BrowserContext;
}  // namespace content

namespace display {
class Screen;
}  // namespace display

namespace gfx {
class Size;
}  // namespace gfx

namespace ui {
class InputMethod;
#if defined(OS_CHROMEOS)
class UserActivityDetector;
class UserActivityPowerManagerNotifier;
#endif
}  // namespace ui

namespace wm {
class CompoundEventFilter;
class CursorManager;
class FocusController;
}  // namespace wm

namespace extensions {
class AppWindowClient;

// Simple desktop controller for app_shell. Associates each display with a
// RootWindowController. Adds AppWindows by passing them to the nearest
// RootWindowController.
class ShellDesktopControllerAura
    : public DesktopController,
      public RootWindowController::DesktopDelegate,
#if defined(OS_CHROMEOS)
      public chromeos::PowerManagerClient::Observer,
      public display::DisplayConfigurator::Observer,
#endif
      public ui::internal::InputMethodDelegate,
      public KeepAliveStateObserver {
 public:
  explicit ShellDesktopControllerAura(content::BrowserContext* browser_context);
  ~ShellDesktopControllerAura() override;

  // DesktopController:
  void Run() override;
  void AddAppWindow(AppWindow* app_window, gfx::NativeWindow window) override;
  void CloseAppWindows() override;

  // RootWindowController::DesktopDelegate:
  void CloseRootWindowController(
      RootWindowController* root_window_controller) override;

#if defined(OS_CHROMEOS)
  // chromeos::PowerManagerClient::Observer:
  void PowerButtonEventReceived(bool down,
                                const base::TimeTicks& timestamp) override;

  // display::DisplayConfigurator::Observer:
  void OnDisplayModeChanged(
      const display::DisplayConfigurator::DisplayStateList& displays) override;
#endif

  // ui::internal::InputMethodDelegate:
  ui::EventDispatchDetails DispatchKeyEventPostIME(
      ui::KeyEvent* key_event) override;

  // KeepAliveStateObserver:
  void OnKeepAliveStateChanged(bool is_keeping_alive) override;
  void OnKeepAliveRestartStateChanged(bool can_restart) override;

  // Returns the WindowTreeHost for the primary display.
  aura::WindowTreeHost* GetPrimaryHost();

  // Returns all root windows managed by RootWindowControllers.
  aura::Window::Windows GetAllRootWindows();

  // Updates the bounds of |app_window|. This may involve reparenting the window
  // to a different root window if the new bounds are in a different display.
  void SetWindowBoundsInScreen(AppWindow* app_window, const gfx::Rect& bounds);

 protected:
  // Creates and sets the aura clients and window manager stuff. Subclass may
  // initialize different sets of the clients.
  virtual void InitWindowManager();

  // Removes all RootWindowControllers and tears down our aura clients.
  virtual void TearDownWindowManager();

 private:
  // Creates a RootWindowController to host AppWindows.
  std::unique_ptr<RootWindowController> CreateRootWindowControllerForDisplay(
      const display::Display& display);

  // Removes handlers from the RootWindowController so it can be destroyed.
  void TearDownRootWindowController(RootWindowController* root);

  // Quits if there are no app windows, and no keep-alives waiting for apps to
  // relaunch.
  void MaybeQuit();

#if defined(OS_CHROMEOS)
  // Returns the desired dimensions of the RootWindowController from the command
  // line, or falls back to a default size.
  gfx::Size GetStartingWindowSize();

  // Returns the dimensions (in pixels) of the primary display, or an empty size
  // if the dimensions can't be determined or no display is connected.
  gfx::Size GetPrimaryDisplaySize();
#endif

  content::BrowserContext* const browser_context_;

#if defined(OS_CHROMEOS)
  std::unique_ptr<display::DisplayConfigurator> display_configurator_;
#endif

  std::unique_ptr<display::Screen> screen_;

  std::unique_ptr<wm::CompoundEventFilter> root_window_event_filter_;

  // Mapping from display ID to the RootWindowController created for that
  // display.
  std::map<int64_t, std::unique_ptr<RootWindowController>>
      root_window_controllers_;

  std::unique_ptr<ui::InputMethod> input_method_;

  std::unique_ptr<wm::FocusController> focus_controller_;

  std::unique_ptr<wm::CursorManager> cursor_manager_;

#if defined(OS_CHROMEOS)
  std::unique_ptr<ui::UserActivityDetector> user_activity_detector_;
  std::unique_ptr<ui::UserActivityPowerManagerNotifier> user_activity_notifier_;
#endif

  std::unique_ptr<AppWindowClient> app_window_client_;

  // NativeAppWindow::Close() deletes the AppWindow.
  std::list<AppWindow*> app_windows_;

  // A pointer to the main message loop if this is run by ShellBrowserMainParts.
  base::RunLoop* run_loop_ = nullptr;

  DISALLOW_COPY_AND_ASSIGN(ShellDesktopControllerAura);
};

}  // namespace extensions

#endif  // EXTENSIONS_SHELL_BROWSER_SHELL_DESKTOP_CONTROLLER_AURA_H_


text:
package org.ams.repstats.utils;

import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import org.ams.repstats.entity.ProjectObs;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;

/**
 * Необходим для редактирования даты в ячейке таблицы с проектами
 */
public class ProjectTableDateEditingCell extends TableCell<ProjectObs, Date> {

    private DatePicker datePicker;

    public ProjectTableDateEditingCell() {
    }

    @Override
    public void startEdit() {
        if (!isEmpty()) {
            super.startEdit();
            createDatePicker();
            setText(null);
            setGraphic(datePicker);
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
        String rez = dateTimeFormatter.format(getDate());
        setText(rez);
        setGraphic(null);
    }

    @Override
    public void updateItem(Date item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (datePicker != null) {
                    datePicker.setValue(getDate());
                }
                setText(null);
                setGraphic(datePicker);
            } else {
                setText(getDate().format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)));
                setGraphic(null);
            }
        }
    }

    private void createDatePicker() {
        datePicker = new DatePicker(getDate());
        datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
        datePicker.setOnAction((e) -> {
            commitEdit(Date.from(datePicker.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant()));
        });

    }

    private LocalDate getDate() {
        if (getItem() instanceof java.sql.Date) {
            LocalDate date = ((java.sql.Date) getItem()).toLocalDate();
            return date;
        }
        return getItem() == null ? LocalDate.now() : getItem().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
}