text:
require 'i18n'

module Contentful
  module Exporter
    module Database
      module RelationsExport

        RELATIONS = [:many, :many_through, :aggregate_many, :aggregate_through, :has_one, :aggregate_has_one]

        def generate_relations_helper_indexes(relations)
          create_directory(config.helpers_dir)
          relations.each do |relation_type, linked_models|
            save_relation_foreign_keys(relation_type, linked_models) if RELATIONS.include?(relation_type.to_sym)
          end
        end

        def save_relation_foreign_keys(relation_type, linked_models)
          linked_models.each do |linked_model|
            save_relation_foreign_keys_for_model(linked_model, relation_type)
          end
        end

        def save_relation_foreign_keys_for_model(linked_model, relation_type)
          primary_id = linked_model[:primary_id]
          fail ArgumentError, "Missing #{primary_id} in relationship in Mapping JSON file" unless primary_id
          case relation_type.to_sym
            when :many_through, :aggregate_through
              related_model = linked_model[:through]
              related_model_id = linked_model[:foreign_id]
            when :many, :aggregate_many, :has_one, :aggregate_has_one
              related_model = linked_model[:relation_to]
              related_model_id = linked_model[:foreign_id] || :id
          end
          save_foreign_keys(related_model, primary_id, related_model_id)
        end

        def save_foreign_keys(related_model, primary_id, related_model_id)
          results = config.db[related_model.underscore.to_sym].each_with_object({}) do |row, res|
            add_index_to_helper_hash(res, row, primary_id, related_model_id)
          end
          write_json_to_file(config.helpers_dir + "/#{primary_id}_#{related_model.underscore}.json", results)
        end

        def add_index_to_helper_hash(results, row, primary_id, id)
          id, primary_id = id.to_sym, primary_id.to_sym
          if results[row[primary_id]].nil?
            results[row[primary_id]] = [row[id]] if row[id]
          else
            results[row[primary_id]] << row[id] if row[id]
          end
          results
        end

        def map_relations_to_links(model_name, relations)
          records = 0
          model_subdirectory = I18n.transliterate(model_content_type(model_name)).underscore.tr(' ', '_')
          Dir.glob("#{config.entries_dir}/#{model_subdirectory}/*json") do |entry_path|
            map_entry_relations(entry_path, model_name, relations, records)
            records += 1
          end
        end

        def relations_from_mapping
          mapping.each_with_object({}) do |(model_name, model_mapping), relations|
            relations[model_name] = model_mapping[:links] if model_mapping[:links].present?
          end
        end

        def map_entry_relations(entry_path, model_name, relations, record)
          relations.each do |relation_type, linked_models|
            logger.info "Mapping #{model_name} - relation: #{relation_type} - #{linked_models}, record: #{record}" if record % 1000 == 0
            map_entry_relation(entry_path, relation_type, linked_models, model_name)
          end
        end

        def map_entry_relation(entry_path, relation_type, linked_models, model_name)
          entry = JSON.parse(File.read(entry_path))
          linked_models.each do |linked_model|
            relationships(entry, entry_path, relation_type, model_name, linked_model)
          end
        end

        def relationships(entry, entry_path, relation_type, model_name, linked_model)
          case relation_type.to_sym
            when :belongs_to
              map_belongs_to_association(model_name, linked_model, entry, entry_path)
            when :has_one
              map_has_one_association(model_name, linked_model, entry, entry_path, :relation_to)
            when :many
              map_many_association(model_name, linked_model, entry, entry_path, :relation_to)
            when :many_through
              map_many_association(model_name, linked_model, entry, entry_path, :through)
            when :aggregate_through
              aggregate_data(model_name, linked_model, entry, entry_path, :through)
            when :aggregate_many
              aggregate_data(model_name, linked_model, entry, entry_path, :relation_to)
            when :aggregate_belongs
              aggregate_belongs(linked_model, entry, entry_path, :relation_to)
            when :aggregate_has_one
              aggregate_has_one(linked_model, entry, entry_path, :relation_to)
          end
        end

        def model_content_type(model_name)
          mapping[model_name][:content_type]
        end

        def map_belongs_to_association(model_name, linked_model, entry, entry_path)
          ct_link_type = contentful_field_attribute(model_name, linked_model, :type)
          ct_field_id = contentful_field_attribute(model_name, linked_model, :id)
          save_belongs_to_entries(linked_model, ct_link_type, ct_field_id, entry, entry_path)
        end

        def contentful_field_attribute(model_name, associated_model_attributes, type)
          contentful_model_hash(model_name)
          contentful_model_fields(model_name)
          contentful_associated_model_name(model_name, associated_model_attributes[:relation_to])

          associated_model = get_associated_model(associated_model_attributes)
          associated_content_type = model_content_type(model_name)
          contentful_associated_parameters(model_name, associated_model_attributes[:relation_to], associated_model)
          config.contentful_structure[associated_content_type][:fields][associated_model][type]
        end

        def contentful_model_hash(model_name)
          fail ArgumentError, "Missing #{model_name} in contentful structure JSON file" unless model_in_structure?(model_name)
        end

        def contentful_model_fields(model_name)
          fail ArgumentError, "Missing fields in #{model_name} in contentful structure JSON file" unless fields_in_structure?(model_name)
        end

        def contentful_associated_model_name(model_name, associated_model_name)
          fail ArgumentError, "Missing associated model content type name for #{model_name} in MAPPING JSON file" unless content_type_in_mapping?(associated_model_name)
        end

        def contentful_associated_parameters(model_name, associated_model_name, associated_model)
          fail ArgumentError, "Missing link field for #{associated_model_name} in #{model_name} in contentful structure JSON file!" unless associated_model_in_structure?(model_name, associated_model)
        end

        def model_in_structure?(model_name)
          config.contentful_structure[model_content_type(model_name)]
        end

        def fields_in_structure?(model_name)
          config.contentful_structure[model_content_type(model_name)][:fields]
        end

        def content_type_in_mapping?(model_name)
          model_content_type(model_name)
        end

        def associated_model_in_structure?(model_name, associated_model)
          config.contentful_structure[model_content_type(model_name)][:fields][associated_model]
        end

        def save_belongs_to_entries(linked_model, ct_link_type, ct_field_id, entry, entry_path)
          content_type = I18n.transliterate(model_content_type(linked_model[:relation_to])).underscore.tr(' ', '_')
          foreign_id = linked_model[:foreign_id]
          if entry[foreign_id].present?
            case ct_link_type
              when 'Asset'
                type = 'File'
              when 'Entry'
                type = 'Entry'
            end
            object = {
                'type' => type,
                'id' => "#{content_type}_#{entry[foreign_id]}"
            }
            write_json_to_file(entry_path, entry.merge!(ct_field_id => object))
          end
        end

        def get_associated_model(associated_model_attributes)
          associated_model_attributes.has_key?(:maps_to) ? associated_model_attributes[:maps_to] : model_content_type(associated_model_attributes[:relation_to])
        end

        def save_many_entries(linked_model, ct_field_id, entry, entry_path, related_to, ct_type)
          related_model = linked_model[related_to].underscore
          contentful_name = I18n.transliterate(model_content_type(linked_model[:relation_to])).underscore.tr(' ', '_')
          objects = entry[ct_field_id] || []
          associated_objects = add_associated_object_to_file(entry, related_model, contentful_name, linked_model[:primary_id], ct_type)
          objects.concat(associated_objects) if objects.present? && associated_objects.present? && objects.is_a?(Array)
          save_objects = objects.present? ? objects : associated_objects
          write_json_to_file(entry_path, entry.merge!(ct_field_id => save_objects)) if save_objects.present?
        end

        def save_has_one_entry(linked_model, ct_field_id, entry, entry_path, related_to, ct_type)
          related_model = linked_model[related_to].underscore
          contentful_name = I18n.transliterate(model_content_type(linked_model[:relation_to])).underscore.tr(' ', '_')
          associated_object = add_associated_object_to_file(entry, related_model, contentful_name, linked_model[:primary_id], ct_type)
          write_json_to_file(entry_path, entry.merge!(ct_field_id => associated_object.first)) if associated_object.present?
        end

        def map_many_association(model_name, linked_model, entry, entry_path, related_to)
          ct_field_id = contentful_field_attribute(model_name, linked_model, :id)
          ct_type = mapping[linked_model[:relation_to]][:type] if mapping[linked_model[:relation_to]]
          save_many_entries(linked_model, ct_field_id, entry, entry_path, related_to, ct_type)
        end

        def map_has_one_association(model_name, linked_model, entry, entry_path, related_to)
          ct_field_id = contentful_field_attribute(model_name, linked_model, :id)
          ct_type = mapping[linked_model[:relation_to]][:type] if mapping[linked_model[:relation_to]]
          save_has_one_entry(linked_model, ct_field_id, entry, entry_path, related_to, ct_type)
        end

        def add_associated_object_to_file(entry, related_model, contentful_name, primary_id, ct_type)
          Dir.glob("#{config.helpers_dir}/#{primary_id}_#{related_model}.json") do |through_file|
            hash_with_foreign_keys = JSON.parse(File.read(through_file))
            return build_hash_with_associated_objects(hash_with_foreign_keys, entry, contentful_name, ct_type)
          end
        end

        def build_hash_with_associated_objects(hash_with_foreign_keys, entry, contentful_name, ct_type)
          if hash_with_foreign_keys.has_key?(entry['database_id'].to_s)
            associated_objects = hash_with_foreign_keys[entry['database_id'].to_s].each_with_object([]) do |foreign_key, result|
              type = case ct_type
                       when 'entry'
                         contentful_name
                       when 'asset'
                         'File'
                     end
              result << {
                  'type' => type,
                  'id' => "#{contentful_name}_#{foreign_key}"
              }
            end
          end
          associated_objects
        end

        def aggregate_data(model_name, linked_model, entry, entry_path, related_to)
          ct_field_id = contentful_field_attribute(model_name, linked_model, :id)
          save_aggregated_entries(linked_model, ct_field_id, entry, entry_path, related_to)
        end

        def aggregate_has_one(linked_model, entry, entry_path, related_to)
          ct_field_id = linked_model[:save_as] || linked_model[:field]
          related_model = linked_model[related_to].underscore
          related_model_directory = I18n.transliterate(mapping[linked_model[related_to]][:content_type]).underscore.tr(' ', '_')
          save_aggregated_has_one_data(entry_path, entry, related_model, related_model_directory, linked_model, ct_field_id)
        end

        def save_aggregated_has_one_data(entry_path, entry, related_model, related_model_directory, linked_model, ct_field_id)
          primary_id = linked_model[:primary_id]
          hash_with_foreign_keys = JSON.parse(File.read("#{config.helpers_dir}/#{primary_id}_#{related_model}.json"))
          if hash_with_foreign_keys.has_key?(entry['database_id'].to_s)
            related_file_id = hash_with_foreign_keys[entry['database_id'].to_s].first if hash_with_foreign_keys[entry['database_id'].to_s].present?
            entry[ct_field_id] = JSON.parse(File.read("#{config.entries_dir}/#{related_model_directory}/#{related_model_directory}_#{related_file_id}.json"))[linked_model[:field]]
            write_json_to_file(entry_path, entry)
          end
        end

        def aggregate_belongs(linked_model, entry, entry_path, related_to)
          if entry[linked_model[:primary_id]]
            related_model = linked_model[related_to]
            ct_field_id = linked_model[:save_as] || linked_model[:field]
            related_model_directory = I18n.transliterate(mapping[related_model][:content_type]).underscore.tr(' ', '_')
            associated_foreign_key = related_model_directory + '_' + entry[linked_model[:primary_id]].to_s
            associated_object = JSON.parse(File.read("#{config.entries_dir}/#{related_model_directory}/#{associated_foreign_key}.json"))[linked_model[:field]]
            write_json_to_file(entry_path, entry.merge!(ct_field_id => associated_object))
          end
        end

        def save_aggregated_entries(linked_model, ct_field_id, entry, entry_path, related_to)
          ct_field = linked_model['save_as'] || ct_field_id
          related_model = linked_model[related_to].underscore
          contentful_name = model_content_type(linked_model[:relation_to]).underscore
          associated_objects = save_aggregated_object_to_file(entry, related_model, contentful_name, linked_model)
          write_json_to_file(entry_path, entry.merge!(ct_field => associated_objects)) if associated_objects.present?
        end

        def save_aggregated_object_to_file(entry, related_model, contentful_name, linked_model)
          primary_id = linked_model[:primary_id]
          Dir.glob("#{config.helpers_dir}/#{primary_id}_#{related_model}.json") do |through_file|
            hash_with_foreign_keys = JSON.parse(File.read(through_file))
            return hash_with_aggregate_objects(hash_with_foreign_keys, entry, contentful_name, linked_model)
          end
        end

        def hash_with_aggregate_objects(hash_with_foreign_keys, entry, contentful_name, linked_model)
          if hash_with_foreign_keys.has_key?(entry['database_id'].to_s)
            associated_objects = hash_with_foreign_keys[entry['database_id'].to_s].each_with_object([]) do |foreign_key, result|
              aggregated_file = JSON.parse(File.read("#{config.entries_dir}/#{contentful_name}/#{contentful_name}_#{foreign_key}.json"))
              result << aggregated_file[linked_model[:field]]
            end
          end
          associated_objects
        end
      end
    end
  end
end


text:
package com.haulmont.chile.core.model;

import com.haulmont.cuba.core.global.MetadataTools;

import javax.annotation.Nullable;
import java.io.Serializable;

/**
 * Interface to be implemented by data model objects.
 */
public interface Instance extends Serializable {

    /**
     * @return metaclass of this object. Throws exception if the metaclass is not found.
     */
    MetaClass getMetaClass();

    /**
     * @return Instance name as defined by {@link com.haulmont.chile.core.annotations.NamePattern}
     * or {@code toString()}.
     * @deprecated Use {@link MetadataTools#getInstanceName(com.haulmont.chile.core.model.Instance)} instead.
     */
    @Deprecated
    String getInstanceName();

    /**
     * Get an attribute value.
     * @param name  attribute name according to JavaBeans notation
     * @return      attribute value
     */
    @Nullable
    <T> T getValue(String name);

    /**
     * Set an attribute value.
     *

     * An implementor should first read a current value of the attribute, and then call an appropriate setter
     * method only if the new value differs. This ensures triggering of {@link PropertyChangeListener}s only if the attribute
     * was actually changed.
     *
     * @param name  attribute name according to JavaBeans notation
     * @param value attribute value
     */
    void setValue(String name, Object value);

    /**
     * Get an attribute value. Locates the attribute by the given path in object graph starting from this instance.
     *

     * The path must consist of attribute names according to JavaBeans notation, separated by dots, e.g.
     * {@code car.driver.name}.
     *
     * @param propertyPath path to an attribute
     * @return attribute value. If any traversing attribute value is null or is not an {@link Instance}, this method
     * stops here and returns this value.
     */
    @Nullable
    <T> T getValueEx(String propertyPath);

    /**
     * Set an attribute value. Locates the attribute by the given path in object graph starting from this instance.
     *
 The path must consist of attribute names according to JavaBeans notation, separated by dots, e.g.
     * {@code car.driver.name}.
     *
 In the example above this method first gets value of {@code car.driver} attribute, and if it is not
     * null and is an {@link Instance}, sets value of {@code name} attribute in it.
     *
 An implementor should first read a current value of the attribute, and then call an appropriate setter
     * method only if the new value differs. This ensures triggering of {@link PropertyChangeListener}s only if the attribute
     * was actually changed.
     *
     * @param propertyPath path to an attribute
     * @param value        attribute value
     */
    void setValueEx(String propertyPath, Object value);

    /**
     * Add listener to track attributes changes.
     * @param listener  listener
     */
    void addPropertyChangeListener(PropertyChangeListener listener);

    /**
     * Remove listener.
     * @param listener listener to remove
     */
    void removePropertyChangeListener(PropertyChangeListener listener);

    /**
     * Remove all {@link PropertyChangeListener}s.
     */
    void removeAllListeners();

    /**
     * Event object for {@link com.haulmont.chile.core.model.Instance.PropertyChangeListener}.
     */
    class PropertyChangeEvent {
        private final Instance item;
        private final String property;
        private final Object prevValue;
        private final Object value;

        public PropertyChangeEvent(Instance item, String property, Object prevValue, Object value) {
            this.item = item;
            this.property = property;
            this.prevValue = prevValue;
            this.value = value;
        }

        /**
         * @return property name
         */
        public String getProperty() {
            return property;
        }

        /**
         * @return data model object
         */
        public Instance getItem() {
            return item;
        }

        /**
         * @return previous value of property
         */
        @Nullable
        public Object getPrevValue() {
            return prevValue;
        }

        /**
         * @return current value of property
         */
        @Nullable
        public Object getValue() {
            return value;
        }
    }

    /**
     * Interface to track changes in data model objects.
     */
    @FunctionalInterface
    interface PropertyChangeListener {
        /**
         * Called when value of instance property changed.
         *
         * @param e event object
         */
        void propertyChanged(PropertyChangeEvent e);
    }
}

redpajama_set_name: RedPajamaGithub


text:
extern "C" {
#endif

struct Turbo_Property {
    const char *name;
    unsigned name_length;
    struct Turbo_Value value;
};

const char *Turbo_Object(struct Turbo_Value * __restrict__ to, const char *in, const char *const end);
void Turbo_WriteObject(struct Turbo_Value *that, FILE *out, int level);

#ifdef __cplusplus
}
#endif


text:
Bienvenue dans votre espace coach

      Gestion des coachs
 Sur cette page que vous allez pouvoir lister l'ensemble des coachs de votre organization.
 Vous pourrez ensuite définir le planning de chaque coach en leur associant les séances qu'ils encadrent.

    <mat-accordion *ngIf="coaches">
      <mat-expansion-panel *ngFor="let coach of coaches" [disabled]="true">
        <mat-expansion-panel-header>
          <mat-panel-title>

{{coach.firstname}} {{coach.lastname}}

          </mat-panel-title>
          <mat-panel-description class="justify-content-end">
            <button mat-raised-button color="accent" routerLink="../{{coach.id}}/edit" class="mr-3"><mat-icon>edit</mat-icon>MODIFIER</button>
            <button mat-raised-button color="accent" routerLink="../../planning/view/coach/{{coach.id}}"><mat-icon>today</mat-icon>VOIR LE PLANNING</button>
          </mat-panel-description>
        </mat-expansion-panel-header>
      </mat-expansion-panel>
      <mat-expansion-panel [disabled]="true">
        <mat-expansion-panel-header>
          <mat-panel-title>
          </mat-panel-title>
          <mat-panel-description class="justify-content-end">
            <button mat-raised-button color="primary" routerLink="../add">AJOUTER UN COACH</button>
          </mat-panel-description>
        </mat-expansion-panel-header>
      </mat-expansion-panel>
    </mat-accordion>


text:
<title>Results for com.idm.polygon.TestConnection</title>
Select a result on the left-hand pane.


text:
package main

import (
	"github.com/adbourne/go-archetype-kafka-processor/config"
	"github.com/adbourne/go-archetype-kafka-processor/processors"
	"github.com/adbourne/go-archetype-kafka-processor/services"
)

// AppContext is the application context
type AppContext struct {
	// AppConfig is the application config
	AppConfig config.AppConfig

	// Logger is the logger
	Logger services.Logger

	// RandomNumberService is the random number service
	RandomNumberService services.RandomNumberService

	// KafkaClient is the Kafka client
	KafkaClient services.KafkaClient

	// KafkaProcessor is the Kafka Processor
	KafkaProcessor services.KafkaProcessor

	// HTTPServer is the HTTP server
	HTTPServer services.HTTPServer
}

// NewAppContext creates the application context
func NewAppContext(appConfig config.AppConfig) *AppContext {
	logger := newLogger()
	randomNumberService := newRandomNumberService()
	return &AppContext{
		AppConfig:           appConfig,
		RandomNumberService: randomNumberService,
		KafkaClient:         newKafkaClient(appConfig, logger),
		KafkaProcessor:      newKafkaProcessor(randomNumberService, logger),
		HTTPServer:          newHTTPServer(appConfig, logger),
		Logger:              newLogger(),
	}
}

// Creates a new Logger
func newLogger() services.Logger {
	return &services.SystemOutLogger{}
}

// Creates a RandomNumberService
func newRandomNumberService() *services.DefaultRandomNumberService {
	return &services.DefaultRandomNumberService{}
}

// Creates a KafkaClient
func newKafkaClient(appConfig config.AppConfig, logger services.Logger) services.KafkaClient {
	return services.NewSaramaKafkaClient(appConfig, logger)
}

// Creates a new KafkaProcessor
func newKafkaProcessor(randomNumberService services.RandomNumberService, logger services.Logger) services.KafkaProcessor {
	return &processors.RandomNumberProcessor{
		Logger:              logger,
		RandomNumberService: randomNumberService,
	}
}

// Creates the HTTP server
func newHTTPServer(appConfig config.AppConfig, logger services.Logger) services.HTTPServer {
	return services.NewDefaultHTTPServer(appConfig.Port, logger)
}


text:
"""Test code shared between test files."""

from pyatv import conf, interface
from pyatv.const import Protocol

class MockPairingHandler(interface.PairingHandler):
    """Mock for PairingHandler in pyatv."""

    def __init__(self, *args):
        """Initialize a new MockPairingHandler."""
        super().__init__(*args)
        self.pin_code = None
        self.paired = False
        self.always_fail = False

    def pin(self, pin):
        """Pin code used for pairing."""
        self.pin_code = pin
        self.paired = False

    @property
    def device_provides_pin(self):
        """Return True if remote device presents PIN code, else False."""
        return self.service.protocol in [Protocol.MRP, Protocol.AirPlay]

    @property
    def has_paired(self):
        """If a successful pairing has been performed.

        The value will be reset when stop() is called.
        """
        return not self.always_fail and self.paired

    async def begin(self):
        """Start pairing process."""

    async def finish(self):
        """Stop pairing process."""
        self.paired = True
        self.service.credentials = self.service.protocol.name.lower() + "_creds"

def create_conf(name, address, *services):
    """Create an Apple TV configuration."""
    atv = conf.AppleTV(name, address)
    for service in services:
        atv.add_service(service)
    return atv


text:
namespace PcapDotNet.Packets.IpV6
{
    /// <summary>
    /// RFC 4283.
    /// </summary>
    public enum IpV6MobileNodeIdentifierSubtype : byte
    {
        /// <summary>
        /// Invalid value.
        /// </summary>
        None = 0,

        /// <summary>
        /// RFC 4283.
        /// Uses an identifier of the form user@realm (RFC 4282).
        /// </summary>
        NetworkAccessIdentifier = 1,
    }
}


text:
![](https://raw.githubusercontent.com/dckg/AndroidBackgroundExample/master/github/img1.png)

Shows examples of performing tasks in background without disturbing UI:

* AsyncTask
* Activity.RunOnUiThread
* Handler Thread & Message
* My fancy double callback with FutureTask

You can filter for ``Thread`` in Android Monitor.
Also see inline comments in ``MainActivity.java``.

The red Button is how **not** to make something in the background. This will execute on UI Thread and make UI unresponsive.

***

# Documentation
[Worker Thread sample implementation](https://dckg.net/blog/p/2016/06/01/java-threadkommunikation)
![](https://raw.githubusercontent.com/dckg/AndroidBackgroundExample/master/github/docs-a4.png)


text:
package com.intellij.util.xml.impl;

import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileWithId;
import com.intellij.psi.PsiErrorElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.impl.PsiFileEx;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.stubs.ObjectStubTree;
import com.intellij.psi.stubs.Stub;
import com.intellij.psi.stubs.StubTreeLoader;
import com.intellij.psi.util.CachedValueProvider;
import com.intellij.psi.util.CachedValuesManager;
import com.intellij.psi.xml.*;
import com.intellij.util.Function;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.xml.*;
import com.intellij.util.xml.structure.DomStructureViewBuilder;
import com.intellij.util.xml.stubs.FileStub;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Gregory.Shrago
 */
public class DomServiceImpl extends DomService {

  @NotNull
  private static XmlFileHeader calcXmlFileHeader(final XmlFile file) {

    if (file instanceof PsiFileEx && ((PsiFileEx)file).isContentsLoaded() && file.getNode().isParsed()) {
      return computeHeaderByPsi(file);
    }

    if (FileBasedIndex.getInstance().getFileBeingCurrentlyIndexed() == null && file.getFileType() == XmlFileType.INSTANCE) {
      VirtualFile virtualFile = file.getVirtualFile();
      if (virtualFile instanceof VirtualFileWithId) {
        ObjectStubTree<?> tree = StubTreeLoader.getInstance().readFromVFile(file.getProject(), virtualFile);
        if (tree != null) {
          Stub root = tree.getRoot();
          if (root instanceof FileStub) {
            return ((FileStub)root).getHeader();
          }
        }
      }
    }

    if (!file.isValid()) return XmlFileHeader.EMPTY;

    XmlFileHeader header = NanoXmlUtil.parseHeader(file);
    if (header.getRootTagLocalName() == null) { // nanoxml failed
      return computeHeaderByPsi(file);
    }
    return header;
  }

  private static XmlFileHeader computeHeaderByPsi(XmlFile file) {
    final XmlDocument document = file.getDocument();
    if (document == null) {
      return XmlFileHeader.EMPTY;
    }

    String publicId = null;
    String systemId = null;
    final XmlProlog prolog = document.getProlog();
    if (prolog != null) {
      final XmlDoctype doctype = prolog.getDoctype();
      if (doctype != null) {
        publicId = doctype.getPublicId();
        systemId = doctype.getSystemId();
        if (systemId == null) {
          systemId = doctype.getDtdUri();
        }
      }
    }

    final XmlTag tag = document.getRootTag();
    if (tag == null) {
      return XmlFileHeader.EMPTY;
    }

    String localName = tag.getLocalName();
    if (StringUtil.isNotEmpty(localName)) {
      if (tag.getPrevSibling() instanceof PsiErrorElement) {
        return XmlFileHeader.EMPTY;
      }

      String psiNs = tag.getLocalNamespaceDeclarations().get(tag.getNamespacePrefix());
      return new XmlFileHeader(localName, psiNs, publicId, systemId);
    }
    return XmlFileHeader.EMPTY;
  }

  @Override
  public ModelMerger createModelMerger() {
    return new ModelMergerImpl();
  }

  @Override
  public <T extends DomElement> DomAnchor<T> createAnchor(T domElement) {
    return DomAnchorImpl.createAnchor(domElement);
  }

  @Override
  @NotNull
  public XmlFile getContainingFile(@NotNull DomElement domElement) {
    if (domElement instanceof DomFileElement) {
      return ((DomFileElement<?>)domElement).getFile();
    }
    return DomManagerImpl.getNotNullHandler(domElement).getFile();
  }

  @Override
  @NotNull
  public EvaluatedXmlName getEvaluatedXmlName(@NotNull final DomElement element) {
    return DomManagerImpl.getNotNullHandler(element).getXmlName();
  }

  @Override
  @NotNull
  public XmlFileHeader getXmlFileHeader(XmlFile file) {
    if (FileBasedIndex.getInstance().getFileBeingCurrentlyIndexed() != null) {
      return calcXmlFileHeader(file);
    }

    return CachedValuesManager.getCachedValue(file, () -> new CachedValueProvider.Result<>(calcXmlFileHeader(file), file));
  }

  @Override
  public Collection<VirtualFile> getDomFileCandidates(Class<? extends DomElement> rootElementClass,
                                                      Project project,
                                                      final GlobalSearchScope scope) {
    return FileBasedIndex.getInstance().getContainingFiles(DomFileIndex.NAME, rootElementClass.getName(), scope);
  }

  @Override
  public <T extends DomElement> List<DomFileElement<T>> getFileElements(final Class<T> clazz, final Project project, @Nullable final GlobalSearchScope scope) {
    final Collection<VirtualFile> list = getDomFileCandidates(clazz, project, scope != null ? scope : GlobalSearchScope.allScope(project));
    final ArrayList<DomFileElement<T>> result = new ArrayList<>(list.size());
    for (VirtualFile file : list) {
      final PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
      if (psiFile instanceof XmlFile) {
        final DomFileElement<T> element = DomManager.getDomManager(project).getFileElement((XmlFile)psiFile, clazz);
        if (element != null) {
          result.add(element);
        }
      }
    }

    return result;
  }

  @Override
  public StructureViewBuilder createSimpleStructureViewBuilder(final XmlFile file, final Function<DomElement, StructureViewMode> modeProvider) {
    return new DomStructureViewBuilder(file, modeProvider);
  }
}


text:
package groovy.swing.impl;

import javax.swing.*;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * A {@code ListModel} implementation that's backed by a live {@code List}.
 *
 * @author Andres Almiray
 */
public class ListWrapperListModel<E> extends AbstractListModel {
    private final List<E> delegate;

    public ListWrapperListModel(List<E> delegateList) {
        this.delegate = delegateList;
    }

    public List<E> getDelegateList() {
        return delegate;
    }

    public int getSize() {
        return delegate.size();
    }

    public Object getElementAt(int i) {
        return delegate.get(i);
    }

    public E set(int i, E e) {
        E element = delegate.set(i, e);
        fireContentsChanged(this, i, i);
        return element;
    }

    public void clear() {
        int i = delegate.size() - 1;
        delegate.clear();
        if (i >= 0) {
            fireIntervalRemoved(this, 0, i);
        }
    }

    public int lastIndexOf(Object o) {
        return delegate.lastIndexOf(o);
    }

    public boolean contains(Object o) {
        return delegate.contains(o);
    }

    public ListIterator<E> listIterator() {
        return delegate.listIterator();
    }

    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    public int indexOf(Object o) {
        return delegate.indexOf(o);
    }

    public void add(int i, E e) {
        int index = delegate.size();
        delegate.add(i, e);
        fireIntervalAdded(this, index, index);
    }

    public Iterator<E> iterator() {
        return delegate.iterator();
    }

    public boolean addAll(Collection<? extends E> es) {
        int i = delegate.size();
        boolean added = delegate.addAll(es);
        if (added) fireIntervalAdded(this, i, i + es.size());
        return added;
    }

    public E remove(int i) {
        E element = delegate.remove(i);
        fireIntervalRemoved(this, i, i);
        return element;
    }

    public boolean addAll(int i, Collection<? extends E> es) {
        boolean added = delegate.addAll(i, es);
        if (added) fireIntervalAdded(this, i, i + es.size());
        return added;
    }

    public ListIterator<E> listIterator(int i) {
        return delegate.listIterator(i);
    }

    public boolean containsAll(Collection<?> objects) {
        return delegate.containsAll(objects);
    }

    public boolean remove(Object o) {
        int i = indexOf(o);
        boolean rv = delegate.remove(o);
        if (i >= 0) {
            fireIntervalRemoved(this, i, i);
        }
        return rv;
    }

    public boolean add(E e) {
        int i = delegate.size();
        boolean added = delegate.add(e);
        if (added) fireIntervalAdded(this, i, i);
        return added;
    }

    public E get(int i) {
        return delegate.get(i);
    }

    public <T> T[] toArray(T[] ts) {
        return delegate.toArray(ts);
    }

    public Object[] toArray() {
        return delegate.toArray();
    }

    public void removeRange(int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException("fromIndex must be <= toIndex");
        }
        delegate.subList(fromIndex, toIndex + 1).clear();
        fireIntervalRemoved(this, fromIndex, toIndex);
    }
}


text:
module HealthSeven::V2_5_1
class Nck < ::HealthSeven::Segment
  # System Date/Time
  attribute :system_date_time, Ts, position: "NCK.1", require: true
end
end


text:
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/module.h>
#include <sys/consio.h>
#include <sys/fbio.h>

#include <dev/fb/fbreg.h>
#include <dev/fb/splashreg.h>
#include <dev/syscons/syscons.h>

#include <sys/selinfo.h>
#include <machine/apm_bios.h>
#include <machine/pc/bios.h>
#ifdef PC98
#include <machine/bus.h>
#include <pc98/apm/apm.h>
#else
#include <i386/apm/apm.h>
#endif

extern int apm_display(int newstate);

extern struct apm_softc apm_softc;

static int blanked=0;

static int
apm_saver(video_adapter_t *adp, int blank)
{
	if (!apm_softc.initialized || !apm_softc.active)
		return 0;

	if (blank==blanked)
		return 0;

	blanked=blank;

	apm_display(!blanked);

	return 0;
}

static int
apm_init(video_adapter_t *adp)
{
	if (!apm_softc.initialized || !apm_softc.active)
		printf("WARNING: apm_saver module requires apm enabled\n");
	return 0;
}

static int
apm_term(video_adapter_t *adp)
{
	return 0;
}

static scrn_saver_t apm_module = {
	"apm_saver", apm_init, apm_term, apm_saver, NULL,
};

SAVER_MODULE(apm_saver, apm_module);


text:
package com.google.cloud.retail.v2alpha;

import com.google.api.pathtemplate.PathTemplate;
import com.google.api.resourcenames.ResourceName;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;

// AUTO-GENERATED DOCUMENTATION AND CLASS.
@Generated("by gapic-generator-java")
public class BranchName implements ResourceName {
  private static final PathTemplate PROJECT_LOCATION_CATALOG_BRANCH =
      PathTemplate.createWithoutUrlEncoding(
          "projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}");
  private volatile Map<String, String> fieldValuesMap;
  private final String project;
  private final String location;
  private final String catalog;
  private final String branch;

  @Deprecated
  protected BranchName() {
    project = null;
    location = null;
    catalog = null;
    branch = null;
  }

  private BranchName(Builder builder) {
    project = Preconditions.checkNotNull(builder.getProject());
    location = Preconditions.checkNotNull(builder.getLocation());
    catalog = Preconditions.checkNotNull(builder.getCatalog());
    branch = Preconditions.checkNotNull(builder.getBranch());
  }

  public String getProject() {
    return project;
  }

  public String getLocation() {
    return location;
  }

  public String getCatalog() {
    return catalog;
  }

  public String getBranch() {
    return branch;
  }

  public static Builder newBuilder() {
    return new Builder();
  }

  public Builder toBuilder() {
    return new Builder(this);
  }

  public static BranchName of(String project, String location, String catalog, String branch) {
    return newBuilder()
        .setProject(project)
        .setLocation(location)
        .setCatalog(catalog)
        .setBranch(branch)
        .build();
  }

  public static String format(String project, String location, String catalog, String branch) {
    return newBuilder()
        .setProject(project)
        .setLocation(location)
        .setCatalog(catalog)
        .setBranch(branch)
        .build()
        .toString();
  }

  public static BranchName parse(String formattedString) {
    if (formattedString.isEmpty()) {
      return null;
    }
    Map<String, String> matchMap =
        PROJECT_LOCATION_CATALOG_BRANCH.validatedMatch(
            formattedString, "BranchName.parse: formattedString not in valid format");
    return of(
        matchMap.get("project"),
        matchMap.get("location"),
        matchMap.get("catalog"),
        matchMap.get("branch"));
  }

  public static List<BranchName> parseList(List<String> formattedStrings) {
    List<BranchName> list = new ArrayList<>(formattedStrings.size());
    for (String formattedString : formattedStrings) {
      list.add(parse(formattedString));
    }
    return list;
  }

  public static List<String> toStringList(List<BranchName> values) {
    List<String> list = new ArrayList<>(values.size());
    for (BranchName value : values) {
      if (value == null) {
        list.add("");
      } else {
        list.add(value.toString());
      }
    }
    return list;
  }

  public static boolean isParsableFrom(String formattedString) {
    return PROJECT_LOCATION_CATALOG_BRANCH.matches(formattedString);
  }

  @Override
  public Map<String, String> getFieldValuesMap() {
    if (fieldValuesMap == null) {
      synchronized (this) {
        if (fieldValuesMap == null) {
          ImmutableMap.Builder<String, String> fieldMapBuilder = ImmutableMap.builder();
          if (project != null) {
            fieldMapBuilder.put("project", project);
          }
          if (location != null) {
            fieldMapBuilder.put("location", location);
          }
          if (catalog != null) {
            fieldMapBuilder.put("catalog", catalog);
          }
          if (branch != null) {
            fieldMapBuilder.put("branch", branch);
          }
          fieldValuesMap = fieldMapBuilder.build();
        }
      }
    }
    return fieldValuesMap;
  }

  public String getFieldValue(String fieldName) {
    return getFieldValuesMap().get(fieldName);
  }

  @Override
  public String toString() {
    return PROJECT_LOCATION_CATALOG_BRANCH.instantiate(
        "project", project, "location", location, "catalog", catalog, "branch", branch);
  }

  @Override
  public boolean equals(Object o) {
    if (o == this) {
      return true;
    }
    if (o != null || getClass() == o.getClass()) {
      BranchName that = ((BranchName) o);
      return Objects.equals(this.project, that.project)
          && Objects.equals(this.location, that.location)
          && Objects.equals(this.catalog, that.catalog)
          && Objects.equals(this.branch, that.branch);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int h = 1;
    h *= 1000003;
    h ^= Objects.hashCode(project);
    h *= 1000003;
    h ^= Objects.hashCode(location);
    h *= 1000003;
    h ^= Objects.hashCode(catalog);
    h *= 1000003;
    h ^= Objects.hashCode(branch);
    return h;
  }

  /** Builder for projects/{project}/locations/{location}/catalogs/{catalog}/branches/{branch}. */
  public static class Builder {
    private String project;
    private String location;
    private String catalog;
    private String branch;

    protected Builder() {}

    public String getProject() {
      return project;
    }

    public String getLocation() {
      return location;
    }

    public String getCatalog() {
      return catalog;
    }

    public String getBranch() {
      return branch;
    }

    public Builder setProject(String project) {
      this.project = project;
      return this;
    }

    public Builder setLocation(String location) {
      this.location = location;
      return this;
    }

    public Builder setCatalog(String catalog) {
      this.catalog = catalog;
      return this;
    }

    public Builder setBranch(String branch) {
      this.branch = branch;
      return this;
    }

    private Builder(BranchName branchName) {
      this.project = branchName.project;
      this.location = branchName.location;
      this.catalog = branchName.catalog;
      this.branch = branchName.branch;
    }

    public BranchName build() {
      return new BranchName(this);
    }
  }
}


text:
Release 0.1.0 Notes
-------------------

Supported features:

-	[deploy protostub](https://github.com/reTHINK-project/core-framework/blob/master/docs/specs/runtime/dynamic-view/basics/deploy-protostub.md)
-	[deploy Hyperty in the App Sandbox](https://github.com/reTHINK-project/core-framework/blob/master/docs/specs/runtime/dynamic-view/basics/deploy-hyperty.md)
-	[Hyperty Registration](https://github.com/reTHINK-project/core-framework/blob/master/docs/specs/runtime/dynamic-view/basics/register-hyperty.md)
-	[Message Routing](https://github.com/reTHINK-project/core-framework/blob/master/docs/specs/runtime/dynamic-view/basics/bus-msg-routing.md)
-	[exchange of messages between local Hyperties](https://github.com/reTHINK-project/core-framework/blob/master/docs/specs/runtime/dynamic-view/basics/intra-local-comm.md)

Known issues:

-	no integration with Catalogue server
-	no integration with Domain Registry Server
-	Messages format not fully compliant with [WP2 Spec](https://github.com/reTHINK-project/architecture/tree/master/docs/datamodel/message).
-	Hyperty descriptor and Protostub descriptor not fully compliant with [WP2 Spec](https://github.com/reTHINK-project/architecture/tree/master/docs/datamodel/hyperty-catalogue).


text:
import BScroll from '@better-scroll/core'
import { IndicatorOptions, Ratio, Postion, ValueSign } from './types'
import {
  EventRegister,
  EventEmitter,
  getRect,
  getClientSize,
  getNow,
  between,
  Probe,
  TouchEvent,
  style,
  maybePrevent,
} from '@better-scroll/shared-utils'
const resolveRatioOption = (ratioConfig?: Ratio) => {
  let ret = {
    ratioX: 0,
    ratioY: 0,
  }
  /* istanbul ignore if  */
  if (!ratioConfig) {
    return ret
  }
  if (typeof ratioConfig === 'number') {
    ret.ratioX = ret.ratioY = ratioConfig
  } else if (typeof ratioConfig === 'object' && ratioConfig) {
    ret.ratioX = ratioConfig.x || 0
    ret.ratioY = ratioConfig.y || 0
  }
  return ret
}

const handleBubbleAndCancelable = (e: TouchEvent) => {
  maybePrevent(e)
  e.stopPropagation()
}
export default class Indicator {
  wrapper: HTMLElement
  indicatorEl: HTMLElement
  maxScrollX: number
  minScrollX: number
  ratioX: number
  maxScrollY: number
  minScrollY: number
  translateXSign: ValueSign
  translateYSign: ValueSign
  ratioY: number
  currentPos: Postion = {
    x: 0,
    y: 0,
  }
  moved: boolean
  startTime: number
  initiated: boolean
  lastPointX: number
  lastPointY: number
  startEventRegister: EventRegister
  moveEventRegister: EventRegister
  endEventRegister: EventRegister
  hooksFn: [EventEmitter, string, Function][] = []
  constructor(public scroll: BScroll, public options: IndicatorOptions) {
    this.handleDOM()
    this.handleHooks()
    this.handleInteractive()
  }

  private handleDOM() {
    const { relationElement, relationElementHandleElementIndex = 0 } =
      this.options
    this.wrapper = relationElement
    this.indicatorEl = this.wrapper.children[
      relationElementHandleElementIndex
    ] as HTMLElement
  }

  private handleHooks() {
    const scroll = this.scroll
    const scrollHooks = scroll.hooks
    const translaterHooks = scroll.scroller.translater.hooks
    const animaterHooks = scroll.scroller.animater.hooks

    this.registerHooks(
      scrollHooks,
      scrollHooks.eventTypes.refresh,
      this.refresh
    )

    this.registerHooks(
      translaterHooks,
      translaterHooks.eventTypes.translate,
      (pos: Postion) => {
        this.updatePosition(pos)
      }
    )

    this.registerHooks(
      animaterHooks,
      animaterHooks.eventTypes.time,
      this.transitionTime
    )

    this.registerHooks(
      animaterHooks,
      animaterHooks.eventTypes.timeFunction,
      this.transitionTimingFunction
    )
  }

  private transitionTime(time: number = 0) {
    this.indicatorEl.style[style.transitionDuration as any] = time + 'ms'
  }

  private transitionTimingFunction(easing: string) {
    this.indicatorEl.style[style.transitionTimingFunction as any] = easing
  }

  private handleInteractive() {
    if (this.options.interactive !== false) {
      this.registerEvents()
    }
  }

  private registerHooks(hooks: EventEmitter, name: string, handler: Function) {
    hooks.on(name, handler, this)
    this.hooksFn.push([hooks, name, handler])
  }

  private registerEvents() {
    const { disableMouse, disableTouch } = this.scroll.options
    const startEvents = []
    const moveEvents = []
    const endEvents = []

    if (!disableMouse) {
      startEvents.push({
        name: 'mousedown',
        handler: this.start.bind(this),
      })

      moveEvents.push({
        name: 'mousemove',
        handler: this.move.bind(this),
      })

      endEvents.push({
        name: 'mouseup',
        handler: this.end.bind(this),
      })
    }

    if (!disableTouch) {
      startEvents.push({
        name: 'touchstart',
        handler: this.start.bind(this),
      })

      moveEvents.push({
        name: 'touchmove',
        handler: this.move.bind(this),
      })

      endEvents.push(
        {
          name: 'touchend',
          handler: this.end.bind(this),
        },
        {
          name: 'touchcancel',
          handler: this.end.bind(this),
        }
      )
    }

    this.startEventRegister = new EventRegister(this.indicatorEl, startEvents)
    this.moveEventRegister = new EventRegister(window, moveEvents)
    this.endEventRegister = new EventRegister(window, endEvents)
  }

  refresh() {
    const {
      x,
      y,
      hasHorizontalScroll,
      hasVerticalScroll,
      maxScrollX: maxBScrollX,
      maxScrollY: maxBScrollY,
    } = this.scroll
    const { ratioX, ratioY } = resolveRatioOption(this.options.ratio)
    const { width: wrapperWidth, height: wrapperHeight } = getClientSize(
      this.wrapper
    )
    const { width: indicatorWidth, height: indicatorHeight } = getRect(
      this.indicatorEl
    )
    if (hasHorizontalScroll) {
      this.maxScrollX = wrapperWidth - indicatorWidth
      this.translateXSign =
        this.maxScrollX > 0 ? ValueSign.Positive : ValueSign.NotPositive
      this.minScrollX = 0
      // ensure positive
      this.ratioX = ratioX ? ratioX : Math.abs(this.maxScrollX / maxBScrollX)
    }

    if (hasVerticalScroll) {
      this.maxScrollY = wrapperHeight - indicatorHeight
      this.translateYSign =
        this.maxScrollY > 0 ? ValueSign.Positive : ValueSign.NotPositive
      this.minScrollY = 0
      this.ratioY = ratioY ? ratioY : Math.abs(this.maxScrollY / maxBScrollY)
    }

    this.updatePosition({
      x,
      y,
    })
  }

  private start(e: TouchEvent) {
    if (this.BScrollIsDisabled()) {
      return
    }
    let point = (e.touches ? e.touches[0] : e) as Touch

    handleBubbleAndCancelable(e)

    this.initiated = true
    this.moved = false
    this.lastPointX = point.pageX
    this.lastPointY = point.pageY
    this.startTime = getNow()
    this.scroll.scroller.hooks.trigger(
      this.scroll.scroller.hooks.eventTypes.beforeScrollStart
    )
  }

  private BScrollIsDisabled() {
    return !this.scroll.enabled
  }

  private move(e: TouchEvent) {
    if (!this.initiated) {
      return
    }
    let point = (e.touches ? e.touches[0] : e) as Touch
    const pointX = point.pageX
    const pointY = point.pageY

    handleBubbleAndCancelable(e)

    let deltaX = pointX - this.lastPointX
    let deltaY = pointY - this.lastPointY
    this.lastPointX = pointX
    this.lastPointY = pointY
    if (!this.moved && !this.indicatorNotMoved(deltaX, deltaY)) {
      this.moved = true
      this.scroll.scroller.hooks.trigger(
        this.scroll.scroller.hooks.eventTypes.scrollStart
      )
    }

    if (this.moved) {
      const newPos = this.getBScrollPosByRatio(this.currentPos, deltaX, deltaY)
      this.syncBScroll(newPos)
    }
  }

  private end(e: TouchEvent) {
    if (!this.initiated) {
      return
    }
    this.initiated = false

    handleBubbleAndCancelable(e)

    if (this.moved) {
      const { x, y } = this.scroll
      this.scroll.scroller.hooks.trigger(
        this.scroll.scroller.hooks.eventTypes.scrollEnd,
        {
          x,
          y,
        }
      )
    }
  }

  private getBScrollPosByRatio(
    currentPos: Postion,
    deltaX: number,
    deltaY: number
  ) {
    const { x: currentX, y: currentY } = currentPos

    const {
      hasHorizontalScroll,
      hasVerticalScroll,
      minScrollX: BScrollMinScrollX,
      maxScrollX: BScrollMaxScrollX,
      minScrollY: BScrollMinScrollY,
      maxScrollY: BScrollMaxScrollY,
    } = this.scroll

    let { x, y } = this.scroll

    if (hasHorizontalScroll) {
      const newPosX = between(
        currentX + deltaX,
        Math.min(this.minScrollX, this.maxScrollX),
        Math.max(this.minScrollX, this.maxScrollX)
      )
      const roundX = Math.round((newPosX / this.ratioX) * this.translateXSign)
      x = between(roundX, BScrollMaxScrollX, BScrollMinScrollX)
    }

    if (hasVerticalScroll) {
      const newPosY = between(
        currentY + deltaY,
        Math.min(this.minScrollY, this.maxScrollY),
        Math.max(this.minScrollY, this.maxScrollY)
      )
      const roundY = Math.round((newPosY / this.ratioY) * this.translateYSign)
      y = between(roundY, BScrollMaxScrollY, BScrollMinScrollY)
    }
    return { x, y }
  }

  private indicatorNotMoved(deltaX: number, deltaY: number): boolean {
    const { x, y } = this.currentPos
    const xNotMoved =
      (x === this.minScrollX && deltaX <= 0) ||
      (x === this.maxScrollX && deltaX >= 0)
    const yNotMoved =
      (y === this.minScrollY && deltaY <= 0) ||
      (y === this.maxScrollY && deltaY >= 0)
    return xNotMoved && yNotMoved
  }

  private syncBScroll(newPos: Postion) {
    const timestamp = getNow()
    const { options, scroller } = this.scroll
    const { probeType, momentumLimitTime } = options
    scroller.translater.translate(newPos)

    // dispatch scroll in interval time
    if (timestamp - this.startTime > momentumLimitTime) {
      this.startTime = timestamp
      if (probeType === Probe.Throttle) {
        scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos)
      }
    }

    // dispatch scroll all the time
    if (probeType > Probe.Throttle) {
      scroller.hooks.trigger(scroller.hooks.eventTypes.scroll, newPos)
    }
  }

  updatePosition(BScrollPos: Postion) {
    const newIndicatorPos = this.getIndicatorPosByRatio(BScrollPos)
    this.applyTransformProperty(newIndicatorPos)
    this.currentPos = { ...newIndicatorPos }
  }

  private applyTransformProperty(pos: Postion) {
    const translateZ = this.scroll.options.translateZ
    const transformProperties = [
      `translateX(${pos.x}px)`,
      `translateY(${pos.y}px)`,
      `${translateZ}`,
    ]
    this.indicatorEl.style[style.transform as any] =
      transformProperties.join(' ')
  }

  private getIndicatorPosByRatio(BScrollPos: Postion) {
    const { x, y } = BScrollPos
    const { hasHorizontalScroll, hasVerticalScroll } = this.scroll
    const position = { ...this.currentPos }
    if (hasHorizontalScroll) {
      const roundX = Math.round(this.ratioX * x * this.translateXSign)
      // maybe maxScrollX is negative
      position.x = between(
        roundX,
        Math.min(this.minScrollX, this.maxScrollX),
        Math.max(this.minScrollX, this.maxScrollX)
      )
    }

    if (hasVerticalScroll) {
      const roundY = Math.round(this.ratioY * y * this.translateYSign)
      // maybe maxScrollY is negative
      position.y = between(
        roundY,
        Math.min(this.minScrollY, this.maxScrollY),
        Math.max(this.minScrollY, this.maxScrollY)
      )
    }

    return position
  }

  destroy() {
    if (this.options.interactive !== false) {
      this.startEventRegister.destroy()
      this.moveEventRegister.destroy()
      this.endEventRegister.destroy()
    }

    this.hooksFn.forEach((item) => {
      const hooks = item[0]
      const hooksName = item[1]
      const handlerFn = item[2]
      hooks.off(hooksName, handlerFn)
    })
    this.hooksFn.length = 0
  }
}


text:
<?php

require_once 'PHPUnit/Util/Filter.php';

PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'PHPUNIT');

if (!class_exists('PHPUnit_Framework_Notice', FALSE)) {

/**
 * Wrapper for PHP notices.
 * You can disable notice-to-exception conversion by setting
 *
 * <code>
 * PHPUnit_Framework_Notice::$enabled = FALSE;
 * </code>
 *
 * @category   Testing
 * @package    PHPUnit
 * @author     Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @copyright  2002-2008 Sebastian Bergmann <sb@sebastian-bergmann.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: 3.2.9
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 3.1.0
 */
class PHPUnit_Framework_Notice extends PHPUnit_Framework_Error
{
    public static $enabled = TRUE;
}

}
?>


text:
use CellRenderer;
use IconSize;
use ffi;
use glib::StaticType;
use glib::Value;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::SignalHandlerId;
use glib::signal::connect_raw;
use glib::translate::*;
use glib_ffi;
use gobject_ffi;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;

glib_wrapper! {
    pub struct CellRendererSpinner(Object<ffi::GtkCellRendererSpinner, ffi::GtkCellRendererSpinnerClass, CellRendererSpinnerClass>) @extends CellRenderer;

    match fn {
        get_type => || ffi::gtk_cell_renderer_spinner_get_type(),
    }
}

impl CellRendererSpinner {
    pub fn new() -> CellRendererSpinner {
        assert_initialized_main_thread!();
        unsafe {
            CellRenderer::from_glib_none(ffi::gtk_cell_renderer_spinner_new()).unsafe_cast()
        }
    }
}

impl Default for CellRendererSpinner {
    fn default() -> Self {
        Self::new()
    }
}

pub const NONE_CELL_RENDERER_SPINNER: Option<&CellRendererSpinner> = None;

pub trait CellRendererSpinnerExt: 'static {
    fn get_property_active(&self) -> bool;

    fn set_property_active(&self, active: bool);

    fn get_property_pulse(&self) -> u32;

    fn set_property_pulse(&self, pulse: u32);

    fn get_property_size(&self) -> IconSize;

    fn set_property_size(&self, size: IconSize);

    fn connect_property_active_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;

    fn connect_property_pulse_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;

    fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}

impl<O: IsA<CellRendererSpinner>> CellRendererSpinnerExt for O {
    fn get_property_active(&self) -> bool {
        unsafe {
            let mut value = Value::from_type(<bool as StaticType>::static_type());
            gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, value.to_glib_none_mut().0);
            value.get().unwrap()
        }
    }

    fn set_property_active(&self, active: bool) {
        unsafe {
            gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"active\0".as_ptr() as *const _, Value::from(&active).to_glib_none().0);
        }
    }

    fn get_property_pulse(&self) -> u32 {
        unsafe {
            let mut value = Value::from_type(<u32 as StaticType>::static_type());
            gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"pulse\0".as_ptr() as *const _, value.to_glib_none_mut().0);
            value.get().unwrap()
        }
    }

    fn set_property_pulse(&self, pulse: u32) {
        unsafe {
            gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"pulse\0".as_ptr() as *const _, Value::from(&pulse).to_glib_none().0);
        }
    }

    fn get_property_size(&self) -> IconSize {
        unsafe {
            let mut value = Value::from_type(<IconSize as StaticType>::static_type());
            gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"size\0".as_ptr() as *const _, value.to_glib_none_mut().0);
            value.get().unwrap()
        }
    }

    fn set_property_size(&self, size: IconSize) {
        unsafe {
            gobject_ffi::g_object_set_property(self.to_glib_none().0 as *mut gobject_ffi::GObject, b"size\0".as_ptr() as *const _, Value::from(&size).to_glib_none().0);
        }
    }

    fn connect_property_active_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(self.as_ptr() as *mut _, b"notify::active\0".as_ptr() as *const _,
                Some(transmute(notify_active_trampoline::<Self, F> as usize)), Box_::into_raw(f))
        }
    }

    fn connect_property_pulse_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(self.as_ptr() as *mut _, b"notify::pulse\0".as_ptr() as *const _,
                Some(transmute(notify_pulse_trampoline::<Self, F> as usize)), Box_::into_raw(f))
        }
    }

    fn connect_property_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
        unsafe {
            let f: Box_<F> = Box_::new(f);
            connect_raw(self.as_ptr() as *mut _, b"notify::size\0".as_ptr() as *const _,
                Some(transmute(notify_size_trampoline::<Self, F> as usize)), Box_::into_raw(f))
        }
    }
}

unsafe extern "C" fn notify_active_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::GtkCellRendererSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<CellRendererSpinner> {
    let f: &F = transmute(f);
    f(&CellRendererSpinner::from_glib_borrow(this).unsafe_cast())
}

unsafe extern "C" fn notify_pulse_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::GtkCellRendererSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<CellRendererSpinner> {
    let f: &F = transmute(f);
    f(&CellRendererSpinner::from_glib_borrow(this).unsafe_cast())
}

unsafe extern "C" fn notify_size_trampoline<P, F: Fn(&P) + 'static>(this: *mut ffi::GtkCellRendererSpinner, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer)
where P: IsA<CellRendererSpinner> {
    let f: &F = transmute(f);
    f(&CellRendererSpinner::from_glib_borrow(this).unsafe_cast())
}

impl fmt::Display for CellRendererSpinner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "CellRendererSpinner")
    }
}


text:
#ifndef _REASON_H_
#define _REASON_H_

#include <stdint.h>

__BEGIN_DECLS

#include <kern/kern_cdata.h>

typedef void * os_reason_t;

os_reason_t os_reason_create(uint32_t osr_namespace, uint64_t osr_code);
int os_reason_alloc_buffer_noblock(os_reason_t cur_reason, uint32_t osr_bufsize);
struct kcdata_descriptor * os_reason_get_kcdata_descriptor(os_reason_t cur_reason);
void os_reason_ref(os_reason_t cur_reason);
void os_reason_free(os_reason_t cur_reason);

/*
 * Reason namespaces.
 */
#define OS_REASON_INVALID       0
#define OS_REASON_JETSAM        1
#define OS_REASON_SIGNAL        2
#define OS_REASON_CODESIGNING   3
#define OS_REASON_HANGTRACER    4
#define OS_REASON_TEST          5
#define OS_REASON_DYLD          6
#define OS_REASON_LIBXPC        7
#define OS_REASON_OBJC          8
#define OS_REASON_EXEC          9
#define OS_REASON_SPRINGBOARD   10
#define OS_REASON_TCC           11
#define OS_REASON_REPORTCRASH   12
#define OS_REASON_COREANIMATION 13
#define OS_REASON_AGGREGATED    14

/*
 * Update whenever new OS_REASON namespaces are added.
 */
#define OS_REASON_MAX_VALID_NAMESPACE OS_REASON_AGGREGATED

#define OS_REASON_BUFFER_MAX_SIZE 5120

#define OS_REASON_FLAG_NO_CRASH_REPORT          0x1  /* Don't create a crash report */
#define OS_REASON_FLAG_GENERATE_CRASH_REPORT    0x2  /* Create a crash report - the default for userspace requests */
#define OS_REASON_FLAG_FROM_USERSPACE           0x4  /* Reason created from a userspace syscall */
#define OS_REASON_FLAG_FAILED_DATA_COPYIN       0x8  /* We failed to copyin data from userspace */
#define OS_REASON_FLAG_PAYLOAD_TRUNCATED        0x10 /* The payload was truncated because it was longer than allowed */
#define OS_REASON_FLAG_BAD_PARAMS               0x20 /* Invalid parameters were passed involved with creating this reason */
#define OS_REASON_FLAG_CONSISTENT_FAILURE       0x40 /* Whatever caused this reason to be created will happen again */
#define OS_REASON_FLAG_ONE_TIME_FAILURE         0x80 /* Whatever caused this reason to be created was a one time issue */

/*
 * Set of flags that are allowed to be passed from userspace
 */
#define OS_REASON_FLAG_MASK_ALLOWED_FROM_USER	(OS_REASON_FLAG_CONSISTENT_FAILURE | OS_REASON_FLAG_ONE_TIME_FAILURE | OS_REASON_FLAG_NO_CRASH_REPORT)

/*
 * Macros to encode the exit reason namespace and first 32 bits of code in exception code
 * which is used by Report Crash as a hint. It should be only used as a hint since it
 * looses higher 32 bits of exit reason code.
 */
#define ENCODE_OSR_NAMESPACE_TO_MACH_EXCEPTION_CODE(code, osr_namespace) \
	(code) = (code) | (((osr_namespace) & ((uint64_t)UINT32_MAX)) << 32)
#define ENCODE_OSR_CODE_TO_MACH_EXCEPTION_CODE(code, osr_code) \
	(code) = (code) | ((osr_code) & ((uint64_t)UINT32_MAX))

/*
 * codesigning exit reasons
 */
#define CODESIGNING_EXIT_REASON_TASKGATED_INVALID_SIG 1
#define CODESIGNING_EXIT_REASON_INVALID_PAGE          2
#define CODESIGNING_EXIT_REASON_TASK_ACCESS_PORT      3

/*
 * exec path specific exit reasons
 */
#define EXEC_EXIT_REASON_BAD_MACHO          1
#define EXEC_EXIT_REASON_SUGID_FAILURE      2
#define EXEC_EXIT_REASON_ACTV_THREADSTATE   3
#define EXEC_EXIT_REASON_STACK_ALLOC        4
#define EXEC_EXIT_REASON_APPLE_STRING_INIT  5
#define EXEC_EXIT_REASON_COPYOUT_STRINGS    6
#define EXEC_EXIT_REASON_COPYOUT_DYNLINKER  7
#define EXEC_EXIT_REASON_SECURITY_POLICY    8
#define EXEC_EXIT_REASON_TASKGATED_OTHER    9
#define EXEC_EXIT_REASON_FAIRPLAY_DECRYPT   10
#define EXEC_EXIT_REASON_DECRYPT            11
#define EXEC_EXIT_REASON_UPX                12

__END_DECLS

#endif /* _REASON_H_ */


text:
package eu.openanalytics.shinyproxy;

import org.apache.commons.lang3.tuple.ImmutableTriple;
import org.springframework.data.util.Pair;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class OperatorCookieFilter extends GenericFilterBean {

    public static final List<FilterMatcher> REQUEST_MATCHERS = Arrays.asList(
            // all methods (to support the various auth backends)
            new FilterMatcher(new AntPathRequestMatcher("/"), false, ""),
            // all methods (to support the various auth backends)
            new FilterMatcher(new AntPathRequestMatcher("/login"),false, ""),
            new FilterMatcher(new AntPathRequestMatcher("/logout-success", HttpMethod.GET.name()), false, "logout-success"),
            // redirect to main page in order to re-try auth on new server
            new FilterMatcher(new AntPathRequestMatcher("/auth-error", HttpMethod.GET.name()), true, ""),
            // redirect to main page in order to re-try auth on new server
            new FilterMatcher(new AntPathRequestMatcher("/app-access-denied", HttpMethod.GET.name()), true, ""));

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        FilterMatcher match = match(httpRequest);

        if (match == null) {
            chain.doFilter(request, response);
            return;
        }

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        // only continue if the FilterMatcher allows authenticated requests OR if the user is NOT logged in
        if (match.alsoIfAuthenticated || !auth.isAuthenticated() || auth instanceof AnonymousAuthenticationToken) {
            String currentInstance = httpRequest.getHeader("X-ShinyProxy-Instance");
            String latestInstance = httpRequest.getHeader("X-ShinyProxy-Latest-Instance");

            if (currentInstance != null && latestInstance != null) {
                if (!currentInstance.equals(latestInstance)) {
                    String pattern = match.requestMatcher.getPattern();
                    HttpServletResponse httpResponse = (HttpServletResponse) response;
                    httpResponse.sendRedirect(
                            ServletUriComponentsBuilder
                                    .fromCurrentContextPath()
                                    .path("/server-transfer")
                                    .queryParam("redirectUri", pattern)
                                    .build()
                                    .toUriString()
                    );
                    return;
                }
            }
        }

        chain.doFilter(request, response);
    }

    public static FilterMatcher match(HttpServletRequest request) {
        for (FilterMatcher matcher : REQUEST_MATCHERS) {
            if (matcher.requestMatcher.matches(request)) {
                return matcher;
            }
        }
        return null;
    }

    public static String getRedirectUriByMatch(String redirectUri) {
        if (redirectUri == null) {
            return "";
        }
        for (FilterMatcher matcher : REQUEST_MATCHERS) {
            if (matcher.requestMatcher.getPattern().equals(redirectUri)) {
                return matcher.redirectUri;
            }
        }
        return "";
    }

    private static class FilterMatcher {
        public final AntPathRequestMatcher requestMatcher;
        public final Boolean alsoIfAuthenticated;
        public final String redirectUri;

        public FilterMatcher(AntPathRequestMatcher requestMatcher, Boolean alsoIfAuthenticated, String redirectUri) {
            this.requestMatcher = requestMatcher;
            this.alsoIfAuthenticated = alsoIfAuthenticated;
            this.redirectUri = redirectUri;
        }
    }

}


text:
package org.lizardbase.phototagger;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class Main extends Activity {

	private final int DIALOG_ALERT = 1;

	private final int REQUEST_SELECT_IMAGE = 9999;
	private final int REQUEST_TAG_PHOTO = 9998;
//	private final int REQUEST_TAKE_PHOTO = 9997;
	private final int REQUEST_CAPTURE_IMAGE = 9996;
	private final int REQUEST_CONFIGURATION = 9995;

	private Button btnCapture;
	private Button btnTag;
	private Button btnConfig;

	private LinearLayout linearMain;
	private LinearLayout linearLoading;

	protected Uri imageUri;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnCapture = (Button) findViewById(R.id.buttonCapture);
        btnTag = (Button) findViewById(R.id.buttonTag);
        btnConfig = (Button) findViewById(R.id.buttonConfig);
        linearMain = (LinearLayout) findViewById(R.id.linearMain);
        linearLoading = (LinearLayout) findViewById(R.id.linearLoading);

        this.btnCapture.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		try {
        			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        			startActivityForResult(intent, REQUEST_CAPTURE_IMAGE);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
        	}
        });

        this.btnTag.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		startActivityForResult(new Intent(Intent.ACTION_PICK,
        				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI),
        				REQUEST_SELECT_IMAGE);
        	}
        });

        this.btnConfig.setOnClickListener(new OnClickListener() {
        	public void onClick(View v) {
        		Intent intent = new Intent(v.getContext(), ConfigurationAct.class);
				startActivityForResult(intent, REQUEST_CONFIGURATION);
        	}
        });
    }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_SELECT_IMAGE) {
			if (resultCode == Activity.RESULT_OK) {
				Uri imgUri = data.getData();
				tagPhoto(imgUri);
			}
		} else if (requestCode == REQUEST_TAG_PHOTO) {
			resumeScreen();
			if (resultCode == Activity.RESULT_OK) {
				//Utils.showMessage(this, "OK TAG");
			}
		} else if (requestCode == REQUEST_CAPTURE_IMAGE) {
			if (resultCode == Activity.RESULT_OK) {
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
						Uri.parse("file://" + Environment.getExternalStorageDirectory())));
				Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
						null, null, null, null);
				long id = 0;
				if(cursor != null && cursor.getCount() > 0){
					cursor.moveToLast();
					id = cursor.getLong(0);
					Uri imgUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
					tagPhoto(imgUri);
				} else {
					String errMsg = "Cannot found any photo in the gallery.";
					showDialog("ERROR", errMsg);
				}
			}
		}
	}

	private void tagPhoto(Uri imgUri) {
		try {
			Intent intent = new Intent(this.getApplicationContext(), TagPhotoAct.class);
			Bundle bundle = new Bundle();
			bundle.putParcelable("IMGURI", imgUri);
			intent.putExtras(bundle);
			showLoading();
			startActivityForResult(intent, REQUEST_TAG_PHOTO);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private void showLoading() {
		this.linearMain.setVisibility(View.GONE);
		this.linearLoading.setVisibility(View.VISIBLE);
	}

	private void resumeScreen() {
		this.linearMain.setVisibility(View.VISIBLE);
		this.linearLoading.setVisibility(View.GONE);
	}

	private String dlgTitle;
	private String dlgMsg;

	private void showDialog(String title, String msg) {
		this.dlgTitle = title;
		this.dlgMsg = msg;
		showDialog(DIALOG_ALERT);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ALERT: {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(dlgTitle);
			builder.setMessage(dlgMsg);
			builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					setResult(Activity.RESULT_CANCELED);
				}
			});
	        return builder.create();
		}
		}
		return null;
	}
}


text:
<?php
/**
 * @package axy\patterns
 * @author Oleg Grigoriev <go.vasac@gmail.com>
 */

namespace axy\patterns;

use axy\callbacks\Callback;
use axy\magic\ArrayMagic;
use axy\patterns\errors\ContainerReadOnly;
use axy\patterns\errors\PropertyReadOnly;

/**
 * The registry
 * @SuppressWarnings(PHPMD.TooManyPublicMethods)
 */
class Registry implements \ArrayAccess, \IteratorAggregate, \Countable
{
    use ArrayMagic;

    /**
     * The constructor
     *
     * @param array $vars [optional]
     *        the list of variables (key => value)
     * @param array $lazy [optional]
     *        the list of lazy variables (key => creator)
     * @param boolean $readonly [optional]
     *        the read-only mode flag
     */
    public function __construct(array $vars = null, array $lazy = null, $readonly = false)
    {
        $this->vars = $vars ?: [];
        $this->lazy = $lazy ?: [];
        $this->readonly = $readonly;
    }

    /**
     * Sets a variable value
     *
     * @param string $name
     *        a variable name
     * @param mixed $value
     *        a variable value
     * @param boolean $const [optional]
     *        a variable read-only flag
     * @throws \axy\patterns\errors\ContainerReadOnly
     *         the registry is in read-only mode
     * @throws \axy\patterns\errors\PropertyReadOnly
     *         the variable is constant
     */
    public function set($name, $value, $const = false)
    {
        $this->checkWritable($name);
        $this->vars[$name] = $value;
        unset($this->lazy[$name]);
        $this->constants[$name] = $const;
    }

    /**
     * Sets a lazy variable
     *
     * @param string $name
     *        a variable name
     * @param callable $creator
     *        a creator of a variable value
     * @param boolean $const [optional]
     *        a variable read-only flag
     * @throws \axy\patterns\errors\ContainerReadOnly
     *         the registry is in read-only mode
     * @throws \axy\patterns\errors\PropertyReadOnly
     *         the variable is constant
     */
    public function setLazy($name, $creator, $const = false)
    {
        $this->checkWritable($name);
        $this->lazy[$name] = $creator;
        unset($this->vars[$name]);
        $this->constants[$name] = $const;
    }

    /**
     * Multi set of variables
     *
     * @param array $vars [optional]
     *        the list of variables (key => value)
     * @param array $lazy [optional]
     *        the list of lazy variables (key => creator)
     * @throws \axy\patterns\errors\ContainerReadOnly
     *         the registry is in read-only mode
     * @throws \axy\patterns\errors\PropertyReadOnly
     *         a variable is constant
     */
    public function setVars(array $vars = null, array $lazy = null)
    {
        if ($vars) {
            foreach ($vars as $k => $v) {
                $this->set($k, $v);
            }
        }
        if ($lazy) {
            foreach ($lazy as $k => $v) {
                $this->setLazy($k, $v);
            }
        }
    }

    /**
     * Returns a variable
     *
     * @param string $name
     *        a variable name
     * @param mixed $default [optional]
     *        a default value for a non-existing variable
     * @param boolean $load [optional]
     *        force load a lazy variable
     * @return mixed
     *         a value or default value
     * @throws \axy\callbacks\errors\NotCallable
     *         the creator for lazy variable is not callable
     */
    public function get($name, $default = null, $load = true)
    {
        if (array_key_exists($name, $this->vars)) {
            return $this->vars[$name];
        }
        if ((array_key_exists($name, $this->lazy)) && $load) {
            $this->vars[$name] = Callback::call($this->lazy[$name], [$name]);
            unset($this->lazy[$name]);
            return $this->vars[$name];
        }
        return $default;
    }

    /**
     * Checks if a variable exists
     *
     * @param string $name
     * @return boolean
     */
    public function exists($name)
    {
        return (array_key_exists($name, $this->vars) || array_key_exists($name, $this->lazy));
    }

    /**
     * Removes a variable
     *
     * @param string $name
     *        the variable name
     * @return boolean
     *         TRUE - if the variable was indeed removed
     * @throws \axy\patterns\errors\ContainerReadOnly
     *         the registry is in read-only mode
     * @throws \axy\patterns\errors\PropertyReadOnly
     *         the variable is constant
     */
    public function remove($name)
    {
        $this->checkWritable($name);
        unset($this->vars[$name]);
        unset($this->lazy[$name]);
        $this->constants[$name] = false;
    }

    /**
     * Checks if a variable is constant
     *
     * @param string $name
     * @return boolean
     */
    public function isConstant($name)
    {
        return (!empty($this->constants[$name]));
    }

    /**
     * Checks if a variable has been loaded
     *
     * @param string $name
     * @return boolean
     */
    public function isLoaded($name)
    {
        return array_key_exists($name, $this->vars);
    }

    /**
     * Returns the list of all variables
     *
     * @param boolean $load [optional]
     *        FALSE - returns only loaded variables
     * @return array
     */
    public function getAllVars($load = true)
    {
        if ($load) {
            foreach (array_keys($this->lazy) as $k) {
                $this->get($k);
            }
        }
        return $this->vars;
    }

    /**
     * Marks a variable as constant
     *
     * @param string $name
     * @return boolean
     */
    public function markAsConstant($name)
    {
        if ($this->exists($name)) {
            $this->constants[$name] = true;
        }
    }

    /**
     * Switches the registry to read-only mode
     *
     * @return boolean
     *         switching occurred in a presently
     */
    public function toReadOnly()
    {
        if (!$this->readonly) {
            $this->readonly = true;
            return true;
        }
        return false;
    }

    /**
     * Checks if the registry mode is read-only
     *
     * @return boolean
     */
    public function isReadOnly()
    {
        return $this->readonly;
    }

    /**
     * {@inheritdoc}
     */
    public function __get($key)
    {
        return $this->get($key);
    }

    /**
     * {@inheritdoc}
     */
    public function __set($key, $value)
    {
        $this->set($key, $value);
    }

    /**
     * {@inheritdoc}
     */
    public function __isset($key)
    {
        return $this->exists($key);
    }

    /**
     * {@inheritdoc}
     */
    public function __unset($key)
    {
        return $this->remove($key);
    }

    /**
     * {@inheritdoc}
     */
    public function count()
    {
        return count($this->vars) + count($this->lazy);
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
        return new \ArrayIterator($this->getAllVars(true));
    }

    /**
     * @param string $name
     * @throws \axy\patterns\errors\ContainerReadOnly
     * @throws \axy\patterns\errors\PropertyReadOnly
     */
    private function checkWritable($name)
    {
        if ($this->readonly) {
            throw new ContainerReadOnly($this);
        }
        if (!empty($this->constants[$name])) {
            throw new PropertyReadOnly($this, $name);
        }
    }

    /**
     * @var array
     */
    private $vars;

    /**
     * @var array
     */
    private $lazy;

    /**
     * @var array
     */
    private $constants = [];

    /**
     * @var boolean
     */
    private $readonly;
}


text:
<?php
namespace SitemapGenerator;

interface PersistingInterface
{
    const SEPERATOR = '-';
    const XML_EXT = '.xml';
    const SCHEMA = 'http://www.sitemaps.org/schemas/sitemap/0.9';
    const SCHEMA_XHTML = 'http://www.w3.org/1999/xhtml';

    /**
     * @param string $fileToSave
     *
     * @return array
     */
    public function persist($fileToSave);
}


text:
NS_ASSUME_NONNULL_BEGIN

@protocol RCDQuicklySendManagerDelegate <NSObject>

- (void)quicklySendViewDidTapImage:(UIImage *)image;

@end

@interface RCDQuicklySendManager : NSObject

@property (nonatomic, weak) id<RCDQuicklySendManagerDelegate> delegate;

+ (RCDQuicklySendManager *)sharedManager;

- (void)showQuicklySendViewWithframe:(CGRect)frame;

- (void)hideQuicklySendView;

@end

NS_ASSUME_NONNULL_END


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class org.deidentifier.arx.metric.v2.QualityMetadata</title>
<meta name="date" content="2019-11-17">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.deidentifier.arx.metric.v2.QualityMetadata

Packages that use QualityMetadata

Package
Description

org.deidentifier.arx

This package provides the public API for the ARX anonymization framework.

org.deidentifier.arx.metric

Package providing access to quality models

Uses of QualityMetadata in org.deidentifier.arx

Methods in org.deidentifier.arx that return types with arguments of type QualityMetadata

Modifier and Type
Method and Description

java.util.List<QualityMetadata<?>>
ARXProcessStatistics.Step.getMetadata()

Returns the metadata associated with the result, if any

Uses of QualityMetadata in org.deidentifier.arx.metric

Methods in org.deidentifier.arx.metric that return types with arguments of type QualityMetadata

Modifier and Type
Method and Description

java.util.List<QualityMetadata<?>>
InformationLoss.getMetadata()

Adds new metadata

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#ifndef _HARDWARE_RESETS_H
#define _HARDWARE_RESETS_H

#include "pico.h"
#include "hardware/structs/resets.h"

/** \file hardware/resets.h
 *  \defgroup hardware_resets hardware_resets
 *
 * Hardware Reset API
 *
 * The reset controller allows software control of the resets to all of the peripherals that are not
 * critical to boot the processor in the RP2040.
 *
 * \subsubsection reset_bitmask
 * \addtogroup hardware_resets
 *
 * Multiple blocks are referred to using a bitmask as follows:
 *
 * Block to reset | Bit
 * ---------------|----
 * USB | 24
 * UART 1 | 23
 * UART 0 | 22
 * Timer | 21
 * TB Manager | 20
 * SysInfo | 19
 * System Config | 18
 * SPI 1 | 17
 * SPI 0 | 16
 * RTC | 15
 * PWM | 14
 * PLL USB | 13
 * PLL System | 12
 * PIO 1 | 11
 * PIO 0 | 10
 * Pads - QSPI | 9
 * Pads - bank 0 | 8
 * JTAG | 7
 * IO Bank 1 | 6
 * IO Bank 0 | 5
 * I2C 1 | 4
 * I2C 0 | 3
 * DMA | 2
 * Bus Control | 1
 * ADC 0 | 0
 *
 * \subsection reset_example Example
 * \addtogroup hardware_resets
 * \include hello_reset.c
 */

/// \tag::reset_funcs[]

/*! \brief Reset the specified HW blocks
 *  \ingroup hardware_resets
 *
 * \param bits Bit pattern indicating blocks to reset. See \ref reset_bitmask
 */
static inline void reset_block(uint32_t bits) {
    hw_set_bits(&resets_hw->reset, bits);
}

/*! \brief bring specified HW blocks out of reset
 *  \ingroup hardware_resets
 *
 * \param bits Bit pattern indicating blocks to unreset. See \ref reset_bitmask
 */
static inline void unreset_block(uint32_t bits) {
    hw_clear_bits(&resets_hw->reset, bits);
}

/*! \brief Bring specified HW blocks out of reset and wait for completion
 *  \ingroup hardware_resets
 *
 * \param bits Bit pattern indicating blocks to unreset. See \ref reset_bitmask
 */
static inline void unreset_block_wait(uint32_t bits) {
    hw_clear_bits(&resets_hw->reset, bits);
    while (~resets_hw->reset_done & bits)
        tight_loop_contents();
}
/// \end::reset_funcs[]

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<versions>
  <component name="NewModuleRootManager" version="1341459616344" />
</versions>