text:
package io.ray.runtime.functionmanager;

import com.google.common.collect.Lists;
import io.ray.api.function.RayFunc;
import io.ray.runtime.util.LambdaUtils;
import java.io.File;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Manages functions in the current worker. */
public class FunctionManager {

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

  static final String CONSTRUCTOR_NAME = "<init>";

  /**
   * Cache from a RayFunc object to its corresponding JavaFunctionDescriptor. Because
   * `LambdaUtils.getSerializedLambda` is expensive.
   */
  // If the cache is not thread local, we'll need a lock to protect it,
  // which means competition is highly possible.
  private static final ThreadLocal<WeakHashMap<Class<? extends RayFunc>, JavaFunctionDescriptor>>
      RAY_FUNC_CACHE = ThreadLocal.withInitial(WeakHashMap::new);

  /** The table that manages functions. */
  private final JobFunctionTable jobFunctionTable;

  /** The resource path which we can load the job's jar resources. */
  private final List<String> codeSearchPath;

  /**
   * Construct a FunctionManager with the specified code search path.
   *
   * @param codeSearchPath The specified job resource that can store the job's resources.
   */
  public FunctionManager(List<String> codeSearchPath) {
    this.codeSearchPath = codeSearchPath;
    jobFunctionTable = createJobFunctionTable();
  }

  public ClassLoader getClassLoader() {
    return jobFunctionTable.classLoader;
  }

  /**
   * Get the RayFunction from a RayFunc instance (a lambda).
   *
   * @param func The lambda.
   * @return A RayFunction object.
   */
  public RayFunction getFunction(RayFunc func) {
    JavaFunctionDescriptor functionDescriptor = RAY_FUNC_CACHE.get().get(func.getClass());
    if (functionDescriptor == null) {
      // It's OK to not lock here, because it's OK to have multiple JavaFunctionDescriptor instances
      // for the same RayFunc instance.
      SerializedLambda serializedLambda = LambdaUtils.getSerializedLambda(func);
      final String className = serializedLambda.getImplClass().replace('/', '.');
      final String methodName = serializedLambda.getImplMethodName();
      final String signature = serializedLambda.getImplMethodSignature();
      functionDescriptor = new JavaFunctionDescriptor(className, methodName, signature);
      RAY_FUNC_CACHE.get().put(func.getClass(), functionDescriptor);
    }
    return getFunction(functionDescriptor);
  }

  /**
   * Get the RayFunction from a function descriptor.
   *
   * @param functionDescriptor The function descriptor.
   * @return A RayFunction object.
   */
  public RayFunction getFunction(JavaFunctionDescriptor functionDescriptor) {
    return jobFunctionTable.getFunction(functionDescriptor);
  }

  /** A helper that creates function table. */
  private JobFunctionTable createJobFunctionTable() {
    ClassLoader classLoader;
    if (codeSearchPath == null || codeSearchPath.isEmpty()) {
      classLoader = getClass().getClassLoader();
    } else {
      URL[] urls =
          codeSearchPath.stream()
              .filter(p -> StringUtils.isNotBlank(p) && Files.exists(Paths.get(p)))
              .flatMap(
                  p -> {
                    try {
                      if (!Files.isDirectory(Paths.get(p))) {
                        if (!p.endsWith(".jar")) {
                          return Stream.of(
                              Paths.get(p).getParent().toAbsolutePath().toUri().toURL());
                        } else {
                          return Stream.of(Paths.get(p).toAbsolutePath().toUri().toURL());
                        }
                      } else {
                        List<URL> subUrls = new ArrayList<>();
                        subUrls.add(Paths.get(p).toAbsolutePath().toUri().toURL());
                        Collection<File> jars =
                            FileUtils.listFiles(
                                new File(p),
                                new RegexFileFilter(".*\\.jar"),
                                DirectoryFileFilter.DIRECTORY);
                        for (File jar : jars) {
                          subUrls.add(jar.toPath().toUri().toURL());
                        }
                        return subUrls.stream();
                      }
                    } catch (MalformedURLException e) {
                      throw new RuntimeException(String.format("Illegal %s resource path", p));
                    }
                  })
              .toArray(URL[]::new);
      classLoader = new URLClassLoader(urls);
      LOGGER.debug("Resource loaded from path {}.", urls);
    }

    return new JobFunctionTable(classLoader);
  }

  /** Manages all functions that belong to one job. */
  static class JobFunctionTable {

    /** The job's corresponding class loader. */
    final ClassLoader classLoader;
    /** Functions per class, per function name + type descriptor. */
    ConcurrentMap<String, Map<Pair<String, String>, Pair<RayFunction, Boolean>>> functions;

    JobFunctionTable(ClassLoader classLoader) {
      this.classLoader = classLoader;
      this.functions = new ConcurrentHashMap<>();
    }

    RayFunction getFunction(JavaFunctionDescriptor descriptor) {
      Map<Pair<String, String>, Pair<RayFunction, Boolean>> classFunctions =
          functions.get(descriptor.className);
      if (classFunctions == null) {
        synchronized (this) {
          classFunctions = functions.get(descriptor.className);
          if (classFunctions == null) {
            classFunctions = loadFunctionsForClass(descriptor.className);
            functions.put(descriptor.className, classFunctions);
          }
        }
      }
      final Pair<String, String> key = ImmutablePair.of(descriptor.name, descriptor.signature);
      RayFunction func = classFunctions.get(key).getLeft();
      if (func == null) {
        if (classFunctions.containsKey(key)) {
          throw new RuntimeException(
              String.format(
                  "RayFunction %s is overloaded, the signature can't be empty.",
                  descriptor.toString()));
        } else {
          throw new RuntimeException(
              String.format("RayFunction %s not found", descriptor.toString()));
        }
      }
      return func;
    }

    /** Load all functions from a class. */
    Map<Pair<String, String>, Pair<RayFunction, Boolean>> loadFunctionsForClass(String className) {
      // If RayFunction is null, the function is overloaded.
      // The value of this map is a pair of <rayFunction, isDefault>.
      // The `isDefault` is used to mark if the method is a marked as default keyword.
      Map<Pair<String, String>, Pair<RayFunction, Boolean>> map = new HashMap<>();
      try {
        Class clazz = Class.forName(className, true, classLoader);
        List<Executable> executables = new ArrayList<>();
        executables.addAll(Arrays.asList(clazz.getDeclaredMethods()));
        executables.addAll(Arrays.asList(clazz.getDeclaredConstructors()));

        Class clz = clazz;
        clz = clz.getSuperclass();
        while (clz != null && clz != Object.class) {
          executables.addAll(Arrays.asList(clz.getDeclaredMethods()));
          clz = clz.getSuperclass();
        }

        // Put interface methods ahead, so that in can be override by subclass methods in `map.put`
        for (Class baseInterface : clazz.getInterfaces()) {
          for (Method method : baseInterface.getDeclaredMethods()) {
            if (method.isDefault()) {
              executables.add(method);
            }
          }
        }

        // Use reverse order so that child class methods can override super class methods.
        for (Executable e : Lists.reverse(executables)) {
          e.setAccessible(true);
          final String methodName = e instanceof Method ? e.getName() : CONSTRUCTOR_NAME;
          final Type type =
              e instanceof Method ? Type.getType((Method) e) : Type.getType((Constructor) e);
          final String signature = type.getDescriptor();
          RayFunction rayFunction =
              new RayFunction(
                  e, classLoader, new JavaFunctionDescriptor(className, methodName, signature));
          final boolean isDefault = e instanceof Method && ((Method) e).isDefault();
          map.put(
              ImmutablePair.of(methodName, signature), ImmutablePair.of(rayFunction, isDefault));
          // For cross language call java function with signature "{length_of_arguments}" or just
          // empty "".
          // TODO: more robust signature type matching
          // https://github.com/ray-project/ray/issues/21380.
          String[] crossLangSignatures = {"", String.format("%s", type.getArgumentTypes().length)};
          for (String crossLangSignature : crossLangSignatures) {
            final Pair<String, String> crossLangDescriptor =
                ImmutablePair.of(methodName, crossLangSignature);
            /// default method is not overloaded, so we should filter it.
            if (map.containsKey(crossLangDescriptor) && !map.get(crossLangDescriptor).getRight()) {
              map.put(
                  crossLangDescriptor,
                  ImmutablePair.of(null, false)); // Mark this function as overloaded.
            } else {
              map.put(crossLangDescriptor, ImmutablePair.of(rayFunction, isDefault));
            }
          }
        }
      } catch (Exception e) {
        throw new RuntimeException("Failed to load functions from class " + className, e);
      }
      return map;
    }
  }
}


text: The assessment price is {{assessment |  currency:'NZD':true:'1.0-2'}}.

redpajama_set_name: RedPajamaGithub


text:
require 'pact_broker/domain/group'

=begin
  Splits all relationships up into groups of non-connecting relationships.
=end

module PactBroker

  module Relationships

    class Groupify

      def self.call relationships
        recurse_groups([], relationships.dup).collect { |group| Domain::Group.new(group) }
      end

      def self.recurse_groups groups, relationship_pool
        if relationship_pool.empty?
          groups
        else
          first, *rest = relationship_pool
          group = [first]
          new_connections = true
          while new_connections
            new_connections = false
            group = rest.inject(group) do |connected, candidate|
              if connected.select { |relationship| relationship.connected?(candidate) }.any?
                new_connections = true
                connected + [candidate]
              else
                connected
              end
            end

            rest = rest - group
            group.uniq
          end

          recurse_groups(groups + [group], relationship_pool - group)
        end
      end
    end

  end
end


text:
@protocol IDEProvisioningBasicTeam;

@protocol IDEProvisioningTeamSelectionDataSource
@property(retain, nonatomic) id <IDEProvisioningBasicTeam> team;
@property(readonly, nonatomic) BOOL isTeamSelectionRequired;
@end


text:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Vue2Spa.Migrations
{
    public partial class FirstMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Blogs",
                columns: table => new
                {
                    BlogId = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    Url = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Blogs", x => x.BlogId);
                });

            migrationBuilder.CreateTable(
                name: "Posts",
                columns: table => new
                {
                    PostId = table.Column<int>(nullable: false)
                        .Annotation("Sqlite:Autoincrement", true),
                    BlogId = table.Column<int>(nullable: false),
                    Content = table.Column<string>(nullable: true),
                    Title = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Posts", x => x.PostId);
                    table.ForeignKey(
                        name: "FK_Posts_Blogs_BlogId",
                        column: x => x.BlogId,
                        principalTable: "Blogs",
                        principalColumn: "BlogId",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Posts_BlogId",
                table: "Posts",
                column: "BlogId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Posts");

            migrationBuilder.DropTable(
                name: "Blogs");
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Search — opcsim 0.5.0rc5 documentation</title>
    <link rel="stylesheet" href="_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="_static/style.css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="#" />

<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          opcsim
        0.5.0rc5

API

Tutorial

Gallery

  Site

Installation

Contributing

API reference

Tutorial

Example gallery

  Page

Search

    Please activate JavaScript to enable the search
    functionality.

    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.

  <form class="form-inline" action="" method="get">

      <input type="text" class="form-control" name="q" value="" />

    <input type="submit" class="btn btn-default" value="search" />

  </form>

      Back to top

        © Copyright 2016-2020, David H Hagan and Jesse H Kroll.

      Created using Sphinx 2.2.1.


text:
import TextArea from '@ember/component/text-area';
import { inject as service } from '@ember/service'
import { run } from '@ember/runloop'
import { computed, get } from '@ember/object';

import { isGecko } from 'ui/utils/platform';
import IntlPlaceholder from 'shared/mixins/intl-placeholder';

export default TextArea.extend(IntlPlaceholder, {
  intl: service(),

  minHeight: 0,
  curHeight: null,
  maxHeight: 200,

  tagName:           'textarea',
  classNames:        ['no-resize', 'no-ease'],
  attributeBindings: ['spellcheck'],
  classNameBindings: ['bg'],

  didInsertElement() {
    run.scheduleOnce('afterRender', this, 'initHeights');
  },

  bg: computed('disabled', function() {
    if ( get(this, 'disabled') ) {
      return 'bg-disabled'
    }
  }),

  changed: function() {
    run.debounce(this, 'autoSize', 100);
  }.observes('value'),

  isSmall: function() {
    if ( this.isDestroyed || this.isDestroying ) {
      return;
    }

    return this.$().hasClass('input-sm');
  }.property(),

  initHeights() {
    if ( this.get('minHeight') === 0 ) {
      this.set('minHeight', ( this.get('isSmall') ? 31 : 36));
    }

    this.autoSize();

    this.$().on('paste', () => {
      run.later(this, 'autoSize', 100);
    });
  },

  autoSize() {
    if ( this.isDestroyed || this.isDestroying ) {
      return;
    }

    let el = this.element;
    let $el = $(el); // eslint-disable-line

    run(() => {
      $el.css('height', '1px');

      let border = parseInt($el.css('borderTopWidth'), 10) || 0 + parseInt($el.css('borderBottomWidth'), 10) || 0;
      let magic = (this.get('isSmall') ? -2 : 0) + ( isGecko ? 1 : 2); // Sigh, but it's wrong without magic fudge
      let neu = Math.max(this.get('minHeight'), Math.min(el.scrollHeight + border + magic, this.get('maxHeight')));

      $el.css('overflowY', (el.scrollHeight > neu ? 'auto' : 'hidden'));
      $el.css('height', `${ neu  }px`);
      this.set('curHeight', neu);
    });
  }
});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Colin's Blog</title>
    <link rel="icon" href="/travelblog/img/Flag_of_Tanzania.svg.png">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/blog-home.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Home

                    Weeks 8 - 11
                    3/05/2017 - 3/30/2017

                    Work on my projects is going well, and in a few weeks we hope to launch two new websites. The olfactometer (which measures odor dilution ) we are using for the smelly sock project is slowly becoming more functional, which means soon we can start collecting data and having people ship us their socks. As odd as it is to be excited about someone shipping their smelly socks to us, it is a good sign that the original project I was brought over to work on is progressing forward again. The project leader, Salum, is in the process of "training" mosquitos to fly back and forth through the race course (olfactometer's tubes) and testing response levels of different smells. After a month and a half break from this project, I am happy to be getting back on track.

 Here is a picture of Salum and I testing which of our fingers the mosquitos prefer more. Having put his finger in the test chamber after recently washing his hands, my finger which was not recently washed attracted  about 15 more mosquitos.

It's proposal writing season here in Ifakara, and many scientists are writing their ideas to different grant donors. I have read probably close to 20 proposals in the last few weeks with ideas ranging from emergency birthing kits to medicine delivery systems using fixed-winged drones. Yes, drones…and it sounds like the scientist who proposed this idea has already carried out several tests and the institute is starting to invest in his idea. Deadlines for these proposals are coming up soon, so this week has been dedicated to a writing boot camp.

  Here is a picture of boot camp. These sessions usually last from 8am to 12am.

  They take proposal writing very seriously here, and reviewing these proposals has been my main job over the last few weeks.

  Even though the scientists are busy writing their proposals, the mosquitos still have to eat. Here is a picture of my buddy Joseph feeding the latest batch of Anopheles Gambiae mosquitos.

I fed one batch of mosquitos in the same way, and it is not as easy as he makes it look. I originally said that one time would be enough for me, but I may have to feed them again to get photographic proof.

Outside of work I have had a very fun time. Three weeks ago I was able to visit the Udzungwa waterfalls in the Udzungwa Mountains National Park. The trip consisted of a two hour hike up a slippery mountainside, but it was definitely worth it. The best part of the hike was being able to swim in the base of the waterfall and seeing the views from the top.

  Other adventures in the past weeks include:

    -More cows and bike tours

   -Piki piki (motorcycle) rides with friends in the rainy season. There are more puddles than roads right now

   -Living with a new roommate for three weeks while the owners traveled

This past weekend I had the chance to visit Iringa, a town 200km northwest of Ifakara. The town is located on a plateau centered between 4 mountains. Its elevation is quite a bit higher than Ifakara's and it was surprisingly cool. Thursday night in Iringa we camped, and for the first time in 2.5 months, I was cold in Tanzania. The next two nights we stayed in a hostel operated by Tanzanians with disabilities. We checked in and ordered food by writing down what we wanted  and handing it to deaf and mute Tanzanians, which I thought was very cool. Not only that, but they connected us to a guide who showed us the city and the famous sights in Iringa.

 My new friend David and I at the Gangilonga Rock in Iringa

I have officially reached my half way mark here in Tanzania and am excited what the next few months will bring. Thanks for reading, I will try to update more frequently.

                        ← Older

                        Newer →

Blog Categories

                                    Weeks 15-17

                                    Weeks 12-14

                                    Weeks 8-11

                                    Weeks 5-7

                                    Weeks 3-4

                                    Week 2

                                    Week 1

                                    Why I'm Here

Blog posted by Colin Quinn


text:
class Admin::TranslationsController < ApplicationController
  before_action :authenticate_user!
  before_action :authorize_setup, except: [:clear_cache]
  before_action :add_breadcrumbs

  def index; end

  def clear_cache
    authorize :translation, :clear_cache?
    clear_cache_i18n
    flash[:notice] = "Translation Cache cleared"
    redirect_to translations_path
  end

  private

  def authorize_setup
    authorize :translation, :index?
  end

  def add_breadcrumbs
    add_breadcrumb "Translations", translations_path
  end
end


text:
import csvtojson from 'csvtojson'
var convertDataToJson = require('../convert-datatojson')
var sut_convertDataToJson = convertDataToJson.default

describe('utils', () => {
	describe('csv converter', () => {
		describe('convert data to json', () => {
			it('should throw exception if the value is null', () => {
				var value = null, headers='headers'
				expect(sut_convertDataToJson.bind(convertDataToJson, value, headers)).to.throw('value cannot be null')
			})

			it('should throw exception if the headers is null and first line does not contain headers', () => {
				var value = 'value', headers=null, firstLineContainsHeader=false
				expect(sut_convertDataToJson.bind(convertDataToJson, value, headers, firstLineContainsHeader)).to.throw('headers are required if first line does not contain headers')
			})

			it('should resolve the converter json value for a csv row with headers and first line contains no header', (done) => {
				var value='csv string', headers='firstname,lastname,address', json={ firstname: 'aaa', lastname: 'bbb', address: 'ccc' }
				var converterStub = root.sandbox.stub(csvtojson, 'Converter').returns({ fromString: (path, callback) => callback(null, json) })

				var promise = sut_convertDataToJson(value, headers)

				promise.then((result) => {
					expect(converterStub).to.have.been.calledWith({noheader: true, headers})
					expect(result).to.equal(json)
					done()
				}).catch(done)
			})

			it('should resolve the converter json value for a csv row with headers and first line contains a header', (done) => {
				var value='csv string', headers='firstname,lastname,address', json={ firstname: 'aaa', lastname: 'bbb', address: 'ccc' }
				var converterStub = root.sandbox.stub(csvtojson, 'Converter').returns({ fromString: (path, callback) => callback(null, json) })

				var promise = sut_convertDataToJson(value, headers, true)

				promise.then((result) => {
					expect(converterStub).to.have.been.calledWith({noheader: false, headers})
					expect(result).to.equal(json)
					done()
				}).catch(done)
			})

			it('should reject if the conversion fails for the given value', (done) => {
				var value='csv string', headers='firstname,lastname,address', somethingWentWrong = 'error'
				var converterStub = root.sandbox.stub(csvtojson, 'Converter').returns({ fromString: (path, callback) => callback(somethingWentWrong, null) })

				var promise = sut_convertDataToJson(value, headers)

				promise.catch((error) => {
					expect(converterStub).to.have.been.calledWith({noheader: true, headers})
					expect(error).to.equal(somethingWentWrong)
					done()
				}).catch(done)
			})
		})
	})
})


text:
package redis

import (
	"bufio"
	"net"
	"sync"

	"github.com/bluegol/errutil"
)

type MuxClient struct {
	host     string
	port     int
	passwd   string
	numConn  int

	jobCh    chan *Job
	quitChs  []chan struct{}
	statusCh chan error

	// wg decrease when receiver returns
	wg       *sync.WaitGroup
	// q is used to quit once
	q        *sync.Once
}

func NewMuxClient(host string, port int, passwd string, numConn int,
	reporter func(error) ) (*MuxClient, error) {
	c := &MuxClient{
		host: host,
		port: port,
		passwd: passwd,
		numConn: numConn,

		jobCh: make(chan *Job, jobChSize),
		quitChs: make([]chan struct{}, numConn),
		statusCh: make(chan error, jobChSize),

		wg: new(sync.WaitGroup),
		q: new(sync.Once),
	}

	go statusHandler(c.statusCh, reporter)
	for i := 0; i < c.numConn; i++ {
		startupCh := make(chan error)
		quitCh := make(chan struct{})
		go c.sender(i, startupCh, quitCh)
		err := <- startupCh
		if err != nil {
			c.Quit()
			return nil, err
		}
		c.quitChs[i] = quitCh
	}

	return c, nil
}

func (c *MuxClient) Command(cmd Cmd, args ...interface{}) (*Reply, error, *Job) {
	return command(c.jobCh, cmd, args...)
}

func (c *MuxClient) Commands(args ...interface{}) ([]*Reply, error, *Job) {
 	return commands(c.jobCh, args...)
}

func (c *MuxClient) Quit() error {
	result := InfoAlreadyQuit
	c.q.Do(func() {
		c.statusCh <- InfoQuitStarted
		for _, q := range c.quitChs {
			if q != nil {
				q <- struct{}{}
				close(q)
			}
		}
		c.wg.Wait()
		c.statusCh <- InfoQuitDone
		close(c.statusCh)
		go func() {
			for job := range c.jobCh {
				job.Err = ErrAlreadyClosed
				job.sendResult()
			}
		}()
		result = nil
	})
	return result
}

/////////////////////////////////////////////////////////////////////

func (c *MuxClient) sender(senderNo int,
	startupCh chan error, quitCh chan struct{}) {

	conn, err := newConn(c.host, c.port, c.passwd, c.statusCh)
	if err != nil {
		startupCh <- err
		close(startupCh)
		return
	}
	waitCh := newReceiver(conn, c.wg, c.statusCh)
	close(startupCh)
	c.statusCh <- InfoConnected

	for {
		select {

		case <-quitCh:
			// send quit anyway, and don't care about response.
			conn.Write(cmdQuitBytes)
			close(waitCh)
			return

		case job := <-c.jobCh:
			ProcessJob:
			err = send(conn, job.b)
			if err == nil {
				waitCh <- job
				continue
			}

			// error occurred
			c.statusCh <- errutil.AddInfo(err, "job", job.DebugString())
			// stop the receiver
			close(waitCh)
			if errutil.CompareType(ErrBeforeSending, err) {
				// nothing was sent, so it could be timeout due to
				// long period of no communication
				var err2 error
				conn, err2 = newConn(
					c.host, c.port, c.passwd, c.statusCh)
				if err == nil {
					// let's resume
					waitCh = newReceiver(conn, c.wg, c.statusCh)
					goto ProcessJob
				} else {
					// cannot reconnect. critical. start shutdown.
					c.statusCh <- err2
					job.Err = errutil.Embed(ErrCannotConnect, err2)
					job.sendResult()
				}
			} else {
				job.Err = err
				job.sendResult()
			}

			go c.Quit()
			<-quitCh
			return
		}
	}
}

func newReceiver(conn net.Conn, wg *sync.WaitGroup, statusCh chan<- error) chan *Job {
	waitCh := make(chan *Job, waitChSize)
	go receiver(conn, waitCh, wg, statusCh)
	return waitCh
}

func receiver(conn net.Conn, waitCh <-chan *Job, wg *sync.WaitGroup, statusCh chan<- error) {

	wg.Add(1)
	defer wg.Done()

	reader := bufio.NewReader( conn )

	for job := range waitCh {
		err := readReplyAndReturn(reader, job)
		if err != nil {
			// critical, but sender will handle it.
			// just report it, and continue
			statusCh <- err
		}
	}
	// channel closed, meaning we are exiting.
	// just close and don't care about the error
	conn.Close()
}

const jobChSize = 10000
const waitChSize = 10000


text:
package io.github.mzmine.modules.dataanalysis.bubbleplots.logratioplot;

import io.github.mzmine.datamodel.RawDataFile;
import io.github.mzmine.datamodel.features.FeatureList;
import io.github.mzmine.parameters.Parameter;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.parameters.parametertypes.ComboParameter;
import io.github.mzmine.parameters.parametertypes.MultiChoiceParameter;
import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsParameter;
import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsSelection;
import io.github.mzmine.util.ExitCode;
import io.github.mzmine.util.FeatureMeasurementType;

public class LogratioParameters extends SimpleParameterSet {

  public static final FeatureListsParameter featureLists = new FeatureListsParameter(1, 1);

  public static final MultiChoiceParameter<RawDataFile> groupOneFiles =
      new MultiChoiceParameter<RawDataFile>("Group one", "Samples in group one", new RawDataFile[0],
          null, 1);

  public static final MultiChoiceParameter<RawDataFile> groupTwoFiles =
      new MultiChoiceParameter<RawDataFile>("Group two", "Samples in group two", new RawDataFile[0],
          null, 1);

  public static final ComboParameter<FeatureMeasurementType> measurementType =
      new ComboParameter<FeatureMeasurementType>("Peak measurement type",
          "Determines whether peak's area or height is used in computations.",
          FeatureMeasurementType.values());

  public LogratioParameters() {
    super(new Parameter[] {featureLists, groupOneFiles, groupTwoFiles, measurementType});
  }

  @Override
  public ExitCode showSetupDialog(boolean valueCheckRequired) {

    FeatureListsSelection featureListSel = getParameter(featureLists).getValue();
    FeatureList selectedFeatureLists[] = featureListSel.getMatchingFeatureLists();
    RawDataFile plDataFiles[] = selectedFeatureLists[0].getRawDataFiles().toArray(RawDataFile[]::new);

    getParameter(groupOneFiles).setChoices(plDataFiles);
    getParameter(groupTwoFiles).setChoices(plDataFiles);

    return super.showSetupDialog(valueCheckRequired);
  }

}


text:
namespace AmgularJsTest.Data
{
    using System;
    using System.Collections.Generic;

    public partial class UnitsOfMeasure
    {
        public UnitsOfMeasure()
        {
            this.Items = new HashSet<Item>();
        }

        public int id { get; set; }
        public string Symbol { get; set; }
        public string Des { get; set; }

        public virtual ICollection<Item> Items { get; set; }
    }
}


text:
package android.location;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class Location
  implements android.os.Parcelable
{
  // Fields

  public static final int FORMAT_DEGREES = 0;

  public static final int FORMAT_MINUTES = 1;

  public static final int FORMAT_SECONDS = 2;

  public static final android.os.Parcelable.Creator<Location> CREATOR = null;

  // Constructors

  public Location(java.lang.String arg1){
  }
  public Location(Location arg1){
  }
  // Methods

  public java.lang.String toString(){
    return (java.lang.String) null;
  }
  public void set(Location arg1){
  }
  public void reset(){
  }
  public long getTime(){
    return 0l;
  }
  public void setTime(long arg1){
  }
  public java.lang.String getProvider(){
    return (java.lang.String) null;
  }
  public void dump(android.util.Printer arg1, java.lang.String arg2){
  }
  public void writeToParcel(android.os.Parcel arg1, int arg2){
  }
  public int describeContents(){
    return 0;
  }
  public android.os.Bundle getExtras(){
    return (android.os.Bundle) null;
  }
  public void setExtras(android.os.Bundle arg1){
  }
  public static java.lang.String convert(double arg1, int arg2){
    return (java.lang.String) null;
  }
  public static double convert(java.lang.String arg1){
    return 0.0d;
  }
  public float getAccuracy(){
    return 0.0f;
  }
  public void setProvider(java.lang.String arg1){
  }
  public double getAltitude(){
    return 0.0d;
  }
  public float distanceTo(Location arg1){
    return 0.0f;
  }
  public double getLatitude(){
    return 0.0d;
  }
  public double getLongitude(){
    return 0.0d;
  }
  public void setLatitude(double arg1){
  }
  public void setLongitude(double arg1){
  }
  public void setAccuracy(float arg1){
  }
  public boolean hasAccuracy(){
    return false;
  }
  public void setAltitude(double arg1){
  }
  public void removeAltitude(){
  }
  public void setSpeed(float arg1){
  }
  public void removeSpeed(){
  }
  public void setBearing(float arg1){
  }
  public void removeBearing(){
  }
  public void removeAccuracy(){
  }
  public static void distanceBetween(double arg1, double arg2, double arg3, double arg4, float [] arg5){
  }
  public float bearingTo(Location arg1){
    return 0.0f;
  }
  public boolean hasAltitude(){
    return false;
  }
  public boolean hasSpeed(){
    return false;
  }
  public float getSpeed(){
    return 0.0f;
  }
  public boolean hasBearing(){
    return false;
  }
  public float getBearing(){
    return 0.0f;
  }
}


text:
package javasmmr.zoowsome.models.animals;

import static javasmmr.zoowsome.repositories.AnimalRepository.createNode;

import javax.xml.stream.*;

import org.w3c.dom.Element;

import javasmmr.zoowsome.models.interfaces.XML_Parsable;

public abstract class Animal implements Killer, XML_Parsable {

	private int nrOfLegs;
	private String name;
	private final double maintenanceCost;
	private final double dangerPerc;
	private boolean takenCareOf;

	public Animal(double maintenanceCost, double dangerPerc) {
		this.maintenanceCost = maintenanceCost;
		this.dangerPerc = dangerPerc;
		setTakenCareOf(false);
	}

	public double getMaintenanceCost() {
		return maintenanceCost;
	}

	public double getDangerPerc() {
		return dangerPerc;
	}

	public int getNrOfLegs() {
		return nrOfLegs;
	}

	public void setNrOfLegs(int nrOfLegs) {
		this.nrOfLegs = nrOfLegs;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public boolean kill() {
		return (Math.random() < dangerPerc + getPredisposition());
	}

	public void setTakenCareOf(boolean takenCareOf) {
		this.takenCareOf = takenCareOf;
	}

	public boolean getTakenCareOf() {
		return takenCareOf;
	}

	public double getPredisposition() {
		return 0;
	}

	public void encodeToXml(XMLEventWriter eventWriter) throws XMLStreamException {
		createNode(eventWriter, "nrOfLegs", String.valueOf(this.nrOfLegs));
		createNode(eventWriter, "name", String.valueOf(this.name));
		createNode(eventWriter, "maintenanceCost", String.valueOf(this.maintenanceCost));
		createNode(eventWriter, "dangerPerc", String.valueOf(this.dangerPerc));
		createNode(eventWriter, "takenCareOf", String.valueOf(this.takenCareOf));
	}

	public void decodeFromXml(Element element) {
		setNrOfLegs(Integer.valueOf(element.getElementsByTagName("nrOfLegs").item(0).getTextContent()));
		setName(element.getElementsByTagName("name").item(0).getTextContent());
		setTakenCareOf(Boolean.valueOf(element.getElementsByTagName("takenCareOf").item(0).getTextContent()));
	}
}


text:
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'Ravelry',
    version:'0.1',
    prepareImgLinks:function (callback) {
        var res = [];
        var repl = options.showHighRes ? '' : '_medium2';

        hoverZoom.urlReplace(res,
            '.thumbnail, .zoomable_photo, .photo',
            ['_small_best_fit', '_small', '_best_fit', /_[mst]\./],
            [repl, repl, repl, '.']
        );

        hoverZoom.urlReplace(res,
            'a img',
            '_square',
            repl
        );

        callback($(res));

        // This second processing makes use of the Flickr API to try to get larger pictures.
        if (options.showHighRes) {
            $('a img[src*="static.flickr.com"]').each(function () {
                var _this = $(this),
                    link = _this.parents('a:eq(0)'),
                    src = _this.attr('src');
                hoverZoomPluginFlickerA.prepareImgLinkFromSrc(link, src, callback);
            });
        }
    }
});


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_14.c
Label Definition File: CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct.label.xml
Template File: sources-sink-14.tmpl.c
*/
/*
 * @description
 * CWE: 588 Attempt to Access Child of Non Structure Pointer
 * BadSource:  Void pointer to an int
 * GoodSource: Void pointer to a twoints struct
 * Sink:
 *    BadSink : Print data
 * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
 *
 * */

#include "std_testcase.h"

#ifndef OMITBAD

void CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_14_bad()
{
    void * data;
    twoIntsStruct dataGoodBuffer;
    int dataBadBuffer = 100;
    dataGoodBuffer.intOne = 0;
    dataGoodBuffer.intTwo = 0;
    if(globalFive==5)
    {
        /* FLAW: Set data to point to an int */
        data = &dataBadBuffer;
    }
    /* POTENTIAL FLAW: Attempt to print a struct when data may be a non-struct data type */
    printStructLine((twoIntsStruct *)data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
    void * data;
    twoIntsStruct dataGoodBuffer;
    int dataBadBuffer = 100;
    dataGoodBuffer.intOne = 0;
    dataGoodBuffer.intTwo = 0;
    if(globalFive!=5)
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        /* FIX: Set data to point to a twoIntsStruct struct */
        data = &dataGoodBuffer;
    }
    /* POTENTIAL FLAW: Attempt to print a struct when data may be a non-struct data type */
    printStructLine((twoIntsStruct *)data);
}

/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
    void * data;
    twoIntsStruct dataGoodBuffer;
    int dataBadBuffer = 100;
    dataGoodBuffer.intOne = 0;
    dataGoodBuffer.intTwo = 0;
    if(globalFive==5)
    {
        /* FIX: Set data to point to a twoIntsStruct struct */
        data = &dataGoodBuffer;
    }
    /* POTENTIAL FLAW: Attempt to print a struct when data may be a non-struct data type */
    printStructLine((twoIntsStruct *)data);
}

void CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_14_good()
{
    goodG2B1();
    goodG2B2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
 * its own for testing or for building a binary to use in testing binary
 * analysis tools. It is not used when compiling all the testcases as one
 * application, which is how source code analysis tools are tested.
 */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_14_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE588_Attempt_to_Access_Child_of_Non_Structure_Pointer__struct_14_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?php
//<<<<<<< 71872a2e747cf024ae6cc231eed8b83ca3bc85b1
/**
 * AppBundle File Doc Comment
 *
 * PHP Version 5.5
 *
 * @category AppBundle
 * @package  AppBundle
 * @author   Display Name <username@example.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     https://github.com/EBMCentraleLille/fablab
 */
//======= >>>>>>> Fix

namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

//<<<<<<< 71872a2e747cf024ae6cc231eed8b83ca3bc85b1
/**
 * MyClass Class Doc Comment
 *
 * @category AppBundle
 * @package  AppBundle
 * @author   Display Name <username@example.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     https://github.com/EBMCentraleLille/fablab
 */
//======= >>>>>>> Fix
class AppBundle extends Bundle
{
}


text:
		        <?php
        $this->load->view('layout/header');
        $this->load->view('layout/container');
		?>
        <!-- BEGIN PAGE BASE CONTENT -->
                   <div class="row">
Drill down list of users under clients
                    </div>
                            <?php
        $this->load->view('layout/footer');
        ?>


text:
import "foo";
import "foo-bar";
import "./directory/foo-bar";
import foo from "foo";
import * as foo from "foo";
import {bar} from "foo";
import {foo as bar} from "foo";

export {test};
export var test = 5;


text:
<?php
namespace Underscore\Types;

use Underscore\Underscore;
use Underscore\UnderscoreTestCase;

class StringTest extends UnderscoreTestCase
{
    public $remove = 'foo foo bar foo kal ter son';

    public function provideAccord()
    {
        return [
            [10, '10 things'],
            [1, 'one thing'],
            [0, 'nothing'],
        ];
    }

    public function provideFind()
    {
        return [

            // Simple cases
            [false, 'foo', 'bar'],
            [true, 'foo', 'foo'],
            [true, 'FOO', 'foo', false],
            [false, 'FOO', 'foo', true],
            // Many needles, one haystack
            [true, ['foo', 'bar'], $this->remove],
            [false, ['vlu', 'bla'], $this->remove],
            [true, ['foo', 'vlu'], $this->remove, false, false],
            [false, ['foo', 'vlu'], $this->remove, false, true],
            // Many haystacks, one needle
            [true, 'foo', ['foo', 'bar']],
            [true, 'bar', ['foo', 'bar']],
            [false, 'foo', ['bar', 'kal']],
            [true, 'foo', ['foo', 'foo'], false, false],
            [false, 'foo', ['foo', 'bar'], false, true],
        ];
    }

    // Tests --------------------------------------------------------- /

    public function testCanCreateString()
    {
        $string = Strings::create();

        $this->assertEquals('', $string->obtain());
    }

    public function testDoesntPluralizeTwice()
    {
        $string = new Strings('person');

        $this->assertEquals('people', $string->plural());
        $this->assertEquals('people', $string->plural());
    }

    public function testHasAccessToStrMethods()
    {
        $string1 = Strings::limit('foo', 1);
        $string2 = Underscore::from('foo')->limit(1)->obtain();

        $this->assertEquals('f...', $string1);
        $this->assertEquals('f...', $string2);
    }

    public function testCanRemoveTextFromString()
    {
        $return = Strings::remove($this->remove, 'bar');

        $this->assertEquals('foo foo  foo kal ter son', $return);
    }

    public function testCanRemoveMultipleTextsFromString()
    {
        $return = Strings::remove($this->remove, ['foo', 'son']);

        $this->assertEquals('bar  kal ter', $return);
    }

    public function testCanToggleBetweenTwoStrings()
    {
        $toggle = Strings::toggle('foo', 'foo', 'bar');
        $this->assertEquals('bar', $toggle);
    }

    public function testCannotLooselyToggleBetweenStrings()
    {
        $toggle = Strings::toggle('dei', 'foo', 'bar');
        $this->assertEquals('dei', $toggle);
    }

    public function testCanLooselyToggleBetweenStrings()
    {
        $toggle = Strings::toggle('dei', 'foo', 'bar', true);
        $this->assertEquals('foo', $toggle);
    }

    public function testCanRepeatString()
    {
        $string = Strings::from('foo')->repeat(3)->obtain();

        $this->assertEquals('foofoofoo', $string);
    }

    /**
     * @dataProvider provideFind
     */
    public function testCanFindStringsInStrings(
        $expect,
        $needle,
        $haystack,
        $caseSensitive = false,
        $absoluteFinding = false
    ) {
        $result = Strings::find($haystack, $needle, $caseSensitive, $absoluteFinding);

        $this->assertEquals($expect, $result);
    }

    public function testCanAssertAStringStartsWith()
    {
        $this->assertTrue(Strings::startsWith('foobar', 'foo'));
        $this->assertFalse(Strings::startsWith('barfoo', 'foo'));
    }

    public function testCanAssertAStringEndsWith()
    {
        $this->assertTrue(Strings::endsWith('foobar', 'bar'));
        $this->assertFalse(Strings::endsWith('barfoo', 'bar'));
    }

    public function testStringsCanBeSlugged()
    {
        $this->assertEquals('my-new-post', Strings::slugify('My_nEw\\\/  @ post!!!'));
        $this->assertEquals('my_new_post', Strings::slugify('My nEw post!!!', '_'));
    }

    public function testRandomStringsCanBeGenerated()
    {
        $this->assertEquals(40, strlen(Strings::random(40)));
    }

    /**
     * @dataProvider provideAccord
     */
    public function testCanAccordAStringToItsNumeral($number, $expect)
    {
        $result = Strings::accord($number, '%d things', 'one thing', 'nothing');

        $this->assertEquals($expect, $result);
    }

    public function testCanSliceFromAString()
    {
        $string = Strings::sliceFrom('abcdef', 'c');

        return $this->assertEquals('cdef', $string);
    }

    public function testCanSliceToAString()
    {
        $string = Strings::sliceTo('abcdef', 'c');

        return $this->assertEquals('ab', $string);
    }

    public function testCanSliceAString()
    {
        $string = Strings::slice('abcdef', 'c');

        return $this->assertEquals(['ab', 'cdef'], $string);
    }

    public function testCanUseCorrectOrderForStrReplace()
    {
        $string = Strings::replace('foo', 'foo', 'bar');

        $this->assertEquals('bar', $string);
    }

    public function testCanExplodeString()
    {
        $string = Strings::explode('foo bar foo', ' ');
        $this->assertEquals(['foo', 'bar', 'foo'], $string);

        $string = Strings::explode('foo bar foo', ' ', -1);
        $this->assertEquals(['foo', 'bar'], $string);
    }

    public function testCanGenerateRandomWords()
    {
        $string = Strings::randomStrings($words = 5, $size = 5);

        $result = ($words * $size) + ($words * 1) - 1;
        $this->assertEquals($result, strlen($string));
    }

    public function testCanConvertToSnakeCase()
    {
        $string = Strings::toSnakeCase('thisIsAString');

        $this->assertEquals('this_is_a_string', $string);
    }

    public function testCanConvertToCamelCase()
    {
        $string = Strings::toCamelCase('this_is_a_string');

        $this->assertEquals('thisIsAString', $string);
    }

    public function testCanConvertToPascalCase()
    {
        $string = Strings::toPascalCase('this_is_a_string');

        $this->assertEquals('ThisIsAString', $string);
    }

    public function testCanConvertToLowercase()
    {
        $this->assertEquals('taylor', Strings::lower('TAYLOR'));
        $this->assertEquals('άχιστη', Strings::lower('ΆΧΙΣΤΗ'));
    }

    public function testCanConvertToUppercase()
    {
        $this->assertEquals('TAYLOR', Strings::upper('taylor'));
        $this->assertEquals('ΆΧΙΣΤΗ', Strings::upper('άχιστη'));
    }

    public function testCanConvertToTitleCase()
    {
        $this->assertEquals('Taylor', Strings::title('taylor'));
        $this->assertEquals('Άχιστη', Strings::title('άχιστη'));
    }

    public function testCanLimitStringsByCharacters()
    {
        $this->assertEquals('Tay...', Strings::limit('Taylor', 3));
        $this->assertEquals('Taylor', Strings::limit('Taylor', 6));
        $this->assertEquals('Tay___', Strings::limit('Taylor', 3, '___'));
    }

    public function testCanLimitByWords()
    {
        $this->assertEquals('Taylor...', Strings::words('Taylor Otwell', 1));
        $this->assertEquals('Taylor___', Strings::words('Taylor Otwell', 1, '___'));
        $this->assertEquals('Taylor Otwell', Strings::words('Taylor Otwell', 3));
    }

    public function testCanCheckIfIsIp()
    {
        $this->assertTrue(Strings::isIp('192.168.1.1'));
        $this->assertFalse(Strings::isIp('foobar'));
    }

    public function testCanCheckIfIsEmail()
    {
        $this->assertTrue(Strings::isEmail('foo@bar.com'));
        $this->assertFalse(Strings::isEmail('foobar'));
    }

    public function testCanCheckIfIsUrl()
    {
        $this->assertTrue(Strings::isUrl('http://www.foo.com/'));
        $this->assertFalse(Strings::isUrl('foobar'));
    }

    public function testCanPrependString()
    {
        $this->assertEquals('foobar', Strings::prepend('bar', 'foo'));
    }

    public function testCanAppendString()
    {
        $this->assertEquals('foobar', Strings::append('foo', 'bar'));
    }

    public function testCanGetBaseClass()
    {
        $this->assertEquals('Baz', Strings::baseClass('Foo\Bar\Baz'));
    }
}


text:
angular.module('myApp.directives')
    .directive('paymentsTimetable', function(){
  	return {
  		link: function(scope, element, attrs)
	  	{

  		},
  		restrict: "EA",
  		templateUrl: "js/directives/paymentsTimetable/payments.html",
  		scope: {
            months: "@"
        },
        controller: ['$scope', '$element', '$attrs', 'creditData', 'creditCalculator', 'CreditCountPayments', 'localStorageService' , function($scope, $element, $attrs, creditData, creditCalculator, CreditCountPayments, localStorageService)
        {
            var calculator = creditCalculator.getInstance(),
                credit,
                prevCredit = new CreditCountPayments({months: 0, annualPercent: 0, creditAmount: 0}),
                percentsYear = creditData.percents || localStorageService.get('percentsYear'),
                creditSum = creditData.creditSum || localStorageService.get('creditSum'),
                paymentToCredit = 0,
                updateCretidPayments = function(creditPayment){
                    var payment = creditPayment || {};

                    if(payment instanceof CreditCountPayments)
                    {
                        payment.recalculate(payment.annualPercent, payment.creditAmount, payment.extraPayment);

                        for(var i = 1; i < $scope.payments.length; i++)
                        {
                            $scope.payments[i].recalculate($scope.payments[i-1].annualPercent, $scope.payments[i-1].leftToPay);
                        }
                    }
                };

            $scope.payments = [];
            $scope.months = +$scope.months;
            $scope.creditSum = creditSum;
            $scope.percentsYear = percentsYear;

            $scope.updatePayments = function(creditPayment){
                updateCretidPayments(creditPayment);
            };

            for(var i = $scope.months; i > 0; i--)
            {
                creditSum = creditSum - paymentToCredit;
                credit = new CreditCountPayments({months: i, annualPercent: percentsYear, creditAmount: creditSum});
                calculator.addCredit(credit);
                prevCredit = credit;
                paymentToCredit = credit.monthlyPay - percentsYear * creditSum / 100 / 12;
            }

            $scope.payments = calculator.getCredits();
            // let's try different ways of watching after input
        }]
    };
  });


text:
package net.tcs.db;

import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.IdName;
import org.javalite.activejdbc.annotations.Table;
import org.javalite.activejdbc.annotations.VersionColumn;

@Table("JobDefinition")
@IdName("name")
@VersionColumn("lock_version")
public class JobDefinitionDAO extends Model {
    static {
        validatePresenceOf("name", "body");
    }
    public String getName() {
        return getString("name");
    }

    public void setName(String name) {
        set("name", name);
    }

    public String getBody() {
        return getString("body");
    }

    public void setBody(String body) {
        set("body", body);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.Gui;
using FlatRedBall.Instructions;
using FlatRedBall.Content.Instructions;
using FlatRedBall.Graphics.Particle;
using System.Reflection;
using Color = System.Drawing.Color;
#if FRB_XNA
using Microsoft.Xna.Framework;
#else
using Vector3 = Microsoft.DirectX.Vector3;
#endif

namespace EditorObjects.Gui
{
    public class InstructionBlueprintPropertyGrid<TargetType> : PropertyGrid<InstructionBlueprint>
    {
        #region Fields
        private string mCurrentMember;
        private ComboBox mMemberBox;
        private UpDown mTimeUpdown;
        private bool mInitialized;

        private static Dictionary<Type, List<String>> mMemberFilter = new Dictionary<Type,List<string>>();
        #endregion

        #region Properties

        public UpDown TimeUpDown
        {
            get { return mTimeUpdown; }
            set { mTimeUpdown = value; }
        }

        public static Dictionary<Type, List<String>> MemberFilter
        {
            get { return mMemberFilter; }
        }

        #endregion

        #region Methods

        #region Events

        public void UpdateUpDownValue(Window callingWindow)
        {
            SelectedObject.MemberValue = (callingWindow as UpDown).CurrentValue;
        }

        public void UpdateComboBoxValue(Window callingWindow)
        {
            if (SelectedObject.MemberType.IsEnum)
            {
                SelectedObject.MemberValue = Enum.Parse(SelectedObject.MemberType, (callingWindow as ComboBox).Text, true);
            }

            else
            {
                SelectedObject.MemberValue = Boolean.Parse((callingWindow as ComboBox).Text);
            }
        }

        public void UpdateTextBoxValue(Window callingWindow)
        {
            if (SelectedObject.MemberType == typeof(long))
            {
                SelectedObject.MemberValue = long.Parse((callingWindow as TextBox).Text);
            }
            else
            {
                SelectedObject.MemberValue = (callingWindow as TextBox).Text;
            }
        }

        public void UpdateColorDisplayValue(Window callingWindow)
        {
            SelectedObject.MemberValue = (callingWindow as ColorDisplay).ColorValue;
        }

        public void UpdateVector3Display(Window callingWindow)
        {
            SelectedObject.MemberValue = (callingWindow as Vector3Display).Vector3Value;
        }

        #endregion

        #region Constructors
        public InstructionBlueprintPropertyGrid(Cursor cursor) :
            base(cursor)
        {
            ExcludeAllMembers();

            #region Member
            IncludeMember("MemberName");
            this.Name = "InstructionBlueprint";

            mMemberBox = new ComboBox(cursor);
            ReplaceMemberUIElement("MemberName", mMemberBox);
            mMemberBox.ScaleX = 12.0f;
            mMemberBox.SortingStyle = ListBoxBase.Sorting.AlphabeticalIncreasing;

            #region Populate with member names
            List<String> memberOptions = new List<String>();
            Type memberType;

            foreach(PropertyInfo propInfo in typeof(TargetType).GetProperties()){
                memberType = propInfo.PropertyType;
                if (memberType.IsEnum ||
                    memberType == typeof(string) ||
                    memberType == typeof(bool) ||
                    memberType == typeof(byte) ||
                    memberType == typeof(float) ||
                    memberType == typeof(double) ||
                    memberType == typeof(int) ||
                    memberType == typeof(long) ||
                    memberType == typeof(Color) ||
                    memberType == typeof(Vector3))
                {
                    memberOptions.Add(propInfo.Name);
                }

            }

            if (MemberFilter.ContainsKey(typeof(TargetType)))
            {
                List<String> filter = MemberFilter[typeof(TargetType)];

                if (filter != null)
                {
                    foreach (string s in filter)
                    {
                        memberOptions.Remove(s);
                    }
                }
            }

            SetOptionsForMember("MemberName", memberOptions);

            #endregion

            #endregion

            mCurrentMember = "<No Object>";
            mInitialized = false;
            AfterUpdateDisplayedProperties += new GuiMessage(AfterUpdate);

            IncludeMember("MemberValue");
            IncludeMember("Time");

            GetUIElementForMember("MemberValue").Visible = false;
            GetUIElementForMember("Time").Visible = false;
            UpdateDisplayedProperties();
        }
        #endregion

        #region Public Methods
        public void AfterUpdate(Window callingWindow)
        {
            if (mCurrentMember != null &&
                !String.IsNullOrEmpty(SelectedObject.MemberName) &&
                !mCurrentMember.Equals(SelectedObject.MemberName))
            {
                //Add properties to grid if this is the first change
                if (!mInitialized)
                {
                    GetUIElementForMember("MemberValue").Visible = true;
                    GetUIElementForMember("Time").Visible = true;

                    GetUIElementForMember("Time").ScaleX = 8;
                    mInitialized = true;

                    UpdateDisplayedProperties();
                }

                SelectedObject.MemberType = GetMemberType(typeof(TargetType), SelectedObject.MemberName);
                mCurrentMember = SelectedObject.MemberName;

                Window replacement = CreateEditWindowForType(SelectedObject.MemberType);
                if (replacement != null)
                    ReplaceMemberUIElement("MemberValue", CreateEditWindowForType(SelectedObject.MemberType));
                else
                    ReplaceMemberUIElement("MemberValue", new Button(GuiManager.Cursor));

                if(SelectedObject.MemberValue != null && SelectedObject.MemberType != SelectedObject.MemberValue.GetType())
                    SelectedObject.MemberValue = null;
            }

          //  (GetUIElementForMember("Time") as UpDown).CurrentValue = (float)SelectedObject.MemberValue;
        }

        public void ExcludeMemberOption(String memberName)
        {

        }

        public void ExcludeMemberOptions(List<String> memberNames)
        {
            foreach (String s in memberNames)
            {
                ExcludeMemberOption(s);
            }
        }

        #endregion

        #region PrivateMethods
        private Window CreateEditWindowForType(Type memberType)
        {
            Window toReturn = null;

            #region ComboBox
            if (memberType.IsEnum ||
                memberType == typeof(bool)){

                ComboBox comboBox = new ComboBox(GuiManager.Cursor);
                comboBox.ScaleX = 8;
                toReturn = comboBox;
                comboBox.ItemClick += UpdateComboBoxValue;

                if(memberType == typeof(bool)){
                    comboBox.AddItem("true", true);
                    comboBox.AddItem("false", false);

                }
                else
                {
                    string[] options = Enum.GetNames(memberType);
                    Array values = Enum.GetValues(memberType);
                    int i = 0;

                    foreach (object value in values)
                    {
                        comboBox.AddItem(options[i], value);

                        ++i;
                    }
                }
                }

            #endregion

            #region UpDown
            else if (
                memberType == typeof(byte) ||
                memberType == typeof(float) ||
                memberType == typeof(double) ||
                memberType == typeof(int))
            {
                UpDown upDown= new UpDown(GuiManager.Cursor);
                upDown.ValueChanged += new GuiMessage(UpdateUpDownValue);
                toReturn = upDown;
                upDown.ScaleX = 8;
            }
            #endregion

            #region Vector3
            else if (
                memberType == typeof(Vector3))
            {
                Vector3Display vecDisplay = new Vector3Display(GuiManager.Cursor);
                vecDisplay.LosingFocus += UpdateVector3Display;
                vecDisplay.ValueChanged += UpdateVector3Display;
                toReturn = vecDisplay;
            }
            #endregion

            #region ColorDisplay
            else if(
                memberType == typeof(System.Drawing.Color)){
                ColorDisplay cDisplay = new ColorDisplay(GuiManager.Cursor);

                cDisplay.ValueChanged += UpdateColorDisplayValue;
                cDisplay.LosingFocus += UpdateColorDisplayValue;

                toReturn = cDisplay;
                }
            #endregion

            #region Textbox
            else if(
                memberType == typeof(string) ||
                memberType == typeof(long)){
                TextBox textBox = new TextBox(GuiManager.Cursor);
                textBox.ScaleX = 8;

                if(memberType == typeof(long)){
                    textBox.Format = TextBox.FormatTypes.Integer;
                }

                textBox.LosingFocus += UpdateTextBoxValue;

                toReturn = textBox;
                }
            #endregion

            return toReturn;

        }

        private Type GetMemberType(Type objectType, string memberName)
        {
            PropertyInfo propertyInfo = objectType.GetProperty(memberName);

            //If this member is a property
            if (propertyInfo != null)
            {
                return propertyInfo.PropertyType;
            }

            else
            {
                return objectType.GetField(memberName).FieldType;
            }
        }

        #endregion

        #endregion

    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :4.0.30319.42000
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AddSpellManager.Properties {
    using System;

    /// <summary>
    ///   Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées.
    /// </summary>
    // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder
    // à l'aide d'un outil, tel que ResGen ou Visual Studio.
    // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen
    // avec l'option /str ou régénérez votre projet VS.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Retourne l'instance ResourceManager mise en cache utilisée par cette classe.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AddSpellManager.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Remplace la propriété CurrentUICulture du thread actuel pour toutes
        ///   les recherches de ressources à l'aide de cette classe de ressource fortement typée.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _1479882212_cut {
            get {
                object obj = ResourceManager.GetObject("1479882212_cut", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _1479882226_copy {
            get {
                object obj = ResourceManager.GetObject("1479882226_copy", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap _88050b84c1ae321bcd9b8db6252abb61 {
            get {
                object obj = ResourceManager.GetObject("88050b84c1ae321bcd9b8db6252abb61", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap a_worn_parchment_paper_background_texture {
            get {
                object obj = ResourceManager.GetObject("a-worn-parchment-paper-background-texture", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap Ac_Medal03 {
            get {
                object obj = ResourceManager.GetObject("Ac_Medal03", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap add {
            get {
                object obj = ResourceManager.GetObject("add", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap back1 {
            get {
                object obj = ResourceManager.GetObject("back1", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap back2 {
            get {
                object obj = ResourceManager.GetObject("back2", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap bible {
            get {
                object obj = ResourceManager.GetObject("bible", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap C_Elm03 {
            get {
                object obj = ResourceManager.GetObject("C_Elm03", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap C_Hat01 {
            get {
                object obj = ResourceManager.GetObject("C_Hat01", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap C_Hat02 {
            get {
                object obj = ResourceManager.GetObject("C_Hat02", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap crystal {
            get {
                object obj = ResourceManager.GetObject("crystal", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap delete {
            get {
                object obj = ResourceManager.GetObject("delete", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap edit {
            get {
                object obj = ResourceManager.GetObject("edit", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap krusader {
            get {
                object obj = ResourceManager.GetObject("krusader", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Icon semblable à (Icône).
        /// </summary>
        internal static System.Drawing.Icon mage111 {
            get {
                object obj = ResourceManager.GetObject("mage111", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap magehat {
            get {
                object obj = ResourceManager.GetObject("magehat", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Icon semblable à (Icône).
        /// </summary>
        internal static System.Drawing.Icon magehat11 {
            get {
                object obj = ResourceManager.GetObject("magehat11", resourceCulture);
                return ((System.Drawing.Icon)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap S_Holy03 {
            get {
                object obj = ResourceManager.GetObject("S_Holy03", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap S_Ice03 {
            get {
                object obj = ResourceManager.GetObject("S_Ice03", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap S_Thunder02 {
            get {
                object obj = ResourceManager.GetObject("S_Thunder02", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap S_Water07 {
            get {
                object obj = ResourceManager.GetObject("S_Water07", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap search {
            get {
                object obj = ResourceManager.GetObject("search", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap Shield {
            get {
                object obj = ResourceManager.GetObject("Shield", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap shield_add {
            get {
                object obj = ResourceManager.GetObject("shield_add", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap shield_delete {
            get {
                object obj = ResourceManager.GetObject("shield_delete", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap user {
            get {
                object obj = ResourceManager.GetObject("user", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap user_add {
            get {
                object obj = ResourceManager.GetObject("user_add", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap W_Mace005 {
            get {
                object obj = ResourceManager.GetObject("W_Mace005", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }

        /// <summary>
        ///   Recherche une ressource localisée de type System.Drawing.Bitmap.
        /// </summary>
        internal static System.Drawing.Bitmap Wizard {
            get {
                object obj = ResourceManager.GetObject("Wizard", resourceCulture);
                return ((System.Drawing.Bitmap)(obj));
            }
        }
    }
}


text:
import React from 'react';

import messages from './messages';
import A from 'components/A';
import styles from './styles.css';
import { FormattedMessage } from 'react-intl';
import LocaleToggle from 'containers/LocaleToggle';

function Footer() {
  return (

        <LocaleToggle />

          <FormattedMessage
            {...messages.authorMessage}
            values={{
              author: ZStack,
            }}
          />

  );
}

export default Footer;


text:
<?php

namespace Symfony\Component\DomCrawler;

/**
 * Link represents an HTML link (an HTML a tag).
 *
 * @author Fabien Potencier <fabien@symfony.com>
 *
 * @api
 */
class Link
{
    protected $node;
    protected $method;
    protected $currentUri;

    /**
     * Constructor.
     *
     * @param \DOMNode $node       A \DOMNode instance
     * @param string   $currentUri The URI of the page where the link is embedded (or the base href)
     * @param string   $method     The method to use for the link (get by default)
     *
     * @throws \LogicException if the node is not a link
     *
     * @api
     */
    public function __construct(\DOMNode $node, $currentUri, $method = 'GET')
    {
        if (!in_array(substr($currentUri, 0, 4), array('http', 'file'))) {
            throw new \InvalidArgumentException(sprintf('Current URI must be an absolute URL ("%s").', $currentUri));
        }

        $this->setNode($node);
        $this->method = $method ? strtoupper($method) : null;
        $this->currentUri = $currentUri;
    }

    protected function setNode(\DOMNode $node)
    {
        if ('a' != $node->nodeName) {
            throw new \LogicException(sprintf('Unable to click on a "%s" tag.', $node->nodeName));
        }

        $this->node = $node;
    }

    /**
     * Gets the node associated with this link.
     *
     * @return \DOMNode A \DOMNode instance
     */
    public function getNode()
    {
        return $this->node;
    }

    /**
     * Gets the URI associated with this link.
     *
     * @return string The URI
     *
     * @api
     */
    public function getUri()
    {
        $uri = $this->getRawUri();

        // absolute URL?
        if ('http' === substr($uri, 0, 4)) {
            return $uri;
        }

        // empty URI
        if (!$uri) {
            return $this->currentUri;
        }

        // only an anchor or a query string
        if (in_array($uri[0], array('?', '#'))) {
            return $this->currentUri.$uri;
        }

        // absolute path
        if ('/' === $uri[0]) {
            return preg_replace('#^(.*?//[^/]+)(?:\/.*)?$#', '$1', $this->currentUri).$uri;
        }

        // relative path
        return substr($this->currentUri, 0, strrpos($this->currentUri, '/') + 1).$uri;
    }

    protected function getRawUri()
    {
        return $this->node->getAttribute('href');
    }

    /**
     * Gets the method associated with this link.
     *
     * @return string The method
     *
     * @api
     */
    public function getMethod()
    {
        return $this->method;
    }
}


text:
package com.hinaka.study.intentdemo;

import android.content.Intent;
import android.net.Uri;
import android.renderscript.Double2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    Button btnCallOtherActivity;
    Button btnAdd;
    Button btnStartBrowser;
    Button btnStartBrowserLaunch;
    Button btnStartPhone;
    Button btnExceptionCondition;
    Button btnSendSms;
    EditText etNum1;
    EditText etNum2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initialViews();
    }

    private void initialViews() {
        btnCallOtherActivity = (Button) findViewById(R.id.button_main_call_other_activity);
        btnCallOtherActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCallOtherActivityButtonClick(v);
            }
        });
        btnAdd = (Button) findViewById(R.id.button_main_add);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAddButtonClick(v);
            }
        });
        etNum1 = (EditText) findViewById(R.id.edittext_main_num_1);
        etNum2 = (EditText) findViewById(R.id.edittext_main_num_2);
        btnStartBrowser = (Button) findViewById(R.id.button_main_start_browser);
        btnStartBrowser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStartBrowserButtonClick();
            }
        });
        btnStartBrowserLaunch = (Button) findViewById(R.id.button_main_start_browser_launch);
        btnStartBrowserLaunch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStartBrowserLaunchButtonClick(v);
            }
        });
        btnStartPhone = (Button) findViewById(R.id.button_main_start_phone);
        btnStartPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onStartPhoneButtonClick(v);
            }
        });
        btnExceptionCondition = (Button) findViewById(R.id.button_main_exception_condition);
        btnExceptionCondition.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onExceptionConditionButtonClick(v);
            }
        });
        btnSendSms = (Button) findViewById(R.id.button_main_send_sms);
        btnSendSms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onSendSmsButtonClick(v);
            }
        });
    }

    private void onSendSmsButtonClick(View v) {
        Intent intent = new Intent(this, SendSmsActivity.class);
        startActivity(intent);
    }

    private void onExceptionConditionButtonClick(View v) {
        Uri uri = Uri.parse("https://google.com.vn");
        Intent intent = new Intent("sample.intent.intentdemo.LAUNCH", uri);
        startActivity(intent);
    }

    private void onStartPhoneButtonClick(View v) {
        Uri uri = Uri.parse("tel:0838417996");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
    }

    private void onStartBrowserLaunchButtonClick(View v) {
        Uri uri = Uri.parse("http://www.google.com.vn?username=trungtnm");
        Intent intent = new Intent("sample.intent.intentdemo.LAUNCH", uri);
        this.startActivity(intent);
    }

    private void onStartBrowserButtonClick() {
        Uri uri = Uri.parse("http://www.google.com.vn");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        this.startActivity(intent);
    }

    private void onAddButtonClick(View v) {
        Intent intent = new Intent(this, ResultActivity.class);
        Bundle bundle = new Bundle();

        double num1 = Double.parseDouble(etNum1.getText().toString());
        double num2 = Double.parseDouble(etNum2.getText().toString());

        bundle.putDouble(ResultActivity.EXTRA_NUM_1, num1);
        bundle.putDouble(ResultActivity.EXTRA_NUM_2, num2);
        intent.putExtra(ResultActivity.BUNDLE_INFO, bundle);
        this.startActivity(intent);
    }

    private void onCallOtherActivityButtonClick(View v) {
        Intent intent = new Intent(this, ChildActivity.class);
        this.startActivity(intent);
    }
}


text:
package com.example.senaisp.personalbooks.preferences;

/**
 * Created by tancredofernando on 03/12/16.
 */

public class Preferences {

}


text:
namespace BlueSheep.Common.Data.DataCenter.Effects.Instances
{
    class EffectInstanceInteger : EffectInstance
    {
        #region Constructeurs
        public EffectInstanceInteger()
        {
        }

        public EffectInstanceInteger(GameDataFileAccessor gameDataFileAccessor)
        {
        }
        #endregion

        public int value;
    }
}


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

import java.lang.management.ManagementFactory;
import java.util.logging.Handler;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.jmx.JMXConfigurator;
import ch.qos.logback.classic.jul.LevelChangePropagator;

/**
 * Assimilates all the other logging frameworks that we use and redirect them to logback.
 *
 * Currently that is only java.util.logging, when using slf4j, it is sent directly to logback.
 */
public final class AssimilateForeignLogging
{
    // @GuardedBy("AssimilateForeignLogging.class")
    private static boolean assimilated = false;

    private AssimilateForeignLogging()
    {
    }

    /**
     * Assimilate a small set of logging frameworks.
     */
    public static synchronized void assimilate()
    {
        if (assimilated) {
            return;
        }
        assimilated = true;

        // Assimilate java.util.logging
        final Logger rootLogger = LogManager.getLogManager().getLogger("");
        final Handler[] handlers = rootLogger.getHandlers();

        if (handlers != null) {
            for (Handler handler : handlers) {
                rootLogger.removeHandler(handler);
            }
        }

        SLF4JBridgeHandler.install();
        LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
        lc.addListener(new LevelChangePropagator());
        try {
            lc.addListener(new JMXConfigurator(lc,
                    ManagementFactory.getPlatformMBeanServer(),
                    new ObjectName("com.opentable.logging:name=LogbackConfig")));
        } catch (MalformedObjectNameException e) {
            throw new RuntimeException(e);
        }
        LoggerFactory.getLogger(AssimilateForeignLogging.class).info("java.util.logging was assimilated.");
    }

    /**
     * Try to unassimilate the logging frameworks.
     */
    public static synchronized void unassimilate()
    {
        SLF4JBridgeHandler.uninstall();
    }
}