text:
local restyRedis = require "resty.redis"
local RedisHealthCheck = require "api-gateway.redis.redisHealthCheck"
local apiGatewayRedisReadReplica = "api-gateway-redis-replica"

local redisHealthCheck = RedisHealthCheck:new({
    shared_dict = "cachedkeys"
})

local max_idle_timeout = 30000
local pool_size = 100
local default_redis_timeout = 5000

local RedisConnectionProvider = {}

function RedisConnectionProvider:new(o)
    local o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

local function isNotEmpty(s)
    return s ~= nil and s ~= ''
end

--- Searches and returns a Redis upstream pair (host:port) based on the name provided
--- @param upstream_name The Redis upstream name, as defined in the Nginx conf file
--- @return Redis host
--- @return Redis port
function RedisConnectionProvider:getRedisUpstream(upstream_name, upstream_password)
    local upstreamName = upstream_name or apiGatewayRedisReadReplica
    local _, host, port = redisHealthCheck:getHealthyRedisNode(upstreamName, upstream_password)
    ngx.log(ngx.DEBUG, "Obtained Redis Host:" .. tostring(host) .. ":" .. tostring(port), " from upstream:", upstreamName)
    if (nil ~= host and nil ~= port) then
        return host, port
    end

    ngx.log(ngx.ERR, "Could not find a Redis upstream.")
    return nil, nil
end

--- Obtains a connection to a provided upstream using an optionally provided password and timeout
--- If no password is provided, it is searched in the REDIS_PASS and REDIS_PASSWORD env variables
--- If the first connection attempt fails, a second retry is automatically performed with the same connection options
--- @param connection_options If this is a table, it should have upstream, password and redis_timeout.
--- Otherwise, the connection_options is considered the upstream name
function RedisConnectionProvider:getConnection(connection_options)
    local redisUpstream,
    redisPassword,
    redisTimeout;

    if (type(connection_options) == 'table') then
        redisUpstream = connection_options["upstream"]
        redisPassword = connection_options["password"]
        redisTimeout = connection_options["redis_timeout"]
    else
        redisUpstream = connection_options
        redisPassword = os.getenv('REDIS_PASS') or os.getenv('REDIS_PASSWORD') or ''
    end

    local redisHost, redisPort = self:getRedisUpstream(redisUpstream, redisPassword)
    ngx.log(ngx.DEBUG, "Trying with: " .. tostring(redisHost) .. " and " .. tostring(redisPort))
    local status, redisInstance = self:connectToRedis(redisHost, redisPort, redisPassword, redisTimeout)
    if not status then
        -- retry
        ngx.log(ngx.WARN, "Connection to Redis failed. Retrieving new Redis host and retrying")
        redisHost, redisPort = self:getRedisUpstream(redisUpstream, redisPassword)
        ngx.log(ngx.DEBUG, "Got new upstream: " .. tostring(redisHost) .. " and " .. tostring(redisPort))
        status, redisInstance = self:connectToRedis(redisHost, redisPort, redisPassword, redisTimeout)
    end
    return status, redisInstance
end

function RedisConnectionProvider:connectToRedis(host, port, password, redisTimeout)
    local redis = restyRedis:new()

    -- sets general timeout - for all operations
    local redis_timeout = redisTimeout or ngx.var.redis_timeout or default_redis_timeout
    redis:set_timeout(redis_timeout)

    local ok, err = redis:connect(host, port)
    if not ok then
        ngx.log(ngx.ERR, "Failed to connect to Redis instance: " .. host .. ", port: " .. port .. ". Error: ", err)
        return false, nil
    end

    -- Check for existing connection
    local times, error = redis:get_reused_times()

    if times and times ~= 0 then
        ngx.log(ngx.DEBUG, "Reusing Redis connection. Reused times: " .. tostring(times))
        return true, redis
    end

    if isNotEmpty(password) then
        -- Authenticate
        ok, err = redis:auth(password)
        if not ok then
            ngx.log(ngx.ERR, "Redis authentication failed for server: " .. host .. ":" .. port .. ". Error: ", err)
            return false, nil
        end
        ngx.log(ngx.DEBUG, "Redis authentication successful")
        return ok, redis
    else
        ngx.log(ngx.DEBUG, "No password authentication for Redis")
        return true, redis
    end
end

function RedisConnectionProvider:closeConnection(redis_instance)
    redis_instance:set_keepalive(max_idle_timeout, pool_size)
end

function RedisConnectionProvider:closeConnectionWithTimeout(redis_instance, max_idle_timeout)
    redis_instance:set_keepalive(max_idle_timeout, pool_size)
end

return RedisConnectionProvider


text:
package org.kaazing.gateway.server.messaging;

public interface MessagingHint {

}

redpajama_set_name: RedPajamaGithub


text:
package subreddit.android.appstore.backend.reddit.wiki.parser;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import subreddit.android.appstore.backend.data.AppInfo;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

public class DescriptionColumnParserTest {
    @Mock
    EncodingFixer encodingFixer;
    private DescriptionColumnParser parser;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        when(encodingFixer.fixHtmlEscapes(anyString())).then(new Answer<String>() {
            public String answer(InvocationOnMock invocation) throws Throwable {
                return invocation.getArgument(0);
            }
        });
        when(encodingFixer.convertMarkdownToHtml(anyString())).then(new Answer<String>() {
            public String answer(InvocationOnMock invocation) throws Throwable {
                return invocation.getArgument(0);
            }
        });
        when(encodingFixer.convertSubredditsToLinks(anyString())).then(new Answer<String>() {
            public String answer(InvocationOnMock invocation) throws Throwable {
                return invocation.getArgument(0);
            }
        });
        parser = new DescriptionColumnParser(encodingFixer);
    }

    @Test
    public void testParse() throws IOException {
        String rawDescriptionData = "This is a description";
        Map<AppParser.Column, String> rawColumnMap = new HashMap<>();
        rawColumnMap.put(AppParser.Column.DESCRIPTION, rawDescriptionData);
        AppInfo appInfo = new AppInfo();
        parser.parse(appInfo, rawColumnMap);

        assertFalse(appInfo.getDescription().isEmpty());
        assertEquals("This is a description", appInfo.getDescription());
    }
}


text:
import pinyin

# connection = sqlite3.connect('/tmp/region.sqlite3')

class Jsonable:
    def json(self):
        return {\
            "id": self.id,
            "name": self.name
        }

class Province(Jsonable):
    def __init__(self, id, name):
        self.id = id
        self.name = name
        self.cities = []

class City(Jsonable):
    def __init__(self, id, name, province):
        self.id = id
        self.name = name
        self.province = province
        self.county = []

class County(Jsonable):
    def __init__(self, id, name, city):
        self.id = id
        self.name = name
        self.city = city
        self.town = []

class Town(Jsonable):
    def __init__(self, id, name, county):
        self.id = id
        self.name = name
        self.county = county
        self.village = []

class Village(Jsonable):
    def __init__(self, id, name, town, category):
        self.id = id
        self.name = name
        self.town = town
        self.category = category

class ProvinceRepository:
    def create(self):
        statement = """CREATE TABLE IF NOT EXISTS province (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT,
            pinyin TEXT
        )
        """

        cursor = connection.cursor()
        cursor.execute(statement)
        connection.commit()

    def add(self, province):
        cursor = connection.cursor()
        cursor.execute("INSERT INTO province(id, name, pinyin) VALUES " \
            "(?, ?, ?)", (province.id, province.name,
                          pinyin.get(province.name),))
        connection.commit()

class CityRepository:
    def create(self):
        statements = [
            """CREATE TABLE IF NOT EXISTS city (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                province INTEGER,
                name TEXT,
                pinyin TEXT
            );""",
            """
            """
        ]

        cursor = connection.cursor()
        for statement in statements:
            cursor.execute(statement)
        connection.commit()

    def add(self, city):
        cursor = connection.cursor()
        cursor.execute("INSERT INTO city(id, province, name, pinyin) VALUES " \
            "(?, ?, ?, ?)", (city.id, city.province.id, city.name,
                             pinyin.get(city.name),))
        connection.commit()

class CountyRepository:
    def create(self):
        statements = [
            """CREATE TABLE IF NOT EXISTS county (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                province INTEGER,
                city INTEGER,
                name TEXT,
                pinyin TEXT
            );""",
            """
            """
        ]

        cursor = connection.cursor()
        for statement in statements:
            cursor.execute(statement)
        connection.commit()

    def add(self, county):
        cursor = connection.cursor()
        cursor.execute("INSERT INTO county (id, province, city, name, pinyin)" \
            " VALUES (?, ?, ?, ?, ?)",
            (county.id, county.city.province.id, county.city.id, \
             county.name, pinyin.get(county.name),))
        connection.commit()

class TownRepository:
    def create(self):
        statements = [
            """CREATE TABLE IF NOT EXISTS town (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                province INTEGER,
                city INTEGER,
                county INTEGER,
                name TEXT,
                pinyin TEXT
            );""",
            """
            """
        ]

        cursor = connection.cursor()
        for statement in statements:
            cursor.execute(statement)
        connection.commit()

    def add(self, town):
        cursor = connection.cursor()
        cursor.execute("INSERT INTO town (id, province, city, county, name, " \
            "pinyin) VALUES (?, ?, ?, ?, ?, ?)",
            (town.id, town.county.city.province.id, town.county.city.id,\
             town.county.id, town.name, pinyin.get(town.name),))
        connection.commit()

class VillageRepository:
    def create(self):
        statements = [
            """CREATE TABLE IF NOT EXISTS village (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                province INTEGER,
                city INTEGER,
                county INTEGER,
                town INTEGER,
                category INTEGER,
                name TEXT,
                pinyin TEXT
            );""",
            """
            """
        ]

        cursor = connection.cursor()
        for statement in statements:
            cursor.execute(statement)
        connection.commit()

    def add(self, village):
        cursor = connection.cursor()
        cursor.execute("INSERT INTO village (id, province, city, county, " \
            "town, category, name, pinyin) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            (village.id, village.town.county.city.province.id, \
             village.town.county.city.id,\
             village.town.county.id, village.town.id, village.category,
             village.name, pinyin.get(village.name),))
        connection.commit()

# ProvinceRepository().create()
# CityRepository().create()
# CountyRepository().create()
# TownRepository().create()
# VillageRepository().create()

if "__main__" == __name__:
    province = Province(11, u"北京")
    city = City(1101, u"市辖区", province)
    county = County(110101, u"东城区", city)
    town = Town(110101001, u"东华门街道办事处", county)
    village = Village(110101001001, u"多福巷社区居委会", town, 111)

    ProvinceRepository().add(province)
    CityRepository().add(city)
    CountyRepository().add(county)
    TownRepository().add(town)
    VillageRepository().add(village)


text:
#ifndef _H_PATHNAME
#define _H_PATHNAME

#include "Collect.h"
#include "Thunks.h"
#include "ObjSets.h"

enum path_flags { rooted_path = 1, wild_card_path = 2 };

visible_class (PathName)

class PathName : public Set
{
public:
	int			flags;
	short		n_levels;
	TCHAR**		path_levels;
	Thunk*		root_set_thunk;
	Value*		root_set;

				PathName();
				~PathName();

				classof_methods (PathName, Set);
	void		collect() { delete this; }
	ScripterExport void		sprin1(CharStream* s);

	ScripterExport Value* eval();
	void		append(TCHAR* level_name);
	Value*		find_object(TCHAR* name);
	Value*		get_object();

	ScripterExport Value* map(node_map& m);

#include "defimpfn.h"
	def_generic  (get,		"get");   // indexed get (no put or append)
	def_property ( count );
	def_property ( center );
	def_property ( min );
	def_property ( max );
};

extern TCHAR* ellipsis_level_name;
extern TCHAR* parent_level_name;

#endif


text:
#include <Array.hpp>

namespace oneapi {
template<typename T>
Array<T> rotate(const Array<T> &in, const float theta, const af::dim4 &odims,
                const af_interp_type method);
}


text:
#include "bytecode/bytecode.h"
#include "bytecode/opcodes.h"
#include "select/propset.h"
#include "select/propget.h"
#include "utils/utils.h"

#include "select/properties/properties.h"
#include "select/properties/helpers.h"

css_error css__cascade_width(uint32_t opv, css_style *style,
		css_select_state *state)
{
	return css__cascade_length_auto(opv, style, state, set_width);
}

css_error css__set_width_from_hint(const css_hint *hint,
		css_computed_style *style)
{
	return set_width(style, hint->status,
			hint->data.length.value, hint->data.length.unit);
}

css_error css__initial_width(css_select_state *state)
{
	return set_width(state->computed, CSS_WIDTH_AUTO, 0, CSS_UNIT_PX);
}

css_error css__compose_width(const css_computed_style *parent,
		const css_computed_style *child,
		css_computed_style *result)
{
	css_fixed length = 0;
	css_unit unit = CSS_UNIT_PX;
	uint8_t type = get_width(child, &length, &unit);

	if (type == CSS_WIDTH_INHERIT) {
		type = get_width(parent, &length, &unit);
	}

	return set_width(result, type, length, unit);
}


text:
var userCount = 0;

var Inbox = function(){
  return {
    noteCount:0,
    notes:[]
  }
};

var Note = function(to, from , body){
  return {
    to: to || '',
    from: from || '',
    body: body || ''
  }
};

var InboxCollection = [];
var OutboxCollection = [];
var UserCollection = [];

var newUser = function(name, callback){
    if( UserCollection.indexOf(name) > -1 ){
      callback("User name taken");
    }else{
      UserCollection.push(name);
      var inbox = Inbox();
      var note = Note(name, "TheHost", "Your first note! Everything looks amazing!");
      inbox.notes.push(note);
      inbox.noteCount++;
      InboxCollection.push(inbox);
      OutboxCollection.push(Inbox()); // Outbox is just an inbox, so clever!
      callback(null,"New user "+ name +" added.");
    }
};

module.exports = {
  newUser : newUser,

  Inbox: function (name, callback){
    var ID = UserCollection.indexOf(name);
    if(  ID > -1 ){
      callback(null, InboxCollection[ID]);
    }else{
      callback("No inbox under that username.");
    }
  },

  Outbox: function (name, callback){
    var ID = UserCollection.indexOf(name);
    if(  ID > -1 ){
      callback(null, OutboxCollection[ID]);
    }else{
      callback("No outbox under that username.");
    }
  },

  Init: function (){
    newUser("TheHost", function(err,data){
      if (err)
        console.error(err)
      else
        console.log(data);
    });
  }
};


text:
import React from 'react';
import { Module, ModuleBody } from '../Module';
import { shallow } from 'enzyme';

describe('Module', () => {
  describe('Renders as expected', () => {
    const testModule = shallow(
      <Module className="extra-class">
        <ModuleBody>Body</ModuleBody>
      </Module>
    );

    it('renders a Module', () => {
      expect(testModule.length).toEqual(1);
    });

    it('should render the appropriate classes', () => {
      expect(testModule.hasClass('bx--module--double')).toEqual(true);
      expect(testModule.hasClass('extra-class')).toEqual(true);
    });

    it('should render with specified class', () => {
      testModule.setProps({ size: 'single' });
      expect(testModule.hasClass('bx--module--single')).toEqual(true);
    });

    it('should render children as expected', () => {
      expect(testModule.find(ModuleBody).length).toEqual(1);
    });
  });

  describe('ModuleBody', () => {
    describe('Renders as expected', () => {
      const moduleBody = shallow(
        <ModuleBody className="extra-class" centered>
          Body
        </ModuleBody>
      );

      it('renders a ModuleBody', () => {
        expect(moduleBody.length).toEqual(1);
      });

      it('has the expected class', () => {
        expect(moduleBody.hasClass('bx--module__content')).toEqual(true);
        expect(moduleBody.hasClass('extra-class')).toEqual(true);
      });

      it('has the centered class when centered prop is true', () => {
        expect(moduleBody.hasClass('bx--module__content--centered')).toEqual(
          true
        );
      });

      it('should render children as expected', () => {
        expect(moduleBody.text()).toEqual('Body');
      });
    });
  });
});


text:
@class DVTButtonTextField, DVTStackBacktrace, IBDocument, NSMenu, NSNumberFormatter, NSSet, NSStepper, NSString;

@interface IBAutolayoutPropertyEditingController : NSObject <DVTInvalidation, NSMenuDelegate>
{
    id <IBCollection> _objectObservingTokens;
    long long _lastStepperValue;
    NSSet *_objects;
    DVTButtonTextField *_textField;
    NSStepper *_stepper;
    NSNumberFormatter *_formatter;
    IBDocument *_document;
    NSMenu *_menu;
    NSString *_keyPathFromEditedObjectToModelObject;
    NSString *_proxiedConfigurablePropertyKeyPath;
}

+ (void)initialize;
@property(copy, nonatomic) NSString *proxiedConfigurablePropertyKeyPath; // @synthesize proxiedConfigurablePropertyKeyPath=_proxiedConfigurablePropertyKeyPath;
@property(copy, nonatomic) NSString *keyPathFromEditedObjectToModelObject; // @synthesize keyPathFromEditedObjectToModelObject=_keyPathFromEditedObjectToModelObject;
@property(readonly, nonatomic) NSMenu *menu; // @synthesize menu=_menu;
@property(readonly, nonatomic) IBDocument *document; // @synthesize document=_document;
@property(retain, nonatomic) NSNumberFormatter *formatter; // @synthesize formatter=_formatter;
@property(retain, nonatomic) NSStepper *stepper; // @synthesize stepper=_stepper;
@property(retain, nonatomic) DVTButtonTextField *textField; // @synthesize textField=_textField;
@property(copy, nonatomic) NSSet *objects; // @synthesize objects=_objects;
- (void).cxx_destruct;
- (void)_userDidPressStepper:(id)arg1;
- (void)decrementValue;
- (void)incrementValue;
- (void)syncModelFromUI;
- (void)syncUIFromModel;
- (void)userDidChangeValue:(id)arg1;
- (void)populateMenu:(id)arg1;
- (void)menuNeedsUpdate:(id)arg1;
- (void)_openMenu:(id)arg1;
- (void)_openMenu:(id)arg1 underControl:(id)arg2;
- (void)primitiveInvalidate;
- (void)populateObservingTokens:(id)arg1;
- (void)startObservingObjects;
- (void)stopObservingObjects;
- (id)documentForEditedObject:(id)arg1;
- (id)modelObjectInCanvasConfigurationForEditedObject:(id)arg1;
- (void)setValue:(id)arg1 forModelKeyPath:(id)arg2 ofEditedObject:(id)arg3;
- (id)valueForModelKeyPath:(id)arg1 ofEditedObject:(id)arg2;
- (id)editedKeyPathForModelKeyPath:(id)arg1;

// Remaining properties
@property(retain) DVTStackBacktrace *creationBacktrace;
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) DVTStackBacktrace *invalidationBacktrace;
@property(readonly) Class superclass;
@property(readonly, nonatomic, getter=isValid) BOOL valid;

@end


text:
/*
 * Title:        GridSim Toolkit
 * Description:  GridSim (Grid Simulation) Toolkit for Modeling and Simulation
 *               of Parallel and Distributed Systems such as Clusters and Grids
 * License:      GPL - http://www.gnu.org/copyleft/gpl.html
 *
 */

package gridsim;

import java.util.*;
import eduni.simjava.Sim_system;

/**
 * GridSim ResourceCalendar class implements a mechanism to support modeling
 * a local load on Grid resources that may vary according to the time zone,
 * time, weekends and holidays.
 *
 * @author       Manzur Murshed and Rajkumar Buyya
 * @since        GridSim Toolkit 1.0
 * @invariant $none
 */
public class ResourceCalendar
{
    private Random random_;
    private double timeZone_;
    private double[] weekdayLoad_;  // load during the day
    private double[] holidayLoad_;  // load during holidays, including weekends
    private LinkedList weekendList_;
    private LinkedList holidayList_;
    private final int TIME = 60;

    // LinkedList weekend is a list of 0 = Sunday, 1 = Monday, 2 = Tuesday,
    // 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday
    /**
     * Allocates a new ResourceCalendar object with a default daily regular load.
     * @param timeZone      time zone
     * @param peakLoad      the load during peak time, with range: [0 ... 1]
     * @param offPeakLoad   the load during off peak time, with range: [0 ... 1]
     * @param relativeHolidayLoad   the load during holidays,
     *                              with range: [0 ... 1]
     * @param weekendList   a list of Integer numbers for weekends
     * @param holidayList   a list of Integer numbers for holidays
     * @param seed          the initial seed
     * @pre timeZone >= 0.0
     * @pre seed > 0
     * @post $none
     */
    public ResourceCalendar(double timeZone, double peakLoad,
                double offPeakLoad, double relativeHolidayLoad,
                LinkedList weekendList, LinkedList holidayList, long seed)
    {
        // initialised as per common observation of relative local
        // usage behavior of resource per hour in a day
        // NOTE: This is similar to background load of a resource
        double[] regularLoad = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,   // 0 - 6 am
                                 0.0, 0.1, 0.2, 0.4, 0.8, 1.0,   // 7 - 11 am
                                 1.0, 0.6, 0.6, 0.9, 1.0, 1.0,   // 12 - 5 pm
                                 0.5, 0.2, 0.1, 0.0, 0.0, 0.0 }; // 6 - 11.59pm

        this.timeZone_ = timeZone;
        init(regularLoad, peakLoad, offPeakLoad, relativeHolidayLoad, weekendList,
             holidayList, seed);
    }

    /**
     * Allocates a new ResourceCalendar object with a pre-defined daily regular load
     * @param regularLoad   the daily regular load, with range: [0 ... 1].
     *                      Note that regularLoad[0] represents time 00:00 (hh:mm),
     *                      and regularLoad[23] represents time 23:00.
     * @param timeZone      time zone
     * @param peakLoad      the load during peak time, with range: [0 ... 1]
     * @param offPeakLoad   the load during off peak time, with range: [0 ... 1]
     * @param relativeHolidayLoad   the load during holidays,
     *                              with range: [0 ... 1]
     * @param weekendList   a list of Integer numbers for weekends
     * @param holidayList   a list of Integer numbers for holidays
     * @param seed          the initial seed
     * @pre timeZone >= 0.0
     * @pre seed > 0
     * @post $none
     */
    public ResourceCalendar(double[] regularLoad, double timeZone, double peakLoad,
                double offPeakLoad, double relativeHolidayLoad,
                LinkedList weekendList, LinkedList holidayList, long seed)
    {
        this.timeZone_ = timeZone;
        init(regularLoad, peakLoad, offPeakLoad, relativeHolidayLoad, weekendList,
             holidayList, seed);
    }

    /**
     * Allocates a new ResourceCalendar object with a pre-defined daily regular load
     * @param regularLoad   the daily regular load, with range: [0 ... 1].
     *                      Note that regularLoad[0] represents time 00:00, and
     *                      regularLoad[23] represents time 23:00.
     * @param peakLoad      the load during peak time, with range: [0 ... 1]
     * @param offPeakLoad   the load during off peak time, with range: [0 ... 1]
     * @param relativeHolidayLoad   the load during holidays,
     *                              with range: [0 ... 1]
     * @param weekendList   a list of Integer numbers for weekends
     * @param holidayList   a list of Integer numbers for holidays
     * @param seed          the initial seed
     * @pre timeZone >= 0.0
     * @pre seed > 0
     * @post $none
     */
    private void init(double[] regularLoad, double peakLoad,
                double offPeakLoad, double relativeHolidayLoad,
                LinkedList weekendList, LinkedList holidayList, long seed)
    {
        this.weekendList_ = weekendList;
        this.holidayList_ = holidayList;
        random_ = new Random(seed);

        // load must be within [0 .. 1] range
        int FULL = 1;
        if (peakLoad > FULL) {
            peakLoad = FULL;
        }

        if (offPeakLoad > FULL) {
            offPeakLoad = FULL;
        }

        if (relativeHolidayLoad > FULL) {
            relativeHolidayLoad = FULL;
        }

        /////////////////
        double val = 0.0;
        double FACTOR = 0.1;
        int SIZE = regularLoad.length;
        int HOUR = 24;
        weekdayLoad_ = new double[HOUR];  // background load during weekdays
        holidayLoad_ = new double[HOUR];  // background load during holidays

        // for each hour in a day, determine the load during the weekday and
        // holiday
        for (int i = 0; i < regularLoad.length; i++)
        {
            val = regularLoad[i] * (peakLoad - offPeakLoad) + offPeakLoad;

            // background load during the week
            weekdayLoad_[i] = GridSimRandom.real( val, FACTOR, FACTOR,
                                    random_.nextDouble() );

            // background load during the holiday
            holidayLoad_[i] = GridSimRandom.real( relativeHolidayLoad * val,
                                    FACTOR, FACTOR, random_.nextDouble() );

            // if the load is full, it means that a resource can't process
            // any jobs. Hence, need to lower the load
            if (weekdayLoad_[i] >= FULL) {
                weekdayLoad_[i] = 0.95;
            }

            if (holidayLoad_[i] >= FULL) {
                holidayLoad_[i] = 0.95;
            }
        }

        if (regularLoad.length < HOUR)
        {
            System.out.println("ResourceCalendar(): Warning regularLoad[] must" +
                " be for 24 hours.\nThe loads in the remaining hours will set to zeros.");

            // then set remaining loads to zero
            for (int i = regularLoad.length; i < HOUR; i++)
            {
                weekdayLoad_[i] = 0;
                holidayLoad_[i] = 0;

            }
        } // end if
    }

    /**
     * Gets a Calendar object for a specified simulation time
     * @param simulationTime    the simulation time
     * @return a Calendar object
     * @throws NullPointerException if <tt>GridSim.init()</tt> has not been
     *              called before
     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre simulationTime >= 0.0
     * @post $result != null
     */
    public Calendar getCalendarAtSimulationTime(double simulationTime)
                throws NullPointerException
    {
        Calendar calendar = GridSim.getSimulationCalendar();
        Date date = GridSim.getSimulationCalendar().getTime();

        if (date == null)
        {
            throw new NullPointerException(
                    "ResourceCalendar.getCalendarAtSimulationTime() : Error - "+
                    "Need to call GridSim.init() first before using any of " +
                    "GridSim entities.");
        }

        // Set calendar time as the Simulation start date-time at 0:00:00 GMT
        calendar.setTime(date);

        // Adjust calendar time for time zone and simulation time
        calendar.add(Calendar.MINUTE, (int) (timeZone_ * TIME));
        calendar.add(Calendar.SECOND, (int) simulationTime);

        return calendar;
    }

    /**
     * Gets the current Calendar object (based on the simulation clock)
     * @return the current Calendar object
     * @throws NullPointerException if <tt>GridSim.init()</tt> has not been
     *              called before
     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @see eduni.simjava.Sim_system#clock()
     * @pre $none
     * @post $result != null
     */
    public Calendar getCurrentCalendar() throws NullPointerException {
        return this.getCalendarAtSimulationTime( Sim_system.clock() );
    }

    /**
     * Gets the current simulation time
     * @param localTime     a Calendar object
     * @return the current simulation time
     * @throws NullPointerException if localTime is <tt>null</tt>
     *              or <tt>GridSim.init()</tt> has not been
     *              called before
     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre localTime != null
     * @post $result >= 0.0
     */
    public double getSimulationTime(Calendar localTime)
                          throws NullPointerException
    {
        if (localTime == null) {
            throw new NullPointerException(
                    "ResourceCalendar.getSimulationTime() : Error - " +
                    "Calendar object must not be null.");
        }

        localTime.add( Calendar.MINUTE, (int) (timeZone_ * TIME) );

        Date date = GridSim.getSimulationCalendar().getTime();
        if (date == null)
        {
            throw new NullPointerException(
                    "ResourceCalendar.getSimulationTime() : Error - " +
                    "Need to call GridSim.init() first before using any of " +
                    "GridSim entities.");
        }

        Calendar start = getCalendarAtGivenDate(date);
        Date localDate = localTime.getTime();
        Date startDate = start.getTime();
        double time = (localDate.getTime() - startDate.getTime()) / 1000.0;

        return time;
    }

    /**
     * Gets a Calendar object at the specified date
     * @param date  the Date object
     * @return the Calendar object
     * @pre date != null
     * @post $result != null
     */
    public Calendar getCalendarAtGivenDate(Date date)
    {
        Calendar calendar = GridSim.getSimulationCalendar();
        if (calendar == null) {
            calendar = Calendar.getInstance();
        }

        calendar.setTime(date);

        // Adjust calendar time for time zone
        calendar.add( Calendar.MINUTE, (int) (timeZone_ * TIME) );
        return calendar;
    }

    /**
     * Checks whether the current simulation time is a holiday or not
     * @return <tt>true</tt> if it is a holiday, otherwise returns
     *         <tt>false</tt>
     * @throws NullPointerException if <tt>GridSim.init()</tt> has not been
     *              called before
     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre $none
     * @post $result == true || $result == false
     */
    public boolean isHoliday() throws NullPointerException
    {
        Calendar myCalendar = getCurrentCalendar();
        int day_of_year = myCalendar.get(Calendar.DAY_OF_YEAR);
        int day_of_week = myCalendar.get(Calendar.DAY_OF_WEEK);

        if (holidayList_ != null)
        {
            if ( holidayList_.contains(new Integer(day_of_year)) ) {
                return true;
            }
        }

        if (weekendList_ != null)
        {
            if ( weekendList_.contains(new Integer(day_of_week)) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Checks whether the given date is a holiday or not
     * @param date  the Date object
     * @return <tt>true</tt> if it is a holiday, otherwise returns
     *         <tt>false</tt>
     * @pre date != null
     * @post $result == true || $result == false
     */
    public boolean isHoliday(Date date)
    {
        if (holidayList_ == null) {
            return false;
        }

        Calendar myCalendar = getCalendarAtGivenDate(date);
        myCalendar.setTime(date);

        int day_of_year = myCalendar.get(Calendar.DAY_OF_YEAR);
        int day_of_week = myCalendar.get(Calendar.DAY_OF_WEEK);

        if (holidayList_ != null)
        {
            if ( holidayList_.contains(new Integer(day_of_year)) ) {
                return true;
            }
        }

        if (weekendList_ != null)
        {
            if (weekendList_.contains(new Integer(day_of_week)) ) {
                return true;
            }
        }

        return false;
    }

    /**
     * Gets the current load for the current simulation time
     * @return the current load
     * @throws NullPointerException if <tt>GridSim.init()</tt> has not been
     *              called before
     * @see gridsim.GridSim#init(int, Calendar, boolean, String[], String[],
     *          String)
     * @pre $none
     * @post $result >= 0.0
     */
    public double getCurrentLoad() throws NullPointerException
    {
        if ( isHoliday() ) {
            return holidayLoad_[getCurrentCalendar().HOUR_OF_DAY];
        }
        else {
            return weekdayLoad_[getCurrentCalendar().HOUR_OF_DAY];
        }
    }

}


text:
import java.util.*;

public class LogEvent {
  public int key;
  public int sourceAddr;
  public int seqno;
  public long nodeEventTime;
  public Date receiveTime;
  public String event;

  public String toString() {
    return key + " " + sourceAddr + " " + seqno + " " + receiveTime + " " + nodeEventTime + " " + event;
  }
}


text:
package com.amazonaws.services.securityhub.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.securityhub.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * VpcInfoCidrBlockSetDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class VpcInfoCidrBlockSetDetailsMarshaller {

    private static final MarshallingInfo<String> CIDRBLOCK_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("CidrBlock").build();

    private static final VpcInfoCidrBlockSetDetailsMarshaller instance = new VpcInfoCidrBlockSetDetailsMarshaller();

    public static VpcInfoCidrBlockSetDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(VpcInfoCidrBlockSetDetails vpcInfoCidrBlockSetDetails, ProtocolMarshaller protocolMarshaller) {

        if (vpcInfoCidrBlockSetDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(vpcInfoCidrBlockSetDetails.getCidrBlock(), CIDRBLOCK_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php
defined('ABSPATH') || exit;

/**
 * Created by PhpStorm.
 * the basic db handling and data exchange
 * User: hesk
 * Date: 4/23/14
 * Time: 10:36 PM
 */
if (!class_exists('gformBase')) {
    class gformBase
    {
        private static function get_mac()
        {
            exec("ipconfig /all", $arr, $retval);
            $arr[14];
            $ph = explode(":", $arr[14]);
            return trim($ph[1]);
        }

        public static function gen_order_num()
        {
            function make_seed()
            {
                list($usec, $sec) = explode(' ', microtime());
                return (float)$sec + ((float)$usec * 100000);
            }

            mt_srand(make_seed());
            return $randval = mt_rand();

        }

        public static function gen_order_str()
        {
            /* Generated a unique order number */

            $str = session_id();
            $str .= (string)time();
            $checksum = crc32($str);
            $date = date('Y-m-d');
            $order_number = $date . $checksum;

            return substr($order_number, 0, 19);
        }

        /**
         * if the entry row exist or not come to here
         * @param $form_id
         * @param $lead_id
         * @return bool
         */
        protected static function gf_entry_row_exist($form_id, $lead_id)
        {
            global $wpdb;
            $sql = $wpdb->prepare("SELECT COUNT(*)
                                   FROM {$wpdb->prefix}rg_lead
                                   WHERE form_id=%d AND id=%d", $form_id, $lead_id);
            $value = $wpdb->get_var($sql);
            if (intval($value) > 0) return true;
            else return false;

        }

        /**
         * @param $field_name
         * @return int
         */
        protected static function convert_field_name_to_id($field_name)
        {
            preg_match('/^\w+(\d+)$/U', $field_name, $match);
            $entry_index = strtolower($match[1]);
            return $entry_index;
        }

        /**
         * get list from gform entries with the form ID
         * @param $form_id
         * @return mixed
         */
        protected static function gf_get_form_entries($form_id)
        {
            global $wpdb;
            $table = $wpdb->prefix . "rg_lead";
            $listed = $wpdb->get_results("SELECT * FROM $table WHERE form_id=" . $form_id . " AND status='active' ORDER BY date_created DESC");
            return $listed;
        }

        protected static function gf_update_field_value($form_id, $lead_id, $field_id, $value_replacement)
        {
            global $wpdb;
            $table = $wpdb->prefix . "rg_lead_detail";
            $sql = "SELECT * FROM $table WHERE id=%d AND form_id=%d AND field_number=%d";
            $sql = $wpdb->prepare($sql, $form_id, $lead_id, $field_id);
            $result = $wpdb->get_row($sql);

            $insert = array(
                "form_id" => $form_id,
                "lead_id" => $lead_id,
                "field_number" => $field_id,
                "value" => $value_replacement,
            );

            if (!$result) {
                $rs = $wpdb->insert($table, $insert);
            } else {
                $rs = $wpdb->update($table, $insert, array('id' => $result->id));
            }
            return $rs;
        }

        public static function gf_get_entry_value($form_id, $lead_id, $field_id)
        {
            global $wpdb;
            /*       $sql =  $wpdb->prepare("SELECT l.*, d.field_number, d.value
                                          FROM {$wpdb->prefix}rg_lead l
                                          INNER JOIN {$wpdb->prefix}rg_lead_detail d ON l.id = d.lead_id
                                          INNER JOIN {$wpdb->prefix}rg_lead_meta m ON l.id = m.lead_id
                                          WHERE m.meta_key=%s AND m.meta_value=%s", $meta_key, $meta_value);*/

            $table = $wpdb->prefix . "rg_lead_detail";
            $sql = $wpdb->prepare("SELECT value
                                   FROM $table
                                   WHERE form_id=%d AND lead_id=%d AND field_number=%d", $form_id, $lead_id, $field_id);
            $value = $wpdb->get_var($sql);
            return $value;
        }

        /**
         * @param $field_id
         * @return mixed
         */
        protected static function getPostJson($field_id)
        {
            return json_decode(trim(rgpost("input_" . $field_id)));
        }

        /**
         * @param $field_id
         * @return string
         */
        protected static function getPostVal($field_id)
        {
            return trim(rgpost("input_" . $field_id));
        }

        /**
         * confirmation message template
         * @param $lead_id
         * @param null $format
         * @return string
         */
        protected static function confirm_msg($lead_id, $format = null)
        {
            if ($format == null) {
                $msg_format = __("Thank you for you registeration and we will process your application soon. ref. no # %d", HKM_LANGUAGE_PACK);
            } else $msg_format = $format;
            return sprintf($msg_format, $lead_id);
        }

        protected static function filter_form_value($form, int $field_id, $value)
        {

            foreach ($form["fields"] as $field) {

                if ($field_id == $field["id"]) {

                    $field["value"] = $value;
                }
            }

            return $form;
        }

        protected static function set_input_value($field_id, $value)
        {
            if (isset($_POST["input_" . $field_id]))
                $_POST["input_" . $field_id] = $value;
        }

        /**}
         * ignore
         * @param $forms_id
         * @return array
         */
        /*   protected static function getSettingParams($forms_id)
           {
               $forms = array(
                   "service_order_cr" => GF_SERVICE_ORDER_FORM,
                   "service_order_internal" => GF_SERVICE_ORDER_FORM_INTERNAL,
               );
               $head = "#input_" . $forms_id . "_";
               switch ($forms_id) {
                   case GF_SERVICE_ORDER_FORM:

                       if (is_user_logged_in() && parent::has_role("cr")) {
                           $memberid = get_current_user_id();
                       } else {
                           $memberid = "";
                       }
                       return array(
                           "head" => $head,
                           "ff_geoloc" => $head . ff_geoloc,
                           "ff_expectdate" => $head . ff_expectdate,
                           "ff_expectedtime" => $head . ff_expectedtime,
                           "ff_cr_id" => $head . ff_cr_id,
                           "field_value_cr_id" => $memberid,
                           "form_id" => $forms_id,
                           "form_type" => $forms,
                           "ff_order_service_detail" => $head . ff_table_service
                       );
                   case GF_SERVICE_ORDER_FORM_INTERNAL:
                       if (is_user_logged_in() && parent::has_role("ocstaff")) {
                           $memberid = get_current_user_id();
                       } else {
                           $memberid = "";
                       }
                       return array(
                           "head" => $head,
                           "ff_geoloc" => $head . ff_geoloc,
                           "ff_expectdate" => $head . ff_expectdate,
                           "ff_expectedtime" => $head . ff_expectedtime,
                           "ff_staff_id" => $head . ff_staff_id,
                           "ff_client_id" => $head . ff_client_company,
                           "field_value_staff_id" => $memberid,
                           "form_id" => $forms_id,
                           "form_type" => $forms,
                           "ff_order_service_detail" => $head . ff_table_service,
                           "company_selection_html" => oc_project::select_ui()
                       );
                   case GF_REP_REGISTRATION_FORM:
                       $head = "#input_" . GF_REP_REGISTRATION_FORM . "_";
                       return array(
                           "head" => $head,
                           "ff_nicename" => $head . fieldid_nicename,
                           "ff_displayname" => $head . fieldid_displayname,
                           "ff_expectedtime" => $head . fieldid_useremail,
                           "ff_phonenumber" => $head . fieldid_phonenumber,
                           "ff_name" => $head . fieldid_name,
                           "ff_companyname" => $head . fieldid_companyname,

                       );
                   case GF_NEW_COM_FORM:
                       $head = "#input_" . GF_NEW_COM_FORM . "_";
                       return array(
                           "head" => $head,
                           "nc_comfullname" => $head . nc_comfullname,
                           "nc_conshortname" => $head . nc_conshortname,
                           "nc_contactemail" => $head . nc_contactemail,
                           "nc_contactfax" => $head . nc_contactfax,
                           "nc_contactnumber" => $head . nc_contactnumber,
                           "nc_contactname" => $head . nc_contactname,

                           "nc_cr_reg_info_json" => $head . nc_cr_reg_info_json,

                           "nc_brfile" => $head . nc_brfile,
                           "nc_brissuedate" => $head . nc_brissuedate,
                           "nc_brnumber" => $head . nc_brnumber,

                           "form_id" => $forms_id,
                           "form_type" => $forms,
                       );

                   default:
                       return array();
               }
           }*/
    }
}


text:
package org.apache.flink.table.catalog;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.Schema;
import org.apache.flink.table.api.TableSchema;

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

/**
 * An implementation of catalog view.
 *
 * @deprecated Use {@link CatalogView#of(Schema, String, String, String, Map)} or a custom
 *     implementation instead. Don't implement against this internal class. It can lead to
 *     unintended side effects if code checks against this class instead of the common interface.
 */
@Deprecated
@Internal
public class CatalogViewImpl extends AbstractCatalogView {
    public CatalogViewImpl(
            String originalQuery,
            String expandedQuery,
            TableSchema schema,
            Map<String, String> properties,
            String comment) {
        super(originalQuery, expandedQuery, schema, properties, comment);
    }

    @Override
    public CatalogBaseTable copy() {
        return new CatalogViewImpl(
                getOriginalQuery(),
                getExpandedQuery(),
                getSchema().copy(),
                new HashMap<>(getOptions()),
                getComment());
    }

    @Override
    public Optional<String> getDescription() {
        return Optional.ofNullable(getComment());
    }

    @Override
    public Optional<String> getDetailedDescription() {
        return Optional.of("This is a catalog view implementation");
    }
}


text:
require 'date'
require 'markdo/commands/command'

module Markdo
  class ProcessCommand < Command
    def initialize(*)
      super
      @lines_by_filename = Hash.new { [] }
      @lines = File.readlines(data_source.inbox_path)
      @line_index = 0
    end

    def run
      catch :abort do
        while has_lines?
          line = current_line
          choice = prompt(line)

          case choice
          when 'h'
            show_help
          when 'i'
            move_line_to(@env['MARKDO_INBOX'], line)
          when 's'
            move_line_to('Sprint.md', line)
          when 'b'
            move_line_to('Backlog.md', line)
          when 'm'
            move_line_to('Maybe.md', line)
          when 'a'
            throw :abort
          end
        end

        write_files
      end
    end

    private

    def has_lines?
      @line_index < @lines.length
    end

    def current_line
      @lines[@line_index]
    end

    def prompt(line)
      @stdout.puts line
      @stdout.print 'File [hisbma]? '

      input_line = @stdin.gets

      @stdout.puts

      if input_line.nil?
        throw :abort
      else
        input_line.chomp.downcase
      end
    end

    def move_line_to(filename, line)
      @lines_by_filename[filename] <<= line
      @line_index += 1
    end

    def write_files
      inbox_lines = @lines_by_filename.delete(@env['MARKDO_INBOX'])
      File.write(data_source.inbox_path, inbox_lines ? inbox_lines.join : '')

      @lines_by_filename.each do |filename, lines|
        path = data_source.file_path(filename)
        new_content = ["\n## Processed on #{@today.iso8601}\n\n"] << lines

        File.open(path, 'a') do |file|
          file.puts(new_content.join)
        end
      end
    end

    def show_help
      @stdout.puts 'i - inbox (keep in inbox)'
      @stdout.puts 's - sprint'
      @stdout.puts 'b - backlog'
      @stdout.puts 'm - maybe'
      @stdout.puts 'a - abort; make no changes'
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Administration;

namespace WebsitePanel.Providers.Web.Handlers
{
	internal sealed class HandlerActionCollection : ConfigurationElementCollectionBase<HandlerAction>
	{
		// Methods
		public HandlerAction AddAt(int index, string name, string path, string verb)
		{
			HandlerAction element = base.CreateElement();
			element.Name = name;
			element.Path = path;
			element.Verb = verb;
			return base.AddAt(index, element);
		}

		public HandlerAction AddCopy(HandlerAction action)
		{
			HandlerAction destination = base.CreateElement();
			CopyInfo(action, destination);
			return base.Add(destination);
		}

		public HandlerAction AddCopyAt(int index, HandlerAction action)
		{
			HandlerAction destination = base.CreateElement();
			CopyInfo(action, destination);
			return base.AddAt(index, destination);
		}

		private static void CopyInfo(HandlerAction source, HandlerAction destination)
		{
			destination.Name = source.Name;
			destination.Modules = source.Modules;
			destination.Path = source.Path;
			destination.PreCondition = source.PreCondition;
			destination.RequireAccess = source.RequireAccess;
			destination.ResourceType = source.ResourceType;
			destination.ScriptProcessor = source.ScriptProcessor;
			destination.Type = source.Type;
			destination.Verb = source.Verb;
		}

		protected override HandlerAction CreateNewElement(string elementTagName)
		{
			return new HandlerAction();
		}

		// Properties
		public new HandlerAction this[string name]
		{
			get
			{
				for (int i = 0; i < base.Count; i++)
				{
					HandlerAction action = base[i];
					if (string.Equals(action.Name, name, StringComparison.OrdinalIgnoreCase))
					{
						return action;
					}
				}
				return null;
			}
		}
	}

}


text:
import numpy as np
import matplotlib.pyplot as plt

from shapely.geometry.polygon import Polygon
from shapely.geometry import MultiPolygon

import cell_tree2d

# create a rotated Cartesian grid
xc, yc = np.mgrid[1:10:15j, 1:20:18j]
yc = yc**1.2 + xc**1.5

def rot2d(x, y, ang):
    '''rotate vectors by geometric angle'''
    xr = x*np.cos(ang) - y*np.sin(ang)
    yr = x*np.sin(ang) + y*np.cos(ang)
    return xr, yr

x, y = rot2d(xc, yc, 0.2)
y /= 10.0

x -= x.mean()
y -= y.mean()

# Create nodes and faces from grid
nodes = np.ascontiguousarray(np.column_stack((x[:].reshape(-1),
                                              y[:].reshape(-1)))).astype(np.float64)
y_size = x.shape[0]
x_size = y.shape[1]
faces = np.array([np.array([[xi, xi + 1, xi + x_size + 1, xi + x_size]
                            for xi in range(0, x_size - 1, 1)]) + yi * x_size for yi in range(0, y_size - 1)])
faces = np.ascontiguousarray(faces.reshape(-1, 4).astype(np.int32))

squares = [nodes[face] for face in faces]

## Convert to a bunch of shapely Polygon objects, for some unknown use.
# mesh = MultiPolygon([Polygon(p) for p in squares])

## Extra functions for plotting the grid
# for square in squares:
#      x, y = square.T
#      plt.fill(x, y)
#
# plt.gca().set_aspect(1.0)
# plt.show()

# Create some trial points and locate them using cell_tree
xyi = np.random.randn(10, 2)

ct = cell_tree2d.CellTree(nodes, faces)
idx = ct.locate(xyi)


text:
if [ "$TEST_SCRIPT" != "" ]
then
        #for testing locally
        PROP_FILE=application.properties
else
	PROP_FILE=hygieia-versionone-feature-collector.properties
fi

if [ "$MONGO_PORT" != "" ]; then
	# Sample: MONGO_PORT=tcp://172.17.0.20:27017
	MONGODB_HOST=`echo $MONGO_PORT|sed 's;.*://\([^:]*\):\(.*\);\1;'`
	MONGODB_PORT=`echo $MONGO_PORT|sed 's;.*://\([^:]*\):\(.*\);\2;'`
else
	env
	echo "ERROR: MONGO_PORT not defined"
	exit 1
fi

echo "MONGODB_HOST: $MONGODB_HOST"
echo "MONGODB_PORT: $MONGODB_PORT"

cat > $PROP_FILE <<EOF
#Database Name
dbname=${HYGIEIA_API_ENV_SPRING_DATA_MONGODB_DATABASE:-dashboard}

#Database HostName - default is localhost
dbhost=${MONGODB_HOST:-10.0.1.1}

#Database Port - default is 27017
dbport=${MONGODB_PORT:-27017}

#Database Username - default is blank
dbusername=${HYGIEIA_API_ENV_SPRING_DATA_MONGODB_USERNAME:-db}

#Database Password - default is blank
dbpassword=${HYGIEIA_API_ENV_SPRING_DATA_MONGODB_PASSWORD:-dbpass}

#Page size for data calls (VersionOne recommended 2000)
feature.pageSize=${VERSIONONE_PAGE_SIZE:-2000}

#In-built folder housing prepared REST queries (required)
feature.queryFolder=${VERSIONONE_QUERY_FOLDER:-v1api-queries}

#Jira API Query file names (String template requires the files to have .st extension) (required)
feature.storyQuery=${VERSIONONE_STORY_QUERY:-story}
feature.epicQuery=${VERSIONONE_EPIC_QUERY:-epicinfo}
feature.projectQuery=${VERSIONONE_PROJECT_QUERY:-projectinfo}
feature.memberQuery=${VERSIONONE_MEMBBER_QUERY:-memberinfo}
feature.sprintQuery=${VERSIONONE_SPRINT_QUERY:-sprintinfo}
feature.teamQuery=${VERSIONONE_TEAM_QUERY:-teaminfo}
feature.trendingQuery${{VERSIONONE_TRENDING_QUERY:-trendinginfo}

# Trending Query:  Number of days in a sprint (not-required)
feature.sprintDays=${VERSIONONE_SPRINT_DAYS:-60}
# Trending Query:  Length of sprint week (not-required)
feature.sprintEndPrior=${VERSIONONE_SPRINT_END_PRIOR:-7}

#Scheduled Job prior minutes to recover data created during execution time (usually, 2 minutes is enough)
feature.scheduledPriorMin=${VERSIONONE_SCHEDULED_PRIOR_MIN:-2}

#Delta change date that modulates the collector item task - should be about as far back as possible, in ISO format (required)
feature.deltaCollectorItemStartDate=${VERSIONONE_DELTA_COLLECTORITEM_START_DATE:-2008-01-01T00:00:00.000000}

#VersionOne Connection Details
#Proxy assumes a host:port syntax
feature.versionOneProxyUrl=${VERSIONONE_PROXY_URL:-""}
feature.versionOneBaseUri=${VERSIONONE_URL:-https://www.versionone.com/our-company-instance/}
#Access token provided by VersionOne
feature.versionOneAccessToken=${VERSIONONE_ACCESS_TOKEN:-accessToken}

#Start dates from which to begin collector data, if no other data is present - usually, a month back is appropriate (required)
feature.deltaStartDate=${VERSIONONE_DELTA_START_DATE:-2015-03-01T00:00:00.000000}
feature.masterStartDate=${VERSIONONE_MASTER_START_DATE:-2008-01-01T00:00:00.000000}

EOF

echo "

===========================================
Properties file created `date`:  $PROP_FILE
Note: passwords hidden
===========================================
`cat $PROP_FILE |egrep -vi password`
 "

exit 0


text:
"""Train a Fast R-CNN network."""

import caffe
from caffe.proto import caffe_pb2

# for action recognition task in still/static images
from fast_rcnn.config_action import cfg
import action_roi_data_layer.roidb as ardl_roidb

from utils.timer import Timer
import numpy as np
import os, sys
import google.protobuf as pb2

#
class SolverWrapper(object):
  """A simple wrapper around Caffe's solver.
  This wrapper gives us control over he snapshotting process, which we
  use to unnormalize the learned bounding-box regression weights.
  """

  def __init__(self, solver_prototxt, roidb, output_dir,
               pretrained_model=None, re_iter=None):
    """Initialize the SolverWrapper."""
    self.output_dir = output_dir
    self.re_iter = re_iter

    print 'Computing bounding-box regression targets...'
    self.bbox_means, self.bbox_stds = \
            ardl_roidb.add_bbox_regression_targets(roidb)
    print 'Computing bounding-box regression targets done...'
    print

    # Initialize Solver
    print "Using SGDSolver for network..."
    self.solver = caffe.SGDSolver(solver_prototxt)

    print "Get solver_param..."
    if pretrained_model is not None:
      print ('Loading pretrained model '
             'weights from {:s}').format(pretrained_model)
      self.solver.net.copy_from(pretrained_model)
    self.solver_param = caffe_pb2.SolverParameter()
    #
    with open(solver_prototxt, 'rt') as f:
      pb2.text_format.Merge(f.read(), self.solver_param)

    # Set roidb for the datalayer
    # See ../action_roi_data_layer/layer.py - set_roidb
    self.solver.net.layers[0].set_roidb(roidb)

  def snapshot(self):
    """Take a snapshot of the network after unnormalizing the learned
    bounding-box regression weights. This enables easy use at test-time.
    """
    net = self.solver.net

    if cfg.TRAIN.BBOX_REG:
      # save original values
      orig_0 = net.params['bbox_pred'][0].data.copy()
      orig_1 = net.params['bbox_pred'][1].data.copy()

      # scale and shift with bbox reg unnormalization; then save snapshot
      net.params['bbox_pred'][0].data[...] = \
              (net.params['bbox_pred'][0].data *
               self.bbox_stds[:, np.newaxis])
      net.params['bbox_pred'][1].data[...] = \
              (net.params['bbox_pred'][1].data *
               self.bbox_stds + self.bbox_means)

    #  build the directory
    if not os.path.exists(self.output_dir):
      os.makedirs(self.output_dir)

    infix = ('_' + cfg.TRAIN.SNAPSHOT_INFIX
             if cfg.TRAIN.SNAPSHOT_INFIX != '' else '')
    filename = (self.solver_param.snapshot_prefix + infix +
                '_iter_{:d}'.format(self.solver.iter) + '.caffemodel')
    filename = os.path.join(self.output_dir, filename)

    print "snapshoted filename:", filename
    net.save(str(filename))
    print 'Wrote snapshot to: {:s}'.format(filename)

    if cfg.TRAIN.BBOX_REG:
      # restore net to original state
      net.params['bbox_pred'][0].data[...] = orig_0
      net.params['bbox_pred'][1].data[...] = orig_1

  def train_model(self, max_iters):
    """Network training loop."""
    last_snapshot_iter = -1
    if self.re_iter is not None:
      re_iter = int(self.re_iter)
      if re_iter > 0:
        print
        print "retrain network from", re_iter, "iteration!"
        print
        import time
        time.sleep(2)
        self.solver.set_iter(re_iter)
    #
    timer = Timer()
    print
    print
    print "start train network!"

    while self.solver.iter < max_iters:
      timer.tic()
      # Make one SGD update -- forward & backward
      self.solver.step(1)
      timer.toc()
      #
      if self.solver.iter % (10 * self.solver_param.display) == 0:
        print 'speed: {:.3f}s / iter'.format(timer.average_time)

      if self.solver.iter % cfg.TRAIN.SNAPSHOT_ITERS == 0:
        last_snapshot_iter = self.solver.iter
        self.snapshot()

    if last_snapshot_iter != self.solver.iter:
      self.snapshot()

    print
    print "Training network has been done!"
    print

# ##################################################

#
def get_training_roidb(imdb):
  """Returns a roidb (Region of Interest database) for use in training."""
  if cfg.TRAIN.USE_FLIPPED:
    print 'Appending horizontally-flipped training examples...'
    imdb.append_flipped_images()
    print 'done!'
    print

  #
  print 'Preparing training data...'
  ardl_roidb.prepare_roidb(imdb, cfg.TRAIN_PHASE)
  print 'done!'
  print

  return imdb.roidb

#
def train_net(solver_prototxt, roidb, output_dir,
            pretrained_model=None, max_iters=40000, \
            exper_name=None, re_iter=None):
  """Train a Fast R-CNN network."""
  if exper_name:
    output_dir = os.path.join(output_dir, exper_name)
    print
    print "output_dir (final):", output_dir
    print
  #
  sw = SolverWrapper(solver_prototxt, roidb, output_dir,
                     pretrained_model=pretrained_model, \
                     re_iter=re_iter)

  print
  print 'Solving...'
  print
  sw.train_model(max_iters)
  print
  print 'Done solving...'
  print


text:
package DDG::Spice::Currency;
# ABSTRACT: Currency Convertor provided by XE.com

use strict;
use DDG::Spice;
with 'DDG::SpiceRole::NumberStyler';
use Text::Trim;
use YAML::XS qw(LoadFile);

primary_example_queries "convert 499 usd to cad";
secondary_example_queries "cad to usd", "cny?";
description "Currency Convertor provided by XE.com";
name "Currency";
source "XE.com";
icon_url "/i/xe.com.ico";
code_url "https://github.com/XenonLab/blob/master/lib/DDG/Spice/Currency.pm";
category "finance";
topics "economy_and_finance", "geography", "travel", "everyday";
attribution web => ['http://www.xe.com', 'xe.com'],
            github => ['https://github.com/laouji','Crimson Thompson'],
            twitter => ['https://twitter.com/laouji','Crimson Thompson'];

# Get all the valid currencies from a text file.
my @currTriggers;
my @currencies = share('currencyNames.txt')->slurp;
my %currHash = ();

# load decimal => unicode currency codes
my $currencyCodes = LoadFile share("currencySymbols.yml");

foreach my $currency (@currencies){
    chomp($currency);
    my @currency = split(/,/,$currency);
    push(@currTriggers, @currency);
    $currHash{$currency[0]} = \@currency;
}

# Define the regexes here.
my $currency_qr = join('|', @currTriggers);
my $into_qr = qr/\s(?:en|in|to|in ?to|to)\s/i;
my $vs_qr = qr/\sv(?:ersu|)s\.?\s/i;
my $question_prefix = qr/(?:convert|what (?:is|are|does)|how (?:much|many) (?:is|are))?\s?/;
my $number_re = number_style_regex();
my $cardinal_re = join('|', qw(hundred thousand k million m billion b trillion));

my $guard = qr/^$question_prefix(\p{Currency_Symbol})?($number_re*)\s?($cardinal_re)?\s?($currency_qr)?(?:s)?(?:$into_qr|$vs_qr|\s)?($number_re*)\s?($currency_qr)?(\p{Currency_Symbol})?(?:s)?\??$/i;

triggers query_lc => qr/\p{Currency_Symbol}|$currency_qr/;

spice from => '([^/]+)/([^/]+)/([^/]+)';
spice to => 'http://www.xe.com/tmi/xe-output.php?amount=$1&from=$2&to=$3&appid={{ENV{DDG_SPICE_CURRENCY_APIKEY}}}';
spice wrap_jsonp_callback => 1;
spice is_cached => 0;
spice proxy_cache_valid => "200 5m";

# This function converts things like "us dollars" to the standard "usd".
sub getCode {
    my $input = shift;
    foreach my $key (keys %currHash) {
        if(exists $currHash{$key}) {
            my @currValues = @{$currHash{$key}};
            foreach my $value (@currValues) {
                if($input eq $value) {
                    return $key;
                }
            }
        }
    }
}

# This function is responsible for processing the input.
# - Setting default values.
# - Checking if the input number is valid.
sub checkCurrencyCode {
    my($amount, $from, $to) = @_;

    # Check if it's a valid number.
    # If it isn't, return early.
    my $styler = number_style_for($amount);
    return unless $styler;

    # Choose the default currency.
    # If the user types in 10 usd, it should default to eur.
    # If the user types in 10 eur, it should default to usd.
    # my $default_to = getCode($from) eq "usd" ? "eur" : "usd";

    my $normalized_number = $styler->for_computation($amount);

    # There are cases where people type in "2016 euro" or "1999 php", so we don't want to trigger on those queries.
    if($normalized_number >= 1900 && $normalized_number < 2100 && (length($from) == 0 || length($to) == 0)) {
        return;
    }

    $from = getCode($from) || '';
    $to = getCode($to) || '';

    # Return early if we get a query like "usd to usd".
    if($from eq $to) {
        return;
    }

    # Return early if we don't get a currency to convert from.
    if($from eq '') {
        return;
    }

    # If we don't get a currency to convert to, e.g., the user types in "usd"
    # we set them to be the same thing. This will trigger our tile view.
    if($to eq '') {
        if($normalized_number == 1) {
            $to = $from;
        } else {
            # This should probably depend on the user's location.
            # For example, if I was in the Philippines, I would expect "10 usd" to mean "10 usd to php"
            # But this would mean mapping currencies to countries.
            $to = $from eq 'usd' ? 'eur' : 'usd';
        }
    }

    return $normalized_number, $from, $to;
}

handle query_lc => sub {

    if(/$guard/) {

        my ($fromSymbol, $amount, $cardinal, $from, $alt_amount, $to, $toSymbol) = ($1 || '', $2, $3 || '', $4 || '', $5 || '' , $6 || '', $7 || '');

        if ($from eq '' && $fromSymbol) {
            $from = $currencyCodes->{ord($fromSymbol)};
        }

        if ($to eq '' && $toSymbol) {
            $to = $currencyCodes->{ord($toSymbol)};
        }

        my $styler = number_style_for($amount);
        return unless $styler;

        if ($cardinal ne '') {
            $amount = $styler->for_computation($amount);

            if ($cardinal eq 'hundred')  { $amount *= 100 }
            elsif ($cardinal =~ /(thousand|k)/i) { $amount *= 1000 }
            elsif ($cardinal =~ /(million|m)/i)  { $amount *= 1000000 }
            elsif ($cardinal =~ /(billion|b)/i)  { $amount *= 1000000000 }
            elsif ($cardinal =~ /(trillion|t)/i) { $amount *= 1000000000000 }
        }

        # If two amounts are available, exit early. It's ambiguous.
        # We use the length function to check if it's an empty string or not.
        if(length($amount) && length($alt_amount)) {
            return;
        }
        # Case where the first amount is available.
        elsif(length($amount)) {
            return checkCurrencyCode($amount, $from, $to);
        }
        # Case where the second amount is available.
        # We switch the $from and $to here.
        elsif(length($alt_amount)) {
            return checkCurrencyCode($alt_amount, $to, $from);
        }
        # Case where neither of them are available.
        else {
            return checkCurrencyCode(1, $from, $to);
        }
    }

    return;
};

1;


text:
var dogs = ['pug','bulldog','chow chow','great dane']

var myFav = dogs[Math.floor(Math.random()*dogs.length)]

var fav = prompt("What is your favorite dog?");

alert("Your favorite breed is " + fav + "? " + "Mine is " + myFav )

if (yourSelection === myFavorite) {
  alert("We're besties!");
} else {
  alert("You're wrong!");
}


text:
require 'omniauth/nordea/version'
require 'omniauth/strategies/nordea'


text:
// Copyright 2021 Google Inc.
//
// 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.

using Xunit;

[Collection(nameof(SpannerFixture))]
public class ListInstanceConfigsTest
{
    private readonly SpannerFixture _spannerFixture;

    public ListInstanceConfigsTest(SpannerFixture spannerFixture)
    {
        _spannerFixture = spannerFixture;
    }

    [Fact]
    public void TestListInstanceConfigs()
    {
        var sample = new ListInstanceConfigsSample();
        var configs = sample.ListInstanceConfigs(_spannerFixture.ProjectId);
        Assert.NotNull(configs);
    }
}


text: To build docs, run `phpdoc -t ./docs -d ./src  --title DMS`


text:
package proguard.evaluation.value;

import proguard.classfile.*;

/**
 * This identified value factory creates array reference values that also
 * represent their elements, in as far as possible.
 *
 * @author Eric Lafortune
 */
public class DetailedValueFactory
extends      IdentifiedValueFactory
{
    // Implementations for ReferenceValue.

    public ReferenceValue createArrayReferenceValue(String       type,
                                                    Clazz        referencedClass,
                                                    IntegerValue arrayLength)
    {
        return type == null ?
            REFERENCE_VALUE_NULL :
            new DetailedArrayReferenceValue(ClassConstants.TYPE_ARRAY + type,
                                            referencedClass,
                                            arrayLength,
                                            this,
                                            referenceID++);
    }
}


text:
using System.Collections.Generic;

namespace TrieNET
{
    public class TrieNode
    {
        public bool EndOfWord { get; set; }
        public Dictionary<char, TrieNode> Children { get; set; }

        public TrieNode()
        {
            Children = new Dictionary<char, TrieNode>();
        }

        public TrieNode(bool isLast)
        {
            Children = new Dictionary<char, TrieNode>();
            EndOfWord = isLast;
        }
    }

    public class TrieNodeEqualityComparer : IEqualityComparer<TrieNode>
    {
        public bool Equals(TrieNode x, TrieNode y)
        {
            if (x == null && y == null)
                return true;
            if (x == null || y == null || x.EndOfWord != y.EndOfWord)
                return false;
            foreach (var xPair in x.Children)
            {
                if (!y.Children.ContainsKey(xPair.Key))
                    return false;
                if (!Equals(y.Children[xPair.Key], xPair.Value))
                    return false;
            }
            return true;
        }

        public int GetHashCode(TrieNode obj)
        {
            return base.GetHashCode();
        }
    }
}


text:
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information.

namespace Narvalo.Web
{
    using System.Web.Mvc;

    public static class HttpVerbsExtensions
    {
        public static bool Contains(this HttpVerbs @this, HttpVerbs value) => (@this & value) != 0;
    }
}


text:
@interface JS_Fixture : JS_BaseClass {

	b2Fixture * m_b2Fixture;
	JSObjectRef m_aabb;
	JSObjectRef m_next;
	JSObjectRef m_body;
	JSObjectRef m_shape;
	JSObjectRef m_filter;
}

@property (readonly) b2Fixture * m_b2Fixture;

@end


text:
package com.birdcopy.BirdCopyApp.MainHome;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.birdcopy.BirdCopyApp.ChannelManage.AlbumData;
import com.birdcopy.BirdCopyApp.ChannelManage.ChannelItem;
import com.birdcopy.BirdCopyApp.Component.Adapter.HomeFragmentPagerAdapter;
import com.birdcopy.BirdCopyApp.Component.UI.ColumnHorizontalScrollView;
import com.birdcopy.BirdCopyApp.ContentList.LessonListFragment;
import com.birdcopy.BirdCopyApp.DataManager.FlyingDataManager;
import com.birdcopy.BirdCopyApp.Http.FlyingHttpTool;
import com.birdcopy.BirdCopyApp.R;
import com.birdcopy.BirdCopyApp.Component.Tools.BaseTools;

import java.util.ArrayList;

/**
 * Created by BirdCopyApp on 22/7/14.
 */
public class TabContentFragment extends Fragment
{
    private View tablConent;

    //记录菜单位置
    private int mDrawMenuPosition=MainActivity.homeMenuPostion;

    /** 用户选择的新闻分类列表*/
    private ArrayList<ChannelItem> mUserChannelList=null;

    /** 左阴影部分*/
    private ImageView mShadeleft;
    /** 右阴影部分 */
    private ImageView mShaderight;

    /** 当前选中的栏目*/
    private int columnSelectIndex = 0;

    /** 自定义HorizontalScrollView */
    private ColumnHorizontalScrollView mColumnHorizontalScrollView;
    LinearLayout mRadioGroup_content;
    RelativeLayout rl_column;
    private ImageView button_more_columns;
    LinearLayout ll_more_columns;

    private ViewPager mViewPager;

    /** 屏幕宽度 */
    private int mScreenWidth = 0;
    /** Item宽度 */
    //private int mItemWidth = 0;
    private ArrayList<Fragment> fragments = new ArrayList<Fragment>();

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        mScreenWidth = BaseTools.getWindowsWidth(getActivity());
        //mItemWidth = mScreenWidth /4;// 一个Item宽度为屏幕的1/4
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        super.onCreateView(inflater,container,savedInstanceState);

        tablConent = (View)inflater.inflate(R.layout.tabcontent, null);

        mShadeleft = (ImageView) tablConent.findViewById(R.id.shade_left);
        mShaderight = (ImageView) tablConent.findViewById(R.id.shade_right);

        mColumnHorizontalScrollView =  (ColumnHorizontalScrollView)tablConent.findViewById(R.id.mColumnHorizontalScrollView);
        mRadioGroup_content = (LinearLayout) tablConent.findViewById(R.id.mRadioGroup_content);
        ll_more_columns = (LinearLayout) tablConent.findViewById(R.id.ll_more_columns);
        rl_column = (RelativeLayout) tablConent.findViewById(R.id.rl_column);
        button_more_columns = (ImageView) tablConent.findViewById(R.id.button_more_columns);

        button_more_columns.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v)
            {
                MainActivity mainActivity=(MainActivity)getActivity();
                mainActivity.showMoreColumn();
            }
        });

        mViewPager = (ViewPager) tablConent.findViewById(R.id.mTableContentViewPager);

        return tablConent;
    }

    /** 此方法意思为fragment是否可见 ,可见时候加载数据 */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser)
    {
        if (isVisibleToUser)
        {
            //fragment可见时加载数据
            if(mShadeleft !=null && mUserChannelList.size() !=0)
            {
                initAndShowView();
            }
            else
            {
                if (FlyingHttpTool.checkNetWorkStatus()==true)
                {
                    loadChannelData(mDrawMenuPosition);
                }
                else
                {
                    loadChannelData(mDrawMenuPosition);
                }
            }
        }

        super.setUserVisibleHint(isVisibleToUser);
    }

    public void  setDrawMenuPosition(int drawMenuPosition)
    {
        if(mDrawMenuPosition!=drawMenuPosition)
        {
            mDrawMenuPosition=drawMenuPosition;

            if(mUserChannelList!=null)
            {
                mUserChannelList.clear();
            }

            if (FlyingHttpTool.checkNetWorkStatus()==true)
            {
                loadChannelData(drawMenuPosition);
            }
            else
            {
                loadChannelData(drawMenuPosition);
            }
        }
    }

    /** 获取Column栏目 数据*/
    public void loadChannelData(int drawMenuPosition)
    {
        mDrawMenuPosition= drawMenuPosition;

        String contentType=null;

        /*
        switch (drawMenuPosition)
        {
            case MainActivity.docMenuPostion:
            {
                contentType=ShareDefine.KContentTypeText;
                break;
            }
            case MainActivity.audioMenuPostion:
            {
                contentType=ShareDefine.KContentTypeAudio;
                break;
            }
            case MainActivity.vedioMenuPostion:
            {
                contentType=ShareDefine.KContentTypeVideo;
                break;
            }
        }
        */

        FlyingHttpTool.getAlbumList(FlyingDataManager.getCurrentPassport(),
                FlyingDataManager.getBirdcopyAppID(),
                contentType,
                1,
                true,
                false,
                new FlyingHttpTool.GetAlbumListListener() {
                    @Override
                    public void completion(final ArrayList<AlbumData> albumList, String allRecordCount) {

                        if(albumList!=null && albumList.size()!=0)
                        {
                            ArrayList<ChannelItem> channelList = new ArrayList<ChannelItem>();

                            for (int i=0;i<albumList.size();i++)
                            {
                                ChannelItem navigate = new ChannelItem();
                                navigate.setId(i);
                                navigate.setName(albumList.get(i).getTagString());
                                navigate.setOrderId(i);
                                navigate.setSelected(0);
                                channelList.add(navigate);
                            }

                            mUserChannelList=channelList;
                        }
                        else
                        {
                            mUserChannelList=null;
                        }

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                initAndShowView();
                            }
                        });

                    }
        });
    }

    public void parseALbumDataOK(ArrayList<AlbumData> list)
    {

    }

    public void setMaxAlbums(int itemCount)
    {}

    /**
     *  当栏目项发生变化时候调用
     * */
    public void initAndShowView()
    {
        initTabColumn();
        initFragment();
    }

    /**
     *  初始化Column栏目项
     * */
    private void initTabColumn()
    {
        mRadioGroup_content.removeAllViews();

        if(mUserChannelList!=null)
        {
            int count =  mUserChannelList.size();
            mColumnHorizontalScrollView.setParam(getActivity(), mScreenWidth, mRadioGroup_content, mShadeleft, mShaderight, ll_more_columns, rl_column);
            for(int i = 0; i< count; i++)
            {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.WRAP_CONTENT);
                params.leftMargin = 5;
                params.rightMargin = 5;
//			TextView localTextView = (TextView) mInflater.inflate(R.layout.column_radio_item, null);
                TextView columnTextView = new TextView(getActivity());
                columnTextView.setTextAppearance(getActivity(), R.style.top_category_scroll_view_item_text);
//			localTextView.setBackground(getResources().getDrawable(R.drawable.top_category_scroll_text_view_bg));
                columnTextView.setBackgroundResource(R.drawable.radio_buttong_bg);
                columnTextView.setGravity(Gravity.CENTER);
                columnTextView.setPadding(5, 5, 5, 5);
                columnTextView.setId(i);
                columnTextView.setText(mUserChannelList.get(i).getName());
                columnTextView.setTextColor(getResources().getColorStateList(R.color.top_category_scroll_text_color_day));
                if(columnSelectIndex == i){
                    columnTextView.setSelected(true);
                }
                columnTextView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        for(int i = 0;i < mRadioGroup_content.getChildCount();i++){
                            View localView = mRadioGroup_content.getChildAt(i);
                            if (localView != v)
                                localView.setSelected(false);
                            else{
                                localView.setSelected(true);
                                mViewPager.setCurrentItem(i);
                            }
                        }
                        Toast.makeText(getActivity().getApplicationContext(), mUserChannelList.get(v.getId()).getName(), Toast.LENGTH_SHORT).show();
                    }
                });
                mRadioGroup_content.addView(columnTextView, i ,params);
            }
        }
    }
    /**
     *  选择的Column里面的Tab
     * */
    private void selectTab(int tab_postion)
    {
        columnSelectIndex = tab_postion;
        for (int i = 0; i < mRadioGroup_content.getChildCount(); i++) {
            View checkView = mRadioGroup_content.getChildAt(tab_postion);
            int k = checkView.getMeasuredWidth();
            int l = checkView.getLeft();
            int i2 = l + k / 2 - mScreenWidth / 2;
            // rg_nav_content.getParent()).smoothScrollTo(i2, 0);
            mColumnHorizontalScrollView.smoothScrollTo(i2, 0);
            // mColumnHorizontalScrollView.smoothScrollTo((position - 2) *
            // mItemWidth , 0);
        }

        //判断是否选中
        for (int j = 0; j <  mRadioGroup_content.getChildCount(); j++)
        {
            View checkView = mRadioGroup_content.getChildAt(j);
            boolean ischeck;
            if (j == tab_postion) {
                ischeck = true;
            }
            else {
                ischeck = false;
            }
            checkView.setSelected(ischeck);
        }
    }
    /**
     *  初始化Fragment
     * */
    private void initFragment()
    {
        fragments.clear();//清空

        if(mUserChannelList!=null)
        {
            int count =  mUserChannelList.size();
            for(int i = 0; i< count;i++)
            {
                LessonListFragment lessonListFragment =new LessonListFragment();
                /*
                if(mDrawMenuPosition==MainActivity.docMenuPostion)
                {
                    lessonListFragment.setContentType(ShareDefine.KContentTypeText);
                }
                else if(mDrawMenuPosition==MainActivity.audioMenuPostion)
                {
                    lessonListFragment.setContentType(ShareDefine.KContentTypeAudio);
                }
                else if(mDrawMenuPosition==MainActivity.vedioMenuPostion)
                {
                    lessonListFragment.setContentType(ShareDefine.KContentTypeVideo);
                }
                */

                Bundle data = new Bundle();
                String tagName = mUserChannelList.get(i).getName();
                data.putString("text",tagName);
                data.putInt("id", mUserChannelList.get(i).getId());
                lessonListFragment.setArguments(data);
                lessonListFragment.setTagString(tagName);
                //lessonListFragment.tabContentFragment=this;

                fragments.add(lessonListFragment);
            }
            HomeFragmentPagerAdapter mAdapetr = new HomeFragmentPagerAdapter(getChildFragmentManager(), fragments);
            //		mViewPager.setOffscreenPageLimit(0);
            mViewPager.setAdapter(mAdapetr);
            mViewPager.setOnPageChangeListener(pageListener);
            mViewPager.setCurrentItem(columnSelectIndex);
        }
    }
    /**
     *  ViewPager切换监听方法
     * */
    public ViewPager.OnPageChangeListener pageListener= new ViewPager.OnPageChangeListener(){

        @Override
        public void onPageScrollStateChanged(int arg0)
        {
           // columnSelectIndex=arg0;
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2)
        {
            //columnSelectIndex=arg0;
        }

        @Override
        public void onPageSelected(int position)
        {
            // TODO Auto-generated method stub
            mViewPager.setCurrentItem(position);
            selectTab(position);

            if(position==0)
            {
                MainActivity mainActivity=(MainActivity)getActivity();
                mainActivity.resetMenuGesture();
            }
            else
            {
                MainActivity mainActivity=(MainActivity)getActivity();
                mainActivity.cancelMenuGesture();
            }
        }
    };
}


text:
package com.cauchymop.goblob.presenter;

public interface GameMessageGenerator {
  String getGameResignedMessage(String winnerName);

  String getEndOfGameMessage(String winnerName, float wonBy);

  String getStoneMarkingMessage();

  String getOpponentPassedMessage(String opponentName);

  String getConfigurationMessageInitial();

  String getConfigurationMessageAcceptOrChange();

  String getConfigurationMessageWaitingForOpponent();
}


text:
<template>

  <div>
    <k-checkbox
      label="Unchecked"
    >
    </k-checkbox>
    <k-checkbox
      label="Indeterminate"
      :indeterminate="true"
    >
    </k-checkbox>
    <k-checkbox
      label="Checked"
      :checked="true"
    >
    </k-checkbox>
    <k-checkbox
      label="Disabled Unchecked"
      :disabled="true"
    >
    </k-checkbox>
    <k-checkbox
      label="Disabled Indeterminate"
      :indeterminate="true"
      :disabled="true"
    >
    </k-checkbox>
    <k-checkbox
      label="Disabled Checked"
      :checked="true"
      :disabled="true"
    >
    </k-checkbox>
  </div>

</template>

<script></script>


text:
package fi.vrk.xroad.catalog.lister;

import fi.vrk.xroad.catalog.lister.util.JaxbUtil;
import fi.vrk.xroad.catalog.persistence.entity.Service;
import fi.vrk.xroad.catalog.persistence.entity.Subsystem;
import fi.vrk.xroad.xroad_catalog_lister.*;
import org.springframework.stereotype.Component;
import javax.xml.datatype.XMLGregorianCalendar;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class JaxbConverter {

    /**
     * Convert entities to XML objects
     * @param members Iterable of Member entities
     * @param onlyActiveChildren if true, convert only active subsystems
     * @return Collection of Members (JAXB generated)
     */
    public Collection<Member> convertMembers(Iterable<fi.vrk.xroad.catalog.persistence.entity.Member> members,
                                             boolean onlyActiveChildren)  {
        List<Member> converted = new ArrayList<>();
        for (fi.vrk.xroad.catalog.persistence.entity.Member member: members) {
            Member cm = new Member();
            cm.setChanged(JaxbUtil.toXmlGregorianCalendar(member.getStatusInfo().getChanged()));
            cm.setCreated(JaxbUtil.toXmlGregorianCalendar(member.getStatusInfo().getCreated()));
            cm.setFetched(JaxbUtil.toXmlGregorianCalendar(member.getStatusInfo().getFetched()));
            cm.setRemoved(JaxbUtil.toXmlGregorianCalendar(member.getStatusInfo().getRemoved()));
            cm.setMemberCode(member.getMemberCode());
            cm.setMemberClass(member.getMemberClass());
            cm.setName(member.getName());
            cm.setXRoadInstance(member.getXRoadInstance());
            cm.setSubsystems(new SubsystemList());
            Iterable<Subsystem> subsystems;
            if (onlyActiveChildren) {
                subsystems = member.getActiveSubsystems();
            } else {
                subsystems = member.getAllSubsystems();
            }
            cm.getSubsystems().getSubsystem().addAll(convertSubsystems(subsystems, onlyActiveChildren));
            converted.add(cm);
        }
        return converted;
    }

    /**
     * Convert entities to XML objects
     * @param subsystems Iterable of Subsystem entities
     * @param onlyActiveChildren if true, convert only active subsystems
     * @return collection of XML objects
     */
    public Collection<fi.vrk.xroad.xroad_catalog_lister.Subsystem> convertSubsystems(Iterable<Subsystem> subsystems,
                                                                                boolean onlyActiveChildren) {
        List<fi.vrk.xroad.xroad_catalog_lister.Subsystem> converted = new ArrayList<>();
        for (Subsystem subsystem: subsystems) {
            fi.vrk.xroad.xroad_catalog_lister.Subsystem cs = new fi.vrk.xroad.xroad_catalog_lister.Subsystem();
            cs.setChanged(JaxbUtil.toXmlGregorianCalendar(subsystem.getStatusInfo().getChanged()));
            cs.setCreated(JaxbUtil.toXmlGregorianCalendar(subsystem.getStatusInfo().getCreated()));
            cs.setFetched(JaxbUtil.toXmlGregorianCalendar(subsystem.getStatusInfo().getFetched()));
            cs.setRemoved(JaxbUtil.toXmlGregorianCalendar(subsystem.getStatusInfo().getRemoved()));
            cs.setSubsystemCode(subsystem.getSubsystemCode());
            cs.setServices(new ServiceList());
            Iterable<Service> services;
            if (onlyActiveChildren) {
                services = subsystem.getActiveServices();
            } else {
                services = subsystem.getAllServices();
            }
            cs.getServices().getService().addAll(convertServices(services, onlyActiveChildren));
            converted.add(cs);
        }
        return converted;
    }

    /**
     * Convert entities to XML objects
     * @param services Iterable of Service entities
     * @param onlyActiveChildren if true, convert only active subsystems
     * @return collection of XML objects
     */
    public Collection<fi.vrk.xroad.xroad_catalog_lister.Service> convertServices(Iterable<Service> services,
                                                                                boolean onlyActiveChildren) {
        List<fi.vrk.xroad.xroad_catalog_lister.Service> converted = new ArrayList<>();
        for (Service service: services) {
            converted.add(JaxbUtil.convertService(service, onlyActiveChildren));
        }
        return converted;
    }

    public LocalDateTime toLocalDateTime(XMLGregorianCalendar calendar) {
        return calendar.toGregorianCalendar().toZonedDateTime().toLocalDateTime();
    }

    /**
     * Convert entities to XML objects
     * @param organizations Iterable of Organization entities
     * @return Collection of Organizations (JAXB generated)
     */
    public Collection<Organization> convertOrganizations(
            Iterable<fi.vrk.xroad.catalog.persistence.entity.Organization> organizations)  {
        List<Organization> converted = new ArrayList<>();
        for (fi.vrk.xroad.catalog.persistence.entity.Organization organization: organizations) {
            Organization co = new Organization();
            co.setChanged(JaxbUtil.toXmlGregorianCalendar(organization.getStatusInfo().getChanged()));
            co.setCreated(JaxbUtil.toXmlGregorianCalendar(organization.getStatusInfo().getCreated()));
            co.setFetched(JaxbUtil.toXmlGregorianCalendar(organization.getStatusInfo().getFetched()));
            co.setRemoved(JaxbUtil.toXmlGregorianCalendar(organization.getStatusInfo().getRemoved()));
            co.setBusinessCode(organization.getBusinessCode());
            co.setOrganizationType(organization.getOrganizationType());
            co.setGuid(organization.getGuid());
            co.setPublishingStatus(organization.getPublishingStatus());

            co.setOrganizationNames(new OrganizationNameList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.OrganizationName> organizationNames = organization.getAllOrganizationNames();
            if (organizationNames != null) {
                co.getOrganizationNames().getOrganizationName().addAll(JaxbUtil.convertOrganizationNames(organizationNames));
            }

            co.setOrganizationDescriptions(new OrganizationDescriptionList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.OrganizationDescription> organizationDescriptions
                    = organization.getAllOrganizationDescriptions();
            if (organizationDescriptions != null) {
                co.getOrganizationDescriptions().getOrganizationDescription().addAll(JaxbUtil.convertOrganizationDescriptions(organizationDescriptions));
            }

            co.setEmails(new EmailList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.Email> emails = organization.getAllEmails();
            if (emails != null) {
                co.getEmails().getEmail().addAll(JaxbUtil.convertEmails(emails));
            }

            co.setPhoneNumbers(new PhoneNumberList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.PhoneNumber> phoneNumbers = organization.getAllPhoneNumbers();
            if (phoneNumbers != null) {
                co.getPhoneNumbers().getPhoneNumber().addAll(JaxbUtil.convertPhoneNumbers(phoneNumbers));
            }

            co.setWebPages(new WebPageList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.WebPage> webPages = organization.getAllWebPages();
            if (webPages != null) {
                co.getWebPages().getWebPage().addAll(JaxbUtil.convertWebPages(webPages));
            }

            co.setAddresses(new AddressList());
            Iterable<fi.vrk.xroad.catalog.persistence.entity.Address> addresses = organization.getAllAddresses();
            if (addresses != null) {
                co.getAddresses().getAddress().addAll(JaxbUtil.convertAddresses(addresses));
            }

            converted.add(co);
        }
        return converted;
    }

    /**
     * Convert entities to XML objects
     * @param companies Iterable of Company entities
     * @return Collection of Companies (JAXB generated)
     */
    public Collection<Company> convertCompanies(
            Iterable<fi.vrk.xroad.catalog.persistence.entity.Company> companies)  {
        List<Company> converted = new ArrayList<>();
        for (fi.vrk.xroad.catalog.persistence.entity.Company company: companies) {
            converted.add(JaxbUtil.convertCompany(company));
        }
        return converted;
    }

    /**
     * Convert entities to XML objects
     * @param errorLogEntries Iterable of ErrorLog entities
     * @return Collection of ErrorLog entries (JAXB generated)
     */
    public Collection<ErrorLog> convertErrorLog(Iterable<fi.vrk.xroad.catalog.persistence.entity.ErrorLog> errorLogEntries)  {
        List<ErrorLog> converted = new ArrayList<>();
        for (fi.vrk.xroad.catalog.persistence.entity.ErrorLog errorLog: errorLogEntries) {
            ErrorLog er = new ErrorLog();
            er.setCreated(JaxbUtil.toXmlGregorianCalendar(errorLog.getCreated()));
            er.setMessage(errorLog.getMessage());
            er.setCode(errorLog.getCode());
            er.setXRoadInstance(errorLog.getXRoadInstance());
            er.setMemberClass(errorLog.getMemberClass());
            er.setMemberCode(errorLog.getMemberCode());
            er.setSubsystemCode(errorLog.getSubsystemCode());
            er.setGroupCode(errorLog.getGroupCode());
            er.setServiceCode(errorLog.getServiceCode());
            er.setServiceVersion(errorLog.getServiceVersion());
            er.setSecurityCategoryCode(errorLog.getSecurityCategoryCode());
            er.setServerCode(errorLog.getServerCode());
            converted.add(er);
        }
        return converted;
    }
}


text:
package org.zstack.sdk;

import org.zstack.sdk.AccountResourceRefInventory;

public class ChangeResourceOwnerResult {
    public AccountResourceRefInventory inventory;
    public void setInventory(AccountResourceRefInventory inventory) {
        this.inventory = inventory;
    }
    public AccountResourceRefInventory getInventory() {
        return this.inventory;
    }

}


text:
package com.hendraanggrian.appcompat.socialview.widget;

import android.os.Build;

import androidx.appcompat.app.AppCompatActivity;

import com.hendraanggrian.appcompat.socialview.SocialViewTestHelper;
import com.hendraanggrian.appcompat.socialview.TestActivity;
import com.hendraanggrian.appcompat.widget.SocialEditText;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.internal.DoNotInstrument;

@RunWith(RobolectricTestRunner.class)
@Config(sdk = Build.VERSION_CODES.LOLLIPOP)
@DoNotInstrument
public class SocialEditTextTest {

    private AppCompatActivity activity;
    private SocialViewTestHelper<SocialEditText> helper;

    @Before
    public void setup() {
        activity = Robolectric.buildActivity(TestActivity.class).setup().get();
        helper = new SocialViewTestHelper<>(new SocialEditText(activity));
    }

    @Test
    public void hashtagPattern() {
        helper.hashtagPattern();
    }

    @Test
    public void mentionPattern() {
        helper.mentionPattern();
    }

    @Test
    public void hyperlinkPattern() {
        helper.hyperlinkPattern();
    }

    @Test
    public void hashtagEnabled() {
        helper.hashtagEnabled();
    }

    @Test
    public void mentionEnabled() {
        helper.mentionEnabled();
    }

    @Test
    public void hyperlinkEnabled() {
        helper.hyperlinkEnabled();
    }

    @Test
    public void hashtagColor() {
        helper.hashtagColor();
    }

    @Test
    public void mentionColor() {
        helper.mentionColor();
    }

    @Test
    public void hyperlinkColor() {
        helper.hyperlinkColor();
    }

    @Test
    public void getHashtags() {
        helper.getHashtags();
    }

    @Test
    public void getMentions() {
        helper.getMentions();
    }
}