text:
from xml.sax.handler import ContentHandler,EntityResolver
from TemplateAssetParameters import TemplateAssetParameters
from SecurityPatternParameters import SecurityPatternParameters
from Borg import Borg

def a2i(spLabel):
  if spLabel == 'Low':
    return 1
  elif spLabel == 'Medium':
    return 2
  elif spLabel == 'High':
    return 3
  else:
    return 0

def it2Id(itLabel):
  if itLabel == 'required':
    return 1
  else:
    return 0

class SecurityPatternContentHandler(ContentHandler,EntityResolver):
  def __init__(self):
    self.theAssets = []
    self.theSecurityPatterns = []
    b = Borg()
    self.configDir = b.configDir
    self.resetAssetAttributes()
    self.resetSecurityPropertyAttributes()
    self.resetPatternAttributes()

  def resolveEntity(self,publicId,systemId):
    return self.configDir + '/securitypattern.dtd'

  def patterns(self):
    return self.theSecurityPatterns

  def assets(self):
    return self.theAssets

  def resetPatternAttributes(self):
    self.inContext = 0
    self.inProblem = 0
    self.inSolution = 0
    self.inDescription = 0
    self.inRationale = 0
    self.inFitCriterion = 0
    self.theName = ''
    self.theContext = ''
    self.theProblem = ''
    self.theSolution = ''
    self.theStructure = []
    self.theRequirements = []
    self.resetStructure()
    self.resetRequirement()

  def resetAssetAttributes(self):
    self.inDescription = 0
    self.inSignificance = 0
    self.theName = ''
    self.theShortCode = ''
    self.theAssetType = ''
    self.theDescription = ''
    self.theSignificance = ''
    self.theTags = []
    self.theInterfaces = []
    self.theSecurityProperties = []

  def resetSecurityPropertyAttributes(self):
    self.thePropertyName = ''
    self.thePropertyValue = 'None'
    self.inRationale = 0
    self.theRationale = ''

  def resetStructure(self):
    self.theHeadName = ''
    self.theHeadAdornment = ''
    self.theHeadNry = ''
    self.theHeadRole = ''
    self.theTailRole = ''
    self.theTailNry = ''
    self.theTailAdornment = ''
    self.theTailName = ''

  def resetRequirement(self):
    self.theAsset = ''
    self.theType = ''
    self.theReqName = ''
    self.theDescription = ''
    self.theRationale = ''
    self.theFitCriterion = ''

  def startElement(self,name,attrs):
    self.currentElementName = name
    if name == 'asset':
      self.theName = attrs['name']
      self.theShortCode = attrs['short_code']
      self.theAssetType = attrs['type']
      self.theSecurityProperties = []
    elif name == 'tag':
      self.theTags.append(attrs['name'])
    elif name == 'interface':
      self.theInterfaces.append((attrs['name'],it2Id(attrs['type'])))
    elif name == 'security_property':
      self.thePropertyName = attrs['property']
      self.thePropertyValue = attrs['value']
    elif name == 'description':
      self.inDescription = 1
      self.theDescripton = ''
    elif name == 'significance':
      self.inSignificance = 1
      self.theSignificance = ''
    elif name == 'pattern':
      self.theName = attrs['name']
    elif name == 'structure':
      self.theHeadName = attrs['head_asset']
      self.theHeadAdornment = attrs['head_adornment']
      rawHeadNry = attrs['head_nry']
      if (rawHeadNry == 'a'):
        rawHeadNry = '*'
      elif (rawHeadNry == '1..a'):
        rawHeadNry = '1..*'
      self.theHeadNry = rawHeadNry
      self.theHeadRole = attrs['head_role']
      self.theTailRole = attrs['tail_role']
      rawTailNry = attrs['tail_nry']
      if (rawTailNry == 'a'):
        rawTailNry = '*'
      elif (rawTailNry == '1..a'):
        rawTailNry = '1..*'
      self.theTailNry = rawTailNry
      self.theTailAdornment = attrs['tail_adornment']
      self.theTailName = attrs['tail_asset']
    elif name == 'requirement':
      self.theReqName = attrs['name']
      self.theAsset = attrs['asset']
      rawType = attrs['type']
      self.theType = rawType.replace('_',' ')
    elif name == 'context':
      self.inContext = 1
      self.theContext = ''
    elif name == 'problem':
      self.inProblem = 1
      self.theProblem = ''
    elif name == 'solution':
      self.inSolution = 1
      self.theSolution = ''
    elif name == 'rationale':
      self.inRationale = 1
      self.theRationale = ''
    elif name == 'fit_criterion':
      self.inFitCriterion = 1
      self.theFitCriterion = ''

  def characters(self,data):
    if self.inDescription:
      self.theDescription += data
    elif self.inSignificance:
      self.theSignificance += data
    elif self.inContext:
      self.theContext += data
    elif self.inProblem:
      self.theProblem += data
    elif self.inSolution:
      self.theSolution += data
    elif self.inRationale:
      self.theRationale += data
    elif self.inFitCriterion:
      self.theFitCriterion += data

  def endElement(self,name):
    if name == 'asset':
      spDict = {}
      spDict['confidentiality'] = (0,'None')
      spDict['integrity'] = (0,'None')
      spDict['availability'] = (0,'None')
      spDict['accountability'] = (0,'None')
      spDict['anonymity'] = (0,'None')
      spDict['pseudonymity'] = (0,'None')
      spDict['unlinkability'] = (0,'None')
      spDict['unobservability'] = (0,'None')
      for sp in self.theSecurityProperties:
        spName = sp[0]
        spValue = a2i(sp[1])
        spRationale = sp[2]
        if spName in spDict:
          spDict[spName] = (spValue,spRationale)
      spValues = []
      spValues.append(spDict['confidentiality'])
      spValues.append(spDict['integrity'])
      spValues.append(spDict['availability'])
      spValues.append(spDict['accountability'])
      spValues.append(spDict['anonymity'])
      spValues.append(spDict['pseudonymity'])
      spValues.append(spDict['unlinkability'])
      spValues.append(spDict['unobservability'])
      p = TemplateAssetParameters(self.theName,self.theShortCode,self.theDescription,self.theSignificance,self.theAssetType,spValues,self.theTags,self.theInterfaces)
      self.theAssets.append(p)
      self.resetAssetAttributes()
    elif name == 'security_property':
      self.theSecurityProperties.append((self.thePropertyName,self.thePropertyValue,self.theRationale))
      self.resetSecurityPropertyAttributes()
    elif name == 'pattern':
      p = SecurityPatternParameters(self.theName,self.theContext,self.theProblem,self.theSolution,self.theRequirements,self.theStructure)
      self.theSecurityPatterns.append(p)
      self.resetPatternAttributes()
    elif name == 'structure':
      self.theStructure.append((self.theHeadName,self.theHeadAdornment,self.theHeadNry,self.theHeadRole,self.theTailRole,self.theTailNry,self.theTailAdornment,self.theTailName))
      self.resetStructure()
    elif name == 'requirement':
      self.theRequirements.append((self.theReqName,self.theDescription,self.theType,self.theRationale,self.theFitCriterion,self.theAsset))
      self.resetRequirement()
    elif name == 'description':
      self.inDescription = 0
    elif name == 'rationale':
      self.inRationale = 0
    elif name == 'significance':
      self.inSignificance = 0
    elif name == 'context':
      self.inContext = 0
    elif name == 'problem':
      self.inProblem = 0
    elif name == 'solution':
      self.inSolution = 0
    elif name == 'fit_criterion':
      self.inFitCriterion = 0


text:
package com.github.sreepadbhagwat.aplos.platform;

import com.github.sreepadbhagwat.aplos.api.AplosAppium;
import com.github.sreepadbhagwat.aplos.appium.ios.AplosAppiumIOS;

public class AppiumIOSService<AplosAppium> implements Platform{

	public AppiumIOSService(){

	}

	@Override
	public String getName() {
		// TODO Auto-generated method stub
		//System.out.println("getname inside appium service");
		return "IOS";
	}

	@Override
	public com.github.sreepadbhagwat.aplos.api.AplosAppium getPlatform() {
		// TODO Auto-generated method stub
		AplosAppium iosPlatform = (AplosAppium) new AplosAppiumIOS();
		return (com.github.sreepadbhagwat.aplos.api.AplosAppium) iosPlatform;
	}

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop;

import java.io.IOException;

import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reporter;

// Mapper that fails
public class FailMapper extends MapReduceBase implements
    Mapper<WritableComparable, Writable, WritableComparable, Writable> {

  public void map(WritableComparable key, Writable value,
      OutputCollector<WritableComparable, Writable> out, Reporter reporter)
      throws IOException {
    // NOTE- the next line is required for the TestDebugScript test to succeed
    System.err.println("failing map");
    throw new RuntimeException("failing map");
  }
}


text:
<?php

namespace Omnipay\VirtualMerchant;

use Omnipay\VirtualMerchant\Message\AuthorizeRequest;
use Omnipay\VirtualMerchant\Message\PurchaseRequest;
use Omnipay\VirtualMerchant\Message\CaptureRequest;
use Omnipay\Common\AbstractGateway;

/**
 * Elavon VirtualMerchant  Class
 */
class Gateway extends AbstractGateway
{
    public function getName()
    {
        return 'VirtualMerchant';
    }

    public function getDefaultParameters()
    {
        return array(
            'vmMerchantId' => '',
            'vmUserId' => '',
            'vmPin' => '',
            'developerMode' => false,
        );
    }

    public function getVmMerchantId()
    {
        return $this->getParameter('vmMerchantId');
    }

    public function setVmMerchantId($value)
    {
        return $this->setParameter('vmMerchantId', $value);
    }

    public function getVmUserId()
    {
        return $this->getParameter('vmUserId');
    }

    public function setVmUserId($value)
    {
        return $this->setParameter('vmUserId', $value);
    }

    public function getVmPin()
    {
        return $this->getParameter('vmPin');
    }

    public function setVmPin($value)
    {
        return $this->setParameter('vmPin', $value);
    }

    public function getDeveloperMode()
    {
        return $this->getParameter('developerMode');
    }

    public function setDeveloperMode($value)
    {
        return $this->setParameter('developerMode', $value);
    }

    public function authorize(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\VirtualMerchant\Message\AuthorizeRequest', $parameters);
    }

    public function capture(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\VirtualMerchant\Message\CaptureRequest', $parameters);
    }

    public function purchase(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\VirtualMerchant\Message\PurchaseRequest', $parameters);
    }

    public function refund(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\VirtualMerchant\Message\RefundRequest', $parameters);
    }

    public function void(array $parameters = array())
    {
        return $this->createRequest('\Omnipay\VirtualMerchant\Message\VoidRequest', $parameters);
    }
}


text:
import {
  LinkProps,
  Link as RouterLink,
} from 'react-router-dom';

import Container from '@mui/material/Container';
import Grid from '@mui/material/Grid';
import { styled } from '@mui/material/styles';
import {
  Alert,
  AlertTitle,
  Link,
} from '@mui/material';

import CentralizedProgress from '@/components/centralized_progress/centralized_progress';
import LoadErrorAlert from '@/components/load_error_alert/load_error_alert';
import PageHeading from '@/components/headings/page_heading/page_heading';

import useFetchProjects from '@/hooks/use_fetch_projects';
import { loginLink } from '@/tools/urlHandling/links';

const ProjectCard = styled(RouterLink)<LinkProps>(() => ({
  'padding': '1rem',
  'display': 'flex',
  'justify-content': 'center',
  'align-items': 'center',
  'box-shadow': '0px 2px 1px -1px rgb(0 0 0 / 20%), 0px 1px 1px 0px rgb(0 0 0 / 14%), 0px 1px 3px 0px rgb(0 0 0 / 12%)',
  'font-size': '1.5rem',
  'text-decoration': 'none',
  'color': 'black',
  'border-radius': '4px',
  'transition': 'transform .2s',
  'height': '100%',
  '&:hover': {
    'transform': 'scale(1.1)',
  },
}));

const HomePage = () => {
  const { error, isLoading, data: projects } = useFetchProjects();
  return (
    <Container maxWidth="xl">
      <PageHeading>
        Projects
      </PageHeading>
      {
        window.isAnonymous && (
          <Alert
            severity="info"
            sx={{ mb: 2 }}>
            <AlertTitle>Some projects may be hidden</AlertTitle>
            Please <Link href={loginLink('/')}>log in</Link> to view all projects you have access to.
          </Alert>
        )
      }
      {
        isLoading && (
          <CentralizedProgress />
        )
      }
      {
        error && (
          <Grid container item>
            <LoadErrorAlert
              entityName="projects"
              error={error} />
          </Grid>
        )
      }
      <Grid container spacing={2} id="project-cards">
        {
          projects && projects.map((project) => (
            <Grid
              key={project.name}
              item xs={2}>
              <ProjectCard
                to={`/p/${project.project}/clusters`}
              >
                {project.displayName}
              </ProjectCard>
            </Grid>
          ))
        }
      </Grid>
    </Container>
  );
};

export default HomePage;


text:
package fm.pattern.valex;

import static fm.pattern.valex.PatternAssertions.assertThat;
import static fm.pattern.valex.fixtures.dsl.PlaceDSL.place;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import fm.pattern.valex.fixtures.model.Place;
import fm.pattern.valex.fixtures.service.PlaceService;

public class PlaceServiceAnnotationTest extends IntegrationTest {

    @Autowired
    private PlaceService placeService;

    @Test
    public void shouldBeAbleToCreateAPlace() {
        Place place = place().build();
        assertThat(placeService.annotationCreate(place)).accepted();
    }

    @Test
    public void shouldBeAbleToUpdateAPlace() {
        Place place = place().build();
        assertThat(placeService.annotationUpdate(place)).accepted();
    }

    @Test
    public void shouldBeAbleToDeleteAPlace() {
        Place place = place().build();
        assertThat(placeService.annotationDelete(place)).accepted();
    }

    @Test
    public void shouldNotBeAbleToCreateAPlaceAndReturnAResultIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();

        Result<Place> result = placeService.annotationCreate(place);
        assertThat(result).rejected().withError("PLC-1002", "An address is required.", UnprocessableEntityException.class);
    }

    @Test
    public void shouldNotBeAbleToUpdateAPlaceAndReturnAResultIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();

        Result<Place> result = placeService.annotationUpdate(place);
        assertThat(result).rejected().withError("PLC-1002", "An address is required.", UnprocessableEntityException.class);
    }

    @Test
    public void shouldNotBeAbleToDeleteAPlaceAndReturnAResultIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();

        Result<Place> result = placeService.annotationDelete(place);
        assertThat(result).rejected().withError("PLC-1002", "An address is required.", UnprocessableEntityException.class);
    }

    @Test
    public void shouldNotBeAbleToActionAPlaceAndReturnAResultIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();

        Result<Place> result = placeService.annotationValid(place);
        assertThat(result).rejected().withError("PLC-1002", "An address is required.", UnprocessableEntityException.class);
    }

    @Test(expected = UnprocessableEntityException.class)
    public void shouldNotBeAbleToCreateAPlaceAndThrowAnExceptionIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();
        placeService.annotationExceptionCreate(place);
    }

    @Test(expected = UnprocessableEntityException.class)
    public void shouldNotBeAbleToUpdateAPlaceAndThrowAnExceptionIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();
        placeService.annotationExceptionUpdate(place);
    }

    @Test(expected = UnprocessableEntityException.class)
    public void shouldNotBeAbleToDeleteAAndThrowAnExceptionIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();
        placeService.annotationExceptionDelete(place);
    }

    @Test(expected = UnprocessableEntityException.class)
    public void shouldNotBeAbleToActionAAndThrowAnExceptionIfThePlaceIsInvalid() {
        Place place = place().withAddress(null).build();
        placeService.annotationExceptionValid(place);
    }

}


text:
using System;
using System.Diagnostics;

namespace System.Security.Cryptography
{
    // This structure is used for returning the set of legal key sizes and
    // block sizes of the symmetric algorithms.
    public sealed class KeySizes
    {
        public KeySizes(int minSize, int maxSize, int skipSize)
        {
            MinSize = minSize;
            MaxSize = maxSize;
            SkipSize = skipSize;
        }

        public int MinSize { get; private set; }
        public int MaxSize { get; private set; }
        public int SkipSize { get; private set; }
    }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package timetable;

/**
 *
 * @author Mavrov
 */
public interface FitnessEvaluator<T extends Speciment> {

    public void evaluateFitness(T speciment);

}


text:
<?php

namespace gateways\controllers;

use gateways\GatewaysModule;
use gateways\models\ChargeRequest;
use gateways\models\enum\Result;
use gateways\models\Request;

class ApiController extends \CController {

	public function actionCheck($gatewayName) {
		$processModel = GatewaysModule::findInstance()->api->check($gatewayName, $this->getPaymentRequestModel());
		echo $processModel->responseText;
	}

	public function actionSuccess($gatewayName) {
		$processModel = GatewaysModule::findInstance()->api->end($gatewayName, Result::SUCCEED, $this->getPaymentRequestModel());

		if ($processModel->result === Result::SUCCEED) {
			// Trigger success event
			$event = new \CEvent($this, $processModel);
			$this->module->onSuccessRequest($event);
		} else {
			// Trigger failure event
			$event = new \CEvent($this, $processModel);
			$this->module->onFailureRequest($event);
		}
	}

	public function actionFailure($gatewayName) {
		$processModel = GatewaysModule::findInstance()->api->end($gatewayName, Result::FAILED, $this->getPaymentRequestModel());

		// Trigger failure event
		$event = new \CEvent($this, $processModel);
		$this->module->onFailureRequest($event);
	}

	public function actionCharge() {
		$chargeRequest = new ChargeRequest();
		$chargeRequest->attributes = $_POST;

		// Validate data, send errors
		if (!$chargeRequest->validate()) {
			echo \CJSON::encode(array(
				'errors' => $chargeRequest,
				'process' => array(),
			));
			return;
		}

		$processModel = GatewaysModule::findInstance()->api->charge($chargeRequest);
		echo \CJSON::encode(array(
			'errors' => array(),
			'process' => $processModel->attributes,
		));
	}

	/**
	 * @return \gateways\models\Request
	 */
	private function getPaymentRequestModel() {
		$request = \Yii::app()->request;
		$port = $request->port && $request->port !== 80 ? ':' . $request->port : '';
		$url = $request->hostInfo . $port . str_replace('?' . $request->queryString, '', $request->requestUri);

		$paymentRequestModel = new Request();
		$paymentRequestModel->method = $request->requestType;
		$paymentRequestModel->url = $url;
		$paymentRequestModel->params = array_merge($_GET, $_POST);

		return $paymentRequestModel;
	}
}


text:
ul.list1 li .drop, .socials a {
	behavior: url(js/PIE.htc);
	position: relative;
}

.socials a {
	margin-right: 9px;
}

#form .invalid .error-message, #form .empty .empty-message {
	display: block;
}

#form .error-message, #form .empty-message {
	display: none;
}

.cat  strong, a.gal1 strong {
	filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70);

}


text:
class User < ActiveRecord::Base
  include Invitation::User

  has_many :memberships
  has_many :companies, through: :memberships

  has_many :project_memberships
  has_many :projects, through: :project_memberships
end


text:
import { UICollapseDirective } from './collapse';
import { Type } from '@angular/core';

export const UI_COLLAPSE_DIRECTIVE: Type<any>[] = [
    UICollapseDirective
];


text:
package io.reactivex.internal.operators.maybe;

import java.util.concurrent.*;

import org.junit.Test;

import io.reactivex.Maybe;
import io.reactivex.internal.functions.Functions;

public class MaybeFromFutureTest {

    @Test
    public void cancelImmediately() {
        FutureTask<Integer> ft = new FutureTask<Integer>(Functions.justCallable(1));

        Maybe.fromFuture(ft).test(true)
        .assertEmpty();
    }

    @Test
    public void timeout() {
        FutureTask<Integer> ft = new FutureTask<Integer>(Functions.justCallable(1));

        Maybe.fromFuture(ft, 1, TimeUnit.MILLISECONDS).test()
        .awaitDone(5, TimeUnit.SECONDS)
        .assertFailure(TimeoutException.class);
    }

    @Test
    public void timedWait() {
        FutureTask<Integer> ft = new FutureTask<Integer>(Functions.justCallable(1));
        ft.run();

        Maybe.fromFuture(ft, 1, TimeUnit.MILLISECONDS).test()
        .awaitDone(5, TimeUnit.SECONDS)
        .assertResult(1);
    }

    @Test
    public void interrupt() {
        FutureTask<Integer> ft = new FutureTask<Integer>(Functions.justCallable(1));

        Thread.currentThread().interrupt();

        Maybe.fromFuture(ft, 1, TimeUnit.MILLISECONDS).test()
        .assertFailure(InterruptedException.class);
    }
}


text:
#include "global.h"
#include "gpath_store.h"
#include "util.h"

size_t gpath_store_mem(size_t graph_capacity, bool split_linked_lists)
{
  return graph_capacity*sizeof(GPath*) * (split_linked_lists ? 2 : 1);
}

// If num_paths != 0, we ensure at least num_paths capacity
// @split_linked_lists whether you intend to have traverse linked list and
//                     all linked list separate
void gpath_store_alloc(GPathStore *gpstore, size_t ncols, size_t graph_capacity,
                       size_t num_paths, size_t mem,
                       bool count_nseen, bool split_linked_lists)
{
  memset(gpstore, 0, sizeof(*gpstore));

  size_t store_mem = gpath_store_mem(graph_capacity, split_linked_lists);
  if(store_mem > mem)
    die("Need at least %zu bytes (only got %zu bytes)", store_mem, mem);

  size_t gpset_mem = mem - store_mem;

  // Don't allow resizing - this allows use to the thread safe
  // and control memory usage (die when we fill up allowed memory)
  if(num_paths)
    gpath_set_alloc2(&gpstore->gpset, ncols, num_paths, gpset_mem, false, count_nseen);
  else
    gpath_set_alloc(&gpstore->gpset, ncols, gpset_mem, false, count_nseen);

  gpstore->graph_capacity = graph_capacity;

  // paths_traverse is always a subset of paths_all
  gpstore->paths_all = ctx_calloc(graph_capacity, sizeof(GPath*));
  gpstore->paths_traverse = gpstore->paths_all;
}

void gpath_store_dealloc(GPathStore *gpstore)
{
  gpath_set_dealloc(&gpstore->gpset);
  gpath_store_merge_read_write(gpstore);
  ctx_free(gpstore->paths_all);
  if(gpstore->paths_traverse != gpstore->paths_all) ctx_free(gpstore->paths_traverse);
  memset(gpstore, 0, sizeof(*gpstore));
}

void gpath_store_reset(GPathStore *gpstore)
{
  gpath_set_reset(&gpstore->gpset);
  gpstore->num_kmers_with_paths = gpstore->num_paths = gpstore->path_bytes = 0;
  memset(gpstore->paths_all, 0, gpstore->graph_capacity * sizeof(GPath*));
  if(gpstore->paths_traverse != gpstore->paths_all)
    ctx_free(gpstore->paths_traverse);
  gpstore->paths_traverse = gpstore->paths_all;
}

void gpath_store_print_stats(const GPathStore *gpstore)
{
  gpath_set_print_stats(&gpstore->gpset);

  char kmers_str[50], paths_str[50], bytes_str[50];
  ulong_to_str(gpstore->num_kmers_with_paths, kmers_str);
  ulong_to_str(gpstore->num_paths, paths_str);
  bytes_to_str(gpstore->path_bytes, 1, bytes_str);
  status("[GPathStore] kmers-with-paths: %s, num paths: %s, path-bytes: %s",
         kmers_str, paths_str, bytes_str);
}

void gpath_store_split_read_write(GPathStore *gpstore)
{
  if(gpstore->paths_traverse == gpstore->paths_all)
  {
    status("[GPathStore] Creating separate read/write GraphPath linked lists");
    if(gpstore->num_paths == 0)
    {
      gpstore->paths_traverse = NULL;
    }
    else
    {
      // Copy current paths over to path set to be updated
      status("[GPathStore]   (allocating new linked lists)");
      size_t mem = gpstore->graph_capacity * sizeof(GPath*);
      gpstore->paths_traverse = ctx_calloc(gpstore->graph_capacity, sizeof(GPath*));
      memcpy(gpstore->paths_traverse, gpstore->paths_all, mem);
    }
  }
}

void gpath_store_merge_read_write(GPathStore *gpstore)
{
  if(gpstore->paths_traverse != gpstore->paths_all)
  {
    status("[GPathStore] Merging read/write GraphPath linked lists");
    ctx_free(gpstore->paths_traverse); // does nothing if NULL
    gpstore->paths_traverse = gpstore->paths_all;
  }
}

GPath* gpath_store_fetch(const GPathStore *gpstore, hkey_t hkey)
{
  return gpstore->paths_all[hkey];
}

GPath* gpath_store_fetch_traverse(const GPathStore *gpstore, hkey_t hkey)
{
  return gpstore->paths_traverse[hkey];
}

// Update stats after removing a path
void gpstore_path_removal_update_stats(GPathStore *gpstore, GPath *gpath)
{
  // Update stats
  size_t nbytes = binary_seq_mem(gpath->num_juncs);
  __sync_fetch_and_sub((volatile uint64_t*)&gpstore->num_paths, 1);
  __sync_fetch_and_sub((volatile uint64_t*)&gpstore->path_bytes, nbytes);
}

// You do not need to acquire the kmer lock before calling this function
static void _gpstore_add_to_llist_mt(GPathStore *gpstore, hkey_t hkey, GPath *gpath)
{
  // Add to linked list
  ctx_assert(sizeof(size_t) == sizeof(GPath*));
  do {
    gpath->next = *(GPath *volatile const*)&gpstore->paths_all[hkey];
  }
  while(!__sync_bool_compare_and_swap((volatile size_t*)&gpstore->paths_all[hkey],
                                      (size_t)gpath->next, (size_t)gpath));

  // Update stats
  size_t nbytes = binary_seq_mem(gpath->num_juncs);
  size_t new_kmer = (gpath->next == NULL ? 1 : 0);
  __sync_fetch_and_add((volatile uint64_t*)&gpstore->num_kmers_with_paths, new_kmer);
  __sync_fetch_and_add((volatile uint64_t*)&gpstore->num_paths, 1);
  __sync_fetch_and_add((volatile uint64_t*)&gpstore->path_bytes, nbytes);
}

// Linear search to find a given path
GPath* gpstore_find(const GPathStore *gpstore, hkey_t hkey, GPathNew find)
{
  GPath *gpath = gpath_store_fetch(gpstore, hkey);
  for(; gpath != NULL; gpath = gpath->next)
    if(gpaths_are_equal(*gpath, find))
      return gpath;
  return NULL;
}

// Always adds new path. If newpath could be a duplicate, use gpathhash
// Note: it is not safe to call _add and _find_add simultaneously, since _add
//       avoids the use of locks.
GPath* gpath_store_add_mt(GPathStore *gpstore, hkey_t hkey, GPathNew newgpath)
{
  ctx_assert(newgpath.seq != NULL);

  GPath *gpath = gpath_set_add_mt(&gpstore->gpset, newgpath);
  _gpstore_add_to_llist_mt(gpstore, hkey, gpath);

  return gpath;
}

/*
// NOT USED ATM
// Linear time search to find or add a given path
// Note: it is not safe to call _add and _find_add simultaneously, since _add
//       avoids the use of locks.
GPath* gpath_store_find_add_mt(GPathStore *gpstore,
                               hkey_t hkey, GPathNew newgpath,
                               bool *found)
{
  ctx_assert(newgpath.seq != NULL);

  GPath *gpath;
  *found = true;

  // Get lock for kmer
  bitlock_yield_acquire(gpstore->kmer_locks, hkey);

  // Add if not found
  if((gpath = gpstore_find(gpstore, hkey, newgpath)) == NULL) {
    gpath = gpath_set_add_mt(&gpstore->gpset, newgpath);
    *found = false;
  }

  // Release kmer lock
  bitlock_release(gpstore->kmer_locks, hkey);

  _gpstore_add_to_llist_mt(gpstore, hkey, gpath);

  return gpath;
}
*/


text:
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Add Body Data

				<form class="form-horizontal" method="post" action="/body/new">
					<fieldset>

							Date*

								<input class="form-control" id="inputDate" name="inputDate" placeholder="01/01/2014" type="date">

							Weight*

								<input class="form-control new-body-log" id="inputWeight" name="inputWeight" type="text">

							Body Fat*

								<input class="form-control new-body-log" id="inputBodyFat" name="inputBodyFat" type="text">

							Lean Muscle

								<input class="form-control new-body-log" id="inputLeanMuscle" name="inputLeanMuscle" type="text">

Circumferences

							Chest

								<input class="form-control" id="inputCircChest" name="inputCircChest" type="text">

							Forearm

								<input class="form-control" id="inputCircForearm" name="inputCircForearm" type="text">

							Waist

								<input class="form-control" id="inputCircWaist" name="inputCircWaist" type="text">

							Thigh

								<input class="form-control" id="inputCircThigh" name="inputCircThigh" type="text">

							Hip

								<input class="form-control" id="inputCircHip" name="inputCircHip" type="text">

							Calf

								<input class="form-control" id="inputCircCalf" name="inputCircCalf" type="text">

							Neck

								<input class="form-control" id="inputCircNeck" name="inputCircNeck" type="text">

							Upper Arm

								<input class="form-control" id="inputCircArm" name="inputCircArm" type="text">

Fat Caliper Measurements (mm)

							Chest

								<input class="form-control" id="inputFatChest" name="inputFatChest" type="number">

							Abdominal

								<input class="form-control" id="inputFatAbdominal" name="inputFatAbdominal" type="number">

							Thigh

								<input class="form-control" id="inputFatThigh" name="inputFatThigh" type="number">

							Tricep

								<input class="form-control" id="inputFatTricep" name="inputFatTricep" type="number">

							Subscapular

								<input class="form-control" id="iinputFatSubscapular" name="inputFatSubscapular" type="number">

							Suprailiac

								<input class="form-control" id="inputFatSuprailiac" name="inputFatSuprailiac" type="number">

							Midaxillary

								<input class="form-control" id="inputFatMidaxillary" name="inputFatMidaxillary" type="number">

								<button class="btn btn-default">Cancel</button>
								<button type="submit" class="btn btn-primary">Submit</button>

					</fieldset>
				</form>


text:
export default {
    Book: {
        __description: 'A simple book',
        authors: {
            resolve({ authors }, { count }) {
                return authors ? authors.slice(0, count) : [];
            },
        },

    },
    IndustryIdentifiers: {
        __description: 'Industry identifiers for a Volume',
    },
    Author: {
        __description: 'A volume author',
    },
};


text:
require 'lite_spec_helper'

describe 'Operations' do
  let(:uri) { ENV['ATLAS_URI'] }
  let(:client) { Mongo::Client.new(uri) }

  before do
    if uri.nil?
      skip "ATLAS_URI not set in environment"
    end
  end

  describe 'list_collections' do
    # Atlas free tier proxy enforces restrictions on list_collections
    # arguments. This tests verifies that list_collections works on Atlas

    it 'works' do
      # We are not allowed to mutate the database, therefore the list of
      # collections would generally be empty.
      expect do
        client.database.list_collections
      end.not_to raise_error
    end
  end
end


text:
This is a server with creates a cache form HTML by account in bitcoin. Look the [API][6].

## Why down the service?

The main reasons are

* The apps isomeptrics
* The project did not receive profits

> A donations in bitcoin [1BhBb3rKHSQPRjPjuPj46xX24RUPQn3hRm](bitcoin:1BhBb3rKHSQPRjPjuPj46xX24RUPQn3hRm)

## Requisites

* [Bitcoin Wallet][2]
* [GitHub App][5]

Bat use [OpenShift][9] or install

* [NodeJs][7]
* [MongoDB][8]

### Tecnology

* Angular (v1.*)
* SASS (SCSS)
* Browserify
* Jade (Now PUG)
* ExpressJs
* MongooseJs
* PassportJs
* MarkDown
* MomentJs
* UglifyJs
* vHost (For ExpressJs)

## Environment Variables

Put the settings the server.

| Var | Type | Requiere | Description |
| --- | ---- |:--------:| ------------ |
| `CACHE_WATCH` | String | YES | The name of of the hearder Eg. `x-cache-watch` |
| `COMPRESS_CSS` | Boolean | NO | Compress the CSS |
| `COMPRESS_JS` | Boolean | NO | Compress the JavaScript in browers |
| `HTTPS_ACTIVE` | Boolean | NO | Use [Https][1] |
| `BITCOIN_MASTER` | String | YES | Bitcoin account master |
| `BLOCKCHAIN_ID` | String | YES | Id form the [BlockChain][2] |
| `BLOCKCHAIN_SECRET1` | String | YES | Password principal form the [BlockChain][2] |
| `BLOCKCHAIN_SECRET2` | String | YES | Password secondary form the [BlockChain][2] |
| `GITHUB_ID` | String | YES | Id form app in [Github][5] |
| `GITHUB_SECRET` | String | YES | Secreet form app in [Github][5] |
| `OPENSHIFT_APP_DNS` | String | NO | The fully-qualified domain namespace of the application [OpenShift][3] |
| `OPENSHIFT_APP_NAME` | String | YES | The name of the application [OpenShift][3] |
| `OPENSHIFT_APP_UUID` | String | YES | The UUID of the application [OpenShift][3] |
| `OPENSHIFT_DATA_DIR` | String | NO | A persistent data directory [OpenShift][3] |
| `IS_FREE` | Number | NO | The number free pages :D |
| `IS_MAX` | Number | NO | Is the max number cache for the service |
| `KONSTANT` | Number | NO | How many per page in the cache in Bitcoin Eg. 0.00001 |
| `LANG_BASIC` | String | YES | Language principal Eg. en |
| `OPENSHIFT_MONGODB_DB_HOST` | String | YES | The host name or IP address used to connect to the mongodb [OpenShift][3] |
| `OPENSHIFT_MONGODB_DB_PORT` | Number | YES | The host name or port used to connect to the mongodb [OpenShift][3] |
| `OPENSHIFT_NODEJS_IP` | String | YES | The host name or IP address used to connect to the nodejs [OpenShift][3] |
| `OPENSHIFT_NODEJS_PORT` | Number | YES | The host name or port used to connect to the nodejs [OpenShift][3] |
| `PUBLIC_DATA` | String | NO | Is the temporal files |
| `URL_DOMAIN` | String | YES | Is the website Eg. cache.watch |
| `URL_SERVICE` | String | YES | Is the API Eg. service.cache.watch |

## Install and Start

Is simple

	$ npm install

And start

	$ npm start

[1]: https://en.wikipedia.org/wiki/HTTPS
[2]: https://blockchain.info/
[3]: https://developers.openshift.com/managing-your-applications/environment-variables.html
[4]: https://blockchain.info/es/wallet/payment-notifications
[5]: https://github.com/settings/developers
[6]: http://developer.cache.watch/
[7]: http://nodejs.org/
[8]: http://mongodb.org/
[9]: https://developers.openshift.com/languages/nodejs/index.html


text:
"""Package version for dm_hard_eight.

Kept in separate file so it can be used during installation.
"""

__version__ = '1.0.0b1'  # https://www.python.org/dev/peps/pep-0440/


text:
+ O(n^2) algorithms
  - Bubble Sort
  - Selection Sort
  - Insertion Sort
+ O(nlogn) algorithms
  - Merge Sort
+ O(n) algorithms
  - Bucket Sort

### Bucket Sort
+ The idea is to partition an array into a number of buckets, and each bucket is sorted individually either using another sorting algorithm or recursively apply bucket sort.

+ The procedure is as follow:
  - set up an array of empty bucekts
  - go through original array, put each element in corresponding bucket
  - sort each non-empty bucket
  - visit buckets in order and put elements back into original array

+ Analysis
  - Time O(n)
  - Space O(n)

+ Drawbacks
  - how to handle duplicates: store duplicates into linkedlist or counting sort
  - must know min and max value in the original array
  - enough memory

### Bubble Sort
+ The idea is to compare each item wth the item next to it, and swap positions if needed. The algorithm repeats until we have a pass without swapping any elements.

+ Analysis
  - Time O(n^2);
  - Space O(1)

### Selection Sort
+ The idea is to select the smallest element of remaining array and then swap it to the front.

+ Analysis
  - Time O(n^2)
  - Space O(1)

### Insertion Sort
+ The idea is to remove one entry at a time and insert it into the correct position in the sorted part.

+ Analysis
  - Time O(n^2)
  - Space O(1)

### Merge Sort
+ Use divide and conquer paradigm
+ Procedure
  - divide array into two subarrays
  - sort each subarray
  - merge sorted subarrays into one
+ Analysis
  - Time O(nlogn)
  - Space O(nlogn)


text:
namespace MottoBeneApps.GoHome
{
    #region Namespace Imports

    using System;
    using System.ComponentModel.Composition;

    using Caliburn.Micro;

    using Gemini;

    using LogManager = NLog.LogManager;

    #endregion

    internal sealed class Bootstrapper : AppBootstrapper
    {
        #region Constants and Fields

        private static ILog _logger;

        #endregion

        #region Constructors and Destructors

        static Bootstrapper()
        {
            Caliburn.Micro.LogManager.GetLog = type => Logger;
        }

        #endregion

        #region Properties

        [Export]
        public static ILog Logger
        {
            get
            {
                if (_logger == null)
                {
                    _logger = (ILog)LogManager.GetLogger(Guid.NewGuid().ToString("B"), typeof(Logger));
                }

                return _logger;
            }
        }

        #endregion
    }
}


text:
ConfigServiceV2
---------------------------------

.. automodule:: google.cloud.logging_v2.services.config_service_v2
    :members:
    :inherited-members:

.. automodule:: google.cloud.logging_v2.services.config_service_v2.pagers
    :members:
    :inherited-members:


text:
static int bCriticalErrCnt = 0;
void TestEdge(Vertex* V1, Vertex* V2, Face* parent) {
    Face* found = 0;
    int f_count = 0;

    for (vecFaceIt I = V1->adjacent.begin(); I != V1->adjacent.end(); I++) {
        Face* test = *I;
        if (test == parent)
            continue;
        if (test->VContains(V2)) {
            f_count++;
            found = test;
        }
    }
    if (f_count > 1) {
        bCriticalErrCnt++;
        pBuild->err_multiedge.w_fvector3(V1->P);
        pBuild->err_multiedge.w_fvector3(V2->P);
    }
}

void CBuild::BuildCForm() {
    Phase("CFORM: construction...");
    // Status		("Building base mesh : vertices...");

    _mesh mesh;                 // a mesh object
    _decimater decimater(mesh); // a decimater object, connected to a mesh
    _HModQuadric hModQuadric;   // use a quadric module
    decimater.add(hModQuadric); // register module at the decimater
    decimater.module(hModQuadric).set_max_err(0.0001, false); // error-limit 0.0001

    // Initializing mesh
    Status("Building base mesh : vertices[%d]...", g_vertices.size());
    for (vecVertexIt _v = g_vertices.begin(); _v != g_vertices.end(); _v++)
        (*_v)->handle = _mesh::InvalidVertexHandle.idx();

    Status("Building base mesh : base faces[%d]...", g_faces.size());
    std::vector<_mesh::VertexHandle> fhandles;
    xr_vector<cform_FailFace> failedfaces;
    cform_mergeprops fmergeprops;

    for (vecFaceIt I = g_faces.begin(); I != g_faces.end(); I++) {
        Progress(float(I - g_faces.begin()) / float(g_faces.size()));
        Face* F = *I;
        if (F->Shader().flags.bCollision) {
            // test correctness
            TestEdge(F->v[0], F->v[1], F);
            TestEdge(F->v[1], F->v[2], F);
            TestEdge(F->v[2], F->v[0], F);

            // add vertices
            fhandles.clear();
            for (u32 v = 0; v < 3; v++) {
                _mesh::VertexHandle h = _mesh::VertexHandle(F->v[v]->handle);
                if (_mesh::InvalidVertexHandle == h) {
                    Fvector& p = F->v[v]->P;
                    h = mesh.add_vertex(_mesh::Point(p.x, p.y, p.z));
                    F->v[v]->handle = h.idx();
                }
                fhandles.push_back(h);
            }

            // add face
            fmergeprops.material = F->dwMaterialGame;
            fmergeprops.sector = materials[F->dwMaterial].sector;
            _mesh::FaceHandle hface = mesh.add_face(fhandles);
            if (hface == _mesh::InvalidFaceHandle) {
                failedfaces.push_back(cform_FailFace());
                failedfaces.back().P[0] = F->v[0]->P;
                failedfaces.back().P[1] = F->v[1]->P;
                failedfaces.back().P[2] = F->v[2]->P;
                failedfaces.back().props = fmergeprops.props;
            } else
                mesh.face(hface).set_props(fmergeprops.props);
        }
    }
    if (bCriticalErrCnt) {
        err_save();
        clMsg("MultipleEdges: %d faces", bCriticalErrCnt);
    }

    Status("Building base mesh : models[%d]...", mu_refs.size());
    mesh.garbage_collection();
    for (u32 ref = 0; ref < mu_refs.size(); ref++)
        mu_refs[ref]->export_cform_game(mesh, failedfaces);

    Status("Building base mesh : normals...");
    mesh.garbage_collection();
    mesh.request_vertex_normals();
    mesh.update_vertex_normals();

    // Decimate
    Status("Reconstructing mesh-topology...");
    clMsg("%d faces failed topology check", failedfaces.size());
    clMsg("%f%% geometry/artist quality",
          100.f * (1 - float(failedfaces.size()) / float(mesh.n_faces())));

    decimater.initialize(); // let the decimater initialize the mesh and the modules

    int nf_before = int(mesh.n_faces());
    int nv_before = int(mesh.n_vertices());
    int nc = decimater.decimate(nv_before); // do decimation, as large, as possible
    mesh.garbage_collection();
    int nf_after = int(mesh.n_faces());
    int nv_after = int(mesh.n_vertices());
    clMsg("vertices: was[%d], now[%d] => %f %% left", nv_before, nv_after,
          100.f * float(nv_after) / float(nv_before));
    clMsg("   faces: was[%d], now[%d] => %f %% left", nf_before, nf_after,
          100.f * float(nf_after) / float(nf_before));

    // Decimate
    Status("Refactoring CFORM...");
    Fbox BB;
    BB.invalidate();
    _mesh::VertexIter vit = mesh.vertices_begin(), vend = mesh.vertices_end();
    for (; vit != vend; ++vit)
        BB.modify(reinterpret_cast<Fvector&>(mesh.point(vit)));

    CDB::CollectorPacked CL(BB, mesh.n_vertices(), mesh.n_faces());
    _mesh::FaceIter fit = mesh.faces_begin(), fend = mesh.faces_end();
    for (; fit != fend; ++fit) {
        // get vertex-handles
        fhandles.clear();
        for (_mesh::CFVIter fv_it = mesh.cfv_iter(fit); fv_it; ++fv_it)
            fhandles.push_back(fv_it.handle());
        CL.add_face_D(reinterpret_cast<Fvector&>(mesh.point(fhandles[0])),
                      reinterpret_cast<Fvector&>(mesh.point(fhandles[1])),
                      reinterpret_cast<Fvector&>(mesh.point(fhandles[2])), fit->props());
    }
    Status("Restoring fail-faces...");
    for (u32 it = 0; it < failedfaces.size(); it++) {
        cform_FailFace& F = failedfaces[it];
        CL.add_face_D(F.P[0], F.P[1], F.P[2], F.props);
    }

    // Saving
    Status("Saving...");
    nf_after = int(CL.getTS());
    nv_after = int(CL.getVS());
    clMsg("vertices: was[%d], now[%d] => %f %% left", nv_before, nv_after,
          100.f * float(nv_after) / float(nv_before));
    clMsg("   faces: was[%d], now[%d] => %f %% left", nf_before, nf_after,
          100.f * float(nf_after) / float(nf_before));
    string512 fn;
    IWriter* MFS = FS.w_open(strconcat(fn, pBuild->path, "level.cform"));

    // Header
    hdrCFORM hdr;
    hdr.version = CFORM_CURRENT_VERSION;
    hdr.vertcount = (u32)CL.getVS();
    hdr.facecount = (u32)CL.getTS();
    hdr.aabb = BB;
    MFS->w(&hdr, sizeof(hdr));
    // Data
    MFS->w(CL.getV(), (u32)CL.getVS() * sizeof(Fvector));
    MFS->w(CL.getT(), (u32)CL.getTS() * sizeof(CDB::TRI));
    // Clear pDeflector (it is stored in the same memory space with dwMaterialGame)
    for (vecFaceIt I = g_faces.begin(); I != g_faces.end(); I++) {
        Face* F = *I;
        F->pDeflector = NULL;
    }
    FS.w_close(MFS);
}

void CBuild::BuildPortals(IWriter& fs) {
    fs.w_chunk(fsL_PORTALS, &*portals.begin(), portals.size() * sizeof(b_portal));
}


text: export AWS_CONFIG_FILE="$XDG_CONFIG_HOME"/aws/confg


text:
require File.expand_path('../../spec_helper', __FILE__)

module Pod
  describe Command::Deintegrate do
    def fixture_project(version, named)
      ROOT + "spec/fixtures/#{version}/#{named}"
    end

    def temporary_directory
      ROOT + 'tmp'
    end

    def deintegrate(directory)
      Dir.chdir(directory) do
        command = Pod::Command.parse(['deintegrate'])
        command.config.sandbox.stubs(:root).returns(directory + 'Pods')
        command.validate!
        command.run
      end
    end

    def deintegrate_project(version, named)
      path = fixture_project(version, named)
      `rsync -r #{path}/ #{temporary_directory}`

      deintegrate(temporary_directory)

      (temporary_directory + 'TestProject.xcworkspace').rmtree
      (temporary_directory + 'Podfile').delete
      (temporary_directory + 'Podfile.lock').delete

      output = `diff -r #{fixture_project(version, 'None')} #{temporary_directory}`
      puts(output) unless $?.success?

      $?.should.be.success
    end

    def deintegrate_target(version, named)
      path = fixture_project(version, 'StaticLibraries/TestProject.xcodeproj')
      project = Xcodeproj::Project.open(path)
      target = project.native_targets.find { |t| t.name == named }
      target_build_files_before_deintegration = target.frameworks_build_phase.files.select do |f|
        f.display_name =~ Pod::Deintegrator::FRAMEWORK_NAMES
      end.map(&:file_ref)
      deintegrator = Deintegrator.new
      deintegrator.deintegrate_target(target)

      target.frameworks_build_phase.files.select do |f|
        f.display_name =~ Pod::Deintegrator::FRAMEWORK_NAMES
      end.should.be.empty
      target.shell_script_build_phases.select { |p| p.name =~ /Pods/ }.should.be.empty
      target.build_configurations.reject { |c| c.base_configuration_reference.nil? }.should.be.empty
      project['Frameworks'].files.none? { |f| target_build_files_before_deintegration.include?(f) }.should.be.true
    end

    describe 'CLAide' do
      it 'registers it self' do
        Command.parse(['deintegrate']).should.be.instance_of Command::Deintegrate
      end
    end

    before do
      temporary_directory.rmtree if temporary_directory.exist?
      temporary_directory.mkdir
    end

    after do
      temporary_directory.rmtree
    end

    describe 'Pre 1.0.0 targets' do
      before do
        @version = 'Project_Pre_1.0.0'
      end

      it 'deintegrates a static library integrated project' do
        deintegrate_project(@version, '/StaticLibraries')
      end

      it 'deintegrates a framework integrated project' do
        deintegrate_project(@version, '/Frameworks')
      end

      it 'deintegrates a particular target' do
        deintegrate_target(@version, 'TestProject')
      end
    end

    describe '1.0.0 targets' do
      before do
        @version = 'Project_1.0.0'
      end

      it 'deintegrates a static library integrated project' do
        deintegrate_project(@version, '/StaticLibraries')
      end

      it 'deintegrates a framework integrated project' do
        deintegrate_project(@version, '/Frameworks')
      end

      it 'deintegrates a particular target' do
        deintegrate_target(@version, 'TestProject')
      end
    end

    describe 'Post 1.0.1 targets' do
      before do
        @version = 'Project_Post_1.0.1'
      end

      it 'deintegrates a static library integrated project' do
        deintegrate_project(@version, '/StaticLibraries')
      end

      it 'deintegrates a framework integrated project' do
        deintegrate_project(@version, '/Frameworks')
      end

      it 'deintegrates a particular target' do
        deintegrate_target(@version, 'TestProject')
      end
    end
  end
end


text:
if [ -z "$GROOVY_CMD" ] ; then
  if [ ! -z "$GROOVY_HOME" ] ; then
    GROOVY_CMD=$GROOVY_HOME/bin/groovysh
  else
    GROOVY_CMD=`which groovysh`
  fi
fi

if [ ! -x "$GROOVY_CMD" ] ; then
  echo groovy executable must be available on the path or in \$GROOVY_HOME/bin
  exit 1
fi

export SOURCE_PATHS=`find ../.. -name java | grep "src/main/java$" | grep -v web-console/plugins | grep -v "^../../sandbox"`

rm -rf target/apidocs/

echo "building javadoc from "$SOURCE_PATHS

$GROOVY_CMD -q << END
sourcePaths = System.env['SOURCE_PATHS'].split('\\\\s+').join(':')
title = "Brooklyn"
ant = new AntBuilder()
ant.taskdef(name: "groovydoc", classname: "org.codehaus.groovy.ant.Groovydoc")
ant.groovydoc(
    destdir      : "target/apidocs/",
    sourcepath   : "\${sourcePaths}",
    packagenames : "**.*",
    use          : "true",
    windowtitle  : "\${title}",
    doctitle     : "\${title}",
    header       : "\${title}",
    footer       : 'Brooklyn Multi-Cloud Application Management Platform
 brooklyncentral.github.com. Apache License. © 2012.',
    private      : "false")
println "\njavadoc built in target/apidocs\n"
END

if (($!)) ; then echo ; echo ; echo "Groovy docs had an error." ; exit 1 ; fi
echo ; echo

if [ -d ../_site/use/api/ ] ; then
  echo "API directory detected in parent, installing docs there"
  cp -r target/apidocs/* ../_site/use/api/
fi


text:
package io.micrometer.core.instrument.internal;

import io.micrometer.common.util.internal.logging.InternalLogger;
import io.micrometer.common.util.internal.logging.InternalLoggerFactory;
import io.micrometer.core.instrument.Meter.Id;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.config.MeterFilterReply;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;

/**
 * {@link MeterFilter} to log only once a warning message and deny a {@link Id Meter.Id}.
 *
 * @author Jon Schneider
 * @author Dmytro Nosan
 * @since 1.5.0
 */
public final class OnlyOnceLoggingDenyMeterFilter implements MeterFilter {

    private static final InternalLogger logger = InternalLoggerFactory
            .getInstance(OnlyOnceLoggingDenyMeterFilter.class);

    private final AtomicBoolean alreadyWarned = new AtomicBoolean();

    private final Supplier<String> message;

    public OnlyOnceLoggingDenyMeterFilter(Supplier<String> message) {
        this.message = message;
    }

    @Override
    public MeterFilterReply accept(Id id) {
        if (logger.isWarnEnabled() && this.alreadyWarned.compareAndSet(false, true)) {
            logger.warn(this.message.get());
        }
        return MeterFilterReply.DENY;
    }

}


text:
package main

import (
	"strconv"
	"time"

	"periph.io/x/conn/v3/gpio"
	"periph.io/x/conn/v3/gpio/gpioreg"
	"periph.io/x/host/v3"
)

// gpioProvider generates pins for the platform (used for testing)
var gpioProvider = xGpioProvider // For testing on non-test setups

// GpioState represents the current binary value of the pin.  Is it High or Low Voltage
type GpioState bool

const (
	// Low voltage registered on the pin (~0-1v)
	Low GpioState = false
	// High voltage registered on the pin (~1-3.3v)
	High GpioState = true
)

// State returns whether the pin is in a High or Low voltage state
func (s GpioState) State() gpio.Level {
	if s == Low {
		return gpio.Low
	}
	return gpio.High
}

func (s GpioState) String() string {
	return s.State().String()
}

// Edge refers to the rising or falling of a voltage value on the pin.
type Edge int

const (
	// NoEdge means no change
	NoEdge Edge = 0
	// RisingEdge means that the voltage is moving from a low to a high voltage state.
	RisingEdge Edge = 1
	// FallingEdge means that the voltage is moving from a high to a low voltage state.
	FallingEdge Edge = 2
	// BothEdges means taht a change is occuring in either direction.
	BothEdges Edge = 3
)

// Edge returns the current edge value.
func (e Edge) Edge() gpio.Edge {
	switch e {
	case NoEdge:
		return gpio.NoEdge
	case RisingEdge:
		return gpio.RisingEdge
	case FallingEdge:
		return gpio.FallingEdge
	case BothEdges:
		return gpio.BothEdges
	}
	return gpio.NoEdge
}

func (e Edge) String() string {
	return e.Edge().String()
}

// Pull refers to the configuration of the pin circuitry.
type Pull int

const (
	// Float lets the input flow directly, resistance is handled elswhere.
	Float Pull = 0
	// PullDown applies pull-down resistance to the pin
	PullDown Pull = 1
	// PullUp applies pull-up resistance to the pin
	PullUp Pull = 2
	// PullNoChange does not change the previous pull resistor setting
	PullNoChange Pull = 3
)

// Pull returns the current state of the pin's pull configuration
func (p Pull) Pull() gpio.Pull {
	switch p {
	case Float:
		return gpio.Float
	case PullDown:
		return gpio.PullDown
	case PullUp:
		return gpio.PullUp
	case PullNoChange:
		return gpio.PullNoChange
	}
	return gpio.PullNoChange
}

func (p Pull) String() string { return p.Pull().String() }

// PiPin represnets a GPIO pin on the Raspberry Pi
type PiPin interface {
	Input()
	InputEdge(Pull, Edge)
	Output(GpioState)
	Read() GpioState
	WaitForEdge(time.Duration) bool
	Pin() uint8
}

// Gpio implements a PiPin interface for a Raspberry Pi system.
type Gpio struct {
	gpio uint8
	pin  gpio.PinIO
}

// SetGpioProvider allows you to change the type of GPIO for the system (useful for testing)
func SetGpioProvider(p func(uint8) PiPin) {
	gpioProvider = p
}

func xGpioProvider(gpio uint8) PiPin {
	g := Gpio{
		gpio: gpio,
		pin:  gpioreg.ByName(strconv.Itoa(int(gpio))),
	}
	gpioreg.Register(g.pin)
	return (PiPin)(&g)
}

// NewGpio creates a new PiPin for a given gpio value.
func NewGpio(gpio uint8) PiPin {
	return gpioProvider(gpio)
}

// GpioInit initializes the system
func GpioInit() error {
	_, err := host.Init()
	return err
}

// Input sets the pin to be read from.
func (g *Gpio) Input() {
	Debug("Setting gpio(%d) to Input(%s, %s)", g.gpio, Float, NoEdge)
	g.pin.In(gpio.Float, gpio.NoEdge)
}

// InputEdge sets the pin to be read from and to alert WaitForEdge when the given Edge is found.
func (g *Gpio) InputEdge(p Pull, e Edge) {
	Debug("Setting gpio(%d) to Input(%s, %s)", g.gpio, p, e)
	g.pin.In(p.Pull(), e.Edge())
}

// Output sets the pin to be written to.
func (g *Gpio) Output(s GpioState) {
	Debug("Output setting gpio(%d) to %s", g.gpio, s)
	g.pin.Out(s.State())
}

// Read returns the current state of the pin
func (g *Gpio) Read() GpioState {
	if g.pin.Read() == gpio.High {
		return High
	}
	return Low
}

// WaitForEdge blocks while waiting for a voltage change on the pin.
func (g *Gpio) WaitForEdge(timeout time.Duration) bool {
	return g.pin.WaitForEdge(timeout)
}

// Pin returns the GPIO number of the pin.
func (g *Gpio) Pin() uint8 {
	return g.gpio
}

// Direction refers to the usage of the pin.  Is it being used for input or output?
type Direction bool

const (
	// Input means that the value of the pin will be read and is controlled externally.
	Input Direction = false
	// Output means that the value of the pin will be written to and is controlled internally.
	Output Direction = true
)


text:
import { getBuffer } from '../../utils';
import { createView } from '../../view';
import { bool } from '../../schemas';

test('bool', () => {
  const view = createView(bool);

  expect(typeof view.value).toBe('boolean');

  expect(view.value).toBe(false);
  expect(getBuffer(view).equals(Buffer.from([0x00]))).toBe(true);

  view.value = true;

  expect(view.value).toBe(true);
  expect(getBuffer(view).equals(Buffer.from([0x01]))).toBe(true);
});


text:
'use strict';

angular.module('mean.members').controller('MembersController', ['$scope', '$location', '$stateParams', 'Global', 'Members',
    function($scope, $location, $stateParams, Global, Members) {
        $scope.global = Global;
        $scope.package = {
            name: 'members'
        };

        $scope.updateMember = function(member){
          if(member.prefersEmail){
            member.phone = null;
          }else{
            member.email = null;
          }

            member.$update(function() {
              //repopulate
              $scope.find();
              member.edit = false;
              $scope.existError = '';
            }, function(error){
              $scope.existError = error.data.error;
            });

        };

        $scope.deleteMember = function(member){
            member.$remove(function(){
                $scope.find();
            });
        };

        $scope.addMember = function(newMember){
            $scope.members.push(newMember);
            $scope.newMember = '';
        };

        $scope.create = function() {
            var billUsersEmail;

            if(this.billPhone === 'true')
              billUsersEmail= false;
            else
              billUsersEmail= true;

            var member = new Members({
              first_name: this.first_name,
              last_name: this.last_name,
              email: this.email,
              phone: this.phone,
              prefersEmail: billUsersEmail
            });
            member.$save(function(response) {
              //repopulate members with a find
              $scope.find();
              $scope.first_name = '';
              $scope.last_name = '';
              $scope.email = '';
              $scope.phone = '';
              $scope.error = '';
              $scope.memberForm.$setPristine();
              $scope.billEmail = undefined;
              $scope.billPhone = undefined;
              $scope.showEmail = false;
              $scope.showPhone = false;
            }, function(error){
              $scope.error = error.data.error;
            });
        };

        $scope.find = function() {
          $scope.findingMembers = true;
          Members.query(function(members) {
            $scope.members = members;
            $scope.msMembers = [];
            for(var i = 0; i < $scope.members.length; i++){
              var newMember = {};
              newMember.first_name = $scope.members[i].first_name;
              newMember.last_name = $scope.members[i].last_name;
              newMember.id = $scope.members[i]._id;
              newMember.phone = $scope.members[i].phone;
              newMember.email = $scope.members[i].email;
              newMember.prefersEmail = $scope.members[i].prefersEmail;
              newMember.ticked = false;
              $scope.msMembers.push(newMember);
            }
            $scope.findingMembers = false;
          });
        };

        $scope.findOne = function() {
          Members.get({
            memberId: $stateParams.memberId
          }, function(member) {
            $scope.member = member;
          });
        };

    }
]);


text:
<?php

/**
 * @package Omeka\View\Helper
 */
class Omeka_View_Helper_Loop extends Zend_View_Helper_Abstract
{
    /**
     * Return an iterator used for looping an array of records.
     *
     * @param string $recordsVar
     * @param array|null $records
     * @return Omeka_Record_Iterator
     */
    public function loop($recordsVar, $records = null)
    {
        $recordsVar = $this->view->pluralize($recordsVar);
        if (!is_array($records)) {
            $records = $this->view->$recordsVar;
            if (!is_array($records)) {
                throw new Zend_View_Exception(__('An array of records is not available for the loop.'));
            }
        }
        return new Omeka_Record_Iterator($records, $this->view, $recordsVar);
    }
}


text:
/*
 * REVISION HISTORY:
 *
 * Date         Author(s)
 * CR           Headline
 * ===========  ==============================================================
 * Jun 27, 2005 Leonardo Barros
 * 34           Implement MEGTCK for the application RFC
 * ===========  ==============================================================
 */
package org.osgi.test.cases.dmt.tc1.tbc.DmtPrincipalPermission;

import org.osgi.service.dmt.security.DmtPrincipalPermission;

import org.osgi.test.cases.dmt.tc1.tbc.DmtConstants;
import org.osgi.test.cases.dmt.tc1.tbc.DmtTestControl;

/**
 * This test case validates the implementation of implies method of DmtPrincipalPermission,
 * according to MEG specification
 */
public class Implies extends DmtTestControl {
	/**
	 * This method asserts that an object implies other object using the same target
	 *
	 * @spec DmtPrincipalPermission.implies(Permission)
	 */
	public void testImplies001() {
		try {
			log("#testImplies001");
			DmtPrincipalPermission d1 = new DmtPrincipalPermission("*");
			DmtPrincipalPermission d2 = new DmtPrincipalPermission("*");

			assertTrue(
							"Asserts that an object implies other object using the same target",
							d1.implies(d2));

		} catch (Exception e) {
			failUnexpectedException(e);
		}
	}

	/**
	 * This method asserts that an object implies other object using the same target and actions
	 *
	 * @spec DmtPrincipalPermission.implies(Permission)
	 */
	public void testImplies002() {
		try {
			log("#testImplies002");

			DmtPrincipalPermission d1 = new DmtPrincipalPermission(
					DmtConstants.PRINCIPAL, "*");
			DmtPrincipalPermission d2 = new DmtPrincipalPermission(
					DmtConstants.PRINCIPAL, "*");

			assertTrue(
							"Asserts that an object implies other object using the same target and actions",
							d1.implies(d2));

		} catch (Exception e) {
			failUnexpectedException(e);
		}
	}

	/**
	 * This method asserts that an object does not imply other object using the different target and actions
	 *
	 * @spec DmtPrincipalPermission.implies(Permission)
	 */
	public void testImplies003() {
		try {
			log("#testImplies003");

			DmtPrincipalPermission d1 = new DmtPrincipalPermission(
					DmtConstants.PRINCIPAL, "*");
			DmtPrincipalPermission d2 = new DmtPrincipalPermission("*", "*");

			assertTrue(
							"Asserts that an object does not imply other object using the different target and actions",
							!d1.implies(d2));

		} catch (Exception e) {
			failUnexpectedException(e);
		}
	}

    /**
     * Asserts that an object implies other object using a wildcard
     *
     * @spec DmtPrincipalPermission.implies(Permission)
     */
    public void testImplies004() {
        try {
            log("#testImplies004");

            DmtPrincipalPermission d1 = new DmtPrincipalPermission(DmtConstants.PRINCIPAL + "*", "*");
            DmtPrincipalPermission d2 = new DmtPrincipalPermission(
                DmtConstants.PRINCIPAL +"a", "*");

            assertTrue(
                            "Asserts that an object implies other object using a wildcard",
                            d1.implies(d2));

        } catch (Exception e) {
            failUnexpectedException(e);
        }
    }
}


text:
GunControlSystem::GunControlSystem()
{
}

void GunControlSystem::Update(float dt)
{
	auto& entities = getEntities();
	for (auto entity : entities)
	{
		auto& gunComp = entity.getComponent<GunComponent>();
		gunComp.timeSinceLastShot += dt;
		if (gunComp.shooting && gunComp.timeSinceLastShot >= gunComp.minimumShotInterval)
		{
			gunComp.timeSinceLastShot = 0;
			ComponentsFactory::CreateBullet(entity, gunComp);
		}
	}
}


text:
package org.sanjeevenutan.marklogic.tradebrowser.repository.search;

import org.sanjeevenutan.marklogic.tradebrowser.domain.Trade;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/**
 * Spring Data ElasticSearch repository for the Trade entity.
 */
public interface TradeSearchRepository extends
		ElasticsearchRepository<Trade, Long> {
}


text:
package com.evolveum.midpoint.prism.query;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import javax.xml.namespace.QName;

import org.apache.commons.lang.StringUtils;

import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.Objectable;
import com.evolveum.midpoint.prism.PrismContainerValue;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.util.DebugUtil;
import com.evolveum.midpoint.util.exception.SchemaException;

public class InOidFilter extends ObjectFilter {

	private Collection<String> oids;
	private ExpressionWrapper expression;

	InOidFilter(Collection<String> oids) {
		this.oids = oids;
	}

	InOidFilter(ExpressionWrapper expression){
		this.expression = expression;
	}

	public static InOidFilter createInOid(Collection<String> oids){
		return new InOidFilter(oids);
	}

	public static InOidFilter createInOid(String... oids){
		return new InOidFilter(Arrays.asList(oids));
	}

	public static InOidFilter createInOid(ExpressionWrapper expression){
		return new InOidFilter(expression);
	}

	public Collection<String> getOids() {
		return oids;
	}

	public void setOids(Collection<String> oids) {
		this.oids = oids;
	}

	public ExpressionWrapper getExpression() {
		return expression;
	}

	public void setExpression(ExpressionWrapper expression) {
		this.expression = expression;
	}

	@Override
	public void checkConsistence() {
		if (oids == null) {
			throw new IllegalArgumentException("Null oids in "+this);
		}
		for (String oid: oids) {
			if (StringUtils.isBlank(oid)) {
				throw new IllegalArgumentException("Empty oid in "+this);
			}
		}
	}

	@Override
	public String debugDump() {
		return debugDump(0);
	}

	@Override
	public String debugDump(int indent) {
		StringBuilder sb = new StringBuilder();
		sb.append("IN OID: ");

		sb.append("\n");
		DebugUtil.indentDebugDump(sb, indent+1);
		sb.append("VALUE:");
		if (getOids() != null) {
			sb.append("\n");
			for (String oid : getOids()) {
				sb.append(oid);
				sb.append("\n");
			}
		} else {
			sb.append(" null");
		}

		return sb.toString();

	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("IN OID: ");
		if (getOids() != null){
			Iterator<String> itertor = getOids().iterator();
			while (itertor.hasNext()){
				String value = itertor.next();
				if (value == null) {
					sb.append("null");
				} else {
					sb.append(value);
				}
				sb.append("; ");

			}
		}
		return sb.toString();
	}

	@Override
	public InOidFilter clone() {
		InOidFilter inOid = new InOidFilter(getOids());
		inOid.setExpression(getExpression());
		return inOid;
	}

	@Override
	public boolean match(PrismContainerValue value, MatchingRuleRegistry matchingRuleRegistry) throws SchemaException {
		return false;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((oids == null) ? 0 : oids.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		InOidFilter other = (InOidFilter) obj;
		if (oids == null) {
			if (other.oids != null)
				return false;
		} else if (!oids.equals(other.oids))
			return false;
		return true;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_share"
        android:title="@string/share"
        app:showAsAction="never" />

    <item
        android:id="@+id/action_about"
        android:title="@string/about"
        app:showAsAction="never" />
</menu>


text:
layout: page
permalink: /articles/
title: Archives
tags: [Jiacheng Park, personal blog, archives, posts, articles, blogs]
image:
  feature: sheep-land2.jpg
  credit: Jiacheng park
  creditlink: http://jiachengpark.com
---

{% for post in site.posts %}

{{ post.title }} <time datetime="{{ post.date | date_to_xmlschema }}">{{ post.date | date: "%B %d, %Y" }}</time>

{% endfor %}


text:
import numpy as np
import rtpipe.RT as rt
import rtpipe.parseparams as pp
import rtpipe.parsecands as pc
import pickle, logging, os
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

def plot_cand(candsfile, candloc=[], candnum=-1, threshold=0, savefile=True, returndata=False, outname='', **kwargs):
    """ Reproduce detection of a single candidate for plotting or inspection.

    candsfile can be merge or single-scan cands pkl file. Difference defined by presence of scan in d['featureind'].
    candloc reproduces candidate at given location (scan, segment, integration, dmind, dtind, beamnum).
    candnum selects one to reproduce from ordered list
    threshold is min of sbs(SNR) used to filter candidates to select with candnum.
    savefile/outname define if/how to save png of candidate
    if returndata, (im, data) returned.
    kwargs passed to rt.set_pipeline
    """

    # get candidate info
    loc, prop = pc.read_candidates(candsfile)

    # define state dict and overload with user prefs
    d0 = pickle.load(open(candsfile, 'r'))
    for key in kwargs:
        logger.info('Setting %s to %s' % (key, kwargs[key]))
        d0[key] = kwargs[key]
    d0['logfile'] = False  # no need to save log

    # feature columns
    if 'snr2' in d0['features']:
        snrcol = d0['features'].index('snr2')
    elif 'snr1' in d0['features']:
        snrcol = d0['features'].index('snr1')
    if 'l2' in d0['features']:
        lcol = d0['features'].index('l2')
    elif 'l1' in d0['features']:
        lcol = d0['features'].index('l1')
    if 'm2' in d0['features']:
        mcol = d0['features'].index('m2')
    elif 'm1' in d0['features']:
        mcol = d0['features'].index('m1')

    try:
        scancol = d0['featureind'].index('scan')  # if merged pkl
    except ValueError:
        scancol = -1   # if single-scan pkl
    segmentcol = d0['featureind'].index('segment')
    intcol = d0['featureind'].index('int')
    dtindcol = d0['featureind'].index('dtind')
    dmindcol = d0['featureind'].index('dmind')

    # sort and prep candidate list
    snrs = prop[:, snrcol]
    select = np.where(np.abs(snrs) > threshold)[0]
    loc = loc[select]
    prop = prop[select]
    times = pc.int2mjd(d0, loc)
    times = times - times[0]

    # default case will print cand info
    if (candnum < 0) and (not len(candloc)):
        logger.info('Getting candidates...')
        logger.info('candnum: loc, SNR, DM (pc/cm3), time (s; rel)')
        for i in range(len(loc)):
            logger.info("%d: %s, %.1f, %.1f, %.1f" % (i, str(loc[i]), prop[i, snrcol], np.array(d0['dmarr'])[loc[i,dmindcol]], times[i]))
    else:  # if candnum or candloc provided, try to reproduce
        if (candnum >= 0) and not len(candloc):
            logger.info('Reproducing and visualizing candidate %d at %s with properties %s.' % (candnum, loc[candnum], prop[candnum]))
            dmarrorig = d0['dmarr']
            dtarrorig = d0['dtarr']
            if scancol >= 0:  # here we have a merge pkl
                scan = loc[candnum, scancol]
            else:   # a scan-based cands pkl
                scan = d0['scan']
            segment = loc[candnum, segmentcol]
            candint = loc[candnum, intcol]
            dmind = loc[candnum, dmindcol]
            dtind = loc[candnum, dtindcol]
            beamnum = 0
            candloc = (scan, segment, candint, dmind, dtind, beamnum)
        elif len(candloc) and (candnum < 0):
            assert len(candloc) == 6, 'candloc should be length 6 ( scan, segment, candint, dmind, dtind, beamnum ).'
            logger.info('Reproducing and visualizing candidate %d at %s' % (candnum, candloc))
            dmarrorig = d0['dmarr']
            dtarrorig = d0['dtarr']
            scan, segment, candint, dmind, dtind, beamnum = candloc
        else:
            raise Exception, 'Provide candnum or candloc, not both'

        # if working locally, set workdir appropriately. Can also be used in queue system with full path given.
        if not os.path.dirname(candsfile):
            d0['workdir'] = os.getcwd()
        else:
            d0['workdir'] = os.path.dirname(candsfile)
        filename = os.path.join(d0['workdir'], os.path.basename(d0['filename']))

        # clean up d0 of superfluous keys
        params = pp.Params()  # will be used as input to rt.set_pipeline
        for key in d0.keys():
            if not hasattr(params, key) and 'memory_limit' not in key:
                _ = d0.pop(key)

        d0['npix'] = 0
        d0['uvres'] = 0
        d0['nsegments'] = 0
        d0['logfile'] = False
        # get cand data
        d = rt.set_pipeline(filename, scan, **d0)
        im, data = rt.pipeline_reproduce(d, candloc, product='imdata') # removed loc[candnum]

        # optionally plot
        if savefile:
            loclabel = scan, segment, candint, dmind, dtind, beamnum
            make_cand_plot(d, im, data, loclabel, outname=outname)

        # optionally return data
        if returndata:
            return (im, data)

def refine_cand(candsfile, candloc=[], threshold=0):
    """ Helper function to interact with merged cands file and refine analysis

    candsfile is merged pkl file
    candloc (scan, segment, candint, dmind, dtind, beamnum) is as above.
    if no candloc, then it prints out cands above threshold.
    """

    if not candloc:
        plot_cand(candsfile, candloc=[], candnum=-1, threshold=threshold,
                  savefile=False, returndata=False)
    else:
        d = pickle.load(open(candsfile, 'r'))
        cands = rt.pipeline_refine(d, candloc)

    return cands

def make_cand_plot(d, im, data, loclabel, outname=''):
    """ Builds candidate plot.
    Expects phased, dedispersed data (cut out in time, dual-pol), image, and metadata
    loclabel is used to label the plot with (scan, segment, candint, dmind, dtind, beamnum).
    """

    # given d, im, data, make plot
    logger.info('Plotting...')
    logger.debug('(image, data) shape: (%s, %s)' % (str(im.shape), str(data.shape)))

    assert len(loclabel) == 6, 'loclabel should have (scan, segment, candint, dmind, dtind, beamnum)'
    scan, segment, candint, dmind, dtind, beamnum = loclabel

    # calc source location
    snrmin = im.min()/im.std()
    snrmax = im.max()/im.std()
    if snrmax > -1*snrmin:
        l1, m1 = rt.calc_lm(d, im, minmax='max')
        snrobs = snrmax
    else:
        l1, m1 = rt.calc_lm(d, im, minmax='min')
        snrobs = snrmin
    pt_ra, pt_dec = d['radec']
    src_ra, src_dec = source_location(pt_ra, pt_dec, l1, m1)
    logger.info('Peak (RA, Dec): %s, %s' % (src_ra, src_dec))

    # build plot
    fig = plt.Figure(figsize=(8.5,8))
    ax = fig.add_subplot(221, axisbg='white')

    # add annotating info
    ax.text(0.1, 0.9, d['fileroot'], fontname='sans-serif', transform = ax.transAxes)
    ax.text(0.1, 0.8, 'sc %d, seg %d, int %d, DM %.1f, dt %d' % (scan, segment, candint, d['dmarr'][dmind], d['dtarr'][dtind]), fontname='sans-serif', transform = ax.transAxes)
    ax.text(0.1, 0.7, 'Peak: (' + str(np.round(l1, 3)) + ' ,' + str(np.round(m1, 3)) + '), SNR: ' + str(np.round(snrobs, 1)), fontname='sans-serif', transform = ax.transAxes)

    # plot dynamic spectra
    left, width = 0.6, 0.2
    bottom, height = 0.2, 0.7
    rect_dynsp = [left, bottom, width, height]
    rect_lc = [left, bottom-0.1, width, 0.1]
    rect_sp = [left+width, bottom, 0.1, height]
    ax_dynsp = fig.add_axes(rect_dynsp)
    ax_lc = fig.add_axes(rect_lc)
    ax_sp = fig.add_axes(rect_sp)
    spectra = np.swapaxes(data.real,0,1)      # seems that latest pickle actually contains complex values in spectra...
    dd = np.concatenate( (spectra[...,0], np.zeros_like(spectra[...,0]), spectra[...,1]), axis=1)    # make array for display with white space between two pols
    impl = ax_dynsp.imshow(dd, origin='lower', interpolation='nearest', aspect='auto', cmap=plt.get_cmap('Greys'))
    ax_dynsp.text(0.5, 0.95, 'RR LL', horizontalalignment='center', verticalalignment='center', fontsize=16, color='w', transform = ax_dynsp.transAxes)
    ax_dynsp.set_yticks(range(0,len(d['freq']),30))
    ax_dynsp.set_yticklabels(d['freq'][::30])
    ax_dynsp.set_ylabel('Freq (GHz)')
    ax_dynsp.set_xlabel('Integration (rel)')
    spectrum = spectra[:,len(spectra[0])/2].mean(axis=1)      # assume pulse in middle bin. get stokes I spectrum. **this is wrong in a minority of cases.**
    ax_sp.plot(spectrum, range(len(spectrum)), 'k.')
    ax_sp.plot(np.zeros(len(spectrum)), range(len(spectrum)), 'k:')
    ax_sp.set_ylim(0, len(spectrum))
    ax_sp.set_yticklabels([])
    xmin,xmax = ax_sp.get_xlim()
    ax_sp.set_xticks(np.linspace(xmin,xmax,3).round(2))
    ax_sp.set_xlabel('Flux (Jy)')
    lc = dd.mean(axis=0)
    lenlc = len(data)  # old (stupid) way: lenlc = np.where(lc == 0)[0][0]
    ax_lc.plot(range(0,lenlc)+range(2*lenlc,3*lenlc), list(lc)[:lenlc] + list(lc)[-lenlc:], 'k.')
    ax_lc.plot(range(0,lenlc)+range(2*lenlc,3*lenlc), list(np.zeros(lenlc)) + list(np.zeros(lenlc)), 'k:')
    ax_lc.set_xlabel('Integration')
    ax_lc.set_ylabel('Flux (Jy)')
    ax_lc.set_xticks([0,0.5*lenlc,lenlc,1.5*lenlc,2*lenlc,2.5*lenlc,3*lenlc])
    ax_lc.set_xticklabels(['0',str(lenlc/2),str(lenlc),'','0',str(lenlc/2),str(lenlc)])
    ymin,ymax = ax_lc.get_ylim()
    ax_lc.set_yticks(np.linspace(ymin,ymax,3).round(2))

    # image
    ax = fig.add_subplot(223)
    fov = np.degrees(1./d['uvres'])*60.
    impl = ax.imshow(im.transpose(), aspect='equal', origin='upper',
                     interpolation='nearest', extent=[fov/2, -fov/2, -fov/2, fov/2],
                     cmap=plt.get_cmap('Greys'), vmin=0, vmax=0.5*im.max())
    ax.set_xlabel('RA Offset (arcmin)')
    ax.set_ylabel('Dec Offset (arcmin)')

    if not outname:
        outname = os.path.join(d['workdir'],
                               'cands_{}_sc{}-seg{}-i{}-dm{}-dt{}.png'.format(d['fileroot'], scan,
                                                                              segment, candint, dmind, dtind))

    try:
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure(outname)
    except ValueError:
        logger.warn('Could not write figure to %s' % outname)

def convertloc(candsfile, candloc, memory_limit):
    """ For given state and location that are too bulky, calculate new location given memory_limit. """

    scan, segment, candint, dmind, dtind, beamnum = candloc

    # set up state and find absolute integration of candidate
    d0 = pickle.load(open(candsfile, 'r'))
    filename = os.path.basename(d0['filename'])
    readints0 = d0['readints']
    nskip0 = (24*3600*(d0['segmenttimes'][segment, 0]
                      - d0['starttime_mjd'])
             / d0['inttime']).astype(int)
    candint_abs = nskip0 + candint

    logger.debug('readints0 {} nskip0 {}, candint_abs {}'.format(readints0, nskip0, candint_abs))

    # clean up d0 and resubmit to set_pipeline
    params = pp.Params()
    for key in d0.keys():
        if not hasattr(params, key):
            _ = d0.pop(key)
    d0['logfile'] = False
    d0['npix'] = 0
    d0['uvres'] = 0
    d0['nsegments'] = 0
    d0['memory_limit'] = memory_limit
    d = rt.set_pipeline(os.path.basename(filename), scan, **d0)

    # find best segment for new state
    readints = d['readints']
    nskips = [(24*3600*(d['segmenttimes'][segment, 0]
                        - d['starttime_mjd']) / d['inttime']).astype(int)
              for segment in range(d['nsegments'])]

    posind = [i for i in range(len(nskips)) if candint_abs - nskips[i] > 0]
    segment_new = [seg for seg in posind if candint_abs - nskips[seg] == min([candint_abs - nskips[i] for i in posind])][0]
    candint_new = candint_abs - nskips[segment_new]

    logger.debug('nskips {}, segment_new {}'.format(nskips, segment_new))

    return [scan, segment_new, candint_new, dmind, dtind, beamnum]

def source_location(pt_ra, pt_dec, l1, m1):
    """ Takes phase center and src l,m in radians to get ra,dec of source.
    Returns string ('hh mm ss', 'dd mm ss')
    """
    import math

    srcra = np.degrees(pt_ra + l1/math.cos(pt_dec))
    srcdec = np.degrees(pt_dec + m1)

    return deg2HMS(srcra, srcdec)

def deg2HMS(ra='', dec='', round=False):
    """ quick and dirty coord conversion. googled to find bdnyc.org.
    """
    RA, DEC, rs, ds = '', '', '', ''
    if dec:
        if str(dec)[0] == '-':
            ds, dec = '-', abs(dec)
        deg = int(dec)
        decM = abs(int((dec-deg)*60))
        if round:
            decS = int((abs((dec-deg)*60)-decM)*60)
        else:
            decS = (abs((dec-deg)*60)-decM)*60
        DEC = '{0}{1} {2} {3}'.format(ds, deg, decM, decS)

    if ra:
        if str(ra)[0] == '-':
            rs, ra = '-', abs(ra)
        raH = int(ra/15)
        raM = int(((ra/15)-raH)*60)
        if round:
            raS = int(((((ra/15)-raH)*60)-raM)*60)
        else:
            raS = ((((ra/15)-raH)*60)-raM)*60
        RA = '{0}{1} {2} {3}'.format(rs, raH, raM, raS)

    if ra and dec:
        return (RA, DEC)
    else:
        return RA or DEC


text:
package com.google.gxp.compiler.collapse;

import com.google.gxp.compiler.alerts.AlertSet;
import com.google.gxp.compiler.alerts.SourcePosition;
import com.google.gxp.compiler.base.Callable;
import com.google.gxp.compiler.base.Expression;
import com.google.gxp.compiler.base.FormalTypeParameter;
import com.google.gxp.compiler.base.Import;
import com.google.gxp.compiler.base.Parameter;
import com.google.gxp.compiler.base.Root;
import com.google.gxp.compiler.base.Template;
import com.google.gxp.compiler.base.ThrowsDeclaration;
import com.google.gxp.compiler.bind.BoundTree;
import com.google.gxp.compiler.GxpcTestCase;

import java.util.*;

/**
 * Tests for {@code SpaceCollapser}.
 */
public class SpaceCollapserTest extends GxpcTestCase {
  private static final SpaceCollapser COLLAPSER = new SpaceCollapser();

  // We don't care so much about source positions for these tests, so make
  // pos() return a fixed value for each test.
  private final SourcePosition POS = super.pos();
  public SourcePosition pos() {
    return POS;
  }

  public void testCollapse(Expression input, Expression expected) {
    Template root = template("bar.Baz",
                             htmlSchema(),
                             Collections.<Import>emptyList(),
                             Collections.<ThrowsDeclaration>emptyList(),
                             Collections.<Parameter>emptyList(),
                             Collections.<FormalTypeParameter>emptyList(),
                             collapse(input, null, null));
    BoundTree inTree = new BoundTree(pos(), AlertSet.EMPTY, root,
                                     Collections.<Callable>emptySet());
    SpaceCollapsedTree outTree = COLLAPSER.apply(inTree);
    Root newRoot = outTree.getRoot();
    assertTrue(newRoot + " is not a Template",
               newRoot instanceof Template);
    Template newTemplate = (Template)newRoot;
    assertEquals(expected, newTemplate.getContent());
  }

  public void testBasic() throws Exception {
    Expression input = str(" hello world ");
    testCollapse(input, str("hello world"));
  }

  public void testBasicWithNewlines() throws Exception {
    Expression input = str("\n hello world \n");
    testCollapse(input, str("hello world"));
  }
}


text:
package foam.nanos.bench.benchmarks;

import foam.core.X;
import foam.nanos.bench.Benchmark;
import foam.lib.json.Outputter;

public class JSONOutputterEscapeBenchmark
  implements Benchmark
{
  protected Outputter out_ = new Outputter(null);

  @Override
  public void setup(X x) {
  }

  @Override
  public void teardown(X x, java.util.Map stats) {
  }

  @Override
  public void execute(X x) {
    for ( int i = 0 ; i < 1000 ; i++ ) {
      out_.escape("abcdefg\n\t\\\u2605\\u0007xjxjxjxjxjxjxjxjxjxj");
    }
  }
}


text:
layout: post
section-type: post
comments: true
title:  "How to start a movement using a twitter bot"
category: tech
tags: [ 'python','programming','bots','social media' ]
---
## BOTS ,BOTS ,BOTS

![image](http://static.wixstatic.com/media/433ed0_bdd1602c3e487168aab17ff4493a20e4.jpg/v1/fill/w_442,h_180,al_c,q_80,usm_0.66_1.00_0.01/433ed0_bdd1602c3e487168aab17ff4493a20e4.jpg)

So lets face bots are taking over, they are on all major social media sites Facebook, Telegram, Slack and Twitter. Even Whatsapp which is against having bots on its platform is filled with bots with a vast number of services ranging from giving sports updates to conversational A.I bots to web-browsing.

To all those a bit lost here, a bot is just software developed to automate tasks you would normally do on your own like checking game scores, making dinner reservations ,fetching or displaying information.Bots have been around for a long time(about 50 years now) but they have only become famous now due to advancements in A.I, a rise in RESTful APIs and their integration onto the social media platform.

### MY TWITTER BOT

![twitter bot image](http://justsimplyoutsourcingworldwide.com/wp-content/uploads/2013/08/robot-icon-twitter-featured.jpg)

In this tutorial I will show you how to make a simple twitter bot using python that re-tweets everything on a certain topic on #hashtag.

Hmmmm ,but whats the point of a it mindlessly retweeting posts ?

Glad you asked ,It can be used to promote certain events or news across a wider audience. People can use this to receive updates on a particular topic, instead of the original poster on Twitter as they are only interested in specific Tweets and not everything that user has to say. People can use the hashtag ReTweet bots to follow the hashtag within their stream, so they don't have to search for it.You can use this bot to promote your business or support a movement or an organisation using a particular hashtag. A live implementation can be found here [A Bot has no name](https://twitter.com/thisflag_zw) , the bot Re-tweets everything with the hashtag #ThisFlag ,a movement against corruption in Zimbabwe.

### NOW TO THE FUN STUFF !!!

First thing is first , head to twitter and create a new app, details on how to do that can be found here [Create a twitter app](http://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/) .Make sure the application has both read and write access in step 8.

You'll need to generate and copy your:

* OAUTH_TOKEN
* OAUTH_SECRET
* CONSUMER_KEY
* CONSUMER_SECRET

we will need them later

Although the are many twitter libraries for python, in this tutorial we will be using [Tweepy](http://www.tweepy.org/) an easy-to-use Python library for accessing the Twitter API.

First head over to your console and install tweepy using

```
pip install tweepy
```

Next lets import it

```python
# import the necessary libraries
import tweepy

```
Now we will define all necessary variables for the script

```python
# define the necessary variables

# The hashtag or search term to retweet
hashtag = ""

#tweet language ,you can leave it blank for all languages
tweetLanguage = ""

# Number of tweets to retweet at a time (Twitter has a limit of 180 requests per every 15 mins)
num =

#Your twitter app consumer key
consumer_key=""

#Your twitter app consumer secret
consumer_secret=""

#Your twitter app access_token
access_token=""

#Your twitter app access_token_secret
access_token_secret=""

```
Setting up tweepy is very is simple ,all we have to do is specify our keys

```python
# Setting up tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

```

Now its time to make our code actually do something useful ,the following snippet queries twitter using our hashtag

```python
# search query
timelineIterator = tweepy.Cursor(api.search, q=hashtag, lang=tweetLanguage).items(num)

# put everything into a list to be able to sort/filter
timeline = []
for status in timelineIterator:
    timeline.append(status)
```
Finally we loop through our search results and retweet them one by one.

```python
tweet_counter = 0
error_counter = 0

# iterate the timeline and retweet
for status in timeline:
    try:
        print("(%(date)s) %(name)s: %(message)s\n" % \
              {"date": status.created_at,
               "name": status.author.screen_name.encode('utf-8'),
               "message": status.text.encode('utf-8')})

        api.retweet(status.id)
        tweet_counter += 1
    except tweepy.error.TweepError as e:
        # just in case tweet got deleted in the meantime or already re-tweeted
        error_counter += 1
        # print e
        continue

print("Finished. %d Tweets re tweeted, %d errors occurred." % (tweet_counter, error_counter))
```
And thats it, save your code and run it ,and watch the magic.

For a further advanced and more re-usable version of this code, checkout my repository [here](https://github.com/mikeyny/retweet-bot)

#### **DISCLAIMER**

The above code is my python3.5 implementation of github user basti2342 's [retweet-bot](https://github.com/basti2342/retweet-bot)


text:
using System;
using Aliyun.OSS.Common.Communication;
using Aliyun.OSS.Util;
using System.Collections.Generic;

namespace Aliyun.OSS.Commands
{
    internal class AbortBucketWormCommand : OssCommand
    {
        private readonly string _bucketName;

        protected override HttpMethod Method
        {
            get { return HttpMethod.Delete; }
        }

        protected override string Bucket
        {
            get { return _bucketName; }
        }

        private AbortBucketWormCommand(IServiceClient client, Uri endpoint, ExecutionContext context,
                                          string bucketName)
            : base(client, endpoint, context)
        {
            OssUtils.CheckBucketName(bucketName);
            _bucketName = bucketName;
        }

        public static AbortBucketWormCommand Create(IServiceClient client, Uri endpoint,
                                                 ExecutionContext context,
                                                 string bucketName)
        {
            return new AbortBucketWormCommand(client, endpoint, context, bucketName);
        }

        protected override IDictionary<string, string> Parameters
        {
            get
            {
                return new Dictionary<string, string>()
                {
                    { RequestParameters.SUBRESOURCE_WORM, null }
                };
            }
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>eclipse</groupId>
  <artifactId>maven-eclipse-plugin-test-project-23</artifactId>
  <packaging>eclipse-plugin</packaging>
  <version>23</version>
  <name>maven-eclipse-plugin-test-project-23</name>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-eclipse-plugin</artifactId>
        <version>test</version>
        <extensions>true</extensions>
        <configuration>
          <workspace>${basedir}/../../eclipse/workspaceDoesNotExist</workspace>
          <additionalConfig>
            <file>
              <name>.checkstyle</name>
              <content>
                <![CDATA[<fileset-config file-format-version="1.2.0" simple-config="true">
  <fileset name="all" enabled="true" check-config-name="acme corporate style" local="false">
    <file-match-pattern match-pattern="." include-pattern="true"/>
  </fileset>
  <filter name="NonSrcDirs" enabled="true"/>
</fileset-config>]]>
              </content>
            </file>
          </additionalConfig>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Observ. mycol. (Havniae) 1: 141 (1815)

#### Original name
Hydnum melaleucum Sw. ex Fr., 1815

### Remarks
null


text:
"""
Sandworks generative artwork
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)))

from lib import helpers  # nopep8
from lib import sand_spline  # nopep8


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 89(1): 117 (1987)

#### Original name
Spororminula Arx & Aa

### Remarks
null


text:
"use strict";

var nconf = require('nconf');

module.exports = function(Plugin) {
	// filter:admin.scripts.get
	Plugin.addAdminScripts = function(scripts, callback) {
		scripts.push('/plugins/nodebb-plugin-paycoin/lib/admin.js');
		callback(null, scripts);
	};
};


text:
package com.hazelcast.simulator.protocol.processors;

import com.hazelcast.simulator.protocol.exception.ExceptionLogger;
import org.apache.log4j.Logger;

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

import static java.lang.String.format;
import static org.junit.Assert.assertEquals;

public class TestExceptionLogger implements ExceptionLogger {

    private static final Logger LOGGER = Logger.getLogger(TestExceptionLogger.class);

    private final List<ExceptionEntry> exceptionEntries = new ArrayList<ExceptionEntry>();

    @Override
    public long getLogInvocationCount() {
        return exceptionEntries.size();
    }

    @Override
    public void log(Throwable cause) {
        log(cause, null);
    }

    @Override
    public void log(Throwable cause, String testId) {
        if (cause == null) {
            LOGGER.fatal("Cannot call log with a null exception");
            return;
        }

        LOGGER.warn("Exception detected.", cause);
        ExceptionEntry exceptionEntry = new ExceptionEntry(cause, testId);

        exceptionEntries.add(exceptionEntry);
    }

    public void assertNoException() {
        assertEquals(0, exceptionEntries.size());
    }

    public void assertException(Class<?>... exceptionTypes) {
        assertEquals(format("Expected %d exceptions, but found %d", exceptionTypes.length, exceptionEntries.size()),
                exceptionTypes.length, exceptionEntries.size());

        Iterator<ExceptionEntry> iterator = exceptionEntries.iterator();
        for (Class<?> exceptionType : exceptionTypes) {
            ExceptionEntry exceptionEntry = iterator.next();

            Throwable throwable = exceptionEntry.cause;
            String throwableClassName = throwable.getClass().getSimpleName();
            throwable.printStackTrace();
            assertEquals(format("Expected %s, but was %s for test %s: %s", exceptionType.getSimpleName(), throwableClassName,
                    exceptionEntry.testId, throwable.getMessage()), exceptionType, throwable.getClass());
        }
    }

    private static class ExceptionEntry {

        private final Throwable cause;
        private final String testId;

        public ExceptionEntry(Throwable cause, String testId) {
            this.cause = cause;
            this.testId = testId;
        }
    }
}


text:
ActiveRecord::Schema.define(version: 20161223234057) do

  create_table "addresses", force: :cascade do |t|
    t.string   "label"
    t.string   "street"
    t.string   "street2"
    t.string   "street3"
    t.string   "number"
    t.string   "care_of"
    t.string   "city"
    t.string   "state"
    t.string   "zip"
    t.float    "lat"
    t.float    "lon"
    t.string   "has_address_type"
    t.integer  "has_address_id"
    t.datetime "created_at",       null: false
    t.datetime "updated_at",       null: false
  end

  create_table "farm_cats", force: :cascade do |t|
    t.string   "name"
    t.text     "description"
    t.string   "main_image"
    t.integer  "farm_cat_id"
    t.string   "slug"
    t.string   "has_farm_cats_type"
    t.integer  "has_farm_cats_id"
    t.string   "master_class"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

  create_table "gal_images", force: :cascade do |t|
    t.integer  "gal_id"
    t.string   "caption"
    t.text     "description"
    t.string   "src"
    t.integer  "order"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  create_table "gals", force: :cascade do |t|
    t.integer  "main_image_id"
    t.string   "name"
    t.string   "has_farm_gals_type"
    t.integer  "has_farm_gals_id"
    t.text     "description"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

  create_table "objs", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end


text:
<?php

/**
 * This event handler lists all activated modules with the description
 * of each module.
 *
 * @package Zepi\Core\Management
 * @subpackage EventHandler
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */

namespace Zepi\Core\Management\EventHandler;

use \Zepi\Turbo\FrameworkInterface\CliEventHandlerInterface;
use \Zepi\Turbo\Framework;
use \Zepi\Turbo\Request\CliRequest;
use \Zepi\Turbo\Response\Response;
use \Zepi\Core\Management\Exception;

/**
 * This event handler lists all activated modules with the description
 * of each module.
 *
 * @author Matthias Zobrist <matthias.zobrist@zepi.net>
 * @copyright Copyright (c) 2015 zepi
 */
class ListModules implements CliEventHandlerInterface
{
    /**
     * This event handler lists all activated modules with the description
     * of each module.
     *
     * @access public
     * @param \Zepi\Turbo\Framework $framework
     * @param \Zepi\Turbo\Request\CliRequest $request
     * @param \Zepi\Turbo\Response\Response $response
     */
    public function execute(Framework $framework, CliRequest $request, Response $response)
    {
        $output = 'Activated modules:' . PHP_EOL;
        $output .= '==================' . PHP_EOL . PHP_EOL;
        $moduleManager = $framework->getModuleManager();
        foreach ($moduleManager->getModules() as $namespace => $module) {
            $properties = $moduleManager->getModuleProperties($module->getDirectory());
            $info = $properties->module;

            $output .= '- ' . $info->name . ' ' . $info->version . ' (' . $namespace . '):' . PHP_EOL;
            $output .= '  ' . $info->description . PHP_EOL . PHP_EOL;
        }

        $response->setOutputPart('modules', $output);
    }
}


text:
layout: post.new
title:  "git authors"
date:   2016-02-02 15:08:10 -0500
img: img/portfolio/safe.png
icon: ""
modalID: modalGitAuthors
category: Tools
---
**git-authors** is a simple addition to your editor - it displays the authors for a file so that you can contact them if required. Their % contributions are also shown.

# Why git-authors
As found by [Maalej et al](https://mobis.informatik.uni-hamburg.de/wp-content/uploads/2014/06/TOSEM-Maalej-Comprehension-PrePrint2.pdf) (page 20):

> The more people developers know, the easier they can identify which ex- perience is worth sharing, with whom, and how.

A simple Atom plugin bridges this gap by displaying the list of authors along with their percentage contribution to the file by line.

Github: [https://github.com/groktools/git-authors](https://github.com/groktools/git-authors)

Atom Package: [https://atom.io/packages/git-authors](https://atom.io/packages/git-authors)