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

    <RelativeLayout
        android:id="@+id/searchBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:visibility="gone">

        <Button
            android:id="@+id/forth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/web_view_forth"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"/>

        <Button
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/web_view_back"
            android:layout_toLeftOf="@+id/forth"
            android:layout_toStartOf="@+id/forth"/>

        <EditText
            android:id="@+id/search"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:scrollHorizontally="true"
            android:inputType="text"
            android:hint="@string/web_view_search_hint"
            android:layout_toLeftOf="@+id/back"
            android:layout_toStartOf="@+id/back"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"/>

    </RelativeLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_above="@id/searchBar"
        android:layout_alignWithParentIfMissing="true"/>

    <FrameLayout
        android:id="@+id/webViewFrame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_above="@id/progressBar"
        android:layout_alignWithParentIfMissing="true"/>

</RelativeLayout>


text:
// Copyright 2021 Jon Skeet. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.

using Microsoft.Extensions.Logging;
using NodaTime;
using NodaTime.Text;
using OscMixerControl.Wpf.Models;

namespace OscMixerControl.Wpf.ViewModels
{
    public sealed class LogEntryViewModel
    {
        private static readonly DateTimeZone TimeZone = DateTimeZoneProviders.Bcl.GetSystemDefault();
        private static readonly LocalDateTimePattern TimestampPattern = LocalDateTimePattern.CreateWithInvariantCulture("HH:mm:ss");

        internal LogEntry Entry { get; }

        public string ToolTip { get; }
        public string Timestamp { get; }
        public string LevelText => FormatLevel(Entry.Level);
        public LogLevel Level => Entry.Level;
        public string Text { get; }

        internal LogEntryViewModel(LogEntry logEntry)
        {
            Entry = logEntry;
            Timestamp = TimestampPattern.Format(logEntry.Timestamp.InZone(TimeZone).LocalDateTime);
            Text = Entry.Exception is null ? Entry.Message : $"{Entry.Message}: {Entry.Exception.GetType()}; {Entry.Exception.Message}";
            ToolTip = Entry.Exception is null ? null : Entry.Exception.StackTrace;
        }

        private static string FormatLevel(LogLevel level) => level switch
        {
            LogLevel.Trace => "Trace",
            LogLevel.Debug => "Debug",
            LogLevel.Information => "Info",
            LogLevel.Warning => "Warn",
            LogLevel.Error => "Error",
            LogLevel.Critical => "Critical",
            LogLevel.None => "None",
            _ => "Unknown"
        };
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.motechproject.appointments.api.service.contract;

import org.junit.Before;
import org.junit.Test;
import org.motechproject.appointments.api.model.search.Criterion;
import org.motechproject.appointments.api.model.search.DueDateInCriterion;
import org.motechproject.appointments.api.model.search.MetadataCriterion;
import org.motechproject.appointments.api.model.search.UnvisitedCriterion;

import java.util.List;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

public class VisitsQueryTest {

    VisitsQuery visitsQuery;

    @Before
    public void before() {
        visitsQuery = new VisitsQuery();
    }

    @Test
    public void shouldQueryForVisitsWithDueDateInRange() {
        VisitsQuery query = visitsQuery.withDueDateIn(null, null);
        List<Criterion> criteria = query.getCriteria();
        assertEquals(criteria.size(), 1);
        assertTrue(criteria.get(0) instanceof DueDateInCriterion);
    }

    @Test
    public void shouldQueryForUnvisitedVisits() {
        VisitsQuery query = visitsQuery.unvisited();
        List<Criterion> criteria = query.getCriteria();
        assertEquals(criteria.size(), 1);
        assertTrue(criteria.get(0) instanceof UnvisitedCriterion);
    }

    @Test
    public void shouldQueryForVisitsUsingMetadata() {
        VisitsQuery query = visitsQuery.havingMetadata("foo", "bar");
        List<Criterion> criteria = query.getCriteria();
        assertEquals(1, criteria.size());
        assertTrue(criteria.get(0) instanceof MetadataCriterion);

    }

}


text:
require 'data_mapper/validation/rule'

module DataMapper
  module Validation
    class Rule

      class Presence < Rule

        def initialize(attribute_name, options = {})
          super

          @allow_nil   = false
          @allow_blank = false
        end

        # Boolean property types are considered present if non-nil.
        # Other property types are considered present if non-blank.
        # Non-properties are considered present if non-blank.
        def valid?(resource)
          value = resource.validation_property_value(attribute_name)

          boolean_type?(resource) ? !value.nil? : !DataMapper::Ext.blank?(value)
        end

        def violation_type(resource)
          boolean_type?(resource) ? :nil : :blank
        end

        # Is the property a boolean property?
        #
        # @return [Boolean]
        #   Returns true for Boolean, ParanoidBoolean, TrueClass and other
        #   properties. Returns false for other property types or for
        #   non-properties.
        #
        # @api private
        #
        # TODO: break this into concrete types and move the property check
        # into #initialize. Will require adding model to signature of #initialize
        def boolean_type?(resource)
          property = get_resource_property(resource, attribute_name)

          property ? property.load_as == TrueClass : false
        end

      end # class Presence

    end # class Rule
  end # module Validation
end # module DataMapper


text:
using PB.Frameworks.Common.Extensions;
using PB.Frameworks.Resources;
using System;
using System.Collections;
using System.Collections.Generic;

namespace PB.Frameworks.Common.General.Exceptions
{
	public static class ExceptionHelper
	{
		public static Exception BuildUtilsException(string msgName, params object[] args)
		{
			return BuildException(msgName, UtilsResource.ResourceManager.GetString(msgName), args);
		}

		public static Exception BuildTypesException(string msgName, params object[] args)
		{
			return BuildException(msgName, TypesResource.ResourceManager.GetString(msgName), args);
		}

		public static Exception BuildDALException(string msgName, params object[] args)
		{
			return BuildException(msgName, DataAccessLayerResource.ResourceManager.GetString(msgName), args);
		}

		public static Exception BuildBLLException(string msgName, params object[] args)
		{
			return BuildException(msgName, BusinessLogicLayerResource.ResourceManager.GetString(msgName), args);
		}

		private static Exception BuildException(string msgName, string msg, params object[] args)
		{
			var argsNew = args;
			if (args != null && args.Length > 0)
			{
				argsNew = new object[args.Length];
				for (int i = 0; i < args.Length; i++)
				{
					if (args[i] == null)
					{
						argsNew[i] = String.Empty;
					}
					else if (args[i] is IEnumerable && args[i].GetType() != typeof(string))
					{
						List<string> list = new List<string>(GlobalConsts.MAX_UI_ERROR_LIST + 1);
						foreach (object obj in args[i] as IEnumerable)
						{
							if (list.Count >= GlobalConsts.MAX_UI_ERROR_LIST)
							{
								list.Add(GlobalConsts.DOTDOTDOT + Environment.NewLine + UtilsResource.REFER_TO_EVENT_LOG);
								break;
							}
							list.Add(obj == null ? String.Empty : obj.ToString());
						}

						argsNew[i] = String.Join(",", list);
					}
					else
					{
						argsNew[i] = args[i].ToString();
					}
				}
			}
			var ex = new Exception(msg.FormatStr(argsNew));
			ex.Data.Add(GlobalConsts.EXCEPTION_MESSAGE_NAME_KEY, msgName);

			return ex;
		}
	}
}


text:
package com.thingtrack.konekti.dao.impl.internal;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.thingtrack.konekti.dao.template.JpaDao;
import com.thingtrack.konekti.dao.api.EmployeeAgentTypeDao;
import com.thingtrack.konekti.domain.EmployeeAgentType;
import com.thingtrack.konekti.domain.Organization;

/**
 * @author Thingtrack S.L.
 *
 */
@Repository
public class EmployeeAgentTypeDaoImpl extends JpaDao<EmployeeAgentType, Integer> implements EmployeeAgentTypeDao {
	@SuppressWarnings("unchecked")
	@Override
	public List<EmployeeAgentType> getAll(Organization organization) throws Exception {
		return (List<EmployeeAgentType>)getEntityManager()
				.createQuery("SELECT p FROM " + getEntityName() + " p WHERE p.organization = :organization")
				.setParameter("organization", organization).getResultList();

	}

	@Override
	public EmployeeAgentType getByName(String name) throws Exception {
		EmployeeAgentType employeeAgentType = (EmployeeAgentType)getEntityManager()
				.createQuery("SELECT p FROM " + getEntityName() + " p WHERE p.name = :name")
				.setParameter("name", name).getSingleResult();

		return employeeAgentType;

	}

}


text:
//kontroler za obnašanje about strani
scrumkin.controller('PBacklog', function($scope, $route, $http, $rootScope, $location, $anchorScroll, LoggedUserService,
    AcceptanceTestsService) {

    $scope.activeTab = 'unfinishedStories';

    //preverimo, ce je uporabnik logiran
    $rootScope.userLogged = false;
    $scope.user = LoggedUserService.getUserToken();
    $rootScope.usertypeDesc = 'User';

    if( typeof $scope.user === 'undefined'){
        $rootScope.userLogged = false;
        $location.path( "/Login" );
    }
    else{
        $rootScope.userLogged = true;
        $rootScope.userUname = $scope.user['username'];

        //pogledamo njegove pravice
        $rootScope.groups = $scope.user['groups'];
        $rootScope.usertype = $scope.groups[0]; //1: admin, 2:super, 3:normal

        $rootScope.isAdmin = false;
        if($rootScope.usertype === 1){
            $rootScope.isAdmin = true;
            $rootScope.usertypeDesc = 'Admin';
        }

        $rootScope.isSuper = false;
        if($rootScope.usertype === 2){
            $rootScope.isSuper = true;
            $rootScope.usertypeDesc = 'Super User';
        }
    }

    //ALI je izbran projekt za delo? - ce ne, redirect
    if(typeof $rootScope.currentProjectID === 'undefined' || $rootScope.currentProjectID === ''
            || $rootScope.currentProjectID === null){
        $location.path("/ChooseProject");
    }

    /*-----------------------------------------------------------*/

    // REST - vse zgodbe na izbranem projektu: $rootScope.currentProjectID
    $scope.allProjectStories = {};
    $scope.finishedStories = [];    //koncane zgodbe
    $scope.unfinishedAssignedStories = [];  //nedokoncane, dodeljene sprintu
    $scope.unfinishedNotAssignedStories = [];   //nedokoncane, niso dodeljene sprintu
    $scope.errTE = '';
    $scope.okTE = '';
    $scope.productBacklogLoader = false;

    if(typeof $rootScope.currentProjectID !== 'undefined' && $rootScope.currentProjectID !== ''
            && $rootScope.currentProjectID !== null){
        $scope.productBacklogLoader = true;
        $http({
            method: 'GET',
            url: '/api/project/'+parseInt($rootScope.currentProjectID)+'/stories'})
        .success(function(data, status, headers, config) {
            $scope.allProjectStories = data;
            //alert('All: ' + JSON.stringify(data));
            $scope.sortStories();
            $scope.productBacklogLoader = false;
        }).error(function(data, status, headers, config) {
            //alert("Error getting all stories of project: " + status);
            $scope.productBacklogLoader = false;
        });
    }
    else{
        //project ID undefined
    }

    $scope.removeWarningsUnfinishedStories = function(){
        $scope.errTE = '';
        $scope.okTE = '';
    };

    $scope.sortStories = function(){
        //filtriramo zgodbe najprej na finished/unfinished in pol na assigned/not assgined
        var dataLen = Object.keys($scope.allProjectStories).length;

        for(var i=0; i<dataLen; i++){
            $scope.currS = $scope.allProjectStories[i];

            //UREDIMO PODATKE
            //priority
            if($scope.currS['priority'] === 3){
                $scope.currS['priorityText'] = 'Must have';
            }
            else if($scope.currS['priority'] === 7){
               $scope.currS['priorityText'] = 'Should have';
            }
            else if($scope.currS['priority'] === 6){
                $scope.currS['priorityText'] = 'Could have';
            }
            else {
                $scope.currS['priorityText'] = "Won't have this time";
            }

            //$scope.currS['comments'] = StoryService.getStoryComment($scope.currS);

            //acceptance tests
            $scope.accTests = $scope.currS['acceptenceTests'];  //tabela z id-ji testov tega story-ja [12,13]
            $scope.currS['acceptenceTestsText'] = [];
            for(var j=0; j<$scope.accTests.length; j++){
                $scope.currTestID = $scope.accTests[j];
                $scope.rez = AcceptanceTestsService.getAccTest($scope.currS['id'], $scope.currTestID);
                $scope.currS['acceptenceTestsText'].push($scope.rez['test']);
            }

            $scope.currS['finished'] = AcceptanceTestsService.isStoryFinished($scope.currS);
            if($scope.currS['finished']){
                //finished
                $scope.finishedStories.push($scope.currS);
            }
            else{
                //not finished - assigned/not assigned
                if($scope.currS['sprint'] === 0){
                    $scope.unfinishedNotAssignedStories.push($scope.currS);
                }
                else{
                    $scope.unfinishedAssignedStories.push($scope.currS);
                }
            }

        }
    };

    $scope.changeTimeEstimate = function(newTimeEstimate, story){
        //iz all project stories potegnemo originalno zgodbo
        var id = story['id'];
        var editedStory = {};
        var dataLen = Object.keys($scope.allProjectStories).length;
        for(var i=0; i<dataLen; i++){
            var cs = $scope.allProjectStories[i];
            if(cs['id'] === id){
                editedStory = cs;
                break;
            }
        }

        if(typeof newTimeEstimate === 'undefined' || newTimeEstimate === '' || newTimeEstimate === null){
            //ali je timeEstimate definiran
            $scope.errTE = 'You have to enter a new Time Estimate!';
            $scope.okTE = '';
        }
        else{
            //ali je time estimate pozitivna cela ali decimalna stevilka
            if (newTimeEstimate.indexOf(",") > -1 || newTimeEstimate.indexOf("-") > -1
                    || !validateEntry(newTimeEstimate, /^\d{0,3}(\.\d{0,4}){0,1}$/)){
                $scope.errTE = 'New time estimate must be an integer or a double, separated by "." !';
                $scope.okTE = '';
            }
            else{
                var temp = parseFloat(newTimeEstimate);
                var temp1 = temp.toFixed(1);        //zaokrozimo in to shranimo
                story['estimatedTime'] = parseFloat(temp1);     //shranimo objekt story v bazo

                var storyToUpdate = {
                    /*"id": story['id'],
                    "title": story['title'],
                    "story": story['story'],
                    "bussinessValue": story['bussinessValue'],*/
                    "estimatedTime": story['estimatedTime']/*,
                    "acceptenceTests": story['acceptenceTests'],
                    "tasks": story['tasks'],
                    "priority": story['priority'],
                    "project": story['project'],
                    "sprint": story['sprint']*/};

                //REST - update izbranega story-ja z novo time estimate vrednostjo
                if(typeof story['id'] !== 'undefined' && story['id'] !== '' && story['id'] !== null){
                    $http({
                    method: 'PUT',
                    url: '/api/userStories/'+story['id'],
                    data: storyToUpdate,
                    headers: {'Content-Type': 'application/json'}})
                        .success(function(data, status, headers, config) {
                            $scope.errTE = '';
                            $scope.okTE = 'Time estimate succesfuly updated!';
                            var els = document.getElementsByClassName('newEstimate');
                            for(var k=0; k<els.length; k++){
                                document.getElementsByClassName('newEstimate')[k].value = '';
                            }
                        }).error(function(data, status, headers, config) {
                            $scope.errTE = 'Error updating time estimate: ' + status;
                            $scope.okTE = '';
                    });
                }
                else{
                    //undefined story id
                }
            }
        }
    };

});

function validateEntry(stringEntry, regex){
    if(typeof stringEntry !== "undefined"){
        if(stringEntry.match(regex)){
            return true;
        }
        else{ return false; }
    }
    else{
        return false;
    }
}


text:
class CPPRESTSHARED_EXPORT ServerWrapper : public QObject
{
    Q_OBJECT

public:
	ServerWrapper(const quint16& port, const bool& insecure = false);
	bool isRunning() const;

private:
	SslServer *server_;
	bool is_running_;
};

#endif // SERVERWRAPPER_H


text:
import os
import re
import codecs

# NOTE: Apparently setuptools "ruins the universe"; be cautious with continued use

try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup

# Utility Code ----------------------------------------------------------------
'''Add to utils'''
here = os.path.abspath(os.path.dirname(__file__))          # REF 024

def read(*parts):
    '''Read the files (REF 024)'''
    # Intentionally *not* adding an encoding option to open, See:
    # https://github.com/pypa/virtualenv/issues/201#issuecomment-3145690
    return codecs.open(os.path.join(here, *parts), 'r').read()

def find_version(*file_paths):
    '''Extract version string (REF 024)'''
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")

# -----------------------------------------------------------------------------
NAME = 'lamana'
VERSION = find_version(NAME, '__init__.py')
URL = 'https://github.com/par2/lamana'

setup(
    name=NAME,
    version=VERSION,
    description='An extensible Python package for laminate analysis',
    author='P. Robinson II',
    author_email='par2.get@gmail.com',
    url=URL,
    download_url='/'.join([URL, 'tarball', VERSION]),
    ##download_url='https://github.com/par2/lamana/tarball/0.4.9-dev',
    # Search all sub directories; specifics commented below
    packages=find_packages(),
    #packages=['lamana', 'lamana.models', 'lamana.utils', 'lamana.tests',
    #          'lamana.tests.controls_LT', 'lamana.models.tests'],
    # Include everything in source control or MANIFEST.in
    # MANIFEST.in is required to add files to source distributions
    include_package_data=True,
    # Required to add files to wheels
    package_data={
        # Include root level items
        # (Uncertain how this is added to wheels...)
        '': ['LICENSE', 'requirements.txt'],
        # Include test *.py files and *.csv files in 'controls_LT' directory
        'lamana': ['tests/*.py', 'tests/controls_LT/*.csv'],
    },
    # Install latest dependencies; "hands-off" approach
    # Invoke `-r requirements.txt` to install pinned dependencies; "hands-on" approach
    install_requires=[
        'numpy',
        'matplotlib',
        'pandas',
        'openpyxl',
        'xlrd',
        'six',
    ],
    keywords=['laminate analysis', 'visualization'],
    license='BSD',
    classifiers=[
        'Framework :: IPython',
        'Intended Audience :: Science/Research',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
    ],
)

# References
# ----- ---------                           -------------
# (001) PyPI Tutorial                       http://peterdowns.com/posts/first-time-with-pypi.html
# (002) Git tagging                         https://git-scm.com/book/en/v2/Git-Basics-Tagging
# (003) Remove remote tag                   https://nathanhoad.net/how-to-delete-a-remote-git-tag
# (004) Create package                      http://zetcode.com/articles/packageinpython/
# (005) Detailed package guide              https://python-packaging-user-guide.readthedocs.org/en/latest/
# (006) Updated guide: twine, pip, wheel    http://joebergantine.com/blog/2015/jul/17/releasing-package-pypi/
# (007) packages                            Python Cookbook, 3rd ed, p. 435
# (008) install_requires                    https://python-packaging-user-guide.readthedocs.org/en/latest/requirements/
# (009) distutils vs. setuptools            http://stackoverflow.com/questions/25337706/setuptools-vs-distutils-why-is-distutils-still-a-thing
# (010) Pinning Dependencies                http://nvie.com/posts/pin-your-packages/
# (011) Improved Package Management         http://nvie.com/posts/better-package-management/
# (012) Modified BSD License                https://opensource.org/licenses/BSD-3-Clause
# (013) On package_data                     https://pythonhosted.org/setuptools/setuptools.html#including-data-files
# (014) find_version code                   https://github.com/pypa/pip/blob/develop/setup.py
# (015) Use pkg_resources to find version   https://stackoverflow.com/questions/2058802/how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package


text:
namespace dotless.Core
{
    using Abstractions;
    using Input;
    using Response;
    using System.IO;

    public class HandlerImpl
    {
        public readonly IHttp Http;
        public readonly IResponse Response;
        public readonly ILessEngine Engine;
        public readonly IFileReader FileReader;

        public HandlerImpl(IHttp http, IResponse response, ILessEngine engine, IFileReader fileReader)
        {
            Http = http;
            Response = response;
            Engine = engine;
            FileReader = fileReader;
        }

        public void Execute()
        {
            var localPath = Http.Context.Request.PhysicalApplicationPath + Http.Context.Request.Url.LocalPath.Replace('/', Path.DirectorySeparatorChar);

            var source = FileReader.GetFileContents(localPath);

            Response.WriteCss(Engine.TransformToCss(source, localPath));
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/seagreen"
    android:orientation="horizontal">

    <Button
        android:id="@+id/back"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/button_click"
        android:drawableStart="@drawable/ic_action_arrow_left"
        android:gravity="start"
        android:padding="10dp"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/button_click"
        android:drawableEnd="@drawable/ic_action_search" />

    <Button
        android:id="@+id/bookmark"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@drawable/button_click"
        android:drawableEnd="@drawable/ic_action_bookmark" />

</LinearLayout>


text:
/**
 * @module 1-liners/isString
 *
 * @description
 *
 * Same as `typeof value === 'string'`.
 *
 * @example
 *
 * 	var isString = require('1-liners/isString');
 *
 * 	isString('');               // => true
 * 	isString('anything');       // => true
 *
 * 	isString(/anything else/);  // => false
 *
 */
export default (value) => typeof value === 'string';


text:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';

export default Model.extend({
  description: attr('string'),
  name: attr('string'),
  slug: attr('string'),

  projects: hasMany('project', { async: true }),
  projectCategories: hasMany('project-category', { async: true }),
  userCategories: hasMany('user-category', { async: true })
});


text:
const { app } = require('electron')
const path = require('path')
const fs = require('fs')
const crypto = require('crypto')
const rimraf = require('rimraf')

const CONFIG_FILE_PATH = path.resolve(app.getPath('home'), '.weibotuchuang')
const CONFIG_SECRET = '今天天气不错'

const storage = {}

try {
  const stat = fs.lstatSync(CONFIG_FILE_PATH)
  if (!stat.isFile()) rimraf.sync(CONFIG_FILE_PATH)
} catch (e) {}

try {
  Object.assign(
    storage,
    JSON.parse(decode(String(fs.readFileSync(CONFIG_FILE_PATH))))
  )
} catch (e) {}

const sync = exports.sync = () => {
  fs.writeFileSync(CONFIG_FILE_PATH, encode(JSON.stringify(storage)))
}

exports.get = key => storage[key]

exports.getObject = () => storage

exports.set = (key, value) => {
  if (typeof key === 'object') {
    Object.assign(storage, key)
  } else {
    storage[key] = value
  }
  sync()
}
exports.remove = key => {
  delete storage[key]
  sync()
}

function encode (str) {
  var cipher = crypto.createCipher('aes192', CONFIG_SECRET)
  var enc = cipher.update(str, 'utf8', 'hex')
  return enc + cipher.final('hex')
}

function decode (str) {
  var decipher = crypto.createDecipher('aes192', CONFIG_SECRET)
  var dec = decipher.update(str, 'hex', 'utf8')
  return dec + decipher.final('utf8')
}


text:
package global.namespace.truelicense.core.misc;

import java.util.Locale;

/**
 * Provides static functions for nullable strings.
 * This class is trivially immutable.
 */
public class Strings {

    public static boolean equalsIgnoreCase(String a, String b) { return null == a ? null == b : a.equalsIgnoreCase(b); }

    public static String toLowerCase(String s, Locale l) { return null == s ? null : s.toLowerCase(l); }

    public static String toUpperCase(String s, Locale l) { return null == s ? null : s.toUpperCase(l); }

    public static String requireNonEmpty(final String s) {
        if (s.isEmpty()) {
            throw new IllegalArgumentException();
        }
        return s;
    }

    private Strings() { }
}


text:
using System;
using Azure.Core;

namespace Azure.AI.MetricsAdvisor.Models
{
    /// <summary> The Dimension. </summary>
    public partial class DataFeedDimension
    {

        /// <summary> Initializes a new instance of DataFeedDimension. </summary>
        /// <param name="name"> dimension name. </param>
        /// <param name="displayName"> dimension display name. </param>
        internal DataFeedDimension(string name, string displayName)
        {
            Name = name;
            DisplayName = displayName;
        }
    }
}


text:
import debug from './../debug';

export default (path) => debug(`breadcrumb-actions/${path}`);


text:
package org.babblelang.engine.impl.natives.java;

import org.babblelang.engine.BabbleException;
import org.babblelang.engine.impl.Scope;
import org.babblelang.engine.impl.Slot;

import java.util.HashMap;
import java.util.Map;

public class JavaObject implements Scope<BoundJavaMethod> {
    private final JavaClass clazz;
    private final Object value;
    private final Map<String, Slot<BoundJavaMethod>> members = new HashMap<>();

    JavaObject(JavaClass clazz, Object value) {
        this.clazz = clazz;
        this.value = value;
    }

    public Slot<BoundJavaMethod> define(String key, boolean isFinal) {
        throw new BabbleException("Cannot define anything in a Java instance");
    }

    public boolean isDeclared(String key) {
        return clazz.isDeclared(key);
    }

    public Slot<BoundJavaMethod> get(String key) {
        return members.computeIfAbsent(key, k -> {
            Slot<BoundJavaMethod> slot = new Slot<>(k, true);
            JavaMethod result = (JavaMethod) clazz.get(k).get();
            slot.set(new BoundJavaMethod(result, value));
            return slot;
        });
    }
}


text:
package org.apereo.openlrs.model.statement;

import com.fasterxml.jackson.annotation.JsonIgnoreType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

/**
 * @author ggilbert
 *
 */
@JsonInclude(Include.NON_NULL)

public class XApiScore {
	private Double scaled;
	private Double raw;
	private Double min;
	private Double max;
	private int id;
	private XApiResult result;
	public int getId() {
	return id;
	}

	public XApiResult getResult() {
		return result;
	}

	public void setResult(XApiResult result) {
		this.result = result;
	}

	public void setId(int id) {
		this.id = id;
	}
	/**
	 * @return the scaled
	 */
	public Double getScaled() {
		return scaled;
	}
	/**
	 * @param scaled the scaled to set
	 */
	public void setScaled(Double scaled) {
		this.scaled = scaled;
	}
	/**
	 * @return the raw
	 */
	public Double getRaw() {
		return raw;
	}
	/**
	 * @param raw the raw to set
	 */
	public void setRaw(Double raw) {
		this.raw = raw;
	}
	/**
	 * @return the min
	 */
	public Double getMin() {
		return min;
	}
	/**
	 * @param min the min to set
	 */
	public void setMin(Double min) {
		this.min = min;
	}
	/**
	 * @return the max
	 */
	public Double getMax() {
		return max;
	}
	/**
	 * @param max the max to set
	 */
	public void setMax(Double max) {
		this.max = max;
	}
}


text:
@class Program;

#include "aiMaterial.h"

@interface Material : NSObject {
    GLuint texture, bumpmap;
}

@property (readonly) GLuint texture, bumpmap;

+ (id) materialWithAsset:(const aiMaterial *)asset;
- (id) initWithAsset:(const aiMaterial *)asset;
- (void) dealloc;

- (BOOL) loadTexture:(NSString *)path;
- (GLuint) texture:(int)num
            ofType:(aiTextureType)type
         fromAsset:(const aiMaterial *)asset;

- (void) apply;

@end


text:
#include <wchar.h>

unsigned long long wcstoull(const wchar_t *_Restrict nptr, wchar_t **_Restrict endptr, int base) {

    anvil_syslog(0, "%s unimplemented\n", __FUNCTION__);
    while (1);
    return 0;
}


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

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

import org.camunda.bpm.engine.impl.util.json.JSONArray;
import org.camunda.bpm.engine.impl.util.json.JSONObject;

/**
 * @author Thorben Lindhauer
 */
public class JsonArrayOfObjectsConverter<T> extends JsonArrayConverter<List<T>> {

  protected JsonObjectConverter<T> objectConverter;

  public JsonArrayOfObjectsConverter(JsonObjectConverter<T> objectConverter) {
    this.objectConverter = objectConverter;
  }

  public JSONArray toJsonArray(List<T> objects) {
    JSONArray jsonArray = new JSONArray();

    for (T object : objects) {
      JSONObject jsonObject = objectConverter.toJsonObject(object);
      jsonArray.put(jsonObject);
    }

    return jsonArray;
  }

  public List<T> toObject(JSONArray jsonArray) {
    List<T> result = new ArrayList<T>();
    for (int i = 0; i < jsonArray.length(); i++) {
      T object = objectConverter.toObject(jsonArray.getJSONObject(i));
      result.add(object);
    }

    return result;
  }
}


text:
class TcpSocketPort : public Port
{
	SOCKET sock = INVALID_SOCKET;
	sockaddr_in serveraddr;
	sockaddr_in other;
	int addrlen = sizeof(sockaddr_in);
	int serverport = -1;

public:

	static HRESULT Initialize();

	// Connect the TCP socket to the given server & port.
	HRESULT Connect(const char* serverIp, int serverPort);

	// write to the socket
	HRESULT Write(const BYTE* ptr, int count);

	// read a given number of bytes from the socket.
	HRESULT Read(BYTE* buffer, int bytesToRead, int* bytesRead);

	// close the socket.
	void Close();
};

#endif // !SOCKETPORT_H


text:
package com.alliander.osgp.domain.core.validation;

import java.util.Collection;
import java.util.Map;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class MapValueRangeValidator implements ConstraintValidator<MapValueRange, Map<?, Integer>> {

    private int min;
    private int max;

    @Override
    public void initialize(final MapValueRange constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(final Map<?, Integer> map, final ConstraintValidatorContext context) {
        if (map == null) {
            return true;
        }

        final Collection<Integer> values = map.values();

        for (final Integer value : values) {
            if (value < this.min || value > this.max) {
                return false;
            }
        }

        return true;
    }
}


text:
package biz.r2s.scaffolding.meta;
/**
 * Created by raphael on 24/07/15.
 */
public class TitleScaffold {
    String name;
    String subTitle;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSubTitle() {
		return subTitle;
	}
	public void setSubTitle(String subTitle) {
		this.subTitle = subTitle;
	}

}


text:
package org.apache.harmony.jndi.tests.javax.naming.spi.mock.news;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;

// import util.Log;

/**
 * Always return null.
 */
public class newsURLContextFactory implements ObjectFactory {
	public Object getObjectInstance(Object o, Name n, Context c, Hashtable<?, ?> h)
			throws Exception {
		return null;
	}

}


text:
<?php
/**
 * Generated by Protobuf protoc plugin.
 *
 * File descriptor : POGOProtos/Data/Battle/BattleActionType.proto
 */

namespace POGOProtos\Data\Battle;

/**
 * Protobuf enum : POGOProtos.Data.Battle.BattleActionType
 */
class BattleActionType extends \Protobuf\Enum
{

    /**
     * ACTION_UNSET = 0
     */
    const ACTION_UNSET_VALUE = 0;

    /**
     * ACTION_ATTACK = 1
     */
    const ACTION_ATTACK_VALUE = 1;

    /**
     * ACTION_DODGE = 2
     */
    const ACTION_DODGE_VALUE = 2;

    /**
     * ACTION_SPECIAL_ATTACK = 3
     */
    const ACTION_SPECIAL_ATTACK_VALUE = 3;

    /**
     * ACTION_SWAP_POKEMON = 4
     */
    const ACTION_SWAP_POKEMON_VALUE = 4;

    /**
     * ACTION_FAINT = 5
     */
    const ACTION_FAINT_VALUE = 5;

    /**
     * ACTION_PLAYER_JOIN = 6
     */
    const ACTION_PLAYER_JOIN_VALUE = 6;

    /**
     * ACTION_PLAYER_QUIT = 7
     */
    const ACTION_PLAYER_QUIT_VALUE = 7;

    /**
     * ACTION_VICTORY = 8
     */
    const ACTION_VICTORY_VALUE = 8;

    /**
     * ACTION_DEFEAT = 9
     */
    const ACTION_DEFEAT_VALUE = 9;

    /**
     * ACTION_TIMED_OUT = 10
     */
    const ACTION_TIMED_OUT_VALUE = 10;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_UNSET = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_ATTACK = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_DODGE = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_SPECIAL_ATTACK = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_SWAP_POKEMON = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_FAINT = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_PLAYER_JOIN = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_PLAYER_QUIT = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_VICTORY = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_DEFEAT = null;

    /**
     * @var \POGOProtos\Data\Battle\BattleActionType
     */
    protected static $ACTION_TIMED_OUT = null;

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_UNSET()
    {
        if (self::$ACTION_UNSET !== null) {
            return self::$ACTION_UNSET;
        }

        return self::$ACTION_UNSET = new self('ACTION_UNSET', self::ACTION_UNSET_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_ATTACK()
    {
        if (self::$ACTION_ATTACK !== null) {
            return self::$ACTION_ATTACK;
        }

        return self::$ACTION_ATTACK = new self('ACTION_ATTACK', self::ACTION_ATTACK_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_DODGE()
    {
        if (self::$ACTION_DODGE !== null) {
            return self::$ACTION_DODGE;
        }

        return self::$ACTION_DODGE = new self('ACTION_DODGE', self::ACTION_DODGE_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_SPECIAL_ATTACK()
    {
        if (self::$ACTION_SPECIAL_ATTACK !== null) {
            return self::$ACTION_SPECIAL_ATTACK;
        }

        return self::$ACTION_SPECIAL_ATTACK = new self('ACTION_SPECIAL_ATTACK', self::ACTION_SPECIAL_ATTACK_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_SWAP_POKEMON()
    {
        if (self::$ACTION_SWAP_POKEMON !== null) {
            return self::$ACTION_SWAP_POKEMON;
        }

        return self::$ACTION_SWAP_POKEMON = new self('ACTION_SWAP_POKEMON', self::ACTION_SWAP_POKEMON_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_FAINT()
    {
        if (self::$ACTION_FAINT !== null) {
            return self::$ACTION_FAINT;
        }

        return self::$ACTION_FAINT = new self('ACTION_FAINT', self::ACTION_FAINT_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_PLAYER_JOIN()
    {
        if (self::$ACTION_PLAYER_JOIN !== null) {
            return self::$ACTION_PLAYER_JOIN;
        }

        return self::$ACTION_PLAYER_JOIN = new self('ACTION_PLAYER_JOIN', self::ACTION_PLAYER_JOIN_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_PLAYER_QUIT()
    {
        if (self::$ACTION_PLAYER_QUIT !== null) {
            return self::$ACTION_PLAYER_QUIT;
        }

        return self::$ACTION_PLAYER_QUIT = new self('ACTION_PLAYER_QUIT', self::ACTION_PLAYER_QUIT_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_VICTORY()
    {
        if (self::$ACTION_VICTORY !== null) {
            return self::$ACTION_VICTORY;
        }

        return self::$ACTION_VICTORY = new self('ACTION_VICTORY', self::ACTION_VICTORY_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_DEFEAT()
    {
        if (self::$ACTION_DEFEAT !== null) {
            return self::$ACTION_DEFEAT;
        }

        return self::$ACTION_DEFEAT = new self('ACTION_DEFEAT', self::ACTION_DEFEAT_VALUE);
    }

    /**
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function ACTION_TIMED_OUT()
    {
        if (self::$ACTION_TIMED_OUT !== null) {
            return self::$ACTION_TIMED_OUT;
        }

        return self::$ACTION_TIMED_OUT = new self('ACTION_TIMED_OUT', self::ACTION_TIMED_OUT_VALUE);
    }

    /**
     * @param int $value
     * @return \POGOProtos\Data\Battle\BattleActionType
     */
    public static function valueOf($value)
    {
        switch ($value) {
            case 0: return self::ACTION_UNSET();
            case 1: return self::ACTION_ATTACK();
            case 2: return self::ACTION_DODGE();
            case 3: return self::ACTION_SPECIAL_ATTACK();
            case 4: return self::ACTION_SWAP_POKEMON();
            case 5: return self::ACTION_FAINT();
            case 6: return self::ACTION_PLAYER_JOIN();
            case 7: return self::ACTION_PLAYER_QUIT();
            case 8: return self::ACTION_VICTORY();
            case 9: return self::ACTION_DEFEAT();
            case 10: return self::ACTION_TIMED_OUT();
            default: return null;
        }
    }

}


text:
[![Code Climate](https://codeclimate.com/github/kaspernj/baza_migrations/badges/gpa.svg)](https://codeclimate.com/github/kaspernj/baza_migrations)
[![Test Coverage](https://codeclimate.com/github/kaspernj/baza_migrations/badges/coverage.svg)](https://codeclimate.com/github/kaspernj/baza_migrations)
[![Build Status](https://img.shields.io/shippable/54f837035ab6cc135292f855.svg)](https://app.shippable.com/projects/54f837035ab6cc135292f855/builds/latest)

# baza_migrations

Migrations support for the Baza database framework in Ruby.

## Usage

```ruby
executor = BazaMigrations::MigrationsExecutor.new(db: db)
executor.add_dir("spec/dummy/db/baza_migrate")
executor.execute_migrations
```

```bash
rake baza:db:migrate
rake baza:db:rollback
```

## Contributing to baza_migrations

* Check out the latest master to make sure the feature hasn't been implemented or the bug hasn't been fixed yet.
* Check out the issue tracker to make sure someone already hasn't requested it and/or contributed it.
* Fork the project.
* Start a feature/bugfix branch.
* Commit and push until you are happy with your contribution.
* Make sure to add tests for it. This is important so I don't break it in a future version unintentionally.
* Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

## Copyright

Copyright (c) 2015 kaspernj. See LICENSE.txt for
further details.


text:
using System.Linq;
using System.Reflection;

namespace OpenNLP.Tools
{
    /// <summary>
    /// The comprehensive list of all the parts of speech.
    /// </summary>
    public static class PartsOfSpeech
    {
        // List of all parts of speech ---------------------------------------

        // verbs
        public const string VerbBaseForm = "VB";
        public const string VerbNon3rdPersSingPresent = "VBP";
        public const string Verb3rdPersSingPresent = "VBZ";
        public const string VerbPastTense = "VBD";
        public const string VerbGerundOrPresentParticiple = "VBG";
        public const string VerbPastParticiple = "VBN";
        // adjectives
        public const string Adjective = "JJ";
        public const string AdjectiveComparative = "JJR";
        public const string AdjectiveSuperlative = "JJS";
        // nouns
        public const string NounSingularOrMass = "NN";
        public const string NounPlural = "NNS";
        public const string ProperNounSingular = "NNP";
        public const string ProperNounPlural = "NNPS";
        // adverbs
        public const string WhAdverb = "WRB";
        public const string Adverb = "RB";
        public const string AdverbComparative = "RBR";
        public const string AdverbSuperlative = "RBS";
        // conjunctions
        public const string CoordinatingConjunction = "CC";
        public const string PrepositionOrSubordinateConjunction = "IN";
        // pronouns
        public const string WhPronoun = "WP";
        public const string PossessiveWhPronoun = "WP$";
        public const string PersonalPronoun = "PRP";
        public const string PossessivePronoun = "PRP$";
        // misc
        public const string Particle = "RP";
        public const string CardinalNumber = "CD";
        public const string Determiner = "DT";
        public const string To = "TO";
        public const string ExistentialThere = "EX";
        public const string Interjection = "UH";
        public const string ForeignWord = "FW";
        public const string ListItemMarker = "LS";
        public const string Modal = "MD";
        public const string WhDeterminer = "WDT";
        public const string Predeterminer = "PDT";
        // punctuation
        public const string LeftOpenDoubleQuote = "``";
        public const string PossessiveEnding = "POS";
        public const string Comma = ",";
        public const string RightCloseDoubleQuote = "''";
        public const string SentenceFinalPunctuation = ".";
        public const string ColonSemiColon = ":";
        public const string LeftParenthesis = "-LRB";
        public const string RightParenthesis = "-RRB";
        // symbols
        public const string DollarSign = "$";
        public const string PoundSign = "#";
        public const string Symbol = "SYM";

        // Utilities -------------------------------------------------------

        /// <summary>
        /// Returns true if the pos corresponds to a verb
        /// (base form, present form non 3rd, present form 3rd, past form,
        /// present particle/gerundive or past participle).
        /// Return false otherwise.
        /// </summary>
        public static bool IsVerb(string pos)
        {
            return !string.IsNullOrEmpty(pos) && pos.StartsWith("VB");
        }

        /// <summary>
        /// Returns true if the pos corresponds to a noun (plural, singular or proper).
        /// Returns false otherwise.
        /// </summary>
        public static bool IsNoun(string pos)
        {
            return !string.IsNullOrEmpty(pos) && pos.StartsWith("NN");
        }

        /// <summary>
        /// Returns true if the pos corresponds to a proper noun (plural or singular).
        /// Returns false otherwise.
        /// </summary>
        public static bool IsProperNoun(string pos)
        {
            return !string.IsNullOrEmpty(pos) && pos.StartsWith("NNP");
        }

        /// <summary>
        /// Returns true if the pos corresponds to an adjective
        /// (regular, comparative or superlative).
        /// Returns false otherwise.
        /// </summary>
        public static bool IsAdjective(string pos)
        {
            return !string.IsNullOrEmpty(pos) && pos.StartsWith("JJ");
        }

        /// <summary>
        /// Returns true if the pos corresponds to a personnal or possessive pronoun.
        /// Returns false otherwise.
        /// </summary>
        public static bool IsPersOrPossPronoun(string tag)
        {
            return !string.IsNullOrEmpty(tag) && tag.StartsWith("PRP");
        }

        /// <summary>
        /// Writes the part of speech to be human understandable
        /// </summary>
        public static string Write(string pos)
        {
            var fields = typeof(PartsOfSpeech).GetTypeInfo().DeclaredFields;
            foreach (FieldInfo fieldInfo in fields)
            {
                var value = (string)fieldInfo.GetValue(null);
                if (value == pos)
                {
                    return fieldInfo.Name;
                }
            }
            return string.Format("Unsupported function abbreviation ({0})", pos);
        }

        /// <summary>
        /// Checks if a string corresponds to a supported part of speech
        /// </summary>
        public static bool IsSupportedPartOfSpeech(string function)
        {
            var fields = typeof(PartsOfSpeech).GetTypeInfo().DeclaredFields;
            return fields
                .Select(fieldInfo => (string) fieldInfo.GetValue(null))
                .Any(value => value == function);
        }
    }
}


text:
package org.sagebionetworks.repo.model.dbo.asynch;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;

import javax.annotation.Resource;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.sagebionetworks.repo.model.AuthorizationConstants.BOOTSTRAP_PRINCIPAL;
import org.sagebionetworks.repo.model.DatastoreException;
import org.sagebionetworks.repo.model.TermsOfUseException;
import org.sagebionetworks.repo.model.asynch.AsynchJobState;
import org.sagebionetworks.repo.model.asynch.AsynchronousJobStatus;
import org.sagebionetworks.repo.model.dao.asynch.AsynchronousJobStatusDAO;
import org.sagebionetworks.repo.model.table.TableUpdateTransactionRequest;
import org.sagebionetworks.repo.model.table.TableUpdateTransactionResponse;
import org.sagebionetworks.repo.model.table.UploadToTableRequest;
import org.sagebionetworks.repo.model.table.UploadToTableResult;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.util.ThreadStepper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = { "classpath:jdomodels-test-context.xml" })
public class AsynchJobStatusDaoImplTest {

	@Autowired
	AsynchronousJobStatusDAO asynchJobStatusDao;

	@Resource(name = "txManager")
	private PlatformTransactionManager transactionManager;

	private Long creatorUserGroupId;

	TableUpdateTransactionRequest body;

	TableUpdateTransactionResponse response;

	@BeforeEach
	public void before(){
		UploadToTableRequest uploadToTableRequest = new UploadToTableRequest();
		uploadToTableRequest.setTableId("syn456");
		uploadToTableRequest.setUploadFileHandleId("123");
		body = new TableUpdateTransactionRequest();
		body.setEntityId("syn456");
		body.setChanges(Collections.singletonList(uploadToTableRequest));

		response = new TableUpdateTransactionResponse();
		UploadToTableResult uploadToTableResult = new UploadToTableResult();
		uploadToTableResult.setRowsProcessed(7L);
		response.setResults(Collections.singletonList(uploadToTableResult));

		creatorUserGroupId = BOOTSTRAP_PRINCIPAL.THE_ADMIN_USER.getPrincipalId();
		assertNotNull(creatorUserGroupId);
	}

	@AfterEach
	public void after(){
		asynchJobStatusDao.truncateAllAsynchTableJobStatus();
	}

	@Test
	public void testUploadCreateGet() throws DatastoreException, NotFoundException{
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status.getJobId());
		assertNotNull(status.getEtag());
		assertNotNull(status.getChangedOn());
		assertNotNull(status.getStartedOn());
		assertNull(status.getErrorDetails());
		assertNull(status.getErrorMessage());
		assertNotNull(status.getRuntimeMS());
		assertEquals(AsynchJobState.PROCESSING, status.getJobState());
		assertEquals(creatorUserGroupId, status.getStartedByUserId());
		assertEquals(body, status.getRequestBody());

		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals(status, clone);
	}

	@Test
	public void testNotFound() throws DatastoreException, NotFoundException{
		String message = assertThrows(NotFoundException.class, ()->{
			asynchJobStatusDao.getJobStatus("-99");
		}).getMessage();
		assertEquals("Asynchronous job: '-99' does not exist", message);
	}

	@Test
	public void testUpdateProgress() throws DatastoreException, NotFoundException, InterruptedException{
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		// sleep to increase elapse time
		Thread.sleep(1);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		// update the progress
		asynchJobStatusDao.updateJobProgress(status.getJobId(), 0L, 1000L, "A MESSAGE");
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals(new Long(0), clone.getProgressCurrent());
		assertEquals(new Long(1000), clone.getProgressTotal());
		assertEquals("A MESSAGE", clone.getProgressMessage());
		assertEquals(body, status.getRequestBody());
		assertEquals(AsynchJobState.PROCESSING, status.getJobState());
		assertNotNull(clone.getRuntimeMS());
		assertTrue(clone.getRuntimeMS() > 0L);
	}

	@Test
	public void testUpdateProgressNotProcessing() throws DatastoreException, NotFoundException {
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		// update the progress
		asynchJobStatusDao.updateJobProgress(status.getJobId(), 0L, 1000L, "A MESSAGE");
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals("A MESSAGE", clone.getProgressMessage());
		assertEquals(AsynchJobState.PROCESSING, status.getJobState());

		String requestHash = null;
		asynchJobStatusDao.setComplete(status.getJobId(), response, requestHash);
		clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals("Complete", clone.getProgressMessage());
		assertEquals(AsynchJobState.COMPLETE, clone.getJobState());

		asynchJobStatusDao.updateJobProgress(status.getJobId(), 3L, 2000L, "A MESSAGE2");
		clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals("Complete", clone.getProgressMessage());
	}

	@Test
	public void testUpdateProgressDuringTransaction() throws Exception {
		final AtomicReference<String> jobId = new AtomicReference<String>();

		final ThreadStepper stepper = new ThreadStepper(20);

		stepper.add(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				DefaultTransactionDefinition transactionDef = new DefaultTransactionDefinition();
				transactionDef.setReadOnly(false);
				transactionDef.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
				transactionDef.setName("Test");
				TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager, transactionDef);

				transactionTemplate.execute(new TransactionCallback<String>() {
					@Override
					public String doInTransaction(TransactionStatus tStatus) {
						AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
						assertNotNull(status);
						assertNotNull(status.getEtag());
						jobId.set(status.getJobId());

						stepper.stepDone("job started");
						stepper.waitForStepDone("get status initial");

						asynchJobStatusDao.updateJobProgress(status.getJobId(), 0L, 1000L, "A MESSAGE");

						stepper.stepDone("progress reported 1");
						stepper.waitForStepDone("get status 1");

						asynchJobStatusDao.updateJobProgress(status.getJobId(), 0L, 1000L, "A MESSAGE2");

						stepper.stepDone("progress reported 2");
						stepper.waitForStepDone("get status 2");

						String requestHash = null;
						asynchJobStatusDao.setComplete(status.getJobId(), response, requestHash);

						stepper.stepDone("job completed");
						stepper.waitForStepDone("get status completed in transaction");

						return "";
					}
				});

				stepper.stepDone("out of transaction");
				stepper.waitForStepDone("get status completed not in transaction");
				return null;
			}
		});

		stepper.add(new Callable<Void>() {
			@Override
			public Void call() throws Exception {
				stepper.waitForStepDone("job started");

				AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(jobId.get());
				assertEquals(null, clone.getProgressMessage());
				assertEquals(AsynchJobState.PROCESSING, clone.getJobState());

				stepper.stepDone("get status initial");
				stepper.waitForStepDone("progress reported 1");

				clone = asynchJobStatusDao.getJobStatus(jobId.get());
				assertEquals("A MESSAGE", clone.getProgressMessage());

				stepper.stepDone("get status 1");
				stepper.waitForStepDone("progress reported 2");

				clone = asynchJobStatusDao.getJobStatus(jobId.get());
				assertEquals("A MESSAGE2", clone.getProgressMessage());

				stepper.stepDone("get status 2");
				stepper.waitForStepDone("job completed");

				clone = asynchJobStatusDao.getJobStatus(jobId.get());
				assertEquals("A MESSAGE2", clone.getProgressMessage());

				stepper.stepDone("get status completed in transaction");
				stepper.waitForStepDone("out of transaction");

				clone = asynchJobStatusDao.getJobStatus(jobId.get());
				assertEquals("Complete", clone.getProgressMessage());
				assertEquals(AsynchJobState.COMPLETE, clone.getJobState());

				stepper.stepDone("get status completed not in transaction");
				return null;
			}
		});

		stepper.run();
	}

	@Test
	public void testUpdateProgressTooBig() throws DatastoreException, NotFoundException{
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		// update the progress
		char[] chars = new char[DBOAsynchJobStatus.MAX_MESSAGE_CHARS+1];
		Arrays.fill(chars, '1');
		String tooBig = new String(chars);
		asynchJobStatusDao.updateJobProgress(status.getJobId(), 0L, 1000L, tooBig);
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals(new Long(0), clone.getProgressCurrent());
		assertEquals(new Long(1000), clone.getProgressTotal());
		assertEquals(tooBig.substring(0,  DBOAsynchJobStatus.MAX_MESSAGE_CHARS-1), clone.getProgressMessage());
		assertEquals(body, status.getRequestBody());
	}

	@Test
	public void testSetFailed() throws DatastoreException, NotFoundException{
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		String startEtag = status.getEtag();
		// update the progress
		Throwable error = new Throwable("something when wrong", new IllegalArgumentException("This is bad"));
		String newEtag = asynchJobStatusDao.setJobFailed(status.getJobId(), error);
		assertNotNull(newEtag);
		assertFalse(startEtag.equals(newEtag), "The etag must change when the status changes");
		// Get the status
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals("something when wrong", clone.getErrorMessage());
		assertEquals(AsynchJobState.FAILED, clone.getJobState());
		System.out.println(clone.getErrorDetails());
		assertNotNull(clone.getErrorDetails());
		assertTrue(clone.getErrorDetails().contains("This is bad"));
		assertEquals(newEtag, clone.getEtag());
		assertEquals("java.lang.Throwable", clone.getException());
		assertEquals(body, status.getRequestBody());
		assertEquals(AsynchJobState.PROCESSING, status.getJobState());
	}

	@Test
	public void testSetFailedNonStringConstructor() throws DatastoreException, NotFoundException {
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		// update the progress
		Throwable error = new TermsOfUseException();
		asynchJobStatusDao.setJobFailed(status.getJobId(), error);
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals(null, clone.getException());
	}

	@Test
	public void testSetCanceling() throws DatastoreException, NotFoundException {
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertFalse(status.getJobCanceling());
		// update the progress
		asynchJobStatusDao.setJobCanceling(status.getJobId());
		// Get the status
		AsynchronousJobStatus clone = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertEquals(AsynchJobState.PROCESSING, clone.getJobState());
		assertTrue(clone.getJobCanceling());
	}

	@Test
	public void testSetComplete() throws DatastoreException, NotFoundException, InterruptedException{
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		String previousEtag = status.getEtag();
		// Update the progress
		asynchJobStatusDao.updateJobProgress(status.getJobId(), 10L, 100L, "Made some progress");
		// Now set it complete
		// Make sure at at least some time has passed before me set it complete
		Thread.sleep(10);
		String requestHash = null;
		long runtimeMS = asynchJobStatusDao.setComplete(status.getJobId(), response, requestHash);
		assertNotNull(runtimeMS);
		AsynchronousJobStatus result = asynchJobStatusDao.getJobStatus(status.getJobId());
		assertNotNull(result);
		assertNotNull(result.getEtag());
		assertFalse(previousEtag.equals(result.getEtag()));
		assertTrue(result.getRuntimeMS() >= 10);
		assertNull(result.getErrorDetails());
		assertNull(result.getErrorMessage());
		assertEquals(new Long(100l), result.getProgressCurrent());
		assertEquals(new Long(100l), result.getProgressTotal());
		assertEquals(AsynchJobState.COMPLETE, result.getJobState());
		assertNotNull(result.getChangedOn());
		assertNotNull(result.getStartedOn());
		assertTrue(result.getChangedOn().getTime() > result.getStartedOn().getTime());
		assertEquals(body, result.getRequestBody());
		assertEquals(response, result.getResponseBody());
	}

	@Test
	public void testFindCompletedJobStatusCompleted() throws DatastoreException, NotFoundException{
		String requestHash = "sd1zQvpC67saUigIElscOgHash";
		AsynchronousJobStatus status = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(status);
		assertNotNull(status.getEtag());
		asynchJobStatusDao.setComplete(status.getJobId(), response, requestHash);
		status = asynchJobStatusDao.getJobStatus(status.getJobId());
		// Find the job with the hash, etag, and user id.
		List<AsynchronousJobStatus> foundStatus = asynchJobStatusDao.findCompletedJobStatus(requestHash, creatorUserGroupId);
		assertNotNull(foundStatus);
		assertEquals(1, foundStatus.size());
		assertEquals(status, foundStatus.get(0));
	}

	@Test
	public void testFindCompletedJobStatusMultiple() throws DatastoreException, NotFoundException{
		String requestHash = "sd1zQvpC67saUigIElscOgHash";
		AsynchronousJobStatus one = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(one);
		assertNotNull(one.getEtag());
		asynchJobStatusDao.setComplete(one.getJobId(), response, requestHash);
		one = asynchJobStatusDao.getJobStatus(one.getJobId());

		// create another with the same data
		AsynchronousJobStatus two = asynchJobStatusDao.startJob(creatorUserGroupId, body);
		assertNotNull(two);
		assertNotNull(two.getEtag());
		asynchJobStatusDao.setComplete(two.getJobId(), response, requestHash);
		two = asynchJobStatusDao.getJobStatus(two.getJobId());

		// Find the job with the hash, etag, and user id.
		List<AsynchronousJobStatus> foundStatus = asynchJobStatusDao.findCompletedJobStatus(requestHash, creatorUserGroupId);
		assertNotNull(foundStatus);
		assertEquals(2, foundStatus.size());
		assertEquals(one, foundStatus.get(0));
		assertEquals(two, foundStatus.get(1));
	}

	@Test
	public void testIdNull(){
		assertThrows(IllegalArgumentException.class, ()->{
			asynchJobStatusDao.getJobStatus(null);
		});

	}

	@Test
	public void testIdNAN(){
		assertThrows(IllegalArgumentException.class, ()->{
			asynchJobStatusDao.getJobStatus("not a number");
		});
	}
}


text:
'use strict';

var errorTypes = require('./errorTypes'),
  ValidationError = errorTypes.ValidationError,
  ValidationErrors = errorTypes.ValidationErrors,
  MissingValueError = errorTypes.MissingValueError,
  validate = require('./index');

// http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object
function clone(obj){
    if(obj === null || obj === undefined || typeof obj !== 'object') return obj;

    if(Array.isArray(obj)) return obj.slice();

    var temp = {};

    for(var key in obj)
        temp[key] = clone(obj[key]);
    return temp;
}

function addInhertiedProperties(model, modelId, models){
  var parent;

  Object.keys(models).some(function(modelName){
    var potentialParent = models[modelName];
    if (!potentialParent.subTypes) return;

    if(potentialParent.subTypes.indexOf(modelId) !== -1){
      parent = potentialParent;
      return true;
    }
  });

  if(!parent) return;

  for(var propertyName in parent.properties){
    model.properties[propertyName] = parent.properties[propertyName];
  }

  if(parent.required) model.required = model.required.concat(parent.required);

  addInhertiedProperties(model, parent.id, models);
}

function validateModel(candidate, model, models){
  if(candidate === null || typeof candidate !== 'object'){
    return new ValidationErrors(candidate, model);
  }

  models = models || {};

  model = clone(model);
  if(!model.required) model.required = [];
  addInhertiedProperties(model, model.id, models);

  var errors = [];

  model.required.forEach(function(propertyName){
    if (candidate[propertyName] !== undefined) return;

    var property = model.properties[propertyName];
    var error = new MissingValueError();
    errors.push(new ValidationError(propertyName, property, error));
  });

  Object.keys(candidate).forEach(function(propertyName){
    var property = model.properties[propertyName];

    if(property === undefined) return;

    var error = validate.dataType(candidate[propertyName], property, models);
    if(error){
      errors.push(new ValidationError(propertyName, property, error));
    }
  });

  if(errors.length){
    return new ValidationErrors(candidate, model.id, model, errors);
  }
}
module.exports = validateModel;


text:
using Common;
using DAL;
using Microsoft.AspNetCore.Http;
using System.IO;
using System.Threading.Tasks;

namespace BL
{
    public interface IRecordOperations
    {
        Task<Result<IModel<Record>>> Get(int id, int userId);
        Task<Result<IFetchResult<IModel<Record>>>> Get(IFetch fetch, int userId);
        Task<Result> Save(IModel<Record> recordModel, int userId);
        Task<Result> Update(IModel<Record> recordModel, int userId);
        Task<Result> Delete(int id, int userId);
        Task<Result> Delete(IModel<Record> recordModel, int userId);
        Task<Result> UploadImage(int recordId, IFormFile file, int userId);
        Task<Result<Image>> GetImage(int recordId, int userId);
    }
}


text:
#ifndef _TABLE_H
#define	_TABLE_H

#include <iostream>
#include <boost/numeric/ublas/vector.hpp>
#include <string>

namespace votca { namespace tools {

using namespace std;
namespace ub = boost::numeric::ublas;

// the entry is invalid, e.g. could not be calculated (ln(0), ...)
#define TBL_INVALID    1

/**
    \brief class to store tables like rdfs, tabulated potentials, etc

    \think about weather to make this a template, can be used in histogram
    as well, of for counting with integeers...

 */
class Table
{
public:
    Table() ;
    Table(Table &tbl);

    ~Table() {};

    void clear(void);

    void GenerateGridSpacing(double min, double max, double spacing);
//    void resize(int N, bool preserve=true) { _x.resize(N, preserve); _y.resize(N, preserve); _flags.resize(N, preserve); }
    void resize(int N, bool preserve=true);
    int size() const {return _x.size(); }

    double &x(int i) { return _x[i]; }
    double &y(int i) { return _y[i]; }
    char &flags(int i) { return _flags[i]; }
    double &yerr(int i) { return _yerr[i]; }

    void set(const int &i, const double &x, const double &y) { _x[i] = x; _y[i]=y; }
    void set(const int &i, const double &x, const double &y, const char &flags) { _x[i] = x; _y[i]=y; _flags[i] = flags; }
    void set(const int &i, const double &x, const double &y, const char &flags, const double &yerr) { _x[i] = x;
                                                                                _y[i]=y; _flags[i] = flags; _yerr[i] = yerr; }

    void set_comment(const string comment) {_has_comment=true; _comment_line = comment;}

    void Load(string filename);
    void Save(string filename) const;

    void Smooth(int Nsmooth);

    bool GetHasYErr() { return _has_yerr; }
    void SetHasYErr(bool has_yerr) { _has_yerr = has_yerr; }

    ub::vector<double> &x() { return _x; }
    ub::vector<double> &y() { return _y; }
    ub::vector<char> &flags() { return _flags; }
    ub::vector<double> &yerr() { return _yerr; }

    void push_back(double x, double y, char flags);

    const string &getErrorDetails() {
        return _error_details;
    }

    void setErrorDetails(string str) {
        _error_details = str;
    }

private:
    ub::vector<double> _x;
    ub::vector<double> _y;
    ub::vector<char>   _flags;
    ub::vector<double> _yerr;
    string _error_details;

    bool _has_yerr;
    bool _has_comment;

    friend ostream &operator<<(ostream &out, const Table& v);
    friend istream &operator>>(istream &out, Table& v);

    string _comment_line;

};

inline Table::Table()
{
    _has_yerr = false;
    _error_details = "";
}

inline Table::Table(Table &tbl)
{
    resize(tbl.size());
    _x = tbl._x;
    _y = tbl._y;
    _flags = tbl._flags;
    _has_yerr = tbl._has_yerr;
    if (_has_yerr) _yerr = tbl._yerr;
    _has_comment = false;
    _error_details = "";
}

inline ostream &operator<<(ostream &out, const Table& t)
{
    //TODO: use a smarter precision guess, XXX.YYYYY=8, so 10 should be enough
    out.precision(10);
    if ( t._has_yerr ) {
        for(size_t i=0; i<t._x.size(); ++i) {
            out << t._x[i] << " " << t._y[i] << " " << t._yerr[i] << " " << t._flags[i] << endl;
        }
    }
    else {
        //out << t.size() << endl;
        for(size_t i=0; i<t._x.size(); ++i) {
            out << t._x[i] << " " << t._y[i] << " " << t._flags[i] << endl;
        }
    }
    return out;
}
// TODO: modify this function to be able to treat _has_yerr == true
inline void Table::push_back(double x, double y, char flags)
{
    size_t n=size();
    resize(n+1);
    _x[n] = x;
    _y[n] = y;
    _flags[n] = flags;
}

istream &operator>>(istream &in, Table& t);

}}

#endif	/* _TABLE_H */


text:
<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="Nullable"
xmlns="http://ibatis.apache.org/mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <alias>
    <typeAlias alias="Nullable" type="IBatisNet.DataMapper.Test.Domain.NullableClass, IBatisNet.DataMapper.Test"/>
  </alias>

  <resultMaps>
    <resultMap id="Nullable-result" class="Nullable">
      <result property="Id" column="Id"/>
      <result property="TestBool" column="TestBool" />
      <result property="TestByte" column="TestByte" />
      <result property="TestChar" column="TestChar" />
      <result property="TestDateTime" column="TestDateTime" />
      <result property="TestDecimal" column="TestDecimal" />
      <result property="TestDouble" column="TestDouble" />
      <result property="TestGuid" column="TestGuid"/>
      <result property="TestInt16" column="TestInt16"/>
      <result property="TestInt32" column="TestInt32"/>
      <result property="TestInt64" column="TestInt64"/>
      <result property="TestSingle" column="TestSingle" />
    </resultMap>
  </resultMaps >

  <statements>

    <select id="GetNullable" resultMap="Nullable-result" >
      select
        *
      from Nullable
      where Id = #value#
    </select>

    <select id="GetClassNullable" resultClass="Nullable" >
      select
      *
      from Nullable
      where Id = #value#
    </select>

    <insert id="InsertNullable" parameterClass="Nullable" >
      <selectKey property="Id" type="post" resultClass="int">
        select SCOPE_IDENTITY() as value
      </selectKey>
      insert into Nullable
      (TestBool, TestByte, TestChar, TestDateTime, TestDecimal, TestDouble, TestGuid, TestInt16, TestInt32, TestInt64, TestSingle)
      values
      (#TestBool#, #TestByte#, #TestChar#, #TestDateTime#, #TestDecimal#, #TestDouble#, #TestGuid#, #TestInt16#, #TestInt32#, #TestInt64#, #TestSingle#)
    </insert>

  </statements>
</sqlMap>


text:
perl
========================

[USAGE]
perl test.pl [confidence parameter] [mode] [mode parameter] [dimension of features]

[MODE]
available modes are below.
cw: confidence weighted. mode parameter is variance.
scw: soft confidence weighted (proposition 1). mode parameter is aggressiveness.
fscw: scw, but sigma has only diagonal elements.

[EXAMPLE]
$$ perl test.pl 0.7 cw 1 3 < colors.csv


text:
/*
 * Author: Alejandro Balderrama
 * Class: Theory of Operating Systems
 * Professor: Dr. Freudenthal
 * Project: Tokenizer
 *
 * Description: The following program implements a string tokenizer. This implementation works by reading in an input string from the user,
 * 			    partitioning its individual tokens by the ' ' character, then storing each token into a vector. The initial input is
 * 			    printed line-by-line along with its vector position.
 */
#include <stdio.h>
#include <stdlib.h>
#include "mytoc.h"

int tokenCounter(char* stringIn, char delim) /****Returns the number or tokens in a given string.****/
{
	int i = 0, numTokens = 1;

	while (stringIn[i] != '\0') /****Traverse the string until the null character is reached.****/
	{
		if (stringIn[i] == delim) /****While traversing, if a space is encountered add 1 to the token counter.****/
		{
			numTokens++;
		}
		i++;
	}
	return numTokens;
}

int* characterCounter(char* stringIn, int numTokens, char delim) /****Returns an int vector containing the number of characters per token.****/
{
	int i, j, k = 0, x = 0, numChars = 0;
	int* numCharacters  = (int*)calloc(numTokens + 1, sizeof(int)); /****In-method int array used to store the # of characters per token.****/

	for (i = 0; stringIn[i] != '\0'; i++) /****Loop to traverse the entire string.****/
	{
		if (stringIn[i] == delim) /****While traversing, if a space is encountered...****/
		{
			for (j = x; stringIn[j] != delim; j++) /****Index j returns to the last location of x...****/
			{									 /****x points to the beginning of the last token before the space was encountered.****/
				numChars++;						 /****The # of characters is counted until the space is reached.****/
			}
			numCharacters[k] = numChars; /****Stores the number of characters for the current token.****/
			numChars = 0; /****Reset the variable before moving on to the next token.****/
			x = i + 1; /****Ensures the index is pointing to the beginning of the next token and not to space.****/
			k++;
		}
	}

	for (j = x + 1; stringIn[j] != '\0'; j++) /****Loop used to count the number of characters in the last token of the string.****/
	{
		numChars++;
	}
	numCharacters[k] = numChars;

	return numCharacters;
}

char** Mytoc(char* stringIn, char delim) /****Returns a string vector of space delimited tokens.****/
{
	int i, j = 0, x = 0, tokenCount = tokenCounter(stringIn, delim);
	char** tokenVecOut = (char**)calloc(tokenCount + 1, sizeof(char*)); /****Memory allocation to hold each token.****/
	int* numCharacters = characterCounter(stringIn, tokenCount, delim);

	for (i = 0; i < tokenCount; i++)
	{
		tokenVecOut[i] = (char*)malloc((numCharacters[i] + 1) * sizeof(char)); /****Memory allocation to hold characters of tokens.****/
	}

	i = 0;

	while (stringIn[x] != '\0') /****Traverse the entire string.****/
	{
		if (stringIn[x] != delim) /****If the current character is not equal to the delimiter...****/
		{
			tokenVecOut[i][j] = stringIn[x]; /****Copy the current character to the vector.****/
			j++;
		}
		if (stringIn[x] == delim) /****If the current character is equal to the delimiter...****/
		{
			tokenVecOut[i][j] = '\0'; /****Assign a null character to the end of the token.****/
			i++;
			j = 0; /****Reset j before continuing to next token.****/
		}
		x++;
	}
	tokenVecOut[tokenCount] = (char*)0;

	return tokenVecOut;

}


text:
<?php

namespace Laelaps\Bundle\FacebookAuthentication\Security;

use BadMethodCallException;
use Laelaps\Bundle\FacebookAuthentication\Exception\InvalidUser as InvalidUserException;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class FacebookAuthenticationProvider implements AuthenticationProviderInterface
{
    /**
     * @param \Symfony\Component\Security\Core\User\UserProviderInterface
     */
    private $userProvider;

    /**
     * @param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token
     * @return bool
     * @throws \Laelaps\Bundle\FacebookAuthentication\Exception\InvalidUser
     */
    public function authenticate(TokenInterface $token)
    {
        $user = $this->getUserProvider()
            ->loadUserByUsername($token->getUsername())
        ;

        if (!($user instanceof UserInterface)) {
            throw new InvalidUserException($user);
        }

        $authenticatedToken = new FacebookUserToken($user);
        $authenticatedToken->setAuthenticated(true);

        return $authenticatedToken;
    }

    /**
     * @return \Symfony\Component\Security\Core\User\UserProviderInterface $userProvider
     * @throws \BadMethodCallException
     */
    public function getUserProvider()
    {
        if (!($this->userProvider instanceof UserProviderInterface)) {
            throw new BadMethodCallException('UserProvider is not set.');
        }

        return $this->userProvider;
    }

    /**
     * @param \Symfony\Component\Security\Core\User\UserProviderInterface $userProvider
     * @return void
     */
    public function setUserProvider(UserProviderInterface $userProvider)
    {
        $this->userProvider = $userProvider;
    }

    /**
     * @param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token
     * @return bool
     */
    public function supports(TokenInterface $token)
    {
        return $token instanceof FacebookUserToken;
    }
}


text:
package orwell.tank.hardware.Colours;

/**
 * Created by Michaël Ludmann on 28/01/17.
 */
public class RgbColourSigma extends RgbColour {

    public RgbColourSigma(float red, float green, float blue) {
        super(red, green, blue);
    }

    public RgbColourSigma mult(float factor) {
        return new RgbColourSigma(red * factor, green * factor, blue * factor);
    }
}


text:
package org.chasen.crfpp;

import static org.junit.Assert.assertEquals;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import org.junit.Test;

public class OSInfoTest {

  @Test
  public void osName() {
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows 7"));
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows XP"));
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows 2000"));
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows Vista"));
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows 98"));
    assertEquals("Windows", OSInfo.translateOSNameToFolderName("Windows 95"));

    assertEquals("Mac", OSInfo.translateOSNameToFolderName("Mac OS"));
    assertEquals("Mac", OSInfo.translateOSNameToFolderName("Mac OS X"));

    assertEquals("AIX", OSInfo.translateOSNameToFolderName("AIX"));

    assertEquals("Linux", OSInfo.translateOSNameToFolderName("Linux"));
    assertEquals("OS2", OSInfo.translateOSNameToFolderName("OS2"));

    assertEquals("HPUX", OSInfo.translateOSNameToFolderName("HP UX"));
  }

  @Test
  public void archName() {
    assertEquals("i386", OSInfo.translateArchNameToFolderName("i386"));
    assertEquals("x86", OSInfo.translateArchNameToFolderName("x86"));
    assertEquals("ppc", OSInfo.translateArchNameToFolderName("ppc"));
    assertEquals("amd64", OSInfo.translateArchNameToFolderName("amd64"));
  }

  @Test
  public void folderPath() {
    String[] component = OSInfo.getNativeLibFolderPathForCurrentOS().split("/");
    assertEquals(2, component.length);
    assertEquals(OSInfo.getOSName(), component[0]);
    assertEquals(OSInfo.getArchName(), component[1]);
  }

  @Test
  public void testMainForOSName() throws Exception {

    // preserve the current System.out
    PrintStream out = System.out;
    try {
      // switch STDOUT
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      PrintStream tmpOut = new PrintStream(buf);
      System.setOut(tmpOut);
      OSInfo.main(new String[] { "--os" });
      assertEquals(OSInfo.getOSName(), buf.toString());
    }
    finally {
      // reset STDOUT
      System.setOut(out);
    }

  }

  @Test
  public void testMainForArchName() throws Exception {

    // preserver the current System.out
    PrintStream out = System.out;
    try {
      // switch STDOUT
      ByteArrayOutputStream buf = new ByteArrayOutputStream();
      PrintStream tmpOut = new PrintStream(buf);
      System.setOut(tmpOut);
      OSInfo.main(new String[] { "--arch" });
      assertEquals(OSInfo.getArchName(), buf.toString());
    }
    finally {
      // reset STDOUT
      System.setOut(out);
    }
  }

}


text:
package org.optaplanner.examples.travelingtournament.domain;

import org.optaplanner.core.api.domain.entity.PlanningEntity;
import org.optaplanner.core.api.domain.variable.PlanningVariable;
import org.optaplanner.examples.common.domain.AbstractPersistable;

import com.thoughtworks.xstream.annotations.XStreamAlias;

@PlanningEntity
@XStreamAlias("TtpMatch")
public class Match extends AbstractPersistable {

    private Team homeTeam;
    private Team awayTeam;

    private Day day;

    public Team getHomeTeam() {
        return homeTeam;
    }

    public void setHomeTeam(Team homeTeam) {
        this.homeTeam = homeTeam;
    }

    public Team getAwayTeam() {
        return awayTeam;
    }

    public void setAwayTeam(Team awayTeam) {
        this.awayTeam = awayTeam;
    }

    @PlanningVariable(valueRangeProviderRefs = { "dayRange" })
    public Day getDay() {
        return day;
    }

    public void setDay(Day day) {
        this.day = day;
    }

    @Override
    public String toString() {
        return homeTeam + "+" + awayTeam;
    }

}


text:
#pragma checksum "C:\Users\asus1\Desktop\14331148_梁乐生_期中project\AccountBook\AccountBook\Search.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "227742B38734212CE0AA9AEFBB3F120F"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace AccountBook
{
    partial class Search : global::Windows.UI.Xaml.Controls.Page
    {

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.Grid ContentPanel;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.StackPanel searchStackPanel;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.ListView listReport;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.TextBox keyWords;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.DatePicker DatePickerEnd;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.DatePicker DatePickerBegin;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.Button backButton;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private global::Windows.UI.Xaml.Controls.TextBlock PageTitle;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        private bool _contentLoaded;

        /// <summary>
        /// InitializeComponent()
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent()
        {
            if (_contentLoaded)
                return;

            _contentLoaded = true;

            global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///Search.xaml");
            global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);
        }

    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="UITitleBarContainer">
        <attr name="title_text" format="string"/>
        <attr name="title_text_size" format="float"/>
    </declare-styleable>
</resources>


text:
/**
 * @file client_id.h
 *
 * Generate a unique client id.
 *
 * This function is used to generate a random client id for clients that don't provide one in their Connect control
 * packet.
 */

#pragma once

#include <string>
#include <cstdint>

/**
 * Generate a unique client id.
 *
 * The client id is a random character sequence drawn from the character set [a-z0-9].
 *
 * @param len Length of the sequence to generate
 * @return    Random character sequence
 */
std::string generate_client_id(size_t len=32);


text:
'''Stubs for requests'''

try:
    from urllib3.connectionpool import HTTPConnection, VerifiedHTTPSConnection
except ImportError:
    from requests.packages.urllib3.connectionpool import HTTPConnection, VerifiedHTTPSConnection

from ..stubs import VCRHTTPConnection, VCRHTTPSConnection

# urllib3 defines its own HTTPConnection classes, which requests goes ahead and assumes
# you're using.  It includes some polyfills for newer features missing in older pythons.

class VCRRequestsHTTPConnection(VCRHTTPConnection, HTTPConnection):
    _baseclass = HTTPConnection

class VCRRequestsHTTPSConnection(VCRHTTPSConnection, VerifiedHTTPSConnection):
    _baseclass = VerifiedHTTPSConnection


text:
package com.jamontes79.scala.movielist

import android.content.Intent
import android.os.Bundle
import android.support.v4.app.{ActivityCompat, ActivityOptionsCompat, FragmentActivity}
import android.support.v4.view.ViewCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.fortysevendeg.macroid.extras.FragmentExtras._
import com.jamontes79.scala.movielist.entities.Movie
import com.jamontes79.scala.movielist.layouts.ImageLayout
import com.jamontes79.scala.movielist.utils.MyUtils
import macroid.FullDsl._
import macroid.{Contexts, IdGeneration}
object ImageActivity
{
  def navigate(activity: FragmentActivity , transitionImage: View , movie: Movie ) {
    val intent = new Intent(activity, classOf[ImageActivity])
    intent.putExtra(MyUtils.EXTRA_IMAGE, movie.cover)
    intent.putExtra(MyUtils.EXTRA_OBJECT,movie)

    val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, transitionImage, MyUtils.EXTRA_IMAGE)

    ActivityCompat.startActivityForResult(activity, intent, MyUtils.IMAGE_REQCODE, options.toBundle())
  }
}
/**
 * Created by alberto on 30/10/15.
 */
class ImageActivity  extends AppCompatActivity
with Contexts[FragmentActivity]
with ImageLayout
with IdGeneration
with MyUtils {

  override def onCreate(savedInstanceState: Bundle) = {
    super.onCreate(savedInstanceState)
    setContentView(layout)

    toolBar map setSupportActionBar

    getSupportActionBar.setDisplayHomeAsUpEnabled(true)
    getSupportActionBar.setHomeButtonEnabled(true)

    if (savedInstanceState == null) {
      runUi(
        replaceFragment(
          builder = f[ImageFragment],
          id = Id.imageFragment,
          tag = Some(Tag.imageFragment)))
    }

  }

  override def onPostCreate(savedInstanceState: Bundle): Unit = {
    findFragmentByTag[ImageFragment](Tag.imageFragment) match {
      case Some(f) => ViewCompat.setTransitionName(f.imageOnView.get, MyUtils.EXTRA_IMAGE)
    }
    super.onPostCreate(savedInstanceState)
  }
}


text:
layout: post
title: 'Entrevista para o Jornal A Tribuna Jan/2010: Profissões em que Sobram Vagas
de Emprego'
date: 2010-02-11 08:30:53.000000000 -02:00
type: post
published: true
status: publish
categories:
- Carreira
- Pessoal
tags:
- A Tribuna
- Carreira
- FAESA
- Pessoal
meta:
views: '5743'
category: pt-br
language: pt-br
display_name: Loiane
first_name: Loiane
last_name: ''
---

Na última de semana de janeiro tive a honra de conceder mais uma entrevista para o jornal A Tribuna - vendido no Espírito Santo, meu estado natal - sobre mercado de trabalho na área de TI.

A reportagem fala sobre os profissionais que são difíceis de achar, o que fazer para se destacar no mercado. Tem uma outra página também sobre quais são as profissões mais procuradas e qual o salário médio destas.

Foi matéria de capa do jornal do dia 31 de janeiro de 2010, e matéria chefe do caderno de economia do jornal.

A entrevista que dei foi sobre como está o mercado de trabalho na área de TI; na matéria destaquei a importância do profissional que possui inglês. Outro ponto foram as atividades extras durante a graduação, que podem ajudar a alavancar a sua carreira.

Agradeço mais uma vez à coordenação de computação e ao núcleo de comunicação da Faesa pela indicação para participar da matéria.

[slideshare id=3116685&doc=no31011034-100209133140-phpapp02&type=d]

Aproveite as oportunidades

Aproveito o post para deixar algumas dicas para aqueles que fazem faculdade. Quase todas as oportunidades que tive nos primeiros 3 anos de carreira foi a faculdade que proporcionou de alguma forma:

 Meu primeiro estágio foi pela indicação do coordenador do curso;

convite para participar da Maratona de Programação - fomos pra final nacional (primeiro time capixaba a conseguir isso), o que rendeu propaganda no site da faculdade e propaganda nos dois jornais do estado (isso nos deu bastante destaque na faculdade)

saí do estágio para o primeiro emprego, indicação de um colega de monitoria

algumas outras matérias para o jornal e no próprio site da faculdade

O que estou querendo dizer é: a faculdade apenas não nos fornace parte do conteúdo que precisamos saber para começar nossa carreira. O seu networking começa na sala de aula, com seus futuros colegas de profissão, que poderão te ajudar a conseguir um emprego depois. Os professores não são apenas professores, podem se tornar amigos, que também te ajudam fora da sala de aula (e até participam da cervejada!). E essa parceria não precisa terminar quando você se formar!

Aproveite também os eventos na sua área! São ótimos para conhecer novas pessoas e trocar idéias com os mais experientes.

São as pequenas coisas, que às vezes nem damos a devida importância, que fazem muita diferença na nossa carreira!

Até a próxima!


text:
<?php echo $_lang['install_results']?>

<?php
ob_start();
include "instprocessor.php";
$content = ob_get_contents();
ob_end_clean();
echo $content;

?>
<form name="install" id="install_form" action="index.php?action=options" method="post">
<?php
if ($errors == 0) {
    // check if install folder is removeable
    if (is_writable("../install")) { ?>
<input type="checkbox" name="rminstaller" onclick="event.cancelBubble=true;" <?php echo (empty ($errors) ? 'checked="checked"' : '') ?> style="cursor:default;" /><?php echo $_lang['remove_install_folder_auto'] ?>
<?php
    } else {
?>
<?php echo $_lang['remove_install_folder_manual']?>
<?php
    }
}
?>

        <a href="javascript:closepage();" title="<?php echo $_lang['btnclose_value']?>"><?php echo $_lang['btnclose_value']?>

</form>


text:
module.exports = {
  Handshake: require('./handshake'),
  Message: require('./message')
};


text:
package me.ryanhamshire.GriefPrevention.command;

import me.ryanhamshire.GriefPrevention.ClaimPermission;
import me.ryanhamshire.GriefPrevention.GriefPrevention;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;

public class CommandTrust implements CommandExecutor {

    @Override
    public CommandResult execute(CommandSource src, CommandContext args) {
        // most trust commands use this helper method, it keeps them
        // consistent
        try {
            CommandHelper.handleTrustCommand(GriefPrevention.checkPlayer(src), ClaimPermission.Build,
                    args.<String>getOne("subject").get());
        } catch (CommandException e) {
            src.sendMessage(Text.of("An error occurred while executing this command."));
        }
        return CommandResult.success();
    }
}


text:
<?php

declare(strict_types=1);

namespace Emonkak\Di\Tests\Binding;

use Emonkak\Di\Binding\BindingInterface;
use Emonkak\Di\Binding\Value;
use Emonkak\Di\Instantiator\InstantiatorInterface;
use PHPUnit\Framework\TestCase;

/**
 * @covers \Emonkak\Di\Binding\Value
 */
class ValueTest extends TestCase
{
    public function testResolve(): void
    {
        $value = 123;
        $binding = new Value($value);
        $bindings = [
            'key' => $this->createMock(BindingInterface::class),
        ];
        $dependencies = [];
        $instantiator = $this->createMock(InstantiatorInterface::class);

        $this->assertEquals($value, $binding->resolve($dependencies, $bindings, $instantiator));
    }

    public function testGetFunction(): void
    {
        $binding = new Value(123);

        $this->assertNull($binding->getFunction());
    }
}