text:
function [spikeshapes] = read_spike2_spikeshapes(spike2filename, spikechannel, times, samples)
%  SPIKE2SPIKESHAPES - Return spike shapes from a Spike2 record exported to Matlab
%
%    [SPIKESHAPES]=READ_SPIKE2_SPIKESHAPES(SPIKE2FILENAME, SPIKECHANNEL,TIMES,SAMPLES)
%
%    Inputs: SPIKE2FILENAME - The spike2 filename
%            SPIKECHANNEL - The channel number for the spike data channel (e.g., 1)
%            TIMES - The spike times to be read, with 0 being onset time of spike2 recording
%            SAMPLES - The number of samples to return around each spike (before and after; the
%                      total samples returned will be 2*SAMPLES+1)
%
%    Outputs: SPIKESHAPES - An Nx2*SAMPLES+1 matrix of spike shapes; each row is a different spikeshape
%
%    Needed libraries: the SON library from Malcolm Kidierth

 % open the file, mimicking Kidierth's ImportSMR.m here

[pathname filename2 extension]=fileparts(spike2filename);
if strcmpi(extension,'.smr')==1
    % Spike2 for Windows source file so little-endian
    fid=fopen(spike2filename,'r','l');
elseif strcmpi(extension,'.son')==1
    % Spike2 for Mac file
    fid=fopen(spike2filename,'r','b');
else
    warning('%s is not a Spike2 file\n', filename);
    matfilename='';
    return
end

[dummy,header] = SONGetADCChannel(fid,spikechannel,1,1);

block_length = length(dummy);

sample_times = 1+round(times/(header.sampleinterval*1e-6));

start_samples = sample_times - samples;
end_samples = sample_times + samples;

block_starts = 1 + floor(start_samples/block_length);
start_sample_within_block = 1+mod(start_samples,block_length);
block_ends = 1 + floor(end_samples/block_length);
end_sample_within_block = start_sample_within_block + 2*samples;

spikeshapes = zeros(length(sample_times),2*samples+1);

currentblock_start = -Inf;
currentblock_end = -Inf;

for i=1:length(sample_times),
	if block_starts(i)~=currentblock_start | block_ends(i)~=currentblock_end,
		data = SONGetADCChannel(fid,spikechannel,block_starts(i),block_ends(i));
		currentblock_start = block_starts(i);
		currentblock_ends = block_ends(i);
	end;
	if length(data)<end_sample_within_block(i), % if we don't have enough data to fill out the spike
		num_samples_available = length(data) - start_sample_within_block(i) + 1;
		spikeshapes(i,1:num_samples_available) = data(start_sample_within_block(i):length(data));
		spikeshapes(i,num_samples_available+1:end) = NaN;
	else,
		spikeshapes(i,:) = data(start_sample_within_block(i):end_sample_within_block(i));
	end;
end;

fclose(fid);


text:
<?php

require_once "LicenseForm.php";
class LicenseInvalidForm extends LicenseForm
{
	public function fetchData()
	{
		$this->getAppRegister();
		return parent::fetchData();
	}

	public function outputAttrs()
	{
		$this->getAppModuleName();
		$result = parent::outputAttrs();
		$result['license_message'] = $this->getErrorMessage();
		return $result;
	}

}
?>

redpajama_set_name: RedPajamaGithub


text:
import HeadingComponent from './heading.component';

const module = angular
  .module('app.common.heading', [])
  .component('heading', HeadingComponent);

export default module.name;


text:
import pytest

import numpy as np

import cirq

class NoMethod:
    pass

class ReturnsNotImplemented:
    def _mixture_(self):
        return NotImplemented

    def _has_mixture_(self):
        return NotImplemented

class ReturnsValidTuple(cirq.SupportsMixture):
    def _mixture_(self):
        return ((0.4, 'a'), (0.6, 'b'))

    def _has_mixture_(self):
        return True

class ReturnsNonnormalizedTuple:
    def _mixture_(self):
        return ((0.4, 'a'), (0.4, 'b'))

class ReturnsNegativeProbability:
    def _mixture_(self):
        return ((0.4, 'a'), (-0.4, 'b'))

class ReturnsGreaterThanUnityProbability:
    def _mixture_(self):
        return ((1.2, 'a'), (0.4, 'b'))

class ReturnsMixtureButNoHasMixture:
    def _mixture_(self):
        return ((0.4, 'a'), (0.6, 'b'))

class ReturnsUnitary:
    def _unitary_(self):
        return np.ones((2, 2))

    def _has_unitary_(self):
        return True

class ReturnsNotImplementedUnitary:
    def _unitary_(self):
        return NotImplemented

    def _has_unitary_(self):
        return NotImplemented

@pytest.mark.parametrize(
    'val,mixture',
    (
        (ReturnsValidTuple(), ((0.4, 'a'), (0.6, 'b'))),
        (ReturnsNonnormalizedTuple(), ((0.4, 'a'), (0.4, 'b'))),
        (ReturnsUnitary(), ((1.0, np.ones((2, 2))),)),
    ),
)
def test_objects_with_mixture(val, mixture):
    expected_keys, expected_values = zip(*mixture)
    keys, values = zip(*cirq.mixture(val))
    np.testing.assert_almost_equal(keys, expected_keys)
    np.testing.assert_equal(values, expected_values)

    keys, values = zip(*cirq.mixture(val, ((0.3, 'a'), (0.7, 'b'))))
    np.testing.assert_almost_equal(keys, expected_keys)
    np.testing.assert_equal(values, expected_values)

@pytest.mark.parametrize(
    'val', (NoMethod(), ReturnsNotImplemented(), ReturnsNotImplementedUnitary())
)
def test_objects_with_no_mixture(val):
    with pytest.raises(TypeError, match="mixture"):
        _ = cirq.mixture(val)
    assert cirq.mixture(val, None) is None
    assert cirq.mixture(val, NotImplemented) is NotImplemented
    default = ((0.4, 'a'), (0.6, 'b'))
    assert cirq.mixture(val, default) == default

def test_has_mixture():
    assert cirq.has_mixture(ReturnsValidTuple())
    assert not cirq.has_mixture(ReturnsNotImplemented())
    assert cirq.has_mixture(ReturnsMixtureButNoHasMixture())
    assert cirq.has_mixture(ReturnsUnitary())
    assert not cirq.has_mixture(ReturnsNotImplementedUnitary())

def test_valid_mixture():
    cirq.validate_mixture(ReturnsValidTuple())

@pytest.mark.parametrize(
    'val,message',
    (
        (ReturnsNonnormalizedTuple(), '1.0'),
        (ReturnsNegativeProbability(), 'less than 0'),
        (ReturnsGreaterThanUnityProbability(), 'greater than 1'),
    ),
)
def test_invalid_mixture(val, message):
    with pytest.raises(ValueError, match=message):
        cirq.validate_mixture(val)

def test_missing_mixture():
    with pytest.raises(TypeError, match='_mixture_'):
        cirq.validate_mixture(NoMethod)


text:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import MyModal from './components/modal.vue'
import superagent from 'superagent'

require('es6-promise').polyfill()

Vue.use(VueRouter)
// define routes
const Home = resolve => require(['./components/home.vue'], resolve)
const About = resolve => require(['./components/about.vue'], resolve)
const Asyncdemo = resolve => require(['./components/asyncdemo.vue'], resolve)
const Signin = resolve => require(['./components/signin.vue'], resolve)
const Signup = resolve => require(['./components/signup.vue'], resolve)
const Pagenotfound = resolve => require(['./components/not-found.vue'], resolve)
const routes = [
  {path: '/', component: Home},
  {path: '/about', component: About},
  {path: '/asyncdemo', component: Asyncdemo},
  {path: '/signin', component: Signin},
  {path: '/signup', component: Signup},
  {path: '*', component: Pagenotfound}
]

const router = new VueRouter({
  routes: routes,
  mode: 'history',
  saveScrollPosition: true
})
Vue.component('MyModal', MyModal)
new Vue(Vue.util.extend({
  router,
  superagent
}, App)).$mount('#app')
window.router = router


text:
import os
from os.path import join

if not os.path.exists("data"):
    os.makedirs("data")

# for beta testing, remove *.blk, *.pyc, and *.db
for i in ["block.blk", "nodes.db", "nodes.lock"]:
    if os.path.exists(join('data', i)):
        os.remove(join('data', i))

import config  # config parameters
import socket
import random
import thread
import json
import time
import hashlib
import logging
try:
    import cPickle as pickle
except:
    import pickle

node_sleep_time = config.sleep_time
node_label = config.label

def merkle(hashList):
    ## <merkle hashing from Ken Shirriff>
    if len(hashList) == 1:
        return hashList[0]
    newHashList = []
    # Process pairs. For odd length, the last is skipped
    for i in range(0, len(hashList) - 1, 2):
        newHashList.append(hash2(hashList[i], hashList[i + 1]))
    if len(hashList) % 2 == 1:  # odd, hash last item twice
        newHashList.append(hash2(hashList[-1], hashList[-1]))
    return merkle(newHashList)

def hash2(a, b):
    ## <merkle hashing from Ken Shirriff>
    # Reverse inputs before and after hashing
    # due to big-endian / little-endian nonsense
    a1 = a.decode('hex')[::-1]
    b1 = b.decode('hex')[::-1]
    h = hashlib.sha256(hashlib.sha256(a1 + b1).digest()).digest()
    return h[::-1].encode('hex')

'''
def count_nodes(obj, data):
    co = config.nodes.find("nodes", "all")
    if not co:
        co = 0
    else:
        co = len(co)
    obj.send(json.dumps({"nodes": co}))

def get_nodes(obj, data):
    with open(join('data', "nodes.db"), 'rb') as file:
        while True:
            data = file.read(100)
            if not data:
                break
            obj.send(data)
'''

def register(obj, data):
    ''' TODO: update to latest node characteristics '''
    while os.path.exists(join('data', "nodes.lock")):
        time.sleep(0.1)
    open(join('data', "nodes.lock"), 'w').close()
    allnodes = config.nodes.find("nodes", "all")
    tmp = set()
    if allnodes:
        for i in allnodes:
            tmp.add(i['ip'] + ":" + str(i['port']))
    if data['ip'] + ":" + str(data['port']) not in tmp:
        config.nodes.insert("nodes", data)
        config.nodes.save()
    else:
        stuff = config.nodes.find(
            "nodes",
            {"port": data['port'], "ip": data['ip']})
        if stuff:
            for x in stuff:
                config.nodes.remove("nodes", x)
                config.nodes.save()
            config.nodes.insert("nodes", data)
            config.nodes.save()
    os.remove(join('data', "nodes.lock"))

def send_command(cmd, out=False, god=False):
    if god:
        nodes = config.seeds
    else:
        nodes = config.nodes.find("nodes", {"relay": 1})
        if nodes:
            random.shuffle(nodes)
            #print "randomized:",
            #print map(lambda x: x["ip"] + ":" + str(x["port"]), nodes)
    if not nodes:
        nodes = config.seeds
    for x in nodes:
        s = socket.socket()
        try:
            s.connect((x['ip'], x['port']))
        except:
            s.close()
            continue
        else:
            s.send(json.dumps(cmd))
            out = ""
            while True:
                data = s.recv(1024)
                if not data:
                    break
                out = out + data
            s.close()
            if out:
                return out

def sha256_for_file(path, block_size=256 * 128):
    cipher = hashlib.sha256()
    with open(path, 'rb') as f:
        for chunk in iter(lambda: f.read(block_size), b''):
            cipher.update(chunk)
    return cipher.hexdigest()

class Node:
    def __init__(self):
        self.data_dict = dict()
        self.label_dict = dict()
        self.cmds = {
            #"get_nodes": get_nodes,
            "register": register,
            #"get_nodes_count": count_nodes,
            "sync": self.syncfile,
        }
        self.block = dict()
        self.merkle_hash = ""
        self.allnodes = ""
        self.node_ip = config.host
        self.node_port = config.port

    def generate_merkle(self):
        self.merkle_hash = merkle(sorted(self.data_dict.keys()))

    def send_register(self):
        send_command({
            "cmd": "register",
            "relay": config.relay,
            "public": "hello from %s node" % node_label,
            "port": config.port,
            "ip": config.host,
            "node_label": node_label,
            "merkle_hash": self.merkle_hash,
            "block_size": len(
                self.block["data_dict"]) if "data_dict" in self.block else 0,
        })

    def parsePNG(self, pngfile):
        if pngfile[-3:] != "png":
            return 0
        with open(pngfile, "rb") as f:
            ib64 = f.read()
            return ib64.encode("base64").strip()

    def syncfile(self, obj, data):
        ## randomly send out one element in data_dict
        if self.data_dict.keys():
            r = random.choice(self.data_dict.keys())
            obj.send(json.dumps(dict(
                cmd="sync", note="syncing from %s" % node_label, hash=r,
                data=self.data_dict[r]["data"],
                label=self.data_dict[r]["label"],
                labeldict=self.label_dict,
                ts=self.data_dict[r]["ts"])))
        else:
            ## no return hash
            obj.send(json.dumps(dict(
                cmd="sync", note="syncing from %s" % node_label,
                ts=time.time())))

    def updateNodes(self):
        self.block_size = len(
            self.block["data_dict"]) if "data_dict" in self.block else 0
        check = config.nodes.find("nodes", "all")
        self.allnodes = check
        if not check:
            ip = config.host
            config.nodes.insert("nodes", {
                "ip": ip,
                "relay": config.relay,
                "port": config.port,
                "merkle_hash": self.merkle_hash,
                "block_size": self.block_size,
                "node_label": node_label,
            })
            config.nodes.save()
        self.send_register()

    def relay(self):
        self.send_register()
        sock = socket.socket()
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((config.host, config.port))
        sock.listen(5)
        while True:
            obj, conn = sock.accept()
            thread.start_new_thread(self.handle, (obj, conn[0]))

    def handle(self, obj, ip):
        data = obj.recv(10240)
        if data:
            try:
                data = json.loads(data)
            except:
                obj.close()
                return
            else:
                if "cmd" in data:
                    if data['cmd'] in self.cmds:
                        data['ip'] = ip
                        self.cmds[data['cmd']](obj, data)
                        obj.close()

    def normal(self):
        counter = 0
        if not config.relay:
            logging.debug("send register")
            self.send_register()
        while True:
            ## sending sync command to peers and load responses
            try:
                sync_data = json.loads(send_command({"cmd": "sync"}))
            except:
                logging.error("error in receiving")
                sync_data = dict()

            # check if received message is valid (contain a hash)
            if "hash" in sync_data:

                # load sync-ed meta labels
                if "labeldict" in sync_data:
                    if os.path.exists(join('data', 'labels.bin')):
                        with open(join('data', 'labels.bin'), 'rb') as input:
                            self.label_dict.update(pickle.load(input))
                    self.label_dict.update(sync_data["labeldict"])
                    with open(join('data', 'labels.bin'), 'wb') as output:
                        pickle.dump(
                            self.label_dict, output, pickle.HIGHEST_PROTOCOL)

                # load block
                if os.path.exists(join('data', "block.blk")):
                    with open(join('data', 'block.blk'), 'rb') as f:
                        self.block = pickle.load(f)
                        self.data_dict.update(self.block["data_dict"])
                else:
                    # create a blank block
                    with open(join('data', 'block.blk'), 'wb') as f:
                        pickle.dump(self.block, f)
                        logging.debug("empty block created")

                # update block and dict
                if "data_dict" not in self.block:
                    self.block["data_dict"] = dict()

                # check duplicated hash (can do more stuff here)
                if sync_data["hash"] not in self.block["data_dict"]:

                    # add new hash to block
                    self.block["data_dict"][sync_data["hash"]] = sync_data

                    # calculate merkle hash
                    if any(self.data_dict.keys()):
                        self.merkle_hash = merkle(
                            sorted(self.data_dict.keys()))

                    # save it
                    with open(join('data', 'block.blk'), 'wb') as f:
                        pickle.dump(self.block, f)
                        logging.info(
                            "block %d %s",
                            len(self.block["data_dict"]), self.merkle_hash)
            # sleep
            logging.info("sleep for %d sec", node_sleep_time)
            time.sleep(node_sleep_time)
            if counter % 5 == 0:
                self.updateNodes()
            counter += 1

if __name__ == "__main__":

    logging.basicConfig(
        format='[%(asctime)s] %(name)s %(levelname)s %(message)s',
        level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    pn = Node()
    if config.relay:
        logging.info("started as a relay node.")
        thread.start_new_thread(pn.normal, ())
        pn.relay()
    else:
        logging.info("started as a leaf node.")
        pn.normal()


text:
package coordinator

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"

	log "github.com/Sirupsen/logrus"
	"github.com/mistifyio/mistify/acomm"
	"github.com/tylerb/graceful"
)

// Server is the coordinator server. It handles accepting internal and external
// requests and proxying them to appropriate providers.
type Server struct {
	config   *Config
	proxy    *acomm.Tracker
	internal *acomm.UnixListener
	external *graceful.Server
}

// NewServer creates and initializes a new instance of Server.
func NewServer(config *Config) (*Server, error) {
	if err := config.Validate(); err != nil {
		return nil, err
	}

	var err error
	s := &Server{
		config: config,
	}

	// Internal socket for requests from providers
	internalSocket := filepath.Join(
		config.SocketDir(),
		"coordinator",
		config.ServiceName()+".sock")
	s.internal = acomm.NewUnixListener(internalSocket, 0)

	// External server for requests from outside
	mux := http.NewServeMux()
	mux.HandleFunc("/stream", acomm.ProxyStreamHandler)
	mux.HandleFunc("/", s.externalHandler)
	s.external = &graceful.Server{
		Server: &http.Server{
			Addr:    fmt.Sprintf(":%d", config.ExternalPort()),
			Handler: mux,
		},
		NoSignalHandling: true,
	}

	// Response socket for proxied requests
	responseSocket := filepath.Join(
		config.SocketDir(),
		"response",
		config.ServiceName()+".sock")

	streamURL, err := url.ParseRequestURI(
		fmt.Sprintf("http://%s:%d/stream", getLocalIP(), config.ExternalPort()))
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("failed to generate stream url")
	}
	s.proxy, err = acomm.NewTracker(responseSocket, streamURL, config.RequestTimeout())
	if err != nil {
		return nil, err
	}
	log.WithFields(log.Fields{
		"response": responseSocket,
		"stream":   streamURL.String(),
		"internal": internalSocket,
		"external": fmt.Sprintf(":%d", config.ExternalPort()),
	}).Info("server addresses")

	return s, nil
}

// externalHandler is the http handler for external requests.
func (s *Server) externalHandler(w http.ResponseWriter, r *http.Request) {
	var respErr error
	req := &acomm.Request{}

	// Send the immediate response
	defer func() {
		resp, err := acomm.NewResponse(req, nil, nil, respErr)
		respJSON, err := json.Marshal(resp)
		if err != nil {
			log.WithFields(log.Fields{
				"error":    err,
				"req":      req,
				"response": resp,
			}).Error("failed to marshal initial response")
		}

		if _, err := w.Write(respJSON); err != nil {
			log.WithFields(log.Fields{
				"error":    err,
				"req":      req,
				"response": resp,
			}).Error("failed to send initial response")
		}
	}()

	// Parse the request
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		respErr = err
		return
	}

	if err := json.Unmarshal(body, req); err != nil {
		respErr = err
		return
	}

	respErr = s.handleRequest(req)
}

func (s *Server) internalHandler() {
	for {
		conn := s.internal.NextConn()
		if conn == nil {
			return
		}
		go s.acceptInternalRequest(conn)
	}
}

func (s *Server) acceptInternalRequest(conn net.Conn) {
	defer s.internal.DoneConn(conn)
	var respErr error
	req := &acomm.Request{}
	defer func() {
		// Respond to the initial request
		resp, err := acomm.NewResponse(req, nil, nil, respErr)
		if err != nil {
			log.WithFields(log.Fields{
				"error":   err,
				"req":     req,
				"respErr": respErr,
			}).Error("failed to create initial response")
			return
		}

		if err := acomm.SendConnData(conn, resp); err != nil {
			log.WithFields(log.Fields{
				"error":   err,
				"req":     req,
				"respErr": respErr,
			}).Error("failed to create initial response")
			return
		}
	}()

	if err := acomm.UnmarshalConnData(conn, req); err != nil {
		respErr = err
		return
	}

	if err := req.Validate(); err != nil {
		respErr = err
		return
	}

	if err := s.handleRequest(req); err != nil {
		respErr = err
		return
	}

	return
}

// handleRequest handles proxying and forwarding a request to a provider for
// the specified task.
func (s *Server) handleRequest(req *acomm.Request) error {
	providerSockets, err := s.getProviders(req.Task)
	if err != nil {
		return err
	}

	if len(providerSockets) == 0 {
		return errors.New("no providers available for task")
	}

	proxyReq, err := s.proxy.ProxyUnix(req, 0)
	if err != nil {
		return err
	}

	// Cycle through available providers until one accepts the request
	for _, providerSocket := range providerSockets {
		addr, _ := url.ParseRequestURI(fmt.Sprintf("unix://%s", providerSocket))
		err = acomm.Send(addr, proxyReq)
		if err == nil {
			// Successfully sent
			break
		}
	}

	return err
}

// getProviders returns a list of providers registered for a given task.
func (s *Server) getProviders(task string) ([]string, error) {
	// Find Task Providers
	if task == "" {
		return nil, errors.New("request missing task")
	}

	taskSocketDir := filepath.Join(s.config.SocketDir(), task)
	files, err := ioutil.ReadDir(taskSocketDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		log.WithFields(log.Fields{
			"error": err,
			"req":   task,
			"dir":   taskSocketDir,
		}).Warn("failed to read task dir")
		return nil, err
	}

	// Filter out any non-socket files
	providerSockets := make([]string, 0, len(files))
	for _, fi := range files {
		if fi.Mode()&os.ModeSocket == os.ModeSocket {
			providerSockets = append(providerSockets, filepath.Join(taskSocketDir, fi.Name()))
		}
	}

	return providerSockets, nil
}

// externalListenAndServe runs and blocks on the external http server.
func (s *Server) externalListenAndServe() {
	if err := s.external.ListenAndServe(); err != nil {
		// Ignore the error from closing the listener, which is involved in the
		// graceful shutdown
		if !strings.Contains(err.Error(), "use of closed network connection") {
			log.WithField("error", err).Error("server error")

			// Stop the coordinator if this was unexpected
			s.Stop()
		}
	}
}

// Start starts the server, running all of the listeners and proxy tracker.
func (s *Server) Start() error {
	// Start up the proxy tracker
	if err := s.proxy.Start(); err != nil {
		return err
	}

	// Start up the internal request handler
	if err := s.internal.Start(); err != nil {
		return err
	}
	go s.internalHandler()

	// Start up the external request handler
	go s.externalListenAndServe()
	return nil
}

// Stop stops the server, gracefully stopping all of the listeners and proxy
// tracker.
func (s *Server) Stop() {
	// Stop accepting new external requests
	stopChan := s.external.StopChan()
	s.external.Stop(0)
	<-stopChan

	// Stop accepting new internal requests
	s.internal.Stop(0)

	// Stop the proxy tracker
	s.proxy.Stop()
}

// StopOnSignal will wait until one of the specified signals is received and
// then stop the server. If no signals are specified, it will use a default
// set.
func (s *Server) StopOnSignal(signals ...os.Signal) {
	if len(signals) == 0 {
		signals = []os.Signal{os.Interrupt, os.Kill, syscall.SIGTERM}
	}

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, signals...)
	sig := <-sigChan
	log.WithFields(log.Fields{
		"signal": sig,
	}).Info("signal received, stopping")

	s.Stop()
}

func getLocalIP() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("failed to list interface addrs")
		return ""
	}

	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}
		}
	}

	return ""
}


text:
function L = noiseExpectationLogLikelihood(noise, mu, varsigma, y);

% NOISEEXPECTATIONLOGLIKELIHOOD Return the expectation of the log likelihood.
% FORMAT
% DESC returns the expectation of the log likelihood for a gven noise model.
% ARG noise : the noise structure for which the expectation of the log
% likelihood is required.
% ARG mu : input mean locations for the likelihood.
% ARG varSigma : input variance locations for the likelihood.
% ARG y : target locations for the likelihood.
%
% SEEALSO : noiseParamInit, noiseLogLikelihood
%
% COPYRIGHT : Neil D. Lawrence, 2007

% NOISE

fhandle = str2func([noise.type 'NoiseExpectationLogLikelihood']);
L = fhandle(noise, mu, varsigma, y);


text:
//
//  snake.hpp
//  snake-genetic-algorithm
//
//  Created by David Reis on 12/02/2017.
//  Copyright © 2017 David Reis. All rights reserved.
//

#ifndef snake_hpp
#define snake_hpp

#include <stdio.h>
#include <deque>
#include <random>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

typedef struct pos{
    int x;
    int y;
}POS;

typedef enum direction {LEFT,RIGHT,UP,DOWN,NONE} DIRECTION;

typedef enum blockType {EMPTY,SNAKEBODY,SNAKEHEAD,WALL,FRUIT} BLOCK_TYPE;

class SnakeGame{
private:

    BLOCK_TYPE gameBoard[20][20];
    int currentFitness;
    POS currentFruit;
    int tickCount;
    int totalTickCount;
public:
    deque<POS> snake;
    int getFitness(){ return (currentFitness*currentFitness)/totalTickCount;}
    SnakeGame();
    void drawGame();
    bool nextTick(DIRECTION nextMove);
    void allocateFruit();
    bool isGameWon();
    POS getCurrentFruitRelativeToHead();
    BLOCK_TYPE getBlockNextToHead(DIRECTION dir);
    DIRECTION getCurrentDirection();
    void resetGame();
};

#endif /* snake_hpp */


text:
using Content.Shared.Research.Prototypes;
using Robust.Client.AutoGenerated;
using Robust.Client.GameObjects;
using Robust.Client.Graphics;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.UserInterface.XAML;

namespace Content.Client.Lathe.UI
{
    [GenerateTypedNameReferences]
    public sealed partial class LatheQueueMenu : DefaultWindow
    {
        [Dependency] private readonly IEntityManager _entityManager = default!;
        private readonly SpriteSystem _spriteSystem;

        public LatheQueueMenu(LatheBoundUserInterface owner)
        {
            RobustXamlLoader.Load(this);
            IoCManager.InjectDependencies(this);
            _spriteSystem = _entityManager.EntitySysManager.GetEntitySystem<SpriteSystem>();

            SetInfo(null);
        }

        public void SetInfo(LatheRecipePrototype? recipe)
        {
            if (recipe != null)
            {
                Icon.Texture = _spriteSystem.Frame0(recipe.Icon);
                NameLabel.Text = recipe.Name;
                Description.Text = recipe.Description;
            }
            else
            {
                Icon.Texture = Texture.Transparent;
                NameLabel.Text = string.Empty;
                Description.Text = Loc.GetString("lathe-queue-menu-not-producing-text");
            }
        }

        public void PopulateList(List<LatheRecipePrototype> queue)
        {
            QueueList.Clear();
            var idx = 1;
            foreach (var recipe in queue)
            {
                QueueList.AddItem($"{idx}. {recipe.Name}", _spriteSystem.Frame0(recipe.Icon));
                idx++;
            }
        }
    }
}


text:
.class public Lcom/sec/ims/IMSAPCSInfo;
.super Ljava/lang/Object;
.source "IMSAPCSInfo.java"

# interfaces
.implements Landroid/os/Parcelable;
.implements Ljava/lang/Cloneable;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/sec/ims/IMSAPCSInfo$1;
    }
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Lcom/sec/ims/IMSAPCSInfo;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private mServiceStatus:Z

# direct methods
.method static constructor <clinit>()V
    .locals 1

    new-instance v0, Lcom/sec/ims/IMSAPCSInfo$1;

    invoke-direct {v0}, Lcom/sec/ims/IMSAPCSInfo$1;-><init>()V

    sput-object v0, Lcom/sec/ims/IMSAPCSInfo;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method public constructor <init>(Landroid/os/Parcel;)V
    .locals 3

    const/4 v0, 0x1

    const/4 v1, 0x0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-boolean v1, p0, Lcom/sec/ims/IMSAPCSInfo;->mServiceStatus:Z

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v2

    if-ne v2, v0, :cond_0

    :goto_0
    iput-boolean v0, p0, Lcom/sec/ims/IMSAPCSInfo;->mServiceStatus:Z

    return-void

    :cond_0
    move v0, v1

    goto :goto_0
.end method

# virtual methods
.method public clone()Lcom/sec/ims/IMSAPCSInfo;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/CloneNotSupportedException;
        }
    .end annotation

    invoke-super {p0}, Ljava/lang/Object;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/sec/ims/IMSAPCSInfo;

    return-object v0
.end method

.method public bridge synthetic clone()Ljava/lang/Object;
    .locals 1
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/CloneNotSupportedException;
        }
    .end annotation

    invoke-virtual {p0}, Lcom/sec/ims/IMSAPCSInfo;->clone()Lcom/sec/ims/IMSAPCSInfo;

    move-result-object v0

    return-object v0
.end method

.method public describeContents()I
    .locals 1

    const/4 v0, 0x0

    return v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1

    iget-boolean v0, p0, Lcom/sec/ims/IMSAPCSInfo;->mServiceStatus:Z

    if-eqz v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    return-void

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
package maru.ui.wizards;

import maru.core.model.ICentralBody;

import org.eclipse.jface.wizard.IWizardPage;
import org.orekit.errors.OrekitException;

public interface ICentralBodyWizardPage extends IWizardPage
{
    ICentralBody createCentralBody() throws OrekitException;
}


text:
import React from "react";
import { View, Text, Image, StyleSheet } from "react-primitives";
import { createContainer, query } from "@phenomic/preset-react-app/lib/client";

import Flex from "../Flex";
import Link from "../Link";
import Spacer from "../Spacer";
import ActivityIndicator from "../ActivityIndicator";
import Header from "../Header";
import Footer from "../Footer";
import BodyContainer from "../BodyContainer";
import urlToSlug from "../../modules/url-to-slug";
import { screenshotsSize } from "../../package.json";

const prepareList = list => {
  let phenomicDocs;
  const newList = list
    .filter(site => site.showcaseTags)
    .sort((a, b) => {
      if (a.curated && !b.curated) {
        return -1;
      }

      // more tags first
      if (a.showcaseTags.length < b.showcaseTags.length) {
        return 1;
      }
      if (a.showcaseTags.length > b.showcaseTags.length) {
        return -1;
      }

      // blog last
      if (
        a.showcaseTags.indexOf("blog") === -1 &&
        b.showcaseTags.indexOf("blog") > -1
      ) {
        return -1;
      }

      return 0;
    })
    .filter(item => {
      if (item.title !== "Phenomic docs") {
        return true;
      }
      phenomicDocs = item;
      return false;
    });
  if (phenomicDocs) newList.push(phenomicDocs);
  return newList;
};

const ShowcaseList = (props: Object) => (
  <Flex>
    <Header headTitle={"Phenomic Showcase "} title={"Who's using Phenomic?"} />
    <BodyContainer style={styles.page}>
      {props.isLoading && <ActivityIndicator />}
      {!props.isLoading &&
        <View>
          <Link to={"/showcase/submit/"} style={styles.addYourOwn}>
            {"Submit your website!"}
          </Link>
          {props.params &&
            props.params.tag &&
            <View style={styles.currentFilter}>
              <Text style={styles.filterMessage}>
                {"You are currently viewing projects that match "}
                <em>{props.params.tag}</em>
                {" tag. "}
                <Link to={"/showcase/"} style={styles.filterMessageLink}>
                  {"View all."}
                </Link>
              </Text>
            </View>}
          <View style={styles.list}>
            {prepareList(props.showcase.node.list).map(item => (
              <View style={styles.item} key={item.id}>
                <View style={styles.row}>
                  <Text style={styles.itemName}>{item.title}</Text>
                  <Text>{" "}</Text>
                  {item.source &&
                    <Link style={styles.itemLinkSource} to={item.source}>
                      {"(Source)"}
                    </Link>}
                </View>
                <View style={styles.tags}>
                  {item.showcaseTags &&
                    item.showcaseTags.map(tag => (
                      <Link
                        key={tag}
                        to={`/showcase/tag/${tag}/`}
                        style={styles.itemTag}
                      >
                        {tag}
                      </Link>
                    ))}
                </View>
                <Link href={item.url}>
                  <View style={styles.imageContainerLarge}>
                    <Image
                      source={{
                        uri: `/showcase/entry/${urlToSlug(item.url)}-large.jpg`
                      }}
                      style={styles.imageLarge}
                      resizeMode="cover"
                    />
                  </View>
                  <View style={styles.imageContainerSmall}>
                    <Image
                      source={{
                        uri: `/showcase/entry/${urlToSlug(item.url)}-small.jpg`
                      }}
                      style={styles.imageSmall}
                      resizeMode="cover"
                    />
                  </View>
                </Link>
              </View>
            ))}
          </View>
          {/*
          <View style={styles.paginationRow}>
            <View style={styles.paginationColumn}>
              {props.showcase.node &&
                props.showcase.node.hasPreviousPage &&
                <Link
                  to={
                    props.showcase.node.previousPageIsFirst
                      ? `/showcase`
                      : `/showcase/after/${props.showcase.node.previous}`
                  }
                >
                  {"Previous"}
                </Link>}
            </View>
            <View style={styles.paginationColumn}>
              {props.showcase.node &&
                props.showcase.node.hasNextPage &&
                <Link to={`/showcase/after/${props.showcase.node.next}`}>
                  {"Next"}
                </Link>}
            </View>
          </View>
          */}
        </View>}
    </BodyContainer>
    <Spacer large />
    <Footer />
  </Flex>
);

const styles = StyleSheet.create({
  row: {
    flexDirection: "row",
    alignItems: "center"
  },
  page: {
    paddingTop: 10,
    paddingBottom: 10
  },
  addYourOwn: {
    position: "absolute",
    right: 20,
    top: -30,
    fontSize: 14,
    color: "#fff",
    opacity: 0.6
  },
  currentFilter: {
    padding: 10,
    flexDirection: "row",
    justifyContent: "center"
  },
  filterMessage: {
    padding: 10,
    color: "#4078c0",
    backgroundColor: "#e6f1f6",
    borderRadius: 3
  },
  filterMessageLink: {
    color: "#4078c0",
    fontWeight: "bold"
  },
  list: {
    flexDirection: "row",
    flexWrap: "wrap"
  },
  item: {
    position: "relative",
    width: "50%",
    padding: 20
  },
  imageContainerLarge: {},
  imageLarge: {
    flex: 1,
    paddingBottom: 100 *
      screenshotsSize.large.height /
      screenshotsSize.large.width +
      "%",
    borderWidth: 1,
    borderColor: "rgba(0,0,0,.1)",
    borderRadius: 4
  },
  imageContainerSmall: {
    position: "absolute",
    right: 0,
    bottom: 0,
    width: "20%"
  },
  imageSmall: {
    flex: 1,
    width: "100%",
    paddingBottom: 100 *
      screenshotsSize.small.height /
      screenshotsSize.small.width +
      "%",
    borderWidth: 1,
    borderColor: "rgba(0,0,0,.1)",
    borderRadius: 4
  },
  itemName: {
    fontWeight: "700",
    fontSize: 18,
    lineHeight: 18 * 2,
    color: "#424345"
  },
  itemLinkSource: {
    fontSize: 12,
    textDecorationLine: "none",
    color: "#006df4",
    opacity: 0.4
  },
  tags: {
    flexDirection: "row",
    justifyContent: "flex-end",
    marginRight: -10
  },
  itemTag: {
    fontSize: 12,
    lineHeight: 24,
    margin: 10,
    paddingLeft: 6,
    paddingRight: 6,
    color: "#08b09b",
    backgroundColor: "#fff",
    borderRadius: 3
  }
  /*
  paginationRow: {
    flexDirection: "row"
  },
  paginationColumn: {
    width: "50%",
    padding: 10,
    alignItems: "center",
    justifyContent: "center"
  }
  */
});

export default createContainer(ShowcaseList, props => ({
  showcase: query({
    collection: "showcase",
    // by: "showcaseTags",
    ...(props.params.tag
      ? {
          by: "showcaseTags",
          value: props.params.tag
        }
      : {})
    // order: "asc",
    // limit: 10,
    // after: props.params.after
  })
}));


text:
namespace SpecificationPattern.Specifications.Base
{
    using System;

    public class NotSpecification<TEntity> : ISpecification<TEntity>
    {
        private readonly ISpecification<TEntity> specification;

        public NotSpecification(ISpecification<TEntity> specification)
        {
            if (specification == null)
            {
                throw new ArgumentNullException("specification");
            }

            this.specification = specification;
        }

        public bool IsSatisfiedBy(TEntity candidate)
        {
            return !this.specification.IsSatisfiedBy(candidate);
        }
    }
}


text:
import collada
from unittest import TestCase

class ColladaTests(TestCase):

    def test_should_find_commented_objects_in_mesh(self):
        #file = open('./test_resources/3wall.dae')
        file = open('./test_resources/blue_house.dae')
        collada_data = collada.Collada(file)

        for item in collada_data.scene.nodes:
            for child in item.children:
                self.assertEqual('ID2', child.id)

class DjangoColladaTests(TestCase):

    def test_should_create_django_collada_instance(self):
        pass


text:
package com.novartis.pcs.ontology.webapp.client.view;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.InlineHyperlink;
import com.google.gwt.user.client.ui.impl.HyperlinkImpl;

public class HyperlinkCell extends AbstractCell<InlineHyperlink> {
	private static final HyperlinkImpl impl = GWT.create(HyperlinkImpl.class);

	public HyperlinkCell() {
		super("click");
	}

	@Override
	public void render(Context context, InlineHyperlink h, SafeHtmlBuilder sb) {
		if(h != null) {
			sb.append(SafeHtmlUtils.fromTrustedString(h.toString()));
		}
	}

	@Override
	@SuppressWarnings("deprecation")
	public void onBrowserEvent(Context context,
			Element parent, InlineHyperlink value, NativeEvent nativeEvent,
			ValueUpdater<InlineHyperlink> valueUpdater) {
		super.onBrowserEvent(context, parent, value, nativeEvent, valueUpdater);
		Event event = Event.as(nativeEvent);
		if(DOM.eventGetType(event) == Event.ONCLICK && impl.handleAsClick(event)) {
			Element target = Element.as(event.getEventTarget());
			Element child = parent.getFirstChildElement();
			if(child.isOrHasChild(target)) {
				History.newItem(value.getTargetHistoryToken());
				DOM.eventPreventDefault(event);
			}
		}
	}
}


text:
/*
 * bpblastparser.h
 *
 *  Created on: 16-feb-2012
 *      Author: M. El-Kebir
 */

#ifndef BPBLASTPARSER_H_
#define BPBLASTPARSER_H_

#include "input/bpparser.h"
#include "verbose.h"

namespace nina {
namespace gna {

template<typename GR, typename BGR>
class BpBlastParser : public BpParser<GR, BGR>
{
public:
  /// Graph type
  typedef GR Graph;
  /// Bipartite graph type
  typedef BGR BpGraph;
  /// Base class type
  typedef BpParser<GR, BGR> Parent;

private:
  TEMPLATE_GRAPH_TYPEDEFS(Graph);

  typedef typename Parent::BpNode BpNode;
  typedef typename Parent::BpEdge BpEdge;
  typedef typename Parent::BpNodeIt BpNodeIt;
  typedef typename Parent::BpEdgeIt BpEdgeIt;
  typedef typename Parent::BpIncEdgeIt BpIncEdgeIt;
  typedef typename Parent::BpRedNode BpRedNode;
  typedef typename Parent::BpBlueNode BpBlueNode;
  typedef typename Parent::BpRedNodeIt BpRedNodeIt;
  typedef typename Parent::BpBlueNodeIt BpBlueNodeIt;

public:
  typedef typename Parent::BpWeightEdgeMap BpWeightEdgeMap;
  typedef typename Parent::ParserType ParserType;
  typedef typename Parent::OrigNodeToMatchNodeMap OrigNodeToMatchNodeMap;
  typedef typename Parent::MatchNodeToOrigNodeMap MatchNodeToOrigNodeMap;

  using Parent::_filename;
  using Parent::_pGm;
  using Parent::_pWeightEdgeMap;
  using Parent::_pWeightAltEdgeMap;
  using Parent::_pG1ToGm;
  using Parent::_pG2ToGm;
  using Parent::_pGmToG12;
  using Parent::_nNodesRed;
  using Parent::_nNodesBlue;
  using Parent::_nEdges;
  using Parent::_pParserG1;
  using Parent::_pParserG2;
  using Parent::constructGm;

private:
  double _eValCutOff;

public:
  BpBlastParser(const std::string& filename,
                const ParserType* pParserG1,
                const ParserType* pParserG2,
                double eValCutOff);
  bool parse();

  double getEValCutOff() const
  {
    return _eValCutOff;
  }
};

template<typename GR, typename BGR>
inline BpBlastParser<GR, BGR>::BpBlastParser(const std::string& filename,
                                             const ParserType* pParserG1,
                                             const ParserType* pParserG2,
                                             double eValCutOff)
  : Parent(filename, pParserG1, pParserG2)
  , _eValCutOff(eValCutOff)
{
}

template<typename GR, typename BGR>
inline bool BpBlastParser<GR, BGR>::parse()
{
  if (!_pGm)
    return false;

  _pGm->clear();
  if (_filename.empty())
  {
    constructGm(true);
    return true;
  }
  else
  {
    constructGm(false);

    lemon::DynArcLookUp<BpGraph> arcLookUp(*_pGm);

    std::ifstream inFile(_filename.c_str());
    if (!inFile.good())
    {
      std::cerr << "Could not open file " << _filename
                << " for reading" << std::endl;
      return false;
    }

    const typename ParserType::InvIdNodeMap* pInvLabelG1 =
            _pParserG1->getInvIdNodeMap();
    const typename ParserType::InvIdNodeMap* pInvLabelG2 =
            _pParserG2->getInvIdNodeMap();

    std::string line;
    while (std::getline(inFile, line))
    {
      if (line[0] == 0)
        continue; // skip comments

      // queryId, subjectId, percIdentity, alnLength,
      // mismatchCount, gapOpenCount, queryStart, queryEnd,
      // subjectStart, subjectEnd, eVal, bitScore
      double percIdentity, alnLength, mismatchCount,
        gapOpenCount, queryStart, queryEnd,
        subjectStart, subjectEnd, eVal, bitScore;

      std::stringstream lineStream(line);

      std::string label_g1, label_g2;
      lineStream >> label_g1 >> label_g2
        >> percIdentity >> alnLength >> mismatchCount
        >> gapOpenCount >> queryStart >> queryEnd
        >> subjectStart >> subjectEnd >> eVal >> bitScore;

      typename ParserType::InvIdNodeMap::const_iterator invIt1 = pInvLabelG1->find(label_g1);
      typename ParserType::InvIdNodeMap::const_iterator invIt2 = pInvLabelG2->find(label_g2);
      if (invIt1 != pInvLabelG1->end() &&
          invIt2 != pInvLabelG2->end() &&
          eVal <= _eValCutOff)
      {
        const Node node1 = invIt1->second;
        const BpRedNode r = _pGm->asRedNode((*_pG1ToGm)[node1]);
        const Node node2 = invIt2->second;
        const BpBlueNode b = _pGm->asBlueNode((*_pG2ToGm)[node2]);

        BpEdge e = arcLookUp(r, b);
        if (e == lemon::INVALID)
        {
          e = _pGm->addEdge(r, b);
          if (_pWeightEdgeMap)
          {
            _pWeightEdgeMap->set(e, bitScore);
          }
          if (_pWeightAltEdgeMap)
          {
            _pWeightAltEdgeMap->set(e, eVal);
          }
          _nEdges++;
        }
        else
        {
          if (_pWeightEdgeMap)
          {
            (*_pWeightEdgeMap)[e] = std::max((*_pWeightEdgeMap)[e], bitScore);
          }
          if (_pWeightAltEdgeMap)
          {
            (*_pWeightAltEdgeMap)[e] = std::min((*_pWeightAltEdgeMap)[e], eVal);
          }
        }
      }
    }
  }

  return true;
}

} // namespace gna
} // namespace nina

#endif // BPBLASTPARSER_H_


text:
package org.jhove2.module.format.wave;

import java.io.EOFException;
import java.io.IOException;
import org.jhove2.annotation.ReportableProperty;
import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.core.io.Input;
import org.jhove2.core.source.Source;
import org.jhove2.module.format.riff.GenericChunk;

import com.sleepycat.persist.model.Persistent;

/** WAVE format text with data length chunk.
 *
 * @author slabrams
 */
@Persistent
public class TextWithDataLengthChunk
    extends GenericChunk
{
    /** Code page. */
    protected int codePage;

    /** Country code in raw form. */
    protected int countryCode;

    /** Dialect code in raw form. */
    protected int dialectCode;

    /** Language code in raw form. */
    protected int languageCode;

    /** Name. */
    protected String name;

    /** Number of samples. */
    protected long numSamples;

    /** Purpose. */
    protected String purpose;

    /** Instantiate a new TextWithDataLengthChunk. */
    public TextWithDataLengthChunk() {
        super();
    }

    /**
     * Parse a WAVE text with data length chunk.
     *
     * @param jhove2
     *            JHOVE2 framework
     * @param source
     *            WAVE source unit
     * @param input  WAVE source input
     * @return Number of bytes consumed
     * @throws EOFException
     *             If End-of-File is reached reading the source unit
     * @throws IOException
     *             If an I/O exception is raised reading the source unit
     * @throws JHOVE2Exception
     */
    @Override
    public long parse(JHOVE2 jhove2, Source source, Input input)
        throws EOFException, IOException, JHOVE2Exception
    {
        long consumed = super.parse(jhove2, source, input);

        /* Name. */
        StringBuffer sb = new StringBuffer(4);
        for (int i=0; i<4; i++) {
            short b = input.readUnsignedByte();
            sb.append((char) b);
        }
        this.name = sb.toString();
        consumed += 4;

        /* Number of samples. */
        this.numSamples = input.readUnsignedInt();
        consumed += 4;

        /* Purpose. */
        sb = new StringBuffer(4);
        for (long i=0; i<4; i++) {
            short b = input.readUnsignedByte();
            sb.append((char) b);
        }
        this.purpose = sb.toString();
        consumed += 4;

        /* Country code. */
        this.countryCode = input.readUnsignedShort();
        consumed += 2;

        /* Language code. */
        this.languageCode = input.readUnsignedShort();
        consumed += 2;

        /* Dialect code. */
        this.dialectCode = input.readUnsignedShort();
        consumed += 2;

        /* Code page. */
        this.codePage = input.readUnsignedShort();
        consumed += 2;

        return consumed;
    }

    /** Get code page.
     * @return Code page
     */
    @ReportableProperty(order=10, value="Code page.")
    public int getCodePage() {
        return this.codePage;
    }

    /** Get country code in raw form.
     * @return Country code
     */
    @ReportableProperty(order=4, value="Get country code in raw form.")
    public int getCountryCode_raw() {
        return this.countryCode;
    }

    /** Get dialect code in raw form.
     * @return Dialect code
     */
    @ReportableProperty(order=8, value="Get dialect code in raw form.")
    public int getDialectCode_raw() {
        return this.dialectCode;
    }

    /** Get language code in raw form.
     * @return Language code
     */
    @ReportableProperty(order=6, value="Get language code in raw form.")
    public int getLanguageCode_raw() {
        return this.languageCode;
    }

    /** Get name.
     * @return name
     */
    @ReportableProperty(order=1, value="Name.")
    public String getName() {
        return this.name;
    }

    /** Get number of samples.
     * @return Number of samples
     */
    @ReportableProperty(order=2, value="Number of samples.")
    public long getNumberOfSamples() {
        return this.numSamples;
    }

    /** Get purpose.
     * @return purpose
     */
    @ReportableProperty(order=3, value="Purpose.")
    public String getPurpose() {
        return this.purpose;
    }
}


text:
package main

import (
	"github.com/Azer0s/Hummus/interpreter"
	"strconv"
	"strings"
)

// CALL conversion functions
var CALL string = "--system-do-convert!"

// Init Hummus stdlib stub
func Init(variables *map[string]interpreter.Node) {
	// noinit
}

// DoSystemCall Hummus stdlib stub
func DoSystemCall(args []interpreter.Node, variables *map[string]interpreter.Node) interpreter.Node {
	mode := args[0].Value.(string)

	switch mode {
	case "string":
		return interpreter.Node{
			Value:    interpreter.DumpNode(args[1]),
			NodeType: interpreter.NODETYPE_STRING,
		}

	case "atom":
		val := interpreter.DumpNode(args[1])
		val = strings.ReplaceAll(val, " ", "_")
		val = strings.ReplaceAll(val, "(", "")
		val = strings.ReplaceAll(val, ")", "")

		return interpreter.Node{
			Value:    val,
			NodeType: interpreter.NODETYPE_ATOM,
		}

	case "int":
		val, err := strconv.Atoi(interpreter.DumpNode(args[1]))
		return interpreter.OptionalNode(val, interpreter.NODETYPE_INT, err != nil)

	case "float":
		val, err := strconv.ParseFloat(interpreter.DumpNode(args[1]), 64)
		return interpreter.OptionalNode(val, interpreter.NODETYPE_FLOAT, err != nil)

	case "bool":
		val, err := strconv.ParseBool(interpreter.DumpNode(args[1]))
		return interpreter.OptionalNode(val, interpreter.NODETYPE_BOOL, err != nil)

	case "identity":
		return args[1]

	default:
		panic("Unrecognized mode")
	}
}


text:
import unittest

import numpy as np

from transformers import ElectraConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from .test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask

if is_flax_available():
    from transformers.models.electra.modeling_flax_electra import (
        FlaxElectraForMaskedLM,
        FlaxElectraForMultipleChoice,
        FlaxElectraForPreTraining,
        FlaxElectraForQuestionAnswering,
        FlaxElectraForSequenceClassification,
        FlaxElectraForTokenClassification,
        FlaxElectraModel,
    )

class FlaxElectraModelTester(unittest.TestCase):
    def __init__(
        self,
        parent,
        batch_size=13,
        seq_length=7,
        is_training=True,
        use_attention_mask=True,
        use_token_type_ids=True,
        use_labels=True,
        vocab_size=99,
        embedding_size=24,
        hidden_size=32,
        num_hidden_layers=5,
        num_attention_heads=4,
        intermediate_size=37,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=16,
        type_sequence_label_size=2,
        initializer_range=0.02,
        num_choices=4,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.seq_length = seq_length
        self.is_training = is_training
        self.use_attention_mask = use_attention_mask
        self.use_token_type_ids = use_token_type_ids
        self.use_labels = use_labels
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.embedding_size = embedding_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.max_position_embeddings = max_position_embeddings
        self.type_vocab_size = type_vocab_size
        self.type_sequence_label_size = type_sequence_label_size
        self.initializer_range = initializer_range
        self.num_choices = num_choices

    def prepare_config_and_inputs(self):
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)

        attention_mask = None
        if self.use_attention_mask:
            attention_mask = random_attention_mask([self.batch_size, self.seq_length])

        token_type_ids = None
        if self.use_token_type_ids:
            token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)

        config = ElectraConfig(
            vocab_size=self.vocab_size,
            hidden_size=self.hidden_size,
            embedding_size=self.embedding_size,
            num_hidden_layers=self.num_hidden_layers,
            num_attention_heads=self.num_attention_heads,
            intermediate_size=self.intermediate_size,
            hidden_act=self.hidden_act,
            hidden_dropout_prob=self.hidden_dropout_prob,
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
            max_position_embeddings=self.max_position_embeddings,
            type_vocab_size=self.type_vocab_size,
            initializer_range=self.initializer_range,
        )

        return config, input_ids, token_type_ids, attention_mask

    def prepare_config_and_inputs_for_common(self):
        config_and_inputs = self.prepare_config_and_inputs()
        config, input_ids, token_type_ids, attention_mask = config_and_inputs
        inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask}
        return config, inputs_dict

@require_flax
class FlaxElectraModelTest(FlaxModelTesterMixin, unittest.TestCase):

    all_model_classes = (
        (
            FlaxElectraModel,
            FlaxElectraForMaskedLM,
            FlaxElectraForPreTraining,
            FlaxElectraForTokenClassification,
            FlaxElectraForQuestionAnswering,
            FlaxElectraForMultipleChoice,
            FlaxElectraForSequenceClassification,
        )
        if is_flax_available()
        else ()
    )

    def setUp(self):
        self.model_tester = FlaxElectraModelTester(self)

    @slow
    def test_model_from_pretrained(self):
        for model_class_name in self.all_model_classes:
            if model_class_name == FlaxElectraForMaskedLM:
                model = model_class_name.from_pretrained("google/electra-small-generator")
            else:
                model = model_class_name.from_pretrained("google/electra-small-discriminator")
            outputs = model(np.ones((1, 1)))
            self.assertIsNotNone(outputs)


text:
#region Copyright
//
// DotNetNuke® - http://www.dotnetnuke.com
// Copyright (c) 2002-2016
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;

namespace DotNetNuke.Web.Mvp
{
    public class ModuleSettingsPresenterBase<TView> : ModulePresenterBase<TView> where TView : class, ISettingsView
    {
        #region Constructors

        public ModuleSettingsPresenterBase(TView view) : base(view)
        {
            view.OnLoadSettings += OnLoadSettingsInternal;
            view.OnSaveSettings += OnSaveSettingsInternal;

            ModuleSettings = new Dictionary<string, string>();
            TabModuleSettings = new Dictionary<string, string>();
        }

        #endregion

        public Dictionary<string, string> ModuleSettings { get; set; }

        public Dictionary<string, string> TabModuleSettings { get; set; }

        #region Event Handlers

        private void OnLoadSettingsInternal(object sender, EventArgs e)
        {
            LoadSettings();
        }

        private void OnSaveSettingsInternal(object sender, EventArgs e)
        {
            SaveSettings();
        }

        #endregion

        #region Protected Methods

        protected override void LoadFromContext()
        {
            base.LoadFromContext();

            foreach (var key in ModuleContext.Configuration.ModuleSettings.Keys)
            {
                ModuleSettings.Add(Convert.ToString(key), Convert.ToString(ModuleContext.Configuration.ModuleSettings[key]));
            }

            foreach (var key in ModuleContext.Configuration.TabModuleSettings.Keys)
            {
                TabModuleSettings.Add(Convert.ToString(key), Convert.ToString(ModuleContext.Configuration.TabModuleSettings[key]));
            }
        }

        protected virtual void LoadSettings()
        {
        }

        protected virtual void SaveSettings()
        {
        }

        #endregion

    }
}


text:
package net.bull.javamelody;

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

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.PriorityOrdered;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;

import net.bull.javamelody.internal.common.LOG;

/**
 * Post-processor Spring pour un éventuel {@link RestTemplate} défini dans le fichier xml Spring.
 * @author Emeric Vernat
 */
public class SpringRestTemplateBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
	private static final boolean REST_TEMPLATE_INTERCEPTOR_AVAILABLE = isRestTemplateInterceptorAvailable();

	// l'interface PriorityOrdered place la priorité assez haute dans le contexte Spring
	// quelle que soit la valeur de order
	private int order = LOWEST_PRECEDENCE;

	/** {@inheritDoc} */
	@Override
	public int getOrder() {
		return order;
	}

	/**
	 * Définit la priorité dans le contexte Spring.
	 * @param order int
	 */
	public void setOrder(int order) {
		this.order = order;
	}

	/** {@inheritDoc} */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		return bean;
	}

	/** {@inheritDoc} */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		// RestTemplate et getInterceptors() existent depuis spring-web 3.1.0.RELEASE
		if (REST_TEMPLATE_INTERCEPTOR_AVAILABLE && bean instanceof RestTemplate) {
			final RestTemplate restTemplate = (RestTemplate) bean;
			final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(
					restTemplate.getInterceptors());
			for (final ClientHttpRequestInterceptor interceptor : interceptors) {
				if (interceptor instanceof SpringRestTemplateInterceptor) {
					return bean;
				}
			}
			interceptors.add(SpringRestTemplateInterceptor.SINGLETON);
			restTemplate.setInterceptors(interceptors);
			LOG.debug("rest template interceptor initialized");
		}

		return bean;
	}

	private static boolean isRestTemplateInterceptorAvailable() {
		try {
			final Class<?> clazz = Class.forName("org.springframework.web.client.RestTemplate");
			clazz.getMethod("getInterceptors");
			return true;
		} catch (final ClassNotFoundException | SecurityException | NoSuchMethodException e) {
			return false;
		}
	}
}


text:
export default function (p3sim, share) {
  let instEditorTextArea = $('#inst-editor-textarea');
  instEditorTextArea.val(p3js.assembly.dumpInstructionsList());
  $('#inst-editor-btn').click(() => {
    try {
      p3js.assembly.registerInstructionList(instEditorTextArea.val());
      alert('Done.');
    } catch (e) {
      alert(e.message);
    }
  });

  ['A', 'B', 'C'].forEach((c, i) => {
    let $wrapper = $('#rom-' + c.toLowerCase() + '-wrapper');
    $wrapper.append($('<h3>').text('ROM ' + c));
    let $btn_apply = $('<button class="btn btn-secundary btn-xs pull-right">').text('Apply to ROM ' + c);
    $wrapper.append($('<h4>').text('Changes ').append($btn_apply));
    let $changes = $('<textarea>').attr({
      rows: 10,
      placeholder: 'Put changes to ROM ' + c + ' here!\n<index hex> <value hex>\n...',
    }).appendTo($wrapper);
    $wrapper.append($('<h4>').text('Contents '));
    let $contents = $('<textarea readonly>').appendTo($wrapper);

    let re = new p3js.dom.ROMEditor(p3sim, i, $contents, $changes);
    $contents.attr('rows', (re._rw.size > 32 ? 32 : re._rw.size));

    $btn_apply.click(() => {
      re.save();
    });
  });
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.10.24 at 02:08:50 PM BST
//

package com.oracle.xmlns.adf.svc.types;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for FloatResult complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="FloatResult">
 *   <complexContent>
 *     <extension base="{http://xmlns.oracle.com/adf/svc/types/}MethodResult">
 *       <sequence>
 *         <element name="Value" type="{http://www.w3.org/2001/XMLSchema}float" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "FloatResult", propOrder = {
    "value"
})
public class FloatResult
    extends MethodResult
{

    @XmlElement(name = "Value", type = Float.class)
    protected List<Float> value;

    /**
     * Gets the value of the value property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the value property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getValue().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Float }
     *
     *
     */
    public List<Float> getValue() {
        if (value == null) {
            value = new ArrayList<Float>();
        }
        return this.value;
    }

}


text:
package Ctr;

import java.util.ArrayList;

import Db.*;
import Mdl.*;

public class CtrDepartment {
	public CtrDepartment() {

    }
    public ArrayList<department> findAllDepartments()
    {
      IFDBdepartment dbDpart= new DBdepartment();
      ArrayList<department> allDpart = new ArrayList<department>();
      allDpart = dbDpart.getAllDepartments();
      return allDpart;
    }
    public department getDepartment(int id)
    {
        IFDBdepartment dbDpart= new DBdepartment();
        return dbDpart.getDepartment(id);
    }

    public department getLatest()
    {
    	IFDBdepartment dbDpart= new DBdepartment();
        return dbDpart.getLatest();
    }
	  public int updateDepartment (int id,String name)
	  {
		  IFDBdepartment dbDpart= new DBdepartment();
	      department dpart = dbDpart.getDepartment(id);
	      department dpartObj = new department();
	      dpartObj.setId(dpart.getId());
	      dpartObj.setDepartmentName(name);
	      return  dbDpart.updateDepartment(dpartObj);
	  }

      public void insertNew(String name) throws Exception
      {
           department dpartObj = new department();
           dpartObj.setDepartmentName(name);

           try{
            DbConnection.startTransaction();
  		  	IFDBdepartment dbDpart= new DBdepartment();
  		  	dbDpart.insertDepartment(dpartObj);
            DbConnection.commitTransaction();
           }
           catch(Exception e)
           {
               DbConnection.rollbackTransaction();
               throw new Exception("Department not inserted");
           }
      }
}


text:
<?
	defined('C5_EXECUTE') or die("Access Denied.");

	class CoreScrapbookDisplayBlockController extends Concrete5_Controller_Block_CoreScrapbookDisplay {

	}


text:
package release_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"testing"
)

func TestRelease(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Release Suite")
}


text:
package mk.ukim.finki.wp.service.db;

import mk.ukim.finki.wp.model.db.Weight;
import mk.ukim.finki.wp.service.BaseEntityCrudService;

public interface WeightService extends BaseEntityCrudService<Weight> {

}


text:
<?php

class ClubTopic extends DataObject
{
	private $images_cache = null;

	protected $ThumbnailWidth = 175;
	protected $ThumbnailHeight = 150;
	protected $ImageWidth = 640;
	protected $ImageHeight = 480;

	static $db = array(
		'ReleaseDate' => 'Date',
		'Title' => 'Varchar(200)',
		'Description' => 'Text'
	);

	static $has_many = array(
		'Images' => 'ClubTopic_Image'
	);

	public function State()
	{
		if(strtotime($this->ReleaseDate) < time()) return 'past';

		$older_new = (int) DB::query("SELECT COUNT(*) FROM ClubTopic WHERE ReleaseDate < '" . $this->ReleaseDate . "' AND ReleaseDate > NOW()")->value();

		if($older_new == 0) return 'active';

		return 'planned';
	}

	public function validate()
	{
		return parent::validate();
	}

	public static function getBaseDirectoryName()
	{
		return 'Clubthemen';
	}

	public function Thumbnails()
	{
		return $this->Images(false);
	}

	public function EnlargableThumbnails()
	{
		return $this->Images();
	}

	public function SortableThumbnails()
	{
		return $this->SortingImages();
	}

	/*
	 * This overwrites parent::Images() !
	 */
	public function Images($link = true)
	{
		$images = $this->fetchImages();
		$newSet = new DataObjectSet();
		foreach($images as $i => $image)
		{
			//Klassenzuweisung für die Bildkonvertierung
			$bigImage = $imgClass->getFormattedImage('ResizeRatio', $this->ImageWidth, $this->ImageHeight); //Bildkonvertierung für vergrößertes Bild ....
			$smallImage = $imgClass->getFormattedImage('ResizeRatio', $this->ThumbnailWidth, $this->ThumbnailHeight); // und für verkleinertes Bild.

			//Bildstring zusammenbauen
			$thumb = '';
			if($link) $thumb .= 'ID . '/' . $image->ID . '" class="thumbnail">';
			if($smallImage != null)
			{
				$thumb .= '
Filename . ')" alt="' . $smallImage->Title . '" class="thumbnail">
';
			}
			if($link) $thumb .= '';

			//TemplateControl setzen
			$imgClass->Thumbnail = $thumb;
			$imgClass->IsModuloThree = $i > 0 && ($i+1)%3 == 0;
			$newSet->push($imgClass);
		}
		return $newSet;
	}

	public function SortingImages()
	{
		$images = $this->fetchImages();
		$newSet = new DataObjectSet();
		foreach($images as $i => $image)
		{
			$bigImage = $image->getFormattedImage('ResizeRatio', $this->ImageWidth, $this->ImageHeight); //Bildkonvertierung für vergrößertes Bild ....
			$smallImage = $image->getFormattedImage('ResizeRatio', 190, 125); // und für verkleinertes Bild.

			//Bildstring zusammenbauen
			$thumb = '';
			if($smallImage != null)
			{
				$thumb .= 'Filename . '" alt="' . $smallImage->Title . '" class="thumbnail" />';
			}

			//TemplateControl setzen
			$image->Thumbnail = $thumb;
			$image->IsModuloThree = $i > 0 && ($i+1)%3 == 0;
			$newSet->push($image);
		}
		return $newSet;
	}

	public function ImagesCount()
	{
		return $this->fetchImages()->Count();
	}

	private function fetchImages()
	{
		if($this->images_cache == null && $this->MemberID) $this->images_cache = DataObject::get('ClubTopic_Image', 'ClubTopicID = ' . $this->ID . ' AND OwnerID = ' . $this->MemberID, 'Sort ASC, ClubTopic_Image.ID ASC');
		return $this->images_cache ? $this->images_cache : new DataObjectSet();
	}

	public function CanEdit()
	{
		return Permission::check('ADMIN') || (is_numeric($this->urlParams['ID']) && Member::currentMember() != null && $this->urlParams['ID'] == Member::currentMember()->ID);
	}
}
/*
 * Erweiterteklasse zur Erzeugung und Bearbeitung von Bildern
 */
class ClubTopic_Image extends Image
{
	static $db = array(
		'Clicks' => 'Int'
	);

	static $has_one = array(
		'ClubTopic' => 'ClubTopic',
		'Member' => 'Member'
	);

	protected $num_comments;

	public function generateResizeRatio($gd, $width, $height)
	{
		return $gd->resizeRatio($width, $height);
	}

	public function SetMaxWidth($width)
	{
		if($this->getWidth() <= $width) return $this;
		return $this->SetWidth($width);
	}

	public function CanEditImage()
	{
		return $this->OwnerID = Member::currentUserID();
	}

	public function NumComments()
	{
		if($this->num_comments == null) $this->num_comments = (int) DB::query('SELECT COUNT(*) FROM PageComment WHERE PageOtherID = ' . $this->ID)->value();
		return $this->num_comments;
	}

	public function recognizeClick()
	{
		if(Member::currentUser() && Member::currentUser()->ID == $this->OwnerID)
		{
			// don't count own image clicks!
			return;
		}

		// don't count bots
		global $fotoclub_config;
		$remoteHostName = gethostbyaddr($_SERVER['REMOTE_ADDR']);
		foreach($fotoclub_config['bots'] as $key => $botHostName)
		{
			if(strpos($remoteHostName, $botHostName))
			{
				return;
			}
		}

		$this->update(array(
			'Clicks' => $this->Clicks + 1 // increment counter
		));
		$this->write();//write the changes
	}

	public function IsFirst()
	{
		return DB::query('SELECT COUNT(*) FROM File LEFT JOIN ClubTopic_Image ON File.ID = ClubTopic_Image.ID WHERE ImageGalleryID = ' . $this->ImageGalleryID . ' AND OwnerID = ' . $this->OwnerID . ' AND ( Sort < ' . $this->Sort . ' OR ( Sort = 0 AND File.ID < ' . $this->ID . '))')->value() == 0;
	}

	public function IsLast()
	{
		return DB::query('SELECT COUNT(*) FROM File LEFT JOIN ClubTopic_Image ON File.ID = ClubTopic_Image.ID WHERE ImageGalleryID = ' . $this->ImageGalleryID . ' AND OwnerID = ' . $this->OwnerID . ' AND ( Sort > ' . $this->Sort . ' OR ( Sort = 0 AND File.ID > ' . $this->ID . '))')->value() == 0;
	}

	public function PrevImage()
	{
		$images = DataObject::get('ClubTopic_Image', 'ClubTopicID = ' . $this->ClubTopicID . ' AND OwnerID = ' . $this->OwnerID . ' AND ( Sort < ' . $this->Sort . ' OR ( Sort = 0 AND File.ID < ' . $this->ID . '))', 'Sort ASC, File.ID DESC', '', '0,1');
		if($images->Count() == 0) return $this;
		return $images->First();
	}

	public function NextImage()
	{
		$images = DataObject::get('ClubTopic_Image', 'ClubTopicID = ' . $this->ClubTopicID . ' AND OwnerID = ' . $this->OwnerID . ' AND ( Sort > ' . $this->Sort . ' OR ( Sort = 0 AND File.ID > ' . $this->ID . '))', 'Sort ASC, File.ID ASC', '', '0,1');
		if($images->Count() == 0) return $this;
		return $images->First();
	}

	public function Exif()
	{
		$exif = exif_read_data($this->getFullPath(), 0, true);
 		$ret = new DataObjectSet();
		foreach($exif as $key => $section)
		{
			foreach($section as $name => $val)
			{
				if(trim($val) != '')
				{
					switch("$key.$name")
					{
						case 'IFD0.Model':
							$data = new ViewableData();
							$data->Key = 'Kamera';
							$data->Value = $val;
							$ret->push($data);
							break;

						case 'EXIF.FocalLength':
							$data = new ViewableData();
							$data->Key = 'Brennweite';
							$data->Value = $val;
							$ret->push($data);
							break;

						case 'COMPUTED.ApertureFNumber':
							$data = new ViewableData();
							$data->Key = 'Blende';
							$data->Value = $val;
							$ret->push($data);
							break;

						case 'EXIF.ExposureTime':
							$data = new ViewableData();
							$data->Key = 'Belichtung';
							$data->Value = $val;
							$ret->push($data);
							break;

						case 'EXIF.ISOSpeedRatings':
							$data = new ViewableData();
							$data->Key = 'ISO';
							$data->Value = $val;
							$ret->push($data);
							break;
					}
				}
			}
		}
		return $ret;
	}
}

?>


text:
layout: post
title: Novelty Sentence Detection
subtitle: A Foray into Anomaly Detection on Textual Data
---

Something I had considered recently was "how much is this sentence like another?"
I figured it would be an interesting exploration at the intersection of natural language processing, statistics, and information theory.
It certainly motivates the application of theory and data gathering.
To be surem there are even many levels of rigor in approaches one may develop, ranging from heuristical to principled.

Then, we consider a few problems to solve at these different levels.

1) measurement of similarity
2) space through which things are measured
to point 1, a mathematical measure is an analytic construction that satisfies specific properties.
If we want to be a little less abstract and immediately accessible, albeit at the cost of rigorous guarantees, we might design some heuristic approximation of the former.

Towards the ends of number 2, an embedding space is a popular approach.
More specifically, it is a learned representation of semantic relationships, whereby an embedding vector's dimensions each correspond to a learned feature expressed through this dimension.
These relationships of course are characterized by the engineer, specifically through the objective, the data, and the training regime.

Learning the embedding space is, intuitively, allowing the data to describe, themselves, the most salient behaviors along which they relate to each other.
Another task that will be later explored is how the dimension of the projection space relates to the interpretability of the vectors' corresponding semantics, i.e. what does each dimension in a vector describe, approximately?
There is a prevailing hypothesis within machine learning, termed the data manifold hypothesis. This is a description of the idea that all learnable data spaces have some lower dimensional representation where all the data relate to each other without loss of information, basically.

The measure theory approach requires some table setting.


text:
* Added checkbox for single folders to be zipped instead of just their contents

## 3.2.0 - Added settings for compression
* Added settings for the compression level of the zip archive
* Added change log notes to help highlight the issues resolved
* Cleaned the debugging code that was missed with the initial 3.1.0 launch

## 3.1.0 - Compression Enabled
* Added compression to the zip archive at level 6 (in future releases this will be a setting)
* Resolved bug where files where getting added with absolute paths instead of relative ones

## 3.0.0 - Added better error catching
* Added better error catching while saving the zip file
* Now able to zip a single file
* When zipping a single folder, the files and folders inside the zip are relative to that folder instead of the base one

## 2.1.1 - Second Release
* Fixed zip issue
* Added done notification


text:
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="/favicon.ico">
    <title>TESTBC</title>
    <link href="/stylesheets/bootstrap.min.css" rel="stylesheet">
    <link href="/stylesheets/bootstrap-select.min.css" rel="stylesheet">
    <link href="/stylesheets/font-awesome.min.css" rel="stylesheet">

    What's New?<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"></button>

UserLists

 CreateUser ListsList ActiveList GuestList Full User Testing GuestList DeniedList AllWho Is Online

Tools

 ActionCreate Blog

Help

OSMBCVersion 1.8.4Help

WeeklyOSM & WochennotizVision & RulesEditorial MeetingsWochennotiz in OSM WikiWeekly in OSM WikiGlossary

EN

EN

Configuration

Calendar

 Calendar Translation Texts

 Flags for calendar

 Filter for calendar

Editor Info

 Formulation Hint for DE

 Formulation Hint for EN

 Descriptions for Categories

Language Indicator Icons

Pictures

Picture Licensing

Blog

Author Documentation

Category Translation

Article

Text for Translate Links

Not a Doublette Link

Votes For Articles

IM Notification

Configuration of IM Channel (Slack,MM)

[changes]

Long Absent

Last Changes  (more)

                    blog
                    user
                    table
                    what
                    Change
                    when

only displaying changesinserted textremoved text

    <title>TESTBC</title>
    <link rel="stylesheet" href="/stylesheets/style.css">


text:
package com.scienceminer.nerd.main.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

public class SoftwareInfo {
    private String name;
    private String version;
    private String description;

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

    private static SoftwareInfo INSTANCE = null;

    private SoftwareInfo(String name, String version, String description) {
        this.name = name;
        this.version = version;
        this.description = description;
    }

    public static SoftwareInfo getInstance() {
        if (INSTANCE != null) {
            return INSTANCE;
        }

        //Default in case of issues of any nature
        INSTANCE = new SoftwareInfo("entity-fishing", "N/A", "Entity Recognition and Disambiguation");

        Properties properties = new Properties();
        try {
            properties.load(SoftwareInfo.class.getResourceAsStream("/service.properties"));
            INSTANCE = new SoftwareInfo(properties.getProperty("name"), properties.getProperty("version"), properties.getProperty("description"));
        } catch (Exception e) {
            LOGGER.error("General error when extracting the version of this application", e);
        }

        return INSTANCE;
    }

    public String toJson() {
        StringBuilder sb = new StringBuilder();
        sb.append("{")
                .append("\"name\": \"" + this.getName() + "\"")
                .append(", \"version\": \"" + this.getVersion() + "\"")
                .append(", \"description\": \"" + this.getDescription() + "\"")
                .append("}");
        return sb.toString();
    }

    public String getName() {
        return name;
    }

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

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}


text:
const refreshDropdown   = require('@binary-com/binary-style').selectDropdown;
const moment            = require('moment');
const TradingAnalysis   = require('./analysis');
const commonTrading     = require('./common');
const Contract          = require('./contract');
const Defaults          = require('./defaults');
const Durations         = require('./duration');
const GetTicks          = require('./get_ticks');
const Lookback          = require('./lookback');
const Notifications     = require('./notifications');
const Price             = require('./price');
const Reset             = require('./reset');
const StartDates        = require('./starttime').StartDates;
const Symbols           = require('./symbols');
const Tick              = require('./tick');
const BinarySocket      = require('../../base/socket');
const getMinPayout      = require('../../common/currency').getMinPayout;
const isCryptocurrency  = require('../../common/currency').isCryptocurrency;
const elementInnerHtml  = require('../../../_common/common_functions').elementInnerHtml;
const getElementById    = require('../../../_common/common_functions').getElementById;
const getVisibleElement = require('../../../_common/common_functions').getVisibleElement;
const localize          = require('../../../_common/localize').localize;
const State             = require('../../../_common/storage').State;
const getPropertyValue  = require('../../../_common/utility').getPropertyValue;

const Process = (() => {
    /*
     * This function process the active symbols to get markets
     * and underlying list
     */
    const processActiveSymbols = () => {
        BinarySocket.send({ active_symbols: 'brief' }).then((response) => {
            if (response.active_symbols && response.active_symbols.length) {
                // populate the Symbols object
                Symbols.details(response);

                const market = commonTrading.getDefaultMarket();

                // store the market
                Defaults.set('market', market);

                commonTrading.displayMarkets();
                processMarket();
            } else {
                $('#content').empty().html($('<div/>', { class: 'container' }).append($('<p/>', { class: 'notice-msg center-text', text: localize('Trading is unavailable at this time.') })));
            }
        });
    };

    /*
     * Function to call when market has changed
     */
    const processMarket = () => {
        // we can get market from sessionStorage as allowed market
        // is already set when this is called
        let market = Defaults.get('market');
        let symbol = Defaults.get('underlying');

        // change to default market if query string contains an invalid market
        if (!market || !Symbols.underlyings()[market]) {
            market = commonTrading.getDefaultMarket();
            Defaults.set('market', market);
        }
        if ((!symbol || !Symbols.underlyings()[market][symbol])) {
            symbol = undefined;
        }

        processMarketUnderlying();
    };

    /*
     * Function to call when underlying has changed
     */
    const processMarketUnderlying = () => {
        const underlying_element = document.getElementById('underlying');
        const underlying = underlying_element.value;

        Defaults.set('underlying', underlying);

        commonTrading.showFormOverlay();

        // get ticks for current underlying
        GetTicks.request(underlying);

        Tick.clean();

        commonTrading.updateWarmChart();

        BinarySocket.clearTimeouts();

        getContracts(underlying);

        commonTrading.displayTooltip();
    };

    const getContracts = (underlying) => {
        BinarySocket.send({ contracts_for: underlying }).then((response) => {
            Notifications.hide('CONNECTION_ERROR');
            processContract(response);
        });
    };

    /*
     * Function to display contract form for current underlying
     */
    const processContract = (contracts) => {
        if (getPropertyValue(contracts, ['error', 'code']) === 'InvalidSymbol') {
            Price.processForgetProposals();
            getElementById('contract_confirmation_container').style.display      = 'block';
            getElementById('contracts_list').style.display = 'none';
            getElementById('confirmation_message').hide();

            const confirmation_error = getElementById('confirmation_error');
            confirmation_error.show();
            elementInnerHtml(confirmation_error, `${contracts.error.message} <a href="javascript:;" onclick="sessionStorage.removeItem('underlying'); window.location.reload();">${localize('Please reload the page')}</a>`);
            return;
        }

        State.set('is_chart_allowed', !(contracts.contracts_for && contracts.contracts_for.feed_license && contracts.contracts_for.feed_license === 'chartonly'));

        getElementById('trading_socket_container').classList.add('show');

        const init_logo = getElementById('trading_init_progress');
        if (init_logo && init_logo.style.display !== 'none') {
            init_logo.style.display = 'none';
            Defaults.update();
        }

        Contract.setContracts(contracts);

        const contract_categories = Contract.contractForms();
        let formname;
        if (Defaults.get('formname') && contract_categories && contract_categories[Defaults.get('formname')]) {
            formname = Defaults.get('formname');
        } else {
            const tree = commonTrading.getContractCategoryTree(contract_categories);
            if (tree[0]) {
                if (typeof tree[0] === 'object') {
                    formname = tree[0][1][0];
                } else {
                    formname = tree[0];
                }
            }
        }

        commonTrading.displayContractForms('contract_form_name_nav', contract_categories, formname);

        processContractForm(formname);

        TradingAnalysis.request();

        commonTrading.hideFormOverlay();
    };

    const processContractForm = (formname_to_set = getElementById('contract').value || Defaults.get('formname')) => {
        setFormName(formname_to_set);

        // get updated formname
        Contract.details(Defaults.get('formname'));

        StartDates.display();

        displayPrediction();
        refreshDropdown('#prediction');
        displaySelectedTick();
        refreshDropdown('#selected_tick');
        Lookback.display();

        if (!Reset.isReset(Defaults.get('formname'))) {
            Reset.hideResetTime();
        }

        let r1;
        if (State.get('is_start_dates_displayed') && Defaults.get('date_start') && Defaults.get('date_start') !== 'now') {
            r1 = Durations.onStartDateChange(Defaults.get('date_start'));
            if (!r1 || Defaults.get('expiry_type') === 'endtime') Durations.display();
        } else {
            Durations.display();
        }

        // needs to be called after durations are populated
        displayEquals();

        const currency  = Defaults.get('currency') || getVisibleElement('currency').value;
        const is_crypto = isCryptocurrency(currency);
        const amount    = is_crypto ? 'amount_crypto' : 'amount';
        if (Defaults.get(amount)) {
            $('#amount').val(Defaults.get(amount));
        } else {
            const default_value = getMinPayout(currency);
            Defaults.set(amount, default_value);
            getElementById('amount').value = default_value;
        }
        if (Defaults.get('amount_type')) {
            commonTrading.selectOption(Defaults.get('amount_type'), getElementById('amount_type'));
        } else {
            Defaults.set('amount_type', getElementById('amount_type').value);
        }

        if (Contract.form() === 'callputspread') {
            commonTrading.selectOption('payout', getElementById('amount_type'));
            refreshDropdown('#amount_type');
            // hide stake option
            getElementById('stake_option').setVisibility(0);
            $('[data-value="stake"]').hide();
        } else {
            getElementById('stake_option').setVisibility(1);
            refreshDropdown('#amount_type');
        }

        if (Defaults.get('currency')) {
            commonTrading.selectOption(Defaults.get('currency'), getVisibleElement('currency'));
        }

        const expiry_type        = Defaults.get('expiry_type') || 'duration';
        const make_price_request = onExpiryTypeChange(expiry_type);

        if (make_price_request >= 0) {
            Price.processPriceRequest();
        }
    };

    const displayPrediction = () => {
        const prediction_row = getElementById('prediction_row');
        if (Contract.form() === 'digits' && sessionStorage.getItem('formname') !== 'evenodd') {
            prediction_row.show();
            const prediction = getElementById('prediction');
            if (Defaults.get('prediction')) {
                commonTrading.selectOption(Defaults.get('prediction'), prediction);
            } else {
                Defaults.set('prediction', prediction.value);
            }
        } else {
            prediction_row.hide();
            Defaults.remove('prediction');
        }
    };

    const displaySelectedTick = () => {
        const selected_tick_row       = getElementById('selected_tick_row');
        const highlowticks_expiry_row = getElementById('highlowticks_expiry_row');
        if (sessionStorage.getItem('formname') === 'highlowticks') {
            selected_tick_row.show();
            highlowticks_expiry_row.show();
            const selected_tick = getElementById('selected_tick');
            if (Defaults.get('selected_tick')) {
                commonTrading.selectOption(Defaults.get('selected_tick'), selected_tick);
            } else {
                Defaults.set('selected_tick', selected_tick.value);
            }
        } else {
            selected_tick_row.hide();
            highlowticks_expiry_row.hide();
            Defaults.remove('selected_tick');
        }
    };

    const hasCallPutEqual = (contracts = getPropertyValue(Contract.contracts(), ['contracts_for', 'available']) || []) =>
        contracts.find(contract => contract.contract_category === 'callputequal');

    const displayEquals = (expiry_type = 'duration') => {
        const formname  = Defaults.get('formname');
        const el_equals = document.getElementById('callputequal');
        const durations = getPropertyValue(Contract.durations(), [commonTrading.durationType(Defaults.get('duration_units'))]) || [];
        if (/^(callputequal|risefall)$/.test(formname) && (('callputequal' in durations || expiry_type === 'endtime') && hasCallPutEqual())) {
            if (+Defaults.get('is_equal')) {
                el_equals.checked = true;
            }
            el_equals.parentElement.setVisibility(1);
        } else {
            el_equals.parentElement.setVisibility(0);
        }
    };

    const setFormName = (formname) => {
        let formname_to_set    = formname;
        const has_callputequal = hasCallPutEqual();
        if (formname_to_set === 'callputequal' && (!has_callputequal || !+Defaults.get('is_equal'))) {
            formname_to_set = 'risefall';
        } else if (formname_to_set === 'risefall' && has_callputequal && +Defaults.get('is_equal')) {
            formname_to_set = 'callputequal';
        }
        Defaults.set('formname', formname_to_set);
        getElementById('contract').setAttribute('value', formname_to_set);
    };

    const forgetTradingStreams = () => {
        Price.processForgetProposals();
        Price.processForgetProposalOpenContract();
        processForgetTicks();
    };

    /*
     * cancel the current tick stream
     * this need to be invoked before makin
     */
    const processForgetTicks = () => {
        BinarySocket.send({ forget_all: 'ticks' });
    };

    const onExpiryTypeChange = (value) => {
        const $expiry_type    = $('#expiry_type');
        const validated_value = value && $expiry_type.find(`option[value=${value}]`).length ? value : 'duration';
        const is_edge = window.navigator.userAgent.indexOf('Edge') !== -1;
        $expiry_type.val(validated_value);

        let make_price_request = 0;
        if (validated_value === 'endtime') {
            Durations.displayEndTime();
            if (Defaults.get('expiry_date')) {
                // if time changed, proposal will be sent there if not we should send it here
                make_price_request = Durations.selectEndDate(moment(Defaults.get('expiry_date'))) ? -1 : 1;
            }
            Defaults.remove('duration_units', 'duration_amount');
            if (is_edge) {
                document.getSelection().empty(); // microsoft edge 18 automatically start selecting text when select expiry time after changing expiry type to end time
            }
        } else {
            StartDates.enable();
            Durations.display();
            if (Defaults.get('duration_units')) {
                onDurationUnitChange(Defaults.get('duration_units'));
            }
            const duration_amount = Defaults.get('duration_amount');
            if (duration_amount && duration_amount > $('#duration_minimum').text()) {
                $('#duration_amount').val(duration_amount);
            }
            make_price_request = 1;
            Defaults.remove('expiry_date', 'expiry_time', 'end_date');
            Durations.validateMinDurationAmount();
        }
        displayEquals(validated_value);

        return make_price_request;
    };

    const onDurationUnitChange = (value) => {
        const $duration_units = $('#duration_units');
        if (!value || !$duration_units.find(`option[value=${value}]`).length) {
            return 0;
        }

        $duration_units.val(value);
        Defaults.set('duration_units', value);

        Durations.selectUnit(value);
        Durations.populate();

        return 1;
    };

    return {
        displayEquals,
        processActiveSymbols,
        processMarket,
        processContract,
        processContractForm,
        forgetTradingStreams,
        onExpiryTypeChange,
        onDurationUnitChange,
    };
})();

module.exports = Process;