text:
const fileUploader = require('../managers/fileUploader');
const TreeFamily = require('../models/TreeFamily').Model;
const removeTreeFamilyFromId = require('../managers/treeFamilyRemover').removeFromId;
const trees = require('./trees');

module.exports.retrieveAvailableTrees = () => new Promise((fulfill, reject) => { // retrieve tree families
  const response = { trees: [] };

  console.log('testTreesLibrary controller:\tretrieveAvailableTrees()');
  TreeFamily.findAll().then((treeFamilies) => {
    treeFamilies.forEach((treeFamily) => {
      response.trees.push({ familyId: treeFamily._id, name: treeFamily.name });
    });
    fulfill(response);
  }).catch((error) => {
    reject({ message: error });
  });
});

module.exports.retrieveTreesFromFamilyId = (parameters) => new Promise((fulfill, reject) => { // retrieve tree family
  const response = { familyId: undefined, familyName: 'undefined', trees: [] };

  console.log('testTreesLibrary controller:\tretrieveTreesFromFamilyId()');
  console.log(parameters);
  if (parameters && parameters.id) {
    TreeFamily.findById(parameters.id).then((treeFamily) => {
      if (!treeFamily) {
        reject({ message: `Tree family id ${parameters.id} not found` });
      }
      response.familyId = treeFamily._id;
      response.familyName = treeFamily.name;
      if ('trees' in treeFamily) {
        treeFamily.trees.forEach((tree) => {
          response.trees.push({ id: tree._id, name: tree.name, version: tree.version });
        });
      }
      fulfill(response);
    }).catch((error) => {
      reject({ message: error });
    });
  } else {
    reject({ error: 'invalid input parameters' });
  }
});

module.exports.deleteTreesFromFamilyId = (parameters) => new Promise((fulfill, reject) => { // delete tree family
  console.log('testTreesLibrary controller:\tdeleteTreesFromFamilyId()');
  console.log(parameters);
  if (parameters && 'familyId' in parameters) {
    // before removal we are supposed to check if a tree is used from the machines tests library
    // do this missing check right here
    removeTreeFamilyFromId(parameters.familyId).then(() => {
      fulfill();
    }).catch((error) => {
      console.log(error);
      reject({ message: error });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

module.exports.validateNewTreeFamilyName = (parameters) => new Promise((fulfill, reject) => { // create tree family (with initial tree)
  console.log('testTreesLibrary controller:\tvalidateNewTreeFamilyName()');
  console.log(parameters);
  if (parameters && 'name' in parameters && typeof parameters.name === 'string') {
    TreeFamily.findByName(parameters.name).then((treeFamily) => {
      if (treeFamily) {
        reject({ message: 'a tree family already exists with this name' });
      } else {
        fulfill({ message: 'this family name is free' });
      }
    }).catch(() => {
      reject({ message: 'internal server error' });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

module.exports.validateNewTreeData = (parameters) => new Promise((fulfill, reject) => { // validate creating tree family (with initial tree)
  console.log('testTreesLibrary controller:\tvalidateNewTreeData()');
  console.log(parameters);
  if (parameters && 'clientId' in parameters) {
    fileUploader.getLastUploadFromClientId(parameters.clientId).then((file) => {
      trees.validate(file.pathName, false).then(() => {
        fulfill({ message: `'${file.name}': success` });
      }).catch((error) => {
        console.log(error);
        reject({ message: `'${file.name}': ${error}` });
      });
    }).catch((error) => {
      reject({ message: error });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

function createNewTreeFamily(inputFile, familyName) {
  return new Promise((fulfill, reject) => {
    trees.validate(inputFile).then((rawTree) => {
      const family = new TreeFamily();
      rawTree.version = ('version' in rawTree ? rawTree.version : 1);
      rawTree.familyId = family._id;
      trees.save(rawTree).then((treeObject) => {
        family.name = familyName;
        family.trees.push(treeObject.tree);
        family.references.push([]);
        family.save().then(() => {
          fulfill();
        }).catch((error) => {
          reject({ message: error });
        });
      }).catch((error) => {
        console.log(error);
        reject({ message: error });
      });
    }).catch((error) => {
      console.log(error);
      reject({ message: error });
    });
  });
}

module.exports.processNewTreeSubmission = (parameters) => new Promise((fulfill, reject) => { // create tree family (with initial tree)
  console.log('testTreesLibrary controller:\tprocessNewTreeSubmission()');
  console.log(parameters);
  if (parameters && 'clientId' in parameters && 'familyName' in parameters && typeof parameters.familyName === 'string') {
    fileUploader.getLastUploadFromClientId(parameters.clientId).then((file) => {
      createNewTreeFamily(file.pathName, parameters.familyName).then(() => {
        fulfill();
      }).catch((error) => {
        reject(error);
      });
    }).catch((error) => {
      reject({ message: error });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

module.exports.validateNewTreeVersionData = (parameters) => new Promise((fulfill, reject) => { // validate adding tree to existing family
  console.log('testTreesLibrary controller:\tvalidateNewTreeVersionData()');
  console.log(parameters);
  if (parameters && 'clientId' in parameters && 'familyId' in parameters && typeof parameters.familyId === 'string') {
    fileUploader.getLastUploadFromClientId(parameters.clientId).then((file) => {
      trees.validate(file.pathName, true).then(() => {
        fulfill({ message: `'${file.name}': success` });
      }).catch((error) => {
        console.log(error);
        reject({ message: `'${file.name}': ${error}` });
      });
    }).catch((error) => {
      console.log(error);
      reject({ message: error });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

function addTreeToFamily(inputFile, familyId) {
  return new Promise((fulfill, reject) => {
    TreeFamily.findById(familyId).then((family) => {
      trees.validate(inputFile, true).then((rawTree) => {
        rawTree.version = ('version' in rawTree ? rawTree.version : family.trees[family.trees.length - 1].version + 1);
        rawTree.familyId = family._id;
        trees.save(rawTree).then((treeObject) => {
          family.trees.push(treeObject.tree);
          family.references.push(treeObject.references);
          family.save().then(() => {
            fulfill(family);
          }).catch((error) => {
            console.log(error);
            reject({ message: error });
          });
        }).catch((error) => {
          console.log(error);
          reject({ message: error });
        });
      }).catch((error) => {
        console.log(error);
        reject({ message: error });
      });
    }).catch(() => {
      reject({ message: 'tree family not found' });
    });
  });
}

module.exports.processNewTreeVersionSubmission = (parameters) => new Promise((fulfill, reject) => { // add tree to existing family
  console.log('testTreesLibrary controller:\tprocessNewTreeVersionSubmission()');
  console.log(parameters);
  if (parameters && 'clientId' in parameters && 'familyId' in parameters && typeof parameters.familyId === 'string') {
    fileUploader.getLastUploadFromClientId(parameters.clientId).then((file) => {
      addTreeToFamily(file.pathName, parameters.familyId).then((family) => {
        fulfill({ familyId: family._id });
      }).catch((error) => {
        reject(error);
      });
    }).catch((error) => {
      reject({ message: error });
    });
  } else {
    reject({ message: 'invalid input parameters' });
  }
});

module.exports.onFileUploadSuccess = fileUploader.onSaved;

module.exports.onFileUploadFailure = fileUploader.onError;


text:
Client library for micropython and python for https://zentropi.com

## Installation for users

**Micropython:**

```bash
$ micropython -m upip install micropython-uzentropi
```
 **Python**:

 ```bash
$ pip install -U uzentropi
```

## Installation for library developers

**Micropython:**

```bash
# run in project directory

$ bin/install_micropython.sh
```
 **Python**:

 ```bash
# run in project directory

$ bin/install_python.sh
```

## Testing

**Micropython:**

```bash
# run in project directory

$ bin/install_dev.sh  # run once

$ bin/test_micropython.sh
```

**Python:**

```bash
# run in project directory

$ bin/install_dev.sh  # run once

$ bin/test_python.sh
```

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.search.aggregations.bucket.nested;

import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.FixedBitSet;
import org.elasticsearch.common.lucene.ReaderContextAware;
import org.elasticsearch.common.lucene.docset.DocIdSets;
import org.elasticsearch.index.cache.fixedbitset.FixedBitSetFilter;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.search.nested.NonNestedDocsFilter;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.SingleBucketAggregator;
import org.elasticsearch.search.aggregations.support.AggregationContext;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Map;

/**
 *
 */
public class NestedAggregator extends SingleBucketAggregator implements ReaderContextAware {

    private final String nestedPath;
    private final Aggregator parentAggregator;
    private FixedBitSetFilter parentFilter;
    private final FixedBitSetFilter childFilter;

    private Bits childDocs;
    private FixedBitSet parentDocs;

    public NestedAggregator(String name, AggregatorFactories factories, String nestedPath, AggregationContext aggregationContext, Aggregator parentAggregator, Map<String, Object> metaData) {
        super(name, factories, aggregationContext, parentAggregator, metaData);
        this.nestedPath = nestedPath;
        this.parentAggregator = parentAggregator;
        MapperService.SmartNameObjectMapper mapper = aggregationContext.searchContext().smartNameObjectMapper(nestedPath);
        if (mapper == null) {
            throw new AggregationExecutionException("[nested] nested path [" + nestedPath + "] not found");
        }
        ObjectMapper objectMapper = mapper.mapper();
        if (objectMapper == null) {
            throw new AggregationExecutionException("[nested] nested path [" + nestedPath + "] not found");
        }
        if (!objectMapper.nested().isNested()) {
            throw new AggregationExecutionException("[nested] nested path [" + nestedPath + "] is not nested");
        }

        childFilter = aggregationContext.searchContext().fixedBitSetFilterCache().getFixedBitSetFilter(objectMapper.nestedTypeFilter());
    }

    @Override
    public void setNextReader(AtomicReaderContext reader) {
        if (parentFilter == null) {
            // The aggs are instantiated in reverse, first the most inner nested aggs and lastly the top level aggs
            // So at the time a nested 'nested' aggs is parsed its closest parent nested aggs hasn't been constructed.
            // So the trick to set at the last moment just before needed and we can use its child filter as the
            // parent filter.
            Filter parentFilterNotCached = findClosestNestedPath(parentAggregator);
            if (parentFilterNotCached == null) {
                parentFilterNotCached = NonNestedDocsFilter.INSTANCE;
            }
            parentFilter = SearchContext.current().fixedBitSetFilterCache().getFixedBitSetFilter(parentFilterNotCached);
        }

        try {
            DocIdSet docIdSet = parentFilter.getDocIdSet(reader, null);
            // In ES if parent is deleted, then also the children are deleted. Therefore acceptedDocs can also null here.
            childDocs = DocIdSets.toSafeBits(reader.reader(), childFilter.getDocIdSet(reader, null));
            if (DocIdSets.isEmpty(docIdSet)) {
                parentDocs = null;
            } else {
                parentDocs = (FixedBitSet) docIdSet;
            }
        } catch (IOException ioe) {
            throw new AggregationExecutionException("Failed to aggregate [" + name + "]", ioe);
        }
    }

    @Override
    public void collect(int parentDoc, long bucketOrd) throws IOException {
        // here we translate the parent doc to a list of its nested docs, and then call super.collect for evey one of them
        // so they'll be collected
        if (parentDoc == 0 || parentDocs == null) {
            return;
        }
        int prevParentDoc = parentDocs.prevSetBit(parentDoc - 1);
        int numChildren = 0;
        for (int childDocId = prevParentDoc + 1; childDocId < parentDoc; childDocId++) {
            if (childDocs.get(childDocId)) {
                ++numChildren;
                collectBucketNoCounts(childDocId, bucketOrd);
            }
        }
        incrementBucketDocCount(bucketOrd, numChildren);
    }

    @Override
    public InternalAggregation buildAggregation(long owningBucketOrdinal) {
        return new InternalNested(name, bucketDocCount(owningBucketOrdinal), bucketAggregations(owningBucketOrdinal), getMetaData());
    }

    @Override
    public InternalAggregation buildEmptyAggregation() {
        return new InternalNested(name, 0, buildEmptySubAggregations(), getMetaData());
    }

    public String getNestedPath() {
        return nestedPath;
    }

    private static Filter findClosestNestedPath(Aggregator parent) {
        for (; parent != null; parent = parent.parent()) {
            if (parent instanceof NestedAggregator) {
                return ((NestedAggregator) parent).childFilter;
            } else if (parent instanceof ReverseNestedAggregator) {
                return ((ReverseNestedAggregator) parent).getParentFilter();
            }
        }
        return null;
    }

    public static class Factory extends AggregatorFactory {

        private final String path;

        public Factory(String name, String path) {
            super(name, InternalNested.TYPE.name());
            this.path = path;
        }

        @Override
        public Aggregator createInternal(AggregationContext context, Aggregator parent, long expectedBucketsCount, Map<String, Object> metaData) {
            return new NestedAggregator(name, factories, path, context, parent, metaData);
        }
    }
}


text:
module EOL
  class AnonymousUser

    # Anonymous users are LANGUAGE-SPECIFIC.
    def initialize(lang)
      @lang = lang
    end

    # This ensures that a whole bunch of method calls will "just work" on anonymous users:
    def method_missing(method, *args, &block)
      known = defaults
      known.has_key?(method.to_sym) ? known[method.to_sym] : raise("Anonymous Users cannot #{method}")
    end

    # If this isn't defined, you end up with lots of "Object#id deprecated" errors.
    def id
      0
    end

    # This can actually be dynamic:
    def language
      @lang_object ||= @lang.is_a?(Language) ? @lang : Language.find_by_iso_639_1(@lang)
    end
    def language_id
      language.id
    end
    def language_abbr
      language.iso_639_1
    end

    # This actually does require a little logic, so can't be a default:
    # NOTE - returns self for convenience; objects can call things like #is_admin? on this object, but not on nil.
    def can_read?(object)
      object.respond_to?(:can_be_read_by?) ? object.can_be_read_by?(self) : false
    end

    def defaults
      @defaults ||=
        Rails.cache.fetch("anonymous/#{@lang}") do
          {:active => true, # Actually a bit torn about this one, but "inactive" means "waiting for email verify"...
          :agent => nil,
          :agreed_with_terms => false,
          :all_collections => [],
          :assistant_curator? => false,
          :blank? => true,
          :can? => false,
          :can_create? => false,
          :can_delete? => false,
          :can_edit_collection? => false,
          :can_manage_community? => false,
          :can_update? => false,
          :content_page_cache_str => 'anonymous',
          :credentials => '',
          :curator_scope => '',
          :default_language? => true,
          :email => '',
          :full_name => I18n.t(:anonymous_user_full_name),
          :given_name => I18n.t(:anonymous_user_given_name),
          :ignored_data_object? => false,
          :is_admin? => false,
          :is_curator? => false,
          :log_activity => nil,
          :logo_url => nil,
          :member_of => false,
          :members => [],
          :min_curator_level? => false,
          :nil? => true,
          :rating_for_object_guids => nil,
          :save => false,
          :short_name => I18n.t(:anonymous_user_given_name),
          :tag_line => I18n.t(:anonymous_user_tag_line),
          :username => I18n.t(:anonymous_user_given_name),
          :vetted => false,
          :visibility_types => ['visible'],
          :vetted_types => ['trusted', 'unreviewed'],
          :news_in_preferred_language => false,
          :watch_collection => nil}
        end
    end

  end
end


text:
function [d imFnames]=walls2()
full_fname = 'walls2.mat';
fname = '/media/blandry/LinuxData/crazyflie-tools/logs/cf2/tests0506/withobs/walls2.mat';
if (exist(full_fname,'file'))
    filename = full_fname;
else
    filename = fname;
end
d = load(filename);


text:
![Tests](https://github.com/phootwork/phootwork/workflows/Tests/badge.svg)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/phootwork/phootwork/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/phootwork/phootwork/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/phootwork/phootwork/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/phootwork/phootwork/?branch=master)
[![License](https://img.shields.io/github/license/phootwork/lang.svg?style=flat-square)](https://packagist.org/packages/phootwork/lang)
[![Latest Stable Version](https://img.shields.io/packagist/v/phootwork/lang.svg?style=flat-square)](https://packagist.org/packages/phootwork/lang)
[![Total Downloads](https://img.shields.io/packagist/dt/phootwork/lang.svg?style=flat-square&colorB=007ec6)](https://packagist.org/packages/phootwork/lang)

Missing PHP language constructs

## Goals

- Provide common but missing php classes
- Objects for native php constructs
- Consistent API
- Inspired by `java.lang`, `java.util`, `String.prototype`, `Array.prototype` and [`Stringy`](https://github.com/danielstjules/Stringy)

## Installation

Installation via composer:

```
composer require phootwork/lang
```

## Documentation

[https://phootwork.github.io/lang](https://phootwork.github.io/lang)

## Running tests

This package is a part of the Phootwork library. In order to run the test suite, you have to download the full library.

```
git clone https://github.com/phootwork/phootwork
```
Then install the dependencies via composer:

```
composer install
```
Now, run the *lang* test suite:

```
vendor/bin/phpunit --testsuite lang
```
If you want to run the whole library tests, simply run:

```
vendor/bin/phpunit
```

## Contact

Report issues at the github [Issue Tracker](https://github.com/phootwork/phootwork/issues).

## Changelog

Refer to [Releases](https://github.com/phootwork/phootwork/releases)


text:
package gov.nasa.jpl.mbee.mdk.emf;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.nomagic.magicdraw.core.Project;
import com.nomagic.magicdraw.openapi.uml.ReadOnlyElementException;
import com.nomagic.magicdraw.openapi.uml.SessionManager;
import com.nomagic.magicdraw.uml.transaction.RepositoryModelValidator;
import com.nomagic.task.ProgressStatus;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element;
import com.nomagic.uml2.transaction.ModelValidationResult;
import gov.nasa.jpl.mbee.mdk.api.incubating.MDKConstants;
import gov.nasa.jpl.mbee.mdk.api.incubating.annotations.SessionManaged;
import gov.nasa.jpl.mbee.mdk.api.incubating.convert.Converters;
import gov.nasa.jpl.mbee.mdk.api.incubating.convert.JsonToElementFunction;
import gov.nasa.jpl.mbee.mdk.json.ImportException;
import gov.nasa.jpl.mbee.mdk.mms.json.JsonEquivalencePredicate;
import gov.nasa.jpl.mbee.mdk.util.Changelog;
import gov.nasa.jpl.mbee.mdk.util.MDUtils;
import gov.nasa.jpl.mbee.mdk.util.Pair;
import org.eclipse.emf.common.util.TreeIterator;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;

import java.text.NumberFormat;
import java.util.*;
import java.util.function.BiFunction;

/**
 * Created by igomes on 9/28/16.
 */
// TODO What about locks? @donbot
public class EMFBulkImporter implements BulkImportFunction {
    private final String sessionName;
    private int sessionCount;

    private Changelog<String, Pair<Element, ObjectNode>> changelog;
    private Map<Pair<Element, ObjectNode>, Exception> failedElementMap;
    private Map<Element, ObjectNode> nonEquivalentElements;
    private Map<String, Element> elementCache;

    private final BiFunction<String, Project, Element> bulkIdToElementConverter = (id, project) -> {
        Element element = Converters.getIdToElementConverter().apply(id, project);
        if (MDUtils.isDeveloperMode()) {
            System.out.println("[NO CACHE] " + id + " -> " + element);
        }
        if (element == null && elementCache != null) {
            element = elementCache.get(id);
            if (MDUtils.isDeveloperMode()) {
                System.out.println("[CACHE] " + id + " -> " + element);
            }
        }
        return element;
    };

    public EMFBulkImporter(String sessionName) {
        this.sessionName = sessionName;
    }

    @SessionManaged
    @Override
    public Changelog<String, Pair<Element, ObjectNode>> apply(Collection<ObjectNode> objectNodes, Project project, ProgressStatus progressStatus) {
        String initialProgressStatusDescription = null;
        long initialProgressStatusCurrent = 0;
        boolean initialProgressStatusIndeterminate = false;
        RepositoryModelValidator validator = new RepositoryModelValidator(project);

        if (progressStatus != null) {
            initialProgressStatusDescription = progressStatus.getDescription();
            initialProgressStatusCurrent = progressStatus.getCurrent();
            initialProgressStatusIndeterminate = progressStatus.isIndeterminate();

            progressStatus.setMax(objectNodes.size() * 3);
            progressStatus.setCurrent(0);
        }

        project.getModels().forEach(EMFBulkImporter::preloadRecursively);

        try {
            objectNodes = new ArrayList<>(objectNodes);
            failedElementMap = new LinkedHashMap<>(objectNodes.size());
            nonEquivalentElements = new LinkedHashMap<>();
            Map<Element, Changelog.ChangeType> changeTypeMap = new HashMap<>(objectNodes.size());

            JsonToElementFunction jsonToElementFunction = new EMFImporter() {
                @Override
                protected List<EStructuralFeatureOverride> getEStructuralFeatureOverrides() {
                    if (eStructuralFeatureOverrides == null) {
                        eStructuralFeatureOverrides = new ArrayList<>(super.getEStructuralFeatureOverrides());
                        eStructuralFeatureOverrides.remove(EStructuralFeatureOverride.OWNER);
                        eStructuralFeatureOverrides.add(EStructuralFeatureOverride.getOwnerEStructuralFeatureOverride(bulkIdToElementConverter));
                    }
                    return eStructuralFeatureOverrides;
                }

                @Override
                protected List<PreProcessor> getPreProcessors() {
                    if (preProcessors == null) {
                        preProcessors = new ArrayList<>(super.getPreProcessors());
                        preProcessors.remove(PreProcessor.CREATE);
                        preProcessors.add(0, PreProcessor.getCreatePreProcessor(bulkIdToElementConverter));
                    }
                    return preProcessors;
                }

                @Override
                protected BiFunction<String, Project, Element> getIdToElementConverter() {
                    return bulkIdToElementConverter;
                }
            };

            bulkImport:
            while (/*failedElementMap.isEmpty() && */!objectNodes.isEmpty()) {
                changelog = new Changelog<>();
                elementCache = new HashMap<>();

                List<ObjectNode> retryObjectNodes = new ArrayList<>();

                if (SessionManager.getInstance().isSessionCreated(project)) {
                    SessionManager.getInstance().cancelSession(project);
                }
                SessionManager.getInstance().createSession(project, sessionName + " x" + objectNodes.size() + " #" + ++sessionCount);
                if (progressStatus != null) {
                    progressStatus.setDescription(sessionName + " - " + NumberFormat.getInstance().format(objectNodes.size()) + " elements" + (!failedElementMap.isEmpty() ? " - " + NumberFormat.getInstance().format(failedElementMap.size()) + " failed" : ""));
                    progressStatus.setCurrent(progressStatus.getMax() - objectNodes.size() * 3);
                }

                Iterator<ObjectNode> iterator = objectNodes.iterator();
                while (iterator.hasNext()) {
                    ObjectNode objectNode = iterator.next();
                    JsonNode sysmlIdJsonNode = objectNode.get(MDKConstants.ID_KEY);
                    String sysmlId = sysmlIdJsonNode != null && sysmlIdJsonNode.isTextual() ? sysmlIdJsonNode.asText() : null;
                    if (MDUtils.isDeveloperMode()) {
                        System.out.println("[ATTEMPT 1] Attempting " + sysmlId);
                    }
                    Changelog.Change<Element> change = null;
                    try {
                        change = jsonToElementFunction.apply(objectNode, project, false);
                    } catch (ImportException | ReadOnlyElementException ignored) {
                    }
                    if (change == null || change.getChanged() == null) {
                        if (MDUtils.isDeveloperMode()) {
                            System.err.println("[FAILED 1] Could not create " + sysmlId);
                        }
                        // Element may fail to create on first pass, ex: Diagram (because owner doesn't exist yet + custom creation), so we need to retry after everything else.
                        retryObjectNodes.add(objectNode);
                        //failedElementMap.put(new Pair<>(Converters.getIdToElementConverter().apply(objectNode.get(MDKConstants.ID_KEY).asText(), project), objectNode), importException);
                        //iterator.remove();
                        //continue bulkImport;
                    }
                    else {
                        if (MDUtils.isDeveloperMode()) {
                            System.out.println("[SUCCESS 1] Imported " + sysmlId);
                        }
                        if (sysmlId != null) {
                            elementCache.put(sysmlId, change.getChanged());
                        }
                        changeTypeMap.put(change.getChanged(), change.getType());
                    }

                    //changelog.addChange(Converters.getElementToIdConverter().apply(change.getChanged()), new Pair<>(change.getChanged(), objectNode), change.getType());
                    if (progressStatus != null) {
                        progressStatus.increase();
                    }
                }

                for (ObjectNode objectNode : retryObjectNodes) {
                    JsonNode sysmlIdJsonNode = objectNode.get(MDKConstants.ID_KEY);
                    String sysmlId = sysmlIdJsonNode != null && sysmlIdJsonNode.isTextual() ? sysmlIdJsonNode.asText() : null;
                    if (MDUtils.isDeveloperMode()) {
                        System.out.println("[ATTEMPT 1.5] Attempting " + sysmlId);
                    }
                    Changelog.Change<Element> change = null;
                    Exception exception = new ImportException(null, objectNode, "Failed to create/update element.");
                    try {
                        change = jsonToElementFunction.apply(objectNode, project, false);
                    } catch (ImportException | ReadOnlyElementException e) {
                        exception = e;
                    }
                    if (change == null || change.getChanged() == null) {
                        if (MDUtils.isDeveloperMode()) {
                            System.err.println("[FAILED 1.5] Could not create " + sysmlId);
                        }
                        Element element = Converters.getIdToElementConverter().apply(sysmlId, project);
                        failedElementMap.put(new Pair<>(element != null && !element.isInvalid() && !project.isDisposed(element) ? element : null, objectNode), exception);
                        objectNodes.remove(objectNode);
                        continue bulkImport;
                    }
                    else {
                        if (MDUtils.isDeveloperMode()) {
                            System.out.println("[SUCCESS 1.5] Imported " + sysmlId);
                        }
                        if (sysmlId != null) {
                            elementCache.put(sysmlId, change.getChanged());
                        }
                        changeTypeMap.put(change.getChanged(), change.getType());
                    }
                }

                iterator = objectNodes.iterator();
                while (iterator.hasNext()) {
                    ObjectNode objectNode = iterator.next();
                    JsonNode sysmlIdJsonNode = objectNode.get(MDKConstants.ID_KEY);
                    String sysmlId = sysmlIdJsonNode != null && sysmlIdJsonNode.isTextual() ? sysmlIdJsonNode.asText() : "<>";
                    if (MDUtils.isDeveloperMode()) {
                        System.out.println("[ATTEMPT 2] Attempting " + sysmlId);
                    }
                    Changelog.Change<Element> change = null;
                    Exception exception = new ImportException(null, objectNode, "Failed to create/update element with relationships.");
                    try {
                        change = jsonToElementFunction.apply(objectNode, project, true);
                    } catch (ImportException | ReadOnlyElementException e) {
                        exception = e;
                    }
                    if (change == null || change.getChanged() == null) {
                        if (MDUtils.isDeveloperMode()) {
                            System.err.println("[FAILED 2] Could not import " + sysmlId);
                        }
                        Element element = Converters.getIdToElementConverter().apply(sysmlId, project);
                        failedElementMap.put(new Pair<>(element != null && !element.isInvalid() && !project.isDisposed(element) ? element : null, objectNode), exception);
                        iterator.remove();
                        continue bulkImport;
                    }
                    else {
                        if (MDUtils.isDeveloperMode()) {
                            System.out.println("[SUCCESS 2] Imported " + sysmlId);
                        }
                        if (sysmlId != null) {
                            elementCache.put(sysmlId, change.getChanged());
                        }
                        Changelog.ChangeType changeType = changeTypeMap.get(change.getChanged());
                        changelog.addChange(Converters.getElementToIdConverter().apply(change.getChanged()), new Pair<>(change.getChanged(), objectNode), changeType != null ? changeType : change.getType());
                    }

                    if (progressStatus != null) {
                        progressStatus.increase();
                    }
                }

                for (Changelog.ChangeType changeType : Changelog.ChangeType.values()) {
                    for (Map.Entry<String, Pair<Element, ObjectNode>> entry : changelog.get(changeType).entrySet()) {
                        Element element = entry.getValue().getKey();
                        ObjectNode objectNode = entry.getValue().getValue();

                        Collection<ModelValidationResult> results = validator.validateChanges(Collections.singleton(element));

                        if (results != null && !results.isEmpty()) {
                            ModelValidationResult result = results.iterator().next();
                            if (MDUtils.isDeveloperMode()) {
                                System.err.println("[FAILED 3] " + result.toString());
                            }
                            failedElementMap.put(new Pair<>(element != null && !element.isInvalid() && !project.isDisposed(element) ? element : null, objectNode), new ImportException(element, objectNode, "Element failed validation after importing. Reason: " + result.getReason()));
                            objectNodes.remove(objectNode);
                            continue bulkImport;
                        }

                        if (element.isInvalid()) {
                            if (MDUtils.isDeveloperMode()) {
                                JsonNode sysmlIdJsonNode = objectNode.get(MDKConstants.ID_KEY);
                                String sysmlId = sysmlIdJsonNode != null && sysmlIdJsonNode.isTextual() ? sysmlIdJsonNode.asText() : "<>";
                                System.err.println("[FAILED 4] Could not create " + sysmlId);
                            }
                            failedElementMap.put(new Pair<>(element != null && !element.isInvalid() && !project.isDisposed(element) ? element : null, objectNode), new ImportException(element, objectNode, "Element was found to be invalid after importing."));
                            objectNodes.remove(objectNode);
                            continue bulkImport;
                        }
                        ObjectNode sourceObjectNode = Converters.getElementToJsonConverter().apply(element, project);
                        if (!JsonEquivalencePredicate.getInstance().test(sourceObjectNode, objectNode)) {
                            // currently handled as a warning instead of an error
                            nonEquivalentElements.put(element, objectNode);
                        }

                        if (progressStatus != null) {
                            progressStatus.increase();
                        }
                    }
                }
                break;
            }
        } finally {
            try {
                if (failedElementMap.isEmpty()) {
                    onSuccess();
                }
                else {
                    onFailure();
                }
                if (SessionManager.getInstance().isSessionCreated(project)) {
                    SessionManager.getInstance().closeSession(project);
                }

                if (progressStatus != null) {
                    progressStatus.setDescription(initialProgressStatusDescription);
                    progressStatus.setCurrent(initialProgressStatusCurrent);
                    progressStatus.setIndeterminate(initialProgressStatusIndeterminate);
                }
            } finally {
                if (SessionManager.getInstance().isSessionCreated(project)) {
                    SessionManager.getInstance().cancelSession(project);
                }
            }
        }
        return (changelog == null ? new Changelog<>() : changelog);
    }

    private static void preloadRecursively(EObject eObject) {
        for (final TreeIterator<Object> allProperContents = EcoreUtil.getAllProperContents(eObject, true); allProperContents.hasNext(); allProperContents.next()) {
            // just iterate to load contents
        }
    }

    public void onSuccess() {
    }

    public void onFailure() {
    }

    public String getSessionName() {
        return sessionName;
    }

    public int getSessionCount() {
        return sessionCount;
    }

    public Changelog<String, Pair<Element, ObjectNode>> getChangelog() {
        return changelog;
    }

    public Map<Pair<Element, ObjectNode>, Exception> getFailedElementMap() {
        return failedElementMap;
    }

    public Map<Element, ObjectNode> getNonEquivalentElements() {
        return nonEquivalentElements;
    }
}


text:
package org.javamoney.moneta.spi.loader;

import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

class LoadRemoteDataLoaderService {

	private static final Logger LOG = Logger.getLogger(DefaultLoaderListener.class.getName());

	private final DefaultLoaderListener listener;

	LoadRemoteDataLoaderService(DefaultLoaderListener listener) {
		this.listener = listener;
	}

	public boolean execute(String resourceId,
			Map<String, LoadableResource> resources) {

		LoadableResource load = resources.get(resourceId);
		if (load!=null) {
			try {
				load.readCache();
				listener.trigger(resourceId, load.getDataStream());
				load.loadRemote();
				listener.trigger(resourceId, load.getDataStream());
				LOG.log(Level.INFO, "The exchange rate with resourceId %s was started remotely", resourceId);
				return true;
			} catch (Exception e) {
				LOG.log(Level.SEVERE, "Failed to load resource: " + resourceId,
						e);
			}
		} else {
			throw new IllegalArgumentException("No such resource: "
					+ resourceId);
		}
		return false;
	}

	@Override
	public String toString() {
		return LoadRemoteDataLoaderService.class.getName() + '{' + " listener: " + listener + '}';
	}
}


text:
NinjectConstructorInjectionWeb
==============================

How to Constructor Dependency Injection(Ninject)


text:
package com.winsun.fruitmix.util;

/**
 * Created by Administrator on 2016/9/18.
 */
public enum OperationResult {

    LOCAL_MEDIASHARE_UPLOADING,SUCCEED,NO_NETWORK,FAIL

}


text:
A script for converting images to different sizes inline, with support for server caching.

Very useful for creating multiple sizes of image urls from single images. Creates a thumbnail image depending on variables passed to it via get.

Images are cached on the server, so server processing overhead is only needed for the first time the script runs on a particular image.

###Usage:

     - to size the thumbnail  to fit a square

     - to  size the thumbnail to fit a rectangle

     -  to set a thumbnails quality
Where:

FILE = the file to retrieve
SIZE = the maximum size of the thumbnail in pixels
SIZEX = the maximum width of the thumbnail (height adjusted accordingly)
SIZEY = the maximum height of the thumbnail (width adjusted accordingly)
QUALITY = an integer from 0-100 specifying the resulting jpeg quality of the image
NOCACHE = an integer 1 or 0. If set to 1, the cached thumbnail is deleted and recreated (use if the source image changes)
###Features:

* Server caching of images
* Creation of jpeg thumbnails inline, on the fly
* Can be used for non-local images, if allow_fopen_url in the php configuration is set to true

###Requires:

GD Library

Installation:

The script should work with GD versions 1 and 2, and Linux and Windows servers

Licensed under the MIT License.
Copyright © 2005 Chris Tomlinson.

###Version Changes:

Changes:

0.1 – first release

0.2 – converted cache thumbnail from png to jpeg

0.3 – fixed error where files weren't being cached properly

0.4 – allowed non local urls (if allow_url_fopen is on), quality and nocache switches

0.5 – allowed maximum x and y settings (for scaling images to fit non square sizes)

0.6 – allowed tagging of images (with the get query placing the text in the bottom left hand corner of the image)

0.7 – fixed gd_info error for php<4.3

0.8 – added gif support (for gd 2.0.28)

0.9 – now supports native outputting of png, jpg and gif formats

1.0 – doesn't fail if the cache file can't be created

1.1 – removed a few more notices


text:
"""
homeassistant.components.sensor.tellduslive
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Shows sensor values from Tellstick Net/Telstick Live.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.tellduslive/

"""
import logging
from datetime import datetime

from homeassistant.components import tellduslive
from homeassistant.const import (
    ATTR_BATTERY_LEVEL, DEVICE_DEFAULT_NAME, TEMP_CELCIUS)
from homeassistant.helpers.entity import Entity

ATTR_LAST_UPDATED = "time_last_updated"

_LOGGER = logging.getLogger(__name__)

SENSOR_TYPE_TEMP = "temp"
SENSOR_TYPE_HUMIDITY = "humidity"
SENSOR_TYPE_RAINRATE = "rrate"
SENSOR_TYPE_RAINTOTAL = "rtot"
SENSOR_TYPE_WINDDIRECTION = "wdir"
SENSOR_TYPE_WINDAVERAGE = "wavg"
SENSOR_TYPE_WINDGUST = "wgust"
SENSOR_TYPE_WATT = "watt"

SENSOR_TYPES = {
    SENSOR_TYPE_TEMP: ['Temperature', TEMP_CELCIUS, "mdi:thermometer"],
    SENSOR_TYPE_HUMIDITY: ['Humidity', '%', "mdi:water"],
    SENSOR_TYPE_RAINRATE: ['Rain rate', 'mm', "mdi:water"],
    SENSOR_TYPE_RAINTOTAL: ['Rain total', 'mm', "mdi:water"],
    SENSOR_TYPE_WINDDIRECTION: ['Wind direction', '', ""],
    SENSOR_TYPE_WINDAVERAGE: ['Wind average', 'm/s', ""],
    SENSOR_TYPE_WINDGUST: ['Wind gust', 'm/s', ""],
    SENSOR_TYPE_WATT: ['Watt', 'W', ""],
}

def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up Tellstick sensors. """
    if discovery_info is None:
        return
    add_devices(TelldusLiveSensor(sensor) for sensor in discovery_info)

class TelldusLiveSensor(Entity):
    """ Represents a Telldus Live sensor. """

    def __init__(self, sensor_id):
        self._id = sensor_id
        self.update()
        _LOGGER.debug("created sensor %s", self)

    def update(self):
        """ update sensor values """
        tellduslive.NETWORK.update_sensors()
        self._sensor = tellduslive.NETWORK.get_sensor(self._id)

    @property
    def _sensor_name(self):
        return self._sensor["name"]

    @property
    def _sensor_value(self):
        return self._sensor["data"]["value"]

    @property
    def _sensor_type(self):
        return self._sensor["data"]["name"]

    @property
    def _battery_level(self):
        sensor_battery_level = self._sensor.get("battery")
        return round(sensor_battery_level * 100 / 255) \
            if sensor_battery_level else None

    @property
    def _last_updated(self):
        sensor_last_updated = self._sensor.get("lastUpdated")
        return str(datetime.fromtimestamp(sensor_last_updated)) \
            if sensor_last_updated else None

    @property
    def _value_as_temperature(self):
        return round(float(self._sensor_value), 1)

    @property
    def _value_as_humidity(self):
        return int(round(float(self._sensor_value)))

    @property
    def name(self):
        """ Returns the name of the device. """
        return "{} {}".format(self._sensor_name or DEVICE_DEFAULT_NAME,
                              self.quantity_name)

    @property
    def available(self):
        return not self._sensor.get("offline", False)

    @property
    def state(self):
        """ Returns the state of the device. """
        if self._sensor_type == SENSOR_TYPE_TEMP:
            return self._value_as_temperature
        elif self._sensor_type == SENSOR_TYPE_HUMIDITY:
            return self._value_as_humidity

    @property
    def device_state_attributes(self):
        attrs = {}
        if self._battery_level is not None:
            attrs[ATTR_BATTERY_LEVEL] = self._battery_level
        if self._last_updated is not None:
            attrs[ATTR_LAST_UPDATED] = self._last_updated
        return attrs

    @property
    def quantity_name(self):
        """ name of quantity """
        return SENSOR_TYPES[self._sensor_type][0]

    @property
    def unit_of_measurement(self):
        return SENSOR_TYPES[self._sensor_type][1]

    @property
    def icon(self):
        return SENSOR_TYPES[self._sensor_type][2]


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Siddharth Gore  </title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                Siddharth Gore

                        Projects

                        About Me

                        Contact Me

                        Siddharth Gore

Web Developer - Java Developer

Software Engineering Graduate Student at San Jose State University

Projects

sidtoursandtravels.com

Food Corporation Of India

Banker's Algorithm in C++

Pet World

JAVA UML Parser

formationyadasid.com

About Me

I am a Software Engineering Graduate at San Jose State University. I have 3.5 Years Work Experience in IT industry.Before coming to SJSU ,I worked for the Government of India at Food Corporation Of India.Prior to That I worked as a JAVA Developer and Unit Tester at Accenture

Contact Me

(669)-254-6905

Location

190 Ryland Street

San Jose, CA 95110

Around the Web

Mail Siddharth

                        Copyright © Siddharth Gore 2017

sidtoursandtravels.com

A website created as a Personal Project for CMPE-272 Enterprise Software Platforms in Fall 16. The website is made in PHP and uses My Sql to mqueries to maintain database.Various features like cURL,Cookies and Session control  are implemented.

                                     Go to the Website

 :
                                     GitHub Link

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Depot-Online

 Food Corporation Of India

Depot Online System is a solution for managing the end to end operations of FCI Depots. The Key Objective of the Depot Online System is to align with 'Digital India' vision for transformation of food distribution supply chain in India. Powered by VIT DepoSoft™, it would facilitate process automation, standardization and efficiency of the management of food grain distribution and would enable real time monitoring of operations and timely data reporting.

Website:
                                    Food Corporation Of India

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Banker's Algorith For Deadlock Avoidance

C++ Project for CMPE 180-92 OOPS And Data Structures subject. Implemented Banker's Algorithm for Deadlock Avoidance by determining the state of the system.

 :
                                     GitHub Link

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Pet World

• Designed a Relational Database for storing information corresponding to a pet adoption organization. • Efficiently managed the database by normalizing it to third normal form thereby minimizing redundancies. • Built a web application in LAMP stack to manage the underlying database. • Optimized Data Retrieval by accounting for functional dependencies while designing the database. • Technologies Used: MySql, PHP

 :
                                     GitHub Link

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

JAVA UML-Parser

 :
                                     GitHub Link

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>

Formationyadasid.com

•    A cross domain Market Place Which CURLs data from websites of three different organizations developed as a part of project.
•   Implemented various functionalities of CMS, like user creations, user accessibility, collaboration with Social Media, session management.
Technologies used:  PHP, MySQL, HTML5, CSS3, Twitter Bootstrap, JQuery.

                                    Go to the Website

 :
                                     GitHub Link

                            <button type="button" class="btn btn-default" data-dismiss="modal"> Close</button>


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="soak">
        <note>
            Frames file for 'soak' based on sentences in financial subcorpus.
            Verbnet entries fill-9.8, wipe_manner-10.4.1, other_caus-45.4.
            Other framed members include spot, surround, trim; scour, squeeze;
            and a whole bunch of others.  No explicit comparison.
        </note>

        <roleset id="soak.01" name="cause to become very very wet">
            <roles>
                <role descr="causer" n="0"/>
                <role descr="thing getting wet" n="1"/>
            </roles>

            <example name="transitive">
                <inflection aspect="ns" form="gerund" person="ns" tense="ns" voice="ns"/>
                <text>
                    [A 10-gallon water cooler]-1 had toppled onto the floor, *trace*-1
                    soaking the red carpeting.
                </text>
                <arg n="0">*trace*</arg>
                <rel>soaking</rel>
                <arg n="1">the red carpeting</arg>
            </example>

            <example name="prepositional thing getting wet">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    The spilled milk slowly soaked into John's homework.
                </text>
                <arg n="0">The spilled milk</arg>
                <arg f="MNR" n="m">slowly</arg>
                <rel>soaked</rel>
                <arg n="1">into John's homework</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>

    <predicate lemma="soak_up">

        <roleset id="soak.02" name="absorb">
            <roles>
                <role descr="absorber, agent" n="0"/>
                <role descr="liquid" n="1"/>
                <role descr="instrument, if separate from agent" n="2"/>
            </roles>

            <example name="no instrument">
                <inflection aspect="ns" form="infinitive" person="ns" tense="ns" voice="ns"/>
                <text>
                    But the recent volatility in stock prices caused by the program
                    trading has made [some market makers]-1 less willing *trace*-1 to soak
                    up the stocks that are for sale.
                </text>
                <arg n="0">*trace*</arg>
                <rel>[ soak] [ up]</rel>
                <arg n="1">the stocks that are for sale</arg>
            </example>

            <example name="with instrument">
                <inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
                <text>
                    John soaked up the spilled milk with his linguistics homework.
                </text>
                <arg n="0">John</arg>
                <rel>soaked up</rel>
                <arg n="1">the spilled milk</arg>
                <arg n="2">with his linguistics homework</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>
</frameset>


text:
using Xunit;
using Shouldly;
using System.Text;
using System.Net.NetworkInformation;

namespace Google.Authenticator.Tests
{
    public class GeneratePinTests
    {
        [Fact]
        public void OverloadsReturnSamePIN()
        {
            var secret = "JBSWY3DPEHPK3PXP";
            var secretAsBytes = Encoding.UTF8.GetBytes(secret);
            var secretAsBase32 = Base32Encoding.ToString(secretAsBytes);
            long counter = 54615912;
            var expected = "508826";

            var subject = new TwoFactorAuthenticator();

            var pinFromString = subject.GeneratePINAtInterval(secret, counter);
            var pinFromBytes = subject.GeneratePINAtInterval(secretAsBytes, counter);
            var pinFromBase32 = subject.GeneratePINAtInterval(secretAsBase32, counter, secretIsBase32: true);

            pinFromString.ShouldBe(expected);
            pinFromBytes.ShouldBe(expected);
            pinFromBase32.ShouldBe(expected);
        }
    }
}

// private long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep) =>
            //(long) (now - epoch).TotalSeconds / timeStep;


text:
@interface AFCollectionViewCellSelectedView : UIView

@property (nonatomic, assign) BOOL selected;

@end

@implementation AFCollectionViewCell
{
    UILabel *nameLabel;
    UILabel *regionLabel;
    UIImageView *imageView;

    UIView *labelBackgroundView;
}

- (id)initWithFrame:(CGRect)frame
{
    if (!(self = [super initWithFrame:frame])) return nil;
    self.backgroundColor = [UIColor colorWithWhite:0.96f alpha:1.0f];

    AFCollectionViewCellSelectedView *selectedBackgroundView = [[AFCollectionViewCellSelectedView alloc] initWithFrame:CGRectZero];
    self.selectedBackgroundView = selectedBackgroundView;

//    self.backgroundView = [[AFCollectionViewCellSelectedView alloc] initWithFrame:CGRectZero];

    nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    nameLabel.backgroundColor = [UIColor clearColor];
    nameLabel.textColor = kTextColor;
    nameLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.contentView addSubview:nameLabel];

    regionLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    regionLabel.backgroundColor = [UIColor clearColor];
    regionLabel.textColor = kTextColor;
    regionLabel.font = [UIFont systemFontOfSize:17];
    [self.contentView addSubview:regionLabel];

    imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    imageView.backgroundColor = [UIColor blueColor];
    [self.contentView insertSubview:imageView belowSubview:nameLabel];

    labelBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    labelBackgroundView.backgroundColor = [UIColor colorWithWhite:1.0f alpha:0.7f];
    [self.contentView insertSubview:labelBackgroundView belowSubview:nameLabel];

    self.layer.masksToBounds = YES;
    self.layer.borderColor = [[UIColor whiteColor] CGColor];
    self.layer.borderWidth = 1.0f;
    self.layer.cornerRadius = 10.0f;

    return self;
}

-(void)prepareForReuse
{
    [super prepareForReuse];

    [self setName:@""];
    [self setImage:nil];
}

-(void)setName:(NSString *)name
{
    nameLabel.text = name;
}

-(void)setImage:(UIImage *)image
{
    if (!image)
    {
        imageView.image = [UIImage imageNamed:@"missing"];
    }
    else
    {
        imageView.image = image;
    }
}

-(void)setRegion:(NSString *)region
{
    regionLabel.text = region;
}

-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    if (![layoutAttributes isKindOfClass:[AFCollectionViewLayoutAttributes class]]) return;

    AFCollectionViewLayoutAttributes *castedLayoutAttributes = (AFCollectionViewLayoutAttributes *)layoutAttributes;

    const CGFloat inset = 0.0f;
    const CGFloat textMargin = 10.0f;

    if (castedLayoutAttributes.layoutMode == AFCollectionViewLayoutAttributesLayoutModeGrid)
    {
        imageView.frame = CGRectInset(self.contentView.bounds, inset, inset);
        labelBackgroundView.alpha = 1.0f;
        nameLabel.frame = CGRectInset(CGRectMake(textMargin, CGRectGetHeight(self.contentView.bounds) - 40, CGRectGetWidth(self.contentView.bounds) - 2.0f*textMargin, 40), inset, inset);
        regionLabel.frame = CGRectInset(CGRectMake(textMargin, CGRectGetHeight(self.contentView.bounds) - 40, CGRectGetWidth(self.contentView.bounds) - 2.0f*textMargin, 40), inset, inset);
        regionLabel.alpha = 0.0f;
        labelBackgroundView.frame = CGRectInset(CGRectMake(0, CGRectGetHeight(self.contentView.bounds) - 40, CGRectGetWidth(self.contentView.bounds), 40), inset, inset);
    }
    else if (castedLayoutAttributes.layoutMode == AFCollectionViewLayoutAttributesLayoutModeList)
    {
        imageView.frame = CGRectMake(inset, inset, CGRectGetHeight(self.contentView.bounds) - inset*2.0f, CGRectGetHeight(self.contentView.bounds) - inset*2.0f);

        if (regionLabel.text.length < 1)
        {
            nameLabel.frame = CGRectMake(CGRectGetHeight(self.contentView.bounds) + textMargin, 5.0f, CGRectGetWidth(self.contentView.bounds) - CGRectGetHeight(self.contentView.bounds) - 2.0f*textMargin, 88);
            regionLabel.frame = CGRectMake(CGRectGetHeight(self.contentView.bounds) + textMargin, 45, CGRectGetWidth(self.contentView.bounds) - CGRectGetHeight(self.contentView.bounds) - 2.0f*textMargin, 44);
        }
        else
        {
            nameLabel.frame = CGRectMake(CGRectGetHeight(self.contentView.bounds) + textMargin, 5.0f, CGRectGetWidth(self.contentView.bounds) - CGRectGetHeight(self.contentView.bounds) - 2.0f*textMargin, 44);
            regionLabel.frame = CGRectMake(CGRectGetHeight(self.contentView.bounds) + textMargin, 45, CGRectGetWidth(self.contentView.bounds) - CGRectGetHeight(self.contentView.bounds) - 2.0f*textMargin, 44);
        }

        regionLabel.alpha = 1.0f;
        labelBackgroundView.alpha = 0.0f;
        labelBackgroundView.frame = CGRectMake(CGRectGetHeight(self.contentView.bounds), inset, CGRectGetWidth(self.contentView.bounds) - CGRectGetHeight(self.contentView.bounds), CGRectGetHeight(self.contentView.bounds) - inset*2.0f);
    }
}

@end

@implementation AFCollectionViewCellSelectedView

-(void)drawRect:(CGRect)rect
{
    [super drawRect:rect];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);

    CGRect drawRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);

//    CGContextSetRGBFillColor(context, 3.0f/255.0f, 121.0f/255.0f, 239.0f/255.0f, self.selected ? 0.5f : 1.0f);
    CGContextSetRGBFillColor(context, 100.0f/255.0f, 140.0f/255.0f, 200.0f/255.0f, 1.0f);

    CGContextFillRect(context, drawRect);

    // Create a gradient from white to black
    CGFloat colors [] = {
        1.0, 1.0, 1.0, 0.3,
        0.0, 0.0, 0.0, 0.3
    };

    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, colors, NULL, 2);
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;

    CGContextSetBlendMode(context, kCGBlendModeOverlay);

    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient), gradient = NULL;

    CGContextRestoreGState(context);
}

@end


text:
package vg.civcraft.mc.citadel.events;

import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import vg.civcraft.mc.citadel.model.Reinforcement;

/**
 * Called when a new reinforcement is created
 *
 */
public class ReinforcementCreationEvent extends ReinforcementEvent {

	private static final HandlerList handlers = new HandlerList();

	public static HandlerList getHandlerList() {
		return handlers;
	}

	public ReinforcementCreationEvent(Player p, Reinforcement rein) {
		super(p, rein);
	}

	@Override
	public HandlerList getHandlers() {
		return handlers;
	}
}


text:
package io.searchbox.cluster.reroute;

import java.util.LinkedHashMap;
import java.util.Map;

public class RerouteAllocateReplica implements RerouteCommand {

    private final String index;
    private final int shard;
    private final String node;

    public RerouteAllocateReplica(String index, int shard, String node) {
        this.index = index;
        this.shard = shard;
        this.node = node;
    }

    @Override
    public String getType() {
        return "allocate_replica";
    }

    @Override
    public Map<String, Object> getData() {
        Map<String, Object> paramsMap = new LinkedHashMap<>();

        paramsMap.put("index", index);
        paramsMap.put("shard", shard);
        paramsMap.put("node", node);

        return paramsMap;
    }

}


text:
package com.bagri.tools.vvm.ui;

import javax.management.ObjectName;
import javax.swing.*;

import com.bagri.tools.vvm.event.*;
import com.bagri.tools.vvm.model.*;
import com.bagri.tools.vvm.service.ClusterManagementService;
import com.bagri.tools.vvm.service.ServiceException;
import com.bagri.tools.vvm.util.ErrorUtil;

import static com.bagri.tools.vvm.util.Icons.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.logging.Logger;

public class ClusterManagementPanel extends JPanel {
    private static final Logger LOGGER = Logger.getLogger(ClusterManagementPanel.class.getName());
    private final ClusterManagementService clusterService;
    private final EventBus eventBus;
    private JTabbedPane tabbedPane;
    private JToolBar toolBar;
    private XTable grid;

    public ClusterManagementPanel(ClusterManagementService clusterService, EventBus eventBus) {
        super(new GridLayout(1, 1));
        this.clusterService = clusterService;
        this.eventBus = eventBus;
        tabbedPane = new JTabbedPane();
        tabbedPane.addTab(ClusterManagement.CLUSTER_MANAGEMENT, createMainPanel());
        add(tabbedPane);
        tabbedPane.setBorder(BorderFactory.createEmptyBorder());
        setBorder(BorderFactory.createEmptyBorder());
    }

    private JPanel createMainPanel() {
        final JPanel panel = new JPanel(new BorderLayout());
        toolBar = new JToolBar();
        // "Add Node" button
        JButton addNode = new JButton("Add");
        addNode.setToolTipText("Adds new node");
        addNode.setIcon(ADD_ICON);
        addNode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onAdd();
            }
        });
        toolBar.add(addNode);
        toolBar.addSeparator();
        // "Edit Node" button
        JButton editNode = new JButton("Edit");
        editNode.setToolTipText("Edit selected node");
        editNode.setIcon(EDIT_ICON);
        editNode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onEdit();
            }
        });
        toolBar.add(editNode);
        toolBar.addSeparator();
        // "Delete Node" button
        JButton deleteNode = new JButton("Delete");
        deleteNode.setToolTipText("Delete selected node");
        deleteNode.setIcon(DELETE_ICON);
        deleteNode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                onDelete();
            }
        });
        toolBar.add(deleteNode);
        toolBar.addSeparator();
        toolBar.setFloatable(false);
        panel.add(toolBar, BorderLayout.PAGE_START);
        // Column configs
        ArrayList<ColumnConfig> configs = new ArrayList<ColumnConfig>();
        ColumnConfig c = new ColumnConfig();
        c.setHeader("Name");
        c.setColumnClass(String.class);
        c.setWidth(45);
        c.setResizable(true);
        configs.add(c);
        grid = new XTable(configs, new GridDataLoader() {
            @Override
            public java.util.List<GridRow> loadData() {
                java.util.List<Node> nodes;
                try {
                    nodes = clusterService.getNodes();
                } catch (ServiceException e) {
                    ErrorUtil.showError(ClusterManagementPanel.this, e);
                    return null;
                }
                java.util.List<GridRow> rows = new ArrayList<GridRow>();
                for (Node n : nodes) {
                    rows.add(new DefaultGridRow(n.getObjectName(), new Object[]{n.getName()}));
                }
                return rows;
            }
        });
        grid.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() >=2 ){
                    onEdit();
                }
            }
        });
        eventBus.addEventHandler(new EventHandler<ApplicationEvent>() {
            @Override
            public void handleEvent(ApplicationEvent e) {
                if (ClusterManagement.CLUSTER_STATE_CHANGED.equals(e.getCommand())) {
                    grid.reload();
                    invalidate();
                }
            }
        });
        panel.add(new JScrollPane(grid), BorderLayout.CENTER);
        return panel;
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (!enabled) {
            grid.clearSelection();
            grid.getTableHeader().setEnabled(false);
            grid.setEnabled(false);
            for (Component c : toolBar.getComponents()) {
                c.setEnabled(false);
            }
            toolBar.setEnabled(false);
            for (Component c : tabbedPane.getComponents()) {
                c.setEnabled(false);
            }
            tabbedPane.setEnabled(false);
        }
    }

    @Override
    public void invalidate() {
        super.invalidate();
        if (!grid.isLoaded()) {
            grid.reload();
        }
    }

    // --- Event Handlers --- //
    private void onAdd() {
        final EditNodeDialog dlg = new EditNodeDialog(null, ClusterManagementPanel.this);
        dlg.setSuccessListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            clusterService.addNode(dlg.getNode());
                        } catch (ServiceException e1) {
                            LOGGER.throwing(ClusterManagementPanel.class.getName(), "onAddNode", e1);
                            ErrorUtil.showError(ClusterManagementPanel.this, e1);
                        }
                        eventBus.fireEvent(new ApplicationEvent(dlg, ClusterManagement.CLUSTER_STATE_CHANGED));
                    }
                });
            }
        });
        dlg.setVisible(true);
    }

    private void onEdit() {
        int selectedIndex = grid.getSelectionModel().getLeadSelectionIndex();
        if (selectedIndex >= 0 && selectedIndex < grid.getModel().getRowCount()) {
            GridRow row = ((GridTableModel) grid.getModel()).getRow(selectedIndex);
            Node node;
            try {
                node = clusterService.getNode((ObjectName) row.getId());
            } catch (ServiceException e1) {
                LOGGER.throwing(ClusterManagementPanel.class.getName(), "onEditNode", e1);
                ErrorUtil.showError(ClusterManagementPanel.this, e1);
                return;
            }
            final EditNodeDialog dlg = new EditNodeDialog(node, ClusterManagementPanel.this);
            dlg.setSuccessListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                clusterService.saveNode(dlg.getNode());
                            } catch (ServiceException e1) {
                                LOGGER.throwing(ClusterManagementPanel.class.getName(), "onEditNode", e1);
                                ErrorUtil.showError(ClusterManagementPanel.this, e1);
                                return;
                            }
                            eventBus.fireEvent(new ApplicationEvent(dlg, ClusterManagement.CLUSTER_STATE_CHANGED));
                        }
                    });
                }
            });
            dlg.setVisible(true);
        }
    }

    private void onDelete() {
        int selectedIndex = grid.getSelectionModel().getLeadSelectionIndex();
        if (selectedIndex >= 0 && selectedIndex < grid.getModel().getRowCount()) {
            final GridRow row = ((GridTableModel) grid.getModel()).getRow(selectedIndex);
            int n = JOptionPane.showConfirmDialog(
                    ClusterManagementPanel.this,
                    "Are you sure you want to delete selected node \"" + row.getValueAt(0) + "\"?",
                    "Confirm deletion",
                    JOptionPane.YES_NO_OPTION);
            if (JOptionPane.YES_OPTION == n) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Node node = clusterService.getNode((ObjectName) row.getId());
                            clusterService.deleteNode(node);
                        } catch (ServiceException e1) {
                            LOGGER.throwing(ClusterManagementPanel.class.getName(), "onDeleteNode", e1);
                            ErrorUtil.showError(ClusterManagementPanel.this, e1);
                        }
                        eventBus.fireEvent(new ApplicationEvent(ClusterManagementPanel.this, ClusterManagement.CLUSTER_STATE_CHANGED));
                    }
                });
            }
        }
    }
}


text: node_modules\.bin\jake.cmd %*


text:
layout: post
title: "Post: Video (YouTube)"
categories:
  - Post Formats
tags:
  - Post Formats
last_modified_at: 2017-03-23T15:33:37-04:00
---

This post tests YouTube video embeds.

Simply wrap embeds with a `<div>` element and the appropriate classes:

```html
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>

<!-- 4:3 aspect ratio -->
<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="..."></iframe>
</div>
```


text:
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.

    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:[[ViewController alloc] init]];
    self.window.rootViewController = navigationController;

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

+ (NSString *)randomLoremIpsum {
    static int arrayCount = sizeof(loremIpsum) / sizeof(loremIpsum[0]);
    return loremIpsum[arc4random_uniform(arrayCount)];
}

@end


text:
var Utils = (function() {

  var DATABASE_PATH = 'db/database.csv';

  var coordinates = Object.freeze({
    LATITUDE: 'LAT',
    LONGITUDE: 'LON'
  });

  var unfilterableFields = Object.freeze([
    coordinates.LATITUDE, coordinates.LONGITUDE
  ]);

  var mSelectors = Object.freeze({
    navBar: {
      btnChangeFilters: '#btn-change-filters'
    },
    loading: '#loading',
    filtersModal: {
      main: '#filters-modal',
      filtersWrapper: '#filters',
      btnLoadMap: '#btn-modal-load',
      btnCancel: '#btn-modal-cancel',
      progressPanel: '#panel-progress'
    },
    filterPanel: {
      main: '#filters div.panel',
      bodies: '#filters .content-top > div.panel-body',
      title: '.panel-title a',
      heading: '.panel-heading',
      content: '.content-top',
      body: '.panel-body',
      select: 'select.main-select'
    },
    markerFields: {
      sel1: '#marker-select-1',
      sel2: '#marker-select-2'
    },
    legend: {
      main: '#legend',
      header: '#legend div.panel-heading',
      body: '#legend div.panel-body',
      itemIcon: 'img.legend-icon',
      expander: '#legend #expander'
    },
    errors: {
      panel: '#error-panel',
      message: '#error-message'
    }
  });

  var fnIsFilterable = function(fieldName) {
    return unfilterableFields.indexOf(fieldName) == -1;
  };

  var fnGetPercent = function(value, min, max) {
    if (!min && !max) return 0;
    if (!min) min = 0;
    if (!max) max = 0;
    if (!value) value = 0;

    if (min == max) return 0.2;

    if (min > max) {
      var aux = max;
      max = min;
      min = aux;
    }

    return (value - min) / (max - min);
  };

  var fnIterate2D = function(array2D, fn) {
    if (typeof fn != 'function') return;

    for (var oProp in array2D) {
      if (!array2D.hasOwnProperty(oProp)) continue;

      for (var iProp in array2D[oProp]) {
        if (!array2D[oProp].hasOwnProperty(iProp)) continue;

        if (fn(array2D[oProp][iProp], oProp, iProp) === false) return;
      }
    }
  };

  // list all properties of an object until nth level
  // obj.prop = level 0; obj.prop.prop = level 1; and so on
  var fnGetAllProps = function(obj, deepestLevel, currentLevel) {
    var props = [];
    if (!currentLevel) currentLevel = 0;

    for (var prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        props.push(prop);
        if (currentLevel < deepestLevel) {
          if (typeof obj[prop] == 'object')
            props = props.concat(fnGetAllProps(obj, deepestLevel, currentLevel + 1));
        }
      }
    }

    return props;
  };

  var fnMakeUniqueArray = function(array) {
    if (!Array.isArray(array)) return array;

    var uniqueArray = [];
    array.forEach(function(item) {
      if (uniqueArray.indexOf(item) == -1) uniqueArray.push(item);
    });
    return uniqueArray;
  }

  var fnIsNumberArray = function(array) {
    if (!array || !Array.isArray(array)) return false;

    var result = true;
    array.forEach(function(item) {
      if (!item || isNaN(item)) {
        result = false;
        return;
      }
    });
    return result;
  };

  var fnCompareNumbers = function(a, b) {
    // NaN controls
    if (isNaN(a) && isNaN(b)) return 0;
    if (isNaN(a)) return -1; // a comes first
    if (isNaN(b)) return  1; // b comes first

    // Number comparisons
    var numA = parseFloat(a), numB = parseFloat(b);
    if (numA == numB) return 0;
    return (numA < numB ? -1 : 1);
  };

  return {
    DATABASE_PATH: DATABASE_PATH,
    coordinates: coordinates,
    selectors: mSelectors,
    iterate2D: fnIterate2D,
    getAllProperties: fnGetAllProps,
    makeUniqueArray: fnMakeUniqueArray,
    isNumberArray: fnIsNumberArray,
    compareNumbers: fnCompareNumbers,
    getPercent: fnGetPercent,
    isFilterable: fnIsFilterable
  };

})();


text:
package org.kuali.rice.krad.data.provider.annotation;

import com.google.common.annotations.Beta;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Represents a property which should be inherited from another data object class.
 *
 *
Allows for the label to be overridden, but nothing else.

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InheritProperty {

    /**
     * Gets the name of the property to be inherited.
     *
     * @return the name of the property to be inherited.
     */
	String name();

    /**
     * Gets the label to override.
     *
     * @return the label to override.
     */
	Label label() default @Label("");

    /**
     * BETA: Gets the hints which can be passed through when auto-generating the input fields for an attribute.
     *
     * @return the hints which can be passed through when auto-generating the input fields for an attribute.
     */
    @Beta
	UifDisplayHints displayHints() default @UifDisplayHints(@UifDisplayHint(UifDisplayHintType.NONE));
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { Component, HostBinding, Inject, Input } from '@angular/core';
import { isBs3 } from '../utils/ng2-bootstrap-config';
import { AccordionComponent } from './accordion.component';
/*
 * ### Accordion heading

 Instead of using `heading` attribute on the `accordion-group`, you can use an `accordion-heading` attribute on `any` element inside of a group that will be used as group's header template.

 * */
var AccordionPanelComponent = (function () {
    function AccordionPanelComponent(accordion) {
        this.accordion = accordion;
    }
    Object.defineProperty(AccordionPanelComponent.prototype, "isOpen", {
        // Questionable, maybe .panel-open should be on child div.panel element?
        /** Is accordion group open or closed */
        get: function () {
            return this._isOpen;
        },
        set: function (value) {
            this._isOpen = value;
            if (value) {
                this.accordion.closeOtherPanels(this);
            }
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(AccordionPanelComponent.prototype, "isBs3", {
        get: function () {
            return isBs3();
        },
        enumerable: true,
        configurable: true
    });
    AccordionPanelComponent.prototype.ngOnInit = function () {
        this.panelClass = this.panelClass || 'panel-default';
        this.accordion.addGroup(this);
    };
    AccordionPanelComponent.prototype.ngOnDestroy = function () {
        this.accordion.removeGroup(this);
    };
    AccordionPanelComponent.prototype.toggleOpen = function (event) {
        if (!this.isDisabled) {
            this.isOpen = !this.isOpen;
        }
    };
    __decorate([
        Input(),
        __metadata("design:type", String)
    ], AccordionPanelComponent.prototype, "heading", void 0);
    __decorate([
        Input(),
        __metadata("design:type", String)
    ], AccordionPanelComponent.prototype, "panelClass", void 0);
    __decorate([
        Input(),
        __metadata("design:type", Boolean)
    ], AccordionPanelComponent.prototype, "isDisabled", void 0);
    __decorate([
        HostBinding('class.panel-open'),
        Input(),
        __metadata("design:type", Boolean),
        __metadata("design:paramtypes", [Boolean])
    ], AccordionPanelComponent.prototype, "isOpen", null);
    AccordionPanelComponent = __decorate([
        Component({
            selector: 'accordion-group, accordion-panel',
            template: "\n
\n
\n
\n
\n
{{heading}}
\n            <ng-content select=\"[accordion-heading]\"></ng-content>\n
\n
\n
\n
\n
\n          <ng-content></ng-content>\n
\n
\n
\n  ",
            host: {
                class: 'panel',
                style: 'display: block'
            }
        }),
        __param(0, Inject(AccordionComponent)),
        __metadata("design:paramtypes", [AccordionComponent])
    ], AccordionPanelComponent);
    return AccordionPanelComponent;
}());
export { AccordionPanelComponent };
//# sourceMappingURL=accordion-group.component.js.map


text:
const WebpackStripLoader = require('strip-loader');
const devConfig = require('./webpack.config.js');
const stripLoader = {
  test: [/\.js$/, /\.jsx/],
  exclude: /node_modules/,
  loader: WebpackStripLoader.loader('console.log')
};

devConfig.module.loaders.push(stripLoader);
module.exports = devConfig;


text:
Select a tab by setting active binding to true:

        <button type="button" class="btn btn-default btn-sm" ng-click="scope.active = 1">Select second tab</button>
        <button type="button" class="btn btn-default btn-sm" ng-click="scope.active = 2">Select third tab</button>

        <button type="button" class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable /
            Disable third tab
        </button>

    <uib-tabset active="active">
        <uib-tab index="0" heading="Static title">Static content</uib-tab>
        <uib-tab index="$index + 1" ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active"
                 disable="tab.disabled">
            {{tab.content}}
        </uib-tab>
        <uib-tab index="3" select="alertMe()">
            <uib-tab-heading>
                 Alert!
            </uib-tab-heading>
            I've got an HTML heading, and a select callback. Pretty cool!
        </uib-tab>
    </uib-tabset>

    <uib-tabset active="activePill" vertical="true" type="pills">
        <uib-tab index="0" heading="Vertical 1">Vertical content 1</uib-tab>
        <uib-tab index="1" heading="Vertical 2">Vertical content 2</uib-tab>
    </uib-tabset>

    <uib-tabset active="activeJustified" justified="true">
        <uib-tab index="0" heading="Justified">Justified content</uib-tab>
        <uib-tab index="1" heading="SJ">Short Labeled Justified content</uib-tab>
        <uib-tab index="2" heading="Long Justified">Long Labeled Justified content</uib-tab>
    </uib-tabset>

    Tabs using nested forms:
    <form name="outerForm" class="tab-form-demo">
        <uib-tabset active="activeForm">
            <uib-tab index="0" heading="Form Tab">
                <ng-form name="nestedForm">

                        Name
                        <input type="text" class="form-control" required ng-model="model.name"/>

                </ng-form>
            </uib-tab>
            <uib-tab index="1" heading="Tab One">
                Some Tab Content
            </uib-tab>
            <uib-tab index="2" heading="Tab Two">
                More Tab Content
            </uib-tab>
        </uib-tabset>
    </form>
    Model:

{{ model | json }}

    Nested Form:

{{ outerForm.nestedForm | json }}


text:
#pragma once

#include "si_base/gpu/gfx_config.h"

#if SI_USE_DX12
#include <d3d12.h>
#include <wrl/client.h>
#include <memory>
#include "si_base/gpu/gfx_enum.h"

struct IDXGISwapChain3;

namespace SI
{
	struct GfxTextureDesc;

	class BaseTexture
	{
		template<typename T> using ComPtr = Microsoft::WRL::ComPtr<T>;

	public:
		BaseTexture();
		~BaseTexture();

		int Initialize(ID3D12Device& device, const GfxTextureDesc& desc);

		int InitializeWICAndUpload(
			ID3D12Device& device,
			ID3D12CommandQueue& queue,
			const char* name,
			const void* buffer,
			size_t bufferSize);

		int InitializeAsSwapChainTexture(
			uint32_t width,
			uint32_t height,
			void* nativeSwapChain,
			uint32_t swapChainBufferId);

		int Terminate();

		uint32_t GetWidth() const
		{
			return m_width;
		}

		uint32_t GetHeight() const
		{
			return m_height;
		}

		uint32_t GetDepth() const
		{
			return m_depth;
		}

		GfxFormat GetFormat() const
		{
			return m_format;
		}

		uint32_t GetArraySize() const
		{
			return m_arraySize;
		}

		uint32_t GetMipLevels() const
		{
			return m_mipLevels;
		}

		void SetWidth(uint32_t w)
		{
			m_width = w;
		}

		void SetHeight(uint32_t h)
		{
			m_height = h;
		}

		void SetDepth(uint32_t d)
		{
			m_depth = d;
		}

		void SetFormat(GfxFormat f)
		{
			m_format = f;
		}

		void SetArraySize(uint32_t arraySize)
		{
			m_arraySize = arraySize;
		}

		void SetMipLevels(uint32_t mipLevels)
		{
			m_mipLevels = mipLevels;
		}

	public:
		ComPtr<ID3D12Resource>& GetComPtrResource()
		{
			return m_resource;
		}

		ID3D12Resource* GetNativeResource()
		{
			return m_resource.Get();
		}

	private:
		ComPtr<ID3D12Resource>            m_resource;
		uint32_t                          m_width  = 0;
		uint32_t                          m_height = 0;
		uint32_t                          m_depth  = 0;
		GfxFormat                         m_format = GfxFormat::Unknown;
		uint32_t                          m_arraySize = 0;
		uint32_t                          m_mipLevels = 0;
	};

} // namespace SI

#endif // SI_USE_DX12


text:
import axios from 'axios'
import store from '../store'
import route from '../router'
import {getVO} from './proto-vo.js'

function initData (obj) {
  let MessageVO = getVO('MessageVO')
  let ParamVO = getVO('ParamVO')

  var msg = new MessageVO()
  msg.phase = 1
  msg.action = obj.action
  var dat = new ParamVO()
  if (obj.data) {
    dat.strValues = obj.data.strValues ? obj.data.strValues : []
    dat.intValues = obj.data.intValues ? obj.data.intValues : []
    dat.longValues = obj.data.longValues ? obj.data.longValues : []
    dat.data = obj.data.data ? obj.data.data : []
  }
  msg.data = dat
  msg.token = store.getters.token
  msg.clientNumId = store.getters.clientNumId
  return msg
}

console.log('process.env.BASE_API', process.env.BASE_API)
var AX = axios.create({
  baseURL: process.env.BASE_API,
  url: '',
  timeout: 10000,
  method: 'post',
  responseType: 'arraybuffer',
  transformRequest: [data => {
    // 对 data 进行任意转换处理
    let msg = initData(data)
    console.log('ax send msg', msg)
    // 这里是自定的数据发送格式 [Uint8Array]
    let body = msg.toBuffer()
    let len = body.byteLength
    let dv = new DataView(new ArrayBuffer(len + 4))
    let bodyDv = new DataView(body)
    dv.setInt32(0, len, false)
    for (let i = 0; i < len; i++) {
      dv.setUint8(i + 4, bodyDv.getUint8(i))
    }
    return dv
  }],
  transformResponse: [data => {
    // 对 data 进行任意转换处理
    let MessageVO = getVO('MessageVO')

    let dv = new DataView(data)
    let len = dv.getInt32(0, false)
    let bodyDv = new DataView(new ArrayBuffer(len))
    for (let i = 0; i < len; i++) {
      bodyDv.setUint8(i, dv.getUint8(i + 4))
    }
    let dd = MessageVO.decode(bodyDv.buffer)
    console.log('ax resp msg', dd)
    return dd
  }]
})

// respone拦截器
AX.interceptors.response.use(
  response => {
    const res = response.data
    if (res.phase !== 2) {
      store.dispatch('FedLogOut').then(() => {
        route.push('/')
        return null
      })
    } else {
      return response
    }
  },
  error => {
    console.log('err' + error)
    return Promise.reject(error)
  }
)

export default AX


text:
<?php

namespace Minsal\GinecologiaBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * SrgCtlTipoReferenciaRetorno
 *
 * @ORM\Table(name="srg_ctl_tipo_referencia_retorno")
 * @ORM\Entity
 */
class SrgCtlTipoReferenciaRetorno
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     * @ORM\SequenceGenerator(sequenceName="srg_ctl_tipo_referencia_retorno_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="tipo", type="string", length=30, nullable=false)
     */
    private $tipo;

    /**
     *
     * @ORM\OneToMany(targetEntity="SrgRetornoExtendido", mappedBy="idTipoReferenciaRetorno", cascade={"all"}, orphanRemoval=true)
     *
     */

    private $SrgRetornoExtendido;

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

    /**
     * Set tipo
     *
     * @param string $tipo
     * @return SrgCtlTipoReferenciaRetorno
     */
    public function setTipo($tipo)
    {
        $this->tipo = $tipo;

        return $this;
    }

    /**
     * Get tipo
     *
     * @return string
     */
    public function getTipo()
    {
        return $this->tipo;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->SrgRetornoExtendido = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add SrgRetornoExtendido
     *
     * @param \Minsal\GinecologiaBundle\Entity\SrgRetornoExtendido $srgRetornoExtendido
     * @return SrgCtlTipoReferenciaRetorno
     */
    public function addSrgRetornoExtendido(\Minsal\GinecologiaBundle\Entity\SrgRetornoExtendido $srgRetornoExtendido)
    {
        $this->SrgRetornoExtendido[] = $srgRetornoExtendido;

        return $this;
    }

    /**
     * Remove SrgRetornoExtendido
     *
     * @param \Minsal\GinecologiaBundle\Entity\SrgRetornoExtendido $srgRetornoExtendido
     */
    public function removeSrgRetornoExtendido(\Minsal\GinecologiaBundle\Entity\SrgRetornoExtendido $srgRetornoExtendido)
    {
        $this->SrgRetornoExtendido->removeElement($srgRetornoExtendido);
    }

    /**
     * Get SrgRetornoExtendido
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getSrgRetornoExtendido()
    {
        return $this->SrgRetornoExtendido;
    }

   public function __toString() {
        return $this->tipo? (string) $this->tipo: '';
    }

}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p60;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test1211 {
    Production1211 objectUnderTest = new Production1211();

    @Test
    public void testProperty0() {
        Production1202 value = new Production1202();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production1206 value = new Production1206();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production1210 value = new Production1210();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
package samples.services;

public class GetQuote {
    String symbol;

    public GetQuote() {
    }

    public GetQuote(String symbol) {
        this.symbol = symbol;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }
}


text:
"use strict";
var router_1 = require('@angular/router');
var region_component_1 = require('./regions/region.component');
var ibg_comp_1 = require('./ItemsByGroup/ibg.comp');
var priceboard_component_1 = require('./PriceBoard/priceboard.component');
var help_component_1 = require('./Help/help.component');
var UserData_component_1 = require('./UserData/UserData.component');
var routes = [
    { path: 'help', component: help_component_1.HelpComponent },
    { path: 'UserData', component: UserData_component_1.UserData },
    { path: 'regions', component: region_component_1.RegionComponent },
    { path: 'ItemsByGroup', component: ibg_comp_1.ibgComponent },
    { path: 'PriceBoard', component: priceboard_component_1.PriceBoardComponent },
    { path: '', redirectTo: 'ItemsByGroup', pathMatch: 'full' }
];
exports.APP_ROUTER_PROVIDERS = [
    router_1.provideRouter(routes),
];
//# sourceMappingURL=app.routes.js.map


text:
	<legend>Sobre a Empresa</legend>

Missão

Mobilidade é a nossa razão de ser. Satisfação do cliente é a nossa motivação. O cliente é a nossa razão de existir. Acreditamos na solidez ética, na honestidade e na integridade como princípios do comportamento empresarial, interno e externo. Acreditamos na inovação como base de desenvolvimento dos negócios. Somos responsáveis perante a comunidade pelo uso eficiente e ponderado dos recursos nos Ecossistemas onde nos movimentamos. Acreditamos que o mais crítico dos factores de sucesso é a capacidade para atrair os melhores, os recursos humanos mais qualificados e motivados. Queremos, por isso, ser reconhecidos como um bom lugar para cada um exercer os seus talentos e ser retribuído com justiça.
					Sentimo-nos responsáveis perante a comunidade pela contribuição para minorar os problemas que afectam as minorias desprotegidas e as pessoas com necessidades especiais.

Atendimentos

Linha Azul: Para o Cliente -> 800 200 200

Telefone : Tel: (+351) 291 234 567

Fax : (+351) 291 234 568

PT : 501335854

E-Mail : ReservasCar@RBRC.pt

Datas

Data de Fundação : 02 / 02 / 1989

Sede da Empresa : Ribeira Brava, Madeira, Portugal

Registo de acesso : 501335854

História

					AUTO RENT A CAR é uma empresa 100% Portuguesa e tem presença no território nacional desde 1989. A actual estrutura acionista resulta de uma join venture entre o Grupo AUTO RENT A CAR e a companhia ACIN. A qualidade do serviço e a vanguarda da tecnologia são premissas essenciais para garantir a satisfação dos nossos clientes na escolha das nossas soluções de mobilidade.
					Mobilidade é a nossa razão de ser. Satisfação do cliente é a nossa motivação.


text:
package com.amazonaws.services.cloudwatchevidently.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum SegmentReferenceResourceType {

    EXPERIMENT("EXPERIMENT"),
    LAUNCH("LAUNCH");

    private String value;

    private SegmentReferenceResourceType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return SegmentReferenceResourceType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static SegmentReferenceResourceType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (SegmentReferenceResourceType enumEntry : SegmentReferenceResourceType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
import sys
import numpy as np

# Set your own Caffe root
caffe_root = '/home/jyh/caffe/'
sys.path.insert(0, caffe_root + 'python')
import caffe

net = caffe.Net("deploy.prototxt", "bvlc_reference_caffenet.caffemodel", caffe.TEST);

f_out = open('model.txt', 'w')

layers = ['conv1','conv2','conv3','conv4','conv5','fc6','fc7','fc8']
for l in layers:
  print l, "weights: ", net.params[l][0].data.shape
  params = net.params[l][0].data.flatten().tolist()
  for cnt, p in enumerate(params):
    f_out.write(str(p) + " ")
#    print cnt, p
  f_out.write("\n")

  print l, "biases: ", net.params[l][1].data.shape
  params = net.params[l][1].data.flatten().tolist()
  for i in params:
    f_out.write(str(i) + " ")
  f_out.write("\n")

f_out.close()