text:
#ifndef AudioIOCallback_h
#define AudioIOCallback_h

#include "public/platform/WebAudioDevice.h"

namespace blink {

class AudioBus;

// Abstract base-class for isochronous audio I/O client.
class AudioIOCallback {
public:
    using StreamPosition = WebAudioDevice::StreamPosition;
    // render() is called periodically to get the next render quantum of audio into destinationBus.
    // Optional audio input is given in sourceBus (if it's not 0).
    virtual void render(AudioBus* sourceBus, AudioBus* destinationBus, size_t framesToProcess, const StreamPosition& device_position) = 0;

    virtual ~AudioIOCallback() { }
};

} // namespace blink

#endif // AudioIOCallback_h


text:
package ezbake.security.permissions;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import ezbake.base.thrift.AdvancedMarkings;
import ezbake.base.thrift.Authorizations;
import ezbake.base.thrift.Permission;
import ezbake.base.thrift.PlatformObjectVisibilities;
import ezbake.base.thrift.Visibility;

/**
 * Used for evaluating bulk {@link ezbake.base.thrift.Visibility} objects against a particular {@link
 * ezbake.base.thrift.Authorizations} object. PermissionEvaluator caches the results of each comparison to allow faster
 * evaluation. All evaluation operations are performed with {@link ezbake.security.permissions.PermissionUtils}.
 */
public class PermissionEvaluator {
    /**
     * Default size for caches in this class.
     */
    private static final int DEFAULT_CACHE_SIZE = 500;

    /**
     * The Authorizations object to compare with Visibility objects.
     */
    private final Authorizations auths;

    /**
     * Keeps track of the result of the comparison of {@code auths} with the important parts of a {@link
     * ezbake.base.thrift.AdvancedMarkings} object.
     */
    private LoadingCache<AdvMarkingComponents, Set<Permission>> advancedMarkingsEvaluations;

    /**
     * Keeps track of the result of the comparison of {@code authsFormal} with a particular formal visibility.
     */
    private LoadingCache<String, Boolean> formalVisibilityEvaluations;

    /**
     * Construct a new PermissionEvaluator.
     *
     * @param auths The Authorizations object against which to evaluate Visibility objects. Methods on this class are
     * thread safe.
     * @param cacheSize The number of visibilities to cache while performing evaluations.
     */
    public PermissionEvaluator(Authorizations auths, int cacheSize) {
        this.auths = auths;
        constructCaches(cacheSize);
    }

    /**
     * Construct a new PermissionEvaluator, this constructor uses the default cache size. Cache size can be configured
     * via an overloaded constructor.
     *
     * @param auths The Authorizations object against which to evaluate Visibility objects. Methods on this class are
     * thread safe.
     */
    public PermissionEvaluator(Authorizations auths) {
        this(auths, DEFAULT_CACHE_SIZE);
    }

    /**
     * Evaluate a Visibility object against this object's authorizations and cache the result. This method is thread
     * safe.
     *
     * @param visibility The Visibility to evaluate against this objects Authorizations.
     * @return The permissions this evaluator's Authorizations have against the passed in Visibility.
     */
    public Set<Permission> getPermissions(Visibility visibility) {
        String formalVisibility = visibility.getFormalVisibility();

        if (StringUtils.isBlank(formalVisibility) || formalVisibilityEvaluations.getUnchecked(formalVisibility)) {
            AdvancedMarkings advancedMarkings = visibility.getAdvancedMarkings();
            if (advancedMarkings == null) {
                return PermissionUtils.ALL_PERMS;
            }

            return advancedMarkingsEvaluations.getUnchecked(
                    new AdvMarkingComponents(
                            visibility.getAdvancedMarkings().externalCommunityVisibility,
                            visibility.getAdvancedMarkings().getPlatformObjectVisibility()));
        } else {
            return PermissionUtils.NO_PERMS;
        }
    }

    /**
     * Builds the caches this class uses while performing evaluations.
     *
     * @param cacheSize The maximum size of these caches. Evictions are based on frequency with least used being removed
     * first.
     */
    private void constructCaches(int cacheSize) {
        advancedMarkingsEvaluations = CacheBuilder.newBuilder().maximumSize(cacheSize).build(
                new CacheLoader<AdvMarkingComponents, Set<Permission>>() {
                    private final Visibility vis = new Visibility().setAdvancedMarkings(new AdvancedMarkings());

                    @Override
                    public Set<Permission> load(AdvMarkingComponents amc) {
                        vis.getAdvancedMarkings().setPlatformObjectVisibility(amc.getPov());
                        vis.getAdvancedMarkings().setExternalCommunityVisibility(amc.getEcv());
                        return PermissionUtils.getPermissions(auths, vis, false);
                    }
                });

        formalVisibilityEvaluations = CacheBuilder.newBuilder().maximumSize(cacheSize).build(
                new CacheLoader<String, Boolean>() {
                    @Override
                    public Boolean load(String formalVisibility) {
                        return PermissionUtils
                                .validateVisibilityExpression(auths.getFormalAuthorizations(), formalVisibility);
                    }
                });
    }

    /**
     * This contains all the necessary components for comparing and Authorizations object to a Visibility object's
     * AdvancedMarkings. Can be used as a key in a Guava cache. Basically a POJO.
     */
    private static class AdvMarkingComponents {
        /**
         * External community visibility, should be from the same AdvancedMarkings object as {@code pov}.
         */
        private final String ecv;

        /**
         * PlatformObjectVisibilities, should be from the same AdvancedMarkings object as {@code ecv}.
         */
        private final PlatformObjectVisibilities pov;

        /**
         * Constructor to initialize this POJO's members.
         *
         * @param ecv Represents an AdvancedMarkings' 'External community visibility'.
         * @param pov A PlatformObjectVisibilities from an AdvancedMarking.
         */
        private AdvMarkingComponents(String ecv, PlatformObjectVisibilities pov) {
            this.ecv = ecv;
            this.pov = pov;
        }

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

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            final AdvMarkingComponents that = (AdvMarkingComponents) o;

            if (ecv != null ? !ecv.equals(that.ecv) : that.ecv != null) {
                return false;
            }
            if (pov != null ? !pov.equals(that.pov) : that.pov != null) {
                return false;
            }

            return true;
        }

        /**
         * Gets a PlatformObjectVisibilities.
         *
         * @return The PlatformObjectVisibilities contained by this object.
         */
        public PlatformObjectVisibilities getPov() {
            return pov;
        }

        /**
         * Gets a String that represents an external community visibility.
         *
         * @return The external community visibility String contained by this object.
         */
        public String getEcv() {
            return ecv;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text: google-site-verification: google9c871aa03d2784b6.html


text:
Scaffold default configuration
Cross-platform $HOME (or just config)
Server/Daemon


text:
function kernDisplay(kern, varargin)

% KERNDISPLAY Display the parameters of the kernel.
% FORMAT
% DESC displays the parameters of the kernel and the kernel type to
% the console.
% ARG kern : the kernel to display.
%
% FORMAT does the same as above, but indents the display according to the amount specified.
% ARG kern : the kernel to display.
% ARG spacing : how many spaces to indent the display of the kernel by.
%
% SEEALSO modelDisplay
%
% COPYRIGHT Neil D. Lawrence, 2006, 2005, 2004

% GPMAT

fhandle = str2func([kern.type 'KernDisplay']);
fhandle(kern, varargin{:});


text:
package models

import (
	"time"
)

// ClairVulnTimestampTable is the name of the table that tracks the timestamp of vulnerability in Clair.
const ClairVulnTimestampTable = "clair_vuln_timestamp"

// ClairVulnTimestamp represents a record in DB that tracks the timestamp of vulnerability in Clair.
type ClairVulnTimestamp struct {
	ID            int64     `orm:"pk;auto;column(id)" json:"-"`
	Namespace     string    `orm:"column(namespace)" json:"namespace"`
	LastUpdate    time.Time `orm:"column(last_update)" json:"-"`
	LastUpdateUTC int64     `orm:"-" json:"last_update"`
}

// TableName is required by beego to map struct to table.
func (ct *ClairVulnTimestamp) TableName() string {
	return ClairVulnTimestampTable
}

// ClairLayer ...
type ClairLayer struct {
	Name           string            `json:"Name,omitempty"`
	NamespaceNames []string          `json:"NamespaceNames,omitempty"`
	Path           string            `json:"Path,omitempty"`
	Headers        map[string]string `json:"Headers,omitempty"`
	ParentName     string            `json:"ParentName,omitempty"`
	Format         string            `json:"Format,omitempty"`
	Features       []ClairFeature    `json:"Features,omitempty"`
}

// ClairFeature ...
type ClairFeature struct {
	Name            string               `json:"Name,omitempty"`
	NamespaceName   string               `json:"NamespaceName,omitempty"`
	VersionFormat   string               `json:"VersionFormat,omitempty"`
	Version         string               `json:"Version,omitempty"`
	Vulnerabilities []ClairVulnerability `json:"Vulnerabilities,omitempty"`
	AddedBy         string               `json:"AddedBy,omitempty"`
}

// ClairVulnerability ...
type ClairVulnerability struct {
	Name          string                 `json:"Name,omitempty"`
	NamespaceName string                 `json:"NamespaceName,omitempty"`
	Description   string                 `json:"Description,omitempty"`
	Link          string                 `json:"Link,omitempty"`
	Severity      string                 `json:"Severity,omitempty"`
	Metadata      map[string]interface{} `json:"Metadata,omitempty"`
	FixedBy       string                 `json:"FixedBy,omitempty"`
	FixedIn       []ClairFeature         `json:"FixedIn,omitempty"`
}

// ClairError ...
type ClairError struct {
	Message string `json:"Message,omitempty"`
}

// ClairLayerEnvelope ...
type ClairLayerEnvelope struct {
	Layer *ClairLayer `json:"Layer,omitempty"`
	Error *ClairError `json:"Error,omitempty"`
}

// ClairNotification ...
type ClairNotification struct {
	Name     string                        `json:"Name,omitempty"`
	Created  string                        `json:"Created,omitempty"`
	Notified string                        `json:"Notified,omitempty"`
	Deleted  string                        `json:"Deleted,omitempty"`
	Limit    int                           `json:"Limit,omitempty"`
	Page     string                        `json:"Page,omitempty"`
	NextPage string                        `json:"NextPage,omitempty"`
	Old      *ClairVulnerabilityWithLayers `json:"Old,omitempty"`
	New      *ClairVulnerabilityWithLayers `json:"New,omitempty"`
}

// ClairNotificationEnvelope ...
type ClairNotificationEnvelope struct {
	Notification *ClairNotification `json:"Notification,omitempty"`
	Error        *ClairError        `json:"Error,omitempty"`
}

// ClairVulnerabilityWithLayers ...
type ClairVulnerabilityWithLayers struct {
	Vulnerability                         *ClairVulnerability     `json:"Vulnerability,omitempty"`
	OrderedLayersIntroducingVulnerability []ClairOrderedLayerName `json:"OrderedLayersIntroducingVulnerability,omitempty"`
}

// ClairOrderedLayerName ...
type ClairOrderedLayerName struct {
	Index     int    `json:"Index"`
	LayerName string `json:"LayerName"`
}

// ClairVulnerabilityStatus reflects the readiness and freshness of vulnerability data in Clair,
// which will be returned in response of systeminfo API.
type ClairVulnerabilityStatus struct {
	OverallUTC int64                     `json:"overall_last_update,omitempty"`
	Details    []ClairNamespaceTimestamp `json:"details,omitempty"`
}

// ClairNamespaceTimestamp is a record to store the clairname space and the timestamp,
// in practice different namespace in Clair maybe merged into one, e.g. ubuntu:14.04 and ubuntu:16.4 maybe merged into ubuntu and put into response.
type ClairNamespaceTimestamp struct {
	Namespace string `json:"namespace"`
	Timestamp int64  `json:"last_update"`
}

// ClairNamespace ...
type ClairNamespace struct {
	Name          string `json:"Name,omitempty"`
	VersionFormat string `json:"VersionFormat,omitempty"`
}

// ClairNamespaceEnvelope ...
type ClairNamespaceEnvelope struct {
	Namespaces *[]ClairNamespace `json:"Namespaces,omitempty"`
	Error      *ClairError       `json:"Error,omitempty"`
}


text:
package com.alibaba.dubbo.rpc.cluster.support;

import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.Result;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.cluster.Directory;
import com.alibaba.dubbo.rpc.cluster.LoadBalance;

import java.util.List;

/**
 * AvailableCluster
 *
 */
public class AvailableClusterInvoker<T> extends AbstractClusterInvoker<T> {

    public AvailableClusterInvoker(Directory<T> directory) {
        super(directory);
    }

    public Result doInvoke(Invocation invocation, List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
        for (Invoker<T> invoker : invokers) {
            if (invoker.isAvailable()) {
                return invoker.invoke(invocation);
            }
        }
        throw new RpcException("No provider available in " + invokers);
    }

}


text:
"use strict";

const ChinoAuth         = require("./auth");
const ChinoUsers        = require("./users");
const ChinoUserSchemas  = require("./userSchemas");
const ChinoGroups       = require("./groups");
const ChinoApplications = require("./applications");
const ChinoRepositories = require("./repositories");
const ChinoSchemas      = require("./schemas");
const ChinoDocuments    = require("./documents");
const ChinoPerms        = require("./perms");
const ChinoBlobs        = require("./blobs");
const ChinoCollections  = require("./collections");
const ChinoSearch       = require("./search");

class Chino {
  /**
   * @constructor
   * @param {string} baseUrl
   * @param {string} customerId
   * @param {string | null} customerKey
   */

  constructor(baseUrl = "", customerId = "", customerKey = null) {
    this.baseUrl = baseUrl;

    // create Chino objects
    this.users        = new ChinoUsers(this.baseUrl, customerId, customerKey);
    this.userSchemas  = new ChinoUserSchemas(this.baseUrl, customerId, customerKey);
    this.groups       = new ChinoGroups(this.baseUrl, customerId, customerKey);
    this.applications = new ChinoApplications(this.baseUrl, customerId, customerKey);
    this.repositories = new ChinoRepositories(this.baseUrl, customerId, customerKey);
    this.schemas      = new ChinoSchemas(this.baseUrl, customerId, customerKey);
    this.documents    = new ChinoDocuments(this.baseUrl, customerId, customerKey);
    this.perms        = new ChinoPerms(this.baseUrl, customerId, customerKey);
    this.blobs        = new ChinoBlobs(this.baseUrl, customerId, customerKey);
    this.collections  = new ChinoCollections(this.baseUrl, customerId, customerKey);
    this.search       = new ChinoSearch(this.baseUrl, customerId, customerKey);
  }

  /** Set up for Chino object an Auth object
   *  using previous created application id & secret
   *
   * @param appId     {string}
   * @param appSecret {string}
   */
  setAuth(appId, appSecret) {
    this.auth = new ChinoAuth(this.baseUrl, appId, appSecret);
  }
}

module.exports = Chino;


text:
from typing import Union

def foo() -> <warning descr="Python versions 2.7, 3.5, 3.6, 3.7, 3.8, 3.9 do not allow writing union types as X | Y"><caret>int | Union[str, bool]</warning>:
    return 42


text:
import React from 'react'
import {renderToString} from 'react-dom/server'
import App from './app'

const googleAnalytics = process.env.NODE_ENV === 'production' ? `` : ''

export const renderFullPage = (component, initialState, options) => `<!doctype html>

        <meta name='viewport' content='width=device-width, initial-scale=1.0'/>
        <link rel='stylesheet' type="text/css" href='/static/${options.cssChecksum}/styles.css'/>
        <link rel='shortcut icon' type='image/png' href='/img/favicon.png'/>
        <meta name="description" content="Lukkarimaatti++ timetable tool for LUT students"/>
        ${googleAnalytics}
        <title>Lukkarimaatti++</title>

${renderToString(<App component={component} state={initialState}></App>)}

    `


text:
"""Classificateur de publications.

Classifie les publications reçues suivant le médium
d'apparition de celles-ci (voir publications.py pour
les types de publications gérés.
"""

import re

__author__ = "Anas Hilama, Moncef Baazet"

class Classifier(object):
    def __init__(self, pubs_types):
        """Construit un classificateur, qui est en fait un dictionnaire
        associant à chaque expression régulière le type de publication
        qu'elle reconnait."""
        self.classtor = {}
        for pty in pubs_types:
            for i, regexp in enumerate(pty.REGEXPS):
                self.classtor[regexp] = (pty, pty.REGEXPS_OPTS[i])

    def get_classified(self, input_gen):
        """Génére, pour chaque publication fournie par input_gen,
        une représentation de cette publication classifiée, suivant
        qu'elle représente une publication de conférence, de journal, etc."""
        for pub in input_gen:
            for regxp, (pub_type, regxp_opt) in self.classtor.items():
                if regxp_opt == -1:
                    res = re.search(regxp, pub)
                else:
                    res = re.search(regxp, pub, regxp_opt)

                if res:
                    yield (pub_type, pub)
                    break


text:
<Record>
<Term>Tridihexethyl</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<ParentTerm>Antimuscarinic Agent</ParentTerm>
<ClassificationPath>Chemicals_and_Drugs_Kind/Drug, Food, Chemical or Biomedical Material/Pharmacologic Substance/Adjuvant/Anticholinergic Agent/Antimuscarinic Agent/Tridihexethyl Chloride</ClassificationPath>
<BroaderTerm>Chemicals_and_Drugs_Kind</BroaderTerm>
<BroaderTerm>Pharmacologic Substance</BroaderTerm>
<BroaderTerm>Tridihexethyl Chloride</BroaderTerm>
<BroaderTerm>Adjuvant</BroaderTerm>
<BroaderTerm>Antimuscarinic Agent</BroaderTerm>
<BroaderTerm>Anticholinergic Agent</BroaderTerm>
<BroaderTerm>Drug, Food, Chemical or Biomedical Material</BroaderTerm>
<Synonym>Tridihexethyl</Synonym>
<Synonym>Tridihexethyl Chloride</Synonym>
<Synonym>Tridihexethyl chloride</Synonym>
<Synonym>TRIDIHEXETHYL CHLORIDE</Synonym>
<Synonym>Pathilon</Synonym>
<Source>FDA Registry</Source>
<Source>NCI Thesaurus</Source>
</Record>


text:
package ru.dso.nano.v3.analyzer.gui;

public interface KnobsListener {
    void onKnob1PositionChanged(int newValue);
    void onKnob2PositionChanged(int newValue);
}


text:
from heatclient.common import template_format
from heatclient.common import template_utils
import json

def get_fields(template_file, params):
    tpl_files, template = template_utils.get_template_contents(template_file = template_file)
    fields = {
        'stack_name': 'teste',
        'parameters': params,
        'template': template,
        'files': dict(list(tpl_files.items())),
    }
    return fields

template_file = "/home/jmhal/repositorios/infraservice/tests/heat_templates/cluster.yaml"

params = {}
params['image'] = 'Ubuntu1404'
params['flavor'] = 'shelf.medium'
params['key'] = 'joaoalencar'
#params['private_network'] = 'demo-net'
params['public_network'] = 'ext-net'
params['cluster_size'] = '4'

print json.dumps(get_fields(template_file,params))


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

  <title>Classes [Robotstxt]</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="rdoc-style.css" type="text/css" />
  <base target="docwin" />

Classes

    Robotstxt

    Robotstxt::Parser


text:
Ruby client for the OpenAdstream API

[travis]: http://travis-ci.org/realmedia/oas-ruby-client
[gemnasium]: https://gemnasium.com/realmedia/oas-ruby-client

## Installation

`oas` is available through [Rubygems](http://rubygems.org/gems/oas) and can be installed via:

    gem install oas

## Usage

Applications that make requests on behalf a single user to a single account can pass configuration options as a block to the `OAS.configure` method.

```ruby
OAS.configure do |config|
  config.endpoint = OAS_ENDPOINT
  config.account  = OAS_ACCOUNT
  config.username = OAS_USERNAME
  config.password = OAS_PASSWORD
end
```
Applications that make requests on behalf of multiple users to multiple accounts should avoid using the global configuration and instantiate `OAS::Client` objects. If the endpoint is the same, you can specify it globally.

```ruby
OAS.configure do |config|
  config.endpoint = OAS_ENDPOINT
end

client = OAS::Client.new(
  :account  => "oas_account",
  :username => "oas_username",
  :password => "oas_password"
)
```
Requests should be created using an `OAS::AdXML` object. Each request type will yield a `Nokogiri::XML::Builder` object.

```ruby
doc = OAS::AdXML.new
doc.request do |req|
  req.Advertiser do |xml|
    xml.Database(:action => 'read') {
      xml.Advertiser {
        xml.Id "DPadvtest"
      }
    }
  end
end
```
Multiple requests can be sent in the same call.

```ruby
doc = OAS::AdXML.new
doc.request do |req|
  req.Site do |xml|
    xml.Database(:action => "read") {
      xml.Site {
        xml.Id "247media"
      }
    }
  end
  req.Site do |xml|
    xml.Database(:action => "read") {
      xml.Site {
        xml.Id "realmedia"
      }
    }
  end
end
```
Executing the request

```ruby
adxml = OAS.execute(doc) # or client.execute(doc)
adxml.each_response do |res|
  if res.success?
    # res.to_hash
  else
    # res.error_code
    # res.error_text
  end
end
```

## Copyright
Copyright (c) 2011 Realmedia Latin America.
See [LICENSE](https://github.com/realmedia/oas-ruby-client/blob/master/LICENSE) for details.


text:
@extends(site()->partial('core::%s.layouts.blank'))

@section('content')

Dashboard

                        Oops The Page you're looking for couldn't be found

@endsection


text:
package base

import (
	"fmt"
	"sort"
	"strings"

	"github.com/Alluxio/alluxio/pkg/common"
	units "github.com/docker/go-units"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
)

// Node capacity info
type NodeInfo struct {
	name                     string
	node                     *corev1.Node
	avaialbleStorageCapacity uint64
}

// Sort the NodeInfo by
type SortNodeInfoByCapacity []NodeInfo

func (n NodeInfo) GetDetails() *corev1.Node {
	return n.node
}

func (n NodeInfo) GetName() string {
	return n.name
}

func (n NodeInfo) GetAvailableStorageCapacity() uint64 {
	return n.avaialbleStorageCapacity
}

func (n NodeInfo) GetAvailableStorageCapacityToGiB() string {
	return fmt.Sprintf("%dGB", n.avaialbleStorageCapacity/1024/1024/1024)
}

func (n NodeInfo) GetAvailableStorageCapacityToMiB() string {
	return fmt.Sprintf("%dMB", n.avaialbleStorageCapacity/1024/1024)
}

func (n NodeInfo) GetAvailableStorageCapacityToKiB() string {
	return fmt.Sprintf("%dKB", n.avaialbleStorageCapacity/1024)
}

// Sort from large to small
func (s SortNodeInfoByCapacity) Len() int      { return len(s) }
func (s SortNodeInfoByCapacity) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortNodeInfoByCapacity) Less(i, j int) bool {
	// return s[i].CreatedAt.Before(s[j].CreatedAt)
	// return s[i].LastTransitionTime.Time.After(s[j].LastTransitionTime.Time)
	return s[i].avaialbleStorageCapacity > s[j].avaialbleStorageCapacity
}

// make sort nodeInfo by capacity
func makeSortNodeInfoByCapacity(nodes []NodeInfo) []NodeInfo {
	newNodes := make(SortNodeInfoByCapacity, 0, len(nodes))
	for _, c := range nodes {
		newNodes = append(newNodes, c)
	}
	sort.Sort(newNodes)
	return []NodeInfo(newNodes)
}

// Get selected node
func getSelectedNodelistAndCapacity(nodes []NodeInfo, clusterCapacity uint64, datasetCapacity uint64) (selectedNodes []NodeInfo, currentCapacity uint64) {
	currentCapacity = clusterCapacity
	if currentCapacity <= datasetCapacity {
		selectedNodes = nodes
	} else {
		selectedNodes = []NodeInfo{}
		currentCapacity = 0
		// index := 0
		for i := 0; i < len(nodes); i++ {
			if currentCapacity < datasetCapacity {
				selectedNodes = append(selectedNodes, nodes[i])
				currentCapacity += nodes[i].avaialbleStorageCapacity
			} else {
				// TODO (cheyang) Optimize
				break
			}
		}
	}

	// Fot now, show the current capacity
	// if currentCapacity > datasetCapacity {
	// 	currentCapacity = datasetCapacity
	// }

	return selectedNodes, currentCapacity
}

// Get AvailableStorageCapacity
func (b *TemplateEngine) GetAvailableStorageCapacityOfNode(node corev1.Node) (available uint64, err error) {

	// 1. Get available memory resource in node
	totalAvailableStorage := node.Status.Allocatable[corev1.ResourceMemory]
	if common.CacheStoreType == "DISK" {
		totalAvailableStorage = node.Status.Allocatable[corev1.ResourceEphemeralStorage]
	}
	b.Log.Info("Get totalAvailableStorage of the node", "node", node.Name,
		"CacheStoreType", common.CacheStoreType,
		"totalAvailableStorage", totalAvailableStorage.Value())
	// allocatableStorage := uint64(float64(&totalAvailableStorage).Value()) * common.PercentageOfNodeStorageCapacity / 100)
	// m := int64(math.Ceil(float64(memory.Value()) / float64(divisor.Value())))
	//  	return strconv.FormatInt(m, 10), nil
	allocatableStorage := uint64(float64(totalAvailableStorage.Value()) * common.PercentageOfNodeStorageCapacity / 100)
	knownDatasetStorageMap := map[string]resource.Quantity{}

	var usedByDataset uint64 = 0

	reserved, err := units.RAMInBytes(common.ReservedNodeStorageCapacity)
	if err != nil {
		return 0, err
	}

	// 2. Get used by dataset
	for _, runtime := range common.RUNTIMES {
		labelNamePrefix := common.LabelAnnotationStorageCapacityPrefix + "raw-" + runtime + "-"
		for label, value := range node.Labels {
			if label == labelNamePrefix+b.Config.Name {
				b.Log.V(1).Info("The node is skiped due to the dataset is already here",
					"dataset",
					b.Config.Name,
					"node",
					node.Name)
				return 0, nil
			}

			if strings.Contains(label, labelNamePrefix) {
				q, err := resource.ParseQuantity(value)
				if err != nil {
					return 0, err
				}
				knownDatasetStorageMap[label] = q
			}
		}
	}

	for _, value := range knownDatasetStorageMap {
		usedByDataset += uint64(value.Value())
	}

	if allocatableStorage < usedByDataset+uint64(reserved) {
		available = 0
	} else {
		available = allocatableStorage - usedByDataset - uint64(reserved)
	}

	b.Log.Info("Get available storage from Node",
		"node", node.Name,
		"allocatableStorage", units.BytesSize(float64(allocatableStorage)),
		"usedByDataset", units.BytesSize(float64(usedByDataset)),
		"reserved", units.BytesSize(float64(reserved)),
		"available", units.BytesSize(float64(available)))
	return available, nil

}


text:
namespace {

// XORs a memory range into another memory range.
void memxor(void* dst, const void* src, size_t num_bytes) {
  uint8_t* dst_ptr = reinterpret_cast<uint8_t*>(dst);
  const uint8_t* src_ptr = reinterpret_cast<const uint8_t*>(src);

  for (size_t i = 0; i < num_bytes; ++i)
    *dst_ptr++ ^= *src_ptr++;
}

bool GetNamedValueUnsigned(const refinery::TypedData& data,
                           base::StringPiece16 field_name,
                           uint64_t* value) {
  DCHECK(value);
  refinery::TypedData field;
  if (!data.GetNamedField(field_name, &field) ||
      !field.GetUnsignedValue(value)) {
    return false;
  }

  return true;
}

}  // namespace

HeapEntryWalker::HeapEntryWalker() : heap_bit_source_(nullptr) {
}

bool HeapEntryWalker::Initialize(refinery::BitSource* bit_source) {
  heap_bit_source_ = bit_source;

  return true;
}

bool SegmentEntryWalker::Initialize(refinery::BitSource* bit_source,
                                    const refinery::TypedData& heap,
                                    const refinery::TypedData& segment) {
  if (!HeapEntryWalker::Initialize(bit_source))
    return false;

  // Retrieve the EncodeFlagMask and the Encoding fields from the heap.
  refinery::TypedData encode_flag_mask;
  refinery::TypedData encoding;
  bool has_flags = heap.GetNamedField(L"EncodeFlagMask", &encode_flag_mask);
  bool has_encoding = heap.GetNamedField(L"Encoding", &encoding);
  if (has_flags != has_encoding) {
    LOG(ERROR) << "Strangeness in types: "
               << "only one of Encoding and EncodeFlagMask present!";
    return false;
  }

  // Check the EncodeFlagMask, and store Encoding if appropriate. This is used
  // to XOR all _HEAP_ENTRY fields in the heap.
  if (has_flags) {
    uint64_t value = 0;
    if (!encode_flag_mask.GetUnsignedValue(&value)) {
      LOG(ERROR) << "Unable to get heap flags mask.";
      return false;
    }
    // From observation of some heaps.
    const uint64_t kEncodingEnabled = 0x00100000;
    if (value & kEncodingEnabled) {
      encoding_.resize(encoding.type()->size());
      if (!heap_bit_source_->GetAll(encoding.GetRange(), &encoding_.at(0)))
        return false;
    }
  }

  // Get the first entry.
  if (!segment.GetNamedField(L"Entry", &curr_entry_))
    return false;

  // Get the end address of the mapped part of the segment.
  uint64_t last_valid_entry = 0;
  if (!GetNamedValueUnsigned(segment, L"LastValidEntry", &last_valid_entry))
    return false;

  // Note that the segment can be discontiguous if it contains any uncommitted
  // ranges. Uncommitted ranges are stored as a list of whole pages with
  // _HEAP_UCR_DESCRIPTOR structures.
  segment_range_ = refinery::AddressRange(
      segment.addr(), refinery::Address(last_valid_entry) - segment.addr());

  return true;
}

bool SegmentEntryWalker::GetDecodedEntry(HeapEntry* entry) {
  DCHECK(entry);
  HeapEntry tmp = {};

  // Bail if the current entry is for some reason not of the right size.
  if (curr_entry_.type()->size() != sizeof(tmp))
    return false;

  // Get the raw entry.
  if (!heap_bit_source_->GetAll(curr_entry_.GetRange(), &tmp))
    return false;

  // Unencode it.
  if (encoding_.size() == sizeof(tmp))
    memxor(&tmp, &encoding_.at(0), sizeof(tmp));

  *entry = tmp;

  return true;
}

bool SegmentEntryWalker::AtEnd() const {
  if (curr_entry_.addr() + curr_entry_.type()->size() >= segment_range_.end())
    return true;

  return false;
}

bool SegmentEntryWalker::Next() {
  HeapEntry decoded = {};
  if (!GetDecodedEntry(&decoded))
    return false;

  return curr_entry_.OffsetAndCast(decoded.size, curr_entry_.type(),
                                   &curr_entry_);
}

LFHBinWalker::LFHBinWalker() : entry_byte_size_(0), heap_(0) {
}

bool LFHBinWalker::Initialize(
    refinery::Address heap,
    refinery::BitSource* bit_source,
    refinery::UserDefinedTypePtr heap_userdata_header_type,
    SegmentEntryWalker* walker) {
  DCHECK(bit_source);
  DCHECK(walker);

  heap_ = heap;

  if (!HeapEntryWalker::Initialize(bit_source))
    return false;

  refinery::AddressRange entry_range = walker->curr_entry().GetRange();
  // Get then entry preceding the bin.
  SegmentEntryWalker::HeapEntry entry = {};
  if (!walker->GetDecodedEntry(&entry))
    return false;

  bin_range_ = refinery::AddressRange(entry_range.start(),
                                      entry.size * entry_range.size());

  // The bin is comprised of a _HEAP_USERDATA_HEADER, followed by a
  // concatenation of heap entries.
  if (!walker->curr_entry().OffsetAndCast(1, heap_userdata_header_type,
                                          &heap_userdata_header_)) {
    return false;
  }

  // Dereference the heap subsegment. This contains the size, entry count
  // and other information on this bin.
  refinery::TypedData subsegment;
  refinery::TypedData heap_subsegment;
  if (!heap_userdata_header_.GetNamedField(L"SubSegment", &subsegment) ||
      !subsegment.Dereference(&heap_subsegment)) {
    return false;
  }

  // TODO(siggi): The UserBlocks pointer should point back to the
  //     _HEAP_USERDATA_HEADER in the bin - validate this.
  uint64_t block_size = 0;
  if (!GetNamedValueUnsigned(heap_subsegment, L"BlockSize", &block_size))
    return false;

  // Compute the entry byte size.
  entry_byte_size_ = block_size * walker->curr_entry().type()->size();

  if (!heap_userdata_header_.OffsetAndCast(1, walker->curr_entry().type(),
                                           &curr_entry_)) {
    return false;
  }

  // Get the obfuscated subsegment pointer from the first entry in the bin.
  uint64_t subsegment_code = 0;
  if (!GetNamedValueUnsigned(curr_entry_, L"SubSegmentCode", &subsegment_code))
    return false;

  // The subsegment_code is
  // XOR(LFHKey, subsegment_code, self addr >> 3, heap_subsegment).
  // By XORing out all the others, we're left with the LFH key.
  lfh_key_ = subsegment_code;
  lfh_key_ ^= heap_;
  lfh_key_ ^= (curr_entry_.addr() >> 3);
  lfh_key_ ^= heap_subsegment.addr();

  return true;
}

bool LFHBinWalker::GetDecodedEntry(LFHEntry* entry) {
  DCHECK(entry);

  LFHEntry tmp = {};
  if (sizeof(tmp) != curr_entry_.type()->size())
    return false;

  if (!curr_entry_.bit_source()->GetAll(curr_entry_.GetRange(), &tmp))
    return false;

  // XOR the LFHKey, self address and heap in to de-obfuscate the subseg field.
  tmp.heap_subsegment ^= lfh_key_;
  tmp.heap_subsegment ^= curr_entry_.addr() >> 3;
  tmp.heap_subsegment ^= heap_;

  *entry = tmp;
  return true;
}

bool LFHBinWalker::Next() {
  curr_entry_ =
      refinery::TypedData(curr_entry_.bit_source(), curr_entry_.type(),
                          curr_entry_.addr() + entry_byte_size_);
  return true;
}

bool LFHBinWalker::AtEnd() const {
  if (curr_entry_.GetRange().end() >= bin_range_.end())
    return true;

  return false;
}


text:
import React from 'react';
import { configure, setAddon, addDecorator } from '@storybook/react';
import InfoAddon from '../src/';

addDecorator(story =>
{story()}
);

setAddon(InfoAddon);

configure(() => {
  require('../example/story');
}, module);


text:
var expect = require('chai').expect;
var Plugin = require('./');

describe('Plugin', function() {
  var plugin;

  beforeEach(function() {
    plugin = new Plugin({});
  });

  it('should be an object', function() {
    expect(plugin).to.be.ok;
  });

  it('should has #compile method', function() {
    expect(plugin.compile).to.be.an.instanceof(Function);
  });

  it('should compile and produce valid result', function(done) {
    var content = '#id {color: #6b0;}';
    var expected = '#id {color: #6b0;}';

    plugin.compile({data: content, path: 'file.css'}).then(result => {
      var data = result.data;
      expect(data).to.equal(expected);
      done();
    }, error => expect(error).not.to.be.ok);
  });
});


text:
.. _example_oneport_calibration:

One-Port Calibration
*********************

Instructive
--------------

This example is written to be instructive, not concise.::

	import skrf as rf

	## created necessary data for Calibration class

	# a list of Network types, holding 'ideal' responses
	my_ideals = [\
	        rf.Network('ideal/short.s1p'),
	        rf.Network('ideal/open.s1p'),
	        rf.Network('ideal/load.s1p'),
	        ]

	# a list of Network types, holding 'measured' responses
	my_measured = [\
	        rf.Network('measured/short.s1p'),
	        rf.Network('measured/open.s1p'),
	        rf.Network('measured/load.s1p'),
	        ]

	## create a Calibration instance
	cal = rf.Calibration(\
	        ideals = my_ideals,
	        measured = my_measured,
	        )

	## run, and apply calibration to a DUT

	# run calibration algorithm
	cal.run()

	# apply it to a dut
	dut = rf.Network('my_dut.s1p')
	dut_caled = cal.apply_cal(dut)

	# plot results
	dut_caled.plot_s_db()
	# save results
	dut_caled.write_touchstone()

Concise
-----------

This example is meant to be the same as the first except more concise::

	import skrf as rf

	my_ideals = rf.load_all_touchstones_in_dir('ideals/')
	my_measured = rf.load_all_touchstones_in_dir('measured/')

	## create a Calibration instance
	cal = rf.Calibration(\
	        ideals = [my_ideals[k] for k in ['short','open','load']],
	        measured = [my_measured[k] for k in ['short','open','load']],
	        )

	## what you do with 'cal' may  may be similar to above example


text:
<navigation model="data.navigation"></navigation>

<div ng-view>
</div>

<custom-footer model="data.footer"></custom-footer>


text:
using DropCore.Persistence.Context;
using DropCore.Persistence.Context.Modes;
using DropCore.Persistence.Session;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace DropCore.Persistence.Tests.Context
{
    [TestClass]
    public class SessionFactoryContextTest
    {
        Mock<ISessionFactory> SessionFactoryMock { get; set; }
        Mock<IContext<ISessionFactory>> ContextMock { get; set; }

        [TestInitialize]
        public void Initialize()
        {
            SessionFactoryMock = new Mock<ISessionFactory>();
            ContextMock = new Mock<IContext<ISessionFactory>>();
            SessionFactoryContext.SetContext(ContextMock.Object);
        }

        [TestMethod]
        public void SessionContext_Can_Get_Current()
        {
            var current = SessionFactoryContext.Current;
            ContextMock.Verify(c => c.Current);
        }

        [TestMethod]
        public void SessionFactoryContext_Can_Set_Context()
        {
            Assert.AreEqual(ContextMock.Object, SessionFactoryContext.Context);
        }

        [TestMethod]
        public void SessionFactoryContext_Can_Bind_Session_Instance()
        {
            SessionFactoryContext.Bind(SessionFactoryMock.Object);
            ContextMock.Verify(c => c.Bind(SessionFactoryMock.Object));
        }

        [TestMethod]
        public void SessionFactoryContext_Can_Unbind_Session_Instance()
        {
            SessionFactoryContext.Unbind();
            ContextMock.Verify(c => c.Unbind());
        }
    }
}


text:
<?php
namespace Asar;

use \Asar\ContentNegotiator\ContentNegotiatorInterface;
/**
 */
class ContentNegotiator implements ContentNegotiatorInterface {

  function negotiateFormat($accept_header, array $available_formats) {
    if (empty($available_formats)) {
      throw new \Asar\ContentNegotiator\Exception(
         get_class($this) . '::negotiateFormat(). 2nd argument '.
          'must not be empty. Please specify available formats.'
      );
    }
    $accept_list = $this->getAcceptList($accept_header);
    foreach ($available_formats as $format) {
      if (!isset($preferred_format)) {
        $preferred_format = $format;
      }
      foreach ($accept_list as $accepts) {
        if (preg_match('/^[\w+-_]+\/[\*]$/', $accepts) ) {
          $exp = str_replace('*', '', $accepts);
            if (strpos($format, $exp) === 0) {
              return $format;
            }
        }
        if ($accepts == $format) {
          return $format;
        }
      }
    }
    if ($accepts == '*/*') {
      return $preferred_format;
    }
    return FALSE;
  }

  function getAcceptList($accept_header) {
    $temp_list = explode(',', $accept_header);
    $array = array();
    foreach ($temp_list as $value) {
      if (strpos($value, ';') > 0) {
        $s = explode(';', $value);
        $array[$s[1]] = $s[0];
      } else {
        $array[] = $value;
      }
    }
    return $array;
  }

}


text:
/* Additional Classes  --------------------------------------------- */

#console {
  height: 220px;
  background: #2b303b;
  border-radius: 5px;
  -moz-border-radius: 5px;
  padding: 5px;
}

#console div.jquery-console-inner {
  height:200px;
  margin: 10px 10px;
  overflow:auto;
  text-align:left;
  position: relative;
}
#console div.jquery-console-message-value {
  color:#bf616a;
  font-family:monospace;
  padding:0.1em;
}
#console div.jquery-console-prompt-box {
  color: #eff1f5;
  font-family: monospace;
  font-weight: bold;
  font-size: 14px;
}
#console div.jquery-console-focus span.jquery-console-cursor {
  background: #eff1f5;
  color:#2b303b;
  font-weight:bold;
}
#console div.jquery-console-message-error {
  color:#bf616a;
  font-style: italic;
  font-weight:bold;
  font-size:14px;
}
#console div.jquery-console-message-success {
  color:##a3be8c;
  font-style: italic;
  font-weight:bold;
  font-size:14px;
}
#console span.jquery-console-prompt-label {
  font-weight:bold;
  color: #ebcb8b;
}

#console div.jquery-console-welcome {
  color: #c4cccc;
  font-style: italic;
  font-family: monospace;
  font-size: 14px;
}
#console div.jquery-console-message-value {
  color: #b48ead;
  font-weight: bold;
  font-size: 14px;
}
.ebnf {
  color:#444; font-family:monospace;
  text-transform: uppercase;
}

.doc-link {
  font-size: 0.65em;
  text-decoration: none;
}


text:
import { t as _t } from "marko/dist/runtime/html/index.js";

const _marko_componentType = "wUxkdMJU",
      _marko_template = _t(_marko_componentType);

export default _marko_template;
import _marko_attr from "marko/dist/runtime/html/helpers/attr.js";
import _marko_renderer from "marko/dist/runtime/components/renderer.js";
const _marko_component = {};
_marko_template._ = _marko_renderer(function (input, out, _componentDef, _component, state) {
  out.w(`<div id=shorthand></div><div${_marko_attr("id", dynamic)}></div><div${_marko_attr("id", `partial-${dynamic}`)}></div>`);
}, {
  t: _marko_componentType,
  i: true
}, _marko_component);


text:
@interface PodsDummy_Pods_SwiftWBTests : NSObject
@end
@implementation PodsDummy_Pods_SwiftWBTests
@end


text:
namespace blink {

class HTMLMediaElement;
class TextTrack;

class MODULES_EXPORT MediaControlsTextTrackManager
    : public GarbageCollected<MediaControlsTextTrackManager> {
 public:
  explicit MediaControlsTextTrackManager(HTMLMediaElement&);

  MediaControlsTextTrackManager(const MediaControlsTextTrackManager&) = delete;
  MediaControlsTextTrackManager& operator=(
      const MediaControlsTextTrackManager&) = delete;

  // Returns the label for the track when a valid track is passed in and "Off"
  // when the parameter is null.
  String GetTextTrackLabel(TextTrack*) const;
  void ShowTextTrackAtIndex(unsigned);
  void DisableShowingTextTracks();

  virtual void Trace(Visitor*) const;

 private:
  Member<HTMLMediaElement> media_element_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_MODULES_MEDIA_CONTROLS_MEDIA_CONTROLS_TEXT_TRACK_MANAGER_H_


text:
import os
import sys
import time

import pytest
from pyjob.exception import PyJobError, PyJobTaskLockedError
from pyjob.local import CPU_COUNT, LocalTask

@pytest.mark.skipif(pytest.on_windows, reason="Deadlock on Windows")
class TestLocalTaskTermination(object):
    def test_terminate_1(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(4)]
        task = LocalTask(scripts, processes=CPU_COUNT)
        task.run()
        task.wait()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_terminate_2(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(4)]
        task = LocalTask(scripts, processes=CPU_COUNT)
        task.run()
        task.close()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_terminate_3(self):
        scripts = [pytest.helpers.get_py_script(i, 1000000) for i in range(4)]
        task = LocalTask(scripts, processes=min(CPU_COUNT, 2))
        task.run()
        not_all_found = not all(os.path.isfile(f) for f in task.log)
        task.close()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert not_all_found and all_found

    def test_terminate_4(self):
        scripts = [pytest.helpers.get_py_script(i, 1000000) for i in range(5)]
        files = []

        def innerf():
            task = LocalTask(scripts, processes=min(CPU_COUNT, 2))
            task.run()
            files.extend(task.script + task.log)

        innerf()
        pytest.helpers.unlink(files)

    @pytest.mark.skip(reason="Unstable test")
    def test_terminate_5(self):
        scripts = [pytest.helpers.get_py_script(i, 1000000) for i in range(10)]
        with LocalTask(scripts, processes=min(CPU_COUNT, 2)) as task:
            with pytest.raises(PyJobError):
                task.run()
                pytest.helpers.unlink(task.script[4:])
        pytest.helpers.unlink(task.script[:4] + task.log)

    def test_terminate_6(self):
        scripts = [pytest.helpers.get_py_script(i, 50000) for i in range(100)]
        with LocalTask(scripts, processes=CPU_COUNT) as task:
            task.run()
            time.sleep(1)
            task.kill()
        all_scripts_found = all(os.path.isfile(path) for path in task.script)
        some_logs_found = any(os.path.isfile(log) for log in task.log) and not all(
            os.path.isfile(log) for log in task.log
        )
        pytest.helpers.unlink(task.script + task.log)
        assert all_scripts_found and some_logs_found

    def test_terminate_7(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(10000)]
        with LocalTask(scripts, processes=min(CPU_COUNT, 2)) as task:
            task.run()
            time.sleep(5)
            task.kill()
        all_scripts_found = all(os.path.isfile(path) for path in task.script)
        some_logs_found = any(os.path.isfile(log) for log in task.log) and not all(
            os.path.isfile(log) for log in task.log
        )
        pytest.helpers.unlink(task.script + task.log)
        assert all_scripts_found and some_logs_found

    def test_terminate_8(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(4)]
        task = LocalTask(scripts, processes=CPU_COUNT)
        task.run()
        task.wait()
        all_found = all(os.path.isfile(f) for f in task.log)
        with pytest.raises(PyJobTaskLockedError):
            task.run()
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_terminate_9(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(4)]
        task = LocalTask(scripts, processes=CPU_COUNT)
        task.run()
        with pytest.raises(PyJobTaskLockedError):
            task.run()
        task.wait()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

@pytest.mark.skipif(pytest.on_windows, reason="Deadlock on Windows")
class TestLocalPerformance(object):
    def test_performance_1(self):
        scripts = [pytest.helpers.get_py_script(i, 1000) for i in range(4)]
        with LocalTask(scripts, processes=CPU_COUNT) as task:
            task.run()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_performance_2(self):
        scripts = [pytest.helpers.get_py_script(i, 1000) for i in range(16)]
        with LocalTask(scripts, processes=CPU_COUNT) as task:
            task.run()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_performance_3(self):
        scripts = [pytest.helpers.get_py_script(i, 1000) for i in range(32)]
        with LocalTask(scripts, processes=CPU_COUNT) as task:
            task.run()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found

    def test_performance_4(self):
        scripts = [pytest.helpers.get_py_script(i, 10000) for i in range(64)]
        with LocalTask(scripts, processes=CPU_COUNT) as task:
            task.run()
        all_found = all(os.path.isfile(f) for f in task.log)
        pytest.helpers.unlink(task.script + task.log)
        assert all_found


text:
import React from 'react';
import { Row , Col  } from 'antd';

var App=React.createClass({
	render(){
		if(!this.props.data.isShow){
			return

		}else{
			let bgimg={
			backgroundImage:`url(${this.props.data.background_img})`
			}
			return

				<Row>
					<Col xs={0} sm={0} md={4} lg={6}></Col>
					<Col xs={24} sm={24} md={18} lg={12}>

{this.props.data.title}

						<Row type="flex" align="top">
						{this.props.data.data.map((item,index)=>{
							return <Col xs={24} sm={12} md={6} lg={6} key={"competitionItem"+index} className="competitions_container wow bounceInUp animated animated">

{item.itemTxt}

{item.itemDate}

							</Col>
						})}
						</Row>

					</Col>

					<Col xs={0} sm={0} md={4} lg={6}></Col>
				</Row>

		}
	}
})
export default App


text:
class Santa
	attr_reader :ethnicity
	attr_accessor :gender, :age

	def initialize(gender, ethnicity)
		puts "Initializing Santa instance..."
		@gender = gender
		@ethnicity = ethnicity
		@reindeer_ranking = ["Rudolph","Dasher","Dancer","Prancer","Vixen","Comet","Cupid","Donner","Blitzen"]
		@age = 0
	end

	def speak
		puts "Ho, ho, ho! Haaaappy holidays!"
	end

	def eat_milk_and_cookies(cookie_type)
		puts "That was a good #{cookie_type}!"
	end

	def celebrate_birthday(age)
		puts @age += 1
	end

	def get_mad_at(reindeer_name)
		puts "Santa is disappointed in #{reindeer_name}, and he knows why."
		reindeer_idx = @reindeer_ranking.index(reindeer_name)
		return @reindeer_ranking.insert(-1, @reindeer_ranking.delete_at(reindeer_idx))
	end
end
# create an array of genders
genders = ["male",
		   "female",
		   "agender",
		   "transfemale",
		   "transmale",
		   "Prince"]

# create an array of ethnicities
ethnicities = ["Latino",
			   "Indo-European",
			   "Afroasiatic",
			   "Semitic",
			   "Native American",
			   "Prince"]

1000.times {
	santa = Santa.new(genders.sample, ethnicities.sample)
	puts "This Santa is #{santa.gender}, #{santa.ethnicity} and is #{santa.age = rand(140)} years old."
	# p santa.get_mad_at("Vixen")
 }
puts "-----Iterating through Santa attributes to identify Santa diversity!-----\n"

=begin attempted loop through gender and ethnicity arrays
# create an array of diverse Santas
# santas = []

# genders.each do |gender|
# 	puts "I'm Santa and my gender is #{@gender}."
# 	santas << Santa.new(@gender)
# 	puts "-------------------------------------"
# end

# ethnicities.each do |ethnicity|
# 	puts "I'm Santa and my ethnicity is #{@ethnicity}."
# 	santas << Santa.new(@ethnicity)
# 	puts "-------------------------------------"
# end
=end

# santa = Santa.new
# p santa.speak
# p santa.eat_milk_and_cookies("oatmeal cookie")
# p santa.get_mad_at
# p @reindeer_ranking


text:
:: Copyright 2019-2021 Google LLC
::
:: 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
::
::     https://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.

echo off
setlocal enabledelayedexpansion

if not defined PY3_VER set PY3_VER=38
set ROOTDIR=%~dp0\..\..\
set TEST_DATA_DIR=%ROOTDIR%\..\test_data
set LIBEDGETPU_DIR=%ROOTDIR%\..\libedgetpu
for /f %%i in ("%ROOTDIR%") do set "ROOTDIR=%%~fi"
for /f %%i in ("%TEST_DATA_DIR%") do set "TEST_DATA_DIR=%%~fi"
for /f %%i in ("%LIBEDGETPU_DIR%") do set "LIBEDGETPU_DIR=%%~fi"
for /f "tokens=2 delims==" %%i in ('wmic os get /format:value ^| findstr TotalVisibleMemorySize') do set /A "MEM_KB=%%i >> 1"

docker run -m %MEM_KB%KB --cpus %NUMBER_OF_PROCESSORS% --rm ^
    -v %ROOTDIR%:c:\edgetpu ^
    -v %TEST_DATA_DIR%:c:\edgetpu\test_data ^
    -v %LIBEDGETPU_DIR%:c:\edgetpu\libedgetpu ^
    -w c:\edgetpu ^
    -e PYTHON=c:\python%PY3_VER%\python.exe ^
    -e BAZEL_OUTPUT_BASE=c:\temp\edgetpu ^
    edgetpu-win ^
    scripts\windows\build.bat


text:
package com.intellij.util.xmlb;

import com.intellij.util.ThreeState;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Collection;
import java.util.Map;

public class SkipEmptySerializationFilter extends SerializationFilterBase {
  @Override
  protected boolean accepts(@NotNull Accessor accessor, @NotNull Object bean, @Nullable Object beanValue) {
    if (beanValue == null) {
      return false;
    }

    ThreeState accepts = accepts(accessor.getName(), beanValue);
    if (accepts != ThreeState.UNSURE) {
      return accepts.toBoolean();
    }

    if (Boolean.FALSE.equals(beanValue) ||
        beanValue instanceof String && ((String)beanValue).isEmpty() ||
        beanValue instanceof Collection && ((Collection<?>)beanValue).isEmpty() ||
        beanValue instanceof Map && ((Map<?, ?>)beanValue).isEmpty()) {
      return false;
    }

    return true;
  }

  protected ThreeState accepts(@NotNull String name, @NotNull Object beanValue) {
    return ThreeState.UNSURE;
  }
}


text:
package uk.gov.gchq.gaffer.serialisation;

import com.fasterxml.jackson.annotation.JsonIgnore;

import uk.gov.gchq.gaffer.exception.SerialisationException;
import uk.gov.gchq.koryphe.serialisation.json.JsonSimpleClassName;

import java.io.Serializable;

/**
 * A class that implements this interface is responsible for serialising an
 * object of class INPUT to a OUTPUT, and for deserialising it back again.
 * It must also be able to deal with serialising null values.
 */
@JsonSimpleClassName(includeSubtypes = true)
public interface Serialiser<INPUT, OUTPUT> extends Serializable {

    /**
     * Handle an incoming null value and generate an appropriate OUTPUT representation.
     *
     * @return OUTPUT the serialised output
     */
    OUTPUT serialiseNull();

    /**
     * Check whether the serialiser can serialise a particular class.
     *

     * //Warning: Due to erasure you may get false positives. e.g.
     *

     * {@code
     * Set<Foo> set = Sets.newHashSet();
     * boolean b = new Serialiser<Set<Bar>, byte[]>().canHandle(set.getClass());
     * b will incorrectly be true because of type erasure between Set<Foo> Set<Bar>
     * }
     *

     *
     * @param clazz the object class to serialise
     * @return boolean true if it can be handled
     */
    boolean canHandle(final Class clazz);

    /**
     * Serialise some object and returns the OUTPUT of the serialised form.
     *
     * @param object the object to be serialised
     * @return OUTPUT the serialised OUTPUT
     * @throws SerialisationException if the object fails to serialise
     */
    OUTPUT serialise(final INPUT object) throws SerialisationException;

    /**
     * Deserialise an OUTPUT into the original object.
     *
     * @param output the OUTPUT to deserialise
     * @return INPUT the deserialised object
     * @throws SerialisationException if the object fails to deserialise
     */
    INPUT deserialise(final OUTPUT output) throws SerialisationException;

    /**
     * Handle an empty OUTPUT and reconstruct an appropriate representation in Object form.
     *
     * @return INPUT the deserialised object
     * @throws SerialisationException if the object fails to deserialise
     */
    INPUT deserialiseEmpty() throws SerialisationException;

    /**
     * Indicates whether the serialisation process preserves the ordering of the INPUT,
     * i.e. if x and y are objects of class INPUT, and x is less than y, then this method should
     * return true if the serialised form of x is guaranteed to be less than the serialised form
     * of y (using the standard ordering of OUTPUT).
     * If INPUT is not Comparable then this test makes no sense and false should be returned.
     *
     * @return true if the serialisation will preserve the order of the INPUT, otherwise false.
     */
    boolean preservesObjectOrdering();

    /**
     * Indicates whether the serialisation process produces a predictable, consistent
     * OUTPUT, from a given INPUT, ie the same object should always serialise in the same way
     * for this to be true.
     *
     * @return true if serialisation is consistent for a given object, otherwise false.
     */
    @JsonIgnore
    boolean isConsistent();
}


text:
Computer Repair System
==================

[![Build status](https://ci.appveyor.com/api/projects/status/52l6ceime3ah9lvx?svg=true)](https://ci.appveyor.com/project/codingbat/compsys)

## Introduction
CompSys is s computer repair system software to maintain everyday task for a computer repair shop. The software provides cutting-edge technology to make your daily task a lot more easier.

CompSys aims to be a simple, fast and technician friendly way of managing your computer repair store. Our goal is to be powerful in functionality while simplistic in appearance, no clutter or other bloated features.

> Features
> *	Tracking of Repair Workflow
> *	Customer Info & Assets
> *	Support for Multiple Tax rates on both Goods and Services and multiple taxes per item.
> *	System Based Interface
> *	Email Invoices, Repair Reports, Receipts
> *	Receipt Printer Support
> *	Reporting - Sales and Technician Activity
> *	Oracle SQL Database driven
> *	Store Inventory Management
> *	Job Timers
> *	Recurring Invoices
> *	Email Service Reminders to your customers

## Functional Components

![alt text][logo]
[logo]: http://i.imgur.com/Aj0jGse.png "Functional Components"

## User Requirements

1.	**The system performs staff administration**
  1.	CompSys will allow the details of each new staff to be recorded.
  2.	CompSys will allow a staff details to be amended.
  3.	CompSys will generate a staff listing.

2.	**The system performs customer administration**
  1.	CompSys will allow the details of each new customer to be recorded.
  2.	CompSys will allow a customer details to be amended.
  3.	CompSys will allow a customer to be queried.
  4.	CompSys will generate a customer listing.

3.	**The system performs repair management**
  1.	CompSys will allow the details of each new repair to be recorded.
  2. CompSys will generate a new repair estimate for a new repair.
  3.	CompSys will allow the system to validate a repair.
  4.	CompSys will allow the system to finalise a repair.
  5.	CompSys will process every repair being collected.
  6.	CompSys will generate repair report for all the completed repairs.

4.	**The system performs administration**
  1.	CompSys will generate a list of jobs and their status.
  2.	CompSys will issue invoice for any repair at any given period.
  3.	CompSys will generate income analysis to required specification.
  4.	CompSys will allow the system to set pre-defined repair rates and parts in the inventory.

## Screenshots
**Login Screen**
![alt text][login]
[login]: http://i.imgur.com/isPSdCT.png "Login Screen"
**Dashboard**
![alt text][dashboard]
[dashboard]: http://i.imgur.com/aEAzHO0.png "Dashboard"
**Estimate**
![alt text][estimate]
[estimate]: http://i.imgur.com/hnl92jR.png "Set Estimate"

## What's included?
 * SQL Files ---- dir/ Oracle SQL Files
 * Program Specification documentation -- dir/ Documentation

### Download the ZIP

Grab the latest stable [zip archive] from [master](https://github.com/codingbat/Computer-Repair-System-2015/archive/master.zip).

### Version

0.0.1.3

### Notes

This system was developed with Visual Studio 2013 and Oracle 12c Database.

License
----

MIT


text: google-site-verification: google4e64c658d85cbc1b.html


text:
FROM ubuntu:16.04

RUN useradd -ms /bin/bash indy

# Install environment
RUN apt-get update -y && apt-get install -y \
	wget \
	python3.5 \
	python3-pip \
	python-setuptools \
	ipython \
	ipython-notebook \
	apt-transport-https \
	ca-certificates \
	software-properties-common

WORKDIR /home/indy

RUN pip3 install -U \
	pip \
	setuptools \
	jupyter \
	python3-indy==1.8.1-dev-1039

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 68DB5E88 \
    && add-apt-repository "deb https://repo.sovrin.org/sdk/deb xenial master" \
    && apt-get update \
    && apt-get install -y \
    libindy=1.8.1~1039

USER indy

EXPOSE 8888


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorBackground"
    tools:context="com.project.mobilesafe.activities.SplashActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@mipmap/splash"/>

    <TextView
        android:id="@+id/tv_splash_version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="16dp"
        android:textColor="@color/white"
        android:text="版本号:" />
</RelativeLayout>


text:
package com.wixpress.guineapig.spi;

import com.wixpress.guineapig.entities.ui.UiExperiment;
import com.wixpress.guineapig.entities.ui.UiExperimentBuilder;
import com.wixpress.petri.experiments.domain.Filter;

import java.util.List;

public interface FilterAdapterExtender {
    void extendUiExperiment(List<Filter> filters, UiExperimentBuilder uiExperimentBuilder);

    Boolean isRecognized(Filter unrecognized);

    List<Filter> extractFiltersFromUiExperiment(UiExperiment uiExperiment);
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg3" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="0dp"
            android:background="@drawable/bg3"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/activity_vertical_margin"
            android:paddingLeft="0dp"
            android:paddingRight="0dp"
            android:paddingTop="0dp"
            tools:context=".TestActivity" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="0dp"
                android:orientation="vertical"
                android:scrollbars="vertical" >

                <ImageView
                    android:id="@+id/imageView1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="0dp"
                    android:adjustViewBounds="true"
                    android:padding="0dp"
                    android:scaleType="fitCenter"
                    android:src="@drawable/header_noir" />

                <TextView
                    android:id="@+id/Button01"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentTop="true"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="@color/orange"
                    android:clickable="false"
                    android:gravity="center"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="@string/settings"
                    android:textAllCaps="true"
                    android:textColor="#ffffff" />

                <TextView
                    android:id="@+id/textGenre"
                    android:layout_width="match_parent"
                    android:layout_height="fill_parent"
                    android:layout_marginTop="20dp"
                    android:layout_weight="1"
                    android:gravity="center"
                    android:singleLine="true"
                    android:text="@string/perimeter"
                    android:textColor="#000000"
                    android:textSize="18sp" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="0dp"
                    android:orientation="vertical" >

                    <com.tcheckit.ExtendedSeekBar
                        android:id="@+id/seekBar1"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="40dp"
                        android:max="5"
                        android:paddingLeft="10dp"
                        android:paddingRight="10dp"
                        android:progress="0"
                        android:progressDrawable="@drawable/seek_bar_bg2"
                        android:secondaryProgress="0"
                        android:thumb="@drawable/seekbar_thumb2" />

                    <TextView
                        android:id="@+id/textView33"
                        android:layout_width="fill_parent"
                        android:layout_height="20dp"
                        android:layout_alignBottom="@+id/seekBar1"
                        android:layout_marginTop="11dp"
                        android:text="500 m"
                        android:textColor="#000000"
                        android:textSize="10dp" />
                </RelativeLayout>
                <!--  -->

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right|center_horizontal"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="2dp" >

                    <ToggleButton
                        android:id="@+id/toggleButton1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="1dp"
                        android:onClick="filtrePerimetre"

                        android:textOff="Désactivé"
                        android:textOn="Activé" />

                    <TextView
                        android:id="@+id/textDistance"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginLeft="10dp"
                        android:text="@string/scope"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#000000"
                        android:textSize="12sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="2dp" >

                    <ToggleButton
                        android:id="@+id/toggleButton2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:onClick="filtrePush"

                        android:textOff="Désactivé"
                        android:textOn="Activé" />

                    <TextView
                        android:id="@+id/textDistance"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal|center_vertical"
                        android:layout_marginLeft="10dp"
                        android:text="@string/push_notifi"
                        android:textAppearance="?android:attr/textAppearanceLarge"
                        android:textColor="#000000"
                        android:textSize="12sp" />
                </LinearLayout>

                <TextView
                    android:id="@+id/textView1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="10dp"
                    android:text="@string/bank_state_req"
                    android:textColor="#000000" />

                <Button
                    android:id="@+id/button1"
                    android:layout_width="fill_parent"
                    android:layout_height="35dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/bg_btn_orange"
                    android:gravity="center"
                    android:onClick="goVotreCompteEnBanque"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="@string/bank_acc"
                    android:textAllCaps="true"
                    android:textColor="#ffffff" />

                <Button
                    android:id="@+id/button1"
                    android:layout_width="fill_parent"
                    android:layout_height="35dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="10dp"
                    android:background="@drawable/bg_btn_orange"
                    android:gravity="center"
                    android:onClick="goVotreComptePaypal"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="@string/paypal_acc"
                    android:textAllCaps="true"
                    android:textColor="#ffffff" />

                <Button
                    android:id="@+id/buttonRetour"
                    android:layout_width="fill_parent"
                    android:layout_height="35dp"
                    android:layout_marginBottom="70dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:layout_marginTop="10dp"
                    android:background="#000000"
                    android:gravity="center"
                    android:onClick="deconnexion"
                    android:paddingBottom="10dp"
                    android:paddingTop="10dp"
                    android:text="@string/logout"
                    android:textAllCaps="true"
                    android:textColor="#ffffff" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <include layout="@layout/activity_menu_bas" />

    <ImageView
        android:id="@+id/imageButtonReglages"
        android:layout_width="67dp"
        android:layout_height="80dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="-20dip"
        android:background="@android:color/transparent"
        android:contentDescription="@string/hello"
        android:onClick="goMain"
        android:src="@drawable/img_center" />

</RelativeLayout>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><roundcube:object name="pagetitle" /></title>
<roundcube:include file="/includes/links.html" />
</head>
<body class="iframe">

<div class="messageheaderbox">
<roundcube:button command="extwin" image="/images/icons/extwin.png" width="15" height="15" title="openinextwin" id="openextwinlink" />
<roundcube:object name="messageHeaders" class="headers-table" cellspacing="0" cellpadding="2" addicon="/images/icons/silhouette.png" summary="Message headers" />
<roundcube:object name="messageFullHeaders" id="full-headers" />
<roundcube:object name="messageAttachments" id="attachment-list" />
</div>

<roundcube:object name="messageObjects" id="message-objects" />
<roundcube:object name="messageBody" id="messagebody" />

</body>
</html>


text:
module Codebreaker
  class Game
    def start
    end
  end
end


text:
package com.sequenceiq.cloudbreak.common.type;

public enum RdsType {

    HIVE, RANGER, DRUID
}


text:
"""Tensor-like objects that are composed from tf.Tensors."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import abc

import six

from tensorflow.python import pywrap_tensorflow
from tensorflow.python.util import nest

@six.add_metaclass(abc.ABCMeta)
class CompositeTensor(object):
  """Abstract base class for Tensor-like objects that are composed from Tensors.

  Each `CompositeTensor` can be decomposed into a structured collection of
  component `tf.Tensor`s, and reconstructed from those components.

  The `tensorflow.python.util.nest` module has support for treating composite
  tensors as structure, which makes it easy to flatten and reconstruct
  composite tensors (or larger structures that contain composite tensors).
  E.g.:

  ```python
  ct = ...  # Create a composite tensor.
  flat_list_of_tensors = nest.flatten(ct, expand_composites=True)
  transformed_list_of_tensors = ...  # do something with the flat tensors.
  result = nest.pack_sequence_as(ct, transformed_list_of_tensors)
  ```
  """

  @abc.abstractmethod
  def _to_components(self):
    """Decomposes this composite tensor into its components.

    Returns:
      The components that comprise this composite tensor: a nested structure
      (as defined by `tf.python.util.nest`) whose values are `tf.Tensor`s or
      `CompositeTensor`s.
    """
    raise NotImplementedError("CompositeTensor._to_components")

  @abc.abstractmethod
  def _from_components(cls, components):  # pylint: disable=no-self-argument
    """Creates a composite tensor of type `cls` from components.

    Args:
      components: The components that should be used to form the
        composite tensor: a nested structure (as defined by
        `tf.python.util.nest`) whose values are tf.Tensors or composite
        tensors.

    Returns:
      A `CompositeTensor` of type `cls`.
    """
    raise NotImplementedError("CompositeTensor._from_components")

  @abc.abstractmethod
  def _shape_invariant_to_components(self, shape=None):
    """Converts a shape invariant into invariants for individual components.

    Args:
      shape: A `tf.TensorShape` object.  The shape invariant for this
        `CompositeTensor`, or `None` if a default shape invariant should be
        used (based on the value of this `CompositeTensor`).

    Returns:
      A nested structure whose values are `tf.TensorShape` objects, specifying
      the shape invariants for the tensors that comprise this `CompositeTensor`.
    """
    raise NotImplementedError("CompositeTensor._shape_invariant_to_components")

  @abc.abstractproperty
  def _is_graph_tensor(self):
    """Returns True if this tensor's components belong to a TF graph."""
    raise NotImplementedError("CompositeTensor._is_symbolic_tensor")

  def consumers(self):
    """Returns a list of `Operation`s that consume this `CompositeTensor`.

    Returns:
      A list of `Operation`s.

    Raises:
      RuntimeError: If this method is called while executing eagerly.
    """
    consumers = nest.flatten([
        component.consumers()
        for component in self._to_components()
        if getattr(component, "graph", None) is not None
    ])
    return list(set(consumers))

pywrap_tensorflow.RegisterType("CompositeTensor", CompositeTensor)

# @TODO(edloper): Can we replace convert_to_tensor_or_xyz with just
# convert_to_tensor_or_composite?  Alternatively, should composite tensors
# register a dispatch override for tf.convert_to_tensor?


text:
import json
import os
import time

from common import file
from manage import whiptail

dialog = whiptail.Whiptail()
dialog.height = 15
dialog.backtitle = "SilverBlog management tool"
system_config = {
    "Project_Name": "",
    "Project_Description": "",
    "Project_URL": "https://",
    "Author_Image": "",
    "Author_Name": "",
    "Author_Introduction": "",
    "Theme": "",
    "Paging": 10,
    "Time_Format": "%Y-%m-%d",
    "Editor": "nano",
    "i18n": "en-US",
    "Pinyin": False,
    "Use_CDN": False,
    "Lazyload": False
}
if os.path.exists("./config/system.json"):
    system_config = json.loads(file.read_file("./config/system.json"))

def setting_menu(main_run=False):
    while True:
        dialog.title = "Setting"
        menu_list = ["Using Setup Wizard", "Using Manual setup",
                     "Theme package manage", "Create a backup", "=" * 25,
                     ]
        if not main_run:
            menu_list.append("Back")
        menu_list.append("Exit")

        result = dialog.menu("Please select an action", menu_list)
        if result == "Exit":
            exit(0)
        if result == "Back":
            break
        if result == "Create a backup":
            from manage import backup
            backup.backup()
            dialog.alert("The backup is complete.")
        if result == "Using Setup Wizard":
            setup_wizard()
        if result == "Using Manual setup":
            manual_setup_list()
        if result == "Theme package manage":
            theme_manage()

def save_config():
    file.write_file("./config/system.json", file.json_format_dump(system_config))

def theme_manage():
    from manage import theme
    dialog.title = "Theme package manager"
    while True:
        menu_list = ["Install the theme", "Use the existing theme", "Upgrade existing theme",
                     "Remove existing theme", "Set insertion point", "=" * 25, "Back", "Exit"]
        result = dialog.menu("Please select an action", menu_list)
        theme_name = ""
        if result == "Exit":
            exit(0)
        if result == "Back":
            break
        if result == "Install the theme":
            install_menu = ["View list", "Enter the theme package name"]
            result = dialog.menu("Please select an action", install_menu)
            package_list = theme.get_package_list()
            if result == "View list":
                item_list = list()
                for item in package_list:
                    item_list.append(item["name"])
                theme_name = dialog.menu("Please select the theme you want to install:", item_list)
            if result == "Enter the theme package name":
                theme_name = dialog.prompt("Please enter the theme package name:")
            if len(theme_name) == 0:
                dialog.alert("Theme name cannot be empty")
                continue
            has_theme = False
            for item in package_list:
                if item["name"].lower() == theme_name.lower():
                    has_theme = True
            if not has_theme:
                dialog.alert("Can not find this theme.")
                continue
            readme = theme.get_readme(theme_name)
            if readme is not None:
                dialog.alert_muilt_line(readme)
            theme.install_theme(theme_name, False)
            if theme_name is not None and dialog.confirm("Do you want to enable this theme now?", "no"):
                system_config["Theme"] = theme_name
                if os.path.exists("./templates/{}/i18n".format(theme_name)):
                    system_config["i18n"] = setting_i18n(theme_name)
                if os.path.exists("./templates/{}/config.json".format(theme_name)):
                    setting_theme_config(theme_name)
            save_config()
        if result == "Use the existing theme":
            theme_name = select_theme()
            system_config["Theme"] = theme_name
            if os.path.exists("./templates/{}/i18n".format(theme_name)):
                system_config["i18n"] = setting_i18n(theme_name)
            if os.path.exists("./templates/{}/config.json".format(theme_name)):
                setting_theme_config(theme_name)
            theme.download_static_file(theme_name)
            save_config()
        if result == "Upgrade existing theme":
            theme.upgrade_theme(select_theme())
        if result == "Remove existing theme":
            theme_name = select_theme()
            if theme_name is None:
                continue
            if system_config["Theme"] == theme_name:
                dialog.alert("This theme is in use and cannot be removed.")
                continue
            theme.remove_theme(theme_name)
        if result == "Set insertion point":
            setting_template_insertion()
        time.sleep(0.5)

def manual_setup_list():
    while True:
        dialog.title = "Manual setup"
        menu_list = ["Project name", "Project description", "Access URL", "Remote API password", "Author name",
                     "Author introduction", "Author avatar", "Paging", "Time format", "Editor", "Use CDN","Image lazyload",
                     "Automatically convert Chinese characters to pinyin",
                     "=" * 50, "Back", "Exit"]
        result = dialog.menu("Please select the item you want to configure", menu_list)
        if result == "Exit":
            exit(0)
        if result == "Back":
            break
        if result == "Project name":
            set_string("Project_Name", "Please enter the project name:")
        if result == "Project description":
            set_string("Project_Description", "Please enter the project description:")
        if result == "Access URL":
            set_string("Project_URL", "Please enter the access URL:")
        if result == "Remote API password":
            remote_api_password()
        if result == "Author name":
            set_string("Author_Name", "Please enter the author name:")
        if result == "Author introduction":
            set_string("Author_Introduction", "Please enter the author introduction:")
        if result == "Author avatar":
            author_avatar()
        if result == "Paging":
            set_int("Paging", "Please enter the paging:")
        if result == "Time format":
            set_string("Time_Format", "Please enter the time format:")
        if result == "Editor":
            editor()
        if result == "Use CDN":
            set_bool("Use_CDN", "Use CDN?")
        if result == "Lazyload":
            set_bool("Image lazyload", "Use image lazyload?")
        if result == "Automatically convert Chinese characters to pinyin":
            set_bool("Pinyin", "Use automatic conversion of Chinese characters to Pinyin?")
        save_config()
        time.sleep(0.5)

def setting_template_insertion():
    menu_list = ["head", "comment", "footer", "Page foot"]
    result = dialog.menu("Please select an action", menu_list)
    if result == "head":
        os.system("{} ./templates/include/head.html".format(system_config["Editor"]))
    if result == "comment":
        os.system("{} ./templates/include/comment_box.html".format(system_config["Editor"]))
    if result == "footer":
        os.system("{} ./templates/include/footer.html".format(system_config["Editor"]))
    if result == "Page foot":
        os.system("{} ./templates/include/foot.html".format(system_config["Editor"]))

def select_theme():
    from manage import theme
    directories = theme.get_local_theme_list()
    if len(directories) == 0:
        dialog.alert("The Theme list can not be blank.")
        return None
    return dialog.menu("Please select the theme to be operated:", directories)

def setting_theme_config(theme_name):
    theme_config = json.loads(file.read_file("./templates/{}/config.json".format(theme_name)))
    for item in theme_config:
        if type(theme_config[item]) == bool:
            status = "no"
            if theme_config[item]:
                status = "yes"
            theme_config[item] = dialog.confirm("Please choose Boolean item [{}]:".format(item), status)
        if type(theme_config[item]) == int:
            theme_config[item] = int(
                dialog.prompt("Please enter Number item [{}]:".format(item), str(theme_config[item])))
        if type(theme_config[item]) == float:
            theme_config[item] = float(
                dialog.prompt("Please enter Number item [{}]:".format(item), str(theme_config[item])))
        if type(theme_config[item]) == str:
            theme_config[item] = str(dialog.prompt("Please enter String item [{}]:".format(item), theme_config[item]))
    file.write_file("./templates/{}/config.json".format(theme_name), file.json_format_dump(theme_config))
    return

def setting_i18n(theme_name):
    dir_list = os.listdir("./templates/{0}/i18n".format(theme_name))
    show_list = list()
    for item in dir_list:
        if item.endswith(".json"):
            show_list.append(item.replace(".json", ""))
    return dialog.menu("Please select the i18n to be operated:", show_list)

def setup_wizard():
    set_string("Project_Name", "Please enter the project name:")
    set_string("Project_Description", "Please enter the project description:")
    set_string("Project_URL", "Please enter the access URL:")
    remote_api_password()
    set_string("Author_Name", "Please enter the author name:")
    set_string("Author_Introduction", "Please enter the author introduction:")
    author_avatar()
    set_int("Paging", "Please enter the paging:")
    set_string("Time_Format", "Please enter the time format:")
    editor()
    set_bool("Use_CDN", "Use CDN?")
    set_bool("Lazyload", "Use image lazyload?")
    set_bool("Pinyin", "Use automatic conversion of Chinese characters to Pinyin?")
    save_config()

def set_string(item, message):
    system_config[item] = dialog.prompt(message, system_config[item])

def set_int(item, message):
    system_config[item] = int(dialog.prompt(message, str(system_config[item])))

def set_bool(item, message):
    status = "no"
    if system_config[item]:
        status = "yes"
    system_config[item] = dialog.confirm(message, status)

def remote_api_password():
    notice = ""
    if os.path.exists("./config/control.json"):
        notice = "\n(Leave blank does not change)"
    while True:
        new_password = dialog.prompt("Please enter the remote api password:" + notice, "", True)
        if notice != "" and len(new_password) == 0:
            break
        if len(new_password) >= 8:
            break
        dialog.alert("The new password is too weak. Please retry with a stronger combination.")
    if len(new_password) != 0:
        import hashlib
        import hmac
        md5_new_password = hashlib.md5(new_password.encode('utf-8')).hexdigest()
        sha256_new_password = hmac.new(str("SiLvErBlOg").encode('utf-8'), str(md5_new_password).encode('utf-8'),
                                       hashlib.sha256).hexdigest()
        file.write_file("./config/control.json", json.dumps({"password": sha256_new_password}))

def author_avatar():
    item = "Author_Image"
    if dialog.confirm("Use Gravatar?", "no"):
        from manage import get
        system_config[item] = get.get_gravatar(system_config["Author_Name"])
    system_config[item] = dialog.prompt("Please enter the author image:", system_config[item])

def editor():
    item = "Editor"
    editor_name = dialog.prompt("Please enter the editor:", system_config[item])
    result = os.system("which {}".format(editor_name))
    result_code = result >> 8
    if result_code != 0:
        dialog.alert("Warning! This editor may not be installed.")
    system_config[item] = editor_name


text:
/* globals FileReader */
import angular from 'angular';
import _ from 'lodash';
import $ from 'jquery';

require('./import.scss');

class AnnotateImportController {
    constructor( // eslint-disable-line max-params
        $log, $state, $scope, $timeout, $ngRedux
    ) {
        'ngInject';
        this.$log = $log;
        this.$state = $state;
        this.$scope = $scope;
        this.$timeout = $timeout;
        this.$parent = $scope.$parent.$ctrl;

        $ngRedux.subscribe(() => {
            this.state = $ngRedux.getState();
            this.uploadAnnotationsError = this.state.projects.uploadAnnotationsError;
        });
    }

    $onInit() {
        this.matchKeys = {};
        this.defaultKeys = {
            label: '',
            description: '',
            quality: null
        };
        this.bindGeoJSONUploadEvent();
        this.bindShapefileUploadEvent();
        this.isMachineData = false;

        this.$scope.$watch('$ctrl.$parent.annotationShapefileProps', (props) => {
            if (props && props.length) {
                this.hasShapefileProps = true;
                this.dataProperties = props;
            }
        });
    }

    bindGeoJSONUploadEvent() {
        $('#geojson-btn-upload').change((e) => {
            let upload = _.values(e.target.files);
            if (upload.length) {
                upload.forEach((datum) => {
                    let reader = new FileReader();
                    reader.onload = (event) => {
                        this.setSelectionMenuItems(JSON.parse(event.target.result));
                    };
                    reader.readAsText(datum);
                });
            }
        });
    }

    bindShapefileUploadEvent() {
        $('#shapefile-btn-upload').change((e) => {
            let upload = _.values(e.target.files);
            if (upload.length) {
                upload.forEach((datum) => {
                    this.setShapefileUploadData(datum);
                });
            }
        });
    }

    isMachineMade() {
        this.isMachineData = !this.isMachineData;
        if (!this.isMachineData) {
            this.matchKeys = _.pick(this.matchKeys, ['label', 'description']);
            if (_.keys(this.matchKeys).length !== 2) {
                this.enableImport = false;
            } else {
                this.enableImport = true;
            }
        } else if (this.isMachineData && _.keys(this.matchKeys).length !== 4) {
            this.enableImport = false;
        }
    }

    setSelectionMenuItems(data) {
        this.uploadData = data;
        this.dataProperties = data.features.reduce((accu, feature) => {
            return _.intersection(accu, Object.keys(feature.properties));
        }, Object.keys(data.features[0].properties));
        this.$scope.$apply();
    }

    setShapefileUploadData(shapefileData) {
        this.shapefileData = shapefileData;
        this.$parent.uploadShapefile(shapefileData);
    }

    updateKeySelection(appKey, dataKey) {
        this.matchKeys[appKey] = dataKey;
        if (this.isMachineData && _.keys(this.matchKeys).length === 4) {
            this.enableImport = true;
        } else if (!this.isMachineData && _.keys(this.matchKeys).length === 2) {
            this.enableImport = true;
        }
    }

    hasDefaultVal(appKey) {
        return typeof this.defaultKeys[appKey] !== 'undefined';
    }

    defaultKeySelection(appKey, defaultVal) {
        this.defaultKeys[appKey] = defaultVal;
    }

    getValOrDefault(appKey, feature) {
        if (this.matchKeys[appKey]) {
            return feature.properties[this.matchKeys[appKey]];
        }
        return this.defaultKeys[appKey];
    }

    onImportClick() {
        if (this.uploadData) {
            this.$parent.createAnnotations({
                'type': 'FeatureCollection',
                'features': this.uploadData.features.map((feature) => {
                    let confidence = null;
                    let quality = null;
                    if (this.isMachineData) {
                        confidence = this.matchKeys.confidence ?
                            feature.properties[this.matchKeys.confidence] : null;
                        quality = this.getValOrDefault('quality', feature);
                    }
                    return {
                        'properties': {
                            'label': this.getValOrDefault('label', feature).toString(),
                            'description': (
                                this.getValOrDefault('description', feature) || ''
                            ).toString(),
                            'machineGenerated': this.isMachineData,
                            'confidence': confidence,
                            'quality': quality
                        },
                        'geometry': feature.geometry,
                        'type': 'Feature'
                    };
                })
            });
        }

        if (this.hasShapefileProps) {
            this.$parent.importShapefileWithProps(this.shapefileData, this.matchKeys);
            this.hasShapefileProps = false;
        }

        this.$state.go('projects.edit.annotate');
    }

    onGoToParent() {
        this.hasShapefileProps = false;
        this.dataProperties = [];
        this.$parent.deleteShapeFileUpload();
        this.$state.go('projects.edit.annotate');
    }
}

const AnnotateImportModule = angular.module('pages.projects.edit.annotate.import', []);

AnnotateImportModule.controller(
    'AnnotateImportController', AnnotateImportController
);

export default AnnotateImportModule;