text:
#include <sys/cdefs.h>

__FBSDID("$FreeBSD: soc2013/dpl/head/usr.bin/talk/ctl.c 227466 2011-11-06 08:17:23Z ed $");

#ifndef lint
static const char sccsid[] = "@(#)ctl.c	8.1 (Berkeley) 6/6/93";
#endif

/*
 * This file handles haggling with the various talk daemons to
 * get a socket to talk to. sockt is opened and connected in
 * the progress
 */

#include <sys/types.h>
#include <sys/socket.h>

#include <string.h>

#include "talk.h"
#include "talk_ctl.h"

struct	sockaddr_in daemon_addr = { .sin_len = sizeof(daemon_addr), .sin_family = AF_INET };
struct	sockaddr_in ctl_addr = { .sin_len = sizeof(ctl_addr), .sin_family = AF_INET };
struct	sockaddr_in my_addr = { .sin_len = sizeof(my_addr), .sin_family = AF_INET };

	/* inet addresses of the two machines */
struct	in_addr my_machine_addr;
struct	in_addr his_machine_addr;

u_short daemon_port;	/* port number of the talk daemon */

int	ctl_sockt;
int	sockt;
int	invitation_waiting = 0;

CTL_MSG msg;

void
open_sockt(void)
{
	socklen_t length;

	(void)memset(&my_addr, 0, sizeof(my_addr));
	my_addr.sin_family = AF_INET;
	my_addr.sin_len = sizeof(my_addr);
	my_addr.sin_addr = my_machine_addr;
	my_addr.sin_port = 0;
	sockt = socket(AF_INET, SOCK_STREAM, 0);
	if (sockt == -1)
		p_error("Bad socket");
	if (bind(sockt, (struct sockaddr *)&my_addr, sizeof(my_addr)) != 0)
		p_error("Binding local socket");
	length = sizeof(my_addr);
	if (getsockname(sockt, (struct sockaddr *)&my_addr, &length) == -1)
		p_error("Bad address for socket");
}

/* open the ctl socket */
void
open_ctl(void)
{
	socklen_t length;

	(void)memset(&ctl_addr, 0, sizeof(ctl_addr));
	ctl_addr.sin_family = AF_INET;
	ctl_addr.sin_len = sizeof(my_addr);
	ctl_addr.sin_port = 0;
	ctl_addr.sin_addr = my_machine_addr;
	ctl_sockt = socket(AF_INET, SOCK_DGRAM, 0);
	if (ctl_sockt == -1)
		p_error("Bad socket");
	if (bind(ctl_sockt,
	    (struct sockaddr *)&ctl_addr, sizeof(ctl_addr)) != 0)
		p_error("Couldn't bind to control socket");
	length = sizeof(ctl_addr);
	if (getsockname(ctl_sockt,
	    (struct sockaddr *)&ctl_addr, &length) == -1)
		p_error("Bad address for ctl socket");
}

/* print_addr is a debug print routine */
void
print_addr(struct sockaddr_in addr)
{
	int i;

	printf("addr = %lx, port = %o, family = %o zero = ",
		(u_long)addr.sin_addr.s_addr, addr.sin_port, addr.sin_family);
	for (i = 0; i<8;i++)
	printf("%o ", (int)addr.sin_zero[i]);
	putchar('\n');
}


text:
package com.wci.umls.server.jpa;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.xml.bind.annotation.XmlRootElement;

import org.hibernate.envers.Audited;

import com.wci.umls.server.ReleaseProperty;

/**
 * JPA and JAXB enabled implementation of a {@link ReleaseProperty}.
 */
@Entity
@Table(name = "release_properties")
@Audited
@XmlRootElement(name = "property")
public class ReleasePropertyJpa implements ReleaseProperty {

  /** The id. */
  @TableGenerator(name = "EntityIdGen", table = "table_generator", pkColumnValue = "Entity")
  @Id
  @GeneratedValue(strategy = GenerationType.TABLE, generator = "EntityIdGen")
  private Long id;

  /** The name. */
  @Column(nullable = false, length = 255)
  private String name;

  /** The value. */
  @Column(nullable = false, length = 4000)
  private String value;

  /**
   * Instantiates an empty {@link ReleasePropertyJpa}.
   */
  public ReleasePropertyJpa() {
    // do nothing
  }

  /**
   * Instantiates a {@link ReleasePropertyJpa} from the specified parameters.
   *
   * @param property the property
   */
  public ReleasePropertyJpa(ReleaseProperty property) {
    id = property.getId();
    name = property.getName();
    value = property.getValue();

  }

  /* see superclass */
  @Override
  public Long getId() {
    return id;
  }

  /* see superclass */
  @Override
  public void setId(Long id) {
    this.id = id;
  }

  /* see superclass */
  @Override
  public String getName() {
    return name;
  }

  /* see superclass */
  @Override
  public void setName(String name) {
    this.name = name;
  }

  /* see superclass */
  @Override
  public String getValue() {
    return value;
  }

  /* see superclass */
  @Override
  public void setValue(String value) {
    this.value = value;
  }

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

  /* see superclass */
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    ReleasePropertyJpa other = (ReleasePropertyJpa) obj;
    if (name == null) {
      if (other.name != null)
        return false;
    } else if (!name.equals(other.name))
      return false;
    if (value == null) {
      if (other.value != null)
        return false;
    } else if (!value.equals(other.value))
      return false;
    return true;
  }

  /* see superclass */
  @Override
  public String toString() {
    return name + ", " + value;
  }

}

redpajama_set_name: RedPajamaGithub


text:
from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT
from requestbuilder import Arg

class UpdateGroup(IAMRequest):
    DESCRIPTION = 'Change the name and/or path of a group'
    ARGS = [Arg('-g', '--group-name', dest='GroupName', metavar='GROUP',
                required=True, help='name of the group to update'),
            Arg('-n', '--new-group-name', dest='NewGroupName', metavar='GROUP',
                help='new name for the group'),
            Arg('-p', '--new-path', dest='NewPath', metavar='PATH',
                help='new path for the group'),
            AS_ACCOUNT]


text:
layout: post
title:  "How to stay alert"
ttc:    4min
difficulty: intermediate
date:   2014-10-27 17:23:00
categories: stockflare
---
How to use our alerts to stay vigilant to key events that could impact your portfolio.

## In this tutorial

In this tutorial we explain how to use Stockflare to stay alert to both positive and negative events that affect your stock. We discuss what to do, when one of these event occurs.

### Table of contents

This tutorial is divided into 3 parts

0. Where are my alerts
0. What different alerts are there
0. Do I need to take action?

### Part 1. Where are my alerts

We find the alerts in two place

0. Inside any stock widget
0. At your alerts page

#### Stock widget

If we click open any stock widget we can see an alarm icon. Clicking this icon opens the alerts summary, with a list of any key events for that widget.

![Alerts in widgets](/images/widget-alerts.png)

#### Your alerts page

Alternative, at the top right of the page, there is an alerts icon. Opening this page it will check what alerts have occurred in the last 24 hours for the stocks in your portfolio.

![Alerts page](/images/my-alerts.png)

### Part 2. What different alerts are there

We provide 5 different types of alerts. They are all automatic. When a key event occurs, with specific thresholds being crossed, then an alert is triggers. The five alerts are:

* Price: If the price moves by more than 2%, up or down, an alert is triggered
* Volume: If the 10 day average volume increases more than 10%, signaling a doubling in the trading in the last 24 hours, an alert is triggered
* Star: If a stock gains stars to become a 5-star stock, or loses it's 5 star rating, then an alert is triggered
* Recommendation: When the Wall Street rating changes from Buy, Sell or Hold, an alert is triggered
* Target Price: When there is a significant change in the target price of the Wall Street analysts, then an alert is triggered

### Do I take action?

Well, no. Too often people react too quickly to the news, without actually considering the long-term implications. Sometimes the best action is inaction.

However, an alert is a good reason to revisit the logic of owning a stock. Ask yourself, is it a bad-egg? Would you buy the stock today if you didn't have it in your portfolio?

Easy ways to do this, could include:

* check Stockflare's analysis of the stock
* look at the competitors, in case they are any better
* and if no competitor is interesting, pop over to Find Ideas, and search for a new business

### Conclusion

There are two easy ways to get alerts. Though using a Watchlist of your stocks is the best way. And if something negative has occurred at one of the stocks you own, then Stockflare is a great place for you to learn what alternatives there are.

### Presentation materials


text:
import sys

from eventlet import event
from eventlet import greenthread
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import reflection
from oslo_utils import timeutils
import six

from oslo_service._i18n import _LE, _LW, _

LOG = logging.getLogger(__name__)

class LoopingCallDone(Exception):
    """Exception to break out and stop a LoopingCallBase.

    The poll-function passed to LoopingCallBase can raise this exception to
    break out of the loop normally. This is somewhat analogous to
    StopIteration.

    An optional return-value can be included as the argument to the exception;
    this return-value will be returned by LoopingCallBase.wait()

    """

    def __init__(self, retvalue=True):
        """:param retvalue: Value that LoopingCallBase.wait() should return."""
        self.retvalue = retvalue

def _safe_wrapper(f, kind, func_name):
    """Wrapper that calls into wrapped function and logs errors as needed."""

    def func(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except LoopingCallDone:
            raise  # let the outer handler process this
        except Exception:
            LOG.error(_LE('%(kind)s %(func_name)r failed'),
                      {'kind': kind, 'func_name': func_name},
                      exc_info=True)
            return 0

    return func

class LoopingCallBase(object):
    _KIND = _("Unknown looping call")

    _RUN_ONLY_ONE_MESSAGE = _("A looping call can only run one function"
                              " at a time")

    def __init__(self, f=None, *args, **kw):
        self.args = args
        self.kw = kw
        self.f = f
        self._running = False
        self._thread = None
        self.done = None

    def stop(self):
        self._running = False

    def wait(self):
        return self.done.wait()

    def _on_done(self, gt, *args, **kwargs):
        self._thread = None
        self._running = False

    def _start(self, idle_for, initial_delay=None, stop_on_exception=True):
        if self._thread is not None:
            raise RuntimeError(self._RUN_ONLY_ONE_MESSAGE)
        self._running = True
        self.done = event.Event()
        self._thread = greenthread.spawn(
            self._run_loop, self._KIND, self.done, idle_for,
            initial_delay=initial_delay, stop_on_exception=stop_on_exception)
        self._thread.link(self._on_done)
        return self.done

    def _run_loop(self, kind, event, idle_for_func,
                  initial_delay=None, stop_on_exception=True):
        func_name = reflection.get_callable_name(self.f)
        func = self.f if stop_on_exception else _safe_wrapper(self.f, kind,
                                                              func_name)
        if initial_delay:
            greenthread.sleep(initial_delay)
        try:
            watch = timeutils.StopWatch()
            while self._running:
                watch.restart()
                result = func(*self.args, **self.kw)
                watch.stop()
                if not self._running:
                    break
                idle = idle_for_func(result, watch.elapsed())
                LOG.trace('%(kind)s %(func_name)r sleeping '
                          'for %(idle).02f seconds',
                          {'func_name': func_name, 'idle': idle,
                           'kind': kind})
                greenthread.sleep(idle)
        except LoopingCallDone as e:
            event.send(e.retvalue)
        except Exception:
            exc_info = sys.exc_info()
            try:
                LOG.error(_LE('%(kind)s %(func_name)r failed'),
                          {'kind': kind, 'func_name': func_name},
                          exc_info=exc_info)
                event.send_exception(*exc_info)
            finally:
                del exc_info
            return
        else:
            event.send(True)

class FixedIntervalLoopingCall(LoopingCallBase):
    """A fixed interval looping call."""

    _RUN_ONLY_ONE_MESSAGE = _("A fixed interval looping call can only run"
                              " one function at a time")

    _KIND = _('Fixed interval looping call')

    def start(self, interval, initial_delay=None, stop_on_exception=True):
        def _idle_for(result, elapsed):
            delay = elapsed - interval
            if delay > 0:
                func_name = reflection.get_callable_name(self.f)
                LOG.warning(_LW('Function %(func_name)r run outlasted '
                                'interval by %(delay).2f sec'),
                            {'func_name': func_name, 'delay': delay})
            return -delay if delay < 0 else 0
        return self._start(_idle_for, initial_delay=initial_delay,
                           stop_on_exception=stop_on_exception)

class DynamicLoopingCall(LoopingCallBase):
    """A looping call which sleeps until the next known event.

    The function called should return how long to sleep for before being
    called again.
    """

    _RUN_ONLY_ONE_MESSAGE = _("A dynamic interval looping call can only run"
                              " one function at a time")
    _TASK_MISSING_SLEEP_VALUE_MESSAGE = _(
        "A dynamic interval looping call should supply either an"
        " interval or periodic_interval_max"
    )

    _KIND = _('Dynamic interval looping call')

    def start(self, initial_delay=None, periodic_interval_max=None,
              stop_on_exception=True):
        def _idle_for(suggested_delay, elapsed):
            delay = suggested_delay
            if delay is None:
                if periodic_interval_max is not None:
                    delay = periodic_interval_max
                else:
                    # Note(suro-patz): An application used to receive a
                    #     TypeError thrown from eventlet layer, before
                    #     this RuntimeError was introduced.
                    raise RuntimeError(
                        self._TASK_MISSING_SLEEP_VALUE_MESSAGE)
            else:
                if periodic_interval_max is not None:
                    delay = min(delay, periodic_interval_max)
            return delay

        return self._start(_idle_for, initial_delay=initial_delay,
                           stop_on_exception=stop_on_exception)

class RetryDecorator(object):
    """Decorator for retrying a function upon suggested exceptions.

    The decorated function is retried for the given number of times, and the
    sleep time between the retries is incremented until max sleep time is
    reached. If the max retry count is set to -1, then the decorated function
    is invoked indefinitely until an exception is thrown, and the caught
    exception is not in the list of suggested exceptions.
    """

    def __init__(self, max_retry_count=-1, inc_sleep_time=10,
                 max_sleep_time=60, exceptions=()):
        """Configure the retry object using the input params.

        :param max_retry_count: maximum number of times the given function must
                                be retried when one of the input 'exceptions'
                                is caught. When set to -1, it will be retried
                                indefinitely until an exception is thrown
                                and the caught exception is not in param
                                exceptions.
        :param inc_sleep_time: incremental time in seconds for sleep time
                               between retries
        :param max_sleep_time: max sleep time in seconds beyond which the sleep
                               time will not be incremented using param
                               inc_sleep_time. On reaching this threshold,
                               max_sleep_time will be used as the sleep time.
        :param exceptions: suggested exceptions for which the function must be
                           retried, if no exceptions are provided (the default)
                           then all exceptions will be reraised, and no
                           retrying will be triggered.
        """
        self._max_retry_count = max_retry_count
        self._inc_sleep_time = inc_sleep_time
        self._max_sleep_time = max_sleep_time
        self._exceptions = exceptions
        self._retry_count = 0
        self._sleep_time = 0

    def __call__(self, f):
        func_name = reflection.get_callable_name(f)

        def _func(*args, **kwargs):
            result = None
            try:
                if self._retry_count:
                    LOG.debug("Invoking %(func_name)s; retry count is "
                              "%(retry_count)d.",
                              {'func_name': func_name,
                               'retry_count': self._retry_count})
                result = f(*args, **kwargs)
            except self._exceptions:
                with excutils.save_and_reraise_exception() as ctxt:
                    LOG.warn(_LW("Exception which is in the suggested list of "
                                 "exceptions occurred while invoking function:"
                                 " %s."),
                             func_name,
                             exc_info=True)
                    if (self._max_retry_count != -1 and
                            self._retry_count >= self._max_retry_count):
                        LOG.error(_LE("Cannot retry %(func_name)s upon "
                                      "suggested exception "
                                      "since retry count (%(retry_count)d) "
                                      "reached max retry count "
                                      "(%(max_retry_count)d)."),
                                  {'retry_count': self._retry_count,
                                   'max_retry_count': self._max_retry_count,
                                   'func_name': func_name})
                    else:
                        ctxt.reraise = False
                        self._retry_count += 1
                        self._sleep_time += self._inc_sleep_time
                        return self._sleep_time
            raise LoopingCallDone(result)

        @six.wraps(f)
        def func(*args, **kwargs):
            loop = DynamicLoopingCall(_func, *args, **kwargs)
            evt = loop.start(periodic_interval_max=self._max_sleep_time)
            LOG.debug("Waiting for function %s to return.", func_name)
            return evt.wait()

        return func


text:
public class Prob02 {

	static int first = 1;
	 static int second = 2;

	public static void main(String[] args) {
		int sum = 0;
		for(;second<=4000000;){
			if(second%2==0){
				sum+=second;
			}
			System.out.println(nextFab());
		}
		System.out.println(sum);

	}
	private static int nextFab(){
		int temp = first + second;
		first = second;
		second = temp;
		return temp;
	}

}


text:
package com.example.innf.beziertest;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {

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

    public void secondBezierTest(View view) {
        startActivity(new Intent(this, SecondBezierActivity.class));
    }

    public void thirdBezierTest(View view) {
        startActivity(new Intent(this, ThirdBezierActivity.class));
    }

    public void drawPadBezierTest(View view) {
        startActivity(new Intent(this, DrawPadActivity.class));
    }

    public void pathMorphingBezierTest(View view) {
        startActivity(new Intent(this, PathMorphingActivity.class));
    }

    public void waveBezierTest(View view) {
        startActivity(new Intent(this, WaveActivity.class));
    }

    public void pathBezierTest(View view) {
        startActivity(new Intent(this, PathBezierActivity.class));
    }
}


text:
package zap

import (
	"crypto/tls"
	"log"
	"net"

	"github.com/puma/puma-dev/dev/launch"
)

func (s *Server) serveHTTP() error {
	var listener net.Listener
	var err error

	if s.HTTPAddr == "Socket" {
		listener = getSocketListener(s.HTTPAddr)
	} else {
		listener, err = net.Listen("tcp", s.HTTPAddr)
		if err != nil {
			log.Fatal("[zap] unable to create listener", err)
		}
	}

	log.Println("[zap] http listening at", listener.Addr())
	return s.http.Serve(listener)
}

func (s *Server) serveHTTPS() error {
	var listener net.Listener
	var err error

	if s.HTTPSAddr == "SocketTLS" {
		listener = tls.NewListener(getSocketListener(s.HTTPSAddr), s.https.TLSConfig)
	} else {
		listener, err = tls.Listen("tcp", s.HTTPSAddr, s.https.TLSConfig)
		if err != nil {
			log.Fatal("[zap] unable to create tls listener", err)
		}
	}

	log.Println("[zap] https listening at", listener.Addr())
	return s.https.Serve(listener)
}

func getSocketListener(socket string) net.Listener {
	listeners, err := launch.SocketListeners(socket)
	if err != nil {
		log.Fatal("[zap] unable to get launchd socket listener", err)
	}
	return listeners[0]
}


text:
var twgl = window.twgl;
var mat4 = require('gl-matrix').mat4;
var vec3 = require('gl-matrix').vec3;

function Renderable(gl, wrapProgram, program, tex) {
    this.vertexBuffer = null;
    this.texture = tex;
    this.translationMatrix = null;

    this.mapDimenX = 8;
    this.mapDimenY = 8;

    this.offset = 0;
    this.program = program;
    this.programWrap = wrapProgram;
    this.gl = gl;

    gl.useProgram(program);

    this.attribs = {
        vertices: [],
        a_position: gl.getAttribLocation(this.program, 'a_position'),
        a_tilepos: gl.getAttribLocation(this.program, 'a_tilepos'),
        a_texcoord: gl.getAttribLocation(this.program, 'a_texcoord')
    };

    this.translationMatrix = mat4.create();

    this.FSIZE = new Float32Array().BYTES_PER_ELEMENT;

    this.customtilepos = new Float32Array([0.0, 0.0]);

    this.initUniforms();
};

Renderable.prototype.addQuad = function(x, y, w, h, u, v) {
    var x1 = x;
    var x2 = x + w;
    var y1 = y;
    var y2 = y + h;

    var base_quad = [
        x, y, 0, -1, u, v,
        x + w, y, 1, -1, u, v,
        x + w, y + h, 1, 0, u, v,
        x, y, 0, -1, u, v,
        x + w, y + h, 1, 0, u, v,
        x, y + h, 0, 0, u, v
    ];

    for (var i = 0; i < base_quad.length; i++) {
        this.attribs.vertices.push(base_quad[i]);
    };

    this.offset += 6;
};

Renderable.prototype.bind = function() {
    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vertexBuffer)
};

Renderable.prototype.render = function(customUniforms) {
    var gl = this.gl;
    customUniforms = customUniforms || [];

    gl.useProgram(this.program);

    //Bind buffer;
    this.bind(gl);

    var uniforms = {
        tex: this.texture,
        u_transform: this.translationMatrix,
        u_mapdimenx: this.mapDimenX,
        u_mapdimeny: this.mapDimenY,
        u_customtilepos: this.customtilepos
    };

    for(var i = 0; i < customUniforms.length; i++) {
        uniforms[customUniforms[i][0]] = customUniforms[i][1];
    };

    //Set uniforms
    twgl.setUniforms(this.programWrap, uniforms);

    //Set attributes
    gl.vertexAttribPointer(this.attribs.a_position, 2, gl.FLOAT, false, 6 * this.FSIZE, 0);
    gl.enableVertexAttribArray(this.attribs.a_position);

    gl.vertexAttribPointer(this.attribs.a_texcoord, 2, gl.FLOAT, false, 6 * this.FSIZE, 2 * this.FSIZE);
    gl.enableVertexAttribArray(this.attribs.a_texcoord);

    gl.vertexAttribPointer(this.attribs.a_tilepos, 2, gl.FLOAT, false, 6 * this.FSIZE, 4 * this.FSIZE);
    gl.enableVertexAttribArray(this.attribs.a_tilepos);

    //Render
    gl.drawArrays(gl.TRIANGLES, 0, this.offset);
};

Renderable.prototype.initUniforms = function() {
    twgl.setUniforms(this.programWrap, {
        tex: this.texture,
        u_transform: this.translationMatrix,
        u_mapdimenx: this.mapDimenX,
        u_mapdimeny: this.mapDimenY
    });
};

Renderable.prototype.initBuffers = function() {
    var vertices = new Float32Array(this.attribs["vertices"]);
    var gl = this.gl;

    gl.useProgram(this.program);

    this.vertexBuffer = gl.createBuffer()

    gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

};

module.exports = Renderable;


text:
package com.github.games647.fastlogin.core.importer;

import com.github.games647.fastlogin.core.AuthStorage;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;

public abstract class Importer {

    public abstract int importData(Connection source, DataSource target, AuthStorage storage) throws SQLException;

    protected void closeQuietly(AutoCloseable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception ignore) {
                //ignore
            }
        }
    }
}


text:
% generate matrix
A = [1 2; 3 4; 5 6]

% get size of matrix
size(A)
sz = size(A) % returns a matrix
sz2 = size(sz) % also returns a matrix

size(A, 1) % size of first dimension
size(A, 2) % size of second dimension

% length returns size of longest dimension
v = [1 2 3 4]
length(v)
length(A)

pwd % print working directory
% `cd '/Users/Niels/'` % change directory
% `ls` to list files in current working directory

%% READ IN DATA
load 'data/featuresX.dat'
load 'data/priceY.dat'

disp('X features')
size(featuresX)
disp(featuresX)
disp('price data')
size(priceY)
disp(priceY)

% list current variable environment
whos

% delete variable
clear featuresX
whos

% SUBSETTING A VECTOR
v = priceY(1:4) % select first 10 elements
whos

% SAVING DATA TO .mat FILE
save 'data/hello.mat' v; % saves data in binary format

% RELOADING VARIABLES
clear
load 'data/hello.mat'
whos

% SAVE DATA AS TEXT FILES
save 'data/hello.txt' v -ascii;

% SUBSETTING A MATRIX
A = [1 2; 3 4; 5 6]
A(3,2) % get 3rd row, 2nd column
A(2,:) % get 2nd row, all columns
A(:,2) % get all rows, 2nd column
A([1 3], 2) % get 1st and 3rd row, 2nd column

% MATRIX VALUE ASSIGNMENT

A(:, 2) = [10; 11; 12] % replace 2nd column with new values
A = [ A, [100; 101; 102]] % column concat
size(A)

% put all elements of A into a single vector
A(:)

% column concat matrices
A = [1 2; 3 4; 5 6]
B = [11 12; 13 14; 15 16]
C = [A B]

% row concatenate matrices
D = [A; B]


text:
import logging
import os
import pytest
from copy import copy
from subprocess import call
from tests.beeswax.impala_beeswax import ImpalaBeeswaxException
from tests.common.impala_test_suite import *
from tests.common.test_vector import *
from tests.common.impala_cluster import ImpalaCluster
from tests.common.test_dimensions import create_exec_option_dimension
from tests.common.skip import SkipIfS3
from tests.util.shell_util import exec_process

@SkipIfS3.caching
class TestHdfsFdCaching(ImpalaTestSuite):
  """
  This test suite tests the behavior of HDFS file descriptor caching by evaluating the
  metrics exposed by the Impala daemon.
  """

  NUM_ROWS = 10000

  @classmethod
  def file_format_constraint(cls, v):
    return v.get_value('table_format').file_format in ["parquet"]

  @classmethod
  def add_test_dimensions(cls):
    super(TestHdfsFdCaching, cls).add_test_dimensions()
    cls.TestMatrix.add_constraint(cls.file_format_constraint)

  @classmethod
  def get_workload(cls):
    return 'functional-query'

  def setup_method(self, method):
    self.cleanup_db("cachefd")
    self.client.execute("create database cachefd")
    self.client.execute("create table cachefd.simple(id int, col1 int, col2 int) "
                        "stored as parquet")
    buf = "insert into cachefd.simple values"
    self.client.execute(buf + ", ".join(["({0},{0},{0})".format(x) for x in range(self.NUM_ROWS)]))

  def teardown_method(self, methd):
    self.cleanup_db("cachedfd")

  @pytest.mark.execute_serially
  def test_simple_scan(self, vector):

    # One table, one file, one handle
    num_handles_before = self.cached_handles()
    self.execute_query("select * from cachefd.simple limit 1", vector=vector)
    num_handles_after = self.cached_handles()

    # Should have at least one more handle cached and not more than three more
    assert num_handles_after >= (num_handles_before + 1)
    assert num_handles_after <= (num_handles_before + 3)

    # No open handles if scanning is finished
    assert self.outstanding_handles() == 0

    # No change when reading the table again
    for x in range(10):
      self.execute_query("select * from cachefd.simple limit 1", vector=vector)

    assert num_handles_after == self.cached_handles()
    assert self.outstanding_handles() == 0

  def cached_handles(self):
    return self.get_agg_metric("impala-server.io.mgr.num-cached-file-handles")

  def outstanding_handles(self):
    return self.get_agg_metric("impala-server.io.mgr.num-file-handles-outstanding")

  def get_agg_metric(self, key, fun=sum):
    cluster = ImpalaCluster()
    return fun([s.service.get_metric_value(key) for s
                in cluster.impalads])


text:
package org.apache.druid.indexing.overlord.hrtr;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Supplier;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.apache.curator.framework.CuratorFramework;
import org.apache.druid.curator.ZkEnablementConfig;
import org.apache.druid.discovery.DruidNodeDiscoveryProvider;
import org.apache.druid.guice.annotations.EscalatedGlobal;
import org.apache.druid.guice.annotations.Smile;
import org.apache.druid.indexing.overlord.TaskRunnerFactory;
import org.apache.druid.indexing.overlord.TaskStorage;
import org.apache.druid.indexing.overlord.autoscaling.NoopProvisioningStrategy;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningSchedulerConfig;
import org.apache.druid.indexing.overlord.autoscaling.ProvisioningStrategy;
import org.apache.druid.indexing.overlord.config.HttpRemoteTaskRunnerConfig;
import org.apache.druid.indexing.overlord.setup.WorkerBehaviorConfig;
import org.apache.druid.java.util.http.client.HttpClient;
import org.apache.druid.server.initialization.IndexerZkConfig;

import javax.annotation.Nullable;

/**
 */
public class HttpRemoteTaskRunnerFactory implements TaskRunnerFactory<HttpRemoteTaskRunner>
{
  public static final String TYPE_NAME = "httpRemote";

  private final ObjectMapper smileMapper;
  private final HttpRemoteTaskRunnerConfig httpRemoteTaskRunnerConfig;
  private final HttpClient httpClient;
  private final Supplier<WorkerBehaviorConfig> workerConfigRef;
  private final ProvisioningSchedulerConfig provisioningSchedulerConfig;
  private final ProvisioningStrategy provisioningStrategy;
  private final DruidNodeDiscoveryProvider druidNodeDiscoveryProvider;
  private final TaskStorage taskStorage;

  // ZK_CLEANUP_TODO : Remove these when RemoteTaskRunner and WorkerTaskMonitor are removed.
  @Nullable //Null if zk is disabled
  private final CuratorFramework cf;
  private final IndexerZkConfig indexerZkConfig;

  @Inject
  public HttpRemoteTaskRunnerFactory(
      @Smile final ObjectMapper smileMapper,
      final HttpRemoteTaskRunnerConfig httpRemoteTaskRunnerConfig,
      @EscalatedGlobal final HttpClient httpClient,
      final Supplier<WorkerBehaviorConfig> workerConfigRef,
      final ProvisioningSchedulerConfig provisioningSchedulerConfig,
      final ProvisioningStrategy provisioningStrategy,
      final DruidNodeDiscoveryProvider druidNodeDiscoveryProvider,
      final TaskStorage taskStorage,
      final Provider<CuratorFramework> cfProvider,
      final IndexerZkConfig indexerZkConfig,
      final ZkEnablementConfig zkEnablementConfig
  )
  {
    this.smileMapper = smileMapper;
    this.httpRemoteTaskRunnerConfig = httpRemoteTaskRunnerConfig;
    this.httpClient = httpClient;
    this.workerConfigRef = workerConfigRef;
    this.provisioningSchedulerConfig = provisioningSchedulerConfig;
    this.provisioningStrategy = provisioningStrategy;
    this.druidNodeDiscoveryProvider = druidNodeDiscoveryProvider;
    this.taskStorage = taskStorage;
    this.indexerZkConfig = indexerZkConfig;

    if (zkEnablementConfig.isEnabled()) {
      this.cf = cfProvider.get();
    } else {
      this.cf = null;
    }
  }

  @Override
  public HttpRemoteTaskRunner build()
  {
    return new HttpRemoteTaskRunner(
        smileMapper,
        httpRemoteTaskRunnerConfig,
        httpClient,
        workerConfigRef,
        provisioningSchedulerConfig.isDoAutoscale() ? provisioningStrategy : new NoopProvisioningStrategy<>(),
        druidNodeDiscoveryProvider,
        taskStorage,
        cf,
        indexerZkConfig
    );
  }
}


text:
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using iHentai.Services;
using iHentai.Services.Models.Core;
using iHentai.Services.Models.Script;
using PropertyChanged;

namespace iHentai.ViewModels.Script
{
    internal class ScriptGalleryDetailViewModel : ViewModelBase
    {
        public ScriptGalleryDetailViewModel(ScriptApi api, ScriptGalleryModel gallery)
        {
            Api = api;
            Gallery = gallery;
            Refresh();
        }

        public bool IsLoading { get; private set; }
        public ScriptApi Api { get; }
        public ScriptGalleryModel Gallery { get; }
        public ScriptGalleryDetailModel? Detail { get; private set; }
        public Exception? Error { get; private set; }

        [DependsOn(nameof(Gallery), nameof(Detail))]
        public string GalleryTitle => Gallery?.Title ?? Detail?.Title ?? "";

        [DependsOn(nameof(Gallery), nameof(Detail))]
        public string Thumb => Detail?.Thumb ?? Gallery?.Thumb ?? "";

        public async Task Refresh()
        {
            IsLoading = true;
            Error = null;
            try
            {
                Detail = await Api.Detail(Gallery);
            }
            catch (Exception exception)
            {
#if DEBUG
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
#endif
                Error = exception;
            }
            IsLoading = false;
        }

        public async Task<bool> CheckCanOpenChapter(IMangaChapter chapter)
        {
            if (Api.HasCheckCanOpenChapter())
            {
                return await Api.CheckCanOpenChapter(chapter);
            }
            else
            {
                return true;
            }
        }
    }
}


text:
<manifest package="com.safechat.android.commons">

    <application/>
</manifest>


text:
namespace pythonic
{

  namespace utils
  {

    template <bool vector_form>
    template <class E, class F, size_t N>
    void _broadcast_copy<vector_form>::
    operator()(E &&self, F const &other, utils::int_<N>, utils::int_<0>)
    {
      long self_size = std::distance(self.begin(), self.end()),
           other_size = std::distance(other.begin(), other.end());
      if (other_size > 0) // empty array sometimes happen when filtering
      {
#ifdef _OPENMP
        if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (long i = 0; i < other_size; ++i)
            self.fast(i) = other.fast(i);
        else
#endif
          std::copy(other.begin(), other.end(), self.begin());

        // eventually repeat the pattern
        size_t n = self_size / other_size;
#ifdef _OPENMP
        if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
        else
#endif
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
      }
    }

    // ``D'' is not ``0'' so we should broadcast
    template <bool vector_form>
    template <class E, class F, size_t N, size_t D>
    void _broadcast_copy<vector_form>::
    operator()(E &&self, F const &other, utils::int_<N>, utils::int_<D>)
    {
      self.fast(0) = other;
#ifdef _OPENMP
      long n = self.shape[0];
      if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
        for (long i = 1; i < n; ++i)
          self.fast(i) = self.fast(0);
      else
#endif
        std::fill(self.begin() + 1, self.end(), self.fast(0));
    }

#ifdef USE_BOOST_SIMD
    // specialize for SIMD only if available
    // otherwise use the std::copy fallback
    template <class E, class F>
    void _broadcast_copy<true>::operator()(E &&self, F const &other,
                                           utils::int_<1>, utils::int_<0>)
    {
      using T = typename F::dtype;
      using vT = typename boost::simd::native<T, BOOST_SIMD_DEFAULT_EXTENSION>;
      long self_size = std::distance(self.begin(), self.end()),
           other_size = std::distance(other.begin(), other.end());

      if (other_size > 0) // empty array sometimes happen when filtering
      {
        static const std::size_t vN = boost::simd::meta::cardinal_of<vT>::value;
        const long bound = other_size / vN * vN;

        long i;
#ifdef _OPENMP
        if (bound >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (i = 0; i < bound; i += vN)
            self.store(other.load(i), i);
        else
#endif
          for (i = 0; i < bound; i += vN)
            self.store(other.load(i), i);
        for (; i < other_size; ++i)
          self.fast(i) = other.fast(i);

        size_t n = self_size / other_size;
#ifdef _OPENMP
        if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
        else
#endif
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
      }
    }

    template <class E, class F, size_t N>
    void _broadcast_copy<true>::operator()(E &&self, F const &other,
                                           utils::int_<N>, utils::int_<0>)
    {
      long self_size = std::distance(self.begin(), self.end()),
           other_size = std::distance(other.begin(), other.end());
      if (other_size > 0) // empty array sometimes happen when filtering
      {
#ifdef _OPENMP
        if (other_size >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (long i = 0; i < other_size; ++i)
            (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(),
                    utils::int_<0>());
        else
#endif
          for (long i = 0; i < other_size; ++i)
            (*this)(self.fast(i), other.fast(i), utils::int_<N - 1>(),
                    utils::int_<0>());

        // eventually repeat the pattern
        size_t n = self_size / other_size;
#ifdef _OPENMP
        if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
        else
#endif
          for (size_t i = 1; i < n; ++i)
            std::copy_n(self.begin(), other_size,
                        self.begin() + i * other_size);
      }
    }

    // ``D'' is not ``0'' so we should broadcast
    template <class E, class F, size_t N, size_t D>
    void _broadcast_copy<true>::operator()(E &&self, F const &other,
                                           utils::int_<N>, utils::int_<D>)
    {
      (*this)(self.fast(0), other, utils::int_<N - 1>(), utils::int_<D - 1>());
#ifdef _OPENMP
      long n = self.shape[0];
      if (n >= PYTHRAN_OPENMP_MIN_ITERATION_COUNT)
#pragma omp parallel for
        for (long i = 1; i < n; ++i)
          self.fast(i) = self.fast(0);
      else
#endif
        std::fill(self.begin() + 1, self.end(), self.fast(0));
    }

#endif

    template <class E, class F, size_t N, size_t D, bool vector_form>
    E &broadcast_copy(E &self, F const &other)
    {
      _broadcast_copy<vector_form>{}(self, other, utils::int_<N>(),
                                     utils::int_<D>());
      return self;
    }
  }
}

#endif


text:
module Discerner
  module Methods
    module Models
      module Warning
        def self.included(base)
          attr_accessor :force_save
        end

        def warnings
          @warnings ||= ActiveModel::Errors.new(self)
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.parse.ParseImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:gravity="center" />

</FrameLayout>


text:
env_caller = File.dirname(caller.detect{|f| f =~ /\/env\.rb:/}) if caller.detect{|f| f =~ /\/env\.rb:/}
if env_caller
  require 'rails'
  require 'cucumber/rails/application'
  ENV["RAILS_ENV"] ||= "test"
  ENV["RAILS_ROOT"] ||= File.expand_path(env_caller + "/../..")
  require File.expand_path(ENV["RAILS_ROOT"] + '/config/environment')
  require 'cucumber/rails/action_controller'

  if defined?(ActiveRecord::Base)
    require 'rails/test_help'
  else
    require 'action_dispatch/testing/test_process'
    require 'action_dispatch/testing/integration'
  end

  if !Rails.application.config.cache_classes
    warn "WARNING: You have set Rails' config.cache_classes to false (most likely in config/environments/cucumber.rb).  This setting is known to cause problems with database transactions. Set config.cache_classes to true if you want to use transactions.  For more information see https://rspec.lighthouseapp.com/projects/16211/tickets/165."
  end

  require 'cucumber/rails/world'
  require 'cucumber/rails/hooks'
  require 'cucumber/rails/capybara'
  require 'cucumber/rails/database'

else
  warn "WARNING: Cucumber-rails required outside of env.rb.  The rest of loading is being defered until env.rb is called.
  To avoid this warning, move 'gem cucumber-rails' under only group :test in your Gemfile"
end


text:
#include "c2cplatform/library/the3/tinyxml/tinyxml.h"
#include "global_consts.h"
#include "config_loader.h"
#include <sstream>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <assert.h>

//////////////////////////
// Utils Definition
uint32_t HexStr2Int(const std::string& sHexStr); // "0x00a10000" --> 10551296L
void LRTrim(std::string& sValue);
bool IsDigit(const std::string& sDigit);
void SpliteStrings(std::string& sStr, std::vector<std::string>& VecStrs);

//////////////////////////
// class CConfigLoader
CConfigLoader::CConfigLoader()
: m_bInit(false)
{
}

CConfigLoader::~CConfigLoader()
{
}

int CConfigLoader::Initialize(
                              const char* pszLocalCfgFile)
{
    assert(pszLocalCfgFile);

    m_bInit = true;
    m_sLocalCfgFile = pszLocalCfgFile;

    return 0;
}

int CConfigLoader::ReLoadAll()
{
    return LoadAll();
}

int CConfigLoader::LoadAll()
{
    assert(m_bInit);

    // Load Config from ServiceConfig.xml & Set value to m_mapSvcCateCfg
    int iRetCode = 0;

    iRetCode = doLoadPrivateConfig();
    if(iRetCode != 0)
    {
        return -1;
    }

    doLoadGlobalServiceConfig(); // ¼æÈÝÄ¿Ç°Çé¿ö
/*
	iRetCode = doLoadGlobalServiceConfig2(m_stLocalCfgItem.sSvcHome.c_str());
    if(iRetCode != 0)
    {
        return -1;
    }
*/

    return 0;
}

int CConfigLoader::doLoadPrivateConfig()
{
    assert(m_bInit);

    m_stLocalCfgItem.sHost              = DEFAULT_LISTEN_HOST;
    m_stLocalCfgItem.wListenPort      = DEFAULT_LISTEN_PORT;
    m_stLocalCfgItem.sSvrStatLog        = DEFAULT_NETIO_STAT_LOG;
	m_stLocalCfgItem.sServiceLog        = DEFAULT_SERVICE_LOG;
	m_stLocalCfgItem.sPerformLog        = DEFAULT_PERFORM_LOG;
    m_stLocalCfgItem.sGlobalServiceConf = DEFAULT_GLOBAL_SVC_CONF;
	m_stLocalCfgItem.sLogSvcConf        = DEFAULT_LOG_SVC_CONF;
	m_stLocalCfgItem.sLogModule         = DEFAULT_LOG_MODULE;
    m_stLocalCfgItem.iMsgqBackKey       = 60001;
    m_stLocalCfgItem.iMsgqCntlKey       = 60000;
	m_stLocalCfgItem.bDebugSupport      = true;
	m_stLocalCfgItem.sSvcHome           = DEFAULT_SVC_HOME;
	m_stLocalCfgItem.iLowestTcpHandlers = DEFAULT_CLEAN_HANDLE_BEGIN;
	m_stLocalCfgItem.dwMaxSendBufLen    = 300 * 1024;
	m_stLocalCfgItem.dwMaxRecvBufLen    = 300 * 1024;

    TiXmlDocument doc(m_sLocalCfgFile.c_str());

    if (!doc.LoadFile())
    {
        m_sLastErrMsg = "Cannot open XML file : ";
        m_sLastErrMsg += m_sLocalCfgFile;
        return -1;
    }

    TiXmlNode* node = NULL;
    TiXmlElement* RootElement = NULL;
    TiXmlElement* ItemElement = NULL;

    // Get Root Element
    node = doc.FirstChild(LOCAL_ROOT.c_str());
    RootElement = node->ToElement();

    // Search for 'Item'
    node = RootElement->FirstChildElement();
    ItemElement = node->ToElement();

    std::string sName;
    std::string sValue;

    while(ItemElement)
    {
        sName = ItemElement->Attribute(ITEM_NAME.c_str());
        LRTrim(sName);
        sValue = ItemElement->Attribute(ITEM_VALUE.c_str());
        LRTrim(sValue);

		if(LISTEN_PORT == sName)
        {
			if(!IsDigit(sValue))
            {
                m_sLastErrMsg = "Invalid Listen Port : ";
                m_sLastErrMsg += sValue;
                return -1;
            }

            m_stLocalCfgItem.wListenPort = atoi(sValue.c_str());
        }
        else if(LISTEN_HOST == sName)
        {
            m_stLocalCfgItem.sHost = sValue;
        }
        else if(GLOBAL_SVC_CONF == sName)
        {
            m_stLocalCfgItem.sGlobalServiceConf = sValue;
        }
        else if(NETIO_STAT_LOG == sName)
        {
            m_stLocalCfgItem.sSvrStatLog = sValue;
        }
		else if(SERVICE_LOG == sName)
        {
            m_stLocalCfgItem.sServiceLog = sValue;
        }
		else if(PERFORM_LOG == sName)
        {
            m_stLocalCfgItem.sPerformLog = sValue;
        }
		else if(LOG_SVC_CONF == sName)
        {
			m_stLocalCfgItem.sLogSvcConf = sValue;
        }
		else if(LOG_MODULE_NAME == sName)
        {
			m_stLocalCfgItem.sLogModule = sValue;
        }
		else if(DEBUG_SUPPORT == sName)
        {
            m_stLocalCfgItem.bDebugSupport = (sValue != "0");
        }
		else if(SVC_HOME == sName)
        {
            m_stLocalCfgItem.sSvcHome = sValue;
        }
		else if(LOWEST_TCP_HANDLERS == sName)
		{
			m_stLocalCfgItem.iLowestTcpHandlers = atoi(sValue.c_str());
		}
		else if(MAX_SEND_BUF_LEN == sName)
		{
			m_stLocalCfgItem.dwMaxSendBufLen = atoi(sValue.c_str());
		}
		else if(MAX_RECV_BUF_LEN == sName)
		{
			m_stLocalCfgItem.dwMaxRecvBufLen = atoi(sValue.c_str());
		}

        ItemElement = ItemElement->NextSiblingElement();
    }

    return 0;
}

int CConfigLoader::doLoadGlobalServiceConfig()
{
    assert(m_bInit);

    TiXmlDocument doc(m_stLocalCfgItem.sGlobalServiceConf.c_str());

    if (!doc.LoadFile())
    {
        m_sLastErrMsg = "Cannot open XML file : ";
        m_sLastErrMsg += m_stLocalCfgItem.sGlobalServiceConf;
        return -1;
    }

    TiXmlNode* node = NULL;
    TiXmlElement* SvcGrpRootElement = NULL;
    TiXmlElement* GrpElement = NULL;

    // Get Root Element
    node = doc.FirstChild(SVC_GROUP_ROOT.c_str());
    SvcGrpRootElement = node->ToElement();

    // Search for 'Category'
    node = SvcGrpRootElement->FirstChildElement();
    GrpElement = node->ToElement();

    std::string sGroupId;
    std::string sGroupName;
    std::string sFrontMsgQKey;
    std::string sBackMsgQKey;
    std::string sGroupSize;
    std::string sLogModule;
    while(GrpElement)
    {
		sGroupName = GrpElement->Attribute(GROUP_NAME.c_str());
        LRTrim(sGroupName);
		sFrontMsgQKey = GrpElement->Attribute(FRONT_MSGQ_KEY.c_str());
		LRTrim(sFrontMsgQKey);
		sGroupId = GrpElement->Attribute(GROUP_ID.c_str());
		LRTrim(sGroupId);
		sBackMsgQKey = GrpElement->Attribute(BACK_MSGQ_KEY.c_str());
		LRTrim(sBackMsgQKey);
		sGroupSize = GrpElement->Attribute(GROUP_SIZE.c_str());
		LRTrim(sGroupSize);

		if(MakeRouteInfo(sGroupId, sFrontMsgQKey, sBackMsgQKey, sGroupSize) != 0)
			return -1;

/*
		SvcInfo_T stSvcInfo;
		stSvcInfo.sGroupName = sGroupName;
		stSvcInfo.sLogModule = sLogModule;
        m_mapSvcInfo[dwGroupId] = stSvcInfo;
  */
        GrpElement = GrpElement->NextSiblingElement();
    }

    if(0 == m_stLocalCfgItem.iMsgqBackKey)
    {
        m_sLastErrMsg = "Service Config Missing MsgqBackKey";
        return -1;
    }
    else if(0 == m_stLocalCfgItem.iMsgqCntlKey)
    {
        m_sLastErrMsg = "Service Config Missing MsgqCntlKey";
        return -1;
    }

    return 0;
}

void CConfigLoader::Dump(std::ostream& os)
{
    os << "------------------ Private Config ---------------------" << std::endl;
    os << "Listen Port          = " << m_stLocalCfgItem.wListenPort << std::endl;
    os << "Group MsgQ Back Key  = " << m_stLocalCfgItem.iMsgqBackKey << "(0x" << std::hex << m_stLocalCfgItem.iMsgqBackKey << std::dec << ")" << std::endl;
    os << "Controllor MsgQ Key  = " << m_stLocalCfgItem.iMsgqCntlKey << "(0x" << std::hex << m_stLocalCfgItem.iMsgqCntlKey << std::dec << ")" << std::endl;
	os << "Stat Log             = " << m_stLocalCfgItem.sSvrStatLog << std::endl;
	os << "Svc Home             = " << m_stLocalCfgItem.sSvcHome << std::endl;
	os << "Lowest TCP Handlers  = " << m_stLocalCfgItem.iLowestTcpHandlers << std::endl;
	os << "Max Send Buf Len     = " << m_stLocalCfgItem.dwMaxSendBufLen << std::endl;
	os << "Max Recv Buf Len     = " << m_stLocalCfgItem.dwMaxRecvBufLen << std::endl;
    os << "-------------------------------------------------------" << std::endl;
}

/////////////////////////////////////////////
// Uitls
uint32_t HexStr2Int(const std::string& sHexStr) // "0x00a10000" --> 10551296L
{
    std::string::const_iterator it = sHexStr.begin() + 2;
    uint32_t dwResult = 0;
    uint32_t dwVal = 0;
    uint8_t cVal = 0;
    for(; it != sHexStr.end(); ++it)
    {
        cVal = *it;
        if(cVal >= '0' && cVal <= '9')
        {
            dwVal = cVal - '0';
        }
        else if(cVal >= 'a' && cVal <= 'f')
        {
            dwVal = cVal - 'a' + 10;
        }
        else if(cVal >= 'A' && cVal <= 'F')
        {
            dwVal = cVal - 'A' + 10;
        }
        else
            return 0; // Invalid HexStr

        dwResult = dwResult * 16 + dwVal;
    }

    return dwResult;
}

void LRTrim(std::string& sValue)
{
	char chSpace = ' ';
	char chTab = '\t';
	std::string::const_iterator it1, it2;

	for(it1 = sValue.begin(); it1 != sValue.end(); it1++)
	{
		if(*it1 != chSpace && *it1 != chTab)
			break;
	}

	it2 = sValue.end() - 1;
	if(it2 == it1)
	{
		it2 = sValue.end();
	}
	else
	{
		for(; it2 >= it1; it2--)
		{
			if(*it2 != chSpace && *it2 != chTab)
			{
				it2++;
				break;
			}
		}
	}

	sValue = std::string(it1, it2);
}

bool IsDigit(const std::string& sDigit)
{
    if(sDigit.length() == 0)
        return false;

    for(std::string::const_iterator it = sDigit.begin()
        ; it != sDigit.end(); ++it)
    {
        char cVal = *it;
        if(!isdigit(cVal))
            return false;
    }

    return true;
}

void SpliteStrings(std::string& sStr, std::vector<std::string>& VecStrs)
{
    std::string::const_iterator itItemStart;
    std::string::size_type itStartPos, itEndPos;
    char cDelima = ';';
    std::string sDelima = ";";

    // Append Delima if need
    if(*(sStr.rbegin()) != cDelima)
        sStr += sDelima;

    itStartPos = 0;
    itItemStart = sStr.begin();
    std::string sTmp;

    while(1)
    {
        itEndPos = sStr.find_first_of(cDelima, itStartPos);

        if(itEndPos == std::string::npos)
        {
            break;
        }

        sTmp = std::string(
            itItemStart + itStartPos,
            itItemStart + itEndPos);

        itStartPos = itEndPos + 1;

        if(sTmp.length() == 0) // No strValue between two Delimas
        {
            continue;
        }

        LRTrim(sTmp);

        VecStrs.push_back(sTmp);
    }
}

int CConfigLoader::doLoadGlobalServiceConfig2(const char* pszBaseDir)
{
	assert(m_bInit);

	// Get all priv config file path
	DIR* dp = NULL;
    if((dp = opendir(pszBaseDir)) == NULL)
	{
		printf("Cannot open %s\n", pszBaseDir);
		return -1;
	}

	std::vector<std::string> vec_priv_conf;
	std::string sTmp;
	struct dirent *dirp;
	while((dirp = readdir(dp)) != NULL)
		if(dirp->d_type == DT_DIR && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0)
		{
				//printf("type[%d]name[%s] ", dirp->d_type, dirp->d_name);
				sTmp = pszBaseDir;
				sTmp += "/";
				sTmp += dirp->d_name;
				sTmp += "/etc/cont_config.xml";
				vec_priv_conf.push_back(sTmp);
		}

	closedir(dp);

	// Get Route info from all these priv config files
	TiXmlNode* node = NULL;
	TiXmlElement* RootElement = NULL;
	TiXmlElement* ItemElement = NULL;
	std::string sPrivConfFile;
	std::string sName;
	std::string sValue;
	std::string sGroupId;
	std::string sFrontQKey;
	std::string sBackQKey;
	std::string sGroupSize;
	for(std::vector<std::string>::iterator it = vec_priv_conf.begin(); it != vec_priv_conf.end(); ++it)
	{
		sPrivConfFile = (*it);
		//printf("parsing file [%s]\n", sPrivConfFile.c_str());
		TiXmlDocument doc(sPrivConfFile.c_str());
		if (!doc.LoadFile())
		{
			m_sLastErrMsg = "Cannot open XML file : ";
			m_sLastErrMsg += sPrivConfFile;
			return -1;
		}

		// Get Root Element
		node = doc.FirstChild(LOCAL_ROOT.c_str());
		RootElement = node->ToElement();

		// Search for 'Item'
		node = RootElement->FirstChildElement();
		ItemElement = node->ToElement();

		sGroupId = "";
		sFrontQKey = "";
		sBackQKey = "";
		sGroupSize = "";
		while(ItemElement)
		{
			sName = ItemElement->Attribute(ITEM_NAME.c_str());
			LRTrim(sName);
			sValue = ItemElement->Attribute(ITEM_VALUE.c_str());
			LRTrim(sValue);

			if(THIS_GROUP_ID == sName)
				sGroupId = sValue;
			else if(FRONT_MSGQ_KEY == sName)
				sFrontQKey = sValue;
			else if(BACK_MSGQ_KEY == sName)
				sBackQKey = sValue;
			else if(GROUP_SIZE == sName)
				sGroupSize = sValue;

			ItemElement = ItemElement->NextSiblingElement();
		}
		MakeRouteInfo(sGroupId, sFrontQKey, sBackQKey, sGroupSize);
	}

    if(0 == m_stLocalCfgItem.iMsgqBackKey)
    {
        m_sLastErrMsg = "Service Config Missing MsgqBackKey";
        return -1;
    }
    else if(0 == m_stLocalCfgItem.iMsgqCntlKey)
    {
        m_sLastErrMsg = "Service Config Missing MsgqCntlKey";
        return -1;
    }
	return 0;
}

int CConfigLoader::MakeRouteInfo(
	std::string& sGroupId, std::string& sFrontMsgQKey,
	std::string& sBackMsgQKey, std::string& sGroupSize)
{
	if(sGroupId.empty())
		return -1;

	sGroupId += "0000";
	uint32_t dwGroupId = HexStr2Int(sGroupId);
	if(0 == dwGroupId)
	{
		m_sLastErrMsg = "Invalid Group Id : ";
		m_sLastErrMsg += sGroupId;
		return -1;
	}

	GroupMsgqKeyFrontMap_T::iterator it = m_mapMsgqKeyFront.find(dwGroupId);
	if(sFrontMsgQKey.empty() && it != m_mapMsgqKeyFront.end())
		return 0;

	if(sFrontMsgQKey.empty())
	{
		std::stringstream oss;
		oss << (dwGroupId / 0x10000);
		sFrontMsgQKey = oss.str();
	}

	////////////////////// Try to Split FrontKeys ///////////////////////////////
	std::vector<std::string> vecFrontKeys;
	SpliteStrings(sFrontMsgQKey, vecFrontKeys);
	///////////////////////////////////////////////////////////////////////////////

	FrontKeys_T stFrontKeys;
	stFrontKeys.nKeyNum = vecFrontKeys.size();
	assert(stFrontKeys.nKeyNum <= MAX_FRONT_KEYS);
	for(uint32_t i = 0; i < stFrontKeys.nKeyNum; ++i)
	{
		stFrontKeys.arrKeys[i] = atoi(vecFrontKeys[i].c_str());
		//printf("GroupId[0x%x] Keys[%d] KeyNum[%d]\n", dwGroupId, stFrontKeys.arrKeys[i], stFrontKeys.nKeyNum);
	}

	m_mapMsgqKeyFront[dwGroupId] = stFrontKeys;

	return 0;
}


text:
'use strict';

require('../../../../../TestHelper');

/* global inject */

var entrySelect = require('./Helper').entrySelect,
    selectAndGet = require('./Helper').selectAndGet,
    bootstrap = require('./Helper').bootstrap;

var domClasses = require('min-dom/lib/classes');

describe('element-templates/parts - Visibility', function() {

  var diagramXML = require('./Visibility.bpmn'),
      elementTemplates = require('./Visibility');

  beforeEach(bootstrap(diagramXML, elementTemplates));

  it('should show default entries', inject(function() {

    // when
    selectAndGet('Task_Default');

    // then
    expectShown([
      'id',
      'name',
      'elementTemplate-chooser'
    ]);

    expectHidden([
      'asyncBefore',
      'executionListeners'
    ]);
  }));

  describe('customization', function() {

    it('should show all entries', inject(function() {

      // when
      selectAndGet('Task_All');

      // then
      expectShown([
        'id',
        'name',
        'elementTemplate-chooser',
        'documentation',
        'asyncBefore',
        'executionListeners',
        'properties'
      ]);
    }));

    it('should hide entries selectively', inject(function() {

      // when
      selectAndGet('Task_AllButSome');

      // then
      expectShown([
        'id',
        'properties',
        'parameterName',
        'elementTemplate-chooser'
      ]);

      expectHidden([
        'name',
        'asyncBefore',
        'asyncAfter',
        'documentation',
        'executionListeners'
      ]);
    }));

    it('should show entries selectively', inject(function() {

      // when
      selectAndGet('Task_Some');

      // then
      expectShown([
        'elementTemplate-chooser',
        'asyncBefore',
        'asyncAfter',
        'executionListeners',
        'documentation'
      ]);

      expectHidden([
        'id',
        'name',
        'properties',
        'parameterName'
      ]);
    }));

  });

});

var HIDDEN_CLS = 'bpp-hidden';

function expectShown(entryIds) {
  expectVisibility(entryIds, true);
}

function expectHidden(entryIds) {
  expectVisibility(entryIds, false);
}

function expectVisibility(entryIds, shown) {

  if (typeof entryIds === 'string') {
    entryIds = [ entryIds ];
  }

  entryIds.forEach(function(entryId) {
    var entryNode = entrySelect(entryId);

    if (!entryNode) {
      console.error('Node for', entryId, 'does not exist');
    }

    expect(entryNode).to.exist;

    var classes = domClasses(entryNode);

    expect(classes.has(HIDDEN_CLS)).to.eql(!shown);
  });
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>EAPSI: Network modeling of evolutionary genomics</AwardTitle>
    <AwardEffectiveDate>06/01/2011</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2012</AwardExpirationDate>
    <AwardAmount>5700</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      01090000
      <Directorate>
        <LongName>Office Of The Director</LongName>
      </Directorate>
      <Division>
        <LongName>Office Of Internatl Science &Engineering</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Anne L. Emig</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>05/18/2011</MinAmdLetterDate>
    <MaxAmdLetterDate>05/18/2011</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1108282</AwardID>
    <Investigator>
      <FirstName>Joel</FirstName>
      <LastName>Wagner</LastName>
      <EmailAddress/>
      <StartDate>05/18/2011</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Wagner Joel P</Name>
      <CityName>Cambridge</CityName>
      <ZipCode>021385345</ZipCode>
      <PhoneNumber></PhoneNumber>
      <StreetAddress></StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Massachusetts</StateName>
      <StateCode>MA</StateCode>
    </Institution>
  </Award>
</rootTag>


text:
class UnifiedRemote < Cask
  version :latest
  sha256 :no_check

  url 'http://www.unifiedremote.com/download/macosx-setup'
  homepage 'http://www.unifiedremote.com'
  license :unknown

  app 'Unified Remote.app'
end


text:
package domino.configuration_watching

import org.osgi.service.cm.{ ConfigurationAdmin, ManagedService }
import domino.capsule.{ CapsuleContext, CapsuleScope }
import org.osgi.service.metatype.{ MetaTypeProvider => JMetaTypeProvider }
import domino.scala_osgi_metatype.interfaces.MetaTypeProvider
import org.osgi.framework.{ BundleContext, Constants, ServiceRegistration }
import java.util.Dictionary
import domino.DominoUtil
import domino.service_consuming.ServiceConsuming

/**
 * A capsule which allows easy access to the [[org.osgi.service.cm.ConfigurationAdmin]] functionality related
 * to normal configurations (not factory configurations).
 *
 * @param servicePid Service PID
 * @param f Handler which is executed initially and on every configuration change
 * @param metaTypeProvider Optional metatype provider
 * @param serviceConsuming Dependency
 * @param bundleContext Dependency
 * @param capsuleContext Dependency
 */
class ConfigurationWatcherCapsule(
  servicePid: String,
  f: Map[String, Any] => Unit,
  metaTypeProvider: Option[MetaTypeProvider],
  serviceConsuming: ServiceConsuming,
  bundleContext: BundleContext,
  capsuleContext: CapsuleContext)
    extends AbstractConfigurationWatcherCapsule(metaTypeProvider) with ManagedService {

  private[this] var _reg: ServiceRegistration[ManagedService] = _

  /**
   * Returns the service registration of the configuration listener as long as the current scope is active.
   */
  protected[configuration_watching] def reg = _reg

  /**
   * Contains the interfaces under which this object will be put in the service registry.
   */
  private[this] lazy val interfacesArray: Array[String] = Array(classOf[ManagedService].getName) ++ (
    metaTypeProvider map { p => classOf[JMetaTypeProvider].getName })

  /**
   * Contains the new capsule scope.
   */
  private[this] var newCapsuleScope: Option[CapsuleScope] = None

  /**
   * Contains the previous configuration map. Used to determine whether the configuration has changed.
   */
  private[this] var oldOptConf: Option[Map[String, Any]] = None

  override def start(): Unit = {
    // Service properties
    val propertiesMap = Map(Constants.SERVICE_PID -> servicePid)

    // Find out current configuration by pulling it
    val optConf = getConfigDirectly

    // At first execute inner block synchronously with current configuration. Even if configuration admin is not present.
    executeBlockWithConf(optConf)

    // Register managed service. This will cause ConfigurationAdmin push the current configuration in a separate
    // thread and call updated(). In updated(), we prevent the second execution of the inner block because we check
    // whether the configuration is still the same.
    val tmp = bundleContext.registerService(interfacesArray, this, DominoUtil.convertToDictionary(propertiesMap))
    _reg = tmp.asInstanceOf[ServiceRegistration[ManagedService]]
  }

  override def stop(): Unit = {
    // Stop capsules in the newly created capsule scope
    newCapsuleScope foreach { _.stop() }

    // Unregister managed service
    _reg.unregister()
    _reg = null
  }

  override def updated(conf: Dictionary[String, _]): Unit = {
    // We query the config admin directly because the user can make sure then that the config value is already set.
    // See http://www.mail-archive.com/users@felix.apache.org/msg06764.html
    val safeOptConf = Option(conf).map(d => DominoUtil.convertToMap(d)).orElse(getConfigDirectly)

    // Execute handler only if configuration has changed
    executeBlockWithConfIfChanged(safeOptConf)
  }

  /**
   * Executes the handler only if the configuration has changed compared to the one which was used last.
   */
  private[this] def executeBlockWithConfIfChanged(optConf: Option[Map[String, Any]]): Unit = {
    if (oldOptConf != optConf) {
      executeBlockWithConf(optConf)
    }
  }

  /**
   * Executes the handler with the given configuration and saves it for future comparison.
   */
  private[this] def executeBlockWithConf(optConf: Option[Map[String, Any]]): Unit = {
    // Stop capsules in previous scope
    newCapsuleScope foreach { _.stop() }

    // Save old conf
    oldOptConf = optConf

    // Start capsules in new scope
    newCapsuleScope = Some(capsuleContext.executeWithinNewCapsuleScope {
      optConf match {
        case Some(conf) =>
          // Execute handler
          f(conf)

        case None =>
          // No configuration there. We use an empty map.
          f(Map.empty)
      }
    })

  }

  /**
   * Pulls the current configuration from the configuration admin.
   */
  private[this] def getConfigDirectly: Option[Map[String, Any]] = {
    serviceConsuming.withService[ConfigurationAdmin, Option[Dictionary[String, _]]] {
      case Some(confAdmin) =>
        Option(confAdmin.getConfiguration(servicePid)) match {
          case Some(c) => Option(c.getProperties)
          case None => None
        }

      case None => None
    }.map(d => DominoUtil.convertToMap(d))
  }
}


text:
package db

import java.util.UUID

import io.apibuilder.api.v0.models.{UserForm, UserUpdateForm}
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerSuite

class UsersDaoSpec extends PlaySpec with GuiceOneAppPerSuite with db.Helpers {

  def createUserForm(
    email: String = "test-user-" + UUID.randomUUID.toString + "@test.apibuilder.io",
    nickname: Option[String] = None
  ) = UserForm(email = email, password = UUID.randomUUID.toString, nickname = nickname)

  "upsert" in {
    val user1 = upsertUser("michael@mailinator.com")
    val user2 = upsertUser("michael@mailinator.com")
    user1.guid must be(user2.guid)
  }

  "create different records for different emails" in {
    val user1 = upsertUser("michael@mailinator.com")
    val user2 = upsertUser("other@mailinator.com")
    user1.guid != user2.guid must be(true)
  }

  "return empty list without error guid is not a valid format" in {
    usersDao.findByGuid("ASDF") must be(None)
  }

  "findByGuid" in {
    val user = upsertUser("michael@mailinator.com")
    usersDao.findByGuid(UUID.randomUUID.toString) must be(None)
    usersDao.findByGuid(user.guid) must be(Some(user))
  }

  "user can login after creation" in {
    val form = UserForm(
      email = UUID.randomUUID.toString + "@test.apibuilder.io",
      password = "testing"
    )
    val user = usersDao.create(form)
    userPasswordsDao.isValid(user.guid, "testing") must be(true)
    userPasswordsDao.isValid(user.guid, "password") must be(false)
  }

  "validate" must {

    "email is valid" in {
      usersDao.validateNewUser(
        UserForm(
          email = "bad-email",
          password = "testing"
        )
      ).map(_.message) must be(Seq("Invalid email address"))
    }

    "email is unique" in {
      val form = UserForm(
        email = "test-user-" + UUID.randomUUID.toString + "@test.apibuilder.io",
        password = "testing"
      )

      usersDao.validateNewUser(form) must be(Nil)

      val user = usersDao.create(form)

      usersDao.validateNewUser(form).map(_.message) must be(Seq("User with this email address already exists"))
      usersDao.validateNewUser(form.copy(email = "other-" + form.email)).map(_.message) must be(Nil)

      val updateForm = UserUpdateForm(
        email = form.email,
        nickname = UUID.randomUUID.toString
      )

      usersDao.validate(updateForm, existingUser = Some(user)).map(_.message) must be(Nil)
      usersDao.validate(updateForm, existingUser = Some(upsertUser())).map(_.message) must be(Seq("User with this email address already exists"))
    }

    "password" in {
      val form = UserForm(
        email = "test-user-" + UUID.randomUUID.toString + "@test.apibuilder.io",
        password = "bad"
      )

      usersDao.validateNewUser(form).map(_.message) must be(Seq("Password must be at least 5 characters"))
    }

    "email in upper case with whitespace" in {
      val email = "TEST-user-" + UUID.randomUUID.toString + "@test.apibuilder.io"
      val form = UserForm(
        email = " " + email,
        password = "testing"
      )

      usersDao.validateNewUser(form) must be(Nil)

      val user = usersDao.create(form)
      user.email must be(email.toLowerCase)

      usersDao.validateNewUser(
        form.copy(email = email.toUpperCase)
      ).map(_.message) must be(
        Seq("User with this email address already exists")
      )
    }

    "nickname is url friendly" in {
      usersDao.validateNewUser(createUserForm(nickname = Some("bad nickname"))).map(_.message) must be(
        Seq("Key must be in all lower case and contain alphanumerics only (-, _, and . are supported). A valid key would be: bad-nickname")
      )
    }

    "nickname is unique" in {
      val form = UserForm(
        email = "test-user-" + UUID.randomUUID.toString + "@test.apibuilder.io",
        password = "testing",
        nickname = Some(UUID.randomUUID.toString)
      )

      usersDao.validateNewUser(form) must be(Nil)
      usersDao.validateNewUser(form.copy(nickname = form.nickname.map(n => "other-" + n))).map(_.message) must be(Nil)

      val user = usersDao.create(form)

      val formWithUniqueEmail = UserUpdateForm(
        email = "other-" + form.email,
        nickname = user.nickname,
        name = form.name
      )

      usersDao.validate(formWithUniqueEmail).map(_.message) must be(Seq("User with this nickname already exists"))
      usersDao.validate(formWithUniqueEmail, existingUser = Some(user)).map(_.message) must be(Nil)
      usersDao.validate(formWithUniqueEmail, existingUser = Some(upsertUser())).map(_.message) must be(Seq("User with this nickname already exists"))
    }

  }

  "generateNickname" must {

    "defaults to a unique name based on email" in {
      val base = UUID.randomUUID.toString
      val email1 = base + "@test1.apibuilder.io"
      val email2 = base + "@test2.apibuilder.io"

      usersDao.generateNickname(email1) must be(base)
      val user = usersDao.create(createUserForm(email1))
      user.nickname must be(base)

      usersDao.generateNickname(email2) must be(base + "-2")
      val user2 = usersDao.create(createUserForm(email2))
      user2.nickname must be(base + "-2")
    }

    "generateNickname creates a url valid token" in {
      usersDao.generateNickname("  with a SPACE  ") must be("with-a-space")
    }

  }

  "update" in {
    val user = createRandomUser()
    val email = "test-email-2@" + UUID.randomUUID.toString
    val nickname = user.nickname + "-2"
    val name = "Test User " + UUID.randomUUID.toString

    usersDao.update(testUser, user, UserUpdateForm(
      email = " " + email + " ",
      nickname = nickname,
      name = Some(name)
    ))

    val updated = usersDao.findByGuid(user.guid).get
    updated.email must be(email)
    updated.nickname must be(nickname)
    updated.name must be(Some(name))
  }

}


text:
#if !NET
using System.Activities;

namespace XrmUnitTest.Test.Builders
{
    /// <summary>
    /// Workflow Builder
    /// </summary>
    public class WorkflowInvokerBuilder : DLaB.Xrm.Test.Builders.WorkflowInvokerBuilderBase<WorkflowInvokerBuilder>
    {
        /// <summary>
        /// Gets the current instance of the builder.
        /// </summary>
        protected override WorkflowInvokerBuilder This => this;

        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowInvokerBuilder"/> class.
        /// </summary>
        /// <param name="workflow">The workflow to invoke.</param>
        public WorkflowInvokerBuilder(Activity workflow) : base(workflow)
        {

        }
    }
}
#endif


text:
package org.apache.asterix.experiment.action.base;

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

public class SequentialActionList extends AbstractAction {
    private final List<IAction> actions;

    public SequentialActionList() {
        actions = new ArrayList<>();
    }

    public void add(IAction exec) {
        actions.add(exec);
    }

    @Override
    protected void doPerform() throws Exception {
        for (IAction e : actions) {
            e.perform();
        }
    }
}


text:
package com.xeiam.xchange.hitbtc.dto.marketdata;

import static org.fest.assertions.api.Assertions.assertThat;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.junit.Test;

import com.fasterxml.jackson.databind.ObjectMapper;

public class HitbtcSymbolsJsonTest {

  @Test
  public void testUnmarshal() throws IOException {

    // Read in the JSON from the example resources
    InputStream is = HitbtcSymbolsJsonTest.class.getResourceAsStream("/marketdata/example-symbols-data.json");

    // Use Jackson to parse it
    ObjectMapper mapper = new ObjectMapper();
    HitbtcSymbols hitbtcSymbols = mapper.readValue(is, HitbtcSymbols.class);

    List<HitbtcSymbol> symbols = hitbtcSymbols.getHitbtcSymbols();
    assertThat(symbols).hasSize(15);
    HitbtcSymbol symbol = symbols.get(0);
    assertThat(symbol.getCommodity()).isEqualTo("BCN");
    assertThat(symbol.getCurrency()).isEqualTo("BTC");
    assertThat(symbol.getStep()).isEqualTo("0.000000001");
    assertThat(symbol.getLot()).isEqualTo("100");
    assertThat(symbol.getTakeLiquidityRate()).isEqualTo("0.001");
    assertThat(symbol.getProvideLiquidityRate()).isEqualTo("-0.0001");
  }
}


text:
package nps;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@SpringBootApplication
public class InviteApplication {

	public static void main(String[] args) {
		SpringApplication.run(InviteApplication.class, args);
	}

}


text:
<?php

namespace SumoCoders\FrameworkUserBundle\EventListener;

use SumoCoders\FrameworkMultiUserBundle\Entity\BaseUser;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;

final class SwitchUserListener
{
    /** @var TokenStorageInterface */
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function onSwitchUser(SwitchUserEvent $event): void
    {
        $impersonator = $this->getImpersonatingUser();

        $impersonatingUser = $this->tokenStorage->getToken()->getUser();
        $impersonatedUser = $event->getTargetUser();

        // If a user is impersonating, check if we want to switch back, in that case
        // $user will be the same as the user doing the impersonating.
        if ($impersonator instanceof BaseUser && $impersonator->getId() === $event->getTargetUser()->getId()) {
            $impersonatedUser = $this->tokenStorage->getToken()->getUser();
            $impersonatingUser = $event->getTargetUser();
        }

        if (!$impersonatingUser->canSwitchTo($impersonatedUser)) {
            throw new AccessDeniedException();
        }
    }

    private function getImpersonatingUser(): ?BaseUser
    {
        foreach ($this->tokenStorage->getToken()->getRoles() as $role) {
            if ($role instanceof SwitchUserRole) {
                return $role->getSource()->getUser();
            }
        }

        return null;
    }
}


text:
<?php

namespace MoneyMan;

use MoneyMan\Currency;
use MoneyMan\Money;
use Swap\Swap;

/**
 * Exchange Class
 *
 * Defines how an exchange should be performed. A subclass is needed to derive
 * the exchange rate used for
 *
 * @category Exchange
 * @package  Exchange
 * @author   Graham A. Sutton <gsutton@sproutloud.com>
 * @license  MIT <http://mit.org>
 * @link     http://mit.org
 */
class Exchange
{
    /**
     * The exchange rate service.
     * @var \Swap\Swap
     */
    private $service;

    /**
     * Constructor
     *
     * Accepts the name of an exchange rates service from Swap. Default is set to
     * use Fixer.
     *
     * @param \Swap\Swap $service  The service to query exchange rates from.
     */
    public function __construct($service)
    {
        $this->service = $service;
    }

    /**
     * Add two \MoneyMan\Money objects together. This will return a new \MoneyMan\Money
     * object.
     *
     * IMPORTANT! If the currencies are different, the second parameter will be converted
     * to the first parameter's currency and then added together.
     *
     * @param \MoneyMan\Money $money1  The first money object.
     * @param \MoneyMan\Money $money2  The second money object.
     *
     * @return \MoneyMan\Money
     */
    public function add(Money $money1, Money $money2)
    {
        // Convert the second money object to the first money object's currency
        $converted_money = $this->exchange($money2, $money1->getCurrency());

        // Return the new \MoneyMan\Money in the first parameter's currency
        return $money1->add($converted_money);
    }

    /**
     * Subtract one \MoneyMan\Money object from another. This will return a brand new
     * \MoneyMan\Money object.
     *
     * IMPORTANT! If the currencies are different, the second parameter will be converted
     * to the first parameter's currency. Afterwards, the second parameter's exchanged
     * amount will be deducted from the first parameter's amount and returned in a
     * new \MoneyMan\Money object.
     *
     * @param \MoneyMan\Money $money1  The first money object
     * @param \MoneyMan\Money $money2  The second money object
     *
     * @return \MoneyMan\Money
     */
    public function subtract(Money $money1, Money $money2)
    {
        // Convert the second money object to the first money object's currency
        $converted_money = $this->exchange($money2, $money1->getCurrency());

        // Return the new \MoneyMan\Money in the first parameter's currency
        return $money1->subtract($converted_money);
    }

    /**
     * Exchanges one \MoneyMan\Money object into the desired currency.
     *
     * This should return a brand new \MoneyMan\Money object.
     *
     * @param \MoneyMan\Money    $base   The money we are exchanging.
     * @param \MoneyMan\Currency $quote  The currency we are exchanging to.
     *
     * @return \MoneyMan\Money
     */
    public function exchange(Money $base, Currency $quote)
    {
        // If they are of the same currency, there's no need to query the service.
        $exchange_rate = $base->getCurrency()->equals($quote)
            ? 1.00000
            : $this->getExchangeRate($base->getCurrency(), $quote);

        return new Money(
            (int) round($base->getAmount() * $exchange_rate, 0),
            $quote
        );
    }

    /**
     * Gets the exchange rate between the base and quote currencies.
     *
     * @param Currency $base   The currency we want to exchange from.
     * @param Currency $quote  The currency we want to exchange to.
     *
     * @return float
     */
    public function getExchangeRate(Currency $base, Currency $quote)
    {
        $base_code  = $base->getCode();
        $quote_code = $quote->getCode();

        return $this->service->latest("$base_code/$quote_code")->getValue();
    }
}


text:
package br.senac.tadsb.pi3.livrarianext.validar;

import java.util.regex.Pattern;

/**
 *
 * @author Nuneez
 */
public class Telefone {
    public static boolean validar(String telefone) {

        if (telefone.trim().isEmpty())
            return false;

        if (Pattern.matches("[0-9]+", telefone) && telefone.length() > 7) {
            return true;
        }
        return false;
    }
}


text:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, Integer, String, ForeignKey, DateTime,
                        MetaData, Boolean, CheckConstraint, Index, Table, Enum)
from sqlalchemy import create_engine, func  # noqa: F401
from sqlalchemy.orm import relationship, sessionmaker, backref  # noqa: F401
from sqlalchemy.sql import select

import os, enum

# for Alembic
naming = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

# Disable naming convention if we're in the test suite; this allows doing it in
# sqlite to work
if os.environ.get('OPENAKUN_TESTING') == '1':
    Base = declarative_base()
else:
    Base = declarative_base(metadata=MetaData(naming_convention=naming))

user_with_role = Table('user_with_role', Base.metadata,
                       Column('user_id', Integer, ForeignKey('users.id')),
                       Column('role_id', Integer, ForeignKey('user_roles.id')))

# This satisfies the requirements of flask_login for a User class.
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    email = Column(String)
    email_verified = Column(Boolean, nullable=False, default=False)
    password_hash = Column(String)
    joined_date = Column(DateTime(timezone=True))

    roles = relationship("UserRole", secondary=user_with_role,
                         backref='users')

    def __repr__(self):
        return "<User '{}' (id {})>".format(self.name, self.id)

    # Methods for flask_login
    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

class UserRole(Base):
    __tablename__ = 'user_roles'

    id = Column(Integer, primary_key=True)
    title = Column(String)

class Story(Base):
    __tablename__ = 'stories'

    id = Column(Integer, primary_key=True)
    title = Column(String)
    description = Column(String)
    author_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    channel_id = Column(Integer, ForeignKey('channels.id'), nullable=False)

    author = relationship("User", backref="stories")
    channel = relationship("Channel", uselist=False)

    def __repr__(self):
        return "<Story '{}' (id {}) by {}>".format(self.title, self.id,
                                                   self.author.name)

class Chapter(Base):
    __tablename__ = 'chapters'

    id = Column(Integer, primary_key=True)
    title = Column(String)
    story_id = Column(Integer, ForeignKey('stories.id'), nullable=False)
    is_appendix = Column(Boolean, nullable=False, default=False)
    order_idx = Column(Integer, nullable=False)

    story = relationship("Story", backref=backref(
        "chapters",
        order_by='Chapter.is_appendix,Chapter.order_idx'
    ))

    def __repr__(self):
        return ("<Chapter '{}' (id {}, idx {}) of '{}', appendix={}>".
                format(self.title, self.id, self.order_idx, self.story.title,
                       self.is_appendix))

class PostType(enum.Enum):
    Text = 1
    Vote = 2
    Writein = 3

def order_idx_default(context):
    cid = context.get_current_parameters()['chapter_id']
    rv = context.connection.execute(select([
        func.coalesce(
            func.max(Post.order_idx) + 10,
            0)]).where(Post.chapter_id == cid))
    rows = rv.fetchall()
    return rows[0][0]

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True)
    text = Column(String)
    posted_date = Column(DateTime(timezone=True), nullable=False)
    story_id = Column(Integer, ForeignKey('stories.id'), nullable=False)
    chapter_id = Column(Integer, ForeignKey('chapters.id'), nullable=False)
    order_idx = Column(Integer, nullable=False, default=order_idx_default)
    post_type = Column(Enum(PostType), default=PostType.Text, nullable=False)
    # null unless type is Vote
    # vote_id = Column(Integer, ForeignKey('vote_info.id'))

    story = relationship("Story", backref=backref(
        "posts",
        order_by='Post.order_idx'
    ))
    chapter = relationship("Chapter", backref="posts")
    vote_info = relationship("VoteInfo", uselist=False, back_populates="post")

class VoteInfo(Base):
    __tablename__ = 'vote_info'

    id = Column(Integer, primary_key=True)
    # unique is True to enforce one-to-one relationship with Post
    post_id = Column(Integer, ForeignKey('posts.id'), nullable=False,
                     unique=True)
    vote_question = Column(String, nullable=False)
    multivote = Column(Boolean, default=True, nullable=False)
    writein_allowed = Column(Boolean, default=True, nullable=False)
    votes_hidden = Column(Boolean, default=False, nullable=False)
    time_closed = Column(DateTime(timezone=True))

    votes = relationship('VoteEntry', uselist=True, back_populates='vote_info')
    post = relationship('Post', back_populates='vote_info')

class VoteEntry(Base):
    __tablename__ = 'vote_entries'

    id = Column(Integer, primary_key=True)
    vote_id = Column(Integer, ForeignKey('vote_info.id'), nullable=False)
    vote_text = Column(String, nullable=False)
    killed = Column(Boolean, default=False, nullable=False)
    killed_text = Column(String)

    votes = relationship('UserVote')
    vote_info = relationship('VoteInfo', uselist=False, back_populates='votes')

class UserVote(Base):
    __tablename__ = 'user_votes'
    __table_args__ = (
        CheckConstraint('(user_id is null) != (anon_id is null)',
                        name='user_or_anon'),
    )

    id = Column(Integer, primary_key=True)
    entry_id = Column(Integer, ForeignKey('vote_entries.id'), nullable=False,
                      )
    user_id = Column(Integer, ForeignKey('users.id'),
                     nullable=True)
    anon_id = Column(String, nullable=True)

class WriteinEntry(Base):
    __tablename__ = 'writein_entries'
    __table_args__ = (
        CheckConstraint('(user_id is null) != (anon_id is null)',
                        name='user_or_anon'),
    )

    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    anon_id = Column(String)
    text = Column(String)
    date_added = Column(DateTime(timezone=True), nullable=False)

class Channel(Base):
    __tablename__ = 'channels'

    id = Column(Integer, primary_key=True)
    private = Column(Boolean, default=False, nullable=False)

    story = relationship("Story", back_populates='channel')

class ChatMessage(Base):
    __tablename__ = 'chat_messages'
    __table_args__ = (
        CheckConstraint('(user_id is null) != (anon_id is null)',
                        name='user_or_anon'),
        Index('channel_idx', 'channel_id', 'date')
    )

    id = Column(Integer, primary_key=True)
    id_token = Column(String, nullable=False, unique=True)
    channel_id = Column(Integer, ForeignKey('channels.id'), nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'))
    anon_id = Column(String)
    date = Column(DateTime(timezone=True), nullable=False)
    text = Column(String)
    special = Column(Boolean, default=False, nullable=False)
    image = Column(Boolean, default=False, nullable=False)

    user = relationship("User")
    channel = relationship("Channel", backref="messages")

class AddressIdentifier(Base):
    __tablename__ = 'address_identifier'

    hash = Column(String, primary_key=True)
    ip = Column(String, nullable=False)

def init_db(engine, use_alembic=True):
    Base.metadata.create_all(engine)

    if use_alembic:
        from alembic.config import Config
        from alembic import command
        alembic_cfg = Config("alembic.ini")
        command.stamp(alembic_cfg, "head")


text:
package com.siyeh.igtest.classlayout;

public abstract class AbstractClassWithoutAbstractMethodsChildInspection2
        extends ClassWithAbstractMethods
{

    public void barangus()
    {
    }

}


text:
<?xml version='1.0'?>
<employer_request
  xmlns="http://openhbx.org/api/terms/1.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://openhbx.org/api/terms/1.0 ../../schemas/vocabulary.xsd">
  <header>
    <hbx_id>DC0</hbx_id>
    <submitted_timestamp>2014-03-07T12:00:00Z</submitted_timestamp>
    <authorization></authorization>
  </header>
  <request>
    <request_name>urn:openhbx:requests:v1:employers#by_id</request_name>
  </request>
</employer_request>


text:
package com.winger.struct.deserialize;

public class JSONDeserializeSubObj
{
    public String str1;
    private String private1;

    public String getName()
    {
        return getClass().getName();
    }

    public String getPrivate1()
    {
        return private1;
    }

    public void setPrivate1(String private1)
    {
        this.private1 = private1;
    }

}


text:
from relative import relative
from baseline import baseline


text:
<?php

require_once dirname(__FILE__)."/../pfci18n.class.php";
require_once dirname(__FILE__)."/../pfcuserconfig.class.php";
require_once dirname(__FILE__)."/../pfcproxycommand.class.php";
require_once dirname(__FILE__)."/../../lib/utf8/utf8_strlen.php";

/**
 * pfcProxyCommand_noflood
 * this proxy will protect the chat from flooders
 * @author Stephane Gully <stephane.gully@gmail.com>
 * fixes noflood not detecting /notice, /invite and
 * kicking users when the type empy strings in chat.
 * Neumann Valle, aka UTAN, RE*S.T.A.R.S.*2 email at : vcomputadoras@yahoo.com
 */
class pfcProxyCommand_noflood extends pfcProxyCommand
{
  function run(&$xml_reponse, $p)
  {
    $clientid    = $p["clientid"];
    $param       = $p["param"];
    $sender      = $p["sender"];
    $recipient   = $p["recipient"];
    $recipientid = $p["recipientid"];

    $c =& pfcGlobalConfig::Instance();
    $u =& pfcUserConfig::Instance();
    /**
     * fixes some anoying issues with noflood not detecting user flooding the chat
     * those are notice and invite
     */
    $cmdtocheck = array("send", "nick", "me","notice","invite");

    // fixes the count of noflood even if the text posted was empty (Neumann Valle (UTAN))
    if ( in_array($this->name, $cmdtocheck) && $param != "")
    {
      $container =& pfcContainer::Instance();
      $nickid        = $u->nickid;
      $isadmin       = $container->getUserMeta($nickid, 'isadmin');
      $lastfloodtime = $container->getUserMeta($nickid, 'floodtime');
      $flood_nbmsg   = $container->getUserMeta($nickid, 'flood_nbmsg');
      $flood_nbchar  = $container->getUserMeta($nickid, 'flood_nbchar');
      $floodtime     = time();

      if ($floodtime - $lastfloodtime <= $c->proxies_cfg[$this->proxyname]["delay"])
      {
        // update the number of posted message indicator
        $flood_nbmsg++;
        // update the number of posted characteres indicator
        $flood_nbchar += utf8_strlen($param);
      }
      else
      {
        $flood_nbmsg = 0;
        $flood_nbchar = 0;
      }

      if (!$isadmin &&
          ($flood_nbmsg>$c->proxies_cfg[$this->proxyname]["msglimit"] ||
           $flood_nbchar>$c->proxies_cfg[$this->proxyname]["charlimit"])
          )
      {
        // warn the flooder
        $msg = _pfc("Please don't post so many message, flood is not tolerated");
        $xml_reponse->script("alert('".addslashes($msg)."');");

        // kick the flooder
        $cmdp = $p;
        $cmdp["param"] = null;
        $cmdp["params"][0] = "ch";
        $cmdp["params"][1] = $u->channels[$recipientid]["name"];
        $cmdp["params"][2] .=_pfc("kicked from %s by %s", $u->channels[$recipientid]["name"], "noflood");
        $cmd =& pfcCommand::Factory("leave");
        $cmd->run($xml_reponse, $cmdp);
        return false;
      }

      if ($flood_nbmsg == 0)
        $container->setUserMeta($nickid, 'floodtime', $floodtime);
      $container->setUserMeta($nickid,   'flood_nbmsg',  $flood_nbmsg);
      $container->setUserMeta($nickid,   'flood_nbchar', $flood_nbchar);
    }

    // forward the command to the next proxy or to the final command
    $p["clientid"]    = $clientid;
    $p["param"]       = $param;
    $p["sender"]      = $sender;
    $p["recipient"]   = $recipient;
    $p["recipientid"] = $recipientid;
    return $this->next->run($xml_reponse, $p);
  }
}
?>


text:
package skinny

/**
 * Skinny provides you Skinny-ORM as the default O/R mapper, which is built with ScalikeJDBC.
 */
package object orm {

  type Alias[A] = scalikejdbc.SyntaxProvider[A]

}