text:
namespace tcmalloc {

// Data kept per size-class in central cache.
class CentralFreeList {
 public:
  void Init(size_t cl);

  // These methods all do internal locking.

  // Insert the specified range into the central freelist.  N is the number of
  // elements in the range.  RemoveRange() is the opposite operation.
  void InsertRange(void *start, void *end, int N);

  // Returns the actual number of fetched elements and sets *start and *end.
  int RemoveRange(void **start, void **end, int N);

  // Returns the number of free objects in cache.
  int length() {
    SpinLockHolder h(&lock_);
    return counter_;
  }

  // Returns the number of free objects in the transfer cache.
  int tc_length();

 private:
  // TransferCache is used to cache transfers of
  // sizemap.num_objects_to_move(size_class) back and forth between
  // thread caches and the central cache for a given size class.
  struct TCEntry {
    void *head;  // Head of chain of objects.
    void *tail;  // Tail of chain of objects.
  };

  // A central cache freelist can have anywhere from 0 to kNumTransferEntries
  // slots to put link list chains into.  To keep memory usage bounded the total
  // number of TCEntries across size classes is fixed.  Currently each size
  // class is initially given one TCEntry which also means that the maximum any
  // one class can have is kNumClasses.
#ifdef TCMALLOC_SMALL_BUT_SLOW
  // For the small memory model, the transfer cache is not used.
  static const int kNumTransferEntries = 0;
#else
  static const int kNumTransferEntries = kNumClasses;
#endif

  // REQUIRES: lock_ is held
  // Remove object from cache and return.
  // Return NULL if no free entries in cache.
  void* FetchFromSpans() EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock_ is held
  // Remove object from cache and return.  Fetches
  // from pageheap if cache is empty.  Only returns
  // NULL on allocation failure.
  void* FetchFromSpansSafe() EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock_ is held
  // Release a linked list of objects to spans.
  // May temporarily release lock_.
  void ReleaseListToSpans(void *start) EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock_ is held
  // Release an object to spans.
  // May temporarily release lock_.
  void ReleaseToSpans(void* object) EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock_ is held
  // Populate cache by fetching from the page heap.
  // May temporarily release lock_.
  void Populate() EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock is held.
  // Tries to make room for a TCEntry.  If the cache is full it will try to
  // expand it at the cost of some other cache size.  Return false if there is
  // no space.
  bool MakeCacheSpace() EXCLUSIVE_LOCKS_REQUIRED(lock_);

  // REQUIRES: lock_ for locked_size_class is held.
  // Picks a "random" size class to steal TCEntry slot from.  In reality it
  // just iterates over the sizeclasses but does so without taking a lock.
  // Returns true on success.
  // May temporarily lock a "random" size class.
  static bool EvictRandomSizeClass(int locked_size_class, bool force);

  // REQUIRES: lock_ is *not* held.
  // Tries to shrink the Cache.  If force is true it will relase objects to
  // spans if it allows it to shrink the cache.  Return false if it failed to
  // shrink the cache.  Decrements cache_size_ on succeess.
  // May temporarily take lock_.  If it takes lock_, the locked_size_class
  // lock is released to keep the thread from holding two size class locks
  // concurrently which could lead to a deadlock.
  bool ShrinkCache(int locked_size_class, bool force) LOCKS_EXCLUDED(lock_);

  // This lock protects all the data members.  cached_entries and cache_size_
  // may be looked at without holding the lock.
  SpinLock lock_;

  // We keep linked lists of empty and non-empty spans.
  size_t   size_class_;     // My size class
  Span     empty_;          // Dummy header for list of empty spans
  Span     nonempty_;       // Dummy header for list of non-empty spans
  size_t   counter_;        // Number of free objects in cache entry

  // Here we reserve space for TCEntry cache slots.  Since one size class can
  // end up getting all the TCEntries quota in the system we just preallocate
  // sufficient number of entries here.
  TCEntry tc_slots_[kNumTransferEntries];

  // Number of currently used cached entries in tc_slots_.  This variable is
  // updated under a lock but can be read without one.
  int32_t used_slots_;
  // The current number of slots for this size class.  This is an
  // adaptive value that is increased if there is lots of traffic
  // on a given size class.
  int32_t cache_size_;
};

// Pads each CentralCache object to multiple of 64 bytes.  Since some
// compilers (such as MSVC) don't like it when the padding is 0, I use
// template specialization to remove the padding entirely when
// sizeof(CentralFreeList) is a multiple of 64.
template<int kFreeListSizeMod64>
class CentralFreeListPaddedTo : public CentralFreeList {
 private:
  char pad_[64 - kFreeListSizeMod64];
};

template<>
class CentralFreeListPaddedTo<0> : public CentralFreeList {
};

class CentralFreeListPadded : public CentralFreeListPaddedTo<
  sizeof(CentralFreeList) % 64> {
};

}  // namespace tcmalloc

#endif  // TCMALLOC_CENTRAL_FREELIST_H_


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Inventory;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;

/**
 *
 * @author joseph
 */
public class Operation implements Serializable{

    private int ID;
    private Person peron;
    private Address Source;
    private Address Destination;
    private Date Scheduled_Date;
    private Operation_type Opt;
    private HashMap<Product,Integer> products_demand; //integer is the quantity/
    private Operation_State State;
    private String Reference_Sequence;

    public Operation(int ID, Person peron, Address Source, Address Destination, Date Scheduled_Date, Operation_type Opt, HashMap<Product,Integer> products_demand, Operation_State State, String Reference_Sequence) {
        this.ID = ID;
        this.peron = peron;
        this.Source = Source;
        this.Destination = Destination;
        this.Scheduled_Date = Scheduled_Date;
        this.Opt = Opt;
        this.products_demand = products_demand;
        this.State = State;
        this.Reference_Sequence = Reference_Sequence;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public Person getPeron() {
        return peron;
    }

    public void setPeron(Person peron) {
        this.peron = peron;
    }

    public Address getSource() {
        return Source;
    }

    public void setSource(Address Source) {
        this.Source = Source;
    }

    public Address getDestination() {
        return Destination;
    }

    public void setDestination(Address Destination) {
        this.Destination = Destination;
    }

    public Date getScheduled_Date() {
        return Scheduled_Date;
    }

    public void setScheduled_Date(Date Scheduled_Date) {
        this.Scheduled_Date = Scheduled_Date;
    }

    public Operation_type getOpt() {
        return Opt;
    }

    public void setOpt(Operation_type Opt) {
        this.Opt = Opt;
    }

    public HashMap<Product,Integer> getProducts_demand() {
        return products_demand;
    }

    public void setProducts_demand(HashMap<Product,Integer> products_demand) {
        this.products_demand = products_demand;
    }

    public Operation_State getState() {
        return State;
    }

    public void setState(Operation_State State) {
        this.State = State;
    }

    public String getReference_Sequence() {
        return Reference_Sequence;
    }

    public void setReference_Sequence(String Reference_Sequence) {
        this.Reference_Sequence = Reference_Sequence;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 41 * hash + this.ID;
        hash = 41 * hash + Objects.hashCode(this.peron);
        hash = 41 * hash + Objects.hashCode(this.Source);
        hash = 41 * hash + Objects.hashCode(this.Destination);
        hash = 41 * hash + Objects.hashCode(this.Scheduled_Date);
        hash = 41 * hash + Objects.hashCode(this.Opt);
        hash = 41 * hash + Objects.hashCode(this.products_demand);
        hash = 41 * hash + Objects.hashCode(this.State);
        hash = 41 * hash + Objects.hashCode(this.Reference_Sequence);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Operation other = (Operation) obj;
        if (this.ID != other.ID) {
            return false;
        }
        if (!Objects.equals(this.Reference_Sequence, other.Reference_Sequence)) {
            return false;
        }
        if (!Objects.equals(this.peron, other.peron)) {
            return false;
        }
        if (!Objects.equals(this.Source, other.Source)) {
            return false;
        }
        if (!Objects.equals(this.Destination, other.Destination)) {
            return false;
        }
        if (!Objects.equals(this.Scheduled_Date, other.Scheduled_Date)) {
            return false;
        }
        if (!Objects.equals(this.Opt, other.Opt)) {
            return false;
        }
        if (!Objects.equals(this.products_demand, other.products_demand)) {
            return false;
        }
        if (!Objects.equals(this.State, other.State)) {
            return false;
        }
        return true;
    }

}

redpajama_set_name: RedPajamaGithub


text:
""" Monitor Manager """

from agent.lib import manifestutil, utils, agenthealth, configutil
from agent.lib.agent_thread.exec_thread import ExecThread
from agent.lib.errors import AgentException, Errors
from agent.lib.scheduler import ThreadedScheduler
from paste.deploy.converters import asbool
from threading import Lock
import copy
import logging
import os
import pylons
import sys
import time
import traceback
from agent.lib.processify import processify
from pympler.asizeof import asizeof

LOG = logging.getLogger(__name__)

METRIC_TAGS_KEY = 'monitoring.metric.tags'
METRIC_TYPE_KEY = 'monitoring.metric.type'
METRIC_CONTEXT = 'monitoring.context'

# allowable resolutions accepted
METRIC_RESOLUTION_SECS = [600.0, 300.0, 60.0, 30.0, 10.0, sys.float_info.min]
METRIC_RESOLUTION_SECS_STR = ['600', '300', '60', '30', '10']

#cmd locks that prevents launching of more subprocess if the previous one has not completed
CMD_LOCKS = {}
CMD_FAILURES = {}

class AgentMonitor():
    """ AgentMonitor class
    This class is responsible for monitoring the agent and all services under it's management
    """

    def __init__(self):
        """ Constructor of the Agent Monitor """
        self.__appGlobal = pylons.config['pylons.app_globals']

        # monitor tasks already scheduled, sample: {(service1,manifest):[monitorReportTask1, monitorTask1, monitorTask2]}
        self.__monitorTasks = {}

        # monitor values, sample: {(service1,monitor): {cpu:[50%,ts,pre-ts], memory:[100,ts,pre-ts]}}
        self.__monitorValues = {}

        # monitor messages, eg: {(service, monitor): [{'t:name':[tag,ts,ts]},{cpu:[50,ts,ts],disk:[10,ts,ts]},{...}]}
        self.__monitorMessages = {}

        # monitor tags, eg: {(service, monitor): [{tag:tagv},{tag:tagv}]}
        self.__monitorTags = {}

        # monitor script probation switch
        self.__probationEnabled = asbool(pylons.config['monitor_probation_enabled'])

        # metrics split count per cal 4k payload limitation
        self.__metricSplitCount = int(pylons.config['cal_metric_split_count']) if 'cal_metric_split_count' in pylons.config else 20

        # schedule a task with scheduler
        self.__monitorSch = ThreadedScheduler()

        # agent monitors
        self._addAgentMonitors()

        # semaphore
        self.__monitorSchLock = Lock()

        # semaphore for monitor change
        self.__addMonitorLock = Lock()

    def start(self):
        ''' starts monitor '''
        with self.__monitorSchLock:
            self.__monitorSch.start()

    def stop(self):
        ''' stop monitor '''
        with self.__monitorSchLock:
            self.__monitorSch.stop()

    def dumpMonitorValues(self):
        ''' dump all monitor values as json string '''
        result = {}
        for (service, mname) in self.__monitorValues:
            key = '%s.%s' % (service, mname)
            result[key] = self.__monitorValues[(service, mname)]
        result['values'] = asizeof(self.__monitorValues)
        result['tasks'] = asizeof(self.__monitorTasks)
        result['messages'] = asizeof(self.__monitorMessages)
        result['tags'] = asizeof(self.__monitorTags)
        result['messagekeys'] = '%s' % self.__monitorMessages
        return result

    def reloadMonitors(self):
        ''' reload service monitors '''
        try:
            self.checkMonitorChanges(forceLoad=True)

        except Exception as excep:
            LOG.error('Failed reload monitors (%s) - %s' % (excep, traceback.format_exc(5)))

    def checkAgentHealth(self):
        '''
        Reports the agent health (as of now, based on disk utilization and file descriptors usage)
        as an attribute to be shown in ValidateInternals page.
        '''
        try:
            (health, healthfactor) = agenthealth.checkAgentHealth()

            self.__appGlobal.agentHealth = health
            self.__appGlobal.agentHealthFactor = healthfactor

        except Exception as excep:
            LOG.error('Fail to get agent health (%s) - %s' % (excep, traceback.format_exc(5)))

    def checkMonitorChanges(self, forceLoad=False):
        ''' check if there is service or manifest changes, and start/stop monitors'''
        try:

            serviceActiveManifests = manifestutil.getAllServiceActiveManifests()

            #if service is created or activeManifest has been changed
            for (service, activeManifest) in serviceActiveManifests:
                needSchedule = True
                if not forceLoad:
                    for (aservice, amanifest) in self.__monitorTasks.keys():
                        if service == aservice and activeManifest == amanifest:
                            needSchedule = False
                            continue

                if needSchedule:
                    if (service, activeManifest) in self.__monitorTasks:
                        # cancel the same existing if any
                        for task in self.__monitorTasks[(service, activeManifest)]:
                            self.__monitorSch.cancel(task)

                    with self.__addMonitorLock:
                        self._addMonitors(service, activeManifest)

            #if the service or manifest is deleted
            for key in self.__monitorTasks.keys():
                if key not in serviceActiveManifests:
                    service, _ = key
                    for task in self.__monitorTasks[key]:
                        self.__monitorSch.cancel(task)
                    del self.__monitorTasks[key]

        except OSError:
            # ignore this type of error.  it's too verbose
            pass
        except Exception as excep:
            LOG.error('Cannot check monitor changes (%s) - %s' % (excep, traceback.format_exc(5)))

    def _addAgentMonitors(self):
        ''' add agent monitors, agent health, local manifest '''
        service = 'agent'

        # agent default, snapshot values to show
        self.__monitorValues[(service, 'default')] = {}
        self.__monitorValues[(service, 'agentmon')] = {}

        # outgoing messages
        self.__monitorMessages[(service, 'default')] = {}
        self.__monitorMessages[(service, 'agentmon')] = {}

        # agent health, schedule only, no reporting
        monitorname = 'AgentHealth'
        interval = float(pylons.config['agent_health_report_interval'])
        self.__monitorSch.add_interval_task(self.checkAgentHealth, monitorname, 30, interval, [], None)

        # check service/manifest changes to load/unload monitors, no reporting
        self.__monitorSch.add_interval_task(self.checkMonitorChanges,
                                                'checkMonitorChanges', 1,
                                                float(pylons.config['monitor_check_timeinterval']),
                                                [], None)

    def _addMonitors(self, service, activeManifest):
        ''' add monitors for a service's activeManifest '''
        monitorTasks = []
        self.__monitorTasks[(service, activeManifest)] = monitorTasks

        # metric tags
        metricTags = {}
        # add default metric tags
        metricTags['fqdn'] = utils.fqdn
        # read tags from agent
        agtMetricTags = manifestutil.readJsonServiceMeta('agent', [METRIC_TAGS_KEY])
        if agtMetricTags and METRIC_TAGS_KEY in agtMetricTags:
            metricTags.update(agtMetricTags[METRIC_TAGS_KEY])
        # read tags from service
        if (service != 'agent'):
            serviceMetricTags = manifestutil.readJsonServiceMeta(service, [METRIC_TAGS_KEY])
            if  serviceMetricTags or METRIC_TAGS_KEY in serviceMetricTags:
                metricTags.update(serviceMetricTags[METRIC_TAGS_KEY])

        # all packages in this manifest
        packages = manifestutil.packagesInManifest(service, os.path.basename(activeManifest))

        # metric tags for externally passed in metrics
        # monitorTags = {additionaltags_dict, datatype_dict, ctx(env.pool.host), appType(Monitor|custom), monitorType(Cronus|CronusApplication)}
        self.__monitorTags[service] = {'default': (metricTags, {}, {})}
        self.__monitorValues[(service, 'default')] = {}
        self.__monitorMessages[(service, 'default')] = {}

        # a unique index for all monitors in the service
        for package in packages:

            # load monitor setting from cronus.ini
            pkgConfigs = manifestutil.getPackageInitConfig(service, activeManifest, package)

            if pkgConfigs is not None and 'monitors' in pkgConfigs:

                metricCtx = pkgConfigs[METRIC_CONTEXT] if METRIC_CONTEXT in pkgConfigs else {}

                metricTypes = {}
                if METRIC_TYPE_KEY in pkgConfigs and pkgConfigs[METRIC_TYPE_KEY]:
                    metricTypes = pkgConfigs[METRIC_TYPE_KEY]

                if METRIC_TAGS_KEY in pkgConfigs and pkgConfigs[METRIC_TAGS_KEY]:
                    metricTags.update(pkgConfigs[METRIC_TAGS_KEY])

                monitors = pkgConfigs['monitors']
                for monitor in monitors:
                    try:
                        m_name = str(monitor['name'])

                        # metric tags for externally passed in metrics
                        # monitorTags = {additionaltags_dict, datatype_dict, ctx(env.pool.host), appType(Monitor|custom), monitorType(Cronus|CronusApplication)}
                        self.__monitorTags[service][m_name] = (metricTags, metricTypes, metricCtx)

                        # now normalize the interval to one allowable by EVPS (downcast)
                        if 'reportIntervalSec' not in monitor:
                            continue
                        m_interval = float(monitor['reportIntervalSec'])
                        m_interval = self._normalizeResolution(m_interval)

                        m_timeout = float(monitor['timeoutSec']) if 'timeoutSec' in monitor else m_interval
                        m_timeout = max(1, min(m_interval-1, m_timeout))
                        m_items = monitor['items'] if 'items' in monitor else []

                        # prime monitor value store
                        self.__monitorValues[(service, m_name)] = {}
                        self.__monitorMessages[(service, m_name)] = {}

                        mi_idx = 0
                        for m_item in m_items:
                            if 'type' not in m_item:
                                continue
                            mi_idx += 1
                            mi_type = m_item['type']
                            mi_cmd = None
                            if 'script' == mi_type:
                                mi_script = m_item['script']
                                mi_cmd = manifestutil.getMonitorScriptPath(service, activeManifest, package, mi_script)
                            else:
                                # unknown type, skip
                                LOG.error('Unknown monitor item type %s, can only be script' % mi_type)
                                continue

                            # schedule monitor
                            m_sch_name = '%s.%s' % (service, m_name)
                            try:
                                self.__monitorMessages[(service, m_name)][mi_cmd] = []
                                task = self.__monitorSch.add_interval_task(self._runMonitor, '%s.%s' % (m_sch_name, str(mi_idx)), 0, float(m_interval),
                                    [mi_type,mi_cmd,service,m_name,m_timeout,(str(int(round(m_interval))),metricTags,metricTypes,metricCtx)],None)
                                monitorTasks.append(task)
                            except Exception as excep:
                                LOG.error('Cannot add monitor task for %s.%s - (%s) %s' % (m_sch_name, str(mi_idx), excep, traceback.format_exc(5)))

                    except Exception as excep1:
                        LOG.error('Cannot add report task for %s.%s - (%s) %s' % (service, m_name, excep1, traceback.format_exc(5)))

    def runReport(self, service, monitorname, cmd, metricoptions):
        '''
        20130326 Change to public  Runs reporting to send data. Should not fail or scheduler will fail.
        metricoptions = {resolution, additionaltags_dict, datatype_dict, metadata_ctx_dict)}
        '''
        monitorKey = (service, monitorname)

        metricResSec = str(metricoptions[0])
        metricTags = metricoptions[1]
        metricTypes = metricoptions[2]
        metricCtx = metricoptions[3]
        try:
            # if no need to send it out, just skip and return
            isPublishing = configutil.getConfigAsBool('monitor_publish_enabled')
            if isPublishing:
                self._connIfNeeded(metricCtx)

            #report monitor status for new values
            tags = []
            try:
                LOG.debug("self.__monitorMessages %s" % self.__monitorMessages)

                # resolution
                tags.append(('m:resSecs', metricResSec))
                # additional tags
                for tkey, tvalue in metricTags.iteritems():
                    tag = 't:%s' % tkey
                    tags.append((tag, tvalue))

                monitorMsg = None
                if monitorKey in self.__monitorMessages and cmd in self.__monitorMessages[monitorKey]:
                    messages = copy.copy(self.__monitorMessages[monitorKey][cmd])
                    del self.__monitorMessages[monitorKey][cmd][:]

                    if not isPublishing:
                        return

                    for message in messages:

                        if monitorMsg is not None:
                            self._publishMonitorMessage(monitorMsg)

                        monitorMsg = self._createMonitorMessage(metricoptions, message)

                        # pre-processing tags from user script
                        overridingTags = set()
                        for (key, value) in message.items():
                            if key.startswith('t:'):
                                overridingTags.add(key)

                        for tkey, tvalue in tags:
                            if tkey not in overridingTags:
                                self._addTagToMessage(monitorMsg, (tkey, tvalue))

                        for (key, msgvalue) in message.items():
                            # there is possibility that we don't see new/updated data, in that case,
                            # prohibit hb creation so as to not corrupt internal transaction stack
                            value, timestamp, preTimestamp = msgvalue[0], msgvalue[1], msgvalue[2]
                            if timestamp != preTimestamp:
                                msgvalue[2] = timestamp

                                if not key.startswith('t:'):
                                    # add metric types, default g:
                                    newKey = '%s:%s' % (metricTypes[key] if (key in metricTypes) else 'g', key)
                                    self._addValueToMessage(monitorMsg, (newKey, value))

                    if monitorMsg is not None:
                        self._publishMonitorMessage(monitorMsg)

            except Exception as excep:
                LOG.error('error when update monitor for %s status (%s) - %s' % (service, excep, traceback.format_exc(5)))

        except OSError:
            pass # ignore this type of error.  it's too verbose
        except Exception as excep:
            LOG.error('Cannot send monitor heartbeat (%s) - %s' % (excep, traceback.format_exc(5)))

    def _putToProbation(self, cmd):
        ''' set a command to probation
            cmd_failures[0]: skip count since probation
            cmd_failures[1]: skip limit 2 ** cmd_failures[1] since probation, it grows exponentially
        '''
        if self.__probationEnabled:
            if cmd in CMD_FAILURES:
                if CMD_FAILURES[cmd][1] < 10:
                    CMD_FAILURES[cmd][1] += 1
                CMD_FAILURES[cmd][0] = 0
            else:
                CMD_FAILURES[cmd] = [0, 0]
            LOG.info('cmd %s put in probation for %s' % (cmd, CMD_FAILURES[cmd][1]))

    def _releaseFromProbation(self, cmd):
        ''' release a command from probation '''
        if self.__probationEnabled and cmd in CMD_FAILURES:
            del CMD_FAILURES[cmd]
            LOG.info('cmd %s released from probation for' % cmd)

    def _shouldRunMonitor(self, cmd):
        ''' should run a monitoring cmd '''
        shouldRun = True
        if cmd in CMD_LOCKS:
            # cmd is locked
            LOG.info('Previous monitor cmd %s not yet complete, skip launching a new one' % cmd)
            shouldRun = False

        if self.__probationEnabled and cmd in CMD_FAILURES:
            # cmd is in probation
            CMD_FAILURES[cmd][0] += 1
            if CMD_FAILURES[cmd][0] < (2 ** CMD_FAILURES[cmd][1]):
                shouldRun = False

        return shouldRun

    def _runMonitor(self, monitortype, cmd, service, monitorname, timeout, metricoptions):
        '''
        Runs monitor script. Should not fail or scheduler will fail.
        CAL logging:
        System wide metrics by agent:
        App wide metrics by apps:
        Establishes connection for each service based on headers obtained from service instance name (of format .env.appService.serviceInstanceName)
        Note: In case of invalid format in both cases, CAL logging is ignored
        '''
        if not self._shouldRunMonitor(cmd):
            return

        try:
            CMD_LOCKS[cmd] = None
            if 'script' == monitortype:
                result = self._executeCommand(cmd, timeout)
            else:
                # unknown type, skip
                return

            if type(result) == dict:
                self.processScriptOuput(service, monitorname, cmd, [result])
            elif type(result) == list:
                self.processScriptOuput(service, monitorname, cmd, result)
            else:
                err_msg = 'monitor %s result error, format not accepted: %s' % (cmd, result)
                LOG.warning(err_msg)
                self._putToProbation(cmd)
                return

            self.runReport(service, monitorname, cmd, metricoptions)
            self._releaseFromProbation(cmd)

        except Exception as excep:
            err_msg = 'Cannot run monitor (%s) - (%s) - (%s)' % (cmd, excep, traceback.format_exc(2))
            LOG.error(err_msg)
            self._putToProbation(cmd)

        finally:
            del CMD_LOCKS[cmd]

    def runExtMonitor(self, service, monitorstream, resSec, result, monitorgroup='default'):
        '''
        Report metrics from external
        '''
        LOG.debug('%s, %s, %s, %s' % (service, monitorstream, resSec, result))
        LOG.debug('%s' % self.__monitorTags)
        if resSec not in METRIC_RESOLUTION_SECS_STR:
            raise AgentException(Errors.MONITOR_INVALID_RESOLUTION,
                                 'Invalid resolution %s, allowable values %s' % (resSec, ','.join(METRIC_RESOLUTION_SECS)))

        metricoptions = (resSec,) + (self.__monitorTags[service][monitorgroup]
                                     if (service in self.__monitorTags and monitorgroup in self.__monitorTags[service])
                                     else (None, None, None, None, None))

        if (service, monitorgroup) not in self.__monitorMessages:
            self.__monitorMessages[monitorgroup] = {}
        if monitorstream not in self.__monitorMessages[(service, monitorgroup)]:
            self.__monitorMessages[(service, monitorgroup)][monitorstream] = []
        try:
            if type(result) == dict:
                self.processScriptOuput(service, monitorgroup, monitorstream, [result])
            elif type(result) == list:
                self.processScriptOuput(service, monitorgroup, monitorstream, result)
            else:
                err_msg = 'monitor %s result error, format not accepted: %s' % (monitorstream, result)
                LOG.warning(err_msg)
                return

            self.runReport(service, monitorgroup, monitorstream, metricoptions)

        except Exception as excep:
            err_msg = 'Cannot run monitor %s error (%s) - (%s)' % (monitorstream, excep, traceback.format_exc(2))
            LOG.error(err_msg)

    def processScriptOuput(self, service, monitorname, cmd, result):
        '''20130326 Change to public ; process multiple key value pairs in result, with tags '''
        monitorKey = (service, monitorname)
        timeCur = time.time()
        tags = []
        tagPrefix = ''
        message = {}
        messages = self.__monitorMessages[monitorKey][cmd]
        for dic in result:
            if 'key' in dic and 'value' in dic:
                key = str(dic['key'])

                if key == 'tagStart' or key == 'tagEnd':
                    if key == 'tagStart':
                        # start tags
                        if type(dic['value']) == dict:
                            tags.append(dic['value'])

                    elif key == 'tagEnd' and tags:
                        # end tags
                        tags.pop()

                    tagFlat = []
                    if message:
                        messages.append(message)
                    message = {}
                    for tagDict in tags:
                        for tagk, tagv in tagDict.items():
                            message[('t:%s' % str(tagk))] = [str(tagv), timeCur, None]
                            tagFlat.append(('%s:%s' % (tagk, str(tagv))))
                    tagPrefix = '.' + '.'.join(tagFlat) + '.' if tagFlat else ''

                else:
                    messages.append(message)
                    message = {}
                    for tagDict in tags:
                        for tagk, tagv in tagDict.items():
                            message[('t:%s' % str(tagk))] = [str(tagv), timeCur, None]

                    value = str(dic['value'])
                    # time not logged in heart beat as it's auto inserted by client while logging
                    fqKey = ('%s%s' % (tagPrefix, key))
                    if monitorKey not in self.__monitorValues:
                        self.__monitorValues[monitorKey] = {}
                    if fqKey not in self.__monitorValues[monitorKey]:
                        rValue = [value, timeCur, None]
                        self.__monitorValues[monitorKey][fqKey] = rValue
                        message[key] = rValue
                    else:
                        rValue = self.__monitorValues[monitorKey][fqKey]
                        rValue[0] = value
                        rValue[1] = timeCur
                        message[key] = rValue

            else:
                # bad format, skip
                err_msg = 'monitor result for service %s error: %s' % (service, dic)
                LOG.debug(err_msg)

        if message:
            messages.append(message)

    def _normalizeResolution(self, userInterval):
        ''' normalize user specified resolution to one supported by EVPS '''
        m_interval = userInterval
        for idx, allowable_interval in enumerate(METRIC_RESOLUTION_SECS):
            if m_interval > allowable_interval:
                if idx == 0:
                    m_interval = allowable_interval
                else:
                    m_interval = METRIC_RESOLUTION_SECS[idx - 1]
                    break
        return m_interval

    @processify
    def _executeCommand(self, cmd, timeout = 2, service = None):
        ''' execute command '''
        execThread = ExecThread(None, cmd)
        execThread.setLogLevel('debug')
        execThread.run()

        # now wait for the threads to complete and update progress
        status = execThread.getStatus()
        if (status['error'] != None):
            return None
#             raise AgentException(status['error'], status['errorMsg'])

        return status['result']

    def _connIfNeeded(self, metricCtx):
        ''' connect to monitoring server if needed '''
        pass

    def _createMonitorMessage(self, metricmeta, message):
        '''
        this creates publishable message
        metricmeta tuple in (metricResSec, metricTags, metricTypes, metricCtx, appType, metricCat)
        '''
        return {}

    def _publishMonitorMessage(self, message):
        '''
        this publish the metrics to its destination, be it event bus, or local logs
        '''
        LOG.info(message)

    def _addValueToMessage(self, message, values):
        ''' add nvp to message '''
        message.put(values)

    def _addTagToMessage(self, message, tags):
        ''' add tag nvp to message '''
        message.put(tags)


text:
<?php

namespace damainpotepuh\CoreBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * NewsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class NewsRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->getEntityManager()
                    ->createQuery('SELECT n FROM damainpotepuhCoreBundle:news n ORDER BY n.created DESC')
                    ->getResult();
    }

    public function findAllWithLimit($limit)
    {
        return $this->getEntityManager()
                    ->createQuery('SELECT n FROM damainpotepuhCoreBundle:news n ORDER BY n.created DESC')
                    ->setMaxResults($limit)
                    ->getResult();
    }
}


text:
<?php

namespace FS\SolrBundle\Query;

use FS\SolrBundle\Query\Exception\UnknownFieldException;

class SolrQuery extends AbstractQuery
{

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

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

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

    /**
     * @var bool
     */
    private $useAndOperator = false;

    /**
     * @var bool
     */
    private $useWildcards = false;

    /**
     * @var string
     */
    private $customQuery;

    /**
     * @return array
     */
    public function getResult()
    {
        return $this->solr->query($this);
    }

    /**
     * @return array
     */
    public function getMappedFields()
    {
        return $this->mappedFields;
    }

    /**
     * @param array $mappedFields
     */
    public function setMappedFields($mappedFields)
    {
        $this->mappedFields = $mappedFields;
    }

    /**
     * @param bool $strict
     */
    public function setUseAndOperator($strict)
    {
        $this->useAndOperator = $strict;
    }

    /**
     * @param bool $boolean
     */
    public function setUseWildcard($boolean)
    {
        $this->useWildcards = $boolean;
    }

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

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

    /**
     * @return array
     */
    public function getSearchTerms()
    {
        return $this->searchTerms;
    }

    /**
     * @param string $value
     */
    public function queryAllFields($value)
    {
        $this->setUseAndOperator(false);

        foreach ($this->mappedFields as $documentField => $entityField) {
            if ($documentField == $this->getMetaInformation()->getIdentifierFieldName()) {
                continue;
            }

            $this->searchTerms[$documentField] = $value;
        }
    }

    /**
     *
     * @param string $field
     * @param string $value
     *
     * @return SolrQuery
     *
     * @throws UnknownFieldException if $field has not mapping / is unknown
     */
    public function addSearchTerm($field, $value)
    {
        $documentFieldsAsValues = array_flip($this->mappedFields);

        $classname = $this->getMetaInformation()->getClassName();

        if (!array_key_exists($field, $documentFieldsAsValues)) {
            throw new UnknownFieldException(sprintf('Entity %s has no mapping for field %s', $classname, $field));
        }

        $documentFieldName = $documentFieldsAsValues[$field];
        if ($position = strpos($field, '.')) {
            $nestedFieldMapping = $documentFieldsAsValues[$field];

            $nestedField = substr($nestedFieldMapping, $position + 1);

            $documentName = $this->getMetaInformation()->getDocumentName();
            $documentFieldName = sprintf('{!parent which="id:%s_*"}%s', $documentName, $nestedField);
            $childFilterPhrase = str_replace('"', '*', $value);
            $childFilterPhrase = str_replace(' ', '*', $value);
            $childFilterPhrase = str_replace('\*', '*', $value);
            $this->childQueries[$documentFieldName] = $childFilterPhrase;
        } else {
            $this->searchTerms[$documentFieldName] = $value;
        }

        return $this;
    }

    /**
     * @param string $field
     *
     * @return SolrQuery
     */
    public function addField($field)
    {
        $entityFieldNames = array_flip($this->mappedFields);
        if (array_key_exists($field, $entityFieldNames)) {
            parent::addField($entityFieldNames[$field]);
        }

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function addFilterQuery($filterQuery)
    {
        if ($this->getFilterQuery('id')) {
            return $this;
        }

        return parent::addFilterQuery($filterQuery);
    }

    /**
     * @return string
     */
    public function getQuery()
    {
        $searchTerms = array_merge($this->searchTerms, $this->childQueries);

        $keyField = $this->getMetaInformation()->getDocumentKey();

        $documentLimitation = $this->createFilterQuery('id')->setQuery('id:'.$keyField.'*');

        $this->addFilterQuery($documentLimitation);
        if ($this->customQuery) {
            parent::setQuery($this->customQuery);

            return $this->customQuery;
        }

        $term = '';
        // query all documents if no terms exists
        if (count($searchTerms) == 0) {
            $query = '*:*';
            parent::setQuery($query);

            return $query;
        }

        $logicOperator = 'AND';
        if (!$this->useAndOperator) {
            $logicOperator = 'OR';
        }

        $termCount = 1;
        foreach ($searchTerms as $fieldName => $fieldValue) {

            if ($fieldName == 'id') {
                $this->getFilterQuery('id')->setQuery('id:' . $fieldValue);

                $termCount++;

                continue;
            }

            $fieldValue = $this->querifyFieldValue($fieldValue);

            $term .= $fieldName . ':' . $fieldValue;

            if ($termCount < count($searchTerms)) {
                $term .= ' ' . $logicOperator . ' ';
            }

            $termCount++;
        }

        if (strlen($term) == 0) {
            $term = '*:*';
        }

        $this->setQuery($term);

        return $term;
    }

    /**
     * Transforms array to string representation and adds quotes
     *
     * @param string $fieldValue
     *
     * @return string
     */
    private function querifyFieldValue($fieldValue)
    {
        if (is_array($fieldValue) && count($fieldValue) > 1) {
            sort($fieldValue);

            $quoted = array_map(function($value) {
                return '"'. $value .'"';
            }, $fieldValue);

            $fieldValue = implode(' TO ', $quoted);
            $fieldValue = '['. $fieldValue . ']';

            return $fieldValue;
        }

        if (is_array($fieldValue) && count($fieldValue) === 1) {
            $fieldValue = array_pop($fieldValue);
        }

        if ($this->useWildcards) {
            $fieldValue = '*' . $fieldValue . '*';
        }

        $termParts = explode(' ', $fieldValue);
        if (count($termParts) > 1) {
            $fieldValue = '"'.$fieldValue.'"';
        }

        return $fieldValue;
    }
}


text:
#include <desc_image_load.h>
#include <platform.h>
#include <platform_def.h>

/*******************************************************************************
 * Following descriptor provides BL image/ep information that gets used
 * by BL2 to load the images and also subset of this information is
 * passed to next BL image. The image loading sequence is managed by
 * populating the images in required loading order. The image execution
 * sequence is managed by populating the `next_handoff_image_id` with
 * the next executable image id.
 ******************************************************************************/
static bl_mem_params_node_t bl2_mem_params_descs[] = {
#ifdef EL3_PAYLOAD_BASE
	/* Fill EL3 payload related information (BL31 is EL3 payload) */
	{ .image_id = BL31_IMAGE_ID,

	  SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				entry_point_info_t,
				SECURE | EXECUTABLE | EP_FIRST_EXE),
	  .ep_info.pc = EL3_PAYLOAD_BASE,
	  .ep_info.spsr = SPSR_64(MODE_EL3, MODE_SP_ELX,
				  DISABLE_ALL_EXCEPTIONS),

	  SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2, image_info_t,
				IMAGE_ATTRIB_PLAT_SETUP | IMAGE_ATTRIB_SKIP_LOADING),

	  .next_handoff_image_id = INVALID_IMAGE_ID,
	},
#else /* EL3_PAYLOAD_BASE */
	/* Fill BL31 related information */
	{ .image_id = BL31_IMAGE_ID,

	  SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				entry_point_info_t,
				SECURE | EXECUTABLE | EP_FIRST_EXE),
	  .ep_info.pc = BL31_BASE,
	  .ep_info.spsr = SPSR_64(MODE_EL3, MODE_SP_ELX,
				  DISABLE_ALL_EXCEPTIONS),
# if DEBUG
	  .ep_info.args.arg1 = QEMU_BL31_PLAT_PARAM_VAL,
# endif
	  SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2, image_info_t,
				IMAGE_ATTRIB_PLAT_SETUP),
	  .image_info.image_base = BL31_BASE,
	  .image_info.image_max_size = BL31_LIMIT - BL31_BASE,

# ifdef QEMU_LOAD_BL32
	  .next_handoff_image_id = BL32_IMAGE_ID,
# else
	  .next_handoff_image_id = BL33_IMAGE_ID,
# endif
	},
# ifdef QEMU_LOAD_BL32
	/* Fill BL32 related information */
	{ .image_id = BL32_IMAGE_ID,

	  SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				entry_point_info_t, SECURE | EXECUTABLE),
	  .ep_info.pc = BL32_BASE,

	  SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2, image_info_t,
				0),
	  .image_info.image_base = BL32_BASE,
	  .image_info.image_max_size = BL32_LIMIT - BL32_BASE,

	  .next_handoff_image_id = BL33_IMAGE_ID,
	},

	/*
	 * Fill BL32 external 1 related information.
	 * A typical use for extra1 image is with OP-TEE where it is the
	 * pager image.
	 */
	{ .image_id = BL32_EXTRA1_IMAGE_ID,

	   SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				 entry_point_info_t, SECURE | NON_EXECUTABLE),

	   SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2,
				 image_info_t, IMAGE_ATTRIB_SKIP_LOADING),
	   .image_info.image_base = BL32_BASE,
	   .image_info.image_max_size = BL32_LIMIT - BL32_BASE,

	   .next_handoff_image_id = INVALID_IMAGE_ID,
	},

	/*
	 * Fill BL32 external 2 related information.
	 * A typical use for extra2 image is with OP-TEE where it is the
	 * paged image.
	 */
	{ .image_id = BL32_EXTRA2_IMAGE_ID,

	   SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				 entry_point_info_t, SECURE | NON_EXECUTABLE),

	   SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2,
				 image_info_t, IMAGE_ATTRIB_SKIP_LOADING),
#ifdef SPD_opteed
	   .image_info.image_base = QEMU_OPTEE_PAGEABLE_LOAD_BASE,
	   .image_info.image_max_size = QEMU_OPTEE_PAGEABLE_LOAD_SIZE,
#endif
	   .next_handoff_image_id = INVALID_IMAGE_ID,
	},
# endif /* QEMU_LOAD_BL32 */

	/* Fill BL33 related information */
	{ .image_id = BL33_IMAGE_ID,
	  SET_STATIC_PARAM_HEAD(ep_info, PARAM_EP, VERSION_2,
				entry_point_info_t, NON_SECURE | EXECUTABLE),
# ifdef PRELOADED_BL33_BASE
	  .ep_info.pc = PRELOADED_BL33_BASE,

	  SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2, image_info_t,
				IMAGE_ATTRIB_SKIP_LOADING),
# else /* PRELOADED_BL33_BASE */
	  .ep_info.pc = NS_IMAGE_OFFSET,

	  SET_STATIC_PARAM_HEAD(image_info, PARAM_EP, VERSION_2, image_info_t,
				0),
	  .image_info.image_base = NS_IMAGE_OFFSET,
	  .image_info.image_max_size = NS_DRAM0_BASE + NS_DRAM0_SIZE -
				       NS_IMAGE_OFFSET,
# endif /* !PRELOADED_BL33_BASE */

	  .next_handoff_image_id = INVALID_IMAGE_ID,
	}
#endif /* !EL3_PAYLOAD_BASE */
};

REGISTER_BL_IMAGE_DESCS(bl2_mem_params_descs)


text:
module.exports = exports = function (err, res, status, msg) {
  msg = msg || err.message;
  process.stderr.write(err + '\n');
  res.status(status).json({ msg });
};


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:focusable="true"
android:focusableInTouchMode="true">
    <TextView
        android:id="@+id/word"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="20dip"
        android:paddingTop="20sp"
        android:text="@string/search_instructions"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="?android:textColorPrimary"
        android:textSize="30sp" />

    <TextView
        android:id="@+id/definition"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingLeft="20sp"
        android:paddingRight="20sp"
        android:paddingTop="20sp"
        android:text="@string/search_instructions"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="?android:textColorSecondary"
        android:textSize="20sp" />

        <TextView
        android:id="@+id/owndefinition"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:paddingLeft="20sp"
        android:paddingRight="20sp"
        android:paddingBottom="20sp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="?android:textColorSecondary"
        android:textSize="20sp"
         />

        <ImageButton
            android:id="@+id/button5"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="62dp"
            android:layout_height="56dp"
            android:layout_gravity="center"
            android:src="@drawable/pronunciation" android:contentDescription="For pronounciation"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10sp"
        android:weightSum="3" >

    <Button
        android:id="@+id/button1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/easy"
        android:text="Easy"
        android:clickable="true"
        android:textColorHint="@color/easy" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/medium"
        android:clickable="true"
        android:linksClickable="true"
        android:text="Medium" />

    <Button
        android:id="@+id/button3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/difficult"
        android:clickable="true"
        android:text="Difficult" />

    </LinearLayout>

    <TextView
        android:id="@+id/textView2"
        android:layout_marginTop="20sp"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:text="Your Own Meaning: " />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" android:inputType="text"/>

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:text="Edit Meaning" />

</LinearLayout>
</ScrollView>


text:
'use strict';

//Incident reports service used to communicate Incident reports REST endpoints
angular.module('incident-reports').factory('IncidentReports', ['$resource',
	function($resource) {
		return $resource('incident-reports/:incidentReportId', { incidentReportId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
import unittest
import llvm.core as lc
import llvm.ee as le
from llvm.core import Type, Builder
from .support import TestCase, tests, skip_if

# Check PTX backend
if le.initialize_target('PTX', noraise=True):
    PTX_ARCH = 'ptx64'
elif le.initialize_target('NVPTX', noraise=True):
    PTX_ARCH = 'nvptx64'
else:
    PTX_ARCH = None

class TestTargetMachines(TestCase):
    '''Exercise target machines

    Require PTX backend
    '''

    def test_native(self):
        m, _ = self._build_module()
        tm = le.EngineBuilder.new(m).select_target()

        self.assertTrue(tm.target_name)
        self.assertTrue(tm.target_data)
        self.assertTrue(tm.target_short_description)
        self.assertTrue(tm.triple)
        self.assertIn('foo', tm.emit_assembly(m))
        self.assertTrue(le.get_host_cpu_name())

    @skip_if(not PTX_ARCH, 'LLVM is not compiled with PTX enabled')
    def test_ptx(self):
        arch = PTX_ARCH
        print(arch)
        m, func = self._build_module()
        func.calling_convention = lc.CC_PTX_KERNEL # set calling conv
        ptxtm = le.TargetMachine.lookup(arch=arch, cpu='sm_20')
        self.assertTrue(ptxtm.triple)
        self.assertTrue(ptxtm.cpu)
        ptxasm = ptxtm.emit_assembly(m)
        self.assertIn('foo', ptxasm)
        if arch == 'nvptx64':
            self.assertIn('.address_size 64', ptxasm)
        self.assertIn('sm_20', ptxasm)

    def _build_module(self):
        m = lc.Module.new('TestTargetMachines')

        fnty = Type.function(Type.void(), [])
        func = m.add_function(fnty, name='foo')

        bldr = Builder.new(func.append_basic_block('entry'))
        bldr.ret_void()
        m.verify()
        return m, func

tests.append(TestTargetMachines)

if __name__ == '__main__':
    unittest.main()


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 com.google.api.ads.adwords.jaxws.utils;

import com.google.api.ads.adwords.jaxws.utils.v201509.batchjob.BatchJobMutateRequest;
import com.google.api.ads.adwords.lib.utils.BatchJobException;
import com.google.api.ads.adwords.lib.utils.BatchJobMutateRequestInterface;
import com.google.api.ads.adwords.lib.utils.BatchJobUploadBodyProvider;
import com.google.api.ads.common.lib.soap.jaxb.JaxBSerializer;
import com.google.api.client.http.ByteArrayContent;
import com.google.common.base.Preconditions;

import javax.xml.namespace.QName;

/**
 * Implementation of {@link BatchJobUploadBodyProvider} for JAX-WS.
 */
public class JaxWsBatchJobUploadBodyProvider implements BatchJobUploadBodyProvider {
  private static final String REQUEST_NAMESPACE_TEMPLATE =
      "https://adwords.google.com/api/adwords/cm/%s";

  private final QName requestQName;

  public JaxWsBatchJobUploadBodyProvider(String apiVersion) {
    this.requestQName = new QName(
        String.format(
            REQUEST_NAMESPACE_TEMPLATE, Preconditions.checkNotNull(apiVersion, "Null API version")),
        "mutate");
  }

  @Override
  public ByteArrayContent getHttpContent(BatchJobMutateRequestInterface request,
      boolean isFirstRequest, boolean isLastRequest) throws BatchJobException {
    JaxBSerializer<BatchJobMutateRequest> serializer =
        new JaxBSerializer<BatchJobMutateRequest>(BatchJobMutateRequest.class, requestQName);

    String serializedRequest =
        serializer.serialize((BatchJobMutateRequest) request, false);

    return new ByteArrayContent("application/xml", serializedRequest.getBytes());
  }
}


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("djasana", "0009_default_ordering"),
    ]

    operations = [
        migrations.AlterField(
            model_name="webhook",
            name="secret",
            field=models.CharField(
                max_length=64, validators=[django.core.validators.MinValueValidator(32)]
            ),
        ),
    ]


text:
require "base64"

saml_data = '<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"></samlp:Response>'
Given /^I am using "(.*?)" as my content type$/ do |type|
  @content_type = type
end

Given /^I make a post request to sso\/post$/ do
  url = Property['api_server_url']+"/api/rest/saml/sso/post"
  data = {"SAMLResponse" => Base64.encode64(saml_data)}
  @res = RestClient.post(url, data, {:content_type => "application/x-www-form-urlencoded", :accept => @content_type}){|response, request, result| response }
end

Then /^I get back a json\-formatted (\d+) error page$/ do |arg1|
  result = JSON.parse(@res.body)
  assert(result['code'] == 403, "Response needs to contain a 403 code")
end

Then /^I get back a html\-formatted (\d+) error page$/ do |arg1|
  assert(@res.body.include?("<html"), "Result must contain html tag")
end


text:
<strand-timepicker></strand-timepicker>

<strand-timepicker use24-hour-time></strand-timepicker>


text:
namespace ChipTuna.Vgm.Headers
{
    public struct V101HeaderPart
    {
        public const uint RateOffset = 0x24;

        public uint Rate;
    }
}


text:
define(["dojo/topic"], function(topic) {
	/*
	* Custom Javascript to be executed while the application is initializing goes here
	*/

	// The application is ready
	topic.subscribe("tpl-ready", function(){
		/*
		* Custom Javascript to be executed when the application is ready goes here
		*/
	});

	// Tab navigation.  This is fired anytime the tab is selected/changed.
	topic.subscribe("story-tab-navigation", function(index){
		/*
		* Custom Javascript to be executed when a tab is selected goes here
		*/
	});
});


text:
#include <algorithm>
#include <iostream>
#include <vector>

/*
 * Solution: the algorithm is as follows
 *
 * 1. Put all intervals into a vector of intervals.
 * 2. Sort all the intervals by start time.
 * 3. Merge all the intervals that can be merged together.
 * 4. The free time intervals will be the formed by combining the end of an interval with the start of the next interval,
 * for all the merged intervals.
 *
 * Time complexity: O(n log n) [where n is the total number of intervals]
 * Space complexity: O(n + m) [where n is the total number of intervals and m is the total number of merged intervals]
 */

class Interval
{
    public:
        int start;
        int end;

        Interval() {}

        Interval(int _start, int _end)
        {
            start = _start;
            end = _end;
        }
};

std::vector<Interval> employeeFreeTime(std::vector<std::vector<Interval>> & schedule)
{
    std::vector<Interval> result;

    auto n=int(schedule.size());

    std::vector<Interval> intervals;

    for(const auto & employeeSchedule : schedule)
    {
        for(const auto & interval : employeeSchedule)
        {
            intervals.emplace_back(interval);
        }
    }

    std::sort(intervals.begin(), intervals.end(), [] (Interval & i1, Interval & i2) {return i1.start < i2.start;});

    std::vector<Interval> merged;

    Interval combined(intervals[0].start, intervals[0].end);

    for(auto i=1;i<int(intervals.size());++i)
    {
        if((combined.end >= intervals[i].start && combined.end <= intervals[i].end) || (intervals[i].start >= combined.start && intervals[i].start <= combined.end))
        {
            combined.start=std::min(combined.start, intervals[i].start);

            combined.end=std::max(combined.end, intervals[i].end);
        }
        else
        {
            Interval interval(combined.start, combined.end);

            merged.emplace_back(interval);

            combined.start=intervals[i].start;

            combined.end=intervals[i].end;
        }
    }

    merged.emplace_back(combined);

    for(auto i=1;i<int(merged.size());++i)
    {
        Interval interval(merged[i-1].end, merged[i].start);

        result.emplace_back(interval);
    }

    return result;
}


text:
/**
 * @author Tarek Auel
 */
/**
 * Creates a mapping module plan object for the new data model
 * @param {object} oldPlan a json object of the old data model
 * @return {modulePlan} a module plan object of the new data model
 */
module.exports = function modulePlan(oldPlan) {
    var newModulePlan;

    newModulePlan = {
        id: oldPlan.idModulplan,
        name: oldPlan.name,
        specialisation: oldPlan.vertiefungsrichtung
    };

    return {
        cypher: 'CREATE (:ModulePlan {props});',
        parameter: {
            props: newModulePlan
        },
        expectedStats: {
            properties_set: 3,
            labels_added: 1,
            nodes_created: 1,
            contains_updates: true
        }
    };
};


text:
import { hashString, Log } from "./utils";

// "Config in code" constant var of logs that should be fed.
export const logs: Log[] = [
  createSimpleLog("pilot", "https://ct.googleapis.com/pilot/ct/v1/"),
];

// Create a log with its ID generated via hashing its name.
function createSimpleLog(name: string, url: string) {
  return { name, url, id: hashString(name) };
}


text:
const tap = require('tap')
const test = tap.test
const guard = require('../index')()

const res = {}

test('no user object present, should throw', function (t) {
  const req = {}
  guard.check(['ping'])(req, res, function (err) {
    if (!err) return t.end('should throw an error')
    t.ok(err.code === 'user_object_not_found', 'correct error code')
    t.end()
  })
})

test('incorrect user object present, should throw', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'bar'
  })
  const req = { user: { scopes: ['foobar'] } }
  guard.check('ping')(req, res, function (err) {
    if (!err) return t.end('should throw an error')
    t.ok(err.code === 'user_object_not_found', 'correct error code')
    t.end()
  })
})

test('valid permissions [Array] notation', function (t) {
  t.plan(1)
  const req = { user: { permissions: ['ping'] } }
  guard.check(['ping'])(req, res, t.error)
})

test('valid multiple permissions', function (t) {
  t.plan(1)
  const req = { user: { permissions: ['foo', 'bar'] } }
  guard.check(['foo', 'bar'])(req, res, t.error)
})

test('valid permissions [String] notation', function (t) {
  t.plan(1)
  const req = { user: { permissions: ['ping'] } }
  guard.check('ping')(req, res, t.error)
})

test('invalid permissions [Object] notation', function (t) {
  const req = { user: { permissions: { ping: true } } }
  guard.check('ping')(req, res, function (err) {
    if (!err) return t.end('should throw an error')
    t.ok(err.code === 'permissions_invalid', 'correct error code')
    t.end()
  })
})

test('permissions array not found', function (t) {
  const req = { user: {} }
  guard.check('ping')(req, res, function (err) {
    if (!err) return t.end('should throw an error')
    t.ok(err.code === 'permissions_not_found', 'correct error code')
    t.end()
  })
})

test('invalid requestProperty with custom options', function (t) {
  const guard = require('../index')({
    requestProperty: undefined,
    permissionsProperty: 'scopes'
  })
  const req = { identity: { scopes: ['ping'] } }
  guard.check('ping')(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'request_property_undefined', 'correct error code')
    t.end()
  })
})

test('valid permissions with custom options', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'scopes'
  })
  const req = { identity: { scopes: ['ping'] } }
  guard.check('ping')(req, res, t.error)
})

test('valid requestProperty of level 1', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'scopes'
  })
  const req = { identity: { scopes: ['ping'] } }
  guard.check('ping')(req, res, t.error)
})

test('valid requestProperty of level n', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'token.identity',
    permissionsProperty: 'scopes'
  })
  const req = { token: { identity: { scopes: ['ping'] } } }
  guard.check('ping')(req, res, t.error)
})

test('invalid permissions [Array] notation', function (t) {
  const req = { user: { permissions: ['ping'] } }
  guard.check('foo')(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'permission_denied', 'correct error code')
    t.end()
  })
})

test('invalid required multiple permissions', function (t) {
  const req = { user: { permissions: ['foo'] } }
  guard.check(['foo', 'bar'])(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'permission_denied', 'correct error code')
    t.end()
  })
})

test('valid permissions with deep permissionsProperty', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'scopes.permissions'
  })
  const req = { identity: { scopes: { permissions: ['ping'] } } }
  guard.check('ping')(req, res, t.error)
})

test('invalid permissions with deep permissionsProperty', function (t) {
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'scopes.permissions'
  })
  const req = { identity: { scopes: { permissions: ['ping'] } } }
  guard.check('foo')(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'permission_denied', 'correct error code')
    t.end()
  })
})

test('valid permissions with very deep permissionsProperty', function (t) {
  t.plan(1)
  const guard = require('../index')({
    requestProperty: 'identity',
    permissionsProperty: 'scopes.permissions.this.is.deep'
  })
  const req = { identity: { scopes: { permissions: { this: { is: { deep: ['ping'] } } } } } }
  guard.check('ping')(req, res, t.error)
})

test('OAuth space-delimited scopes', function (t) {
  t.plan(1)
  const req = { user: { permissions: 'ping foo bar' } }
  guard.check('foo')(req, res, t.error)
})

test('valid boolean "OR" with single required permissions', function (t) {
  t.plan(1)
  const req = { user: { permissions: 'ping foo bar' } }
  guard.check([['nope'], ['ping']])(req, res, t.error)
})

test('valid boolean "OR" with single and multiple required permissions', function (t) {
  t.plan(1)
  const req = { user: { permissions: 'ping foo bar' } }
  guard.check([['nope'], ['ping', 'foo']])(req, res, t.error)
})

test('invalid boolean "OR" with single required permissions', function (t) {
  t.plan(1)
  const req = { user: { permissions: 'ping foo bar' } }
  guard.check([['nope'], ['nada']])(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'permission_denied', 'correct error code')
    t.end()
  })
})

test('invalid boolean "OR" with multiple partial required permissions', function (t) {
  t.plan(1)
  const req = { user: { permissions: 'ping foo bar' } }
  guard.check([['nope', 'foo'], ['nada', 'bar']])(req, res, function (err) {
    if (!err) return t.end('should throw an error')

    t.ok(err.code === 'permission_denied', 'correct error code')
    t.end()
  })
})

test('express unless integration', function (t) {
  t.plan(2)

  const skipReq = { user: { permissions: [] }, url: '/not-secret' }
  guard
    .check(['foo'])
    .unless({ path: '/not-secret' })(skipReq, res, t.error)

  const doNotSkipReq = { user: { permissions: [] }, url: '/secret' }
  guard
    .check(['foo'])
    .unless({ path: '/not-secret' })(doNotSkipReq, res, function (err) {
      if (!err) return t.end('should throw an error')

      t.ok(err.code === 'permission_denied', 'correct error code')
      t.end()
    })
})


text:
require 'traveling_salesman/solution'
require 'traveling_salesman/partially_mapped_crossover'

module TravelingSalesman
  class MatingPair

    attr_reader :parent1, :parent2, :brood_size

    def initialize(parent1, parent2, brood_size: )
      raise ArgumentError, 'brood_size must be positive' unless brood_size > 0
      @brood_size = brood_size
      @parent1 = parent1
      @parent2 = parent2
    end

    def children
      return @children if defined? @children
      child_pairs = (@brood_size / 2.0).ceil.times.map{ make_child_pair }
      @children = child_pairs.flatten.sample(brood_size)
    end

    def make_child_pair
      sequences = PartiallyMappedCrossover.apply(parent1.city_sequence,
                                                 parent2.city_sequence)
      sequences.map {|sequence| Solution.new(sequence)}
    end
  end
end


text:
<?php

class Controller_Home extends Controller_Base
{
    private $guestBook;

    /*
     * 初始化guestBook全局实例
     */
    public function __construct()
    {
        $this->guestBook = Model_GuestBook::getInstance();
    }

    /**
     * 默认handler
     */
    public function index()
    {
        $data = array(
            'title' => '首页',
            'messages' => $this->guestBook->getMessages(),
        );
        $this->render($data, 'home');
    }

    public function add()
    {
        $content = $_POST['content'];
        $message = $this->guestBook->save($content);
        echo json_encode($message->__toArray());
    }

    public function del()
    {
        $uid = $_POST['uid'];
        $this->guestBook->delete($uid);
        echo json_encode(array('success'));
    }
}


text:
<!--
Description: iTunes item category
Expect:      not bozo and entries[0]['tags'][0]['term'] == 'Technology'
-->
<rss xmlns:itunes="http://www.itunes.com/DTDs/Podcast-1.0.dtd">
<channel>
<item>
<itunes:category text="Technology"></itunes:category>
</item>
</channel>
</rss>


text:
package org.apache.camel.component.chronicle.engine;

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

import net.openhft.chronicle.engine.api.map.MapEvent;
import net.openhft.chronicle.engine.api.pubsub.InvalidSubscriberException;
import net.openhft.chronicle.engine.api.pubsub.Subscriber;
import net.openhft.chronicle.engine.api.pubsub.TopicSubscriber;
import net.openhft.chronicle.engine.api.tree.AssetTree;
import net.openhft.chronicle.engine.tree.TopologicalEvent;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.support.DefaultConsumer;

/**
 * The Chronicle Engine consumer.
 */
public class ChronicleEngineConsumer extends DefaultConsumer {
    private final String path;
    private AssetTree client;

    public ChronicleEngineConsumer(ChronicleEngineEndpoint endpoint, Processor processor) {
        super(endpoint, processor);

        this.path = endpoint.getPath();
    }

    @Override
    protected void doStart() throws Exception {
        if (client != null) {
            throw new IllegalStateException("AssetTree already configured");
        }

        ChronicleEngineEndpoint endpoint = (ChronicleEngineEndpoint)getEndpoint();
        ChronicleEngineConfiguration conf = endpoint.getConfiguration();
        client = endpoint.createRemoteAssetTree();

        if (conf.isSubscribeMapEvents()) {
            client.registerSubscriber(
                endpoint.getPath(),
                MapEvent.class,
                new EngineMapEventListener(conf.getFilteredMapEvents()));
        }

        if (conf.isSubscribeTopologicalEvents()) {
            client.registerSubscriber(
                endpoint.getPath(),
                TopologicalEvent.class,
                new EngineTopologicalEventListener());
        }

        if (conf.isSubscribeTopicEvents()) {
            client.registerTopicSubscriber(
                endpoint.getPath(),
                Object.class,
                Object.class,
                new EngineTopicEventListener());
        }
    }

    @Override
    protected void doStop() throws Exception {
        if (client != null) {
            client.close();
            client = null;
        }
    }

    // ****************************
    // MAP EVENT LISTENER
    // ****************************

    private class EngineMapEventListener implements Subscriber<MapEvent> {
        private List<Class<? extends MapEvent>> filteredEvents;

        EngineMapEventListener(String[] events) {
            this.filteredEvents = null;

            if (events != null && events.length > 0) {
                filteredEvents = new ArrayList<>(events.length);
                for (String event : events) {
                    filteredEvents.add(ChronicleEngineMapEventType.getType(event));
                }
            }
        }

        @Override
        public void onMessage(MapEvent event) throws InvalidSubscriberException {
            if (filteredEvents != null && filteredEvents.contains(event.getClass())) {
                return;
            }

            final Exchange exchange = getEndpoint().createExchange();
            final Message message = exchange.getIn();

            message.setHeader(ChronicleEngineConstants.PATH, path);
            message.setHeader(ChronicleEngineConstants.ASSET_NAME, event.assetName());
            message.setHeader(ChronicleEngineConstants.MAP_EVENT_TYPE, ChronicleEngineMapEventType.fromEvent(event));
            message.setHeader(ChronicleEngineConstants.KEY, event.getKey());
            message.setBody(event.getValue());

            if (event.oldValue() != null) {
                message.setHeader(ChronicleEngineConstants.OLD_VALUE, event.oldValue());
            }

            try {
                getProcessor().process(exchange);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
        }
    }

    // ****************************
    // TOPOLOGICAL EVENT LISTENER
    // ****************************

    private class EngineTopologicalEventListener implements Subscriber<TopologicalEvent> {
        @Override
        public void onMessage(TopologicalEvent event) throws InvalidSubscriberException {
            final Exchange exchange = getEndpoint().createExchange();
            final Message message = exchange.getIn();

            message.setHeader(ChronicleEngineConstants.PATH, path);
            message.setHeader(ChronicleEngineConstants.ASSET_NAME, event.assetName());
            message.setHeader(ChronicleEngineConstants.TOPOLOGICAL_EVENT_NAME, event.name());
            message.setHeader(ChronicleEngineConstants.TOPOLOGICAL_EVENT_FULL_NAME, event.fullName());
            message.setHeader(ChronicleEngineConstants.TOPOLOGICAL_EVENT_ADDED, Boolean.toString(event.added()));

            try {
                getProcessor().process(exchange);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
        }
    }

    // ****************************
    // TOPIC EVENT LISTENER
    // ****************************

    private class EngineTopicEventListener implements TopicSubscriber<Object, Object> {
        @Override
        public void onMessage(Object topic, Object dataMessage) throws InvalidSubscriberException {
            final Exchange exchange = getEndpoint().createExchange();
            final Message message = exchange.getIn();

            message.setHeader(ChronicleEngineConstants.PATH, path);
            message.setHeader(ChronicleEngineConstants.TOPIC, topic);
            message.setBody(dataMessage);

            try {
                getProcessor().process(exchange);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
        }
    }
}


text:
from __future__ import print_function, division, absolute_import

import os
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt

import numpy as np
from odin import fuel as F, visual
from odin.ml import MiniBatchPCA
from sklearn.manifold import TSNE
from odin.utils import UnitTimer, TemporaryDirectory

iris = F.load_iris()
print(iris)
pca = MiniBatchPCA()

X = iris['X'][:]

i = 0
while i < X.shape[0]:
    x = X[i:i + 20]
    i += 20
    pca.partial_fit(x)
    print("Fitting PCA ...")

with UnitTimer():
    for i in range(8):
        x = pca.transform(X)

with UnitTimer():
    for i in range(8):
        x = pca.transform_mpi(X, keep_order=True, ncpu=1, n_components=2)
print("Output shape:", x.shape)

colors = ['r' if i == 0 else ('b' if i == 1 else 'g')
          for i in iris['y'][:]]
visual.plot_scatter(x[:, 0], x[:, 1], color=colors, size=8)
visual.plot_save('/tmp/tmp.pdf')
# bananab


text:
var fs = require("fs"),
    filePath = require("@nathanfaucett/file_path"),
    findExt = require("./utils/findExt"),
    getPackagePath = require("./utils/getPackagePath"),
    findPackageJSON = require("./utils/findPackageJSON"),
    createError = require("./utils/createError"),
    readJSONFile = require("./utils/readJSONFile"),
    Dependency = require("./Dependency");

module.exports = resolveModule;

function resolveModule(path, requiredFromFullPath, options) {
    var exts = options.extensions,
        fullPath = filePath.isAbsolute(path) ? path : filePath.join(filePath.dirname(requiredFromFullPath), path),
        tmpFullPath, pkgFullPath, pkg, stat;

    try {
        stat = fs.statSync(fullPath);
    } catch (e) {}

    if (stat && stat.isDirectory()) {
        tmpFullPath = findExt(filePath.join(fullPath, "index"), exts);

        if (tmpFullPath) {
            return new Dependency(tmpFullPath, null, null);
        } else if ((tmpFullPath = findExt(fullPath, exts))) {
            return new Dependency(tmpFullPath, null, null);
        } else {
            pkgFullPath = findPackageJSON(fullPath);

            if (pkgFullPath) {
                try {
                    pkg = readJSONFile(pkgFullPath);
                } catch (e) {}
            }

            if (pkg) {
                tmpFullPath = findExt(filePath.join(fullPath, getPackagePath(pkg, options.packageType)), exts);

                if (tmpFullPath) {
                    return new Dependency(tmpFullPath, pkgFullPath, pkg);
                } else {
                    if (options.throwError) {
                        throw createError(path, requiredFromFullPath, false);
                    } else {
                        return null;
                    }
                }
            } else {
                if (options.throwError) {
                    throw createError(path, requiredFromFullPath, false);
                } else {
                    return null;
                }
            }
        }
    } else {
        fullPath = findExt(fullPath, exts);

        if (fullPath) {
            return new Dependency(fullPath, null, null);
        } else {
            if (options.throwError) {
                throw createError(path, requiredFromFullPath, false);
            } else {
                return null;
            }
        }
    }
}


text:
Firebase Cloud Messaging Quickstart
==============================

The Firebase Cloud Messaging Android Quickstart app demonstrates registering
an Android app for notifications and handling the receipt of a message.
**InstanceID** allows easy registration while **FirebaseMessagingService** and **FirebaseInstanceIDService**
enable token refreshes and message handling on the client.

Introduction
------------

- [Read more about Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging)

Getting Started
---------------

- [Add Firebase to your Android Project](https://firebase.google.com/docs/android/setup).
- Run the sample on Android device or emulator.

Sending Notifications
---------------------

Use Firebase console to send FCM messages to device or emulator.

## Send to a single device

- From Firebase console Notification section, click **New Message**.
- Enter the text of your message in the Message Text field.
- Set the target to **Single Device**.
- Check the logs for the **InstanceID** token, copy and paste it into the Firebase console Token field.
  - If you cannot find the token in your logs, click on the **LOG TOKEN** button in the application and the token will
  be logged in **logcat**.
- Click on the **Send Message** button.
- If your application is in the foreground you should see the incoming
  message printed in the logs. If it is in the background, a system notification should be
  displayed. When the notification is tapped, the application should return to the quickstart application.

## Send to a topic

- From Firebase console Notification section, click **New Message**.
- Enter the text of your message in the Message Text field.
- Click on the **SUBSCRIBE TO NEWS** button to subscribe to the news topic.
- Set the target to **Topic**.
- Select the news topic from the list of topics. You must subscribe from the device or emulator
  before the topic will will be visible in the console.
- Click on the **Send Message** button.
- If your application is in the foreground you should see the incoming
  message printed in the logs. If it is in the background, a system notification should be
  displayed. When the notification is tapped, the application should return to the quickstart application.

Best Practices
--------------

## Android notification channels

### Set default channel

If incoming FCM messages do not specify an Android notification channel, you can indicate
to FCM what channel should be used as the default by adding a metadata element to your
application manifest. In the metadata element specify the ID of the channel that should
be used by default by FCM.

    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel"
        android:value="default_channel_id"/>

Note: You are still required to create a notification channel in code with an ID that
matches the one defined in the manifest. See the Android [docs](https://goo.gl/x9fh5X) for more.

## Customize default notification

### Custom default icon

Setting a custom default icon allows you to specify what icon is used for notification
messages if no icon is set in the notification payload. Also use the custom default
icon to set the icon used by notification messages sent from the Firebase console.
If no custom default icon is set and no icon is set in the notification payload,
the application icon (rendered in white) is used.

### Custom default Color

You can also define what color is used with your notification. Different android
versions use this settings in different ways: Android < N use this as background color
for the icon. Android >= N use this to color the icon and the app name.

See the [docs](https://goo.gl/sPggnS) for more.

Result
-----------
<img src="app/src/screen.png" height="534" width="300"/>

Support
-------

- [Stack Overflow](https://stackoverflow.com/questions/tagged/firebase-cloud-messaging)
- [Firebase Support](https://firebase.google.com/support/)

License
-------

Copyright 2016 Google, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements.  See the NOTICE file distributed with this work for
additional information regarding copyright ownership.  The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License.  You may obtain a copy of
the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
License for the specific language governing permissions and limitations under
the License.


text:
layout: post
title: "git diff show only file names"
description: ""
category: memo
tags: ["git", "cli"]
---
{% include JB/setup %}

# Command

```bash
$ git diff --name-only
```

# Documentation
- [Stack overflow](http://stackoverflow.com/questions/9848347/can-i-make-git-diff-only-show-the-changed-file-names-and-line-numbers)


text:
module Gitlab
  module Ci
    module Pipeline
      module Expression
        class Statement
          StatementError = Class.new(Expression::ExpressionError)

          GRAMMAR = [
            %w[variable],
            %w[variable equals string],
            %w[variable equals variable],
            %w[variable equals null],
            %w[string equals variable],
            %w[null equals variable],
            %w[variable matches pattern]
          ].freeze

          def initialize(statement, variables = {})
            @lexer = Expression::Lexer.new(statement)
            @variables = variables.with_indifferent_access
          end

          def parse_tree
            raise StatementError if @lexer.lexemes.empty?

            unless GRAMMAR.find { |syntax| syntax == @lexer.lexemes }
              raise StatementError, 'Unknown pipeline expression!'
            end

            Expression::Parser.new(@lexer.tokens).tree
          end

          def evaluate
            parse_tree.evaluate(@variables.to_h)
          end

          def truthful?
            evaluate.present?
          rescue Expression::ExpressionError
            false
          end

          def valid?
            parse_tree.is_a?(Lexeme::Base)
          rescue Expression::ExpressionError
            false
          end
        end
      end
    end
  end
end


text:
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Simple REST controller that maps the different request methods to the
 * correct action. Before doing this the controller checks if the requested
 * method / action exists.
 *
 * @package   Backbone
 * @category  Controller
 * @author    T. Zengerink
 */
class Controller_REST extends Controller {

	/**
	 * @var  array  map of methods
	 */
	protected $_method_map = array
	(
		Request::POST   => 'create',
		Request::GET    => 'read',
		Request::PUT    => 'update',
		Request::DELETE => 'delete',
	);

	/**
	 * Checks if the requested method is in the method map and if the mapped
	 * action is also declared in the controller. Throws a HTTP Exception 405
	 * if not so.
	 *
	 * @throws  HTTP_Exception_405
	 */
	public function before()
	{
		// Execute parent's before method
		parent::before();

		// Check if request is allowed, otherwise throw a HTTP_Exception_405
		$allowed = array_key_exists($this->request->method(), $this->_method_map);
		$exists	= method_exists($this, 'action_'.Arr::get($this->_method_map, $this->request->method()));
		if ( ! $allowed OR ! $exists)
		{
			throw new Http_Exception_405('Method :method not allowed.', array(
				':method' => $this->request->method())
			);
		}

		// Execute the correct CRUD action based on the requested method
		$this->request->action(Arr::get($this->_method_map, $this->request->method()));
	}

	/**
	 * Set the cache-control header, so the response will not be cached.
	 */
	public function after()
	{
		// Set headers to not cache anything
		$this->response->headers('cache-control', 'no-cache, no-store, max-age=0, must-revalidate');

		// Execute parent's after method
		parent::after();
	}

} // End Controller Rest


text:
import csv
import shutil as sh
import random as rand

#declare some strings we'll need to read in eventually
city_file_name = '2012_zip_code_use.csv'
infile_name = '2012_individual_use.csv'
outfile_name = 'test.csv'

#open up the list of city files to generate a dictionary mapping cities to zip codes
city_file = open(city_file_name)
reader = csv.DictReader(city_file , delimiter=',')
city_dict = dict()

for row in reader:
    if row['city'] in city_dict:
        city_dict[row['city']].append(row['zipcode'])
    else:
        city_dict[row['city']] = [row['zipcode']]

#sh.copyfile(infile_name, outfile_name)

#open the output and input files
outfile = open(outfile_name, 'wb')
infile = open(infile_name, 'r')

#initiate the csv reader, will need to switch from a Dictreader to a normal reader to make this
#work the way I want.
reader = csv.reader(infile, delimiter=',')
fieldnames = reader.next()
fieldnames.append('CorrectedZipCode')

#print fieldnames

zip_index = fieldnames.index('ZipCode')
city_index = fieldnames.index('City')

writer = csv.writer(outfile, fieldnames,  delimiter=',', quoting=csv.QUOTE_ALL)

writer.writerow(fieldnames)
#writer.writerow('corrected_zip' : 0)

count = 0
correct_zip_count = 0
wrong_city_count = 0

total_count = 0

#we'll want to put this into a function once it works I think
for row in reader:
    total_count = total_count + 1
    if row[city_index] in city_dict:
        if row[zip_index] not in city_dict[row[city_index]]:
            #print "zip code: " + row[zip_index] + " in city: " + row[city_index] +  "  does not match, replacing with random selection from" , city_dict[row[city_index]]
            new_zip = rand.choice(city_dict[row[city_index]])
            row.append(new_zip)
            count = count + 1
            #print row
            writer.writerow(row)
            #print row.append(new_zip)
            #print new_zip
        else:
            correct_zip_count = correct_zip_count + 1
            row.append('no correction')
            writer.writerow(row)

    else:
        wrong_city_count  = wrong_city_count + 1
        row.append('city not found')
        writer.writerow(row)

print count
print correct_zip_count
print wrong_city_count
print total_count


text:
from webbrowser import *

url="https://www.google.co.in"

open(url)

'''
This script lets you open the given link from terminal directly.
It is made meanwhile learning python.
'''


text: MATRIX_TO_VECTOR_FUNCTION(efficiency_local)