text:
package org.apache.stratos.autoscaler.status.processor.group;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.autoscaler.applications.ApplicationHolder;
import org.apache.stratos.autoscaler.applications.topic.ApplicationBuilder;
import org.apache.stratos.autoscaler.status.processor.StatusProcessor;
import org.apache.stratos.messaging.domain.application.*;
import org.apache.stratos.messaging.domain.instance.ClusterInstance;
import org.apache.stratos.messaging.domain.instance.GroupInstance;
import org.apache.stratos.messaging.domain.topology.Cluster;
import org.apache.stratos.messaging.domain.topology.ClusterStatus;
import org.apache.stratos.messaging.domain.topology.Service;
import org.apache.stratos.messaging.message.receiver.topology.TopologyManager;

import java.util.Collection;
import java.util.Map;

/**
 * Cluster active status processor
 */
public class GroupStatusActiveProcessor extends GroupStatusProcessor {
    private static final Log log = LogFactory.getLog(GroupStatusActiveProcessor.class);
    private GroupStatusProcessor nextProcessor;

    @Override
    public void setNext(StatusProcessor nextProcessor) {
        this.nextProcessor = (GroupStatusProcessor) nextProcessor;
    }

    @Override
    public boolean process(String idOfComponent, String appId, String instanceId) {
        boolean statusChanged;
        statusChanged = doProcess(idOfComponent, appId, instanceId);
        if (statusChanged) {
            return true;
        }

        if (nextProcessor != null) {
            // ask the next processor to take care of the message.
            return nextProcessor.process(idOfComponent, appId, instanceId);
        } else {

            log.warn(String.format("No possible state change found for [component] %s, [instance] %s", idOfComponent,
                    instanceId));
        }
        return false;
    }

    @SuppressWarnings("unchecked")
    private boolean doProcess(String idOfComponent, String appId, String instanceId) {
        ParentComponent component;
        Map<String, Group> groups;
        Map<String, ClusterDataHolder> clusterData;

        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "GroupStatusActiveProcessor is checking the status of [application-id] %s, [group-id] %s, "
                            + "[group-instance-id] %s", appId, idOfComponent, instanceId));
        }
        try {
            ApplicationHolder.acquireWriteLock();

            Application application = ApplicationHolder.getApplications().
                    getApplication(appId);
            component = application;
            if (!idOfComponent.equals(appId)) {
                //it is an application
                component = application.getGroupRecursively(idOfComponent);
            }
            //finding all the children of the application/group
            groups = component.getAliasToGroupMap();
            clusterData = component.getClusterDataMap();

            if (groups.isEmpty() && getAllClusterInSameState(clusterData, ClusterStatus.Active, instanceId) ||
                    clusterData.isEmpty() && getAllGroupInSameState(groups, GroupStatus.Active, instanceId) ||
                    getAllClusterInSameState(clusterData, ClusterStatus.Active, instanceId) && getAllGroupInSameState(
                            groups, GroupStatus.Active, instanceId)) {

                if (component instanceof Application) {
                    //send application activated event
                    log.info(String.format(
                            "Sending application instance active event for [application-id] %s, [instance-id] %s",
                            appId, instanceId));
                    ApplicationBuilder.handleApplicationInstanceActivatedEvent(appId, instanceId);
                    return true;
                } else {
                    //send activation to the parent
                    log.info(String.format(
                            "Sending group instance active event for [application-id] %s, [group-id] %s, "
                                    + "[instance-id] %s", appId, component.getUniqueIdentifier(), instanceId));
                    ApplicationBuilder
                            .handleGroupInstanceActivatedEvent(appId, component.getUniqueIdentifier(), instanceId);
                    return true;
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "GroupStatusActiveProcessor did not detect any status change for [application-id] %s, "
                                    + "[group-id] %s, [instance-id] %s", appId, idOfComponent, instanceId));
                    for (Map.Entry<String, Group> entry : groups.entrySet()) {
                        Collection<Group> groupCollection = entry.getValue().getGroups();
                        for (Group group : groupCollection) {
                            for (GroupInstance groupInstance : group.getInstanceIdToInstanceContextMap().values()) {
                                log.debug(String.format("Groups: [group-id] %s, [group-instance-id] %s, [status] %s",
                                        group.getUniqueIdentifier(), groupInstance.getInstanceId(), entry.getKey(),
                                        groupInstance.getStatus()));
                            }

                        }

                    }
                    for (Map.Entry<String, ClusterDataHolder> entry : clusterData.entrySet()) {
                        String serviceName = entry.getValue().getServiceType();
                        String clusterId = entry.getValue().getClusterId();
                        TopologyManager.acquireReadLockForCluster(serviceName, clusterId);
                        try {
                            Service service = TopologyManager.getTopology().getService(serviceName);
                            Cluster cluster = service.getCluster(clusterId);
                            ClusterInstance context = cluster.getInstanceContexts(instanceId);
                            if (context != null) {
                                log.debug(String.format(
                                        "ClusterData: [cluster-id] %s, [cluster-instance-id] %s, [status] %s",
                                        entry.getKey(), instanceId, context.getStatus()));
                            } else {
                                log.debug(String.format(
                                        "ClusterData: cluster instance context is null: [cluster-instance-id] %s",
                                        instanceId));
                            }
                        } finally {
                            TopologyManager.releaseReadLockForCluster(serviceName, clusterId);
                        }
                    }
                }
            }
        } finally {
            ApplicationHolder.releaseWriteLock();
        }
        return false;
    }

}


text:
@interface TGRESTResource ()

@property (nonatomic, copy, readwrite) NSString *name;
@property (nonatomic, copy, readwrite) NSDictionary *model;
@property (nonatomic, copy, readwrite) NSString *primaryKey;
@property (nonatomic, copy, readwrite) NSArray *parentResources;
@property (nonatomic, copy, readwrite) NSArray *childResources;
@property (nonatomic, copy, readwrite) NSDictionary *foreignKeys;
@property (nonatomic, assign, readwrite) TGPropertyType primaryKeyType;
@property (nonatomic, assign, readwrite) TGResourceRESTActions actions;

@end

@implementation TGRESTResource

#pragma mark - Initialization

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.name = @"";
        self.model = @{};
        self.primaryKey = @"id";
        self.parentResources = @[];
        self.foreignKeys = @{};
        self.primaryKeyType = TGPropertyTypeInteger;
        self.actions = TGResourceRESTActionsGET;
    }

    return self;
}

+ (instancetype)newResourceWithName:(NSString *)name
                              model:(NSDictionary *)model
{
    return [self newResourceWithName:name
                               model:model
                             actions:TGResourceRESTActionsGET | TGResourceRESTActionsPOST | TGResourceRESTActionsPUT | TGResourceRESTActionsDELETE
                          primaryKey:nil
                     parentResources:nil
                         foreignKeys:nil];
}

+ (instancetype)newResourceWithName:(NSString *)name
                              model:(NSDictionary *)model
                            actions:(TGResourceRESTActions)actions
                         primaryKey:(NSString *)key
{
    return [self newResourceWithName:name
                               model:model
                             actions:actions
                          primaryKey:key
                         parentResources:nil
                         foreignKeys:nil];
}

+ (instancetype)newResourceWithName:(NSString *)name
                              model:(NSDictionary *)model
                            actions:(TGResourceRESTActions)actions
                         primaryKey:(NSString *)key
                    parentResources:(NSArray *)parents
{
    return [self newResourceWithName:name
                               model:model
                             actions:actions
                          primaryKey:key
                     parentResources:parents
                         foreignKeys:nil];
}

+ (instancetype)newResourceWithName:(NSString *)name
                              model:(NSDictionary *)model
                            actions:(TGResourceRESTActions)actions
                         primaryKey:(NSString *)key
                    parentResources:(NSArray *)parents
                        foreignKeys:(NSDictionary *)fkeys
{
    NSParameterAssert(name);
    NSParameterAssert(model);
    NSParameterAssert(actions);

    TGRESTResource *resource = [TGRESTResource new];

    resource.name = name;
    resource.actions = actions;

    NSMutableDictionary *mergeModel = [NSMutableDictionary new];

    if (model.allKeys.count == 0) {
        @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                       reason:@"Your model is empty, you need to add at least a single property type"
                                     userInfo:nil];
    }

    for (NSString *modelKey in model.allKeys) {
        if (modelKey.length == 0) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"You cannot set a model property with an empty key string"]
                                         userInfo:nil];
        }
    }

    if (key) {
        if (!model[key]) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"Primary key %@ not found in model", key]
                                         userInfo:nil];
        } else if (key.length == 0) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"You cannot set a primary key with an empty string"]
                                         userInfo:nil];
        } else {
            TGPropertyType primaryKeyType = [model[key] integerValue];
            if (primaryKeyType == TGPropertyTypeString || primaryKeyType == TGPropertyTypeInteger) {
                resource.primaryKey = key;
            } else {
                @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                               reason:@"Primary keys must be of text or integer type only"
                                             userInfo:nil];
            }
        }
    } else {
        NSNumber *existingModelIDProperty = model[@"id"];
        if (!existingModelIDProperty) {
            [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeInteger] forKey:resource.primaryKey];
        } else if ([existingModelIDProperty integerValue] != TGPropertyTypeInteger && [existingModelIDProperty integerValue] != TGPropertyTypeString) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"The default primary key of 'id' is set to a type that is not text or integer type.  If you want to use 'id' as your primary key give it a valid type in the model or if you want to use a different primary key then set the primary key name explicitly in the constructor. %@", model]
                                         userInfo:nil];
        }
    }

    [mergeModel addEntriesFromDictionary:model];

    NSMutableArray *validParents = [NSMutableArray new];
    NSMutableDictionary *foreignKeyBuilder = [NSMutableDictionary new];

    for (id object in parents) {
        if (![object isKindOfClass:[TGRESTResource class]]) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:@"Parent resources must be of TGRESTResource class type"
                                         userInfo:nil];
        }
        TGRESTResource *parent = (TGRESTResource *)object;
        if (fkeys[parent.name] && resource.model[fkeys[parent.name]]) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"Your model already has a key named %@, you cannot use it as a foreign key", fkeys[parent.name]]
                                         userInfo:nil];
        } else if (!fkeys[parent.name] && resource.model[[NSString stringWithFormat:@"%@_id", [parent.name singularizedString]]]) {
            @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                           reason:[NSString stringWithFormat:@"Your have not specified a foreign key for parent named %@ but the default foreign key name of %@_id is already specified in your model.  Either delete this from your model or specify a custom foreign key identifier for this parent.", parent.name, parent.name]
                                         userInfo:nil];
        } else {
            [validParents addObject:object];
            if (fkeys[parent.name]) {
                [foreignKeyBuilder setObject:fkeys[parent.name] forKey:parent.name];
                if (parent.primaryKeyType == TGPropertyTypeString) {
                    [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeString] forKey:fkeys[parent.name]];
                } else {
                    [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeInteger] forKey:fkeys[parent.name]];
                }
            } else {
                NSString *defaultForeignKey = [NSString stringWithFormat:@"%@_id", [parent.name singularizedString]];
                [foreignKeyBuilder setObject:defaultForeignKey forKey:parent.name];
                if (parent.primaryKeyType == TGPropertyTypeString) {
                    [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeString] forKey:defaultForeignKey];
                } else {
                    [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeInteger] forKey:defaultForeignKey];
                }
            }
        }
    }

    for (NSString *modelKey in mergeModel.allKeys) {
        NSNumber *modelType = mergeModel[modelKey];
        if ([modelType integerValue] < 1 || [modelType integerValue] > 5) {
            [mergeModel setObject:[NSNumber numberWithInteger:TGPropertyTypeString] forKey:modelKey];
        }
    }

    resource.parentResources = [NSArray arrayWithArray:validParents];
    resource.model = [NSDictionary dictionaryWithDictionary:mergeModel];
    resource.primaryKeyType = [resource.model[resource.primaryKey] integerValue];
    resource.foreignKeys = [NSDictionary dictionaryWithDictionary:foreignKeyBuilder];

    for (TGRESTResource *parentResource in resource.parentResources) {
        NSMutableArray *newChildren = [NSMutableArray arrayWithArray:parentResource.childResources];
        [newChildren addObject:resource];
        [parentResource setValue:[NSArray arrayWithArray:newChildren] forKey:@"childResources"];
    }

    return resource;
}

#pragma mark - Private

- (NSDictionary *)sqliteModel
{
    NSMutableDictionary *sqlite3Model = [NSMutableDictionary new];
    for (NSString *key in [self.model allKeys]) {
        NSNumber *value = self.model[key];
        if ([value integerValue] == TGPropertyTypeString) {
            [sqlite3Model setObject:@"TEXT" forKey:key];
        } else if ([value integerValue] == TGPropertyTypeInteger) {
            [sqlite3Model setObject:@"INTEGER" forKey:key];
        } else if ([value integerValue] == TGPropertyTypeFloatingPoint) {
            [sqlite3Model setObject:@"REAL" forKey:key];
        } else if ([value integerValue] == TGPropertyTypeBlob) {
            [sqlite3Model setObject:@"BLOB" forKey:key];
        }
    }
    return [NSDictionary dictionaryWithDictionary:sqlite3Model];
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@\n  %@", self.name, self.model];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.dgex.offspring.providers.bitcoinaverage;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.log4j.Logger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.dgex.offspring.dataprovider.service.HTTPDataProviderException;
import com.dgex.offspring.providers.service.Currencies;
import com.dgex.offspring.providers.service.ICurrency;
import com.dgex.offspring.providers.service.ICurrencyPair;
import com.dgex.offspring.providers.service.IRate;
import com.dgex.offspring.providers.service.IRateSink;
import com.dgex.offspring.providers.service.Rate;
import com.dgex.offspring.providers.service.RateProvider;
import com.dgex.offspring.providers.utils.JSONUtils;

public class TickerAllProvider extends RateProvider {

  private static TickerAllProvider instance = null;

  public static TickerAllProvider getInstance() {
    if (instance == null)
      instance = new TickerAllProvider();
    return instance;
  }

  private static Logger logger = Logger.getLogger(TickerAllProvider.class);

  private static final String url = "http://api.bitcoinaverage.com/ticker/all";

  private static final String _24HOUR_AVERAGE = "24h_avg";
  private static final String ASK = "ask";
  private static final String BID = "bid";
  private static final String LAST = "last";
  private static final String TIMESTAMP = "timestamp";
  private static final String TOTAL_VOL = "total_vol";

  private final Map<ICurrencyPair, List<IRate>> rates = new HashMap<ICurrencyPair, List<IRate>>();

  private static final ICurrencyPair[] supportedPairs = {
      Currencies.AUD.getPair(Currencies.BTC),
      Currencies.BRL.getPair(Currencies.BTC),
      Currencies.CAD.getPair(Currencies.BTC),
      Currencies.CHF.getPair(Currencies.BTC),
      Currencies.CNY.getPair(Currencies.BTC),
      Currencies.EUR.getPair(Currencies.BTC),
      Currencies.GBP.getPair(Currencies.BTC),
      Currencies.ILS.getPair(Currencies.BTC),
      Currencies.JPY.getPair(Currencies.BTC),
      Currencies.NOK.getPair(Currencies.BTC),
      Currencies.NZD.getPair(Currencies.BTC),
      Currencies.PLN.getPair(Currencies.BTC),
      Currencies.RUB.getPair(Currencies.BTC),
      Currencies.SEK.getPair(Currencies.BTC),
      Currencies.SGD.getPair(Currencies.BTC),
      Currencies.TRY.getPair(Currencies.BTC),
      Currencies.USD.getPair(Currencies.BTC),
      Currencies.ZAR.getPair(Currencies.BTC) };

  @Override
  public String getLabel() {
    return "Bitcoinaverage.com";
  }

  @Override
  public long getIntervalMilliseconds() {
    return 10 * 1000;
  }

  // Sun, 09 Feb 2014 14:17:51 -0000
  private static long parseDate(String dateString) {
    try {
      DateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",
          Locale.ENGLISH);
      return df.parse(dateString).getTime();
    }
    catch (java.text.ParseException e) {
      logger.trace("Date=" + dateString, e);
    }
    return 0l;
  }

  @SuppressWarnings("unchecked")
  @Override
  protected void doRun() {
    try {
      String data = get(new URL(url));

      Object x = new JSONParser().parse(data);
      if (!(x instanceof JSONObject)) {
        logger.error("Expected JSONObject");
        return;
      }

      Map<String, Object> map = (Map<String, Object>) x;
      for (String c : map.keySet()) {
        if ("timestamp".equals(c))
          continue;

        ICurrency currency = Currencies.getCurrency(c);
        if (currency == null) {
          logger.error("Unsupported currency: " + c);
          continue;
        }

        Object obj = map.get(c);
        if (!(obj instanceof JSONObject)) {
          logger.error("Expecting JSONObject: " + obj);
          continue;
        }

        JSONObject mapObj = (JSONObject) obj;
        double price = JSONUtils.getDouble(mapObj, _24HOUR_AVERAGE);
        double last = JSONUtils.getDouble(mapObj, LAST);
        double ask = JSONUtils.getDouble(mapObj, ASK);
        double bid = JSONUtils.getDouble(mapObj, BID);
        double vol = JSONUtils.getDouble(mapObj, TOTAL_VOL);
        long timestamp = parseDate(JSONUtils.getString(mapObj, TIMESTAMP));

        // logger.info(" > timestamp=" + timestamp + " date="
        // + new Date(timestamp));

        IRate rate = new Rate(currency, Currencies.BTC, timestamp, price, vol,
            last, ask, bid);

        ICurrencyPair pair = currency.getPair(Currencies.BTC);

        List<IRate> temp = new ArrayList<IRate>();
        temp.add(rate);
        rates.put(pair, temp);

        for (Object sink : sinks) {
          ((IRateSink) sink).addRate(rate);
        }
      }
      notifyListeners();
    }
    catch (MalformedURLException e) {
      logger.error("Mallformed URL " + url, e);
    }
    catch (HTTPDataProviderException e) {
      logger.error("HTTPDataProviderException " + url, e);
    }
    catch (IOException e) {
      logger.error("IOException " + url, e);
    }
    catch (ParseException e) {
      logger.error("ParseException " + url, e);
    }
  }

  @Override
  public ICurrencyPair[] getSupportedPairs() {
    return supportedPairs;
  }

  @Override
  public List<IRate> doGetRates(ICurrencyPair pair) {
    return rates.get(pair);
  }

}


text:
Update Web API for Soletta
==========================

Introduction
------------
This document presents a JavaScript API based on the [Soletta Update API](http://solettaproject.github.io/docs/c-api/group__Update.html).

The use case is to check, download, check download progress, and install Soletta updates.

Web IDL
-------

```javascript
// var update = require('soletta/update');

[NoInterfaceObject]
interface Update: {
  Promise<UpdateInfo> check();
  Promise<DOMString> fetch();
  Promise<void> install();
  long getProgress(UpdateOperationType type);
  boolean cancel(UpdateOperationType type);
};

dictionary UpdateInfo {
  DOMString version;
  unsigned long long size;
  boolean needed;
};

enum UpdateOperationType { "check", "fetch", "install" };
```

Cancellable operations are defined by the implementations. If an operation cannot be canceled, or canceling is not supported for it, ```cancel``` SHOULD return ```false```.

If an ongoing operation is repeated, e.g. a call to ```fetch()``` is invoked while a fetch is ongoing, the previous operation SHOULD be canceled and its Promise SHOULD reject with ```AbortError```. However, implementations MAY reuse partially downloaded files in the next invocations of ```fetch()```, even though previous fetch operations failed.

The ```install()``` method is considered a transaction. The underlying implementation SHOULD ensure that a failed ```install()``` is rolled back, i.e. it does not leave the system in an indeterministic state.

#### Example
```javascript
var update = require('soletta/update');

update.check()
.then(info => {
  console.log("Update available and needed: " + info.needed ? "yes" : "no");
  if (info.needed) {
    console.log("Update version: " + info.version);
    console.log("Update size (bytes): " + info.size);

    var fetchTimer = setInterval(function() {
      var progress = update.getProgress("fetch");
      if (progress >= 0)
        console.log("Update fetch progress: " + progress + " %");
    }, 1000);

    update.fetch()
    .then(() => {
      clearTimeout(fetchTimer);

      update.install().then(() => {
        console.log("Update installed.");
      }).catch((err) => {
        console.log("Update installation failed.");
      });
    })
    .catch((err) => {
      clearTimeout(fetchTimer);
      console.log("Fetching update failed.");
    });
  }
})
.catch((err) => {
  console.log("Checking update failed.");
});

```


text:
package com.gabrielsamojlo.keyboarddismisser.dismissinglayouts;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.gabrielsamojlo.keyboarddismisser.DismissingUtils;
import com.gabrielsamojlo.keyboarddismisser.KeyboardListener;

public class KeyboardDismissingCoordinatorLayout extends CoordinatorLayout {

    private boolean mIsKeyboardVisible;
    private KeyboardListener mKeyboardListener;

    public KeyboardDismissingCoordinatorLayout(Context context) {
        super(context);
    }

    public KeyboardDismissingCoordinatorLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public KeyboardDismissingCoordinatorLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean wasDispatched = super.dispatchTouchEvent(ev);

        if (!wasDispatched && mIsKeyboardVisible) {
            DismissingUtils.hideKeyboard(this);
        }

        return wasDispatched;
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        mKeyboardListener = new KeyboardListener() {
            @Override
            public void onKeyboardVisibilityChanged(boolean isVisible) {
                mIsKeyboardVisible = isVisible;
            }
        };

        DismissingUtils.setupKeyboardListener(this, mKeyboardListener);
    }

    @Override
    public void onDetachedFromWindow() {
        DismissingUtils.removeKeyboardListener(this, mKeyboardListener);
        mKeyboardListener = null;
        super.onDetachedFromWindow();
    }
}


text:
{{totalJobsWaiting}} Jobs Waiting {{resqueSelected}}

            Queue
            Jobs

 0}">
            {{ jobsInQueue.queue }}
            {{ jobsInQueue.jobs }}


text:
bindkey -e

# Edit the current command line in $EDITOR
autoload -U edit-command-line
zle -N edit-command-line
bindkey '\C-x\C-e' edit-command-line

bindkey "^[[1;5C" forward-word
bindkey "^[[1;5D" backward-word

bindkey '^[[Z' reverse-menu-complete
bindkey '^[/' undo

# auto expand dot to path
zle -N rationalize-dot
bindkey . rationalize-dot


text:
namespace Api.ApplicationServices
{
    public interface IGetValues
    {
        int GetAValue(int id);
    }
}


text:
This command line utility simply converts colors from hexadecimal colors to RGB
and vice versa. It aims for simplicity, portability and uses ``bc``, ``cut``
and other commands as little as possible.

Feel free to contribute to the project in any way or create an issue if you
happen to find a bug.

## Installation
```bash
$ git clone https://github.com/majjoha/color-converter.git
```

```bash
$ cd color-converter && sudo cp color-converter /usr/local/bin/color-converter
```

## Usage
### Convert a hexadecimal color to RGB
```bash
$ color-converter ff0000
#ff0000 -> rgb(255, 255, 0)
```

```bash
$ color-converter "#c71585"
#c71585 -> rgb(199, 21, 133)
```

### Convert a color in RGB to a hexadecimal value
```bash
$ color-converter 255 255 0
rgb(255, 255, 0) -> #ffff00
```

### Change luminosity of a RGB value
```bash
$ color-converter 255 255 255 -25
rgb(255, 255, 255) -> rgb(230, 230, 230)
```


text:
"""
Copy files from a playlist in m3u (MusicMatch) format to a memory stick,
preserving the order of the files in the playlist.
"""
import shutil, sys, re, os

usage = "%s playlistfile [-fp from-path -tp to-path] destination-dir" % \
        sys.argv[0]

if '-fp' in sys.argv:
    from_path = sys.argv[sys.argv.index('-fp')+1]
else:
    from_path = None
if '-tp' in sys.argv:
    to_path = sys.argv[sys.argv.index('-tp')+1]
else:
    to_path = None

destdir = sys.argv[-1]
playlistfile = sys.argv[1]

try:
    songpaths = open(playlistfile, 'r')
except IOError:
    print 'no file %s; maybe wrong arguments to the script?' %  playlistfile
    sys.exit(1)

track_counter = 0
for songpath in songpaths:
    songpath = songpath.strip()
    if from_path is not None:
        songpath = re.sub(from_path, to_path, songpath)
    if not os.path.isfile(songpath):
        print "****************** song file %s does not exist" % songpath
    track_counter += 1
    # prefix song name by the track counter to preserve the sequence of songs on
    # the destination memory stick:
    songname = os.path.basename(songpath)
    destsong = os.path.join(destdir, "%03d - " % track_counter + songname)
    if not os.path.isfile(destsong):
        print 'copy %s to %s' % (songname, destsong)
        shutil.copy(songpath, destsong)
    else:
        print '%s was already on %s' % (songname, destdir)


text:
local tableText = {

	blancas = {
		--<< START translate >>--
		title = "Impostazioni",
		account = "Impostazioni account",
		volume = "Audio e lingua",
		music = "Musica",
		sound = "Souni",
		idiom = "Lingua",
		credits = "Riconoscimenti",
		followFB = "Seguici su Facebook",
		closeUser = "Esci",
		createUser = "Crea un account",
		signup = "Iscriviti",
		createCaja = "Crea un nuovo account",
		identificate = "Accedi",
		cancel = "Annulla",
		showCredits = "Mostra i riconoscimenti",
		--<< END translate >>--
	},

	negras = {
		--<< START translate >>--
		credits = "Wonder Gardens è stato progettato e programmato da Playtypus. Basandosi sul gioco da tavolo \"Gardens\", creato da Pere Pau Listosella." ,
		username = "Nome utente",
		signup = "Non hai effettuato l'accesso",
		conect = "Accedi come:",
		ooo = "O",
		nickname = "Nome utente",
		mail = "Indirizzo e-mail",
		pass = "Password",
		errorSign1 = "Errore: Il nome utente o la password",
		errorSign2 = "          inseriti non sono corretti.",
		errorCreateA1 = "Errore: Il nome utente deve contenere",
		errorCreateA2 = "           dai 2 ai 9 caratteri.",
		errorCreateB1 = "Errore: L'indirizzo e-mail inserito",
		errorCreateB2 = "           non è corretto.",
		errorCreateC1 = "Errore: La password deve contenere almeno 6",
		errorCreateC2 = "           numeri e/o lettere.",
		errorCreateD1 = "Errore: L'indirizzo e-mail inserito ",
		errorCreateD2 = "           è già in uso.",
		--<< END translate >>--
	}
}
return tableText


text:
title: Query functions
nav_title: Functions
sort_rank: 3
---

# Functions

Some functions have default arguments, e.g. `year(v=vector(time())
instant-vector)`. This means that there is one argument `v` which is an instant
vector, which if not provided it will default to the value of the expression
`vector(time())`.

_Notes about the experimental native histograms:_

* Ingesting native histograms has to be enabled via a [feature
  flag](../feature_flags/#native-histograms). As long as no native histograms
  have been ingested into the TSDB, all functions will behave as usual.
* Functions that do not explicitly mention native histograms in their
  documentation (see below) effectively treat a native histogram as a float
  sample of value 0. (This is confusing and will change before native
  histograms become a stable feature.)
* Functions that do already act on native histograms might still change their
  behavior in the future.
* If a function requires the same bucket layout between multiple native
  histograms it acts on, it will automatically convert them
  appropriately. (With the currently supported bucket schemas, that's always
  possible.)

## `abs()`

`abs(v instant-vector)` returns the input vector with all sample values converted to
their absolute value.

## `absent()`

`absent(v instant-vector)` returns an empty vector if the vector passed to it
has any elements (floats or native histograms) and a 1-element vector with the
value 1 if the vector passed to it has no elements.

This is useful for alerting on when no time series exist for a given metric name
and label combination.

```
absent(nonexistent{job="myjob"})
# => {job="myjob"}

absent(nonexistent{job="myjob",instance=~".*"})
# => {job="myjob"}

absent(sum(nonexistent{job="myjob"}))
# => {}
```

In the first two examples, `absent()` tries to be smart about deriving labels
of the 1-element output vector from the input vector.

## `absent_over_time()`

`absent_over_time(v range-vector)` returns an empty vector if the range vector
passed to it has any elements (floats or native histograms) and a 1-element
vector with the value 1 if the range vector passed to it has no elements.

This is useful for alerting on when no time series exist for a given metric name
and label combination for a certain amount of time.

```
absent_over_time(nonexistent{job="myjob"}[1h])
# => {job="myjob"}

absent_over_time(nonexistent{job="myjob",instance=~".*"}[1h])
# => {job="myjob"}

absent_over_time(sum(nonexistent{job="myjob"})[1h:])
# => {}
```

In the first two examples, `absent_over_time()` tries to be smart about deriving
labels of the 1-element output vector from the input vector.

## `ceil()`

`ceil(v instant-vector)` rounds the sample values of all elements in `v` up to
the nearest integer.

## `changes()`

For each input time series, `changes(v range-vector)` returns the number of
times its value has changed within the provided time range as an instant
vector.

## `clamp()`

`clamp(v instant-vector, min scalar, max scalar)`
clamps the sample values of all elements in `v` to have a lower limit of `min` and an upper limit of `max`.

Special cases:
- Return an empty vector if `min > max`
- Return `NaN` if `min` or `max` is `NaN`

## `clamp_max()`

`clamp_max(v instant-vector, max scalar)` clamps the sample values of all
elements in `v` to have an upper limit of `max`.

## `clamp_min()`

`clamp_min(v instant-vector, min scalar)` clamps the sample values of all
elements in `v` to have a lower limit of `min`.

## `day_of_month()`

`day_of_month(v=vector(time()) instant-vector)` returns the day of the month
for each of the given times in UTC. Returned values are from 1 to 31.

## `day_of_week()`

`day_of_week(v=vector(time()) instant-vector)` returns the day of the week for
each of the given times in UTC. Returned values are from 0 to 6, where 0 means
Sunday etc.

## `day_of_year()`

`day_of_year(v=vector(time()) instant-vector)` returns the day of the year for
each of the given times in UTC. Returned values are from 1 to 365 for non-leap years,
and 1 to 366 in leap years.

## `days_in_month()`

`days_in_month(v=vector(time()) instant-vector)` returns number of days in the
month for each of the given times in UTC. Returned values are from 28 to 31.

## `delta()`

`delta(v range-vector)` calculates the difference between the
first and last value of each time series element in a range vector `v`,
returning an instant vector with the given deltas and equivalent labels.
The delta is extrapolated to cover the full time range as specified in
the range vector selector, so that it is possible to get a non-integer
result even if the sample values are all integers.

The following example expression returns the difference in CPU temperature
between now and 2 hours ago:

```
delta(cpu_temp_celsius{host="zeus"}[2h])
```

`delta` acts on native histograms by calculating a new histogram where each
compononent (sum and count of observations, buckets) is the difference between
the respective component in the first and last native histogram in
`v`. However, each element in `v` that contains a mix of float and native
histogram samples within the range, will be missing from the result vector.

`delta` should only be used with gauges and native histograms where the
components behave like gauges (so-called gauge histograms).

## `deriv()`

`deriv(v range-vector)` calculates the per-second derivative of the time series in a range
vector `v`, using [simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
The range vector must have at least two samples in order to perform the calculation. When `+Inf` or
`-Inf` are found in the range vector, the slope and offset value calculated will be `NaN`.

`deriv` should only be used with gauges.

## `exp()`

`exp(v instant-vector)` calculates the exponential function for all elements in `v`.
Special cases are:

* `Exp(+Inf) = +Inf`
* `Exp(NaN) = NaN`

## `floor()`

`floor(v instant-vector)` rounds the sample values of all elements in `v` down
to the nearest integer.

## `histogram_count()` and `histogram_sum()`

_Both functions only act on native histograms, which are an experimental
feature. The behavior of these functions may change in future versions of
Prometheus, including their removal from PromQL._

`histogram_count(v instant-vector)` returns the count of observations stored in
a native histogram. Samples that are not native histograms are ignored and do
not show up in the returned vector.

Similarly, `histogram_sum(v instant-vector)` returns the sum of observations
stored in a native histogram.

Use `histogram_count` in the following way to calculate a rate of observations
(in this case corresponding to "requests per second") from a native histogram:

    histogram_count(rate(http_request_duration_seconds[10m]))

The additional use of `histogram_sum` enables the calculation of the average of
observed values (in this case corresponding to "average request duration"):

      histogram_sum(rate(http_request_duration_seconds[10m]))
	/
      histogram_count(rate(http_request_duration_seconds[10m]))

## `histogram_fraction()`

_This function only acts on native histograms, which are an experimental
feature. The behavior of this function may change in future versions of
Prometheus, including its removal from PromQL._

For a native histogram, `histogram_fraction(lower scalar, upper scalar, v
instant-vector)` returns the estimated fraction of observations between the
provided lower and upper values. Samples that are not native histograms are
ignored and do not show up in the returned vector.

For example, the following expression calculates the fraction of HTTP requests
over the last hour that took 200ms or less:

    histogram_fraction(0, 0.2, rate(http_request_duration_seconds[1h]))

The error of the estimation depends on the resolution of the underlying native
histogram and how closely the provided boundaries are aligned with the bucket
boundaries in the histogram.

`+Inf` and `-Inf` are valid boundary values. For example, if the histogram in
the expression above included negative observations (which shouldn't be the
case for request durations), the appropriate lower boundary to include all
observations less than or equal 0.2 would be `-Inf` rather than `0`.

Whether the provided boundaries are inclusive or exclusive is only relevant if
the provided boundaries are precisely aligned with bucket boundaries in the
underlying native histogram. In this case, the behavior depends on the schema
definition of the histogram. The currently supported schemas all feature
inclusive upper boundaries and exclusive lower boundaries for positive values
(and vice versa for negative values). Without a precise alignment of
boundaries, the function uses linear interpolation to estimate the
fraction. With the resulting uncertainty, it becomes irrelevant if the
boundaries are inclusive or exclusive.

## `histogram_quantile()`

`histogram_quantile(φ scalar, b instant-vector)` calculates the φ-quantile (0 ≤
φ ≤ 1) from a [conventional
histogram](https://prometheus.io/docs/concepts/metric_types/#histogram) or from
a native histogram. (See [histograms and
summaries](https://prometheus.io/docs/practices/histograms) for a detailed
explanation of φ-quantiles and the usage of the (conventional) histogram metric
type in general.)

_Note that native histograms are an experimental feature. The behavior of this
function when dealing with native histograms may change in future versions of
Prometheus._

The conventional float samples in `b` are considered the counts of observations
in each bucket of one or more conventional histograms. Each float sample must
have a label `le` where the label value denotes the inclusive upper bound of
the bucket. (Float samples without such a label are silently ignored.) The
other labels and the metric name are used to identify the buckets belonging to
each conventional histogram. The [histogram metric
type](https://prometheus.io/docs/concepts/metric_types/#histogram)
automatically provides time series with the `_bucket` suffix and the
appropriate labels.

The native histogram samples in `b` are treated each individually as a separate
histogram to calculate the quantile from.

As long as no naming collisions arise, `b` may contain a mix of conventional
and native histograms.

Use the `rate()` function to specify the time window for the quantile
calculation.

Example: A histogram metric is called `http_request_duration_seconds` (and
therefore the metric name for the buckets of a conventional histogram is
`http_request_duration_seconds_bucket`). To calculate the 90th percentile of request
durations over the last 10m, use the following expression in case
`http_request_duration_seconds` is a conventional histogram:

    histogram_quantile(0.9, rate(http_request_duration_seconds_bucket[10m]))

For a native histogram, use the following expression instead:

    histogram_quantile(0.9, rate(http_request_duration_seconds[10m]))

The quantile is calculated for each label combination in
`http_request_duration_seconds`. To aggregate, use the `sum()` aggregator
around the `rate()` function. Since the `le` label is required by
`histogram_quantile()` to deal with conventional histograms, it has to be
included in the `by` clause. The following expression aggregates the 90th
percentile by `job` for conventional histograms:

    histogram_quantile(0.9, sum by (job, le) (rate(http_request_duration_seconds_bucket[10m])))

When aggregating native histograms, the expression simplifies to:

    histogram_quantile(0.9, sum by (job) (rate(http_request_duration_seconds[10m])))

To aggregate all conventional histograms, specify only the `le` label:

    histogram_quantile(0.9, sum by (le) (rate(http_request_duration_seconds_bucket[10m])))

With native histograms, aggregating everything works as usual without any `by` clause:

    histogram_quantile(0.9, sum(rate(http_request_duration_seconds[10m])))

The `histogram_quantile()` function interpolates quantile values by
assuming a linear distribution within a bucket.

If `b` has 0 observations, `NaN` is returned. For φ < 0, `-Inf` is
returned. For φ > 1, `+Inf` is returned. For φ = `NaN`, `NaN` is returned.

The following is only relevant for conventional histograms: If `b` contains
fewer than two buckets, `NaN` is returned. The highest bucket must have an
upper bound of `+Inf`. (Otherwise, `NaN` is returned.) If a quantile is located
in the highest bucket, the upper bound of the second highest bucket is
returned. A lower limit of the lowest bucket is assumed to be 0 if the upper
bound of that bucket is greater than
0. In that case, the usual linear interpolation is applied within that
bucket. Otherwise, the upper bound of the lowest bucket is returned for
quantiles located in the lowest bucket.

## `holt_winters()`

`holt_winters(v range-vector, sf scalar, tf scalar)` produces a smoothed value
for time series based on the range in `v`. The lower the smoothing factor `sf`,
the more importance is given to old data. The higher the trend factor `tf`, the
more trends in the data is considered. Both `sf` and `tf` must be between 0 and
1.

`holt_winters` should only be used with gauges.

## `hour()`

`hour(v=vector(time()) instant-vector)` returns the hour of the day
for each of the given times in UTC. Returned values are from 0 to 23.

## `idelta()`

`idelta(v range-vector)` calculates the difference between the last two samples
in the range vector `v`, returning an instant vector with the given deltas and
equivalent labels.

`idelta` should only be used with gauges.

## `increase()`

`increase(v range-vector)` calculates the increase in the
time series in the range vector. Breaks in monotonicity (such as counter
resets due to target restarts) are automatically adjusted for. The
increase is extrapolated to cover the full time range as specified
in the range vector selector, so that it is possible to get a
non-integer result even if a counter increases only by integer
increments.

The following example expression returns the number of HTTP requests as measured
over the last 5 minutes, per time series in the range vector:

```
increase(http_requests_total{job="api-server"}[5m])
```

`increase` acts on native histograms by calculating a new histogram where each
compononent (sum and count of observations, buckets) is the increase between
the respective component in the first and last native histogram in
`v`. However, each element in `v` that contains a mix of float and native
histogram samples within the range, will be missing from the result vector.

`increase` should only be used with counters and native histograms where the
components behave like counters. It is syntactic sugar for `rate(v)` multiplied
by the number of seconds under the specified time range window, and should be
used primarily for human readability.  Use `rate` in recording rules so that
increases are tracked consistently on a per-second basis.

## `irate()`

`irate(v range-vector)` calculates the per-second instant rate of increase of
the time series in the range vector. This is based on the last two data points.
Breaks in monotonicity (such as counter resets due to target restarts) are
automatically adjusted for.

The following example expression returns the per-second rate of HTTP requests
looking up to 5 minutes back for the two most recent data points, per time
series in the range vector:

```
irate(http_requests_total{job="api-server"}[5m])
```

`irate` should only be used when graphing volatile, fast-moving counters.
Use `rate` for alerts and slow-moving counters, as brief changes
in the rate can reset the `FOR` clause and graphs consisting entirely of rare
spikes are hard to read.

Note that when combining `irate()` with an
[aggregation operator](operators.md#aggregation-operators) (e.g. `sum()`)
or a function aggregating over time (any function ending in `_over_time`),
always take a `irate()` first, then aggregate. Otherwise `irate()` cannot detect
counter resets when your target restarts.

## `label_join()`

For each timeseries in `v`, `label_join(v instant-vector, dst_label string, separator string, src_label_1 string, src_label_2 string, ...)` joins all the values of all the `src_labels`
using `separator` and returns the timeseries with the label `dst_label` containing the joined value.
There can be any number of `src_labels` in this function.

This example will return a vector with each time series having a `foo` label with the value `a,b,c` added to it:

```
label_join(up{job="api-server",src1="a",src2="b",src3="c"}, "foo", ",", "src1", "src2", "src3")
```

## `label_replace()`

For each timeseries in `v`, `label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)`
matches the regular expression `regex` against the value of the label `src_label`. If it
matches, the value of the label `dst_label` in the returned timeseries will be the expansion
of `replacement`, together with the original labels in the input. Capturing groups in the
regular expression can be referenced with `$1`, `$2`, etc. If the regular expression doesn't
match then the timeseries is returned unchanged.

This example will return timeseries with the values `a:c` at label `service` and `a` at label `foo`:

```
label_replace(up{job="api-server",service="a:c"}, "foo", "$1", "service", "(.*):.*")
```

## `ln()`

`ln(v instant-vector)` calculates the natural logarithm for all elements in `v`.
Special cases are:

* `ln(+Inf) = +Inf`
* `ln(0) = -Inf`
* `ln(x < 0) = NaN`
* `ln(NaN) = NaN`

## `log2()`

`log2(v instant-vector)` calculates the binary logarithm for all elements in `v`.
The special cases are equivalent to those in `ln`.

## `log10()`

`log10(v instant-vector)` calculates the decimal logarithm for all elements in `v`.
The special cases are equivalent to those in `ln`.

## `minute()`

`minute(v=vector(time()) instant-vector)` returns the minute of the hour for each
of the given times in UTC. Returned values are from 0 to 59.

## `month()`

`month(v=vector(time()) instant-vector)` returns the month of the year for each
of the given times in UTC. Returned values are from 1 to 12, where 1 means
January etc.

## `predict_linear()`

`predict_linear(v range-vector, t scalar)` predicts the value of time series
`t` seconds from now, based on the range vector `v`, using [simple linear
regression](https://en.wikipedia.org/wiki/Simple_linear_regression).
The range vector must have at least two samples in order to perform the
calculation. When `+Inf` or `-Inf` are found in the range vector,
the slope and offset value calculated will be `NaN`.

`predict_linear` should only be used with gauges.

## `rate()`

`rate(v range-vector)` calculates the per-second average rate of increase of the
time series in the range vector. Breaks in monotonicity (such as counter
resets due to target restarts) are automatically adjusted for. Also, the
calculation extrapolates to the ends of the time range, allowing for missed
scrapes or imperfect alignment of scrape cycles with the range's time period.

The following example expression returns the per-second rate of HTTP requests as measured
over the last 5 minutes, per time series in the range vector:

```
rate(http_requests_total{job="api-server"}[5m])
```

`rate` acts on native histograms by calculating a new histogram where each
compononent (sum and count of observations, buckets) is the rate of increase
between the respective component in the first and last native histogram in
`v`. However, each element in `v` that contains a mix of float and native
histogram samples within the range, will be missing from the result vector.

`rate` should only be used with counters and native histograms where the
components behave like counters. It is best suited for alerting, and for
graphing of slow-moving counters.

Note that when combining `rate()` with an aggregation operator (e.g. `sum()`)
or a function aggregating over time (any function ending in `_over_time`),
always take a `rate()` first, then aggregate. Otherwise `rate()` cannot detect
counter resets when your target restarts.

## `resets()`

For each input time series, `resets(v range-vector)` returns the number of
counter resets within the provided time range as an instant vector. Any
decrease in the value between two consecutive samples is interpreted as a
counter reset.

`resets` should only be used with counters.

## `round()`

`round(v instant-vector, to_nearest=1 scalar)` rounds the sample values of all
elements in `v` to the nearest integer. Ties are resolved by rounding up. The
optional `to_nearest` argument allows specifying the nearest multiple to which
the sample values should be rounded. This multiple may also be a fraction.

## `scalar()`

Given a single-element input vector, `scalar(v instant-vector)` returns the
sample value of that single element as a scalar. If the input vector does not
have exactly one element, `scalar` will return `NaN`.

## `sgn()`

`sgn(v instant-vector)` returns a vector with all sample values converted to their sign, defined as this: 1 if v is positive, -1 if v is negative and 0 if v is equal to zero.

## `sort()`

`sort(v instant-vector)` returns vector elements sorted by their sample values,
in ascending order.

## `sort_desc()`

Same as `sort`, but sorts in descending order.

## `sqrt()`

`sqrt(v instant-vector)` calculates the square root of all elements in `v`.

## `time()`

`time()` returns the number of seconds since January 1, 1970 UTC. Note that
this does not actually return the current time, but the time at which the
expression is to be evaluated.

## `timestamp()`

`timestamp(v instant-vector)` returns the timestamp of each of the samples of
the given vector as the number of seconds since January 1, 1970 UTC.

## `vector()`

`vector(s scalar)` returns the scalar `s` as a vector with no labels.

## `year()`

`year(v=vector(time()) instant-vector)` returns the year
for each of the given times in UTC.

## `<aggregation>_over_time()`

The following functions allow aggregating each series of a given range vector
over time and return an instant vector with per-series aggregation results:

* `avg_over_time(range-vector)`: the average value of all points in the specified interval.
* `min_over_time(range-vector)`: the minimum value of all points in the specified interval.
* `max_over_time(range-vector)`: the maximum value of all points in the specified interval.
* `sum_over_time(range-vector)`: the sum of all values in the specified interval.
* `count_over_time(range-vector)`: the count of all values in the specified interval.
* `quantile_over_time(scalar, range-vector)`: the φ-quantile (0 ≤ φ ≤ 1) of the values in the specified interval.
* `stddev_over_time(range-vector)`: the population standard deviation of the values in the specified interval.
* `stdvar_over_time(range-vector)`: the population standard variance of the values in the specified interval.
* `last_over_time(range-vector)`: the most recent point value in specified interval.
* `present_over_time(range-vector)`: the value 1 for any series in the specified interval.

Note that all values in the specified interval have the same weight in the
aggregation even if the values are not equally spaced throughout the interval.

## Trigonometric Functions

The trigonometric functions work in radians:

- `acos(v instant-vector)`: calculates the arccosine of all elements in `v` ([special cases](https://pkg.go.dev/math#Acos)).
- `acosh(v instant-vector)`: calculates the inverse hyperbolic cosine of all elements in `v` ([special cases](https://pkg.go.dev/math#Acosh)).
- `asin(v instant-vector)`: calculates the arcsine of all elements in `v` ([special cases](https://pkg.go.dev/math#Asin)).
- `asinh(v instant-vector)`: calculates the inverse hyperbolic sine of all elements in `v` ([special cases](https://pkg.go.dev/math#Asinh)).
- `atan(v instant-vector)`: calculates the arctangent of all elements in `v` ([special cases](https://pkg.go.dev/math#Atan)).
- `atanh(v instant-vector)`: calculates the inverse hyperbolic tangent of all elements in `v` ([special cases](https://pkg.go.dev/math#Atanh)).
- `cos(v instant-vector)`: calculates the cosine of all elements in `v` ([special cases](https://pkg.go.dev/math#Cos)).
- `cosh(v instant-vector)`: calculates the hyperbolic cosine of all elements in `v` ([special cases](https://pkg.go.dev/math#Cosh)).
- `sin(v instant-vector)`: calculates the sine of all elements in `v` ([special cases](https://pkg.go.dev/math#Sin)).
- `sinh(v instant-vector)`: calculates the hyperbolic sine of all elements in `v` ([special cases](https://pkg.go.dev/math#Sinh)).
- `tan(v instant-vector)`: calculates the tangent of all elements in `v` ([special cases](https://pkg.go.dev/math#Tan)).
- `tanh(v instant-vector)`: calculates the hyperbolic tangent of all elements in `v` ([special cases](https://pkg.go.dev/math#Tanh)).

The following are useful for converting between degrees and radians:

- `deg(v instant-vector)`: converts radians to degrees for all elements in `v`.
- `pi()`: returns pi.
- `rad(v instant-vector)`: converts degrees to radians for all elements in `v`.


text:
'use strict'; // camunda guys are using strict mode as well, might make sense
// for us, too

ngDefine('cockpit.plugin.statistics-plugin.controllers', function(module) {

  module.controller('timeChartCtrl', [ '$scope', 'DataFactory',
      function($scope, DataFactory) {

        function getDurations() {
          DataFactory.durations().success(function(data) {

            var values = [];
            $scope.data = [];
            // later when get takes parameters different
            // keys for different processes
            var ended = {
              "key" : "Ended Process Instances",
              "values" : []
            };
            $scope.data.push(ended);
            angular.forEach(data, function(startingTimeAndDuration) {
              $scope.data[0].values.push(startingTimeAndDuration);
            }, values);
            console.log($scope.data);

          });
        }
        ;

        getDurations();

        var parseDate = d3.time.format("%Y-%m-%dT%H:%M:%S").parse;

        $scope.options = {
          chart : {
            type : 'scatterChart',
            height : 500,
            width : 1500,
            x : function(d) {
              return parseDate(d.startingTime);
            },
            y : function(d) {
              return d.duration;
            },
            showLabels : true,
            transitionDuration : 500,
            labelThreshold : 0.01,
            legend : {
              margin : {
                top : 5,
                right : 35,
                bottom : 5,
                left : 0
              }
            }
          }
        };

      } ]);
});


text:
using CsProjParser.Models;
using System;
using System.Linq;

namespace CsProjParser
{
    public static class ProjectExtensions
    {
        public static Tree<Item> ToDependencyTree(this Project project)
        {
            var tree = new Tree<Item>();

            tree.Nodes.Add(
                new Node<Item>
                {
                    Value = new Project { Name = project.Name }
                });

            tree.Nodes.AddRange(project.AssemblyReferences.Select(c =>
                new Node<Item>
                {
                    Value = new Assembly { Name = c.Name }
                }));

            tree.Nodes.AddRange(project.ProjectReferences.Select(c =>
                new Node<Item>
                {
                    Value = new Project { Name = c.Name }
                }));

            tree.Edges.AddRange(project.AssemblyReferences.Select(c =>
                new Edge<Item>
                {
                    Item1 = tree.Nodes.First(d => d.Value.Equals(project)),
                    Item2 = tree.Nodes.First(d => d.Value.Equals(c)),
                }));

            tree.Edges.AddRange(project.ProjectReferences.Select(c =>
                new Edge<Item>
                {
                    Item1 = tree.Nodes.First(d => d.Value.Equals(project)),
                    Item2 = tree.Nodes.First(d => d.Value.Equals(c)),
                }));

            return tree;
        }
    }
}


text:
package com.example.administrator.musicstart.activity;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.musicstart.bean.Music;
import com.example.administrator.musicstart.R;

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

public class MainActivity extends Activity {

    public static boolean prepared;
    public static Boolean tag;
    public static int position;

    private  Cursor cursor;
    private ListView lv_musicname;
    private List<Music> musicsList =new ArrayList<Music>();;
    private long mFistBackKeyPressTime = -1;
    private long mLastBackKeyPressTime = -1;
    private static long INTERVAL = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        lv_musicname = (ListView)this.findViewById(R.id.Lv_musicname);
        //musicsList = new ArrayList<Music>();

        cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null);

        if(cursor!=null&&cursor.getCount()>0)
        {
            while(cursor.moveToNext()){
                int id = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
                String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                int duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                long size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                Music music = new Music();
                music.setId(id);
                music.setName(tilte);
                music.setAlbum(album);
                music.setArtist(artist);
                music.setUrl(url);
                music.setDuration(duration);
                music.setSize(size);
                musicsList.add(music);
            }
            lv_musicname.setAdapter(new myListAdapter());
        }

         lv_musicname.setOnItemClickListener(new ListListener());
        findViewById(R.id.skip).setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                tag = false;
            }
        });
    }
    private class ListListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position1, long id) {
            position = position1;
            tag = true;
            intent(position);
        }
    }
    private void intent(int position){
        Intent it =new Intent(MainActivity.this,musicPlayActivity.class);
        Music music = (Music) musicsList.get(position);

        it.putExtra("position",position);
        //it.putExtra("name",music.getName());
       // it.putExtra("artist",music.getArtist());
        //it.putExtra("path",music.getUrl());
        //it.putExtra("count",musicsList.size());
        Bundle bundle=new Bundle();
        bundle.putParcelableArrayList("list", (ArrayList)musicsList);
        it.putExtras(bundle);

        startActivity(it);

        overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
    }
    public  class myListAdapter extends BaseAdapter{

        @Override
        public int getCount() {

            return musicsList.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

           View view;
            if(convertView == null)
            {
               view = View.inflate(getApplicationContext(),R.layout.usic_item,null);

            }else
            {
                view = convertView;
            }
            TextView name = (TextView)view.findViewById(R.id.tv_musicname);
            TextView artist = (TextView)view.findViewById(R.id.tv_musicartist);
            Music music = (Music) musicsList.get(position);
            name.setText(music.getName());
            artist.setText(music.getArtist());

            return view;
        }
    }

    //按"返回"两次退出程序
    @Override
    public void onBackPressed() {
        if(mFistBackKeyPressTime == -1){
            mFistBackKeyPressTime = System.currentTimeMillis();
            Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_LONG).show();

        }else{
            mLastBackKeyPressTime = System.currentTimeMillis();
            if((mLastBackKeyPressTime-mFistBackKeyPressTime) <= INTERVAL){
                prepared = false;
                if(musicPlayActivity.mPlayer!=null){
                    musicPlayActivity.mPlayer.reset();

                }

                AppManager.getAppManager().finishActivity();
            }else{
                mFistBackKeyPressTime = mLastBackKeyPressTime;
                Toast.makeText(getApplicationContext(),"再按一次退出程序",Toast.LENGTH_LONG).show();
            }
        }
    }
}


text:
package lsh.ext.gson.ext.java.time;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.stream.Stream;
import javax.annotation.Nullable;

import lsh.ext.gson.adapters.AbstractTypeAdapterTest;
import org.junit.jupiter.params.provider.Arguments;

public final class LocalDateTypeAdapterTest
		extends AbstractTypeAdapterTest<LocalDate, LocalDate> {

	@Nullable
	@Override
	protected LocalDate finalize(@Nullable final LocalDate value) {
		return value;
	}

	@Override
	protected Stream<Arguments> source() {
		return Stream.of(
				test(
						LocalDateTypeAdapter.getInstance(),
						"\"2018-01-01\"",
						() -> LocalDate.of(2018, 01, 01)
				),
				test(
						LocalDateTypeAdapter.getInstance(DateTimeFormatter.ISO_LOCAL_DATE),
						"\"2018-01-01\"",
						() -> LocalDate.of(2018, 01, 01)
				)
		);
	}

}


text:
'use strict';

import winjs = require('vs/base/common/winjs.base');
import URI from 'vs/base/common/uri';
import EditorCommon = require('vs/editor/common/editorCommon');
import Modes = require('vs/editor/common/modes');
import Monarch = require('vs/editor/common/modes/monarch/monarch');
import Types = require('vs/editor/common/modes/monarch/monarchTypes');
import Compile = require('vs/editor/common/modes/monarch/monarchCompile');
import lessWorker = require('vs/languages/less/common/lessWorker');
import {cssTokenTypes} from 'vs/languages/css/common/css';
import supports = require('vs/editor/common/modes/supports');
import {AbstractMode} from 'vs/editor/common/modes/abstractMode';
import {OneWorkerAttr} from 'vs/platform/thread/common/threadService';
import {AsyncDescriptor2, createAsyncDescriptor2} from 'vs/platform/instantiation/common/descriptors';
import {IModeService} from 'vs/editor/common/services/modeService';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {IThreadService} from 'vs/platform/thread/common/thread';
import {IModelService} from 'vs/editor/common/services/modelService';

export var language: Types.ILanguage = <Types.ILanguage> {
	displayName: 'LESS',
	name: 'less',

	// TODO@Martin: This definition does not work with umlauts for example
	wordDefinition: /(#?-?\d*\.\d\w*%?)|([@#!.:]?[\w-?]+%?)|[@#!.]/g,

	defaultToken: '',

	lineComment: '//',
	blockCommentStart: '/*',
	blockCommentEnd: '*/',

	identifier: '-?-?([a-zA-Z]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))([\\w\\-]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))*',
	identifierPlus: '-?-?([a-zA-Z:.]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))([\\w\\-:.]|(\\\\(([0-9a-fA-F]{1,6}\\s?)|[^[0-9a-fA-F])))*',

	brackets: [
		{ open: '{', close: '}', token: 'punctuation.curly' },
		{ open: '[', close: ']', token: 'punctuation.bracket' },
		{ open: '(', close: ')', token: 'punctuation.parenthesis' },
		{ open: '<', close: '>', token: 'punctuation.angle' }
	],

	tokenizer: {
		root: <any[]>[
			{ include: '@nestedJSBegin' },

			['[ \\t\\r\\n]+', ''],

			{ include: '@comments' },
			{ include: '@keyword' },
			{ include: '@strings' },
			{ include: '@numbers' },
			['[*_]?[a-zA-Z\\-\\s]+(?=:.*(;|(\\\\$)))', cssTokenTypes.TOKEN_PROPERTY, '@attribute'],

			['url(\\-prefix)?\\(', { token: 'function', bracket: '@open', next: '@urldeclaration'}],

			['[{}()\\[\\]]', '@brackets'],
			['[,:;]', 'punctuation'],

			['#@identifierPlus', cssTokenTypes.TOKEN_SELECTOR + '.id'],
			['&', cssTokenTypes.TOKEN_SELECTOR_TAG],

			['\\.@identifierPlus(?=\\()', cssTokenTypes.TOKEN_SELECTOR + '.class', '@attribute'],
			['\\.@identifierPlus', cssTokenTypes.TOKEN_SELECTOR + '.class'],

			['@identifierPlus', cssTokenTypes.TOKEN_SELECTOR_TAG],
			{ include: '@operators' },

			['@(@identifier(?=[:,\\)]))', 'variable', '@attribute'],
			['@(@identifier)', 'variable'],
			['@', 'key', '@atRules']
		],

		nestedJSBegin: [
			['``', 'punctuation.backtick'],
			<any[]>['`', { token: 'punctuation.backtick', bracket: '@open', next: '@nestedJSEnd', nextEmbedded: 'text/javascript' }],
		],

		nestedJSEnd: [
			<any[]>['`', { token: 'punctuation.backtick', bracket: '@close', next: '@pop' }],
			<any[]>['.', { token: '@rematch', next: '@javascript_block' }],
		],

		javascript_block: [
			<any[]>['`', { token: '@rematch', next: '@pop', nextEmbedded: '@pop' }],
		],

		operators: [
			['[<>=\\+\\-\\*\\/\\^\\|\\~]', 'operator']
		],

		keyword: [
			['(@[\\s]*import|![\\s]*important|true|false|when|iscolor|isnumber|isstring|iskeyword|isurl|ispixel|ispercentage|isem|hue|saturation|lightness|alpha|lighten|darken|saturate|desaturate|fadein|fadeout|fade|spin|mix|round|ceil|floor|percentage)\\b', 'keyword']
		],

		urldeclaration: [
			{ include: '@strings'},
			[ '[^)\r\n]+', 'string' ],
			['\\)', { token: 'tag', bracket: '@close', next: '@pop'}],
		],

		attribute: <any[]>[
			{ include: '@nestedJSBegin' },
			{ include: '@comments' },
			{ include: '@strings' },
			{ include: '@numbers' },

			{ include: '@keyword' },

			['[a-zA-Z\\-]+(?=\\()', cssTokenTypes.TOKEN_VALUE, '@attribute'],
			['>', 'operator', '@pop'],
			['@identifier', cssTokenTypes.TOKEN_VALUE],
			{ include: '@operators' },
			['@(@identifier)', 'variable'],

			['[)\\}]', '@brackets', '@pop'],
			['[{}()\\[\\]>]', '@brackets'],

			['[;]', 'punctuation', '@pop'],
			['[,=:]', 'punctuation'],

			['\\s', ''],
			['.', cssTokenTypes.TOKEN_VALUE]
		],

		comments: [
			['\\/\\*', 'comment', '@comment'],
			['\\/\\/+.*', 'comment'],
		],

		comment: [
			['\\*\\/', 'comment', '@pop'],
			['.', 'comment'],
		],

		numbers: [
			<any[]>['(\\d*\\.)?\\d+([eE][\\-+]?\\d+)?', { token: cssTokenTypes.TOKEN_VALUE + '.numeric', next: '@units' }],
			['#[0-9a-fA-F_]+(?!\\w)', cssTokenTypes.TOKEN_VALUE + '.rgb-value']
		],

		units: [
			['((em|ex|ch|rem|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)\\b)?', cssTokenTypes.TOKEN_VALUE + '.unit', '@pop']
		],

		strings: [
			<any[]>['~?"', { token: 'string.punctuation', bracket: '@open', next: '@stringsEndDoubleQuote' }],
			<any[]>['~?\'', { token: 'string.punctuation', bracket: '@open', next: '@stringsEndQuote' }]
		],

		stringsEndDoubleQuote: [
			['\\\\"', 'string'],
			<any[]>['"', { token: 'string.punctuation', next: '@popall', bracket: '@close' }],
			['.', 'string']
		],

		stringsEndQuote: [
			['\\\\\'', 'string'],
			<any[]>['\'', { token: 'string.punctuation', next: '@popall', bracket: '@close' }],
			['.', 'string']
		],

		atRules: <any[]>[
			{ include: '@comments' },
			{ include: '@strings' },
			['[()]', 'punctuation'],
			['[\\{;]', 'punctuation', '@pop'],
			['.', 'key']
		]
	}
};

export class LESSMode extends Monarch.MonarchMode<lessWorker.LessWorker> implements Modes.IExtraInfoSupport, Modes.IOutlineSupport {

	public referenceSupport: Modes.IReferenceSupport;
	public logicalSelectionSupport: Modes.ILogicalSelectionSupport;
	public extraInfoSupport: Modes.IExtraInfoSupport;
	public declarationSupport: Modes.IDeclarationSupport;
	public outlineSupport: Modes.IOutlineSupport;
	public suggestSupport: Modes.ISuggestSupport;

	private modeService: IModeService;

	constructor(
		descriptor:Modes.IModeDescriptor,
		@IInstantiationService instantiationService: IInstantiationService,
		@IThreadService threadService: IThreadService,
		@IModeService modeService: IModeService,
		@IModelService modelService: IModelService
	) {
		super(descriptor, Compile.compile(language), instantiationService, threadService, modeService, modelService);

		this.modeService = modeService;

		this.extraInfoSupport = this;
		this.referenceSupport = new supports.ReferenceSupport(this, {
			tokens: [cssTokenTypes.TOKEN_PROPERTY + '.less', cssTokenTypes.TOKEN_VALUE + '.less', 'variable.less', cssTokenTypes.TOKEN_SELECTOR + '.class.less', cssTokenTypes.TOKEN_SELECTOR + '.id.less', 'selector.less'],
			findReferences: (resource, position, /*unused*/includeDeclaration) => this.findReferences(resource, position)});
		this.logicalSelectionSupport = this;
		this.declarationSupport = new supports.DeclarationSupport(this, {
			tokens: ['variable.less', cssTokenTypes.TOKEN_SELECTOR + '.class.less', cssTokenTypes.TOKEN_SELECTOR + '.id.less', 'selector.less'],
			findDeclaration: (resource, position) => this.findDeclaration(resource, position)});
		this.outlineSupport = this;

		this.suggestSupport = new supports.SuggestSupport(this, {
			triggerCharacters: [],
			excludeTokens: ['comment.less', 'string.less'],
			suggest: (resource, position) => this.suggest(resource, position)});
	}

	protected _getWorkerDescriptor(): AsyncDescriptor2<Modes.IMode, Modes.IWorkerParticipant[], lessWorker.LessWorker> {
		return createAsyncDescriptor2('vs/languages/less/common/lessWorker', 'LessWorker');
	}

	_worker<T>(runner:(worker:lessWorker.LessWorker)=>winjs.TPromise<T>): winjs.TPromise<T> {
		// TODO@Alex: workaround for missing `bundles` config, before instantiating the lessWorker, we ensure the cssWorker has been loaded
		return this.modeService.getOrCreateMode('css').then((cssMode) => {
			return (<AbstractMode<any>>cssMode)._worker((worker) => winjs.TPromise.as(true));
		}).then(() => {
			return super._worker(runner);
		});
	}

	static $findReferences = OneWorkerAttr(LESSMode, LESSMode.prototype.findReferences);
	public findReferences(resource:URI, position:EditorCommon.IPosition):winjs.TPromise<Modes.IReference[]> {
		return this._worker((w) => w.findReferences(resource, position));
	}

	static $getRangesToPosition = OneWorkerAttr(LESSMode, LESSMode.prototype.getRangesToPosition);
	public getRangesToPosition(resource:URI, position:EditorCommon.IPosition):winjs.TPromise<Modes.ILogicalSelectionEntry[]> {
		return this._worker((w) => w.getRangesToPosition(resource, position));
	}

	static $computeInfo = OneWorkerAttr(LESSMode, LESSMode.prototype.computeInfo);
	public computeInfo(resource:URI, position:EditorCommon.IPosition): winjs.TPromise<Modes.IComputeExtraInfoResult> {
		return this._worker((w) => w.computeInfo(resource, position));
	}

	static $getOutline = OneWorkerAttr(LESSMode, LESSMode.prototype.getOutline);
	public getOutline(resource:URI):winjs.TPromise<Modes.IOutlineEntry[]> {
		return this._worker((w) => w.getOutline(resource));
	}

	static $findDeclaration = OneWorkerAttr(LESSMode, LESSMode.prototype.findDeclaration);
	public findDeclaration(resource:URI, position:EditorCommon.IPosition):winjs.TPromise<Modes.IReference> {
		return this._worker((w) => w.findDeclaration(resource, position));
	}

	static $findColorDeclarations = OneWorkerAttr(LESSMode, LESSMode.prototype.findColorDeclarations);
	public findColorDeclarations(resource:URI):winjs.TPromise<{range:EditorCommon.IRange; value:string; }[]> {
		return this._worker((w) => w.findColorDeclarations(resource));
	}
}


text:
$:.unshift(File.expand_path(File.dirname(__FILE__)) + "/../lib")

require 'rubygems'
require 'benchmark-config'
require 'benchmark-result'

config = BenchmarkConfig.instance.reset
config.read_latency["result_file"] = ARGV[0]
result_file = ReadLatencyResult.new(config)
result_file.load

new_rows = []
result_file.each_legend(1) do |legend, rows|
  first = new_rows.empty?
  rows.each_with_index do |row, i|
    if first
      new_rows.push(["History duration [sec]", "History duration [day]"]) if i == 0
      new_rows.push([row[2].to_i, (row[2].to_i / 60 / 60 / 24)])
    end

    new_rows[0].push("#{legend} monitoring targets") if i == 0
    new_rows[i + 1].push(row[3])
  end
end

open(ARGV[1], "w") do |file|
  new_rows.each do |row|
    file << "#{row.join(",")}\n"
  end
end


text:
struct coroutine_impl;

struct coroutine
{
	using yield = std::function<void()>;
	using body  = std::function<void(yield&&)>;

	class stop: public std::exception {};

	coroutine();
	coroutine(coroutine&& other);

	coroutine(body);
	~coroutine();

	bool operator()();
	explicit operator bool() const { return bool(p); }

private:
	std::unique_ptr<coroutine_impl> p;
	friend bool operator==(const coroutine& a, const coroutine& b);
};

inline bool operator==(const coroutine& a, const coroutine& b) {return a.p == b.p;}
inline bool operator!=(const coroutine& a, const coroutine& b) {return !(a == b);}


text:
@implementation ClayRelaxer

- (id)initWithCells:(NSMutableArray *)cellArray
{
    self = [super init];
    if (self) {
        cells = [[NSMutableArray alloc] initWithArray:cellArray];
        newSites = [[NSMutableArray alloc] init];

    }
    return self;
}

// Return an NSMutableArray of NSValues that encode NSPoints that
// can be used to regenerate the Voronoi diagram
+ (NSMutableArray *)relaxSitesInCells:(NSMutableArray *)cellArray
{
    ClayRelaxer *cr = [[ClayRelaxer alloc] initWithCells:cellArray];
    [cr processCells];
    return [cr newSites];

}

- (void)processCells
{
    //NSLog(@"Processing Cells...");
    // Iterate through each cell, process its sites, and then
    // put the new site into the newSites array.
    for (Cell *c in cells) {

        // Put the point from the cell into this array, which we'll process
        NSMutableArray *cellPoints = [[NSMutableArray alloc] init];

        for (Halfedge *he in [c halfedges]) {
            // Get the start point from each halfedge
            // and thereby avoid getting duplicates
            // (vs. getting both points).
            Vertex *start = [he getStartpoint];
            [cellPoints addObject:[NSValue valueWithCGPoint:[start coord]]];
        }

        double newX = 0;
        double newY = 0;
        double countPoints = 0;

        for (NSValue *v in cellPoints) {
            newX += [v CGPointValue].x;
            newY += [v CGPointValue].y;
            countPoints += 1;
        }

        newX = newX / countPoints;
        newY = newY / countPoints;

        [newSites addObject:[NSValue valueWithCGPoint:CGPointMake(newX, newY)]];
    }
    //NSLog(@"...completed processing cells.");
}

- (NSMutableArray *)newSites
{
    return newSites;
}

@end


text:
[![NPM version][npm-image]][npm-url]
[![Build Status][travis-image]][travis-url]
[![Coverage Status][codecov-image]][codecov-url]
[![Dependency Status][daviddm-image]][daviddm-url]
[![DevDependency Status][daviddm-dev-image]][daviddm-dev-url]
[![License][license-image]][license-url]

Helper of Hubot Scripts for implementing schedule tasks.

You can implement scheduled tasks to your hubot scripts easily.
And, scheduled tasks are stored to "Hubot brain".

## Installation

```
npm install --save @moqada/hubot-schedule-helper
```

## Usage

See [example scripts](https://github.com/moqada/hubot-schedule-helper/blob/master/example/scripts/example.coffee).
More detail, see [API Document](https://moqada.github.io/hubot-schedule-helper/).

```coffee
{Scheduler, Job} = require '@moqada/hubot-schedule-helper'
storeKey = 'hubot-scheule-helper-example:schedule'

# You must define your Job class extending Job

class AwesomeJob extends Job

  # You must implement exec method
  exec: (robot) ->
    envelope = @getEnvelope()
    {message} = @meta
    robot.send envelope, message

module.exports = (robot) ->
  scheduler = new Scheduler({robot, storeKey, job: AwesomeJob})

  # Add scheduled job (send 'hello! hello!' at every 6 o'clock)
  robot.respond /add/i, (res) ->
    {user} = res.message
    meta = {message: 'hello! hello!'}
    pattern = '* 6 * * *'  # every 6 o'clock
    job = scheduler.createJob({pattern, user, meta})

  # Cancel target job
  robot.respond /cancel (\d+)$/i, (res) ->
    [id] = res.match.slice(1)
    scheduler.cancelJob(id)

  # List job
  robot.respond /list$/i, (res) ->
    msgs = []
    for job of scheduler.jobs
      msgs.push "#{job.id}: \"#{job.pattern}\" #{job.getRoom()} #{job.meta.message}"
    res.send msgs.join('\n')

  # Update target job
  robot.respond /update (\d+) (.+)$/i, (res) ->
    [id, message] = res.match.slice(1)
    meta = {message}
    scheduler.updateJob(id, meta)
```

## Related

This module's code is greatly inspired by [hubot-schdule](https://github.com/matsukaz/hubot-schedule).

[npm-url]: https://www.npmjs.com/package/@moqada/hubot-schedule-helper
[npm-image]: https://img.shields.io/npm/v/@moqada/hubot-schedule-helper.svg?style=flat-square
[travis-url]: https://travis-ci.org/moqada/hubot-schedule-helper
[travis-image]: https://img.shields.io/travis/moqada/hubot-schedule-helper.svg?style=flat-square
[daviddm-url]: https://david-dm.org/moqada/hubot-schedule-helper
[daviddm-image]: https://img.shields.io/david/moqada/hubot-schedule-helper.svg?style=flat-square
[daviddm-dev-url]: https://david-dm.org/moqada/hubot-schedule-helper#info=devDependencies
[daviddm-dev-image]: https://img.shields.io/david/dev/moqada/hubot-schedule-helper.svg?style=flat-square
[codecov-url]: https://codecov.io/github/moqada/hubot-schedule-helper
[codecov-image]: https://img.shields.io/codecov/c/github/moqada/hubot-schedule-helper.svg?style=flat-square
[license-url]: http://opensource.org/licenses/MIT
[license-image]: https://img.shields.io/github/license/moqada/hubot-schedule-helper.svg?style=flat-square


text:
package com.xeiam.xchange.cexio;

import java.io.InputStream;

import si.mazi.rescu.SynchronizedValueFactory;

import com.xeiam.xchange.BaseExchange;
import com.xeiam.xchange.Exchange;
import com.xeiam.xchange.ExchangeSpecification;
import com.xeiam.xchange.cexio.service.polling.CexIOAccountService;
import com.xeiam.xchange.cexio.service.polling.CexIOMarketDataService;
import com.xeiam.xchange.cexio.service.polling.CexIOTradeService;
import com.xeiam.xchange.utils.nonce.AtomicLongIncrementalTime2014NonceFactory;

public class CexIOExchange extends BaseExchange implements Exchange {

  private SynchronizedValueFactory<Long> nonceFactory = new AtomicLongIncrementalTime2014NonceFactory();

  @Override
  protected void initServices() {
    this.pollingMarketDataService = new CexIOMarketDataService(this);
    this.pollingAccountService = new CexIOAccountService(this);
    this.pollingTradeService = new CexIOTradeService(this);
  }

  @Override
  public ExchangeSpecification getDefaultExchangeSpecification() {

    ExchangeSpecification exchangeSpecification = new ExchangeSpecification(this.getClass().getCanonicalName());
    exchangeSpecification.setSslUri("https://cex.io");
    exchangeSpecification.setHost("cex.io");
    exchangeSpecification.setPort(80);
    exchangeSpecification.setExchangeName("Cex IO");
    exchangeSpecification.setExchangeDescription("Cex.IO is a virtual commodities exchange registered in United Kingdom.");

    return exchangeSpecification;
  }

  @Override
  public SynchronizedValueFactory<Long> getNonceFactory() {

    return nonceFactory;
  }
}