text:
'''
Created on Aug 4, 2016

@author: Yusuke Kawatsu.
'''

# built-in modules.
import datetime
import threading

# installed modules.
from flask import Flask
from flask import jsonify
from flask_autodoc.autodoc import Autodoc

# my modules.
from server.awsapis import aws_billing
from server.http_error import _HttpError
from server.store.costs import CostStore
from server.store.costs import MonthlyCostStore
from server.store.awskeys import AwsKeyStore
from server.util import Dot
from server.util import normalize
from server.util import json_params
from server.logger import logger

# flask app.
app = Flask(__name__, static_path=u'/static', static_folder=u'./static')
app.debug = True
auto = Autodoc(app)

# register error handler.
@app.errorhandler(_HttpError)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

@auto.doc()
@app.route('/', methods=['GET'])
def index():
    '''
    index page.
    '''
    # index.htmlを返す. Jinja2でrenderingはしない.
    return app.send_static_file(u'html/index.html')

@auto.doc()
@app.route('/apis', methods=['GET'])
def apidocs():
    '''
    api documentation.
    '''
    return auto.html()

@auto.doc()
@app.route('/apis/estimated_charge', methods=['GET'])
def get_estimated_charge():
    '''
    get estimated charge.
    '''
    ret = {}

    for key in map(lambda k: Dot(k), AwsKeyStore.keys()):
        store = CostStore(key.aws_access_key_id)
        func_pairs = [
            [ store.awsDataTransfer, u'AWSDataTransfer' ],
            [ store.awsQueueService, u'AWSQueueService' ],
            [ store.amazonEC2, u'AmazonEC2' ],
            [ store.amazonES, u'AmazonES' ],
            [ store.amazonElastiCache, u'AmazonElastiCache' ],
            [ store.amazonRDS, u'AmazonRDS' ],
            [ store.amazonRoute53, u'AmazonRoute53' ],
            [ store.amazonS3, u'AmazonS3' ],
            [ store.amazonSNS, u'AmazonSNS' ],
            [ store.awskms, u'awskms' ]
        ]

        part = {}
        for f, name in func_pairs:
            data = f()
            part[name] = data
        ret[key.aws_access_key_id] = part

    return jsonify(**normalize(ret))

@auto.doc()
@app.route('/apis/monthly', methods=['GET'])
def get_monthly():
    '''
    get monthly costs.
    '''
    ret = {}

    for key in map(lambda k: Dot(k), AwsKeyStore.keys()):
        store = MonthlyCostStore(CostStore(key.aws_access_key_id))
        func_pairs = [
            [ store.awsDataTransfer, u'AWSDataTransfer' ],
            [ store.awsQueueService, u'AWSQueueService' ],
            [ store.amazonEC2, u'AmazonEC2' ],
            [ store.amazonES, u'AmazonES' ],
            [ store.amazonElastiCache, u'AmazonElastiCache' ],
            [ store.amazonRDS, u'AmazonRDS' ],
            [ store.amazonRoute53, u'AmazonRoute53' ],
            [ store.amazonS3, u'AmazonS3' ],
            [ store.amazonSNS, u'AmazonSNS' ],
            [ store.awskms, u'awskms' ]
        ]

        part = {}
        for f, name in func_pairs:
            data = f()
            part[name] = data
        ret[key.aws_access_key_id] = part

    return jsonify(**normalize(ret))

@auto.doc()
@app.route('/apis/awskeys', methods=['GET'])
def get_awskeys():
    '''
    get list of aws access key / aws secret key.
    '''
    awskeys = AwsKeyStore.keys()
    return jsonify(awskeys=awskeys)

@auto.doc()
@app.route('/apis/awskeys', methods=['POST'])
def post_awskey():
    '''
    {
      "name": "...",
      "aws_access_key_id": "...",
      "aws_secret_access_key": "..."
    }
    '''
    name, aws_access_key_id, aws_secret_access_key = json_params(
        u'name', u'aws_access_key_id', u'aws_secret_access_key')

    # update db.
    AwsKeyStore.putKey(name, aws_access_key_id, aws_secret_access_key)

    return jsonify(name=name, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)

@auto.doc()
@app.route('/apis/awskeys/<aws_access_key_id>', methods=['DELETE'])
def delete_awskey(aws_access_key_id):
    '''
    :param aws_access_key_id: aws_access_key_id
    '''
    # update db.
    AwsKeyStore.deleteKey(aws_access_key_id)

    return jsonify(aws_access_key_id=aws_access_key_id)

def _fetch_billings_every_day(hour=14, minute=0, second=0):
    '''
    start daemon thread to fetch aws-billing.
    '''
    def _exec():
        # keys without duplicates.
        key_list = { key.aws_access_key_id: key for key in map(lambda k: Dot(k), AwsKeyStore.keys()) }.values()

        # update db.
        for key in key_list:
            # fetch.
            o = aws_billing(key.aws_access_key_id, key.aws_secret_access_key)
            res = o.estimated_charge()

            store = CostStore(key.aws_access_key_id)
            func_pairs = [
                [ store.putAwsDataTransfer, u'AWSDataTransfer' ],
                [ store.putAwsQueueService, u'AWSQueueService' ],
                [ store.putAmazonEC2, u'AmazonEC2' ],
                [ store.putAmazonES, u'AmazonES' ],
                [ store.putAmazonElastiCache, u'AmazonElastiCache' ],
                [ store.putAmazonRDS, u'AmazonRDS' ],
                [ store.putAmazonRoute53, u'AmazonRoute53' ],
                [ store.putAmazonS3, u'AmazonS3' ],
                [ store.putAmazonSNS, u'AmazonSNS' ],
                [ store.putAwskms, u'awskms' ]
            ]

            for f, name in func_pairs:
                if not name in res or not res[name]:
                    continue

                data = Dot(res[name])
                f(data.Maximum, data.Timestamp)

        logger.info(u'called aws clougwatch api.')
        _fetch_billings_every_day(hour, minute, second) # call recursively.

    # next 23:00.
    now = datetime.datetime.utcnow()
    today = datetime.datetime(now.year, now.month, now.day, hour, minute, second)
    tommorow = datetime.datetime(now.year, now.month, now.day + 1, hour, minute, second)
    sec = int((today - now).total_seconds())
    sec = sec if sec > 0 else int((tommorow - now).total_seconds())

    # start next one.
    threading.Timer(sec, _exec).start()
    logger.info(u'scheduled next after (sec): %s' % (sec))

if __name__ == '__main__':
    # run daemon thread.
    _fetch_billings_every_day()

    # :see: http://askubuntu.com/questions/224392/how-to-allow-remote-connections-to-flask
    app.run(host='0.0.0.0', port=5001, threaded=True, use_reloader=False)


text:
/**
 * @module helpers/Task
 */

var grunt = require('grunt');
var surrogateSuffix = '_assets_versioning';
var postSuffix = '_post_assets_versioning';

/**
 * Create a task instance
 * @param {string} taskName
 * @param {Array} [taskFiles]
 * @constructor
 */
var Task = function (taskName, taskFiles) {
  grunt.log.writeln("Versioning files from " + taskName + " task.");
  this.taskName = taskName;

  this.taskConfig = this.getTaskConfig();

  if (!this.taskConfig) {
    grunt.fail.warn("Task '" + this.taskName + "' doesn't exist or doesn't have any configuration.", 1);
  }

  this.taskFiles = taskFiles || this.getFiles();
  if (!this.taskFiles || this.taskFiles.length === 0) {
    grunt.fail.warn("Task '" + this.taskName + "' doesn't have any src-dest file mappings.", 1);
  }

};

/**
 * Get the task configuration
 * @returns {Object}
 */
Task.prototype.getTaskConfig = function () {
  return grunt.config(this.getTaskConfigKey());
};

/**
 * Get the task configuration key
 * @returns {string}
 */
Task.prototype.getTaskConfigKey = function (taskName) {
  taskName = taskName || this.taskName;
  return taskName.replace(':', '.');
};

/**
 * Get the target task grunt files configuration
 * @returns {Array}
 */
Task.prototype.getFiles = function () {
  return grunt.task.normalizeMultiTaskFiles(this.taskConfig);
};

/**
 *
 * @param {Array} filesObj
 * @returns {string}
 */
Task.prototype.createSurrogate = function (filesObj) {
  var surrogateTask = this.taskName + surrogateSuffix;
  var surrogateTaskConfigKey = this.getTaskConfigKey(surrogateTask);

  if (grunt.config(surrogateTaskConfigKey)) {
    grunt.fail.warn("Task '" + surrogateTask + "' already exists!");
  }

  var surrogateTaskConfig = this.taskConfig;
  // remove src & dest keys as they take precedence over the files key
  delete surrogateTaskConfig.src;
  delete surrogateTaskConfig.dest;
  surrogateTaskConfig.files = filesObj;

  grunt.config.set(surrogateTaskConfigKey, surrogateTaskConfig);
  grunt.log.debug("Created surrogateTask '" + surrogateTaskConfigKey + "'");
  grunt.log.debug("Surrogate Task config: " + JSON.stringify(surrogateTaskConfig));

  return surrogateTask;
};

/**
 *
 * @param {Array} filesObj
 * @returns {string}
 */
Task.prototype.createPostVersioningTask = function (filesObj) {
  var postTask = this.taskName + postSuffix;
  var taskConfigKey = this.getTaskConfigKey(postTask);

  if (grunt.config(taskConfigKey)) {
    grunt.fail.warn("Task '" + postTask + "' already exists!");
  }

  var postTaskConfig = this.taskConfig;
  // remove src & dest keys as they take precedence over the files key
  delete postTaskConfig.src;
  delete postTaskConfig.dest;
  postTaskConfig.options = postTaskConfig.options || {};
  postTaskConfig.options.post = false;
  postTaskConfig.options.tasks = false;
  postTaskConfig.isPostVersioningTaskFor = this.getTaskConfigKey();
  postTaskConfig.files = filesObj;

  grunt.config.set(taskConfigKey, postTaskConfig);
  grunt.log.debug("Created Post Versioning Task '" + taskConfigKey + "'");
  grunt.log.debug("Post Versioning Task config: " + JSON.stringify(postTaskConfig));

  return this.taskName + postSuffix;
};

module.exports = Task;

redpajama_set_name: RedPajamaGithub


text:
import csv
import logging
import os

from emgapi import models as emg_models
from emgapianns.management.lib.uploader_exceptions import UnexpectedVariableName
from ..lib import EMGBaseCommand

logger = logging.getLogger(__name__)

class Command(EMGBaseCommand):

    def add_arguments(self, parser):
        parser.add_argument('--emg_db',
                            help='Target emg_db_name alias',
                            choices=['default', 'dev', 'prod'],
                            default='default')
        super(Command, self).add_arguments(parser)

    def populate_from_accession(self, options):
        logger.info("Found %d" % len(self.obj_list))
        for o in self.obj_list:
            self.find_path(o, options)

    def find_path(self, obj, options):
        rootpath = options.get('rootpath', None)
        emg_db = options['emg_db']

        for infile in ['qc_summary', 'functional-annotation/stats/interproscan.stats']:
            self.load_stats(rootpath, obj, infile, emg_db)
        self.import_rna_counts(rootpath=rootpath, job=obj, emg_db=emg_db)
        self.import_orf_stats(rootpath=rootpath, job=obj, emg_db=emg_db)

    def load_stats(self, rootpath, obj, input_file_name, emg_db):
        res = os.path.join(rootpath, obj.result_directory, input_file_name)

        if input_file_name == 'qc_summary':
            if not os.path.exists(res):  # Check existence of the v4.1 result file
                res = os.path.join(rootpath, obj.result_directory, 'charts', 'new.summary')

        if os.path.exists(res):
            if os.path.isfile(res):
                if os.stat(res).st_size > 0:
                    logger.info("Found: %s" % res)
                    with open(res) as csvfile:
                        reader = csv.reader(csvfile, delimiter='\t')
                        self.import_qc(reader, obj, emg_db)
                else:
                    logger.error("Path %r exist. Empty file. SKIPPING!" % res)
            else:
                logger.error("Path %r exist. No summary. SKIPPING!" % res)
        else:
            logger.error("Path %r doesn't exist. SKIPPING!" % res)

    @staticmethod
    def import_qc(reader, job, emg_db):
        anns = []
        for row in reader:
            var = None
            try:
                # The following if else case are a fix for older v4.1 uploads after we changed the labels
                # Could be removed when no more v4.1 results for uploading available
                if row[0] == "Nucleotide sequences with InterProScan match":
                    row[0] = "Reads with InterProScan match"
                elif row[0] == "Nucleotide sequences with predicted CDS":
                    row[0] = "Reads with predicted CDS"
                elif row[0] in ["Nucleotide sequences with predicted rRNA", "Nucleotide sequences with predicted RNA"]:
                    row[0] = "Reads with predicted RNA"
                #     End v4.1 fix
                var = emg_models.AnalysisMetadataVariableNames.objects.using(emg_db) \
                    .get(var_name=row[0])
            except emg_models.AnalysisMetadataVariableNames.DoesNotExist:
                var = emg_models.AnalysisMetadataVariableNames(var_name=row[0])
                var.save()
                # because PK is not AutoField
                var = emg_models.AnalysisMetadataVariableNames.objects.using(emg_db) \
                    .get(var_name=row[0])
            if var is not None:
                job_ann, created = emg_models.AnalysisJobAnn.objects.using(emg_db).update_or_create(
                    job=job, var=var,
                    defaults={'var_val_ucv': row[1]}
                )

                anns.append(job_ann)
        logger.info("Total %d Annotations for Run: %s" % (len(anns), job))

    @staticmethod
    def import_rna_counts(rootpath, job, emg_db):
        logging.info("Loading RNA counts into the database...")
        res = os.path.join(rootpath, job.result_directory, 'RNA-counts')
        if os.path.exists(res):
            with open(res) as tsvfile:
                reader = csv.reader(tsvfile, delimiter='\t')
                for row in reader:
                    if not row: # skip empty lines at the end of the file
                        continue
                    try:
                        if row[0] == 'SSU count':
                            var_name = 'Predicted SSU sequences'
                        elif row[0] == 'LSU count':
                            var_name = 'Predicted LSU sequences'
                        elif not row[0]:
                            continue # Skip empty value rows
                        else:
                            logging.error("Unsupported variable name {}".format(row[0]))
                            raise UnexpectedVariableName

                        var = emg_models.AnalysisMetadataVariableNames.objects.using(emg_db) \
                            .get(var_name=var_name)

                        job_ann, created = emg_models.AnalysisJobAnn.objects.using(emg_db).update_or_create(
                            job=job, var=var,
                            defaults={'var_val_ucv': row[1]}
                        )
                        logging.info("{} successfully loaded into the database.".format(row[0]))

                    except emg_models.AnalysisMetadataVariableNames.DoesNotExist:
                        logging.error("Could not find variable name {} in the database even "
                                        "though it should be supported!".format(row[0]))
                        raise UnexpectedVariableName
        else:
            logging.warning("RNA counts file does not exist: {}".format(res))

    @staticmethod
    def import_orf_stats(rootpath, job, emg_db):
        logging.info("Loading ORF stats into the database...")
        res = os.path.join(rootpath, job.result_directory, 'functional-annotation/stats/orf.stats')
        if os.path.exists(res):
            with open(res) as tsvfile:
                reader = csv.reader(tsvfile, delimiter='\t')
                for row in reader:
                    try:
                        if row[0] == "Predicted CDS":
                            var_name = "Predicted CDS"
                        elif row[0] == "Contigs with predicted CDS":
                            var_name = "Contigs with predicted CDS"
                        elif row[0] in ["Contigs with predicted rRNA", "Contigs with predicted with rRNA",
                                        "Contigs with predicted RNA"]:
                            var_name = "Contigs with predicted RNA"
                        elif row[0] in ["Reads with predicted CDS", "Nucleotide sequences with predicted CDS"]:
                            var_name = "Reads with predicted CDS"
                        elif row[0] in ["Reads with predicted rRNA", "Nucleotide sequences with predicted rRNA",
                                        "Reads with predicted RNA"]:
                            var_name = "Reads with predicted RNA"
                        else:
                            msg = "Unsupported variable name {}".format(row[0])
                            logging.error(msg)
                            raise UnexpectedVariableName(msg)

                        var = emg_models.AnalysisMetadataVariableNames.objects.using(emg_db) \
                            .get(var_name=var_name)

                        job_ann, created = emg_models.AnalysisJobAnn.objects.using(emg_db).update_or_create(
                            job=job, var=var,
                            defaults={'var_val_ucv': row[1]}
                        )
                        logging.info("{} successfully loaded into the database.".format(row[0]))

                    except emg_models.AnalysisMetadataVariableNames.DoesNotExist:
                        msg = "Could not find variable name [{}|{}] in the database even though it should be supported!\n" \
                              "There are {} variables registered" \
                            .format(row[0], var_name, emg_models.AnalysisMetadataVariableNames.objects.count())
                        logging.error(msg)
                        raise UnexpectedVariableName(msg)
        else:
            logging.warning("orf.stats file does not exist: {}".format(res))


text:
using System;
using System.Collections.Generic;
using System.Linq;
using MIMER.RFC2045;
using MIMER.RFC2183;
using MIMER.RFC2633.Pattern;
using MIMER.RFC822;
using MIMER.RFC2045.Pattern;

namespace MIMER.RFC2633
{
    class SMIMEFieldParser:FieldParserDecorator
    {
        #region IFieldParser Members

        public SMIMEFieldParser(ContentDispositionFieldParser original)
            : base(original)
        {
            Original = original;

            var pattern = PatternFactory.GetInstance().Get(typeof (ApplicationSubTypePatern));
            var applicationSubtypePattern = pattern as ApplicationSubTypePatern;

            pattern = PatternFactory.GetInstance().Get(typeof (SMIMEApplicationSubTypePattern), new object[]{applicationSubtypePattern});
            var sMIMEPattern = pattern as SMIMEApplicationSubTypePattern;

            if (sMIMEPattern == null)
                throw new ApplicationException("Could not retrive a " + typeof(SMIMEApplicationSubTypePattern).Name);

           sMIMEPattern.Compile();
        }

        public ContentDispositionFieldParser Original { get; set; }

        public override void CompilePattern()
        {
            DecoratedFieldParser.CompilePattern();
        }

        public override void Parse(ref IList<Field> fields, ref string fieldString)
        {
            DecoratedFieldParser.Parse(ref fields, ref fieldString);

            var smimeFields = from field in fields
                              where field is ContentTypeField &&
                                    !string.IsNullOrEmpty(((ContentTypeField) field).Parameters["smime-type"])
                              select new SMIMETypeField(field as ContentTypeField);

            foreach (var smimeTypeField in smimeFields.ToList())
            {
                fields.Add(smimeTypeField);
            }

        }

        #endregion
    }
}


text:
package net.sf.esfinge.querybuilder.jpa1.testresources;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {

	@Id
	private int id;
	private String city;
	private String state;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}

}


text:
<?php

namespace computerundsound\culibrary\db\mysqli;
use computerundsound\culibrary\db\CuDBResult;

/**
 * Class CuDBiResult
 */
class CuDBiResult implements CuDBResult {

	/** @var  \mysqli_result */
	private $result;

	private $lastInsertId;
	/** @var  string */
	private $message;
	/** @var  string */
	private $query;

	/**
	 * @return int
	 */
	public function getLastInsertId() {
		return $this->lastInsertId;
	}

	/**
	 * @param mixed $lastInsertId
	 */
	public function setLastInsertId($lastInsertId) {
		$this->lastInsertId = $lastInsertId;
	}

	/**
	 * @return string
	 */
	public function getMessage() {
		return $this->message;
	}

	/**
	 * @param string $message
	 */
	public function setMessage($message) {
		$this->message = (string)$message;
	}

	/**
	 * @return \mysqli_result | bool
	 */
	public function getResult() {
		return $this->result;
	}

	/**
	 * @param \mysqli_result | bool $result
	 */
	public function setResult($result) {
		$this->result = $result;
	}

	/**
	 * @return string
	 */
	public function getQuery() {
		return $this->query;
	}

	/**
	 * @param string $query
	 */
	public function setQuery($query) {
		$this->query = (string)$query;
	}
}


text:
module.exports = {
	before: function (browser) {
		browser.adminUIApp = browser.page.adminUIApp();
		browser.signinScreen = browser.page.signinScreen();
		browser.listScreen = browser.page.listScreen();
		browser.itemScreen = browser.page.itemScreen();
		browser.initialFormScreen = browser.page.initialForm();

		browser.adminUIApp
			.gotoHomeScreen()
			.waitForSigninScreen();

		browser.signinScreen.signin();

		browser.adminUIApp.waitForHomeScreen();
	},
	after: function (browser) {
		browser.adminUIApp.signout();
		browser.end();
	}
};


text:
@interface GPHParticleCell ()

@property (nonatomic) UIImageView *observedObject;

@end

@implementation GPHParticleCell

- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  _emitterCell = [CAEmitterCell emitterCell];
  return self;
}

- (void)dealloc
{
  [_observedObject removeObserver:self forKeyPath:@"image"];
  _observedObject = nil;
}

- (void)addSubview:(UIView *)view
{
  NSAssert([view isKindOfClass:[RCTImageView class]],
           @"Only an RCTImageView may be a child of a ParticleCell");

  UIImageView *imageView = (UIImageView*) [[view subviews] firstObject];

  [imageView addObserver:self forKeyPath:@"image"
                 options:NSKeyValueObservingOptionNew context:nil];
  self.observedObject = imageView;

  [self checkForCellImageSetup:imageView];
}

- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index
{
  NSAssert([view isKindOfClass:[RCTImageView class]],
           @"Only an Image may be a child of a ParticleCell");

  UIImageView *imageView = (UIImageView*) [[view subviews] firstObject];

  [imageView addObserver:self forKeyPath:@"image"
                 options:NSKeyValueObservingOptionNew context:nil];
  self.observedObject = imageView;

  [self checkForCellImageSetup:imageView];
  // don't actually insert the imageview
}

// to avoid a lot of boilerplate code we'll just forward the set property calls
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
  if ([self.emitterCell respondsToSelector:anInvocation.selector]) {
    anInvocation.target = self.emitterCell;

    [anInvocation invoke];
  }
}

- (NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
{
  NSMethodSignature *signature = [self.emitterCell methodSignatureForSelector:aSelector];

  NSAssert(signature != nil, @"unknown property set on GPHParticleCell: %@",
           NSStringFromSelector(aSelector));
  return signature;
}

- (void)setLifetime:(float)lifetime
{
  self.emitterCell.lifetime = lifetime/kMillisecondsPerSecond;
}

- (void)setDuration:(double)duration
{
  self.emitterCell.duration = duration/kMillisecondsPerSecond;
}

- (void)setTimeOffset:(double)timeOffset
{
  self.emitterCell.timeOffset = timeOffset/kMillisecondsPerSecond;
}

- (void)setRepeatDuration:(double)repeatDuration
{
  self.emitterCell.repeatDuration = repeatDuration/kMillisecondsPerSecond;
}

-(void)setEmitterSetupCompletion:(void (^)(CAEmitterCell *))emitterSetupCompletion
{
  _emitterSetupCompletion = emitterSetupCompletion;

  if (self.emitterCell.contents) {
    // if we already have the image, execute the callbac right away
    emitterSetupCompletion(self.emitterCell);
  }
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context
{
  UIImageView *imageView = (UIImageView*) object;
  [self checkForCellImageSetup:imageView];
}

- (void)checkForCellImageSetup:(UIImageView *)imageView
{
  if (imageView.image) {
    self.emitterCell.contents = (__bridge id) imageView.image.CGImage;
    if (self.emitterSetupCompletion) {
      self.emitterSetupCompletion(self.emitterCell);
    }
    [self.observedObject removeObserver:self forKeyPath:@"image"];
    self.observedObject = nil;
  }
}
@end


text:
Product

Design:
 proto.io Interface
 Prototype

Proof of Concept:
 Beacon & Personalized Notification
Andriod Application

Proof of Concept:
 Beacon Location & Google Map
 iOS Application


text:
<?php

namespace   Splash\Local\Objects\Address;

use Splash\Local\Local;

/**
 * Dolibarr Contacts Address Fields (Required)
 */
trait CoreTrait
{
    /**
     * Build Core Fields using FieldFactory
     *
     * @return void
     */
    protected function buildCoreFields()
    {
        global $langs;

        //====================================================================//
        // Firstname
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->Identifier("firstname")
            ->Name($langs->trans("Firstname"))
            ->MicroData("http://schema.org/Person", "familyName")
            ->isListed()
            ->isLogged()
            ->isRequired();

        //====================================================================//
        // Lastname
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->Identifier("lastname")
            ->Name($langs->trans("Lastname"))
            ->MicroData("http://schema.org/Person", "givenName")
            ->isLogged()
            ->isListed();

        //====================================================================//
        // Job Title
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->Identifier("poste")
            ->Name($langs->trans("PostOrFunction"))
            ->description("The job title of the person (for example, Financial Manager).")
            ->MicroData("http://schema.org/Person", "jobTitle")
            ->isLogged();

        //====================================================================//
        // Customer
        $this->fieldsFactory()->create((string) self::objects()->Encode("ThirdParty", SPL_T_ID))
            ->Identifier("socid")
            ->Name($langs->trans("Company"))
            ->MicroData("http://schema.org/Organization", "ID");

        //====================================================================//
        // Reference
        $this->fieldsFactory()->create(SPL_T_VARCHAR)
            ->Identifier("ref_ext")
            ->Name($langs->trans("CustomerCode"))
            ->Description($langs->trans("CustomerCodeDesc"))
            ->isListed()
            ->isLogged()
            ->MicroData("http://schema.org/PostalAddress", "name");
    }

    /**
     * Read requested Field
     *
     * @param string $key       Input List Key
     * @param string $fieldName Field Identifier / Name
     *
     * @return void
     */
    protected function getCoreFields(string $key, string $fieldName): void
    {
        //====================================================================//
        // READ Fields
        switch ($fieldName) {
            //====================================================================//
            // Contact ThirdParty Id
            case 'socid':
                $this->out[$fieldName] = self::objects()->Encode("ThirdParty", $this->object->socid);

                break;
                //====================================================================//
                // Direct Readings
            case 'name':
            case 'firstname':
            case 'lastname':
            case 'poste':
            case 'ref_ext':
                $this->getSimple($fieldName);

                break;
            default:
                return;
        }

        unset($this->in[$key]);
    }

    /**
     * Write Given Fields
     *
     * @param string $fieldName Field Identifier / Name
     * @param mixed  $fieldData Field Data
     *
     * @return void
     */
    protected function setCoreFields(string $fieldName, $fieldData): void
    {
        //====================================================================//
        // WRITE Field
        switch ($fieldName) {
            //====================================================================//
            // Contact Company Id
            case 'socid':
                $this->setSimple($fieldName, self::objects()->Id($fieldData));

                break;
                //====================================================================//
                // Direct Writings
            case 'name':
            case 'firstname':
            case 'lastname':
            case 'poste':
                $this->setSimple($fieldName, $fieldData);

                break;
            case 'ref_ext':
                //====================================================================//
                // Update of ref_ext added to Update Func in V14
                if ((Local::dolVersionCmp("14.0.0") < 0) && ($this->object->{$fieldName} != $fieldData)) {
                    $this->setDatabaseField("ref_ext", $fieldData);
                }
                $this->setSimple($fieldName, $fieldData);

                break;
            default:
                return;
        }
        unset($this->in[$fieldName]);
    }
}


text:
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}

module Yesod.Paginator.PagesSpec
    ( spec
    ) where

import Prelude

import Data.Foldable (traverse_)
import Data.Functor.Classes (Eq1(..), Show1(..))
import Data.Proxy
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Classes
import Yesod.Paginator.Pages

instance Arbitrary a => Arbitrary (Page a) where
    arbitrary = (`toPage` 1) <$> arbitrary

instance Arbitrary a => Arbitrary (Pages a) where
    arbitrary = toPages 1 5 100 <$> arbitrary

instance Eq1 Page where
    liftEq f a b = liftEq f (pageItems a) (pageItems b)

instance Show1 Page where
    liftShowsPrec f g h = liftShowsPrec f g h . pageItems

instance Arbitrary1 Page where
    liftArbitrary = fmap (`toPage` 1) . liftArbitrary

instance Eq1 Pages where
    liftEq f a b = liftEq f (pagesCurrent a) (pagesCurrent b)

instance Show1 Pages where
    liftShowsPrec f g h = liftShowsPrec f g h . pagesCurrent

instance Arbitrary1 Pages where
    liftArbitrary = fmap (toPages 1 5 100) . liftArbitrary

spec :: Spec
spec = do
    describe "Page" $ do
        let proxyPage :: Proxy Page
            proxyPage = Proxy

        itPreserves $ functorLaws proxyPage
        itPreserves $ foldableLaws proxyPage
        itPreserves $ traversableLaws proxyPage

    describe "Pages" $ do
        let proxyPages :: Proxy Pages
            proxyPages = Proxy

        itPreserves $ functorLaws proxyPages
        itPreserves $ foldableLaws proxyPages
        itPreserves $ traversableLaws proxyPages

itPreserves :: Laws -> Spec
itPreserves Laws {..} = mkContext $ traverse_ (uncurry mkIt) lawsProperties
  where
    mkContext :: SpecWith a -> SpecWith a
    mkContext = context $ lawsTypeclass <> " laws"

    mkIt :: Example a => String -> a -> SpecWith (Arg a)
    mkIt name = it $ "preserves " <> name


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Extensions.Configuration;

namespace PartsUnlimited.Security
{
    public class ConfigurationLoginProviderCredentials : ILoginProviderCredentials
    {
        public ConfigurationLoginProviderCredentials(IConfiguration config)
        {
            Key = config["Key"];
            Secret = config["Secret"];

            Use = !string.IsNullOrWhiteSpace(Key) && !string.IsNullOrWhiteSpace(Secret);
        }

        public string Key { get; }
        public string Secret { get; }
        public bool Use { get; protected set; }
    }
}


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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.DataObject;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.parse.BpmnParseHandler;
import org.slf4j.Logger;

/**
 * @author Joram Barrez
 */
public class BpmnParseHandlers {

  private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(BpmnParseHandlers.class);

  protected Map<Class<? extends BaseElement>, List<BpmnParseHandler>> parseHandlers;

  public BpmnParseHandlers() {
    this.parseHandlers = new HashMap<Class<? extends BaseElement>, List<BpmnParseHandler>>();
  }

  public List<BpmnParseHandler> getHandlersFor(Class<? extends BaseElement> clazz) {
    return parseHandlers.get(clazz);
  }

  public void addHandlers(List<BpmnParseHandler> bpmnParseHandlers) {
    for (BpmnParseHandler bpmnParseHandler : bpmnParseHandlers) {
      addHandler(bpmnParseHandler);
    }
  }

  public void addHandler(BpmnParseHandler bpmnParseHandler) {
    for (Class<? extends BaseElement> type : bpmnParseHandler.getHandledTypes()) {
      List<BpmnParseHandler> handlers = parseHandlers.get(type);
      if (handlers == null) {
        handlers = new ArrayList<BpmnParseHandler>();
        parseHandlers.put(type, handlers);
      }
      handlers.add(bpmnParseHandler);
    }
  }

  public void parseElement(BpmnParse bpmnParse, BaseElement element) {

    if (element instanceof DataObject) {
      // ignore DataObject elements because they are processed on Process
      // and Sub process level
      return;
    }

    if (element instanceof FlowElement) {
      bpmnParse.setCurrentFlowElement((FlowElement) element);
    }

    // Execute parse handlers
    List<BpmnParseHandler> handlers = parseHandlers.get(element.getClass());

    if (handlers == null) {
      LOGGER.warn("Could not find matching parse handler for + " + element.getId() + " this is likely a bug.");
    } else {
      for (BpmnParseHandler handler : handlers) {
        handler.parse(bpmnParse, element);
      }
    }
  }

}


text:
package org.lastaflute.di.core.deployer;

import org.lastaflute.di.core.ComponentDef;

/**
 * @author modified by jflute (originated in Seasar)
 */
public class ExternalComponentDeployerProvider extends ComponentDeployerFactory.DefaultProvider {

    public ComponentDeployer createRequestComponentDeployer(final ComponentDef cd) {
        return new RequestComponentDeployer(cd);
    }

    public ComponentDeployer createSessionComponentDeployer(final ComponentDef cd) {
        return new SessionComponentDeployer(cd);
    }

    public ComponentDeployer createApplicationComponentDeployer(final ComponentDef cd) {
        return new ApplicationComponentDeployer(cd);
    }
}