text:
page_title: Repositories and Images on Docker Hub
page_description: Repositories and Images on Docker Hub
page_keywords: Docker, docker, registry, accounts, plans, Dockerfile, Docker Hub, docs, documentation

# Repositories and Images on Docker Hub

![repositories](/docker-hub/repos.png)

## Searching for repositories and images

You can `search` for all the publicly available repositories and images using
Docker.

    $ docker search ubuntu

This will show you a list of the currently available repositories on the
Docker Hub which match the provided keyword.

If a repository is private it won't be listed on the repository search
results. To see repository statuses, you can look at your [profile
page](https://hub.docker.com) on [Docker Hub](https://hub.docker.com).

## Repositories

Your Docker Hub repositories have a number of useful features.

### Stars

Your repositories can be starred and you can star repositories in
return. Stars are a way to show that you like a repository. They are
also an easy way of bookmarking your favorites.

### Comments

You can interact with other members of the Docker community and maintainers by
leaving comments on repositories. If you find any comments that are not
appropriate, you can flag them for review.

### Collaborators and their role

A collaborator is someone you want to give access to a private
repository. Once designated, they can `push` and `pull` to your
repositories. They will not be allowed to perform any administrative
tasks such as deleting the repository or changing its status from
private to public.

> **Note:**
> A collaborator cannot add other collaborators. Only the owner of
> the repository has administrative access.

You can also collaborate on Docker Hub with organizations and groups.
You can read more about that [here](accounts/).

## Official Repositories

The Docker Hub contains a number of [official
repositories](http://registry.hub.docker.com/official). These are
certified repositories from vendors and contributors to Docker. They
contain Docker images from vendors like Canonical, Oracle, and Red Hat
that you can use to build applications and services.

If you use Official Repositories you know you're using a supported,
optimized and up-to-date image to power your applications.

> **Note:**
> If you would like to contribute an official repository for your
> organization, product or team you can see more information
> [here](https://github.com/docker/stackbrew).

## Private Docker Repositories

Private repositories allow you to have repositories that contain images
that you want to keep private, either to your own account or within an
organization or group.

To work with a private repository on [Docker
Hub](https://hub.docker.com), you will need to add one via the [Add
Repository](https://registry.hub.docker.com/account/repositories/add/)
link. You get one private repository for free with your Docker Hub
account. If you need more accounts you can upgrade your [Docker
Hub](https://registry.hub.docker.com/plans/) plan.

Once the private repository is created, you can `push` and `pull` images
to and from it using Docker.

> *Note:* You need to be signed in and have access to work with a
> private repository.

Private repositories are just like public ones. However, it isn't
possible to browse them or search their content on the public registry.
They do not get cached the same way as a public repository either.

It is possible to give access to a private repository to those whom you
designate (i.e., collaborators) from its Settings page. From there, you
can also switch repository status (*public* to *private*, or
vice-versa). You will need to have an available private repository slot
open before you can do such a switch. If you don't have any available,
you can always upgrade your [Docker
Hub](https://registry.hub.docker.com/plans/) plan.

## Webhooks

You can configure webhooks for your repositories on the Repository
Settings page. A webhook is called only after a successful `push` is
made. The webhook calls are HTTP POST requests with a JSON payload
similar to the example shown below.

> **Note:** For testing, you can try an HTTP request tool like
> [requestb.in](http://requestb.in/).

*Example webhook JSON payload:*

    {
       "push_data":{
          "pushed_at":1385141110,
          "images":[
             "imagehash1",
             "imagehash2",
             "imagehash3"
          ],
          "pusher":"username"
       },
       "repository":{
          "status":"Active",
          "description":"my docker repo that does cool things",
          "is_automated":false,
          "full_description":"This is my full description",
          "repo_url":"https://registry.hub.docker.com/u/username/reponame/",
          "owner":"username",
          "is_official":false,
          "is_private":false,
          "name":"reponame",
          "namespace":"username",
          "star_count":1,
          "comment_count":1,
          "date_created":1370174400,
          "dockerfile":"my full dockerfile is listed here",
          "repo_name":"username/reponame"
       }
    }

Webhooks allow you to notify people, services and other applications of
new updates to your images and repositories.


text:
<readable><title>2053777548_108e54c826</title><content>
A brown and white dog is catching a tennis ball while standing on its hind legs .
A red dog jumps an catches a tennis ball in its mouth .
a skiny dog jumping in the air with a tennis ball in his mouth .
A tan dog jumps up to catch a tennis ball .
The dog jumps to catch the ball .
</content></readable>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.log4j.spi;

/**

   Implementions of this interface allow certain appenders to decide
   when to perform an appender specific action.

For example the {@link org.apache.log4j.net.SMTPAppender} sends
  an email when the {@link #isTriggeringEvent} method returns
  true and adds the event to an internal buffer when the
  returned result is false.

  @author Ceki Gülcü
  @since version 1.0

 */
public interface TriggeringEventEvaluator {

  /**
     Is this the triggering event?
   */
  public boolean isTriggeringEvent(LoggingEvent event);
}


text:
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Verify that it is possible to build an object that depends on a
PrivateFramework.
"""

import os
import sys
import TestGyp

if sys.platform == 'darwin':
  test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])

  CHDIR = 'framework-dirs'
  test.run_gyp('framework-dirs.gyp', chdir=CHDIR)
  test.build('framework-dirs.gyp', 'calculate', chdir=CHDIR)

  test.pass_test()


text:
class CreateCategories < ActiveRecord::Migration[5.1]
  def change
    create_table :categories do |t|
      t.string :name
      t.integer :weight
    end
  end
end


text:
/*
 * Performative.hpp
 *
 *  Created on: Apr 3, 2017
 *      Author: kpvdr
 */

#ifndef SRC_AMQPANALYZE_AMQP10_PERFORMATIVE_HPP_
#define SRC_AMQPANALYZE_AMQP10_PERFORMATIVE_HPP_

#include <amqpAnalyze/amqp10/AmqpBlock.hpp>

namespace amqpAnalyze
{
    namespace amqp10
    {
        enum class AmqpRole_t:bool;
        enum class AmqpSenderSettleMode_t:uint8_t;
        enum class AmqpReceiverSettleMode_t:uint8_t;
        class AmqpErrorRecord;
        class AmqpList;
        class AmqpMap;
        class AmqpMessageFormat;
        class AmqpSource;
        class AmqpTarget;
        class CompositeType;

        enum class PerformativeType_t:uint64_t {
            OPEN=0x10,
            BEGIN,
            ATTACH,
            FLOW,
            TRANSFER,
            DISPOSITION,
            DETACH,
            END,
            CLOSE
        };

        class Performative: public AmqpBlock {
        public:
            Performative(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~Performative();

            std::ostringstream& appendString(std::ostringstream& oss, std::size_t margin, bool ignoreFirstMargin) const override;
            inline AmqpBlockType_t blockType() const override { return AmqpBlockType_t::PERFORMATIVE; }
            inline const AmqpList* fieldList() const { return _fieldListPtr; }
            virtual const FieldTypeList_t& fieldTypeList() const = 0;
            virtual PerformativeType_t type() const = 0;
            inline const char* typeStr() const { return s_performativeTypeName.at(type()); }
            void validate() override;

        protected:
            AmqpList* _fieldListPtr;

            static std::map<PerformativeType_t, const char*> s_performativeTypeName;
        };

#define AMQPOPEN_FN_CONTAINER_ID "container-id"
#define AMQPOPEN_FN_HOSTNAME "hostname"
#define AMQPOPEN_FN_MAX_FRAME_SIZE "max-frame-size"
#define AMQPOPEN_FN_CHANNEL_MAX "channel-max"
#define AMQPOPEN_FN_IDLE_TIME_OUT "idle-time-out"
#define AMQPOPEN_FN_OUTGOING_LOCALES "outgoing-locales"
#define AMQPOPEN_FN_INCOMING_LOCALES "incoming-locales"
#define AMQPOPEN_FN_OFFERED_CAPABILITIES "offered-capabilities"
#define AMQPOPEN_FN_DESIRED_CAPABILITIES "desired-capabilities"
#define AMQPOPEN_FN_PROPERTIES "properties"

        class AmqpOpen: public Performative {
        public:
            AmqpOpen(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpOpen();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::OPEN; }
            void validate() override;

            // convenience getter methods
            const std::string& containerId(bool throwFlag) const; // required
            const std::string& hostname(bool throwFlag) const;
            uint32_t maxFrameSize(bool throwFlag) const;
            uint16_t channelMax(bool throwFlag) const;
            uint32_t idleTimeOut(bool throwFlag) const;
            const AmqpArray_t& outgoingLocales(bool throwFlag) const;
            const AmqpArray_t& incomingLocales(bool throwFlag) const;
            const AmqpArray_t& offeredCapabilities(bool throwFlag) const;
            const AmqpArray_t& desiredCapabilities(bool throwFlag) const;
            const AmqpMap_t& properties(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPBEGIN_FN_REMOTE_CHANNEL "remote-channel"
#define AMQPBEGIN_FN_NEXT_OUTGOING_ID "next-outgoing-id"
#define AMQPBEGIN_FN_INCOMING_WINDOW "incoming-window"
#define AMQPBEGIN_FN_OUTGOING_WINDOW "outgoing-window"
#define AMQPBEGIN_FN_HANDLE_MAX "handle-max"
#define AMQPBEGIN_FN_OFFERED_CAPABILITIES "offered-capabilities"
#define AMQPBEGIN_FN_DESIRED_CAPABILITIES "desired-capabilities"
#define AMQPBEGIN_FN_PROPERTIES "properties"

        class AmqpBegin: public Performative {
        public:
            AmqpBegin(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpBegin();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::BEGIN; }
            void validate() override;

            // convenience getter methods
            uint16_t remoteChannel(bool throwFlag) const;
            uint32_t nextOutgoingId(bool throwFlag) const; // req'd
            uint32_t incomingWindow(bool throwFlag) const; // req'd
            uint32_t outgoingWindow(bool throwFlag) const; // req'd
            uint32_t handleMax(bool throwFlag) const;
            const AmqpArray_t& offeredCapabilities(bool throwFlag) const;
            const AmqpArray_t& desiredCapabilities(bool throwFlag) const;
            const AmqpMap_t& properties(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPATTACH_FN_NAME "name"
#define AMQPATTACH_FN_HANDLE "handle"
#define AMQPATTACH_FN_ROLE "role"
#define AMQPATTACH_FN_SND_SETTLE_MODE "snd-settle-mode"
#define AMQPATTACH_FN_RCV_SETTLE_MODE "rcv-settle-mode"
#define AMQPATTACH_FN_SOURCE "source"
#define AMQPATTACH_FN_TARGET "target"
#define AMQPATTACH_FN_UNSETTLED "unsettled"
#define AMQPATTACH_FN_INOMPLETE_UNSETTTLED "incomplete-unsettled"
#define AMQPATTACH_FN_INITIAL_DELIVERY_COUNT "initial-delivery-count"
#define AMQPATTACH_FN_MAX_MESSAGE_SIZE "max-message-size"
#define AMQPATTACH_FN_OFFERED_CAPABILITES "offered-capabilities"
#define AMQPATTACH_FN_DESIRED_CAPABILITIES "desired-capabilities"
#define AMQPATTACH_FN_PROPERTIES "properties"
        class AmqpAttach: public Performative {
        public:
            AmqpAttach(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpAttach();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::ATTACH; }
            void validate() override;

            // convenience getter methods
            const std::string& name(bool throwFlag) const; // TODO: shadows AmqpBlock::name()
            uint32_t handle(bool throwFlag) const;
            AmqpRole_t role(bool throwFlag) const;
            AmqpSenderSettleMode_t sndSettleMode(bool throwFlag) const;
            AmqpReceiverSettleMode_t rcvSettleMode(bool throwFlag) const;
            const AmqpSource* source(bool throwFlag) const;
            const AmqpTarget* target(bool throwFlag) const;
            const AmqpMap_t& unsettled(bool throwFlag) const;
            bool incompleteUnsettled(bool throwFlag) const;
            uint32_t initialDeliveryCount(bool throwFlag) const;
            uint64_t maxMessageSize(bool throwFlag) const;
            const AmqpArray_t& offeredCapabilities(bool throwFlag) const;
            const AmqpArray_t& desiredCapabilities(bool throwFlag) const;
            const AmqpMap_t& properties(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPFLOW_FN_NEXT_INCOMING_ID "next-incoming-id"
#define AMQPFLOW_FN_INCOMING_WINDOW "incoming-window"
#define AMQPFLOW_FN_NEXT_OUTGOING_WINDOW "next-outgoing-id"
#define AMQPFLOW_FN_OUTGOING_WINDOW "outgoing-window"
#define AMQPFLOW_FN_HANDLE "handle"
#define AMQPFLOW_FN_DELIVERY_COUNT "delivery-count"
#define AMQPFLOW_FN_LINK_CREDIT "link-credit"
#define AMQPFLOW_FN_AVAILABLE "available"
#define AMQPFLOW_FN_DRAIN "drain"
#define AMQPFLOW_FN_ECHO "echo"
#define AMQPFLOW_FN_PROPERTIES "properties"
        class AmqpFlow: public Performative {
        public:
            AmqpFlow(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpFlow();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::FLOW; }
            void validate() override;

            // convenience getter methods
            uint32_t nextIncomingId(bool throwFlag) const;
            uint32_t incomingWindow(bool throwFlag) const; // req'd
            uint32_t nextOutgoingId(bool throwFlag) const; // req'd
            uint32_t outgoingWindow(bool throwFlag) const; // req'd
            uint32_t handle(bool throwFlag) const;
            uint32_t deliveryCount(bool throwFlag) const;
            uint32_t linkCredit(bool throwFlag) const;
            uint32_t available(bool throwFlag) const;
            bool drain(bool throwFlag) const;
            bool echo(bool throwFlag) const;
            const AmqpMap_t& properties(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPTRANSFER_FN_HANDLE "handle"
#define AMQPTRANSFER_FN_DELIVERY_ID "delivery-id"
#define AMQPTRANSFER_FN_DELIVERY_TAG "delivery-tag"
#define AMQPTRANSFER_FN_MESSAGE_FORMAT "message-format"
#define AMQPTRANSFER_FN_SETTLED "settled"
#define AMQPTRANSFER_FN_MORE "more"
#define AMQPTRANSFER_FN_RCV_SETTLE_MODE "rcv-settle-mode"
#define AMQPTRANSFER_FN_STATE "state"
#define AMQPTRANSFER_FN_RESUME "resume"
#define AMQPTRANSFER_FN_ABORTED "aborted"
#define AMQPTRANSFER_FN_BATCHABLE "batchable"
        class AmqpTransfer: public Performative {
        public:
            AmqpTransfer(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpTransfer();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::TRANSFER; }
            void validate() override;

            // convenience getter methods
            uint32_t handle(bool throwFlag) const; // req'd
            uint32_t deliveryId(bool throwFlag) const;
            const AmqpBinary_t& deliveryTag(bool throwFlag) const;
            uint32_t messageFormat(bool throwFlag) const;
            const AmqpMessageFormat* messageFormatObj(bool throwFlag) const;
            bool settled(bool throwFlag) const;
            bool more(bool throwFlag) const;
            AmqpReceiverSettleMode_t rcvSettleMode(bool throwFlag) const;
            const CompositeType* state(bool throwFlag) const;
            bool resume(bool throwFlag) const;
            bool aborted(bool throwFlag) const;
            bool batchable(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPDISPOSITION_FN_ROLE "role"
#define AMQPDISPOSITION_FN_FIRST "first"
#define AMQPDISPOSITION_FN_LAST "last"
#define AMQPDISPOSITION_FN_SETTLED "settled"
#define AMQPDISPOSITION_FN_STATE "state"
#define AMQPDISPOSITION_FN_BATCHABLE "batchable"
        class AmqpDisposition: public Performative {
        public:
            AmqpDisposition(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpDisposition();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::DISPOSITION; }
            void validate() override;

            // convenience getter methods
            AmqpRole_t role(bool throwFlag) const;
            uint32_t first(bool throwFlag) const;
            uint32_t last(bool throwFlag) const;
            bool settled(bool throwFlag) const;
            const CompositeType* state(bool throwFlag) const;
            bool batchable(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPDETACH_FN_HANDLE "handle"
#define AMQPDETACH_FN_CLOSED "closed"
#define AMQPDETACH_FN_ERROR "error"
        class AmqpDetach: public Performative {
        public:
            AmqpDetach(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpDetach();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::DETACH; }
            void validate() override;

            // convenience getter methods
            uint32_t handle(bool throwFlag) const;
            bool cloased(bool throwFlag) const;
            const AmqpErrorRecord* error(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPEND_FN_ERROR "error"

        class AmqpEnd: public Performative {
        public:
            AmqpEnd(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpEnd();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::END; }
            void validate() override;

            // convenience getter methods
            const AmqpErrorRecord* error(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

#define AMQPCLOSE_FN_ERROR "error"

        class AmqpClose: public Performative {
        public:
            AmqpClose(uint64_t packetNum, std::size_t dataOffset, AmqpList* fieldListPtr);
            virtual ~AmqpClose();

            inline const FieldTypeList_t& fieldTypeList() const override { return s_fieldTypeList; };
            inline PerformativeType_t type() const override { return PerformativeType_t::CLOSE; }
            void validate() override;

            // convenience getter methods
            const AmqpErrorRecord* error(bool throwFlag) const;

            static const FieldTypeList_t s_fieldTypeList;
        };

    } /* namespace amqp10 */
} /* namespace amqpAnalyze */

#endif /* SRC_AMQPANALYZE_AMQP10_PERFORMATIVE_HPP_ */


text:
package org.fujion.jmx;

import com.udojava.jmx.wrapper.JMXBean;
import com.udojava.jmx.wrapper.JMXBeanAttribute;
import com.udojava.jmx.wrapper.JMXBeanOperation;
import com.udojava.jmx.wrapper.JMXBeanOperation.IMPACT_TYPES;
import org.fujion.common.StrUtil;
import org.fujion.expression.ExpressionCache;
import org.fujion.jmx.JMXConsole.IJMXConsolePlugin;
import org.fujion.page.PageDefinitionCache;
import org.springframework.web.context.ServletContextAware;

import javax.servlet.ServletContext;

/**
 * JMX console plugin for cache management.
 */
@JMXBean(resourceBundleName = "org.fujion.common.MessageBundle", descriptionKey = "org.fujion.console.cache.description", sorted = true)
public class CacheManagementConsole implements IJMXConsolePlugin, ServletContextAware {

    private final PageDefinitionCache fspCache = PageDefinitionCache.getInstance();

    private final ExpressionCache elCache = ExpressionCache.getInstance();

    private String type;

    @Override
    public String getType() {
        return type;
    }

    /**
     * Returns the size of the page definition cache.
     *
     * @return The size of the cache.
     */
    @JMXBeanAttribute(sortValue = "10", nameKey = "org.fujion.console.cache.fsp.size.name", descriptionKey = "org.fujion.console.cache.fsp.size.description")
    public String getFSPCacheSize() {
        int size = fspCache.size();
        return formatResult("fsp.size", size);
    }

    /**
     * Clears the page definition cache.
     *
     * @return The result of the operation.
     */
    @JMXBeanOperation(sortValue = "11", nameKey = "org.fujion.console.cache.fsp.clear.name", impactType = IMPACT_TYPES.ACTION, descriptionKey = "org.fujion.console.cache.fsp.clear.description")
    public String clearFSPCache() {
        int size = fspCache.size();
        fspCache.clear();
        return formatResult("fsp.clear", size);
    }

    /**
     * Refreshes the page definition cache.
     *
     * @return The result of the operation.
     */
    @JMXBeanOperation(sortValue = "12", nameKey = "org.fujion.console.cache.fsp.refresh.name", impactType = IMPACT_TYPES.ACTION, descriptionKey = "org.fujion.console.cache.fsp.refresh.description")
    public String refreshFSPCache() {
        int size = fspCache.size();
        fspCache.refresh();
        return formatResult("fsp.refresh", size);
    }

    /**
     * Returns the size of the expression cache.
     *
     * @return The size of the cache.
     */
    @JMXBeanAttribute(sortValue = "20", nameKey = "org.fujion.console.cache.exp.size.name", descriptionKey = "org.fujion.console.cache.exp.size.description")
    public String getELCacheSize() {
        int size = elCache.size();
        return formatResult("exp.size", size);
    }

    /**
     * Clears the expression cache.
     *
     * @return The result of the operation.
     */
    @JMXBeanOperation(sortValue = "21", nameKey = "org.fujion.console.cache.exp.clear.name", impactType = IMPACT_TYPES.ACTION, descriptionKey = "org.fujion.console.cache.exp.clear.description")
    public String clearELCache() {
        int size = elCache.size();
        elCache.clear();
        return formatResult("exp.clear", size);
    }

    private String formatResult(String id, Object... args) {
        return StrUtil.getLabel("org.fujion.console.cache." + id + ".result", args);
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        type = "Cache Manager [" + servletContext.getContextPath().replace("/", "") + "]";
    }
}


text:
package org.apache.accumulo.tserver.log;

import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.ScannerBase;
import org.apache.accumulo.core.client.rfile.RFile;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.server.ServerContext;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.server.log.SortedLogState;
import org.apache.accumulo.tserver.logger.LogEvents;
import org.apache.accumulo.tserver.logger.LogFileKey;
import org.apache.accumulo.tserver.logger.LogFileValue;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Iterators;

/**
 * Iterates over multiple sorted recovery logs merging them into a single sorted stream.
 */
public class RecoveryLogsIterator
    implements Iterator<Entry<LogFileKey,LogFileValue>>, AutoCloseable {

  private static final Logger LOG = LoggerFactory.getLogger(RecoveryLogsIterator.class);

  private final List<Scanner> scanners;
  private final Iterator<Entry<Key,Value>> iter;

  /**
   * Scans the files in each recoveryLogDir over the range [start,end].
   */
  public RecoveryLogsIterator(ServerContext context, List<Path> recoveryLogDirs, LogFileKey start,
      LogFileKey end, boolean checkFirstKey) throws IOException {

    List<Iterator<Entry<Key,Value>>> iterators = new ArrayList<>(recoveryLogDirs.size());
    scanners = new ArrayList<>();
    Range range = start == null ? null : LogFileKey.toRange(start, end);
    var vm = context.getVolumeManager();

    for (Path logDir : recoveryLogDirs) {
      LOG.debug("Opening recovery log dir {}", logDir.getName());
      List<Path> logFiles = getFiles(vm, logDir);
      var fs = vm.getFileSystemByPath(logDir);

      // only check the first key once to prevent extra iterator creation and seeking
      if (checkFirstKey) {
        validateFirstKey(context, fs, logFiles, logDir);
      }

      for (Path log : logFiles) {
        var scanner = RFile.newScanner().from(log.toString()).withFileSystem(fs)
            .withTableProperties(context.getConfiguration()).build();

        scanner.setRange(range);
        Iterator<Entry<Key,Value>> scanIter = scanner.iterator();

        if (scanIter.hasNext()) {
          LOG.debug("Write ahead log {} has data in range {} {}", log.getName(), start, end);
          iterators.add(scanIter);
          scanners.add(scanner);
        } else {
          LOG.debug("Write ahead log {} has no data in range {} {}", log.getName(), start, end);
          scanner.close();
        }
      }
    }
    iter = Iterators.mergeSorted(iterators, Entry.comparingByKey());
  }

  @Override
  public boolean hasNext() {
    return iter.hasNext();
  }

  @Override
  public Entry<LogFileKey,LogFileValue> next() {
    Entry<Key,Value> e = iter.next();
    return new AbstractMap.SimpleImmutableEntry<>(LogFileKey.fromKey(e.getKey()),
        LogFileValue.fromValue(e.getValue()));
  }

  @Override
  public void remove() {
    throw new UnsupportedOperationException("remove");
  }

  @Override
  public void close() {
    scanners.forEach(ScannerBase::close);
  }

  /**
   * Check for sorting signal files (finished/failed) and get the logs in the provided directory.
   */
  private List<Path> getFiles(VolumeManager fs, Path directory) throws IOException {
    boolean foundFinish = false;
    List<Path> logFiles = new ArrayList<>();
    for (FileStatus child : fs.listStatus(directory)) {
      if (child.getPath().getName().startsWith("_"))
        continue;
      if (SortedLogState.isFinished(child.getPath().getName())) {
        foundFinish = true;
        continue;
      }
      if (SortedLogState.FAILED.getMarker().equals(child.getPath().getName())) {
        continue;
      }
      FileSystem ns = fs.getFileSystemByPath(child.getPath());
      Path fullLogPath = ns.makeQualified(child.getPath());
      logFiles.add(fullLogPath);
    }
    if (!foundFinish)
      throw new IOException(
          "Sort '" + SortedLogState.FINISHED.getMarker() + "' flag not found in " + directory);
    return logFiles;
  }

  /**
   * Check that the first entry in the WAL is OPEN. Only need to do this once.
   */
  private void validateFirstKey(ServerContext context, FileSystem fs, List<Path> logFiles,
      Path fullLogPath) {
    try (var scanner =
        RFile.newScanner().from(logFiles.stream().map(Path::toString).toArray(String[]::new))
            .withFileSystem(fs).withTableProperties(context.getConfiguration()).build()) {
      Iterator<Entry<Key,Value>> iterator = scanner.iterator();
      if (iterator.hasNext()) {
        Key firstKey = iterator.next().getKey();
        LogFileKey key = LogFileKey.fromKey(firstKey);
        if (key.event != LogEvents.OPEN) {
          throw new IllegalStateException("First log entry is not OPEN " + fullLogPath);
        }
      }
    }
  }
}


text:
package com.google.appengine.datanucleus.test.jdo;

import com.google.appengine.api.datastore.Key;

import java.util.List;

import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.InheritanceStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

/**
 * @author Max Ross <max.ross@gmail.com>
 */
public class AbstractBaseClassesJDO {

  private AbstractBaseClassesJDO() {}

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  @Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
  public abstract static class Base1 {
    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    private String base1Str;

    @Persistent(dependent = "true")
    private Concrete3 concrete3;

    @Persistent
    @Element(dependent = "true")
    private List<Concrete4> concrete4;

    public Long getId() {
      return id;
    }

    public void setId(Long id) {
      this.id = id;
    }

    public String getBase1Str() {
      return base1Str;
    }

    public void setBase1Str(String base1Str) {
      this.base1Str = base1Str;
    }

    public Concrete3 getConcrete3() {
      return concrete3;
    }

    public void setConcrete3(Concrete3 concrete3) {
      this.concrete3 = concrete3;
    }

    public List<Concrete4> getConcrete4() {
      return concrete4;
    }

    public void setConcrete4(List<Concrete4> concrete4) {
      this.concrete4 = concrete4;
    }
  }

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public static class Concrete1 extends Base1 {
    private String concrete1Str;

    public String getConcrete1Str() {
      return concrete1Str;
    }

    public void setConcrete1Str(String concrete1Str) {
      this.concrete1Str = concrete1Str;
    }
  }

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  @Inheritance(strategy = InheritanceStrategy.SUBCLASS_TABLE)
  public abstract static class Base2 extends Base1 {
    private String base2Str;

    public String getBase2Str() {
      return base2Str;
    }

    public void setBase2Str(String base2Str) {
      this.base2Str = base2Str;
    }
  }

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public static class Concrete2 extends Base2 {
    private String concrete2Str;

    public String getConcrete2Str() {
      return concrete2Str;
    }

    public void setConcrete2Str(String concrete2Str) {
      this.concrete2Str = concrete2Str;
    }
  }

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public static class Concrete3 {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;

    private String str;

    public Key getId() {
      return id;
    }

    public String getStr() {
      return str;
    }

    public void setStr(String str) {
      this.str = str;
    }
  }

  @PersistenceCapable(identityType = IdentityType.APPLICATION)
  public static class Concrete4 {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key id;

    private String str;

    public Key getId() {
      return id;
    }

    public String getStr() {
      return str;
    }

    public void setStr(String str) {
      this.str = str;
    }
  }
}


text:
from PyQt4.QtGui import (QVBoxLayout, QHBoxLayout, QTableWidgetItem,
                         QIcon, QGridLayout, QSplitter, QLineEdit, QFrame,
                         QPushButton, QMenu, QComboBox)
from PyQt4.QtCore import QDate, Qt, SIGNAL

from configuration import Config
from Common.ui.common import (FWidget, IntLineEdit,
                              FormLabel, FormatDate)
from Common.ui.util import is_int, date_to_datetime, date_on_or_end
from Common.ui.table import FTableWidget
from peewee import fn

from ui.reports_managers import GReportViewWidget
from GCommon.ui._product_detail import InfoTableWidget
from models import (Store, Product, Reports)

class StockOutputWidget(FWidget):

    def __init__(self, store="", parent=0, *args, **kwargs):
        super(StockOutputWidget, self).__init__(parent=parent, *args, **kwargs)
        self.parentWidget().setWindowTitle(
            "{} {}".format(Config.APP_NAME, "SORTIE STOCK "))
        self.parent = parent
        self.store = store
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout(self)
        editbox = QGridLayout()

        self.date_out = FormatDate(QDate.currentDate())

        # Combobox widget for add store
        self.liste_store = Store.all()

        self.box_store = QComboBox()
        for index in range(0, len(self.liste_store)):
            op = self.liste_store[index]
            self.box_store.addItem(op.name, op.id)
            if self.store and self.store.name == op.name:
                self.box_store.setCurrentIndex(index)

        self.search_field = QLineEdit()
        self.search_field.setPlaceholderText("Rechercher un article")
        self.search_field.setMaximumSize(
            200, self.search_field.maximumSize().height())
        self.search_field.textChanged.connect(self.finder)

        self.vline = QFrame()
        self.vline.setFrameShape(QFrame.VLine)
        self.vline.setFrameShadow(QFrame.Sunken)

        self.table_resultat = ResultatTableWidget(parent=self)
        self.table_info = InfoTableWidget(parent=self)
        self.table_out = InproductTableWidget(parent=self)
        self.box_store.connect(self.box_store,
                               SIGNAL("currentIndexChanged(int)"),
                               self.table_out.changed_value)

        self.table_resultat.refresh_("")
        # editbox.addWidget(FormLabel(u"Recherche:"), 0, 0)
        editbox.addWidget(self.search_field, 0, 0)

        editbox.addWidget(self.vline, 0, 2, 1, 1)

        editbox.addWidget(FormLabel(u"Magasin:"), 0, 4)
        editbox.addWidget(self.box_store, 0, 5)
        editbox.addWidget(FormLabel(u"Date d'achat:"), 0, 6)
        editbox.addWidget(self.date_out, 0, 7)

        editbox.setColumnStretch(3, 3)
        splitter = QSplitter(Qt.Horizontal)

        splitter_left = QSplitter(Qt.Vertical)
        # splitter_left.addWidget(FBoxTitle(u"Les products"))
        splitter_left.addWidget(self.table_resultat)

        splitter_down = QSplitter(Qt.Vertical)
        splitter_down.resize(15, 20)
        splitter_down.addWidget(self.table_info)

        splitter_rigth = QSplitter(Qt.Vertical)
        # splitter_rigth.addWidget(FBoxTitle(u"Les products achatés"))
        splitter_rigth.addWidget(self.table_out)
        splitter_rigth.resize(500, 900)

        splitter_left.addWidget(splitter_down)
        splitter.addWidget(splitter_left)
        splitter.addWidget(splitter_rigth)

        hbox.addWidget(splitter)
        vbox.addLayout(editbox)
        vbox.addLayout(hbox)
        self.setLayout(vbox)

    def finder(self):
        value = str(self.search_field.text())
        self.table_resultat.refresh_(value)

    def save_report(self):
        ''' add operation '''
        # entete de la facture
        self.table_out.changed_value()
        if not self.table_out.isvalid:
            return False
        date_out = str(self.date_out.text())
        datetime_ = date_to_datetime(date_out)
        self.current_store = self.liste_store[self.box_store.currentIndex()]

        values_t = self.table_out.get_table_items()

        for qty, name in values_t:
            rep = Reports(type_=Reports.S, store=self.current_store,
                          date=datetime_, product=Product.get(name=name),
                          qty_use=int(qty))
            try:
                rep.save()
            except:
                self.parent.Notify(
                    u"Ce mouvement n'a pas pu être enrgistré dans les raports",
                    "error")
                return False

        self.parent.change_context(GReportViewWidget)
        self.parent.Notify(u"La sortie des articles avec succès", "success")

class ResultatTableWidget(FTableWidget):

    """docstring for ResultatTableWidget"""

    def __init__(self, parent, *args, **kwargs):
        FTableWidget.__init__(self, parent=parent, *args, **kwargs)

        self.parent = parent

        self.hheaders = [u"i", u"Resultat", u"Ajouter"]
        self.stretch_columns = [1]
        self.align_map = {1: 'l'}
        # self.display_fixed = True
        # self.display_vheaders = False
        self.refresh_()

    def refresh_(self, value=None):
        """ """
        pw = self.width()
        self.setColumnWidth(0, 20)
        self.setColumnWidth(1, pw)
        self.setColumnWidth(2, 40)
        self._reset()
        self.set_data_for(value)
        self.refresh()

    def set_data_for(self, value):

        products = [(Product.get(id=rpt.product_id).name) for rpt in
                    Reports.select(fn.Distinct(Reports.product))]
        if value:
            products = [(prod.name) for prod in Product.select(
            ).where(Product.name.contains(value)).where(
                Product.name << products).order_by(Product.name.desc())]
        self.data = [("", rpt, "") for rpt in products]

    def _item_for_data(self, row, column, data, context=None):
        if column == 2:
            return QTableWidgetItem(
                QIcon(u"{img_media}{img}".format(img_media=Config.img_cmedia,
                                                 img="go-next.png")), "")
        if column == 0:
            return QTableWidgetItem(
                QIcon(u"{img_media}{img}".format(img_media=Config.img_cmedia,
                                                 img="info.png")), "")
        return super(ResultatTableWidget, self)._item_for_data(row, column,
                                                               data, context)

    def click_item(self, row, column, *args):
        self.choix = Product.filter(name=self.data[row][1]).get()
        if column != 2:
            self.parent.table_info.refresh_(self.choix.id)
        if column == 2:
            self.parent.table_out.refresh_(self.choix)

class InproductTableWidget(FTableWidget):

    def __init__(self, parent, *args, **kwargs):
        FTableWidget.__init__(self, parent=parent, *args, **kwargs)

        self.parent = parent

        self.hheaders = ["Quantité (carton)", "Nombre pièce", "Désignation"]

        # self.setSelectionMode(QAbstractItemView.NoSelection)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.popup)

        self.stretch_columns = [0, 1, 2]
        self.align_map = {0: 'r', 1: 'r', 2: 'l'}
        self.display_vheaders = False
        # self.display_fixed = True
        self.refresh_()
        # self.isvalid = True
        self.col_dest = 2
        self.col_qtty = 0

    def refresh_(self, choix=None):
        if choix:
            self.row = [1, choix.number_parts_box, choix.name]
            if not [row for row in self.data if self.row[
                    self.col_dest] in row]:
                self.set_data_for()
                self.refresh()
            self.refresh()

    def set_data_for(self):

        self._reset()
        self.data.extend([self.row])
        self.refresh_()
        pw = self.width() / 4 - 20
        self.setColumnWidth(0, pw)
        self.setColumnWidth(1, pw)
        self.setColumnWidth(2, (pw * 2))

    def popup(self, pos):
        if (len(self.data) - 1) < self.selectionModel().selection().indexes(
        )[0].row():
            return False
        menu = QMenu()
        quit_action = menu.addAction("Supprimer cette ligne")
        action = menu.exec_(self.mapToGlobal(pos))
        if action == quit_action:
            try:
                self.data.pop(self.selectionModel()
                                  .selection().indexes()[0].row())
            except IndexError:
                pass
            if self.data == []:
                self._reset()
            self.refresh()

    def extend_rows(self):
        nb_rows = self.rowCount()

        self.setRowCount(nb_rows + 1)
        bicon = QIcon.fromTheme(
            '', QIcon(u"{img_media}{img}".format(img_media=Config.img_cmedia,
                                                 img='save.png')))
        self.button = QPushButton(bicon, u"Enrgistrer la sortie")
        self.button.released.connect(self.parent.save_report)
        self.setCellWidget(nb_rows, self.col_dest, self.button)

    def _item_for_data(self, row, column, data, context=None):
        if column == 0:
            self.line_edit = IntLineEdit(u"%s" % data)
            self.line_edit.textChanged.connect(self.changed_value)
            return self.line_edit
        return super(InproductTableWidget, self)._item_for_data(
            row, column, data, context)

    def _update_data(self, row_num, new_data):
        self.data[row_num] = (new_data[0], new_data[1], self.data[row_num][2])

    def get_table_items(self):
        """  """
        list_order = []
        for i in range(self.rowCount() - 1):
            liste_item = []
            row_data = self.data[i]
            try:
                liste_item.append(int(row_data[self.col_qtty]))
                liste_item.append(str(row_data[self.col_dest]))
                list_order.append(liste_item)
            except:
                liste_item.append("")

        return list_order

    def changed_value(self, refresh=False):
        """ Calcule les Resultat """
        current_store = self.parent.liste_store[
            self.parent.box_store.currentIndex()]

        self.button.setEnabled(True)
        self.isvalid = True
        for row_num in range(0, self.data.__len__()):
            qtsaisi = is_int(self.cellWidget(row_num, self.col_qtty).text())

            nb_parts_box = Product.filter(
                name=self.item(row_num, self.col_dest).text()).get(
            ).number_parts_box * qtsaisi

            self.setItem(row_num, 1, QTableWidgetItem(
                "{}".format(nb_parts_box)))

            self._update_data(row_num, [qtsaisi, nb_parts_box])

            try:
                last_report = Reports.filter(
                    store=current_store, product__name=str(
                        self.item(row_num, self.col_dest).text())).order_by(
                    Reports.date.desc()).get()
                qtremaining = last_report.remaining
                date_out = str(self.parent.date_out.text())
                if last_report.date > date_on_or_end(date_out, on=False):
                    self.parent.date_out.setStyleSheet("font-size:15px;"
                                                       "color:red")
                    self.parent.date_out.setToolTip(
                        "Cette date est Inférieure à la date de la dernière rapport ({}).".format(last_report.date))
                    self.isvalid = False
                    self.button.setEnabled(False)
                    # return False

            except Exception as e:
                qtremaining = 0

            viderreur_qtsaisi = ""
            stylerreur = "background-color: rgb(255, 235, 235);" + \
                "border: 3px double SeaGreen"
            if qtsaisi == 0:
                viderreur_qtsaisi = stylerreur
                self.cellWidget(row_num, self.col_qtty).setToolTip(
                    u"obligatoire")
                self.isvalid = False
                self.button.setEnabled(False)

            self.cellWidget(row_num, self.col_qtty).setStyleSheet(
                viderreur_qtsaisi)

            self.cellWidget(row_num, self.col_qtty).setToolTip("")
            if qtremaining < qtsaisi:
                self.cellWidget(row_num, self.col_qtty).setStyleSheet(
                    "font-size:20px; color: red")
                self.cellWidget(
                    row_num, self.col_qtty).setToolTip(
                    u"{} est > {} la quantité restante.".format(
                        qtsaisi, qtremaining))
                self.isvalid = False
                # self.button.setEnabled(False)


text:
macro_rules! def_operation {
    ($name:ident, $operation_name:expr) => {
        #[derive(Clone, Copy)]
        pub struct $name(MlirOperation);

        impl WrapRaw for $name {
            type RawType = MlirOperation;
            fn from_raw(raw: MlirOperation) -> Self {
                Self(raw)
            }
            fn raw(&self) -> MlirOperation {
                self.0
            }
        }

        impl OperationExt for $name {
            fn operation_name() -> &'static str {
                $operation_name
            }
        }
    };
}

/// Define an operation with a single result.
macro_rules! def_operation_single_result {
    ($name:ident, $operation_name:expr) => {
        def_operation!($name, $operation_name);

        impl Into<Value> for $name {
            fn into(self) -> Value {
                self.result(0)
            }
        }
    };
}

/// Define a unary operation with the result type inherited from the operand.
#[allow(unused_macros)]
macro_rules! def_simple_unary_operation {
    ($name:ident, $operation_name:expr) => {
        def_operation_single_result!($name, $operation_name);

        impl $name {
            pub fn new(builder: &mut Builder, arg: Value) -> Self {
                builder.build_with(|_, state| {
                    state.add_operand(arg);
                    state.add_result(arg.ty());
                })
            }
        }
    };
}

/// Define a binary operation with the result type inherited from the first
/// operand.
macro_rules! def_simple_binary_operation {
    ($name:ident, $operation_name:expr) => {
        def_operation_single_result!($name, $operation_name);

        impl $name {
            pub fn new(builder: &mut Builder, lhs: Value, rhs: Value) -> Self {
                builder.build_with(|_, state| {
                    state.add_operand(lhs);
                    state.add_operand(rhs);
                    state.add_result(lhs.ty());
                })
            }
        }
    };
}

/// Define a binary operation with an explicit result type.
macro_rules! def_binary_operation_explicit_result {
    ($name:ident, $operation_name:expr) => {
        def_operation_single_result!($name, $operation_name);

        impl $name {
            pub fn new(builder: &mut Builder, ty: Type, lhs: Value, rhs: Value) -> Self {
                builder.build_with(|_, state| {
                    state.add_operand(lhs);
                    state.add_operand(rhs);
                    state.add_result(ty);
                })
            }
        }
    };
}

pub mod builtin;
pub mod cf;
pub mod comb;
pub mod func;
pub mod hw;
pub mod llhd;
pub mod mlir;
pub mod moore;
pub mod seq;

pub use builtin::*;

pub mod sys {
    pub use moore_circt_sys::*;
}

pub mod prelude {
    pub use crate::llhd::EntityLike as _;
    pub use crate::mlir::{
        OperationExt as _, SingleBlockOp as _, SingleRegionOp as _, WrapRaw as _,
    };
}

mod crate_prelude {
    pub use crate::mlir::*;
    pub use crate::prelude::*;
    pub use crate::sys::*;
    pub use num::{BigInt, BigRational, One, ToPrimitive, Zero};
}


text:
#include "posix_file.h"
#include "../script_variable.h"

#define VFS_POSIX_READ_BLOCK 4096

namespace VFS {

PosixFile::PosixFile(const char* filename, AccessMode newMode) :
	File(filename), f(NULL), fileSize(0)
{
	setMode(newMode);
}

PosixFile::~PosixFile() {
	xassert((f != NULL || mode == MODE_CLOSED) && ! (f != NULL && mode == MODE_CLOSED), "Inconsistent file state.");
	if(mode != MODE_CLOSED)
		fclose(f);
}

PosixFile* PosixFile::copy() {
	return new PosixFile(name(), MODE_CLOSED);
}

bool PosixFile::setMode(AccessMode newMode) {
	switch(newMode){
	case MODE_READ:
		f = fopen(name(), "rb");
		break;
	case MODE_WRITE:
		f = fopen(name(), "r+b");
		break;
	case MODE_APPEND:
		f = fopen(name(), "ab");
		break;
	case MODE_TRUNCATE:
		f = fopen(name(), "w+b");
		break;
	case MODE_CLOSED:
		mode = MODE_CLOSED;
		return true;
	}

	if(!f) {
		syslog("PosixFile VFS module : cannot open %s", name());
		return false;
	}

	mode = newMode;

	if(mode == MODE_READ) {
		fseek(f, 0, SEEK_END);
		fileSize = ftell(f);
		rewind(f);
	}

	return true;
}

bool PosixFile::switchMode(AccessMode newMode) {
	if(newMode == mode)
		return true;

	xassert((f != NULL || mode == MODE_CLOSED) && ! (f != NULL && mode == MODE_CLOSED), "Inconsistent file state.");

	// MODE_CLOSED is trivial

	if(mode == MODE_CLOSED) {
		return setMode(newMode);
	}

	if(newMode == MODE_CLOSED) {
		fclose(f);
		f = NULL;
		mode = MODE_CLOSED;
		return true;
	}

	// Bypass re-opening for compatible modes

	if(newMode == MODE_READ && (mode == MODE_WRITE || mode == MODE_TRUNCATE)) {
		seek(0, SEEK_SET);
		mode = newMode;
		return true;
	}

	if(newMode == MODE_APPEND && (mode == MODE_WRITE || mode == MODE_TRUNCATE)) {
		seek(0, SEEK_END);
		mode = newMode;
		return true;
	}

	if(newMode == MODE_TRUNCATE && mode == MODE_WRITE) {
		seek(0, SEEK_SET);
		truncate(0);
		mode = newMode;
		return true;
	}

	// Re-open file for incompatible modes

	fclose(f);
	return setMode(newMode);
}

off_t PosixFile::size() {
	if(mode == MODE_READ) {
		return fileSize;
	}

	if(mode == MODE_CLOSED)
		f = fopen(name(), "rb");
	xerror(f, "Could not open file %s.", name());
	off_t current = ftello(f);
	fseeko(f, 0, SEEK_END);
	fileSize = ftello(f);
	fseeko(f, current, SEEK_SET);
	if(mode == MODE_CLOSED) {
		fclose(f);
		f = NULL;
	}

	return fileSize;
}

File* PosixFile::openRelative(const char* filename, AccessMode mode) const {
	const char* finalName = relPath(name(), filename);
	if(isDirectory(finalName)) {
		return new PosixDirectory(finalName);
	}

	return new PosixFile(finalName, mode);
}

// QC:S
size_t PosixFile::read(void* outputBuffer, size_t bufferLen) {
	char* buffer = (char*) outputBuffer;

	assert(canRead());

	/*XXX*/
	/*
	 size_t blocksRead = 0;
	 if(bufferLen > VFS_POSIX_READ_BLOCK) {
	 blocksRead = fread(buffer, VFS_POSIX_READ_BLOCK, bufferLen/VFS_POSIX_READ_BLOCK, f);
	 buffer += blocksRead*VFS_POSIX_READ_BLOCK;
	 bufferLen -= blocksRead*VFS_POSIX_READ_BLOCK;
	 }
	 size_t lastBlock = fread(buffer, bufferLen, 1, f);*
	 return blocksRead*VFS_POSIX_READ_BLOCK + lastBlock*bufferLen;
	 //*/
	return fread(buffer, 1, bufferLen, f);
}

bool PosixFile::seek(off_t position, int whence) {
	assert(canSeek(position));
	return fseeko(f, position, whence) == 0 ? true : false;
}

PosixDirectory* PosixDirectory::copy() {
	return new PosixDirectory(name());
}

File* PosixDirectory::openRelative(const char* filename, AccessMode mode) const {
	static char finalName[4096];

	if(!*name()) {
		strncpy(finalName, filename, 4096);
	} else {
		// Compute finalName by appending / and filename.
		int filenameLen = strlen(name());
		if(filenameLen > 4096)
			filenameLen = 4096;
		memcpy(finalName, name(), filenameLen);
		finalName[filenameLen] = '/';
		strncpy(finalName + filenameLen + 1, filename, 4096 - (filenameLen + 1));
	}
	finalName[4095] = '\0';

	if(!*finalName)
		return new PosixDirectory(".");

	if(isDirectory(finalName)) {
		return new PosixDirectory(finalName);
	}

	return new PosixFile(finalName, mode);
}

ScriptTable* PosixDirectory::parse() {
	xassert(name(), "Directory has no path information.");
	DIR* dir = opendir(name());
	struct dirent* dp;
	xassert(dir, "Could not open directory %s.", name());

	ScriptTable* result = new ScriptTable;

	while((dp = readdir(dir))) {
		ScriptVariable v;
		v.setval(dp->d_name);
		result->push_back(v);
	}

	closedir(dir);
	return result;
}

// QC:A (TODO:implement recursive lookup)
std::list<std::string> PosixDirectory::listFiles(const char* extension, bool recursive) {
	xassert(name(), "Directory has no path information.");
	DIR* dir = opendir(name());
	struct dirent* dp;
	xassert(dir, "Could not open directory %s.", name());

	std::list<std::string> result;

	while((dp = readdir(dir))) {
		const char* file = dp->d_name;
		const char* extdot = strrchr(file, '.');
		if(!extension || (extdot && strcmp(extdot, extension) == 0)) {
			result.push_back(file);
		}
	}

	closedir(dir);
	return result;
}

#if VFS_ROOT_DIRECTORY == PosixDirectory
const PosixDirectory* root() {
	static PosixDirectory* r = NULL;
	if(!r)
		r = AOENEW PosixDirectory();
	return r;
}
#endif

}


text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	General
	Use Time Sheet Functionality
	Panel Widgets
	Panel widget time sheet
	Export Time Sheet
	Export time sheet of all persons
	Export time sheet of all employers
	Can see time sheet of other persons
</labels>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or
    more contributor license agreements. See the NOTICE file
    distributed with this work for additional information regarding
    copyright ownership. The ASF licenses this file to you under the
    Apache License, Version 2.0 (the "License"); you may not use
    this file except in compliance with the License. You may obtain
    a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0 Unless required by
    applicable law or agreed to in writing, software distributed
    under the License is distributed on an "AS IS" BASIS, WITHOUT
    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions
    and limitations under the License.
-->
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.apache.sling.ide</groupId>
    <artifactId>reactor</artifactId>
    <version>1.0.99-SNAPSHOT</version>
  </parent>
  <artifactId>org.apache.sling.ide.feature</artifactId>
  <packaging>eclipse-feature</packaging>
  <name>Sling IDE Tools: Eclipse Feature</name>

  <scm>
    <connection>scm:svn:http://svn.apache.org/repos/asf/sling/trunk/tooling/ide/feature</connection>
    <developerConnection>scm:svn:https://svn.apache.org/repos/asf/sling/trunk/tooling/ide/feature</developerConnection>
    <url>http://svn.apache.org/viewvc/sling/trunk/tooling/ide/feature</url>
  </scm>

  <build>
    <!-- ensure that extra files are picked up by the maven-source-plugin -->
    <resources>
        <resource>
            <directory>.</directory>
            <includes>
                <include>build.properties</include>
                <include>META-INF/*</include>
                <include>feature.xml</include>
            </includes>
        </resource>
    </resources>
  </build>
</project>


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>All Pawns Must Die: AllPawnsMustDie.MoveInformation Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

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

All Pawns Must Die

Simple GUI for UCI chess engine using C# and Windows Forms

Public Member Functions |
Public Attributes |
Properties |
List of all members

AllPawnsMustDie.MoveInformation Struct Reference

Holds more detailed information on a single move for the GUI.
 More...

Collaboration diagram for AllPawnsMustDie.MoveInformation:

<map name="_all_pawns_must_die_8_move_information_coll__map" id="_all_pawns_must_die_8_move_information_coll__map">
<area shape="rect" id="node2" href="struct_all_pawns_must_die_1_1_board_square.html" title="Wraps a board location " alt="" coords="5,5,208,32"/>
<area shape="rect" id="node3" href="class_all_pawns_must_die_1_1_chess_piece.html" title="Encapsulates a chess piece " alt="" coords="233,5,431,32"/>
</map>
[legend]

Public Member Functions

 	MoveInformation (BoardSquare start, BoardSquare end, bool deployed, string oldFEN)

 	Create a new MoveInformation struct and fill in the minumum required information  More...

override string 	ToString ()

 	Return the move in a SAN friendly format  More...

Public Attributes

BoardSquare 	startSquare

BoardSquare 	endSquare

ChessPiece 	ancillaryPiece

PieceClass 	promotionClass

PieceColor 	color

BoardSide 	castlingRights

bool 	firstMove

bool 	isCapture

bool 	isCastle

string 	prevFEN

Properties

ChessPiece 	CapturedPiece [get, set]

 	If not null, the piece that was captured on this move.  More...

ChessPiece 	CastlingRook [get, set]

 	If not null, the Rook associated with the castle  More...

PieceClass 	PromotionJob [get, set]

 	Property for the promotion job  More...

PieceColor 	Color [get, set]

 	Color of the move  More...

BoardSide 	CastlingRights [get, set]

 	Castling rights prior to this move  More...

BoardSquare 	Start [get]

 	Returns the start square for the move More...

BoardSquare 	End [get]

 	Returns the ending square for the move More...

bool 	FirstMove [get]

 	True if this is the piece's first move More...

bool 	IsPromotion [get]

 	True if the move is a promotion move More...

bool 	IsCapture [get]

 	true if move was a capture More...

bool 	IsCastle [get]

 	true if move was a castle More...

string 	PreviousFEN [get]

 	board FEN prior to move More...

Detailed Description

Holds more detailed information on a single move for the GUI.

Constructor & Destructor Documentation

◆ MoveInformation()

          AllPawnsMustDie.MoveInformation.MoveInformation
          (
          BoardSquare
          start,

          BoardSquare
          end,

          bool
          deployed,

          string
          oldFEN

          )

Create a new MoveInformation struct and fill in the minumum required information

Parameters

start	starting square

end	ending square

deployed	true if piece has ever moved, prior to this move

oldFEN	last FEN for board

Member Function Documentation

◆ ToString()

          override string AllPawnsMustDie.MoveInformation.ToString
          (
          	)

Return the move in a SAN friendly format

Returns

SAN engine-friendly format e.g. e2e4 or d7d8q, etc

Property Documentation

◆ CapturedPiece

          ChessPiece AllPawnsMustDie.MoveInformation.CapturedPiece

getset

If not null, the piece that was captured on this move.

◆ CastlingRights

          BoardSide AllPawnsMustDie.MoveInformation.CastlingRights

getset

Castling rights prior to this move

◆ CastlingRook

          ChessPiece AllPawnsMustDie.MoveInformation.CastlingRook

getset

If not null, the Rook associated with the castle

◆ Color

          PieceColor AllPawnsMustDie.MoveInformation.Color

getset

Color of the move

◆ End

          BoardSquare AllPawnsMustDie.MoveInformation.End

get

Returns the ending square for the move

◆ FirstMove

          bool AllPawnsMustDie.MoveInformation.FirstMove

get

True if this is the piece's first move

◆ IsCapture

          bool AllPawnsMustDie.MoveInformation.IsCapture

get

true if move was a capture

◆ IsCastle

          bool AllPawnsMustDie.MoveInformation.IsCastle

get

true if move was a castle

◆ IsPromotion

          bool AllPawnsMustDie.MoveInformation.IsPromotion

get

True if the move is a promotion move

◆ PreviousFEN

          string AllPawnsMustDie.MoveInformation.PreviousFEN

get

board FEN prior to move

◆ PromotionJob

          PieceClass AllPawnsMustDie.MoveInformation.PromotionJob

getset

Property for the promotion job

◆ Start

          BoardSquare AllPawnsMustDie.MoveInformation.Start

get

Returns the start square for the move

The documentation for this struct was generated from the following file:

AllPawnsMustDie/core/ChessTypes.cs

AllPawnsMustDie

MoveInformation

Generated by

     1.8.13


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

using org.freedesktop.DBus;

namespace DBus
{
	using Protocol;

	//TODO: perhaps ExportObject should not derive from BusObject
	internal class ExportObject : BusObject, IDisposable
	{
		//maybe add checks to make sure this is not called more than once
		//it's a bit silly as a property
		bool isRegistered = false;
		Dictionary<string, MethodInfo> methodInfoCache = new Dictionary<string, MethodInfo> ();

		static readonly Dictionary<MethodInfo, MethodCaller> mCallers = new Dictionary<MethodInfo, MethodCaller> ();

		public ExportObject (Connection conn, ObjectPath object_path, object obj) : base (conn, null, object_path)
		{
			Object = obj;
		}

		public virtual bool Registered
		{
			get {
				return isRegistered;
			}
			set {
				if (value == isRegistered)
					return;

				Type type = Object.GetType ();

				foreach (var memberForType in Mapper.GetPublicMembers (type)) {
					MemberInfo mi = memberForType.Value;
					EventInfo ei = mi as EventInfo;

					if (ei == null)
						continue;

					Delegate dlg = GetHookupDelegate (ei);

					if (value)
						ei.AddEventHandler (Object, dlg);
					else
						ei.RemoveEventHandler (Object, dlg);
				}

				isRegistered = value;
			}
		}

		internal virtual void WriteIntrospect (Introspector intro)
		{
			intro.WriteType (Object.GetType ());
		}

		internal static MethodCaller GetMCaller (MethodInfo mi)
		{
			MethodCaller mCaller;
			if (!mCallers.TryGetValue (mi, out mCaller)) {
				mCaller = TypeImplementer.GenCaller (mi);
				mCallers[mi] = mCaller;
			}
			return mCaller;
		}

		public static ExportObject CreateExportObject (Connection conn, ObjectPath object_path, object obj)
		{
			return new ExportObject (conn, object_path, obj);
		}

		public virtual void HandleMethodCall (MessageContainer method_call)
		{
			MethodInfo mi;
			if (!methodInfoCache.TryGetValue (method_call.Member, out mi))
				methodInfoCache[method_call.Member] = mi = Mapper.GetMethod (Object.GetType (), method_call);

			if (mi == null) {
				conn.MaybeSendUnknownMethodError (method_call);
				return;
			}

			MethodCaller mCaller;
			if (!mCallers.TryGetValue (mi, out mCaller)) {
				mCaller = TypeImplementer.GenCaller (mi);
				mCallers[mi] = mCaller;
			}

			Signature inSig, outSig;
			TypeImplementer.SigsForMethod (mi, out inSig, out outSig);

			Message msg = method_call.Message;
			MessageReader msgReader = new MessageReader (msg);
			MessageWriter retWriter = new MessageWriter ();

			Exception raisedException = null;
			try {
				mCaller (Object, msgReader, msg, retWriter);
			} catch (Exception e) {
				raisedException = e;
			}

			if (!msg.ReplyExpected)
				return;

			Message replyMsg;

			if (raisedException == null) {
				MessageContainer method_return = new MessageContainer {
					Type = MessageType.MethodReturn,
					ReplySerial = msg.Header.Serial
				};
				replyMsg = method_return.Message;
				replyMsg.AttachBodyTo (retWriter);
				replyMsg.Signature = outSig;
			} else {
				// BusException allows precisely formatted Error messages.
				BusException busException = raisedException as BusException;
				if (busException != null)
					replyMsg = method_call.CreateError (busException.ErrorName, busException.ErrorMessage);
				else if (raisedException is ArgumentException && raisedException.TargetSite.Name == mi.Name) {
					// Name match trick above is a hack since we don't have the resolved MethodInfo.
					ArgumentException argException = (ArgumentException)raisedException;
					using (System.IO.StringReader sr = new System.IO.StringReader (argException.Message)) {
						replyMsg = method_call.CreateError ("org.freedesktop.DBus.Error.InvalidArgs", sr.ReadLine ());
					}
				} else
					replyMsg = method_call.CreateError (Mapper.GetInterfaceName (raisedException.GetType ()), raisedException.Message);
			}

			if (method_call.Sender != null)
				replyMsg.Header[FieldCode.Destination] = method_call.Sender;

			conn.Send (replyMsg);
		}

		public object Object {
			get;
			private set;
		}

		public void Dispose ()
		{
			Dispose (true);
			GC.SuppressFinalize (this);
		}

		~ExportObject ()
		{
			Dispose (false);
		}

		protected virtual void Dispose (bool disposing)
		{
			if (disposing) {
				if (Object != null) {
					Registered = false;
					Object = null;
				}
			}
		}
	}
}


text:
Attendees: CFA Sommerville Team, Hunter Owens (Impact Lab), Andrew Martin (KIPP NJ), Chris Haid (KIPP Chicago)

"NEXT STEPS" TYPE THINGS (I.E. THINGS WE SAID WE'D DO)
	* Data standard decision: do we go with Ed-Fi?
	* Give ourselves 2 weeks to research & discuss
	* Next week:  Folks research, contribute their thoughts
	* Week after:  Make a decision
	* Three buckets:  No, Soft Yes, Hard Yes
	* Hunter organizes this process
* App gallery:  let's get our apps in one place so people can see what kinds of things they could do with their SIS data once it's more interoperable
	* Alex will add some Somerville app screenshots
## Minimum viable interoperability
* Can CfA stand up a KIPP app for Somerville?
* Can KIPP stand up the CfA app for KIPP schools?

## OTHER NOTES (I.E. THINGS WE SAID)
* "Trying to understand college readiness at scale" —Andrew

* "Mint.com for college readiness"  —Hunter
* College readiness tool will be done in November  —Hunter

Hunter:

* Every district has its own unique set of SISes, 3rd party tools
But the data itself in common in terms of what it's about
EdFi standard — mandatory in Texas now?

Andrew:
* One of the reasons there's a need for this is the scope is bigger than what the commercial services do already
Clever exists but it's not in the business of a student's full academic history
I don't think about this as being a funky competitor to Clever — not a giant killer
Let's do something open source for schools
There are bunch of ad hoc scripts running against databases, but they're not exporting to a common standard yet
"Like an old telephone switchboard."

Chris:
* Concern: developers don't usually think about an education data level
You run into this weird problem where the products that get written for edtech — testing or teaching products — they don't even know to go look for a standard
The people buying those products are not the people on the call right now

Hunter:
* Everybody's solving the same problems, like exporting to Powerschool

Andrew:
* We're a bunch of organizations with common interests & common problems
Chris's skepticism, I also share it
But there has to be a home for this

Chris:
* Schoolzilla, went to their data conference — one thing that came up was EdFi
Andrew:
We have some super tricked out Excel dashboards
They date back to 2008
Sortable view, clickthrough, drill down, if you click to a student you get a full page student profile

Alex:
* We are building the same product for Somerville!
Except as a web product, not Excel
Let's make an app gallery so that people who make decisions about this can see what it means


text:
## Requirements

| Name | Version |
|------|---------|
|  [terraform](#requirement\_terraform) | >= 1.0.0 |

## Providers

No providers.

## Modules

| Name | Source | Version |
|------|--------|---------|
|  [external\_dns](#module\_external\_dns) | nlamirault/external-dns/google | 1.1.0 |

## Resources

No resources.

## Inputs

| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
|  [namespace](#input\_namespace) | The Kubernetes namespace | `string` | n/a | yes |
|  [project](#input\_project) | The project in which the resource belongs | `string` | n/a | yes |
|  [service\_account](#input\_service\_account) | The Kubernetes service account | `string` | n/a | yes |

## Outputs

| Name | Description |
|------|-------------|
|  [service\_account](#output\_service\_account) | Service Account for External DNS |


text:
namespace
{
constexpr char kRunAppTestEnvVarName[]  = "RUN_APP_TEST_ENV";
constexpr char kRunAppTestEnvVarValue[] = "RunAppTest environment variable value\n";
constexpr char kRunAppTestStdout[]      = "RunAppTest stdout test\n";
constexpr char kRunAppTestStderr[] = "RunAppTest stderr test\n  .. that expands multiple lines\n";
constexpr char kRunAppTestArg1[]   = "--expected-arg1";
constexpr char kRunAppTestArg2[]   = "expected_arg2";
constexpr char kRunTestSuite[]     = "--run-test-suite";
}  // anonymous namespace

#endif  // COMMON_SYSTEM_UTILS_UNITTEST_HELPER_H_


text:
package com.paypal.selion.mobile.sample;

import com.paypal.selion.annotations.MobileTest;
import com.paypal.selion.internal.platform.grid.WebDriverPlatform;
import com.paypal.selion.mobile.sample.pages.SamplePage;
import com.paypal.selion.mobile.sample.pages.TapPage;
import com.paypal.selion.platform.mobile.ios.UIAButton;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestTapPage {
    @Test
    @MobileTest
    public void testSingleTap() throws Exception {
        TapPage tapPage = InitializePages();
        tapPage.getSingleTapButton().tap();
        Assert.assertEquals(tapPage.getSingleTapTextField().getValue(), "Tap Count: 1");
        tapPage.getSingleTapButton().tap();
        Assert.assertEquals(tapPage.getSingleTapTextField().getValue(), "Tap Count: 1");
    }

    @Test
    @MobileTest
    public void testMultiTap() throws Exception {
        TapPage tapPage = InitializePages();
        if (tapPage.getPlatform().equals(WebDriverPlatform.IOS)) {
            UIAButton multiTapButton = (UIAButton) tapPage.getMultiTapButton();
            multiTapButton.doubleTap();
            Assert.assertEquals(tapPage.getMultiTapTextField().getValue(), "Tap Count: 2");
        } else {
            Assert.fail("paltform " + tapPage.getPlatform().name() + " does not support double tap.");
        }

    }

    private TapPage InitializePages() {
        SamplePage samplePage = new SamplePage();
        TapPage tapPage = new TapPage();
        samplePage.getNextButton().tap(tapPage.getSingleTapButton());
        return tapPage;
    }
}


text:
import numpy as np
import torch
import torch.nn as nn

def pos_table(n, dim):
    """Create a table of positional encodings."""

    def get_angle(x, h):
        return x / np.power(10000, 2 * (h // 2) / dim)

    def get_angle_vec(x):
        return [get_angle(x, j) for j in range(dim)]

    tab = np.array([get_angle_vec(i) for i in range(n)]).astype(float)
    tab[:, 0::2] = np.sin(tab[:, 0::2])
    tab[:, 1::2] = np.cos(tab[:, 1::2])
    return tab

class AttentionMatrix(nn.Module):
    """Self-attention matrix."""

    def __init__(self, dim_in_q, dim_in_k, msg_dim, bias=True, scale=True):
        super(AttentionMatrix, self).__init__()
        self.proj_q = nn.Linear(
            in_features=dim_in_q, out_features=msg_dim, bias=bias)
        self.proj_k = nn.Linear(
            in_features=dim_in_k, out_features=msg_dim, bias=bias)
        if scale:
            self.msg_dim = msg_dim
        else:
            self.msg_dim = 1

    def forward(self, data_q, data_k):
        q = self.proj_q(data_q)
        k = self.proj_k(data_k)
        if data_q.ndim == data_k.ndim == 2:
            dot = torch.matmul(q, k.T)
        else:
            dot = torch.bmm(q, k.permute(0, 2, 1))
        return torch.div(dot, np.sqrt(self.msg_dim))

class SelfAttentionMatrix(AttentionMatrix):
    """Self-attention matrix."""

    def __init__(self, dim_in, msg_dim, bias=True, scale=True):
        super(SelfAttentionMatrix, self).__init__(
            dim_in_q=dim_in,
            dim_in_k=dim_in,
            msg_dim=msg_dim,
            bias=bias,
            scale=scale,
        )

class AttentionLayer(nn.Module):
    """The attention mechanism."""

    def __init__(self, dim_in_q, dim_in_k, dim_in_v, msg_dim, out_dim):
        super(AttentionLayer, self).__init__()
        self.attention_matrix = AttentionMatrix(
            dim_in_q=dim_in_q,
            dim_in_k=dim_in_k,
            msg_dim=msg_dim,
        )
        self.proj_v = nn.Linear(in_features=dim_in_v, out_features=out_dim)
        self.mostly_attended_entries = None

    def forward(self, data_q, data_k, data_v):
        a = torch.softmax(
            self.attention_matrix(data_q=data_q, data_k=data_k), dim=-1)
        self.mostly_attended_entries = set(torch.argmax(a, dim=-1).numpy())
        v = self.proj_v(data_v)
        return torch.matmul(a, v)

class AttentionNeuronLayer(nn.Module):
    """Permutation invariant layer."""

    def __init__(self,
                 act_dim,
                 hidden_dim,
                 msg_dim,
                 pos_em_dim,
                 bias=True,
                 scale=True):
        super(AttentionNeuronLayer, self).__init__()
        self.act_dim = act_dim
        self.hidden_dim = hidden_dim
        self.msg_dim = msg_dim
        self.pos_em_dim = pos_em_dim
        self.pos_embedding = torch.from_numpy(
            pos_table(self.hidden_dim, self.pos_em_dim)
        ).float()
        self.hx = None
        self.lstm = nn.LSTMCell(
            input_size=1 + self.act_dim, hidden_size=pos_em_dim)
        self.attention = SelfAttentionMatrix(
            dim_in=pos_em_dim, msg_dim=self.msg_dim, bias=bias, scale=scale)

    def forward(self, obs, prev_act):
        if isinstance(obs, np.ndarray):
            x = torch.from_numpy(obs.copy()).float().unsqueeze(-1)
        else:
            x = obs.unsqueeze(-1)
        obs_dim = x.shape[0]

        x_aug = torch.cat([x, torch.vstack([prev_act] * obs_dim)], dim=-1)
        if self.hx is None:
            self.hx = (
                torch.zeros(obs_dim, self.pos_em_dim).to(x.device),
                torch.zeros(obs_dim, self.pos_em_dim).to(x.device),
            )
        self.hx = self.lstm(x_aug, self.hx)

        w = torch.tanh(self.attention(
            data_q=self.pos_embedding.to(x.device), data_k=self.hx[0]))
        output = torch.matmul(w, x)
        return torch.tanh(output)

    def reset(self):
        self.hx = None

class VisionAttentionNeuronLayer(nn.Module):
    """Permutation invariant layer for vision tasks."""

    def __init__(self,
                 act_dim,
                 hidden_dim,
                 msg_dim,
                 pos_em_dim,
                 patch_size=6,
                 stack_k=4,
                 with_learnable_ln_params=False,
                 stack_dim_first=False):
        super(VisionAttentionNeuronLayer, self).__init__()
        self.act_dim = act_dim
        self.hidden_dim = hidden_dim
        self.msg_dim = msg_dim
        self.patch_size = patch_size
        self.stack_k = stack_k
        self.stack_dim_first = stack_dim_first
        self.pos_em_dim = pos_em_dim
        self.pos_embedding = torch.from_numpy(
            pos_table(self.hidden_dim, self.pos_em_dim)
        ).float()
        self.attention = AttentionLayer(
            dim_in_q=self.pos_em_dim,
            dim_in_k=(self.stack_k - 1) * self.patch_size**2 + self.act_dim,
            dim_in_v=self.stack_k * self.patch_size**2,
            msg_dim=self.msg_dim,
            out_dim=self.msg_dim,
        )
        # The normalization layers have no learnable parameters.
        self.input_ln = nn.LayerNorm(
            normalized_shape=self.patch_size**2,
            elementwise_affine=with_learnable_ln_params,
        )
        self.input_ln.eval()
        self.output_ln = nn.LayerNorm(
            normalized_shape=self.msg_dim,
            elementwise_affine=with_learnable_ln_params,
        )
        self.output_ln.eval()

    def get_patches(self, x):
        h, w, c = x.size()
        patches = x.unfold(
            0, self.patch_size, self.patch_size).permute(0, 3, 1, 2)
        patches = patches.unfold(
            2, self.patch_size, self.patch_size).permute(0, 2, 1, 4, 3)
        return patches.reshape((-1, self.patch_size, self.patch_size, c))

    def forward(self, obs, prev_act):
        if isinstance(obs, dict):
            # Puzzle pong may drop some patches.
            patch_to_keep_ix = obs['patches_to_use']
            obs = obs['obs']
        else:
            patch_to_keep_ix = None

        k, h, w = obs.shape
        assert k == self.stack_k
        if patch_to_keep_ix is None:
            num_patches = (h // self.patch_size) * (w // self.patch_size)
        else:
            num_patches = patch_to_keep_ix.size

        # AttentionNeuron is the first layer, so obs is numpy array.
        x_obs = torch.div(torch.from_numpy(obs).float(), 255.)

        # Create Key.
        x_k = torch.diff(x_obs, dim=0).permute(1, 2, 0)
        x_k = self.get_patches(x_k)
        if patch_to_keep_ix is not None:
            x_k = x_k[patch_to_keep_ix]
        assert x_k.shape == (
            num_patches, self.patch_size, self.patch_size, self.stack_k - 1)
        if self.stack_dim_first:
            x_k = x_k.permute(0, 3, 1, 2)
        x_k = torch.cat([
            torch.flatten(x_k, start_dim=1),
            torch.repeat_interleave(prev_act, repeats=num_patches, dim=0)
        ], dim=-1)

        # Create Value.
        x_v = self.get_patches(x_obs.permute(1, 2, 0)).permute(0, 3, 1, 2)
        if patch_to_keep_ix is not None:
            x_v = x_v[patch_to_keep_ix]
        x_v = self.input_ln(torch.flatten(x_v, start_dim=2))

        x = self.attention(
            data_q=self.pos_embedding,
            data_k=x_k,
            data_v=x_v.reshape(num_patches, -1),
        )
        return self.output_ln(torch.relu(x))


text:
from os import path

from setuptools import find_packages, setup

this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, "README.rst")) as fd:
    long_description = fd.read()

setup(
    name="pyoffers",
    url="https://github.com/Stranger6667/pyoffers",
    version="0.7.0",
    license="MIT",
    author="Dmitry Dygalo",
    author_email="dadygalo@gmail.com",
    maintainer="Dmitry Dygalo",
    maintainer_email="dadygalo@gmail.com",
    keywords=["hasoffers", "api", "client"],
    description="Python client library for HasOffers API",
    long_description=long_description,
    long_description_content_type="text/x-rst",
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "Operating System :: OS Independent",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3 :: Only",
        "Programming Language :: Python :: 3.5",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: Implementation :: CPython",
        "Programming Language :: Python :: Implementation :: PyPy",
    ],
    include_package_data=True,
    packages=find_packages(where="src"),
    package_dir={"": "src"},
    install_requires=["requests"],
)


text:
package com.almasb.datavis;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Almas Baimagambetov (almaslvl@gmail.com)
 */
public class WordExtractor implements DataExtractor {

    private Path file;

    public WordExtractor(Path file) {
        this.file = file;
    }

    @Override
    public List<Entry> extract() {
        try {
            Map<String, Long> map = Files.readAllLines(file)
                    .stream()
                    .flatMap(line -> Arrays.stream(line.split(" +")))
                    .map(word -> word.toLowerCase())
                    .filter(word -> isWord(word))
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

            List<Entry> entries = new ArrayList<>();

            map.forEach((word, freq) -> entries.add(new Entry(word, freq.intValue())));

            return entries;

        } catch (IOException e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    private boolean isWord(String word) {
        if (word.length() < 4)
            return false;

        if (word.isEmpty())
            return false;

        for (char c : word.toCharArray()) {
            if (!Character.isLetter(c))
                return false;
        }

        return true;
    }
}


text:
var testBrowser = require("./wdio_helper.js").testBrowser

const BACKSPACE_UNICODE = "\uE003";

testBrowser
  .init()
  .url('http://localhost:3000/')
  .click(".btn-edit-robot")

  .setValue('#robot-name', [' ', BACKSPACE_UNICODE])
  .setValue('#robot-description', [' ', BACKSPACE_UNICODE])
  .submitForm("#robots-form").then(function(){
    console.log("SUBMITTING...");
  })
  .getUrl().then(function(url){
    console.log("URL", url);
  })
  .elements(".alert").then(function(elements){
    console.log("MESSAGE COUNT", elements.value.length)
  })

  .end();


text:
package commands

import (
	"fmt"

	"github.com/pivotal-cf/jhanda"
	"github.com/pivotal-cf/om/api"
	"github.com/pivotal-cf/om/presenters"
)

type CertificateAuthorities struct {
	service   certificateAuthoritiesService
	presenter presenters.FormattedPresenter
	Options   struct {
		Format string `long:"format" short:"f" default:"table" description:"Format to print as (options: table,json)"`
	}
}

//go:generate counterfeiter -o ./fakes/certificate_authorities_service.go --fake-name CertificateAuthoritiesService . certificateAuthoritiesService

type certificateAuthoritiesService interface {
	ListCertificateAuthorities() (api.CertificateAuthoritiesOutput, error)
}

func NewCertificateAuthorities(certificateAuthoritiesService certificateAuthoritiesService, presenter presenters.FormattedPresenter) CertificateAuthorities {
	return CertificateAuthorities{
		service:   certificateAuthoritiesService,
		presenter: presenter,
	}
}

func (c CertificateAuthorities) Execute(args []string) error {
	if _, err := jhanda.Parse(&c.Options, args); err != nil {
		return fmt.Errorf("could not parse certificate-authorities flags: %s", err)
	}

	casOutput, err := c.service.ListCertificateAuthorities()
	if err != nil {
		return err
	}

	c.presenter.SetFormat(c.Options.Format)
	c.presenter.PresentCertificateAuthorities(casOutput.CAs)

	return nil
}

func (c CertificateAuthorities) Usage() jhanda.Usage {
	return jhanda.Usage{
		Description:      "lists certificates managed by Ops Manager",
		ShortDescription: "lists certificates managed by Ops Manager",
		Flags:            c.Options,
	}
}


text:
package sunning.democollection.learn._0504.bean;

/**
 * Created by sunning on 16/5/4.
 */
public class Course {
    public String courseName;

    public Course(String courseName) {
        this.courseName = courseName;
    }
}


text:
using System;
using Utils.TypeMapping.MappingInfo;
using Utils.TypeMapping.TypeMappers;
using Utils.TypeMapping.ValueResolvers.ServiceLocator;

namespace Utils
{
    public class TypeMapper<TSource, TDest> : TypeMapperBase<TSource, TDest>
    {
        private readonly PropertyMappingInfo<TDest> propertyMappingInfo;
        private readonly LocatorRegistrationInfo<TDest> locatorMappingInfo;
        private readonly PropertyRegistrationInfo<TDest> registrationInfo;
        private ServiceLocator locator;

        public TypeMapper(ServiceLocator locator)
        {
            DestType = typeof(TDest);

            SourceType = typeof(TSource);
            propertyMappingInfo = new PropertyMappingInfo<TDest>();
            registrationInfo= new PropertyRegistrationInfo<TDest>();
            locatorMappingInfo = new LocatorRegistrationInfo<TDest>();
            this.locator = locator;
            LocatorInjectOnlyFlaggedProperties = true;

        }

        public TypeMapper():this(new ServiceLocator())
        {
        }

        public ILocatorRegistrationInfo<TDest> LocatorMappingInfo
        {
            get { return locatorMappingInfo; }
        }

        public IPropertyMappingInfo<TDest> PropertyMappingInfo
        {
            get { return propertyMappingInfo; }
        }

        public IPropertyRegistrationInfo<TDest> RegistrationInfo
        {
            get { return registrationInfo; }
        }

        public bool LocatorInjectOnlyFlaggedProperties { get;set; }

        public override bool CanMap(TSource source)
        {
            return true;
        }

        public override IOperationResult<TDest> TryMap(TSource source)
        {
            var mapper = CreateTypeBuilder();

            mapper.PropertyMappings = propertyMappingInfo.Mapping;

            var propertyResolver = new LocatorRegistrationInfoResolver(locator);

            locatorMappingInfo.PropertyInjectionResolvers
                .ForEach(_=>propertyResolver.PropertyInjectionResolvers.Add(_.Key,_.Value));

            mapper.RegisterSourceResolver(propertyResolver);

            var ctor = mapper.GetConstructor();

            mapper.CreateBuildingContext();
            mapper.InitBuildingContext();
            mapper.Context.Source = source;
            mapper.CreateInstance(ctor, DestType.FullName);
            mapper.CallInitMethods();

            mapper.InjectTypeProperties();

            return OperationResult<TDest>.Successful(mapper.Context.DestInstance);
        }

        protected virtual MappingTypeBuilder<TSource, TDest> CreateTypeBuilder()
        {
            if (DestType.IsGenericType || DestType.IsGenericType)
                throw new TypeNotSupportedException(DestType.FullName, "Generic types are not supported");

            var mapper = new MappingTypeBuilder<TSource, TDest>(locator, registrationInfo);
            return mapper;
        }

        public Type DestType { get; private set; }

        public Type SourceType { get; private set; }

    }

}


text:
using System;
using System.Runtime.Serialization;

namespace Frapid.Reports.Models
{
    [Serializable]
    public sealed class EmailException:Exception
    {
        public EmailException()
        {
        }

        public EmailException(string message) : base(message)
        {
        }

        public EmailException(string message, Exception innerException) : base(message, innerException)
        {
        }

        public EmailException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;

namespace Parsing
{
    public abstract class Tokenizer<TToken>
        : ITokenizer<TToken>
        where TToken : IToken
    {
        protected TextReader _reader;

        public void Reset()
        {
            _reader = null;
        }

        public IEnumerator<TToken> Tokenize(TextReader reader)
        {
            if (reader == null)
                throw new ArgumentNullException("reader");

            _reader = reader;

            return Tokenize();
        }

        protected abstract IEnumerator<TToken> Tokenize();

        #region Reading

        private int? _peek;
        private int _line = 1;
        private int _lineRef = 1;
        private int _col;
        private int _colPrev;

        protected int Read()
        {
            int c;
            if (_peek.HasValue)
            {
                c = _peek.Value;
                _peek = null;
            }
            else c = _reader.Read();

            switch (c)
            {
                case '\r':
                    if (Peek() == '\n')
                        _peek = null;
                    c = '\n';
                    NextLine();
                    break;
                case '\n':
                    NextLine();
                    break;
                default:
                    _col++;
                    break;
            }

            return c;
        }

        protected int Peek()
        {
            if (!_peek.HasValue)
                _peek = _reader.Read();
            return _peek.Value;
        }

        protected int Peek2()
        {
            if (_peek.HasValue)
                return _peek.Value;
            return Peek();
        }

        private void NextLine()
        {
            _line++;
            _lineRef++;
            _colPrev = _col;
            _col = 0;
        }

        #endregion

        #region Characters

        /// <summary>
        ///  Checks if the next character is alpha.
        /// </summary>
        protected bool IsAlpha()
        {
            int c = Peek();
            return
                (c >= 'A' && c <= 'Z') ||
                (c >= 'a' && c <= 'z');
        }

        /// <summary>
        ///  Checks if the next character is decimal.
        /// </summary>
        protected bool IsDec()
        {
            int c = Peek();
            return c >= '0' && c <= '9';
        }

        /// <summary>
        ///  Reads the next character number as an integer.
        /// </summary>
        protected int GetDec()
        {
            int c = Read();
            if (c >= '0' && c <= '9')
                return (c - '0');

            throw NewTokenizerException("Invalid decimal character");
        }

        /// <summary>
        ///  Checks if the next character is hexadecimal.
        /// </summary>
        protected bool IsHex()
        {
            int c = Peek();
            return
                (c >= '0' && c <= '9') ||
                (c >= 'A' && c <= 'F') ||
                (c >= 'a' && c <= 'f');
        }

        /// <summary>
        ///  Converts the next character from hexadecimal to integer representation.
        /// </summary>
        protected int GetHex()
        {
            int c = Read();
            if (c >= '0' && c <= '9') return (c - '0');
            if (c >= 'a' && c <= 'f') return (c - 'a') + 10;
            if (c >= 'A' && c <= 'F') return (c - 'A') + 10;

            throw NewTokenizerException("Invalid hexadecimal character");
        }

        protected bool IsOctal()
        {
            int c = Peek();
            return c >= '0' && c <= '7';
        }

        protected int GetOctal()
        {
            int c = Read();
            if (c >= '0' && c <= '7') return (c - '0');

            throw NewTokenizerException("Invalid hexadecimal character");
        }

        #endregion

        #region Helpers

        /// <summary>
        ///  Check if the next character is in a list of characters,
        ///  if so, return the one that was found.
        /// </summary>
        /// <param name="chars">
        ///  The characters to check for.
        /// </param>
        /// <returns>
        ///  The character that was found, or null if it wasn't.
        /// </returns>
        protected int? Maybe(params int[] chars)
        {
            int ch = Peek();
            if (Array.IndexOf(chars, ch) < 0)
                return null;

            return ch;
        }

        /// <summary>
        ///  Check if the next character is the character we want.
        ///  If it is, we discard it.
        /// </summary>
        /// <param name="c">
        ///  The character we want to check for.
        /// </param>
        /// <returns>
        ///  True if it was the correct character, false it if wasn't.
        /// </returns>
        protected bool Maybe(int c)
        {
            if (Peek() != c)
                return false;

            Read();
            return true;
        }

        /// <summary>
        ///  Check if the next character is the character we expect.
        ///  If it is not, we throw an exception.
        /// </summary>
        /// <param name="c">
        ///  The character we want to check for.
        /// </param>
        protected void Expect(int c)
        {
            int ch;
            if ((ch = Read()) != c)
                throw NewTokenizerException(String.Format("Expected '{0}', got '{1}'", (char)c, (char)ch));
        }

        /// <summary>
        ///  Check if the next characters form the string we expect them to.
        /// </summary>
        /// <param name="s">
        ///  The string we want to check for.
        /// </param>
        protected void Expect(string s)
        {
            for (int i = 0; i < s.Length; i++)
                if (Read() != s[i])
                    throw NewTokenizerException(String.Format("Error in expected string '{0}' on place '{1}'", s, i));
        }

        /// <summary>
        ///  Returns a new exception, containing the current position.
        /// </summary>
        /// <param name="message">
        ///  The message explaining what went wrong.
        /// </param>
        protected TokenizerException NewTokenizerException(string message)
        {
            string file = "<null>";
            var reader = _reader as StreamReader;
            if (reader != null)
            {
                var stream = reader.BaseStream as FileStream;
                file = stream.Name;
            }

            var location = new Location
            {
                File = file,
                Line = _line,
                Column = _col,
            };
            return new TokenizerException(message, location);
        }

        #endregion

    }
}


text:
//hitMe / hitUs : sends the server the current timestamp and the number of calls to make back to the client.  hitMe: just the callign client, hitUs: all clients on the hub.
//stepOne / stepAll : increments a counter
//doneOne / doneAll : prints # of messages and total duration.

$(function () {
    var playerHub = $.connection.playerHub;

    playerHub.client.updateFrame = function (newFrame) {
        $('#myScreen').text(newFrame);
    };

    playerHub.client.nameOk = function (ok) {
        if (true === ok) {
            $("#submitForm").hide();
            $(document).keypress(function (event) {
                playerHub.server.input(event.ctrlKey, event.altKey, event.key);
            });
        } else {
            $('#inputName').css("background-color", "red");
        }
    };

    $.connection.hub.start(options, function () { console.log("Connected"); });

    $("#submitForm").submit(function (event) {
        playerHub.server.insertNew($('#inputName').val());
        return false;
    });
});


text:
#ifndef LP_BLD_BLEND_H
#define LP_BLD_BLEND_H

#include "gallivm/lp_bld.h"
#include "gallivm/lp_bld_init.h"

#include "pipe/p_format.h"

struct pipe_blend_state;
struct lp_type;
struct lp_build_context;

LLVMValueRef
lp_build_blend(struct lp_build_context *bld,
               unsigned func,
               unsigned factor_src,
               unsigned factor_dst,
               LLVMValueRef src,
               LLVMValueRef dst,
               LLVMValueRef src_factor,
               LLVMValueRef dst_factor,
               boolean not_alpha_dependent,
               boolean optimise_only);

LLVMValueRef
lp_build_blend_aos(struct gallivm_state *gallivm,
                   const struct pipe_blend_state *blend,
                   const enum pipe_format *cbuf_format,
                   struct lp_type type,
                   unsigned rt,
                   LLVMValueRef src,
                   LLVMValueRef dst,
                   LLVMValueRef mask,
                   LLVMValueRef const_,
                   const unsigned char swizzle[4]);

void
lp_build_blend_soa(struct gallivm_state *gallivm,
                   const struct pipe_blend_state *blend,
                   struct lp_type type,
                   unsigned rt,
                   LLVMValueRef src[4],
                   LLVMValueRef dst[4],
                   LLVMValueRef const_[4],
                   LLVMValueRef res[4]);

/**
 * Apply a logic op.
 *
 * src/dst parameters are packed values. It should work regardless the inputs
 * are scalars, or a vector.
 */
LLVMValueRef
lp_build_logicop(LLVMBuilderRef builder,
                 unsigned logicop_func,
                 LLVMValueRef src,
                 LLVMValueRef dst);

LLVMValueRef
lp_build_blend_func(struct lp_build_context *bld,
                    unsigned func,
                    LLVMValueRef term1,
                    LLVMValueRef term2);

boolean
lp_build_blend_func_reverse(unsigned rgb_func,
                            unsigned alpha_func);

boolean
lp_build_blend_func_commutative(unsigned func);

#endif /* !LP_BLD_BLEND_H */