text:
<?xml version="1.0"?>
<NiniDocs>

<Class name="IniException">
	<docs>
		Returns information about the last INI exception.
	</docs>
	<Property name="LinePosition">
		<docs>
			Returns the line position where the exception occurred.
		</docs>
	</Property>

	<Property name="LineNumber">
		<docs>
			Returns the line number where the exception occurred.
		</docs>
	</Property>

	<Property name="Message">
		<docs>
			Returns the exception message.
		</docs>
	</Property>

	<Constructor name="Constructor">
		<docs>
			Initializes an INI exception instance
		</docs>
	</Constructor>

	<Constructor name="ConstructorException">
		<docs>
			Initializes an INI exception instance
			<param name="message">
				The exception message.
			</param>
			<param name="exception">
				The Exception that threw this exception
			</param>
		</docs>
	</Constructor>

	<Constructor name="ConstructorSerialize">
		<docs>
			Initializes an INI exception instance
			<param name="info">
				The serialization information for this exception.
			</param>
			<param name="context">
				The object containing the context information for this
				exception.
			</param>
		</docs>
	</Constructor>

	<Constructor name="ConstructorMessage">
		<docs>
			Initializes an INI exception instance
			<param name="message">The exception message.</param>
		</docs>
	</Constructor>

	<Constructor name="ConstructorTextReader">
		<docs>
			Initializes a new instance of the class with the IniReader.
			<param name="reader">The IniReader.</param>
			<param name="message">The exception message.</param>
		</docs>
	</Constructor>

	<Method name="GetObjectData">
		<docs>
			ISerializable GetObjectData method.
			<remarks>
			</remarks>
			<param name="info">The serialized object data.</param>
			<param name="context">The context of the source or destination.</param>
		</docs>
	</Method>
</Class>

</NiniDocs>


text:
package com.neon.intellij.plugins.gitlab.view.toolwindow;

import com.intellij.icons.AllIcons;
import com.neon.intellij.plugins.gitlab.OpenIssueEditorAction;
import com.neon.intellij.plugins.gitlab.RefreshProjectIssuesAction;
import com.neon.intellij.plugins.gitlab.model.gitlab.GIPIssue;
import com.neon.intellij.plugins.gitlab.model.gitlab.GIPProject;
import com.neon.intellij.plugins.gitlab.model.intellij.GLProjectNode;

import javax.swing.*;

public class GLProjectPopup extends JPopupMenu {

    public GLProjectPopup(final GLProjectNode node,
                          final OpenIssueEditorAction openIssueEditorAction,
                          final RefreshProjectIssuesAction refreshProjectIssuesAction ) {
        final GIPProject project = node.getUserObject();

        JMenuItem refresh = new JMenuItem( "Refresh Issues", AllIcons.Actions.Refresh );
        refresh.addActionListener(e -> {
            refreshProjectIssuesAction.accept( node );
        });
        this.add( refresh );

        JMenuItem create = new JMenuItem( "New Issue", AllIcons.General.Add );
        create.addActionListener(e -> {
            GIPIssue issue = new GIPIssue();
            issue.project_id = project.id;
            openIssueEditorAction.accept( issue );
        });
        this.add( create );
    }

}

redpajama_set_name: RedPajamaGithub


text:
django-union
============

Unite several querysets into one.

This is now natively supported in Django since 1.11: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#union


text:
var hn = require('../');
var fs = require('fs');
var assert = require('assert');

describe('hn.js', function(){

  describe('#parsePage()', function(){
    it('should return with equal to fixture', function(done){
      fs.readFile(__dirname + '/fixture/home.html', function(err, body) {
        if(err) return done(err);

        hn.parsePage(body, function(err, items) {
          assert.equal(err, null);
          assert.deepEqual(items, JSON.parse(fs.readFileSync(__dirname + '/fixture/home.json')));
          done();

        });
      });
    });
  });

});


text:
package fr.openwide.core.test.wicket.more;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.wicket.model.IDetachable;
import org.apache.wicket.util.tester.WicketTester;
import org.javatuples.Tuple;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;

import fr.openwide.core.jpa.exception.SecurityServiceException;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.core.jpa.junit.AbstractTestCase;
import fr.openwide.core.test.wicket.more.business.person.service.IPersonService;
import fr.openwide.core.test.wicket.more.config.spring.SimpleWicketMoreTestWebappConfig;
import fr.openwide.core.test.wicket.more.junit.IWicketTestCase;
import fr.openwide.core.test.wicket.more.junit.WicketTesterTestExecutionListener;

@ContextConfiguration(classes = SimpleWicketMoreTestWebappConfig.class)
@TestExecutionListeners({ WicketTesterTestExecutionListener.class, DirtiesContextTestExecutionListener.class })
@DirtiesContext
public abstract class AbstractWicketMoreTestCase extends AbstractTestCase implements IWicketTestCase {

	private WicketTester wicketTester;

	@Autowired
	private IPersonService personService;

	@Override
	public void setWicketTester(WicketTester wicketTester) {
		this.wicketTester = wicketTester;
	}

	public WicketTester getWicketTester() {
		return wicketTester;
	}

	@Override
	protected void cleanAll() throws ServiceException, SecurityServiceException {
		cleanEntities(personService);
	}

	protected static <D extends IDetachable> D serializeAndDeserialize(D object) {
		object.detach();

		return doSerializeAndDeserialize(object);
	}

	protected static <T extends Tuple> T serializeAndDeserialize(T tuple) {
		for (Object value : tuple) {
			if (value instanceof IDetachable) {
				((IDetachable)value).detach();
			}
		}
		return doSerializeAndDeserialize(tuple);
	}

	@SuppressWarnings("unchecked")
	private static <T> T doSerializeAndDeserialize(T object) {
		byte[] array;
		try {
			ByteArrayOutputStream arrayOut = new ByteArrayOutputStream();
			ObjectOutputStream objectOut = new ObjectOutputStream(arrayOut);
			objectOut.writeObject(object);
			array = arrayOut.toByteArray();
		} catch (IOException e) {
			throw new RuntimeException("Error while serializing " + object, e);
		}

		try {
			ByteArrayInputStream arrayIn = new ByteArrayInputStream(array);
			ObjectInputStream objectIn = new ObjectInputStream(arrayIn);
			return (T) objectIn.readObject();
		} catch (IOException | ClassNotFoundException e) {
			throw new RuntimeException("Error while deserializing " + object, e);
		}
	}

}


text:
#ifndef _DAVINCI_VPFE_DM365_RESIZER_H
#define _DAVINCI_VPFE_DM365_RESIZER_H

enum resizer_oper_mode {
	RESIZER_MODE_CONTINIOUS = 0,
	RESIZER_MODE_ONE_SHOT = 1,
};

struct f_div_pass {
	unsigned int o_hsz;
	unsigned int i_hps;
	unsigned int h_phs;
	unsigned int src_hps;
	unsigned int src_hsz;
};

#define MAX_PASSES		2

struct f_div_param {
	unsigned char en;
	unsigned int num_passes;
	struct f_div_pass pass[MAX_PASSES];
};

/* Resizer Rescale Parameters*/
struct resizer_scale_param {
	bool h_flip;
	bool v_flip;
	bool cen;
	bool yen;
	unsigned short i_vps;
	unsigned short i_hps;
	unsigned short o_vsz;
	unsigned short o_hsz;
	unsigned short v_phs_y;
	unsigned short v_phs_c;
	unsigned short v_dif;
	/* resize method - Luminance */
	enum vpfe_rsz_intp_t v_typ_y;
	/* resize method - Chrominance */
	enum vpfe_rsz_intp_t v_typ_c;
	/* vertical lpf intensity - Luminance */
	unsigned char v_lpf_int_y;
	/* vertical lpf intensity - Chrominance */
	unsigned char v_lpf_int_c;
	unsigned short h_phs;
	unsigned short h_dif;
	/* resize method - Luminance */
	enum vpfe_rsz_intp_t h_typ_y;
	/* resize method - Chrominance */
	enum vpfe_rsz_intp_t h_typ_c;
	/* horizontal lpf intensity - Luminance */
	unsigned char h_lpf_int_y;
	/* horizontal lpf intensity - Chrominance */
	unsigned char h_lpf_int_c;
	bool dscale_en;
	enum vpfe_rsz_down_scale_ave_sz h_dscale_ave_sz;
	enum vpfe_rsz_down_scale_ave_sz v_dscale_ave_sz;
	/* store the calculated frame division parameter */
	struct f_div_param f_div;
};

enum resizer_rgb_t {
	OUTPUT_32BIT,
	OUTPUT_16BIT
};

enum resizer_rgb_msk_t {
	NOMASK = 0,
	MASKLAST2 = 1,
};

/* Resizer RGB Conversion Parameters */
struct resizer_rgb {
	bool rgb_en;
	enum resizer_rgb_t rgb_typ;
	enum resizer_rgb_msk_t rgb_msk0;
	enum resizer_rgb_msk_t rgb_msk1;
	unsigned int rgb_alpha_val;
};

/* Resizer External Memory Parameters */
struct rsz_ext_mem_param {
	unsigned int rsz_sdr_oft_y;
	unsigned int rsz_sdr_ptr_s_y;
	unsigned int rsz_sdr_ptr_e_y;
	unsigned int rsz_sdr_oft_c;
	unsigned int rsz_sdr_ptr_s_c;
	unsigned int rsz_sdr_ptr_e_c;
	/* offset to be added to buffer start when flipping for y/ycbcr */
	unsigned int flip_ofst_y;
	/* offset to be added to buffer start when flipping for c */
	unsigned int flip_ofst_c;
	/* c offset for YUV 420SP */
	unsigned int c_offset;
	/* User Defined Y offset for YUV 420SP or YUV420ILE data */
	unsigned int user_y_ofst;
	/* User Defined C offset for YUV 420SP data */
	unsigned int user_c_ofst;
};

enum rsz_data_source {
	IPIPE_DATA,
	IPIPEIF_DATA
};

enum rsz_src_img_fmt {
	RSZ_IMG_422,
	RSZ_IMG_420
};

enum rsz_dpaths_bypass_t {
	BYPASS_OFF = 0,
	BYPASS_ON = 1,
};

struct rsz_common_params {
	unsigned int vps;
	unsigned int vsz;
	unsigned int hps;
	unsigned int hsz;
	/* 420 or 422 */
	enum rsz_src_img_fmt src_img_fmt;
	/* Y or C when src_fmt is 420, 0 - y, 1 - c */
	unsigned char y_c;
	/* flip raw or ycbcr */
	unsigned char raw_flip;
	/* IPIPE or IPIPEIF data */
	enum rsz_data_source source;
	enum rsz_dpaths_bypass_t passthrough;
	unsigned char yuv_y_min;
	unsigned char yuv_y_max;
	unsigned char yuv_c_min;
	unsigned char yuv_c_max;
	bool rsz_seq_crv;
	enum vpfe_chr_pos out_chr_pos;
};

struct resizer_params {
	enum resizer_oper_mode oper_mode;
	struct rsz_common_params rsz_common;
	struct resizer_scale_param rsz_rsc_param[2];
	struct resizer_rgb rsz2rgb[2];
	struct rsz_ext_mem_param ext_mem_param[2];
	bool rsz_en[2];
	struct vpfe_rsz_config_params user_config;
};

#define ENABLE			1
#define DISABLE			(!ENABLE)

#define RESIZER_CROP_PAD_SINK		0
#define RESIZER_CROP_PAD_SOURCE		1
#define RESIZER_CROP_PAD_SOURCE2	2

#define RESIZER_CROP_PADS_NUM		3

enum resizer_crop_input_entity {
	RESIZER_CROP_INPUT_NONE = 0,
	RESIZER_CROP_INPUT_IPIPEIF = 1,
	RESIZER_CROP_INPUT_IPIPE = 2,
};

enum resizer_crop_output_entity {
	RESIZER_CROP_OUTPUT_NONE,
	RESIZER_A,
	RESIZER_B,
};

struct dm365_crop_resizer_device {
	struct v4l2_subdev			subdev;
	struct media_pad			pads[RESIZER_CROP_PADS_NUM];
	struct v4l2_mbus_framefmt		formats[RESIZER_CROP_PADS_NUM];
	enum resizer_crop_input_entity		input;
	enum resizer_crop_output_entity		output;
	enum resizer_crop_output_entity		output2;
	struct vpfe_resizer_device		*rsz_device;
};

#define RESIZER_PAD_SINK		0
#define RESIZER_PAD_SOURCE		1

#define RESIZER_PADS_NUM		2

enum resizer_input_entity {
	RESIZER_INPUT_NONE = 0,
	RESIZER_INPUT_CROP_RESIZER = 1,
};

enum resizer_output_entity {
	RESIZER_OUTPUT_NONE = 0,
	RESIZER_OUPUT_MEMORY = 1,
};

struct dm365_resizer_device {
	struct v4l2_subdev		subdev;
	struct media_pad		pads[RESIZER_PADS_NUM];
	struct v4l2_mbus_framefmt	formats[RESIZER_PADS_NUM];
	enum resizer_input_entity	input;
	enum resizer_output_entity	output;
	struct vpfe_video_device	video_out;
	struct vpfe_resizer_device	*rsz_device;
};

struct vpfe_resizer_device {
	struct dm365_crop_resizer_device	crop_resizer;
	struct dm365_resizer_device		resizer_a;
	struct dm365_resizer_device		resizer_b;
	struct resizer_params			config;
	void *__iomem base_addr;
};

int vpfe_resizer_init(struct vpfe_resizer_device *vpfe_rsz,
		      struct platform_device *pdev);
int vpfe_resizer_register_entities(struct vpfe_resizer_device *vpfe_rsz,
				   struct v4l2_device *v4l2_dev);
void vpfe_resizer_unregister_entities(struct vpfe_resizer_device *vpfe_rsz);
void vpfe_resizer_cleanup(struct vpfe_resizer_device *vpfe_rsz,
			  struct platform_device *pdev);
void vpfe_resizer_buffer_isr(struct vpfe_resizer_device *resizer);
void vpfe_resizer_dma_isr(struct vpfe_resizer_device *resizer);

#endif		/* _DAVINCI_VPFE_DM365_RESIZER_H */


text:
A small web/client program to play with sliding puzzles [(link)](http://jleahred.github.io/apps/puzzle3t/index.html)

There are three kind of topologies

* Plain (classical)
* Cylindrical
* Toroidal

This is my second web program the first one is [(link)](http://jleahred.github.io/apps/hello_world/index.html)

My urls in github to see the code...  [link](http://jleahred.github.io), [link](https://github.com/jleahred/puzzle3t) and [link](https://github.com/jleahred)

It has been developed with **Dart**

## Instructions

* Press [readme] to see/hide this file
* Press [setup] to access/hide configuration parameters
* Press [randomize] to mess the puzzle
* You can choose...

    * Image from server
    * Consecutive numbers
    * Color columns
    * Just two colors

### Difficulty

To train and learn how to solve, you can start with 2 Colors, and continue with colors.

Obviously, reducing the number of pieces will also reduce the complexity.

## Topologies

* **Plain** topology is the classic sliding puzzle game
* **Cylinder**, is a cylindric puzzle. You can move rows rotating them on the cylinder.
You can also move vertically pieces to the hole.
* **Toroidal** topology doesn't require a hole. You can move the whole row or column. Just try it, it's fun

## Moving

### Plain

* Click on piece to move

### Cylindrical

* In order to move a row, press mouse button and move the piece horizontally to new position
* In order to move vertically a piece to the hole, just click on this piece

## Toroidal

* Easy, just move the piece to the new position with left button pressed

## Credits

Developed by José Luis Esteban, Carolina Esteban Salgado and Marcos Esteban Salgado

## Todo

* Inprove randomize
* Full screen mode
* Working on tablets
* Small preview
* Using images from web (url)


text:
FROM centos:7

RUN yum install -y curl

# Install nvm
RUN touch .profile
RUN curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.30.2/install.sh | bash


text:
@implementation IntegerTransformer
+ (Class)transformedValueClass
{
    return [NSNumber class];
}

- (id)transformedValue:(id)value
{
    if (value == nil) return [NSNumber numberWithInteger:0];
    if([value respondsToSelector:@selector(intValue)])
    {
        int i = [value intValue];
        return [NSNumber numberWithInteger:i];
    }

    return [NSNumber numberWithInteger:0];
}
@end


text:
ACCEPTED

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

#### Published in
Lichenologist 22(3): 242 (1990)

#### Original name
Ramalina erosa Krog

### Remarks
null


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {
REGISTER5(BinaryOp, CPU, "SquaredDifference", functor::squared_difference,
          float, Eigen::half, double, int32, int64);
#if GOOGLE_CUDA
REGISTER4(BinaryOp, GPU, "SquaredDifference", functor::squared_difference,
          float, Eigen::half, double, int64);
#endif

// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(
    Name("SquaredDifference")
        .Device(DEVICE_GPU)
        .HostMemory("x")
        .HostMemory("y")
        .HostMemory("z")
        .TypeConstraint<int32>("T"),
    BinaryOp<CPUDevice, functor::squared_difference<int32>>);

#ifdef TENSORFLOW_USE_SYCL
REGISTER3(BinaryOp, SYCL, "SquaredDifference", functor::squared_difference,
          float, double, int64);
REGISTER_KERNEL_BUILDER(
    Name("SquaredDifference")
        .Device(DEVICE_SYCL)
        .HostMemory("x")
        .HostMemory("y")
        .HostMemory("z")
        .TypeConstraint<int32>("T"),
    BinaryOp<CPUDevice, functor::squared_difference<int32>>);
#endif  // TENSORFLOW_USE_SYCL

}  // namespace tensorflow


text:
class CreateBlackCards < ActiveRecord::Migration[5.1]
  def change
    create_table :black_cards do |t|
      t.text :title

      t.timestamps
    end
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Bulletninja - bulletninja</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="http://bullet.ninja/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//bullet.ninja/themes/ichi/assets/css/normalize.css?v=1482132052896" />
    <link rel="stylesheet" type="text/css" href="//bullet.ninja/themes/ichi/assets/css/foundation.min.css?v=1482132052896" />

    <link rel="stylesheet" type="text/css" href="//bullet.ninja/themes/ichi/assets/fonts/foundation-icons/foundation-icons.css?v=1482132052896" />
    <link rel="stylesheet" type="text/css" href="//bullet.ninja/themes/ichi/assets/css/styles.css?v=1482132052896" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans:300,700,400|Source+Sans+Pro:300,400,600,700,900,300italic,400italic,600italic,700italic,900italic" />

    <link rel="canonical" href="http://bullet.ninja/http://bullet.ninja/author/Bulletninja/" />
    <meta name="referrer" content="origin" />

    <meta property="og:site_name" content="bulletninja" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="Bulletninja - bulletninja" />
    <meta property="og:url" content="http://bullet.ninja/http://bullet.ninja/author/Bulletninja/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Bulletninja - bulletninja" />
    <meta name="twitter:url" content="http://bullet.ninja/http://bullet.ninja/author/Bulletninja/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="bulletninja" href="http://bullet.ninja/rss/" />

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

    <button type="button" class="overlay-close">Close</button>

Home

bulletninja

Bulletninja

             1 post

        Page 1 of 1

Multiples of 3 and 5

Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The »

            Bulletninja
             on project euler,  python
            <time class="post-date" datetime="2015-11-02">02 November 2015</time>

        Page 1 of 1


text:
package br.edu.ufcg.computacao.si1.service;

import br.edu.ufcg.computacao.si1.model.Anuncio;
import br.edu.ufcg.computacao.si1.model.Usuario;
import br.edu.ufcg.computacao.si1.model.form.AnuncioForm;
import br.edu.ufcg.computacao.si1.repository.AnuncioRepository;
import br.edu.ufcg.computacao.si1.repository.UsuarioRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by Marcus Oliveira on 28/12/16.
 */
@Service
public class AnuncioServiceImpl implements AnuncioService {
	// TODO add validity checks

	@Autowired
	private AnuncioRepository anuncioRepository;
	@Autowired
	private AnuncioServiceImpl anuncioService;
	@Autowired
	private UsuarioServiceImpl usuarioServiceImpl;
	@Autowired
	private UsuarioRepository usuarioRepository;

	@Autowired
	public AnuncioServiceImpl(AnuncioRepository anuncioRepository) {
		/* neste codigo apenas atribuimos o repositorio jpa ao atributo */
		this.anuncioRepository = anuncioRepository;
	}

	public AnuncioRepository getAnuncioRepository() {
		return this.anuncioRepository;
	}

	@Override
	public Anuncio create(Anuncio anuncio) {
		/* aqui salvamos o anuncio recem criado no repositorio jpa */
		return anuncioRepository.save(anuncio);
	}

	@Override
	public Optional<Anuncio> getById(Long id) {
		/* aqui recuperamos o anuncio pelo seu id */
		return Optional.ofNullable(anuncioRepository.findOne(id));
	}

	@Override
	public Collection<Anuncio> get(String tipo) {

		/*
		 * pegamos aqui todos os anuncios, mas retornamos os anuncios por tipo
		 * filtrando o tipo, pelo equals, retornando um arrayLista
		 */
		return anuncioRepository.findAll().stream().filter(anuncio -> anuncio.getTipo().equals(tipo))
				.collect(Collectors.toCollection(ArrayList::new));
	}

	@Override
	public Collection<Anuncio> getAll() {
		/* aqui retornamos todos os anuncios, sem distincao */

		return anuncioRepository.findAll();
	}

	@Override
	public boolean update(Anuncio anuncio) {
		/* a atualizacao do anuncio eh feita apenas se o anuncio ja existir */
		if (anuncioRepository.exists(anuncio.get_id())) {
			anuncioRepository.save(anuncio);
			return true;
		}
		return false;
	}

	@Override
	public boolean delete(Long id) {
		/* aqui se apaga o anuncio se ele existir */

		if (anuncioRepository.exists(id)) {
			anuncioRepository.delete(id);
			return true;
		}
		return false;
	}

	@Override
	public Collection<Anuncio> getAnuncioByDateFormat(Date data) {
		return anuncioRepository.getAnuncioByDataDeCriacao(data);
	}

	@Override
	public Anuncio cadastrarAnuncio(AnuncioForm anuncioForm) {
		Anuncio anuncio = new Anuncio();
		anuncio.setTitulo(anuncioForm.getTitulo());
		anuncio.setPreco(anuncioForm.getPreco());
		anuncio.setTipo(anuncioForm.getTipo());

		Usuario usuarioLogado = usuarioServiceImpl.usuarioLogadoEmail();
		Long idUsuario = usuarioLogado.getId();
		anuncio.setIdUsuario(idUsuario);

		return anuncioService.create(anuncio);
	}

	@Override
	public void compraAnuncio(Long id) {
		Usuario usuarioLogado = usuarioServiceImpl.usuarioLogadoEmail();

		Anuncio recuperaAnuncio = anuncioRepository.findOne(id);
		// usuario logado compra o anuncio
		usuarioLogado.compraAnuncio(recuperaAnuncio.getPreco());

		// usuario que tem o anuncio vai vender
		Usuario usuarioDonoAnuncio = usuarioRepository.findOne(recuperaAnuncio.getIdUsuario());
		usuarioDonoAnuncio.vendeAnuncio(recuperaAnuncio.getPreco());

		// excluir anuncio
		anuncioRepository.delete(id);

	}

}


text:
package org.gradle.tooling.internal.provider;

import org.gradle.initialization.layout.BuildLayoutFactory;
import org.gradle.internal.event.ListenerManager;
import org.gradle.internal.jvm.inspection.JvmVersionDetector;
import org.gradle.internal.logging.events.OutputEventListener;
import org.gradle.internal.logging.services.LoggingServiceRegistry;
import org.gradle.internal.service.ServiceRegistration;
import org.gradle.internal.service.ServiceRegistry;
import org.gradle.internal.service.scopes.GlobalScopeServices;
import org.gradle.launcher.daemon.client.DaemonClientFactory;
import org.gradle.launcher.daemon.client.DaemonClientGlobalServices;
import org.gradle.launcher.exec.BuildExecuter;
import org.gradle.tooling.internal.adapter.ProtocolToModelAdapter;
import org.gradle.tooling.internal.provider.serialization.ClassLoaderCache;
import org.gradle.tooling.internal.provider.serialization.ClasspathInferer;
import org.gradle.tooling.internal.provider.serialization.ClientSidePayloadClassLoaderFactory;
import org.gradle.tooling.internal.provider.serialization.ClientSidePayloadClassLoaderRegistry;
import org.gradle.tooling.internal.provider.serialization.DefaultPayloadClassLoaderRegistry;
import org.gradle.tooling.internal.provider.serialization.ModelClassLoaderFactory;
import org.gradle.tooling.internal.provider.serialization.PayloadSerializer;
import org.gradle.tooling.internal.provider.serialization.WellKnownClassLoaderRegistry;

/**
 * Shared services for a tooling API provider connection.
 */
public class ConnectionScopeServices {
    private final LoggingServiceRegistry loggingServices;

    public ConnectionScopeServices(LoggingServiceRegistry loggingServices) {
        this.loggingServices = loggingServices;
    }

    void configure(ServiceRegistration serviceRegistration) {
        serviceRegistration.add(LoggingServiceRegistry.class, loggingServices);
        serviceRegistration.addProvider(new GlobalScopeServices(true));
        serviceRegistration.addProvider(new DaemonClientGlobalServices());
    }

    ShutdownCoordinator createShutdownCoordinator(ListenerManager listenerManager, DaemonClientFactory daemonClientFactory, OutputEventListener outputEventListener) {
        ShutdownCoordinator shutdownCoordinator = new ShutdownCoordinator(daemonClientFactory, outputEventListener);
        listenerManager.addListener(shutdownCoordinator);
        return shutdownCoordinator;
    }

    ProviderConnection createProviderConnection(BuildExecuter buildActionExecuter,
                                                DaemonClientFactory daemonClientFactory,
                                                BuildLayoutFactory buildLayoutFactory,
                                                ServiceRegistry serviceRegistry,
                                                JvmVersionDetector jvmVersionDetector,
                                                // This is here to trigger creation of the ShutdownCoordinator. Could do this in a nicer way
                                                ShutdownCoordinator shutdownCoordinator) {
        ClassLoaderCache classLoaderCache = new ClassLoaderCache();
        return new ProviderConnection(
                serviceRegistry,
                loggingServices,
                buildLayoutFactory,
                daemonClientFactory,
                buildActionExecuter,
                new PayloadSerializer(
                        new WellKnownClassLoaderRegistry(
                            new ClientSidePayloadClassLoaderRegistry(
                                new DefaultPayloadClassLoaderRegistry(
                                    classLoaderCache,
                                    new ClientSidePayloadClassLoaderFactory(
                                        new ModelClassLoaderFactory())),
                                new ClasspathInferer(),
                                classLoaderCache))),
            jvmVersionDetector
        );
    }

    ProtocolToModelAdapter createProtocolToModelAdapter() {
        return new ProtocolToModelAdapter();
    }
}


text:
#pragma once

#include <glog/logging.h>

#include <folly/Conv.h>

namespace folly {

namespace detail {

template <typename T, typename BucketT>
HistogramBuckets<T, BucketT>::HistogramBuckets(
    ValueType bucketSize,
    ValueType min,
    ValueType max,
    const BucketType& defaultBucket)
    : bucketSize_(bucketSize), min_(min), max_(max) {
  CHECK_GT(bucketSize_, ValueType(0));
  CHECK_LT(min_, max_);

  // Deliberately make this a signed type, because we're about
  // to compare it against max-min, which is nominally signed, too.
  int64_t numBuckets = int64_t((max - min) / bucketSize);
  // Round up if the bucket size does not fit evenly
  if (numBuckets * bucketSize < max - min) {
    ++numBuckets;
  }
  // Add 2 for the extra 'below min' and 'above max' buckets
  numBuckets += 2;
  buckets_.assign(size_t(numBuckets), defaultBucket);
}

template <typename T, typename BucketType>
size_t HistogramBuckets<T, BucketType>::getBucketIdx(ValueType value) const {
  if (value < min_) {
    return 0;
  } else if (value >= max_) {
    return buckets_.size() - 1;
  } else {
    // the 1 is the below_min bucket
    return size_t(((value - min_) / bucketSize_) + 1);
  }
}

template <typename T, typename BucketType>
template <typename CountFn>
uint64_t HistogramBuckets<T, BucketType>::computeTotalCount(
    CountFn countFromBucket) const {
  uint64_t count = 0;
  for (size_t n = 0; n < buckets_.size(); ++n) {
    count += countFromBucket(const_cast<const BucketType&>(buckets_[n]));
  }
  return count;
}

template <typename T, typename BucketType>
template <typename CountFn>
size_t HistogramBuckets<T, BucketType>::getPercentileBucketIdx(
    double pct,
    CountFn countFromBucket,
    double* lowPct,
    double* highPct) const {
  CHECK_GE(pct, 0.0);
  CHECK_LE(pct, 1.0);

  auto numBuckets = buckets_.size();

  // Compute the counts in each bucket
  std::vector<uint64_t> counts(numBuckets);
  uint64_t totalCount = 0;
  for (size_t n = 0; n < numBuckets; ++n) {
    uint64_t bucketCount =
        countFromBucket(const_cast<const BucketType&>(buckets_[n]));
    counts[n] = bucketCount;
    totalCount += bucketCount;
  }

  // If there are no elements, just return the lowest bucket.
  // Note that we return bucket 1, which is the first bucket in the
  // histogram range; bucket 0 is for all values below min_.
  if (totalCount == 0) {
    // Set lowPct and highPct both to 0.
    // getPercentileEstimate() will recognize this to mean that the histogram
    // is empty.
    if (lowPct) {
      *lowPct = 0.0;
    }
    if (highPct) {
      *highPct = 0.0;
    }
    return 1;
  }

  // Loop through all the buckets, keeping track of each bucket's
  // percentile range: [0,10], [10,17], [17,45], etc.  When we find a range
  // that includes our desired percentile, we return that bucket index.
  double prevPct = 0.0;
  double curPct = 0.0;
  uint64_t curCount = 0;
  size_t idx;
  for (idx = 0; idx < numBuckets; ++idx) {
    if (counts[idx] == 0) {
      // skip empty buckets
      continue;
    }

    prevPct = curPct;
    curCount += counts[idx];
    curPct = static_cast<double>(curCount) / totalCount;
    if (pct <= curPct) {
      // This is the desired bucket
      break;
    }
  }

  if (lowPct) {
    *lowPct = prevPct;
  }
  if (highPct) {
    *highPct = curPct;
  }
  return idx;
}

template <typename T, typename BucketType>
template <typename CountFn, typename AvgFn>
T HistogramBuckets<T, BucketType>::getPercentileEstimate(
    double pct, CountFn countFromBucket, AvgFn avgFromBucket) const {
  // Find the bucket where this percentile falls
  double lowPct;
  double highPct;
  size_t bucketIdx =
      getPercentileBucketIdx(pct, countFromBucket, &lowPct, &highPct);
  if (lowPct == 0.0 && highPct == 0.0) {
    // Invalid range -- the buckets must all be empty
    // Return the default value for ValueType.
    return ValueType();
  }
  if (lowPct == highPct) {
    // Unlikely to have exact equality,
    // but just return the bucket average in this case.
    // We handle this here to avoid division by 0 below.
    return avgFromBucket(buckets_[bucketIdx]);
  }

  CHECK_GE(pct, lowPct);
  CHECK_LE(pct, highPct);
  CHECK_LT(lowPct, highPct);

  // Compute information about this bucket
  ValueType avg = avgFromBucket(buckets_[bucketIdx]);
  ValueType low;
  ValueType high;
  if (bucketIdx == 0) {
    if (kIsExact && min_ < avg) {
      // This normally shouldn't happen.  This bucket is only supposed to track
      // values less than min_.  Most likely this means that integer overflow
      // occurred, and the code in avgFromBucket() returned a huge value
      // instead of a small one.  Just return the minimum possible value for
      // now.
      //
      // (Note that if the counter keeps being decremented, eventually it will
      // wrap and become small enough that we won't detect this any more, and
      // we will return bogus information.)
      LOG(ERROR) << "invalid average value in histogram minimum bucket: " << avg
                 << " > " << min_ << ": possible integer overflow?";
      return getBucketMin(bucketIdx);
    }
    // For the below-min bucket, just assume the lowest value ever seen is
    // twice as far away from min_ as avg.
    high = min_;
    low = high - (2 * (high - avg));
    // Adjust low in case it wrapped
    if (low > avg) {
      low = std::numeric_limits<ValueType>::min();
    }
  } else if (bucketIdx == buckets_.size() - 1) {
    if (kIsExact && avg < max_) {
      // Most likely this means integer overflow occurred.  See the comments
      // above in the minimum case.
      LOG(ERROR) << "invalid average value in histogram maximum bucket: " << avg
                 << " < " << max_ << ": possible integer overflow?";
      return getBucketMax(bucketIdx);
    }
    // Similarly for the above-max bucket, assume the highest value ever seen
    // is twice as far away from max_ as avg.
    low = max_;
    high = low + (2 * (avg - low));
    // Adjust high in case it wrapped
    if (high < avg) {
      high = std::numeric_limits<ValueType>::max();
    }
  } else {
    low = getBucketMin(bucketIdx);
    high = getBucketMax(bucketIdx);
    if (kIsExact && (avg < low || avg > high)) {
      // Most likely this means an integer overflow occurred.
      // See the comments above.  Return the midpoint between low and high
      // as a best guess, since avg is meaningless.
      LOG(ERROR) << "invalid average value in histogram bucket: " << avg
                 << " not in range [" << low << ", " << high
                 << "]: possible integer overflow?";
      return (low + high) / 2;
    }
  }

  // Since we know the average value in this bucket, we can do slightly better
  // than just assuming the data points in this bucket are uniformly
  // distributed between low and high.
  //
  // Assume that the median value in this bucket is the same as the average
  // value.
  double medianPct = (lowPct + highPct) / 2.0;
  if (pct < medianPct) {
    // Assume that the data points lower than the median of this bucket
    // are uniformly distributed between low and avg
    double pctThroughSection = (pct - lowPct) / (medianPct - lowPct);
    return T(low + ((avg - low) * pctThroughSection));
  } else {
    // Assume that the data points greater than the median of this bucket
    // are uniformly distributed between avg and high
    double pctThroughSection = (pct - medianPct) / (highPct - medianPct);
    return T(avg + ((high - avg) * pctThroughSection));
  }
}

} // namespace detail

template <typename T>
std::string Histogram<T>::debugString() const {
  std::string ret = folly::to<std::string>(
      "num buckets: ",
      buckets_.getNumBuckets(),
      ", bucketSize: ",
      buckets_.getBucketSize(),
      ", min: ",
      buckets_.getMin(),
      ", max: ",
      buckets_.getMax(),
      "\n");

  for (size_t i = 0; i < buckets_.getNumBuckets(); ++i) {
    folly::toAppend(
        "  ",
        buckets_.getBucketMin(i),
        ": ",
        buckets_.getByIndex(i).count,
        "\n",
        &ret);
  }

  return ret;
}

template <typename T>
void Histogram<T>::toTSV(std::ostream& out, bool skipEmptyBuckets) const {
  for (size_t i = 0; i < buckets_.getNumBuckets(); ++i) {
    // Do not output empty buckets in order to reduce data file size.
    if (skipEmptyBuckets && getBucketByIndex(i).count == 0) {
      continue;
    }
    const auto& bucket = getBucketByIndex(i);
    out << getBucketMin(i) << '\t' << getBucketMax(i) << '\t' << bucket.count
        << '\t' << bucket.sum << '\n';
  }
}

} // namespace folly


text:
package org.jbb.security.api.oauth;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class OAuthClientSearchCriteria {

    private String clientId;

    private String displayedName;

    @Builder.Default
    private Pageable pageRequest = PageRequest.of(0, 20);

}


text:
/**
 * File UniformAi.java
 * @author Yuri Kravchik
 * Created 16.05.2008
 */
package yk.senjin.shaders.uniforms;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL20;

import java.nio.IntBuffer;

/**
 * UniformAi
 *
 * @author Yuri Kravchik Created 16.05.2008
 */
public class Uniform4Ai extends UniformVariable {
    private final IntBuffer values;

    public Uniform4Ai(final String name, final Integer... values) {
        super(name);
        this.values = BufferUtils.createIntBuffer(values.length);
        for (final Integer i : values) {
            this.values.put(i);
        }
        this.values.rewind();
    }

    @Override
    public void plug() {
        GL20.glUniform4(index, values);
    }
}


text:
module QueuedMail
  class DeliveryMethod
    def initialize(options)
      @options = options
    end

    def deliver!(mail)
      message = QueuedMail::Message.new(:source => mail.to_s)

      addresses = mail.bcc
      if addresses
        message.bcc_addresses = addresses.map{|address| address.to_s.scan(/^.*?([a-zA-Z0-9._+-]+@[a-zA-Z0-9._-]+?)(?![a-zA-Z0-9._-]).*$/).flatten.first }.uniq.compact.join(', ')
      end

      message.save
      enqueue(message.id)
    end

    private
    def enqueue(message_id)
      service = instance_eval("QueuedMail::Queue::#{ Rails.application.config.mail_queue_service.to_s.camelcase }")
      service.enqueue(message_id)
    end
  end
end


text:
layout: post
title:  "El Pulpo Caliente"
date:   2017-02-10
excerpt: "I came, I knit, I conquered"
project: true
preview: pulpo.jpg
tag:
- knitting
comments: false
---

## Who
My sister, also me

## What
A giant sweater covered with a giant octopus

![el pulpo caliente](/assets/img/pulpo-caliente.jpg)

## When
December 22 - December 28, 2016

## Why

My sister is one of those people who is constantly cold. In southern California where we grew up, this is never really an issue, because the temperature stays in that ideal 60-80 range for 360 days per year. When she visits, even in August, she tells me that it is too cold at my house in San Leandro. It is never cold here in August.

She, for some reason, is traveling to Germany and Russia this winter as part of a study-abroad/touring-theater-group. This is concerning for a lot of reasons, but mostly because IT SNOWS IN RUSSIA. Clearly, I had to knit something to keep her warm and also to impress the local grandmas. You can go far if you have the blessing of the local grandmas.

I never have time to knit, especially not a big sweater with a complicated octopus face on it. Between the cats and the job and the house, I am lucky if I have time and the braincells to knit a hat every couple of weeks. December rolled around, and I had not started on this sweater, which I had promised as a christmas present. Mid december came, and the yarn was still sitting in its bag, taunting me.

I started knitting on the bus ride to LA, and only stopped to eat and sleep. I finished it the night before I had to go back. I am ridiculously pleased with it, and am also thrilled to know that it is traveling across Europe and getting compliments from every babushka it meets.


text:
/**
 * Created by josemanuel on 3/21/14.
 */
module latte {

    /**
     * Used to model swatches on the palettes
     */
    export interface ColorPickerSwatch{

        /**
         * Bounds of swatch in canvas
         */
        bounds: Rectangle;

        /**
         * Color of swatch
         */
        color: Color;
    }

    /**
     *
     */
    export class ColorPicker extends ItemStack {

        //region Static
        //endregion

        //region Fields
        //endregion

        /**
         *
         */
        constructor() {
            super();

            // Structure
            var wrapper = new Item();
            wrapper.element.append(this.canvas);
            this.items.add(wrapper);

            this.items.add(this.toolbar);
            this.toolbar.sideItems.addArray([
                this.lblIndicator,
                this.txtHex
            ])

            // Init selection
            this.color = Color.transparent;
        }

        //region Private Methods
        //endregion

        //region Methods

        /**
         * Handles mouse move on canvas
         * @param screenX
         * @param screenY
         */
        canvasMouseMove(screenX: number, screenY: number){

            var swatch = this.swatchAt(screenX, screenY);

            if(swatch) {
//                console.log(swatch.color.toString());
            }

        }

        /**
         * Handles mouse down on canvas
         * @param screenX
         * @param screenY
         */
        canvasMouseDown(screenX: number, screenY: number){

            var swatch = this.swatchAt(screenX, screenY);

            if(swatch) {
                this.color = swatch.color;
            }

        }

        /**
         * Draws the palette
         */
        drawPalette(){

            var canvasWidth = this.canvas.width();
            var canvasHeight = this.canvas.height();

            this.context.clearRect(0, 0, canvasWidth, canvasHeight);

            var swatchSize = canvasWidth / 20;

            //region Swatches

            this._swatches = [];

            var selectedSwatch: ColorPickerSwatch = null;

            // Adds a swatch to the palette
            var swatch = (x: number, y: number, color: string) => {

                var r = new Rectangle(x * swatchSize, y *swatchSize, swatchSize, swatchSize);
                var colorObj = (color == 'transparent' ?Color.transparent : Color.fromHex(color));
                this.context.fillStyle = color;
                this.context.fillRect(r.left, r.top, r.width, r.height);

                var swatch: ColorPickerSwatch = {
                    bounds: r,
                    color: colorObj
                }

                this.swatches.push(swatch);

                if(colorObj.isTransparent) {
                    this.context.lineWidth = 3;
                    this.context.strokeStyle = 'red';
                    this.context.beginPath();
                    this.context.moveTo(r.right, r.top);
                    this.context.lineTo(r.left, r.bottom);
                    this.context.stroke();
                    this.context.lineWidth = 1;
                }

                if(!selectedSwatch && colorObj.toString() == this.color.toString()) {
                    selectedSwatch = swatch;
                }
            }

            var swatchGroup = (x, y, initialRed) => {

                var startX = x;
                var startY = y;
                var colorValues = ['0', '3', '6', '9', 'C', 'F'];
                var r = colorValues[initialRed];
                var g = '0';
                var b = '0';

                for(var j = 0; j < colorValues.length; j++){
                    b = colorValues[j];
                    for(var i = 0; i < colorValues.length; i++){
                        g = colorValues[i];
                        swatch(startX + i, startY + j, sprintf('#%s%s%s%s%s%s', r, r, g, g, b, b));
                    }
                    g = colorValues[0];

                }
            }

            swatchGroup(2, 0, 0);
            swatchGroup(8, 0, 1);
            swatchGroup(14, 0, 2);
            swatchGroup(2, 6, 3);
            swatchGroup(8, 6, 4);
            swatchGroup(14, 6, 5);

            swatch(0, 0, '#000000');
            swatch(0, 1, '#333333');
            swatch(0, 2, '#666666');
            swatch(0, 3, '#999999');
            swatch(0, 4, '#CCCCCC');
            swatch(0, 5, '#FFFFFF');
            swatch(0, 6, '#FF0000');
            swatch(0, 7, '#00FF00');
            swatch(0, 8, '#0000FF');
            swatch(0, 9, '#FFFF00');
            swatch(0, 10, '#00FFFF');
            swatch(0, 11, '#FF00FF');

            for(var i = 0; i <= 10; i++) swatch(1, i, '#000');

            swatch(1, 11, 'transparent');

            //endregion

            //region Grid

            this.context.strokeStyle = 'black';

            var gridX = 0;
            var gridY = 0;

            for(var i = 0; i < Math.ceil(canvasWidth / swatchSize) + 1; i++){
                this.context.beginPath();
                this.context.moveTo(i * swatchSize, 0);
                this.context.lineTo(i * swatchSize, canvasHeight);
                this.context.stroke();
            }

            for(var i = 0; i < Math.ceil(canvasHeight / swatchSize) + 1; i++){
                this.context.beginPath();
                this.context.moveTo(0, i * swatchSize);
                this.context.lineTo(canvasWidth, i * swatchSize);
                this.context.stroke();
            }

            //endregion

            //region Mark Selection
            if(selectedSwatch) {
                this.context.lineWidth = 2;
                this.context.strokeStyle = 'white';
                this.context.strokeRect(selectedSwatch.bounds.left, selectedSwatch.bounds.top,
                    selectedSwatch.bounds.width, selectedSwatch.bounds.height);
                this.context.lineWidth = 1;
            }
            //endregion

        }

        /**
         * Raises the <c>color</c> event
         */
        onColorChanged(){
            if(this._colorChanged){
                this._colorChanged.raise();
            }

            this.txtHex.value = this.color.toString().toUpperCase();
            this.lblIndicator.css({background: this.color.toString()});
            this.drawPalette();
        }

        /**
         * Override.
         */
        onLayout(){
            super.onLayout();

            // Get swatch size
            var swatchSize = this.element.width() / 20;

            // Adjust height to 12 swatches
            var swatchesHeight = swatchSize * 12;

            // Pass width & height
            this.canvas.attr('width', this.element.width());
            this.canvas.attr('height', swatchesHeight);

            // Redraw palette
            this.drawPalette();
        }

        /**
         * Gets the swatch at the specified point (if any)
         * @param screenX
         * @param screenY
         * @returns {*}
         */
        swatchAt(screenX: number, screenY: number){

            var offset: {top: number; left: number} = this.canvas.offset();

            var x = screenX - offset.left;
            var y = screenY - offset.top;

            for (var i = 0; i < this.swatches.length; i++) {
                var colorPickerSwatch:ColorPickerSwatch = this.swatches[i];

                if(colorPickerSwatch.bounds.contains(x, y)) {
                    return colorPickerSwatch;
                }
            }

            return null;

        }

        //endregion

        //region Events

        /**
         * Back field for event
         */
        private _colorChanged: LatteEvent

        /**
         * Gets an event raised when the value of the color property changes
         *
         * @returns {LatteEvent}
         */
        public get colorChanged(): LatteEvent{
            if(!this._colorChanged){
                this._colorChanged = new LatteEvent(this);
            }
            return this._colorChanged;
        }
        //endregion

        //region Components

        /**
         * Field for canvas property
         */
        private _canvas:JQuery;

        /**
         * Gets the canvas where color palette is drawn
         *
         * @returns {JQuery}
         */
        public get canvas():JQuery {
            if (!this._canvas) {
                this._canvas = jQuery('<canvas>');
                this._canvas.mousemove((e: JQueryEventObject) => { this.canvasMouseMove(e.pageX, e.pageY) });
                this._canvas.mousedown((e) => { this.canvasMouseDown(e.pageX, e.pageY) });
            }
            return this._canvas;
        }

        /**
         * Field for lblIndicator property
         */
        private _lblIndicator:LabelItem;

        /**
         * Gets the color indicator label
         *
         * @returns {LabelItem}
         */
        public get lblIndicator():LabelItem {
            if (!this._lblIndicator) {
                this._lblIndicator = new LabelItem();
                this._lblIndicator.css({
                    border: 'solid 1px black',
                    width: 50,
                    minHeight: 25,
                    marginTop: -1,
                    marginLeft: 10
                });

            }
            return this._lblIndicator;
        }

        /**
         * Field for toolbar property
         */
        private _toolbar:Toolbar;

        /**
         * Gets the toolbar
         *
         * @returns {Toolbar}
         */
        public get toolbar():Toolbar {
            if (!this._toolbar) {
                this._toolbar = new Toolbar();
            }
            return this._toolbar;
        }

        /**
         * Field for txtHex property
         */
        private _txtHex:TextboxItem;

        /**
         * Gets the textbox item
         *
         * @returns {TextboxItem}
         */
        public get txtHex():TextboxItem {
            if (!this._txtHex) {
                this._txtHex = new TextboxItem();
//                this._txtHex.width = 60;
                this._txtHex.enterPressed.add(() => {
                    this.color = Color.fromHex(this._txtHex.value);
                });
            }
            return this._txtHex;
        }

        //endregion

        //region Properties

        /**
         * Property field
         */
        private _color: Color = null;

        /**
         * Gets or sets the selected color of the picker
         *
         * @returns {Color}
         */
        public get color(): Color{
            return this._color;
        }

        /**
         * Gets or sets the selected color of the picker
         *
         * @param {Color} value
         */
        public set color(value: Color){

            // Check if value changed
            var changed: boolean = value !== this._color;

            // Set value
            this._color = value;

            // Trigger changed event
            if(changed){
                this.onColorChanged();
            }
        }

        /**
         * Field for context property
         */
        private _context:CanvasRenderingContext2D;

        /**
         * Gets the context for rendering
         *
         * @returns {CanvasRenderingContext2D}
         */
        public get context():CanvasRenderingContext2D {
            if (!this._context) {
                this._context = this.canvas.get(0).getContext('2d');
            }
            return this._context;
        }

        /**
         * Field for swatches property
         */
        private _swatches:ColorPickerSwatch[] = [];

        /**
         * Gets the swatches on the canvas
         *
         * @returns {ColorPickerSwatch[]}
         */
        public get swatches():ColorPickerSwatch[] {
            return this._swatches;
        }

        //endregion

    }

}


text:
namespace HomeCloud.Api.Formatters
{
	#region Usings

	using System;
	using System.Diagnostics.CodeAnalysis;
	using System.IO;
	using System.Linq;
	using System.Reflection;
	using System.Text;
	using System.Threading.Tasks;

	using HomeCloudApi.Helpers;

	using Microsoft.AspNetCore.Http.Features;
	using Microsoft.AspNetCore.Mvc.Formatters;
	using Microsoft.AspNetCore.WebUtilities;

	using Microsoft.Net.Http.Headers;

	#endregion

	/// <summary>
	/// Represents the <see cref="MultipartFormDataInputFormatter"/> class to handle <see cref="multipart/form-data"/> requests.
	/// </summary>
	public class MultipartFormDataInputFormatter : InputFormatter
	{
		#region Private Constants

		/// <summary>
		/// The <see cref="multipart/form-data"/> content type
		/// </summary>
		private const string MultipartContentType = "multipart/form-data";

		/// <summary>
		/// The <see cref="FileName"/> property name
		/// </summary>
		private const string FileNamePropertyName = "FileName";

		/// <summary>
		/// The <see cref="Stream"/> property name
		/// </summary>
		private const string StreamPropertyName = "Stream";

		#endregion

		#region Private Members

		/// <summary>
		/// The default form options to set the default limits for request body data.
		/// </summary>
		private static readonly FormOptions DefaultFormOptions = new FormOptions();

		#endregion

		#region Constructors

		/// <summary>
		/// Initializes a new instance of the <see cref="MultipartFormDataInputFormatter"/> class.
		/// </summary>
		public MultipartFormDataInputFormatter()
			: base()
		{
			this.SupportedMediaTypes.Add(MultipartContentType);
		}

		#endregion

		/// <summary>
		/// Indicates whether the current instance of <see cref="InputFormatter"/> can read request.
		/// </summary>
		/// <param name="context"><see cref="InputFormatterContext"/> context.</param>
		/// <returns><c>true</c> if the instance can read request. Otherwise <c>false</c>.</returns>
		/// <inheritdoc />
		public override bool CanRead(InputFormatterContext context)
		{
			return MultipartRequestHelper.IsMultipartContentType(context.HttpContext.Request.ContentType);
		}

		/// <summary>
		/// Reads an object from the request body.
		/// </summary>
		/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Formatters.InputFormatterContext" />.</param>
		/// <returns>
		/// A <see cref="T:System.Threading.Tasks.Task" /> that on completion deserializes the request body.
		/// </returns>
		[SuppressMessage("Microsoft.StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "C# 7.0 syntax not supported")]
		public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
		{
			if (context is null)
			{
				throw new ArgumentNullException(nameof(context));
			}

			try
			{
				var request = context.HttpContext.Request;

				if (request.Body.CanSeek)
				{
					request.Body.Seek(0, SeekOrigin.Begin);
				}

				object model = context.ModelType.GetConstructor(Type.EmptyTypes).Invoke(null);

				string boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(request.ContentType), DefaultFormOptions.MultipartBoundaryLengthLimit);
				MultipartReader reader = new MultipartReader(boundary, request.Body);

				bool isSuccess = false;
				bool isReadable = true;

				do
				{
					MultipartSection section = await reader.ReadNextSectionAsync();

					isReadable = section != null;
					if (isReadable && ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition))
					{
						if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
						{
							SetProperty(model, FileNamePropertyName, HeaderUtilities.RemoveQuotes(contentDisposition.FileName).ToString());
							SetProperty(model, StreamPropertyName, section.Body, false);

							isSuccess = true;

							isReadable = false;
						}
						else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
						{
							string key = HeaderUtilities.RemoveQuotes(contentDisposition.Name).ToString();
							Encoding encoding = GetEncoding(section);

							string value = null;

							using (StreamReader streamReader = new StreamReader(section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true))
							{
								value = await streamReader.ReadToEndAsync();

								if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
								{
									value = string.Empty;
								}
							}

							SetProperty(model, key, value);

							isSuccess = true;
						}
					}
				}
				while (isReadable);

				if (!isSuccess && !context.TreatEmptyInputAsDefaultValue)
				{
					return InputFormatterResult.NoValue();
				}

				return InputFormatterResult.Success(model);
			}
			catch
			{
				return InputFormatterResult.Failure();
			}
		}

		#region Private Methods

		/// <summary>
		/// Gets the encoding of the specified multipart section.
		/// </summary>
		/// <param name="section">The multipart section of <see cref="MultipartSection"/> type.</param>
		/// <returns>The encoding presented by th einstance of <see cref="Encoding"/>.</returns>
		[SuppressMessage("Microsoft.StyleCop.CSharp.ReadabilityRules", "SA1126:PrefixCallsCorrectly", Justification = "C# 7.0 syntax not supported")]
		private static Encoding GetEncoding(MultipartSection section)
		{
			if (!MediaTypeHeaderValue.TryParse(section.ContentType, out MediaTypeHeaderValue mediaType) || Encoding.UTF7.Equals(mediaType.Encoding))
			{
				return Encoding.UTF8;
			}

			return mediaType.Encoding;
		}

		/// <summary>
		/// Sets the specified value to the object property by property name.
		/// </summary>
		/// <param name="model">The object model.</param>
		/// <param name="propertyName">Property name.</param>
		/// <param name="value">The value.</param>
		/// <param name="convert">Sets the value indicating whether the conversion to the object property type should be done.</param>
		private static void SetProperty(object model, string propertyName, object value, bool convert = true)
		{
			PropertyInfo property = model.GetType().GetProperties().FirstOrDefault(field => field.Name.ToLower() == propertyName?.ToLower());
			if (model != null && property != null)
			{
				try
				{
					if (convert)
					{
						value = Convert.ChangeType(value, property.PropertyType);
					}

					property.SetValue(model, value, null);
				}
				catch
				{
				}
			}
		}

		#endregion
	}
}


text:
 (METODO 1 -> JAVA, BANCO DE DADOS, ORIENTACAO A OBJETOS) e
 (METODO 2 -> PHP, BANCO DE DADOS).

Inicio do Projeto: 10 de fevereiro de 2017.

Materia: Banco de Dados II.

Orientador: Prof. Me. Fernando Luiz de Oliveira.

INTEGRANTES:
 - ANA CLARA DA CONCEIÇÃO MACÊDO DA SILVA

 - GUSTAVO SILVA ALENCAR SIQUEIRA

 - JOÃO ANTONIO DOS SANTOS ILÁRIO

 - RODRIGO VASCONCELOS FIGUEIREDO

 Recursos:
  - JAVA (https://www.java.com/pt_BR/download/manual.jsp)
  - NETBEANS IDE (https://netbeans.org/)
  - MYSQL Connector Java (https://dev.mysql.com/downloads/connector/j/)
  - GitHub (https://github.com/)
  - PHP (http://www.php.net/)
  - HTML5 (https://www.w3.org/html/)
  - CSS3 (http://www.maujor.com/)
  - MYSQL Workbench (https://www.mysql.com/products/workbench/)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Webplayer.Modules.Spotify.Views
{
    /// <summary>
    /// Interaction logic for TransitionsView.xaml
    /// </summary>
    public partial class TransitionsView : UserControl
    {
        public string Title { get; set; } = "Spotify";

        public TransitionsView()
        {
            InitializeComponent();
        }
    }
}


text:
require 'rubygems'
require 'etc'

home = Etc.getpwuid.dir

# Configuration is loaded from ~/.escape/config
# If the file is not there we'll simply create it and make SQLite the db

begin
  cfg = YAML.load_file("#{home}/.escape/config")
rescue
  # File is not there, let's create a default!
  FileUtils.makedirs("#{home}/.escape")
  cfg = {
    "database" => "sqlite:///#{File.expand_path(File.dirname(__FILE__))}/escape.db",
    "port" => 7000
  }

  File.open("#{home}/.escape/config", 'w') do |f|
    f.write(YAML.dump(cfg))
  end
end

$connection_string = cfg["database"]
$listen_port = cfg["port"]

# Initialize controllers and models
require_relative 'app/model/init'
require_relative 'app/controller/init'


text:
package com.gudnam.bringluck.qrcode.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;

import com.gudnam.bringluck.common.BLConfig;
import com.gudnam.bringluck.domain.UserLottoVo;
import com.gudnam.bringluck.mypage.service.LottoResultService;
import com.gudnam.bringluck.sqlite.BLSQLiteQuery;
import com.gudnam.bringluck.util.BringluckUtil;

public class QRCodeService{

	private Activity activity = null;
	public UserLottoVo userLottoVo = new UserLottoVo();

	public QRCodeService(){}
	public QRCodeService(Activity activity){
		this.activity = activity;
	}

	public boolean setQRCodeContents(String contents){
		String host = contents.substring(0, contents.indexOf("/?"));
		String lottoAge = contents.substring(host.length()+4, host.length()+8);
		int nTemp = Integer.parseInt(lottoAge);
		lottoAge = String.valueOf(nTemp);
		String temp = host + "/?" + "v=" + "0000" + "m";
		String []lottoNum = new String[5];//contents.substring(temp.length(), temp.length() + 13);
		String strNowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		for( int cnt=0; cnt < 5; cnt++){
			int tempLen = temp.length();
			String buffer = contents.substring(tempLen, tempLen + 12);
			temp += buffer + "n";
			if( !BringluckUtil.isNumber(buffer)){
				return false;
			}
			if( buffer.equalsIgnoreCase(BLConfig.LOTTO_NULL)){
				continue;
			}

			lottoNum[cnt] = buffer.substring(0, 2) + "," + buffer.substring(2, 4) + "," +
							buffer.substring(4, 6) + "," + buffer.substring(6, 8) + "," +
							buffer.substring(8, 10) + "," + buffer.substring(10, 12); // GUDNAM END "," 삽입

			saveUserLottoInfo(lottoAge, lottoNum[cnt], strNowDate);
		}

		// 로또번호 저장 후 이미 당첨번호가 있다면 비교
		int result = LottoResultService.resultMyLotto(activity, lottoAge);
		if( result >= BLConfig.LOTTO_THE_FAIL){
			// 로또 결과 화면에 출력
		}

		return true;
	}

	public boolean saveUserLottoInfo(String lottoAge, String lottoNum, String nowDate){
		final Dialog dialog = BringluckUtil.setLoadingDialog(activity, "저장중...");
		dialog.show();

		BLSQLiteQuery.addUserLotto(new UserLottoVo(
										BLConfig.BL_ANDROID_ID, lottoAge, nowDate, lottoNum));
		// 유저 로또와 당첨번호 비교하여 저장 (당첨번호 없으면 무시)
		LottoResultService.resultMyLotto(activity, lottoAge);
		dialog.dismiss();

		return true;
	}

}


text:
"use strict";

import * as spec from "./../../index";
import * as v1 from "./index";

export class V1Thread {
    public comments: v1.V1Comment[];
    public page = 1;
    public last_page = 1;
    public story_id = 0;
    public story_name = "WebChatty";

    constructor(comments: v1.V1Comment[]) {
        this.comments = comments;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<data xmlns="ns:workflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="ns:workflow resource:WorkflowData">
	<documentTypes xmlns="ns:workflow/DocumentType" xsi:schemaLocation="ns:workflow/DocumentType resource:DocumentType">
		<documentType>
			<name>OrganizationTypeMaintenanceDocument</name>
			<description>Create/Edit an Organization Type</description>
			<label>Organization</label>
			<parent>KcSharedMaintenanceDocument</parent>
			<helpDefinitionURL>default.htm?turl=Documents/organizationtype.htm</helpDefinitionURL>
		</documentType>
	</documentTypes>
</data>


text:
package topoos;

public class Messages {

	public static final String TOPOOS_NORESULT="Response null or empty";
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gov.hhs.fha.nhinc.direct.addressparsing;

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

/**
 *
 * @author svalluripalli
 */
public class ToAddressParserFactoryTest {

    /**
     * Test of getToParser method, of class ToAddressParserFactory.
     */
    @Test
    public void testGetToParser() {
        ToAddressParserFactory instance = new ToAddressParserFactory();
        ToAddressParser result = instance.getToParser();
        assertTrue(result instanceof ToAddressParser);
    }
}


text:
{% load static %}
{% load extras %}
{% load i18n %}

{% for lc in learning_circles %}

      {% if lc.image %}{% else %}{% endif %}

{{lc.name}}

{% blocktrans with first_name=lc.facilitator.first_name last_name=lc.facilitator.last_name %}Facilitator: {{first_name}} {{last_name}}{% endblocktrans %}

 {{lc.venue_name}}

        {{lc.venue_address}}, {{lc.city}}

{% blocktrans with day=lc.day meeting_time=lc.meeting_time|time:"f A" end_time=lc.end_time|time:"f A" timezone=lc.timezone %}{{day}}s, {{meeting_time}} - {{end_time}}, {{timezone}}{% endblocktrans %}

{% blocktrans with start_date=lc.start_date|date:"j N Y" count weeks=lc.meeting_set.active.count %}One week beginning {{start_date}}{% plural %}{{weeks}} weeks beginning {{start_date}}{% endblocktrans %}

{% endfor %}


text:
package echo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;

/**
 * Created by Administrator on 2014/12/30.
 */
public class EchoClientHandler3 extends ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("Client received: " + buf.toString(CharsetUtil.UTF_8));
    }

}


text:
"""
dispatching execution to threads

(c) 2009, holger krekel
"""
import threading
import time
import sys

# py2/py3 compatibility
try:
    import queue
except ImportError:
    import Queue as queue
if sys.version_info >= (3,0):
    exec ("def reraise(cls, val, tb): raise val")
else:
    exec ("def reraise(cls, val, tb): raise cls, val, tb")

ERRORMARKER = object()

class Reply(object):
    """ reply instances provide access to the result
        of a function execution that got dispatched
        through WorkerPool.dispatch()
    """
    _excinfo = None
    def __init__(self, task):
        self.task = task
        self._queue = queue.Queue()

    def _set(self, result):
        self._queue.put(result)

    def _setexcinfo(self, excinfo):
        self._excinfo = excinfo
        self._queue.put(ERRORMARKER)

    def get(self, timeout=None):
        """ get the result object from an asynchronous function execution.
            if the function execution raised an exception,
            then calling get() will reraise that exception
            including its traceback.
        """
        if self._queue is None:
            raise EOFError("reply has already been delivered")
        try:
            result = self._queue.get(timeout=timeout)
        except queue.Empty:
            raise IOError("timeout waiting for %r" %(self.task, ))
        if result is ERRORMARKER:
            self._queue = None
            excinfo = self._excinfo
            reraise(excinfo[0], excinfo[1], excinfo[2])
        return result

class WorkerThread(threading.Thread):
    def __init__(self, pool):
        threading.Thread.__init__(self)
        self._queue = queue.Queue()
        self._pool = pool
        self.setDaemon(1)

    def _run_once(self):
        reply = self._queue.get()
        if reply is SystemExit:
            return False
        assert self not in self._pool._ready
        task = reply.task
        try:
            func, args, kwargs = task
            result = func(*args, **kwargs)
        except (SystemExit, KeyboardInterrupt):
            return False
        except:
            reply._setexcinfo(sys.exc_info())
        else:
            reply._set(result)
        # at this point, reply, task and all other local variables go away
        return True

    def run(self):
        try:
            while self._run_once():
                self._pool._ready[self] = True
        finally:
            del self._pool._alive[self]
            try:
                del self._pool._ready[self]
            except KeyError:
                pass

    def send(self, task):
        reply = Reply(task)
        self._queue.put(reply)
        return reply

    def stop(self):
        self._queue.put(SystemExit)

class WorkerPool(object):
    """ A WorkerPool allows to dispatch function executions
        to threads.  Each Worker Thread is reused for multiple
        function executions. The dispatching operation
        takes care to create and dispatch to existing
        threads.

        You need to call shutdown() to signal
        the WorkerThreads to terminate and join()
        in order to wait until all worker threads
        have terminated.
    """
    _shuttingdown = False
    def __init__(self, maxthreads=None):
        """ init WorkerPool instance which may
            create up to `maxthreads` worker threads.
        """
        self.maxthreads = maxthreads
        self._ready = {}
        self._alive = {}

    def dispatch(self, func, *args, **kwargs):
        """ return Reply object for the asynchronous dispatch
            of the given func(*args, **kwargs) in a
            separate worker thread.
        """
        if self._shuttingdown:
            raise IOError("WorkerPool is already shutting down")
        try:
            thread, _ = self._ready.popitem()
        except KeyError: # pop from empty list
            if self.maxthreads and len(self._alive) >= self.maxthreads:
                raise IOError("can't create more than %d threads." %
                              (self.maxthreads,))
            thread = self._newthread()
        return thread.send((func, args, kwargs))

    def _newthread(self):
        thread = WorkerThread(self)
        self._alive[thread] = True
        thread.start()
        return thread

    def shutdown(self):
        """ signal all worker threads to terminate.
            call join() to wait until all threads termination.
        """
        if not self._shuttingdown:
            self._shuttingdown = True
            for t in list(self._alive):
                t.stop()

    def join(self, timeout=None):
        """ wait until all worker threads have terminated. """
        current = threading.currentThread()
        deadline = delta = None
        if timeout is not None:
            deadline = time.time() + timeout
        for thread in list(self._alive):
            if deadline:
                delta = deadline - time.time()
                if delta <= 0:
                    raise IOError("timeout while joining threads")
            thread.join(timeout=delta)
            if thread.isAlive():
                raise IOError("timeout while joining threads")

if __name__ == '__channelexec__':
    maxthreads = channel.receive()
    execpool = WorkerPool(maxthreads=maxthreads)
    gw = channel.gateway
    channel.send("ok")
    gw._trace("instantiated thread work pool maxthreads=%s" %(maxthreads,))
    while 1:
        gw._trace("waiting for new exec task")
        task = gw._execqueue.get()
        if task is None:
            gw._trace("thread-dispatcher got None, exiting")
            execpool.shutdown()
            execpool.join()
            raise gw._StopExecLoop
        gw._trace("dispatching exec task to thread pool")
        execpool.dispatch(gw.executetask, task)


text:
! { dg-do compile }
!
! PR fortran/32867 - nested initialization expression not simplified
!
! Testcase contributed by H. J. Lu <hjl AT lucon DOT org>
!

MODULE Readdata_mod
IMPLICIT NONE
Private
Public Parser
  integer, parameter :: nkeywords = 2
character(80), PARAMETER, dimension(1:nkeywords) :: keywords = &
(/'PROBLEMSIZE                                  ',             &
  'NFTRANS_TD                                   '/)

CONTAINS
SUBROUTINE Parser(nx, ny, keyword)
integer, intent(inout) :: nx, ny
character(80), intent(inout) :: keyword

select case (keyword)
  case (trim(keywords(1))) ! PROBLEMSIZE
    nx = 1
  case (trim(keywords(2))) !'NFTRANS_TD'
    ny = 1
end select

END SUBROUTINE Parser
END MODULE Readdata_mod

! { dg-final { cleanup-modules "readdata_mod" } }


text:
package com.mygdx.game.android.notifactions;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;

import com.mygdx.game.android.NeblinaClasses.Neblina;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import static com.mygdx.game.android.NeblinaClasses.Neblina.JSON;

public class HapticService extends Service implements SensorEventListener {

    public static Neblina mNeblina;
    private SensorManager sensorManager;
    private long RETRY_TIME = 1000;
    private long START_TIME = 1000;

//    private String getNotificationUrl = "http://10.92.0.85:3000/api/notification";
    private static String getNotificationUrl = "http://requestb.in/19wezdi1";
//    private String postSnoozeUrl = "http://10.92.0.85:3000/api/snooze";
    private String postSnoozeUrl = "http://requestb.in/10nj3cu1";

    private static boolean alarmRinging = true;
    private static boolean alarmAcknowledged = true;

    public HapticService() {
        Log.w("HAPTIC SERVICE","HAPTIC SERVICE CONSTRUCTOR!");
    }

    @Override
    public void onCreate() {
        Log.w("HAPTIC SERVICE","HAPTIC SERVICE ONCREATE()!");
        Timer myTimer = new Timer();
        myTimer.scheduleAtFixedRate(new pollNotification(),START_TIME,RETRY_TIME);
    }

    public class pollNotification extends TimerTask {

        @Override
        public void run() {
            Log.w("HAPTIC SERVICE","HAPTIC SERVICE IS UP AND RUNNING!");
            if(alarmRinging == true){
                triggerAlarm();
            }

            getFromNotificationUrl();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        sensorManager.registerListener(this,
                sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);

        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            getAccelerometer(event);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
    }

    private void getAccelerometer(SensorEvent event) {
        float[] values = event.values;
        // Movement
        float x = values[0];
        float y = values[1];
        float z = values[2];

        float accelationSquareRoot = (x * x + y * y + z * z)
                / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);

        if (accelationSquareRoot >= 2) //
        {
            Log.w("HAPTIC DEBUG", "Calling the haptics!");
            if(alarmRinging == true){
                alarmRinging = false;
                alarmAcknowledged = true;
                postToSnoozeUrl();
            }

        }
    }

    public void triggerAlarm(){
        Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        v.vibrate(500);

        Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        r.play();
    }

    public void getFromNotificationUrl(){
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(getNotificationUrl) //TODO: Phase this out because we are getting this through the notification
                    .build();
            Response response = client.newCall(request).execute();
            Log.w("BLUETOOTH_DEBUG", "RECEIVED THE NOTIFICATION STATUS: " + response.body().toString());
            //TODO: Once API for getMotionUrl is finished -> Set motionStatus based on the result to either 0 or 1
            if(response.body().toString()=="0"){
            }else if(response.body().toString()=="1"){
                triggerAlarm();
                alarmRinging = true;
            }else if(response.body().toString()=="2"){
            }else {
            }
        } catch (IOException e){
            Log.w("BLUETOOTH_DEBUG","DANGER! WILL ROBINSON!");
        }
    }

    public void postToSnoozeUrl(){
        try {
            OkHttpClient client2 = new OkHttpClient();
            String json = "";
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(postSnoozeUrl)
                    .post(body)
                    .build();
            Response response2 = client2.newCall(request).execute();
        }catch (IOException e){}
    }

    @Override
    public void onDestroy() {
        sensorManager.unregisterListener(this);
        Log.w("HAPTIC SERVICE","HAPTIC SERVICE ENDING :( BYE FOR NOW!");
    }
}


text:
package voldemort.store.readonly;

import java.io.File;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import voldemort.VoldemortException;
import voldemort.cluster.Cluster;
import voldemort.cluster.Node;
import voldemort.utils.Time;
import voldemort.utils.Utils;
import voldemort.xml.ClusterMapper;

/**
 * A helper class to invoke the FETCH and SWAP operations on a remote store via
 * HTTP.
 *
 * @author jay
 *
 */
public class StoreSwapper {

    private static final Logger logger = Logger.getLogger(StoreSwapper.class);

    private final Cluster cluster;
    private final ExecutorService executor;
    private final HttpClient httpClient;
    private final String readOnlyMgmtPath;

    public StoreSwapper(Cluster cluster,
                        ExecutorService executor,
                        HttpClient httpClient,
                        String readOnlyMgmtPath) {
        super();
        this.cluster = cluster;
        this.executor = executor;
        this.httpClient = httpClient;
        this.readOnlyMgmtPath = readOnlyMgmtPath;
    }

    public void swapStoreData(String storeName, String basePath) {
        List<String> fetched = invokeFetch(basePath);
        invokeSwap(storeName, fetched);
    }

    private List<String> invokeFetch(final String basePath) {
        // do fetch
        Map<Integer, Future<String>> fetchDirs = new HashMap<Integer, Future<String>>();
        for(final Node node: cluster.getNodes()) {
            fetchDirs.put(node.getId(), executor.submit(new Callable<String>() {

                public String call() throws Exception {
                    String url = node.getHttpUrl() + "/" + readOnlyMgmtPath;
                    PostMethod post = new PostMethod(url);
                    post.addParameter("operation", "fetch");
                    String storeDir = basePath + "/node-" + node.getId();
                    post.addParameter("dir", storeDir);
                    logger.info("Invoking fetch for node " + node.getId() + " for " + storeDir);
                    int responseCode = httpClient.executeMethod(post);
                    String response = post.getResponseBodyAsString(30000);
                    if(responseCode != 200)
                        throw new VoldemortException("Swap request on node " + node.getId() + " ("
                                                     + url + ") failed: " + post.getStatusText());
                    logger.info("Fetch succeeded on node " + node.getId());
                    return response.trim();
                }
            }));
        }

        // wait for all operations to complete successfully
        List<String> results = new ArrayList<String>();
        for(int nodeId = 0; nodeId < cluster.getNumberOfNodes(); nodeId++) {
            Future<String> val = fetchDirs.get(nodeId);
            try {
                results.add(val.get());
            } catch(ExecutionException e) {
                throw new VoldemortException(e.getCause());
            } catch(InterruptedException e) {
                throw new VoldemortException(e);
            }
        }

        return results;
    }

    private void invokeSwap(String storeName, List<String> fetchFiles) {
        // do swap
        int successes = 0;
        Exception exception = null;
        for(int nodeId = 0; nodeId < cluster.getNumberOfNodes(); nodeId++) {
            try {
                Node node = cluster.getNodeById(nodeId);
                String url = node.getHttpUrl() + "/" + readOnlyMgmtPath;
                PostMethod post = new PostMethod(url);
                post.addParameter("operation", "swap");
                String dir = fetchFiles.get(nodeId);
                logger.info("Attempting swap for node " + nodeId + " dir = " + dir);
                post.addParameter("dir", dir);
                post.addParameter("store", storeName);
                int responseCode = httpClient.executeMethod(post);
                String response = post.getStatusText();
                if(responseCode == 200) {
                    successes++;
                    logger.info("Swap succeeded for node " + node.getId());
                } else {
                    throw new VoldemortException(response);
                }
            } catch(Exception e) {
                exception = e;
                logger.error("Exception thrown during swap operation on node " + nodeId + ": ", e);
            }
        }

        if(exception != null)
            throw new VoldemortException(exception);
    }

    public static void main(String[] args) throws Exception {
        if(args.length != 4)
            Utils.croak("USAGE: cluster.xml store_name mgmtpath store_file_path");
        String clusterXml = args[0];
        String storeName = args[1];
        String mgmtPath = args[2];
        String filePath = args[3];

        String clusterStr = FileUtils.readFileToString(new File(clusterXml));
        Cluster cluster = new ClusterMapper().readCluster(new StringReader(clusterStr));
        ExecutorService executor = Executors.newFixedThreadPool(10);
        HttpConnectionManager manager = new MultiThreadedHttpConnectionManager();

        int numConnections = cluster.getNumberOfNodes() + 3;
        manager.getParams().setMaxTotalConnections(numConnections);
        manager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION,
                                                     numConnections);
        HttpClient client = new HttpClient(manager);
        client.getParams().setParameter("http.socket.timeout", 3 * 60 * 60 * 1000);

        StoreSwapper swapper = new StoreSwapper(cluster, executor, client, mgmtPath);
        long start = System.currentTimeMillis();
        swapper.swapStoreData(storeName, filePath);
        long end = System.currentTimeMillis();
        logger.info("Swap succeeded on all nodes in " + ((end - start) / Time.MS_PER_SECOND)
                    + " seconds.");
        executor.shutdownNow();
        executor.awaitTermination(1, TimeUnit.SECONDS);
        System.exit(0);
    }
}


text:
/*
 * This file has been modified from the original.
 *
 * The original file can be found at:
 *		https://code.google.com/p/replicaisland/
 */

package com.replica.core.components;

import com.replica.core.BaseObject;
import com.replica.core.GameObject;
import com.replica.utility.Utils;
import com.replica.utility.Vector2;
import com.replica.utility.VectorPool;

/**
 * Component that adds physics to its parent game object.  This component implements force
 * calculation based on mass, impulses, friction, and collisions.
 */
public class PhysicsComponent extends GameComponent {

    private float mMass;
    private float mBounciness; // 1.0 = super bouncy, 0.0 = zero bounce
    private float mInertia;
    private float mStaticFrictionCoeffecient;
    private float mDynamicFrictionCoeffecient;

    private static final float DEFAULT_MASS = 1.0f;
    private static final float DEFAULT_BOUNCINESS = 0.1f;
    private static final float DEFAULT_INERTIA = 0.01f;
    private static final float DEFAULT_STATIC_FRICTION_COEFFECIENT = 0.05f;
    private static final float DEFAULT_DYNAMIC_FRICTION_COEFFECIENT = 0.02f;

    PhysicsComponent() {
        super();
        reset();
        setPhase(ComponentPhases.POST_PHYSICS.ordinal());
    }

    @Override
    public void reset() {
        // TODO: no reason to call accessors here locally.
        setMass(DEFAULT_MASS);
        setBounciness(DEFAULT_BOUNCINESS);
        setInertia(DEFAULT_INERTIA);
        setStaticFrictionCoeffecient(DEFAULT_STATIC_FRICTION_COEFFECIENT);
        setDynamicFrictionCoeffecient(DEFAULT_DYNAMIC_FRICTION_COEFFECIENT);
    }

    @Override
    public void update(float timeDelta, BaseObject parent) {
        GameObject parentObject = (GameObject) parent;

        // we look to user data so that other code can provide impulses
        Vector2 impulseVector = Vector2.ZERO; //parentObject.getImpulse();
        									//TODO: put impulse back in
        final Vector2 currentVelocity = parentObject.getVelocity();

        final Vector2 surfaceNormal = parentObject.getBackgroundCollisionNormal();
        if (surfaceNormal.length2() > 0.0f) {
            resolveCollision(currentVelocity, impulseVector, surfaceNormal, impulseVector);
        }

        VectorPool vectorPool = sSystemRegistry.vectorPool;

        // if our speed is below inertia, we need to overcome inertia before we can move.

        boolean physicsCausesMovement = true;

        final float inertiaSquared = getInertia() * getInertia();

        Vector2 newVelocity = vectorPool.allocate(currentVelocity);
        newVelocity.add(impulseVector);

        if (newVelocity.length2() < inertiaSquared) {
            physicsCausesMovement = false;
        }

        final boolean touchingFloor = true;//parentObject.touchingGround();

        GravityComponent gravity = parentObject.findByClass(GravityComponent.class);

        if (touchingFloor && currentVelocity.y <= 0.0f && Math.abs(newVelocity.x) > 0.0f
                        && gravity != null) {
            final Vector2 gravityVector = gravity.getGravity();

            // if we were moving last frame, we'll use dynamic friction. Else
            // static.
            float frictionCoeffecient = Math.abs(currentVelocity.x) > 0.0f ?
                        getDynamicFrictionCoeffecient() : getStaticFrictionCoeffecient();
            frictionCoeffecient *= timeDelta;

            // Friction = cofN, where cof = friction coefficient and N = force
            // perpendicular to the ground.
            final float maxFriction = Math.abs(gravityVector.y) * getMass()
                    * frictionCoeffecient;

            if (maxFriction > Math.abs(newVelocity.x)) {
                newVelocity.x = (0.0f);
            } else {
                newVelocity.x = (newVelocity.x
                        - (maxFriction * Utils.sign(newVelocity.x)));
            }
        }

        if (Math.abs(newVelocity.x) < 0.01f) {
            newVelocity.x = (0.0f);
        }

        if (Math.abs(newVelocity.y) < 0.01f) {
            newVelocity.y = (0.0f);
        }

        // physics-based movements means constant acceleration, always. set the target to the
        // velocity.
        if (physicsCausesMovement) {
            parentObject.setVelocity(newVelocity);
//            parentObject.setTargetVelocity(newVelocity);
//            parentObject.setAcceleration(Vector2.ZERO);
//            parentObject.setImpulse(Vector2.ZERO);
        }

        vectorPool.release(newVelocity);
    }

    protected void resolveCollision(Vector2 velocity, Vector2 impulse, Vector2 opposingNormal,
                    Vector2 outputImpulse) {
        VectorPool vectorPool = sSystemRegistry.vectorPool;

        outputImpulse.set(impulse);

        Vector2 collisionNormal = vectorPool.allocate(opposingNormal);

        collisionNormal.normalize();

        Vector2 relativeVelocity = vectorPool.allocate(velocity);
        relativeVelocity.add(impulse);

        final float dotRelativeAndNormal = relativeVelocity.dot(collisionNormal);

        // make sure the motion of the entity requires resolution
        if (dotRelativeAndNormal < 0.0f) {
            final float coefficientOfRestitution = getBounciness(); // 0 = perfectly inelastic,
                                                                    // 1 = perfectly elastic

            // calculate an impulse to apply to the entity
            float j = (-(1 + coefficientOfRestitution) * dotRelativeAndNormal);

            j /= ((collisionNormal.dot(collisionNormal)) * (1 / getMass()));

            Vector2 entity1Adjust = vectorPool.allocate(collisionNormal);

            entity1Adjust.set(collisionNormal);
            entity1Adjust.multiply(j);
            entity1Adjust.divide(getMass());
            entity1Adjust.add(impulse);
            outputImpulse.set(entity1Adjust);
            vectorPool.release(entity1Adjust);

        }

        vectorPool.release(collisionNormal);
        vectorPool.release(relativeVelocity);
    }

    protected void resolveCollision(Vector2 velocity, Vector2 impulse, Vector2 opposingNormal,
                    float otherMass, Vector2 otherVelocity, Vector2 otherImpulse,
                    float otherBounciness, Vector2 outputImpulse) {
        VectorPool vectorPool = sSystemRegistry.vectorPool;

        Vector2 collisionNormal = vectorPool.allocate(opposingNormal);
        collisionNormal.normalize();

        Vector2 entity1Velocity = vectorPool.allocate(velocity);
        entity1Velocity.add(impulse);

        Vector2 entity2Velocity = vectorPool.allocate(otherVelocity);
        entity2Velocity.add(otherImpulse);

        Vector2 relativeVelocity = vectorPool.allocate(entity1Velocity);
        relativeVelocity.subtract(entity2Velocity);

        final float dotRelativeAndNormal = relativeVelocity.dot(collisionNormal);

        // make sure the entities' motion requires resolution
        if (dotRelativeAndNormal < 0.0f) {
            final float bounciness = Math.min(getBounciness() + otherBounciness, 1.0f);
            final float coefficientOfRestitution = bounciness;  // 0 = perfectly inelastic,
                                                                // 1 = perfectly elastic

            // calculate an impulse to apply to both entities
            float j = (-(1 + coefficientOfRestitution) * dotRelativeAndNormal);

            j /= ((collisionNormal.dot(collisionNormal)) * (1 / getMass() + 1 / otherMass));

            Vector2 entity1Adjust = vectorPool.allocate(collisionNormal);
            entity1Adjust.multiply(j);
            entity1Adjust.divide(getMass());
            entity1Adjust.add(impulse);

            outputImpulse.set(entity1Adjust);

            // TODO: Deal impulses both ways.
            /*
             * Vector3 entity2Adjust = (collisionNormal j);
             * entity2Adjust[0] /= otherMass;
             * entity2Adjust[1] /= otherMass;
             * entity2Adjust[2] /= otherMass;
             *
             * const Vector3 newEntity2Impulse = otherImpulse + entity2Adjust;
             */

            vectorPool.release(entity1Adjust);
        }

        vectorPool.release(collisionNormal);
        vectorPool.release(entity1Velocity);
        vectorPool.release(entity2Velocity);
        vectorPool.release(relativeVelocity);
    }

    public float getMass() {
        return mMass;
    }

    public void setMass(float mass) {
        mMass = mass;
    }

    public float getBounciness() {
        return mBounciness;
    }

    public void setBounciness(float bounciness) {
        mBounciness = bounciness;
    }

    public float getInertia() {
        return mInertia;
    }

    public void setInertia(float inertia) {
        mInertia = inertia;
    }

    public float getStaticFrictionCoeffecient() {
        return mStaticFrictionCoeffecient;
    }

    public void setStaticFrictionCoeffecient(float staticFrictionCoeffecient) {
        mStaticFrictionCoeffecient = staticFrictionCoeffecient;
    }

    public float getDynamicFrictionCoeffecient() {
        return mDynamicFrictionCoeffecient;
    }

    public void setDynamicFrictionCoeffecient(float dynamicFrictionCoeffecient) {
        mDynamicFrictionCoeffecient = dynamicFrictionCoeffecient;
    }

}