text:
#include "mega.h"

#ifdef USE_SQLITE
namespace mega {
SqliteDbAccess::SqliteDbAccess(string* path)
{
    if (path)
    {
        dbpath = *path;
    }
}

SqliteDbAccess::~SqliteDbAccess()
{
}

DbTable* SqliteDbAccess::open(FileSystemAccess* fsaccess, string* name)
{
    //Each table will use its own database object and its own file
    sqlite3* db;
    string dbfile;
    ostringstream legacyoss;
    legacyoss << dbpath;
    legacyoss << "megaclient_statecache";
    legacyoss << LEGACY_DB_VERSION;
    legacyoss << "_" << *name << ".db";
    string legacydbpath = legacyoss.str();

    string locallegacydbpath;
    FileAccess *fa = fsaccess->newfileaccess();
    fsaccess->path2local(&legacydbpath, &locallegacydbpath);
    bool legacydbavailable = fa->fopen(&locallegacydbpath);
    delete fa;

    if (legacydbavailable)
    {
        if (currentDbVersion == LEGACY_DB_VERSION)
        {
            LOG_debug << "Using a legacy DB";
            dbfile = legacydbpath;
        }
        else
        {
            LOG_debug << "Legacy DB is outdated. Deleting.";
            fsaccess->unlinklocal(&locallegacydbpath);
        }
    }

    if (!dbfile.size())
    {
        ostringstream newoss;
        newoss << dbpath;
        newoss << "megaclient_statecache";
        newoss << DB_VERSION;
        newoss << "_" << *name << ".db";

        LOG_debug << "Using an upgraded DB";
        dbfile = newoss.str();
        currentDbVersion = DB_VERSION;
    }

    int rc;

    rc = sqlite3_open(dbfile.c_str(), &db);

    if (rc)
    {
        return NULL;
    }

#if !(TARGET_OS_IPHONE)
    sqlite3_exec(db, "PRAGMA journal_mode=WAL;", NULL, NULL, NULL);
#endif

    const char *sql = "CREATE TABLE IF NOT EXISTS statecache (id INTEGER PRIMARY KEY ASC NOT NULL, content BLOB NOT NULL)";

    rc = sqlite3_exec(db, sql, NULL, NULL, NULL);

    if (rc)
    {
        return NULL;
    }

    return new SqliteDbTable(db, fsaccess, &dbfile);
}

SqliteDbTable::SqliteDbTable(sqlite3* cdb, FileSystemAccess *fs, string *filepath)
{
    db = cdb;
    pStmt = NULL;
    fsaccess = fs;
    dbfile = *filepath;
}

SqliteDbTable::~SqliteDbTable()
{
    if (!db)
    {
        return;
    }

    if (pStmt)
    {
        sqlite3_finalize(pStmt);
    }
    abort();
    sqlite3_close(db);
    LOG_debug << "Database closed " << dbfile;
}

// set cursor to first record
void SqliteDbTable::rewind()
{
    if (!db)
    {
        return;
    }

    if (pStmt)
    {
        sqlite3_reset(pStmt);
    }
    else
    {
        sqlite3_prepare(db, "SELECT id, content FROM statecache", -1, &pStmt, NULL);
    }
}

// retrieve next record through cursor
bool SqliteDbTable::next(uint32_t* index, string* data)
{
    if (!db)
    {
        return false;
    }

    if (!pStmt)
    {
        return false;
    }

    int rc = sqlite3_step(pStmt);

    if (rc != SQLITE_ROW)
    {
        sqlite3_finalize(pStmt);
        pStmt = NULL;
        return false;
    }

    *index = sqlite3_column_int(pStmt, 0);

    data->assign((char*)sqlite3_column_blob(pStmt, 1), sqlite3_column_bytes(pStmt, 1));

    return true;
}

// retrieve record by index
bool SqliteDbTable::get(uint32_t index, string* data)
{
    if (!db)
    {
        return false;
    }

    sqlite3_stmt *stmt;
    bool result = false;

    if (sqlite3_prepare(db, "SELECT content FROM statecache WHERE id = ?", -1, &stmt, NULL) == SQLITE_OK)
    {
        if (sqlite3_bind_int(stmt, 1, index) == SQLITE_OK)
        {
            if (sqlite3_step(stmt) == SQLITE_ROW)
            {
                data->assign((char*)sqlite3_column_blob(stmt, 0), sqlite3_column_bytes(stmt, 0));

                result = true;
            }
        }
    }

    sqlite3_finalize(stmt);
    return result;
}

// add/update record by index
bool SqliteDbTable::put(uint32_t index, char* data, unsigned len)
{
    if (!db)
    {
        return false;
    }

    sqlite3_stmt *stmt;
    bool result = false;

    if (sqlite3_prepare(db, "INSERT OR REPLACE INTO statecache (id, content) VALUES (?, ?)", -1, &stmt, NULL) == SQLITE_OK)
    {
        if (sqlite3_bind_int(stmt, 1, index) == SQLITE_OK)
        {
            if (sqlite3_bind_blob(stmt, 2, data, len, SQLITE_STATIC) == SQLITE_OK)
            {
                if (sqlite3_step(stmt) == SQLITE_DONE)
                {
                    result = true;
                }
            }
        }
    }

    sqlite3_finalize(stmt);
    return result;
}

// delete record by index
bool SqliteDbTable::del(uint32_t index)
{
    if (!db)
    {
        return false;
    }

    char buf[64];

    sprintf(buf, "DELETE FROM statecache WHERE id = %" PRIu32, index);

    return !sqlite3_exec(db, buf, 0, 0, NULL);
}

// truncate table
void SqliteDbTable::truncate()
{
    if (!db)
    {
        return;
    }

    sqlite3_exec(db, "DELETE FROM statecache", 0, 0, NULL);
}

// begin transaction
void SqliteDbTable::begin()
{
    if (!db)
    {
        return;
    }

    LOG_debug << "DB transaction BEGIN " << dbfile;
    sqlite3_exec(db, "BEGIN", 0, 0, NULL);
}

// commit transaction
void SqliteDbTable::commit()
{
    if (!db)
    {
        return;
    }

    LOG_debug << "DB transaction COMMIT " << dbfile;
    sqlite3_exec(db, "COMMIT", 0, 0, NULL);
}

// abort transaction
void SqliteDbTable::abort()
{
    if (!db)
    {
        return;
    }

    LOG_debug << "DB transaction ROLLBACK " << dbfile;
    sqlite3_exec(db, "ROLLBACK", 0, 0, NULL);
}

void SqliteDbTable::remove()
{
    if (!db)
    {
        return;
    }

    if (pStmt)
    {
        sqlite3_finalize(pStmt);
    }
    abort();
    sqlite3_close(db);

    db = NULL;

    string localpath;
    fsaccess->path2local(&dbfile, &localpath);
    fsaccess->unlinklocal(&localpath);
}
} // namespace

#endif


text:
"""
EngineLog - file ``var/log/ovirt-engine/engine.log``
====================================================

This is a standard log parser based on the LogFileOutput class.

Sample input::

    2016-05-18 13:21:21,115 INFO [org.ovirt.engine.core.bll.scheduling.policyunits.EvenGuestDistributionBalancePolicyUnit] (DefaultQuartzScheduler_Worker-95) [5bc194fa] There is no host with more than 8 running guests, no balancing is needed
    2016-05-18 14:00:51,272 INFO [org.ovirt.engine.core.vdsbroker.VdsUpdateRunTimeInfo] (DefaultQuartzScheduler_Worker-95) [5bc194fa] VM ADLG8201 ab289661-bbaa-4d27-a67a-ad20626f60f0 moved from PoweringUp --> Paused
    2016-05-18 14:00:51,318 ERROR [org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector] (DefaultQuartzScheduler_Worker-95) [5bc194fa] Correlation ID: null, Call Stack: null, Custom Event ID: -1, Message: VM ADLG8201 has paused due to storage I/O problem.

Examples:

    >>> logs = shared[EngineLog]
    >>> 'has paused due to storage I/O problem' in logs
    True
    >>> logs.get('INFO')
    ['2016-05-18 13:21:21,115 INFO [org.ovirt.engine.core.bll.scheduling.policyunits.EvenGuestDistributionBalancePolicyUnit] (DefaultQuartzScheduler_Worker-95) [5bc194fa] There is no host with more than 8 running guests, no balancing is needed',
     '2016-05-18 14:00:51,272 INFO [org.ovirt.engine.core.vdsbroker.VdsUpdateRunTimeInfo] (DefaultQuartzScheduler_Worker-95) [5bc194fa] VM ADLG8201 ab289661-bbaa-4d27-a67a-ad20626f60f0 moved from PoweringUp --> Paused']
    >>> from datetime import datetime
    >>> list(logs.get_after(datetime(2016, 5, 18, 14, 0, 0)))
    ['2016-05-18 14:00:51,272 INFO [org.ovirt.engine.core.vdsbroker.VdsUpdateRunTimeInfo] (DefaultQuartzScheduler_Worker-95) [5bc194fa] VM ADLG8201 ab289661-bbaa-4d27-a67a-ad20626f60f0 moved from PoweringUp --> Paused',
     '2016-05-18 14:00:51,318 ERROR [org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector] (DefaultQuartzScheduler_Worker-95) [5bc194fa] Correlation ID: null, Call Stack: null, Custom Event ID: -1, Message: VM ADLG8201 has paused due to storage I/O problem.']

"""

from .. import LogFileOutput, parser
from insights.specs import engine_log

@parser(engine_log)
class EngineLog(LogFileOutput):
    """
    Provide access to ovirt engine logs using the LogFileOutput parser class.
    """
    pass

redpajama_set_name: RedPajamaGithub


text:
@implementation Annotation

@dynamic minZoomLevel;
@dynamic maxZoomLevel;
@dynamic code;
@dynamic longitude;
@dynamic latitude;
@dynamic title;
@dynamic subtitle;

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia rugosa var. lundensis Fr.

### Remarks
null


text:
package hex.kmeans;

import hex.ModelMojoWriter;

import java.io.IOException;

public class KMeansMojoWriter extends ModelMojoWriter<KMeansModel, KMeansModel.KMeansParameters, KMeansModel.KMeansOutput> {

  @SuppressWarnings("unused")  // Called through reflection in ModelBuildersHandler
  public KMeansMojoWriter() {}

  public KMeansMojoWriter(KMeansModel model) {
    super(model);
  }

  @Override
  public String mojoVersion() {
    return "1.00";
  }

  @Override
  protected void writeModelData() throws IOException {
    writekv("standardize", model._parms._standardize);
    double[][] centers;
    if (model._parms._standardize) {
      writekv("standardize_means", model._output._normSub);
      writekv("standardize_mults", model._output._normMul);
      writekv("standardize_modes", model._output._mode);
      centers = model._output._centers_std_raw;
    } else
      centers = model._output._centers_raw;
    writekv("center_num", centers.length);
    for (int i = 0; i < centers.length; i++)
      writekv("center_" + i, centers[i]);
  }

}


text:
package org.zstack.header.storage.primary;

import org.zstack.header.message.APIListMessage;

import java.util.List;

public class APIListPrimaryStorageMsg extends APIListMessage {

    public APIListPrimaryStorageMsg() {
    }

    public APIListPrimaryStorageMsg(List<String> uuids) {
        super(uuids);
    }

    public static APIListPrimaryStorageMsg __example__() {
        APIListPrimaryStorageMsg msg = new APIListPrimaryStorageMsg();
        return msg;
    }

}


text:
  Bazens est
       un village
       géographiquement positionné dans le département de Lot-et-Garonne en Aquitaine. Elle totalisait 513 habitants en 2008.

La ville offre quelques  aménagements, elle propose entre autres un terrain de tennis et un terrain de sport.

À Bazens, la valorisation moyenne à la vente d'un appartement s'évalue à zero € du m² en vente. La valeur moyenne d'une maison à l'achat se situe à 1 791 € du m². À la location le prix moyen se situe à 0 € du m² par mois.

Si vous envisagez de demenager à Bazens, vous pourrez aisément trouver une maison à vendre.

Le nombre de logements, à Bazens, se décomposait en 2011 en neuf appartements et 243 maisons soit
 un marché relativement équilibré.

À proximité de Bazens sont positionnées géographiquement les communes de
Aiguillon à 7 km, 4 325 habitants,
Lacépède localisée à 7 km, 278 habitants,
Feugarolles située à 7 km, 956 habitants,
Galapian située à 4 km, 302 habitants,
Bruch à 6 km, 749 habitants,
Port-Sainte-Marie à 2 km, 1 913 habitants,
 entre autres. De plus, Bazens est située à seulement 27 km de Saint-Paul.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Functions.cs" company="OxyPlot">
//   The MIT License (MIT)
//
//   Copyright (c) 2014 OxyPlot contributors
//
//   Permission is hereby granted, free of charge, to any person obtaining a
//   copy of this software and associated documentation files (the
//   "Software"), to deal in the Software without restriction, including
//   without limitation the rights to use, copy, modify, merge, publish,
//   distribute, sublicense, and/or sell copies of the Software, and to
//   permit persons to whom the Software is furnished to do so, subject to
//   the following conditions:
//
//   The above copyright notice and this permission notice shall be included
//   in all copies or substantial portions of the Software.
//
//   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
//   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
//   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
//   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
//   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
//   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
//   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// <summary>
//   Provides functions for the icon generator.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace IconGenerator
{
    using System;

    /// <summary>
    /// Provides functions for the icon generator.
    /// </summary>
    public static class Functions
    {
        /// <summary>
        /// Initializes static members of the <see cref="Functions" /> class.
        /// </summary>
        static Functions()
        {
            Peaks = (x, y) => 3 * (1 - x) * (1 - x) * Math.Exp(-(x * x) - (y + 1) * (y + 1)) - 10 * (x / 5 - x * x * x - y * y * y * y * y) * Math.Exp(-x * x - y * y) - 1.0 / 3 * Math.Exp(-(x + 1) * (x + 1) - y * y);
        }

        /// <summary>
        /// Gets the peaks function.
        /// </summary>
        public static Func<double, double, double> Peaks { get; private set; }
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Risk Assessed Password Policies - Overview</title>

	<meta name="author" content="raesene">

	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<link href="https://raesene.github.io/assets/resources/bootstrap/css/bootstrap.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/font-awesome/css/font-awesome.min.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/resources/syntax/syntax.css" rel="stylesheet">
	<link href="https://raesene.github.io/assets/css/style.css" rel="stylesheet">

	<link rel="alternate" type="application/rss+xml" title="" href="https://raesene.github.io/feed.xml">

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

			</button>

				Raesene's Ramblings

Home

Categories

Tags

		<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">

		</button>

Home

Categories

Tags

Top of Page

        Raesene's Ramblings

	Security Geek, Kubernetes, Docker, Ruby, Hillwalking

Risk Assessed Password Policies - Overview

	   September
	   25th,

	   2007

I jumped in earlier talking about password rotation policies without actually mentioning why I think password policies are so important, so I'll back up and cover that now.

The use of passwords as authenticators for computer systems has been around for a very long time, and for quite some period the security industry has had a focus on reducing their use, as their shortcomings have been well known.  Single sign-on, identity management, two factor authentication etc etc have been themes for quite a while.

But here's the thing, passwords aren't going away, in fact I'd say that their usage is increasing.

At home we've got a hugely increasing number of websites offering us services, from social networking sites like Facebook and myspace to forum sites to e-commerce sites, and all of them use passwords (usually not integrated with any over-arching identity management system)

At work, there's the rise of application service providers and "software as a service" which leads to company staff accessing external websites for business purposes, again usually without identity management support...

So it means that getting your password policy right is actually getting more important.

The problem I've seen is that many companies don't actually risk assess their password policies.  They set one level for users and one for "super users" regardless of the system location and other controls.  Combined with that you get "best practice" principles that seem really inappropriate for most systems and it can be quite a mess....

Over a series of posts I'll look at some examples of where password policies could do with some attention, any feedback/comments welcome :)

Share Post

          Twitter

          Facebook

          Google+

raesene

Security Geek, Kubernetes, Docker, Ruby, Hillwalking

← Previous

Next →

				© 2022 raesene with Jekyll. Theme: dbyll by dbtek.


text:
import * as React from 'react'
import { createElement, StatelessComponent } from 'react'
import { render } from 'react-dom'

import { Alice } from '../components/index'

import * as index from './index'

declare module './index' {
  interface BootArgs {
    React: typeof React
    render: typeof render
  }

  type boot = (args: BootArgs) => Promise<void>

  type getGetAlice = (react: typeof React) => Promise<Alice>

  interface RendererArgs {
    React: typeof React
    Alice: StatelessComponent<any>
    render: typeof render
    FB?: any
  }
  type Renderer = (args: RendererArgs) => void
}


text:
#ifndef	uint8
#define	uint8  unsigned	char
#endif

#ifndef	uint32
#define	uint32 unsigned	long int
#endif

#ifndef	__MD5_H__
#define	__MD5_H__

#define MD5_MAC_LEN 16

typedef struct _MD5_CTX {
    UINT32   Buf[4];             // buffers of four states
	UCHAR   Input[64];          // input message
	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits
}   MD5_CTX;

VOID MD5Init(MD5_CTX *pCtx);
VOID MD5Update(MD5_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
VOID MD5Final(UCHAR Digest[16], MD5_CTX *pCtx);
VOID MD5Transform(UINT32 Buf[4], UINT32 Mes[16]);

void md5_mac(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);
void hmac_md5(u8 *key, size_t key_len, u8 *data, size_t data_len, u8 *mac);

//
// SHA context
//
typedef	struct _SHA_CTX
{
	UINT32   Buf[5];             // buffers of five states
	UCHAR   Input[80];          // input message
	UINT32   LenInBitCount[2];   // length counter for input message, 0 up to 64 bits

}	SHA_CTX;

VOID SHAInit(SHA_CTX *pCtx);
UCHAR SHAUpdate(SHA_CTX *pCtx, UCHAR *pData, UINT32 LenInBytes);
VOID SHAFinal(SHA_CTX *pCtx, UCHAR Digest[20]);
VOID SHATransform(UINT32 Buf[5], UINT32 Mes[20]);

#define SHA_DIGEST_LEN 20
#endif // __MD5_H__

/******************************************************************************/
#ifndef	_AES_H
#define	_AES_H

typedef	struct
{
	uint32 erk[64];		/* encryption round	keys */
	uint32 drk[64];		/* decryption round	keys */
	int	nr;				/* number of rounds	*/
}
aes_context;

int	 rtmp_aes_set_key( aes_context *ctx,	uint8 *key,	int	nbits );
void rtmp_aes_encrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );
void rtmp_aes_decrypt( aes_context *ctx,	uint8 input[16], uint8 output[16] );

void F(char *password, unsigned char *ssid, int ssidlength, int iterations, int count, unsigned char *output);
int PasswordHash(char *password, unsigned char *ssid, int ssidlength, unsigned char *output);

#endif /* aes.h	*/


text:
namespace Vidyano.WebComponents {
    "use strict";

    @WebComponent.register({
        properties: {
            items: Array,
            as: String,
            parentScroller: {
                type: Boolean,
                reflectToAttribute: true,
                value: false
            }
        },
        observers: [
            "_hookIronListToScroller(parentScroller, isAttached)"
        ]
    })
    export class List extends WebComponent {
        parentScroller: boolean;

        private _hookIronListToScroller(parentScroller: boolean, isAttached: boolean) {
            if (!isAttached)
                return;

            if (parentScroller) {
                const template = this.$.parentScrollerTemplate;
                template["render"]();
            }

            this.async(() => {
                if (parentScroller !== this.parentScroller || !this.isAttached)
                    return;

                const list = Polymer.dom(this.root).querySelector("#list");
                const scroller = <any>this.findParent(e => e instanceof Vidyano.WebComponents.Scroller, list);
                (<any>list).scrollTarget = scroller.$.wrapper;

                this._sizeChanged();
            });
        }

        private _bindIronListDataHost() {
            // Workaround for making sure events are delegated to the correct host
            const list = Polymer.dom(this.root).querySelector("#list");
            if (list["dataHost"] && list["dataHost"]["_rootDataHost"] === this) {
                const dataHostParent = this.findParent(e => e["dataHost"]);
                if (dataHostParent)
                    list["dataHost"] = dataHostParent["dataHost"];
            }
        }

        private _sizeChanged() {
            const list = <PolymerBase>Polymer.dom(this.root).querySelector("#list");
            if (!list || !list.fire)
                return;

            list.fire("iron-resize", null);
        }
    }
}


text:
require 'spec_helper'

describe( 'tomcat6::instance', :type => :define) do
  context "instance 'someapp'" do
    let(:title) { 'someapp' }
    #
    ## Test our no-parameter case, which should throw an error
    context "with no parameters" do
      it do
        expect {
          should contain_file('/etc/sysconfig/tomcat6-someapp')
        }.to raise_error(Puppet::Error,/account must be set/)
      end
    end

    #
    ## Test when we pass a valid account name
    context "with account='someapp_account'" do
      let(:params) { { 'account' => 'someapp_account' } }
      it do
        # ensure sysconfig file for this instance is setup
        should contain_file('/etc/sysconfig/tomcat6-someapp').with({
          'ensure' => 'file',
          'replace' => false,
          'owner' => 'root',
          'group' => 'root',
          'mode' => '0444',
          'content' => /\/home\/someapp_account\/tomcat6-someapp/
        })

        # ensure an init script is setup for this instance
        should contain_file('/etc/init.d/tomcat6-someapp').with({
          'ensure' => 'link',
          'owner' => 'root',
          'group' => 'root',
          'target' => '/etc/init.d/tomcat6',
          'require' => 'Class[Tomcat6::Package]',
        })

        # ensure our application dirs are setup
        app_dirs = [
          '/home/someapp_account/tomcat6-someapp',
          '/home/someapp_account/tomcat6-someapp/conf/Catalina',
          '/home/someapp_account/tomcat6-someapp/webapps',
          '/home/someapp_account/tomcat6-someapp/lib',
        ]
        app_dirs.each do |ad|
          should contain_file(ad).with({
            'ensure' => 'directory',
            'replace' => false,
            'owner' => 'someapp_account',
            'group' => 'someapp_account',
            'mode' => '2775',
          })
        end

        # ensure our log dir is setup
        should contain_file('/var/log/tomcat6-someapp').with({
          'ensure' => 'directory',
          'owner' => 'someapp_account',
          'group' => 'someapp_account',
          'mode' => '2775',
        })

        # setup a symlink to our log dir in the app home dir
        should contain_file('/home/someapp_account/tomcat6-someapp/logs').with({
          'ensure' => 'link',
          'owner' => 'someapp_account',
          'group' => 'someapp_account',
          'mode' => '2775',
          'target' => '/var/log/tomcat6-someapp',
        })

        # setup a symlink to our bin dir in the app home dir
        should contain_file('/home/someapp_account/tomcat6-someapp/bin').with({
          'ensure' => 'link',
          'owner' => 'someapp_account',
          'group' => 'someapp_account',
          'mode' => '2775',
          'target' => '/usr/share/tomcat6/bin',
        })

        # setup some additional links
        should contain_file('/home/someapp_account/tomcat6-someapp/temp').with({
          'ensure' => 'link',
          'target' => '/var/cache/tomcat6-someapp/temp',
        })
        should contain_file('/home/someapp_account/tomcat6-someapp/work').with({
          'ensure' => 'link',
          'target' => '/var/cache/tomcat6-someapp/work',
        })

        # ensure our cache directory is setup properly
        should contain_file('/var/cache/tomcat6-someapp').with({
          'ensure' => 'directory',
          'owner' => 'someapp_account',
          'group' => 'someapp_account',
          'mode' => '2775',
        })

        # check for the initial setup of the app home dir
        should contain_file('/home/someapp_account/tomcat6-someapp/conf').with({
         'replace' => false,
         'recurse' => true,
         'purge' => false,
         'source' => 'puppet:///modules/tomcat6/app-home/',
         'owner' => 'someapp_account',
         'group' => 'someapp_account',
         'mode' => '0644',
        })

        # check for our initial config
        config_file = '/home/someapp_account/tomcat6-someapp/conf/server.xml'
        should contain_file(config_file).with({
          'replace' => false,
          'owner' => 'someapp_account',
          'group' => 'someapp_account',
          'mode' => '0644',
        })

        # check to make sure expected config settings are there
        lines = [
          /<Server\ port="8005"\ shutdown="SHUTDOWN">\n/,
          /\s+<Connector\ port="8080"\ protocol="HTTP\/1.1"\n/,
          /\s+redirectPort="8443" \/>/,
          /\s+<!-- Define an AJP 1.3 Connector on port 8011 -->\n/,
          /\s+<Connector port="8011" protocol="AJP\/1.3" redirectPort="8443" \/>/,
        ]
        lines.each do |l|
          should contain_file(config_file).with_content(l)
        end

        # last, let's ensure our service is ther
        should contain_service('tomcat6-someapp').with({
          'enable' => true,
          'require' => 'File[/etc/init.d/tomcat6-someapp]',
        })
      end

      context "with port overrides" do
        let(:params) { {
          'account' => 'someapp_acct',
          'ajp_port' => '1111',
          'http_port' => '2222',
          'redirect_port' => '3333',
          'shutdown_port' => '4444' }}
        it do
          # check to make sure expected config settings are there
          lines = [
            /<Server\ port="4444"\ shutdown="SHUTDOWN">\n/,
            /\s+<Connector\ port="2222"\ protocol="HTTP\/1.1"\n/,
            /\s+redirectPort="3333" \/>/,
            /\s+<!-- Define an AJP 1.3 Connector on port 1111 -->\n/,
            /\s+<Connector port="1111" protocol="AJP\/1.3" redirectPort="3333" \/>/,
          ]
          config_file = '/home/someapp_acct/tomcat6-someapp/conf/server.xml'
          lines.each do |l|
            should contain_file(config_file).with_content(l)
          end # lines
        end # it do
      end # context - with port overrides
    end

    context "test override of home owner and group" do
      let :title do
        'someapp'
      end
      let :params do
        {
          'account' => 'someapp_acct',
          'home_owner' => 'content_acct',
          'home_group' => 'content_group',
        }
      end
      home_dirs = [
        '/home/someapp_acct/tomcat6-someapp',
        '/home/someapp_acct/tomcat6-someapp/conf/Catalina',
        '/home/someapp_acct/tomcat6-someapp/lib',
        '/home/someapp_acct/tomcat6-someapp/webapps',
        '/var/cache/tomcat6-someapp',
        '/var/cache/tomcat6-someapp/work',
        '/var/cache/tomcat6-someapp/temp',
      ]
      it do
        home_dirs.each do |d|
          should contain_file(d).with({
            'ensure' => 'directory',
            'owner' => 'content_acct',
            'group' => 'content_group',
          })
        end
      end
    end
  end
end


text:
package com.all.chat;

import com.all.chat.exceptions.ChatException;

public class ChatServiceStub implements ChatService {

	@Override
	public ChatUser login(ChatCredentials chatCredentials) throws ChatException {
		return null;
	}

	@Override
	public void logout(ChatUser loggedContact) {
	}

	@Override
	public Message sendMessage(String message, ChatUser to) throws ChatException {
		return null;
	}

	@Override
	public void addListener(ChatServiceListener chatServiceListener) {
	}

	@Override
	public void removeListener(ChatServiceListener chatServiceListener) {
	}

}


text:
module SecondBase
  module Forced

    def connection_pool
      SecondBase::Base.connection_pool
    end

    def retrieve_connection
      SecondBase::Base.retrieve_connection
    end

    def connected?
      SecondBase::Base.connected?
    end

    def remove_connection(klass = self)
      SecondBase::Base.remove_connection
    end

  end
end


text:
namespace Merchello.Web.Search
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Core;
    using Core.Models;
    using Core.Persistence.Querying;
    using Core.Services;
    using Examine;
    using global::Examine;
    using global::Examine.Providers;
    using Models.ContentEditing;
    using Models.Querying;
    using Umbraco.Core.Persistence;

    /// <summary>
    /// Responsible for invoice related queries - caches via lucene
    /// </summary>
    internal class CachedInvoiceQuery : CachedQueryBase<IInvoice, InvoiceDisplay>, ICachedInvoiceQuery
    {
        /// <summary>
        /// The invoice service.
        /// </summary>
        private readonly InvoiceService _invoiceService;

        /// <summary>
        /// The method to retrieve orders for an invoice
        /// </summary>
        private readonly Func<Guid, IEnumerable<OrderDisplay>> _getOrders;

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedInvoiceQuery"/> class.
        /// </summary>
        public CachedInvoiceQuery()
            : this(MerchelloContext.Current.Services.InvoiceService)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedInvoiceQuery"/> class.
        /// </summary>
        /// <param name="invoiceService">
        /// The invoice service.
        /// </param>
        internal CachedInvoiceQuery(IInvoiceService invoiceService)
            : this(invoiceService, new CachedOrderQuery(MerchelloContext.Current.Services.OrderService).GetByInvoiceKey)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedInvoiceQuery"/> class.
        /// </summary>
        /// <param name="invoiceService">
        /// The invoice service.
        /// </param>
        /// <param name="getOrders">
        /// The get Orders.
        /// </param>
        internal CachedInvoiceQuery(IInvoiceService invoiceService, Func<Guid, IEnumerable<OrderDisplay>> getOrders)
            : this(
            invoiceService,
            getOrders,
            ExamineManager.Instance.IndexProviderCollection["MerchelloInvoiceIndexer"],
            ExamineManager.Instance.SearchProviderCollection["MerchelloInvoiceSearcher"])
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CachedInvoiceQuery"/> class.
        /// </summary>
        /// <param name="service">
        /// The service.
        /// </param>
        /// <param name="getOrders">
        /// The get Orders.
        /// </param>
        /// <param name="indexProvider">
        /// The index provider.
        /// </param>
        /// <param name="searchProvider">
        /// The search provider.
        /// </param>
        internal CachedInvoiceQuery(
            IPageCachedService<IInvoice> service,
            Func<Guid, IEnumerable<OrderDisplay>> getOrders,
            BaseIndexProvider indexProvider,
            BaseSearchProvider searchProvider)
            : base(service, indexProvider, searchProvider)
        {
            _invoiceService = (InvoiceService)service;
            _getOrders = getOrders;
        }

        /// <summary>
        /// Gets the key field in index.
        /// </summary>
        protected override string KeyFieldInIndex
        {
            get { return "invoiceKey"; }
        }

        /// <summary>
        /// Gets an display class by it's unique by key.
        /// </summary>
        /// <param name="key">
        /// The key.
        /// </param>
        /// <returns>
        /// The <see cref="InvoiceDisplay"/>.
        /// </returns>
        public override InvoiceDisplay GetByKey(Guid key)
        {
            return GetDisplayObject(key);
        }

        /// <summary>
        /// Searches all invoices
        /// </summary>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by field
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches all invoices by a term
        /// </summary>
        /// <param name="term">
        /// The term.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(string term, long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(term, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches invoices that have invoice dates within a specified date range
        /// </summary>
        /// <param name="invoiceDateStart">
        /// The invoice date start.
        /// </param>
        /// <param name="invoiceDateEnd">
        /// The invoice date end.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <param name="customerOnly">
        /// Restricts search to only invoices associated with a customer
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(DateTime invoiceDateStart, DateTime invoiceDateEnd, long page, long itemsPerPage, string sortBy = "invoiceDate", SortDirection sortDirection = SortDirection.Descending, bool customerOnly = false)
        {

            var query = customerOnly ?
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.CustomerKey != null ):
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches invoices that have invoice dates within a specified date range with a particular invoice status
        /// </summary>
        /// <param name="invoiceDateStart">
        /// The invoice date start.
        /// </param>
        /// <param name="invoiceDateEnd">
        /// The invoice date end.
        /// </param>
        /// <param name="invoiceStatusKey">
        /// The invoice status key.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <param name="customerOnly">
        /// Restricts search to only invoices associated with a customer
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(DateTime invoiceDateStart, DateTime invoiceDateEnd, Guid invoiceStatusKey, long page, long itemsPerPage, string sortBy = "invoiceDate", SortDirection sortDirection = SortDirection.Descending, bool customerOnly = false)
        {
            var query = customerOnly ?
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.InvoiceStatusKey == invoiceStatusKey  && x.CustomerKey != null ):
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.InvoiceStatusKey == invoiceStatusKey);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches invoices that have invoice dates within a specified date range with an export value
        /// </summary>
        /// <param name="invoiceDateStart">
        /// The invoice date start.
        /// </param>
        /// <param name="invoiceDateEnd">
        /// The invoice date end.
        /// </param>
        /// <param name="exported">
        /// The exported.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <param name="customerOnly">
        /// Restricts search to only invoices associated with a customer
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(DateTime invoiceDateStart, DateTime invoiceDateEnd, bool exported, long page, long itemsPerPage, string sortBy = "invoiceDate", SortDirection sortDirection = SortDirection.Descending, bool customerOnly = false)
        {
            var query = customerOnly ?
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.Exported == exported   && x.CustomerKey != null ):
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.Exported == exported);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches invoices that have invoice dates within a specified date range with a particular invoice status and export value
        /// </summary>
        /// <param name="invoiceDateStart">
        /// The invoice date start.
        /// </param>
        /// <param name="invoiceDateEnd">
        /// The invoice date end.
        /// </param>
        /// <param name="invoiceStatusKey">
        /// The invoice status key.
        /// </param>
        /// <param name="exported">
        /// The exported.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <param name="customerOnly">
        /// Restricts search to only invoices associated with a customer
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay Search(DateTime invoiceDateStart, DateTime invoiceDateEnd, Guid invoiceStatusKey, bool exported, long page, long itemsPerPage, string sortBy = "invoiceDate", SortDirection sortDirection = SortDirection.Descending, bool customerOnly = false)
        {
            var query = customerOnly ?
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.Exported == exported && x.InvoiceStatusKey == invoiceStatusKey  && x.CustomerKey != null):
                Query<IInvoice>.Builder.Where(x => x.InvoiceDate >= invoiceDateStart && x.InvoiceDate <= invoiceDateEnd && x.Exported == exported && x.InvoiceStatusKey == invoiceStatusKey  );

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches for invoices by invoice status.
        /// </summary>
        /// <param name="invoiceStatusKey">
        /// The invoice status key.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay SearchByInvoiceStatus(Guid invoiceStatusKey, long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            var query = Query<IInvoice>.Builder.Where(x => x.InvoiceStatusKey == invoiceStatusKey);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches for invoices by invoice status and exported value
        /// </summary>
        /// <param name="invoiceStatusKey">
        /// The invoice status key.
        /// </param>
        /// <param name="exported">
        /// The exported.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay SearchByInvoiceStatus(Guid invoiceStatusKey, bool exported, long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            var query = Query<IInvoice>.Builder.Where(x => x.InvoiceStatusKey == invoiceStatusKey && x.Exported == exported);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches for invoices associated with a customer
        /// </summary>
        /// <param name="customerKey">
        /// The customer key.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay SearchByCustomer(Guid customerKey, long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            var query = Query<IInvoice>.Builder.Where(x => x.CustomerKey == customerKey);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Searches for invoices associated with a customer and invoice status
        /// </summary>
        /// <param name="customerKey">
        /// The customer key.
        /// </param>
        /// <param name="invoiceStatusKey">
        /// The invoice status key.
        /// </param>
        /// <param name="page">
        /// The page.
        /// </param>
        /// <param name="itemsPerPage">
        /// The items per page.
        /// </param>
        /// <param name="sortBy">
        /// The sort by.
        /// </param>
        /// <param name="sortDirection">
        /// The sort direction.
        /// </param>
        /// <returns>
        /// The <see cref="QueryResultDisplay"/>.
        /// </returns>
        public QueryResultDisplay SearchByCustomer(Guid customerKey, Guid invoiceStatusKey, long page, long itemsPerPage, string sortBy = "invoiceNumber", SortDirection sortDirection = SortDirection.Descending)
        {
            var query = Query<IInvoice>.Builder.Where(x => x.CustomerKey == customerKey && x.InvoiceStatusKey == invoiceStatusKey);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, page, itemsPerPage, sortBy, sortDirection));
        }

        /// <summary>
        /// Gets the collection of all customer invoices
        /// </summary>
        /// <param name="customerKey">
        /// The customer key.
        /// </param>
        /// <returns>
        /// The collection of customer invoices.
        /// </returns>
        public IEnumerable<InvoiceDisplay> GetByCustomerKey(Guid customerKey)
        {
            var query = Query<IInvoice>.Builder.Where(x => x.CustomerKey == customerKey);

            return GetQueryResultDisplay(_invoiceService.GetPagedKeys(query, 1, int.MaxValue, "invoiceNumber")).Items.Select(x => (InvoiceDisplay)x);
        }

        /// <summary>
        /// The re-index entity.
        /// </summary>
        /// <param name="entity">
        /// The entity.
        /// </param>
        internal override void ReindexEntity(IInvoice entity)
        {
            IndexProvider.ReIndexNode(entity.SerializeToXml().Root, IndexTypes.Invoice);
        }

        /// <summary>
        /// Maps a <see cref="SearchResult"/> to <see cref="InvoiceDisplay"/>
        /// </summary>
        /// <param name="result">
        /// The result.
        /// </param>
        /// <returns>
        /// The <see cref="InvoiceDisplay"/>.
        /// </returns>
        protected override InvoiceDisplay PerformMapSearchResultToDisplayObject(SearchResult result)
        {
            return result.ToInvoiceDisplay(_getOrders);
        }
    }
}


text:
#region S# License

#endregion S# License
namespace StockSharp.Logging
{
	using System;
	using System.Collections.Generic;
	using System.IO;

	using Ecng.Collections;
	using Ecng.Common;

	using log4net;
	using log4net.Config;

	/// <summary>
	/// Helper class for messages logging based on log4net.
	/// </summary>
	public class Log4NetLogger : LogListener
	{
		private sealed class Source : BaseLogSource
		{
			public Source(string name)
			{
				_name = name;
			}

			private readonly string _name;

			public override string Name => _name;
		}

		private readonly Dictionary<string, Source> _sources = new Dictionary<string,Source>();
		private readonly ILog _log;

		/// <summary>
		/// Initializes a new instance of the <see cref="Log4NetLogger"/>.
		/// </summary>
		/// <param name="configFile">The path to the configuration file log4net.</param>
		public Log4NetLogger(string configFile)
		{
			XmlConfigurator.Configure(new FileInfo(configFile));

			_log = log4net.LogManager.GetLogger("FileAppender");
		}

		internal Log4NetLogListener LogListener { get; set; }

		/// <summary>
		/// To send an information message.
		/// </summary>
		/// <param name="message">Message text.</param>
		/// <param name="source">The message source.</param>
		public void Info(string message, string source = "")
		{
			Log(LogLevels.Info, message, source);
		}

		/// <summary>
		/// To send a warning message.
		/// </summary>
		/// <param name="message">Message text.</param>
		/// <param name="source">The message source.</param>
		public void Warning(string message, string source = "")
		{
			Log(LogLevels.Warning, message, source);
		}

		/// <summary>
		/// To send an error message.
		/// </summary>
		/// <param name="message">Message text.</param>
		/// <param name="source">The message source.</param>
		public void Error(string message, string source = "")
		{
			Log(LogLevels.Error, message, source);
		}

		/// <summary>
		/// To send a debug message.
		/// </summary>
		/// <param name="message">Message text.</param>
		/// <param name="source">The message source.</param>
		public void Debug(string message, string source = "")
		{
			Log(LogLevels.Debug, message, source);
		}

		private void Log(LogLevels level, string message, string source)
		{
			WriteMessages(new[] { new LogMessage(_sources.SafeAdd(source, key => new Source(key)), TimeHelper.NowWithOffset, level, message) });
		}

		/// <summary>
		/// To record a message.
		/// </summary>
		/// <param name="message">A debug message.</param>
		protected override void OnWriteMessage(LogMessage message)
		{
			if (message.IsDispose)
			{
				Dispose();
				return;
			}

			var str = "{0} | {1,-15} | {2}".Put(message.Time.ToString(LogListener.TimeFormat), message.Source, message.Message);

			switch (message.Level)
			{
				case LogLevels.Info:
					_log.Info(str);
					break;
				case LogLevels.Warning:
					_log.Warn(str);
					break;
				case LogLevels.Error:
					_log.Error(str);
					break;
				case LogLevels.Debug:
					_log.Debug(str);
					break;
				default:
					throw new ArgumentOutOfRangeException(nameof(message));
			}
		}
	}

	/// <summary>
	/// Logger sending out messages to <see cref="Log4NetLogger"/>.
	/// </summary>
	public class Log4NetLogListener : ExternalLogListener
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="Log4NetLogListener"/>.
		/// </summary>
		public Log4NetLogListener()
			: this("logger.xml")
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Log4NetLogListener"/>.
		/// </summary>
		/// <param name="configFile">The path to the configuration file log4net.</param>
		public Log4NetLogListener(string configFile)
			: this(new Log4NetLogger(configFile))
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="Log4NetLogListener"/>.
		/// </summary>
		/// <param name="logger">Helper class for messages logging based on log4net.</param>
		public Log4NetLogListener(Log4NetLogger logger)
			: base(logger)
		{
			logger.LogListener = this;
		}
	}
}


text:
package com.flowci.util;

import java.io.*;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.Consumer;

/**
 * @author yang
 */
public abstract class ObjectsHelper {

    public static int randomNumber(int min, int max) {
        return (int) ((Math.random() * (max - min)) + min);
    }

    public static boolean hasCollection(Collection<?> collection) {
        return collection != null && collection.size() > 0;
    }

    public static boolean hasCollection(Map<?, ?> map) {
        return map != null && !map.isEmpty();
    }

    public static Set<String> fields(Class<?> klass) {
        Set<String> fields = new HashSet<>();
        for (Class<?> c = klass; c != null; c = c.getSuperclass()) {
            for (Field f : c.getDeclaredFields()) {
                fields.add(f.getName());
            }
        }
        return fields;
    }

    /**
     * Check input fields are all have value or not
     */
    public static <T> boolean hasValue(T instance, Set<String> fields) throws ReflectiveOperationException {
        Map<String, Field> all = new HashMap<>();

        for (Class<?> c = instance.getClass(); c != null; c = c.getSuperclass()) {
            for (Field f : c.getDeclaredFields()) {
                all.put(f.getName(), f);
            }
        }

        for (String name : fields) {
            Field field = all.get(name);
            if (field == null) {
                throw new NoSuchFieldException(name);
            }

            field.setAccessible(true);
            Object o = field.get(instance);

            if (o == null) {
                return false;
            }

            if (o instanceof Collection) {
                if (((Collection<?>) o).isEmpty()) {
                    return false;
                }
            }
        }

        return true;
    }

    public static <T extends Serializable> List<T> copy(List<T> source) {
        List<T> dest = new ArrayList<>(source.size());

        for (T item : source) {
            dest.add(copy(item));
        }

        return dest;
    }

    public static <T extends Serializable> T copy(T source) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {

            try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
                oos.writeObject(source);
                oos.flush();
            }

            try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()))) {
                return (T) ois.readObject();
            }
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public static boolean tryParseInt(String val) {
        try {
            Integer.parseInt(val);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static <T> void ifNotNull(T val, Consumer<T> consumer) {
        if (Objects.isNull(val)) {
            return;
        }

        consumer.accept(val);
    }

    public static void throwIfNotNull(RuntimeException e) {
        if (e != null) {
            throw e;
        }
    }
}


text:
FROM gcr.io/oss-fuzz-base/base-builder
RUN apt-get update && apt-get install -y make autoconf automake libtool

# Using a real zlib project, but with broken build script and/or fuzz target.

RUN git clone --depth 1 https://github.com/madler/zlib.git
WORKDIR zlib
COPY build.sh bad_example_fuzzer.cc $SRC/


text:
package com.hazelcast.client.cache.eviction;

import com.hazelcast.cache.eviction.CacheEvictionPolicyComparatorTest;
import com.hazelcast.client.test.TestHazelcastFactory;
import com.hazelcast.config.Config;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.After;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import javax.cache.spi.CachingProvider;
import java.util.concurrent.ConcurrentMap;

import static com.hazelcast.cache.CacheTestSupport.createClientCachingProvider;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class ClientCacheEvictionPolicyComparatorTest extends CacheEvictionPolicyComparatorTest {

    private final TestHazelcastFactory instanceFactory = new TestHazelcastFactory();
    private HazelcastInstance instance;

    @Override
    protected CachingProvider createCachingProvider(HazelcastInstance instance) {
        return createClientCachingProvider(instance);
    }

    @Override
    protected HazelcastInstance createInstance(Config config) {
        instance = instanceFactory.newHazelcastInstance(config);
        return instanceFactory.newHazelcastClient();
    }

    @Override
    protected ConcurrentMap getUserContext(HazelcastInstance hazelcastInstance) {
        return instance.getUserContext();
    }

    @After
    public void tearDown() {
        instanceFactory.shutdownAll();
    }

}


text:
package com.codeteddy.frcscout.utils;

import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by Alex on 24.02.2017.
 */

public class TeamNumberWatcher implements TextWatcher {

    private TextInputLayout textInputLayout;
    private EditText editText;

    public TeamNumberWatcher(EditText editText, TextInputLayout textInputLayout){
        this.textInputLayout = textInputLayout;
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        try {
            int a = Integer.valueOf(editText.getText().toString().trim());

            if((a > 0) && (a < 10000)){
                textInputLayout.setErrorEnabled(false);
            }
            else if(a < 10000){
                textInputLayout.setError("Your number is too small");
            }
            else {
                textInputLayout.setError("Your number is too big");
            }

        }catch (Exception ex){
            textInputLayout.setError("This is not a number");
        }

    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Fusicladium hariotianum Sacc.

### Remarks
null


text:
package com.rackspace.com.papi.components.checker.wadl

import com.rackspace.com.papi.components.checker.TestConfig
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

//
//  Test for bug fix where preproc was turning on WellForm check in
//  appropriately.
//

@RunWith(classOf[JUnitRunner])
class WADLCheckerPreProcSpec extends BaseCheckerSpec {

    register ("chk","http://www.rackspace.com/repose/wadl/checker")

    feature ("The WADLCheckerBuilder should enable wellform checks only when approprite when prepoc extension is enabled") {
      val testWADL =
        <application xmlns="http://wadl.dev.java.net/2009/02">
        <grammars/>
        <resources base="https://test.api.openstack.com">
           <resource path="/a/b">
               <method name="PUT">
                  <request>
                      <representation mediaType="application/xml"/>
                      <representation mediaType="application/json"/>
                  </request>
               </method>
               <method name="POST">
                  <request>
                      <representation mediaType="application/xml"/>
                  </request>
               </method>
           </resource>
           <resource path="/c">
               <method name="POST">
                  <request>
                      <representation mediaType="application/json"/>
                  </request>
               </method>
               <method name="GET"/>
           </resource>
           <resource path="/any">
              <method name="POST">
                 <request>
                    <representation mediaType="*/*"/>
                 </request>
              </method>
           </resource>
           <resource path="/text">
              <method name="POST">
                 <request>
                    <representation mediaType="text/*"/>
                 </request>
              </method>
           </resource>
           <resource path="/v">
              <method name="POST">
                 <request>
                    <representation mediaType="text/plain;charset=UTF8"/>
                 </request>
              </method>
           </resource>
        </resources>
      </application>

      val testPreProcWADL =
        <application xmlns="http://wadl.dev.java.net/2009/02"
                     xmlns:rax="http://docs.rackspace.com/api"
                     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <grammars/>
        <resources base="https://test.api.openstack.com">
           <resource path="/a/b">
               <method name="PUT">
                  <request>
                      <representation mediaType="application/xml"/>
                      <representation mediaType="application/json"/>
                  </request>
               </method>
               <method name="POST">
                  <request>
                      <representation mediaType="application/xml">
                        <rax:preprocess>
                            <xsl:stylesheet version="1.0">
                              <xsl:output method="xml" encoding="UTF-8"/>
                            </xsl:stylesheet>
                        </rax:preprocess>
                      </representation>
                  </request>
               </method>
           </resource>
           <resource path="/c">
               <method name="POST">
                  <request>
                      <representation mediaType="application/json"/>
                  </request>
               </method>
               <method name="GET"/>
           </resource>
           <resource path="/any">
              <method name="POST">
                 <request>
                    <representation mediaType="*/*"/>
                 </request>
              </method>
           </resource>
           <resource path="/text">
              <method name="POST">
                 <request>
                    <representation mediaType="text/*"/>
                 </request>
              </method>
           </resource>
           <resource path="/v">
              <method name="POST">
                 <request>
                    <representation mediaType="text/plain;charset=UTF8"/>
                 </request>
              </method>
           </resource>
        </resources>
      </application>

      scenario("The testWADL is processed with preporc extension disabled") {
        Given("The testWADL with preproc extension disabled")
        When("The WADL is transalted")
        val checker = builder.build(testWADL, TestConfig(false, false, false, false, false, 1, false, false, false))
        Then("There should not be any well-form checks")
        assert(checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 0");
      }

      scenario("The testWADL is processed with preporc extension enabled") {
        Given("The testWADL with preproc extension disabled")
        When("The WADL is transalted")
        val checker = builder.build(testWADL, TestConfig(false, false, false, false, false, 1, false, false, true))
        Then("There should not be any well-form checks")
        assert(checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 0");
      }

      scenario("The testPreProcWADL is processed with preporc extension enabled") {
        Given("The testPreProcWADL with preproc extension disabled")
        When("The WADL is transalted")
        val checker = builder.build(testPreProcWADL, TestConfig(false, false, false, false, false, 1, false, false, true))
        Then("There should be a single WELL_XML step on the POST operation")
        assert(checker, "count(/chk:checker/chk:step[@type='WELL_XML']) = 1")
        assert(checker, "count(/chk:checker/chk:step[@type='XSL']) = 1")
        assert(checker, Start, URL("a"), URL("b"), Method("POST"),
               ReqType("(application/xml)(;.*)?"), WellXML, XSL, Accept)
      }
    }
}


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from prov.model import ProvDocument
from prov.tests.utility import BaseTestCase, RoundTripTestCase
from prov.tests.test_model import AllTestsBase

import logging
logger = logging.getLogger(__name__)

class TestJSONSerializer(BaseTestCase):
    def test_decoding_unicode_value(self):
        unicode_char = u'\u2019'
        json_content = u'''{
    "prefix": {
        "ex": "http://www.example.org"
    },
    "entity": {
        "ex:unicode_char": {
            "prov:label": "%s"
        }
    }
}''' % unicode_char

        prov_doc = ProvDocument.deserialize(content=json_content, format='json')
        e1 = prov_doc.get_record('ex:unicode_char')[0]
        self.assertIn(unicode_char, e1.get_attribute('prov:label'))

class RoundTripJSONTests(RoundTripTestCase, AllTestsBase):
    FORMAT = 'json'


text:
def process_dictionary(dict):
    '''
    :param dict: the raw dictionary
    :return: a dictionary where all the values have been checked and manipulated as needed
    '''

    batch_interpreter_version = 'beta2'

    ## Replace special tags with simulation-relevant ones

    if 'r_mitosis_R123' in dict.keys():
        val = dict['r_mitosis_R123']
        dict['r_mitosis_R1'] = val
        dict['r_mitosis_R2'] = val
        dict['r_mitosis_R3'] = val
        del dict['r_mitosis_R123']

    if 'r_grow_R123' in dict.keys():
        val = dict['r_grow_R123']
        dict['r_grow_R1'] = val
        dict['r_grow_R2'] = val
        dict['r_grow_R3'] = val
        del dict['r_grow_R123']

    if 'r_mitosis_GZ' in dict.keys():
        val = dict['r_mitosis_GZ']
        dict['r_mitosis_R2'] = val
        dict['r_mitosis_R3'] = val
        del dict['r_mitosis_GZ']

    if 'r_grow_GZ' in dict.keys():
        val = dict['r_grow_GZ']
        dict['r_grow_R2'] = val
        dict['r_grow_R3'] = val
        del dict['r_grow_GZ']

    ## Turn off r_grow if r_mitosis is off and, if r_grow is not specified then give is a default value. Also, vise-versa.

    # First, pull default values from the params dict
    default_growth_rate = dict.get('default_growth_rate', 0.02) # Unless otherwise specified, this will be 0.02
    default_mitosis_rate = dict.get('default_mitosis_rate', 0.2) # Unless otherwise specified, this will be 0.2
    num_mitosis_transitions = len(dict['mitosis_transition_times'])

    # Then, generate the keys
    mitosis_keys = ('r_mitosis_R{}'.format(i) for i in range(4))
    growth_keys = ('r_grow_R{}'.format(i) for i in range(4))

    # Finally, scan through the r_mitosis_* and R_grow_* to see if we need turn them on.
    for mitosis_key, growth_key in zip(mitosis_keys, growth_keys):
        if mitosis_key not in dict and growth_key not in dict:
            dict[mitosis_key] = [default_mitosis_rate] * num_mitosis_transitions
            dict[growth_key] = [default_growth_rate] * num_mitosis_transitions

        elif mitosis_key in dict and growth_key not in dict:
            dict[growth_key] = []
            for mitosis_window in dict[mitosis_key]:
                if mitosis_window == 0.0:
                    dict.get(growth_key,[]).append(0.0)
                else:
                    dict.get(growth_key,[]).append(default_growth_rate)

        elif mitosis_key not in dict and growth_key in dict:
            dict[mitosis_key] = []
            for growth_window in dict[growth_key]:
                if growth_window == 0.0:
                    dict.get(mitosis_key, []).append(0.0)
                else:
                    dict.get(mitosis_key, []).append(default_mitosis_rate)

    error_check_params_dict(dict)
    return dict

def error_check_params_dict(dict):
    '''
    Make sure that all parameters are specified and raise an error if they are not
    '''
    necessary_variables = ['embryo_size', 'stripe_period', 'dye_flag', 'x0_dye', 'xf_dye', 'y0_dye', 'yf_dye',
                           'AP_growth_constraint_flag', 'forces_on', 'V_AP_GZposterior', 'k1_AP_GZanterior',
                           'k2_AP_GZanterior', 'k1_AP_Segments', 'k2_AP_Segments', 'k1_ML_GZ', 'k2_ML_GZ',
                           'k1_ML_Segments', 'k2_ML_Segments', 'mitosis_on', 'y_GZ_mitosis_border_percent',
                           'mitosis_transition_times', 'r_mitosis_R0', 'r_mitosis_R1', 'r_mitosis_R2', 'r_mitosis_R3',
                           'r_grow_R0', 'r_grow_R1', 'r_grow_R2', 'r_grow_R3', 'mitosis_fraction_AP_oriented',
                           'mitosis_window', 'mitosis_Vmin_divide', 'mitosis_Vmax', 'mitosis_visualization_flag',
                           'mitosis_visualization_window', 'dye_mitosis_clones', 'mitosis_dye_window']

    missing_variables = []
    for var in necessary_variables:
        if var not in dict:
            missing_variables.append(var)
    if len(missing_variables) > 0:
        raise NameError('Missing Variables! Please specify: {}'.format(', '.join(missing_variables)))


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

package Bio::EnsEMBL::Analysis::Hive::Config::LoadAssembly;

use strict;
use warnings;
use File::Spec::Functions;

use Bio::EnsEMBL::Hive::PipeConfig::HiveGeneric_conf; # Needed for the WHEN ELSE structure
use base ('Bio::EnsEMBL::Analysis::Hive::Config::HiveBaseConfig_conf');

sub default_options {
  my ($self) = @_;
  return {
    # inherit other stuff from the base class
    %{ $self->SUPER::default_options() },

######################################################
#
# Variable settings- You change these!!!
#
######################################################
########################
# Misc setup info
########################
    dbowner                   => '' || $ENV{EHIVE_USER} || $ENV{USER},
    pipeline_name             => '' || $self->o('production_name').'_'.$self->o('ensembl_release'),
    user_r                    => '', # read only db user
    user                      => '', # write db user
    password                  => '', # password for write db user
    pipe_db_host              => '', # host for pipe db
    dna_db_host               => '', # host for dna db
    pipe_db_port              => '', # port for pipeline host
    dna_db_port               => '', # port for dna db host
    release_number            => '' || $self->o('ensembl_release'),
    species_name              => '', # e.g. mus_musculus
    production_name           => '', # usually the same as species name but currently needs to be a unique entry for the production db, used in all core-like db names
    dbname_accession          => '', # This is the assembly accession without [._] and all lower case, i.e gca001857705v1
    taxon_id                  => '', # should be in the assembly report file
    output_path               => '', # Lustre output dir. This will be the primary dir to house the assembly info and various things from analyses
    wgs_id                    => '', # Can be found in assembly report file on https://ftp.ncbi.nlm.nih.gov/genomes/genbank/
    assembly_name             => '', # Name (as it appears in the assembly report file)
    assembly_accession        => '', # Versioned GCA assembly accession, e.g. GCA_001857705.1
    stable_id_prefix          => '', # e.g. ENSPTR. When running a new annotation look up prefix in the assembly registry db
    species_url               => '', # sets species.url meta key
    species_division          => 'EnsemblVertebrates', # sets species.division meta key

    # Keys for custom loading, only set/modify if that's what you're doing
    load_toplevel_only        => '1', # This will not load the assembly info and will instead take any chromosomes, unplaced and unlocalised scaffolds directly in the DNA table
    custom_toplevel_file_path => '', # Only set this if you are loading a custom toplevel, requires load_toplevel_only to also be set to 2

    # The following might not be known in advance, since the come from other pipelines
    # These values can be replaced in the analysis_base table if they're not known yet
    # If they are not needed (i.e. no projection or rnaseq) then leave them as is
    assembly_provider_name   => '',
    assembly_provider_url    => '',
    annotation_provider_name => 'Ensembl',
    annotation_provider_url  => 'www.ensembl.org',

########################
# Pipe and ref db info
########################
    pipe_db_name => $self->o('dbowner').'_'.$self->o('dbname_accession').'_load_assembly_pipe_'.$self->o('release_number'),
    dna_db_name  => $self->o('dbowner').'_'.$self->o('dbname_accession').'_core_'.$self->o('release_number'),

    reference_db_name   => $self->o('dna_db_name'),
    reference_db_host   => $self->o('dna_db_host'),
    reference_db_port   => $self->o('dna_db_port'),

    # This is used for the ensembl_production and the ncbi_taxonomy databases
    ensembl_release      => $ENV{ENSEMBL_RELEASE}, # this is the current release version on staging to be able to get the correct database
    production_db_host   => 'mysql-ens-meta-prod-1',
    production_db_port   => '4483',
    production_db_name   => 'ensembl_production',

    taxonomy_db_host   => $self->o('production_db_host'),
    taxonomy_db_port   => $self->o('production_db_port'),
    taxonomy_db_name   => 'ncbi_taxonomy',

    databases_to_delete => ['reference_db'],#, 'projection_realign_db'

######################################################
#
# Mostly constant settings
#
######################################################
    genome_dumps => catdir($self->o('output_path'), 'genome_dumps'),
    # This one is used in replacement of the dna table in the core db, so where analyses override slice->seq. Has simple headers with just the seq_region name. Also used by bwa in the RNA-seq analyses. Not masked
    faidx_genome_file => catfile($self->o('genome_dumps'), $self->o('species_name').'_toplevel.fa'),

    primary_assembly_dir_name => 'Primary_Assembly',
    contigs_source            => 'ena',

    ensembl_analysis_script => catdir($self->o('enscode_root_dir'), 'ensembl-analysis', 'scripts'),
    sequence_dump_script    => catfile($self->o('ensembl_analysis_script'), 'sequence_dump.pl'),

########################
# Executable paths
########################
    samtools_path => catfile($self->o('binary_base'), 'samtools'), #You may need to specify the full path to the samtools binary

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# No option below this mark should be modified
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#
########################################################
# URLs for retrieving the INSDC contigs and RefSeq files
########################################################
    ncbi_base_ftp           => 'https://ftp.ncbi.nlm.nih.gov/genomes/all',
    insdc_base_ftp          => $self->o('ncbi_base_ftp').'/#expr(substr(#assembly_accession#, 0, 3))expr#/#expr(substr(#assembly_accession#, 4, 3))expr#/#expr(substr(#assembly_accession#, 7, 3))expr#/#expr(substr(#assembly_accession#, 10, 3))expr#/#assembly_accession#_#assembly_name#',
    assembly_ftp_path       => $self->o('insdc_base_ftp'),

########################
# db info
########################
    reference_db => {
      -dbname => $self->o('reference_db_name'),
      -host   => $self->o('reference_db_host'),
      -port   => $self->o('reference_db_port'),
      -user   => $self->o('user'),
      -pass   => $self->o('password'),
      -driver => $self->o('hive_driver'),
    },

    production_db => {
      -host   => $self->o('production_db_host'),
      -port   => $self->o('production_db_port'),
      -user   => $self->o('user_r'),
      -pass   => $self->o('password_r'),
      -dbname => $self->o('production_db_name'),
      -driver => $self->o('hive_driver'),
    },

    taxonomy_db => {
      -host   => $self->o('taxonomy_db_host'),
      -port   => $self->o('taxonomy_db_port'),
      -user   => $self->o('user_r'),
      -pass   => $self->o('password_r'),
      -dbname => $self->o('taxonomy_db_name'),
      -driver => $self->o('hive_driver'),
    },
  };
}

sub pipeline_create_commands {
  my ($self) = @_;

  return [
  # inheriting database and hive tables' creation
    @{$self->SUPER::pipeline_create_commands},
    'mkdir -p '.$self->o('genome_dumps'),
  ];
}

sub pipeline_wide_parameters {
  my ($self) = @_;

  return {
    %{$self->SUPER::pipeline_wide_parameters},
    load_toplevel_only => $self->o('load_toplevel_only'),
  }
}

## See diagram for pipeline structure
sub pipeline_analyses {
  my ($self) = @_;

  return [
    {
      -logic_name => 'create_core_db',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveCreateDatabase',
      -parameters => {
        'target_db'        => $self->o('reference_db'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'create_type'      => 'core_only',
      },
      -rc_name    => 'default',
      -input_ids  => [
        {
          assembly_name => $self->o('assembly_name'),
          assembly_accession => $self->o('assembly_accession'),
        },
      ],
      -flow_into  => {
        1 => ['populate_production_tables'],
      },
    },

    {
      -logic_name => 'populate_production_tables',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HivePopulateProductionTables',
      -parameters => {
        'target_db'        => $self->o('reference_db'),
        'output_path'      => $self->o('output_path'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'production_db'    => $self->o('production_db'),
      },
      -rc_name    => 'default',
      -flow_into  => {
        1 => WHEN ('#load_toplevel_only# == 1' => ['process_assembly_info'],
              '#load_toplevel_only# == 2' => ['custom_load_toplevel'],
            ELSE ['download_assembly_info']),
      },
    },

    ####
    # Loading custom assembly where the user provide a FASTA file, probably a repeat library
    ####
    {
      -logic_name => 'custom_load_toplevel',
      -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('enscode_root_dir'), 'ensembl-analysis', 'scripts', 'assembly_loading', 'load_seq_region.pl').
          ' -dbhost '.$self->o('reference_db_host').
          ' -dbuser '.$self->o('user').
          ' -dbpass '.$self->o('password').
          ' -dbport '.$self->o('reference_db_port').
          ' -dbname '.$self->o('reference_db_name').
          ' -coord_system_version '.$self->o('assembly_name').
          ' -default_version'.
          ' -coord_system_name primary_assembly'.
          ' -rank 1'.
          ' -fasta_file '. $self->o('custom_toplevel_file_path').
          ' -sequence_level'.
          ' -noverbose',
      },
      -rc_name => '4GB',
      -flow_into => {
        1 => ['custom_set_toplevel'],
      },
    },

    {
      -logic_name => 'custom_set_toplevel',
      -module => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -parameters => {
        cmd => 'perl '.catfile($self->o('enscode_root_dir'), 'ensembl-analysis', 'scripts', 'assembly_loading', 'set_toplevel.pl').
          ' -dbhost '.$self->o('reference_db_host').
          ' -dbuser '.$self->o('user').
          ' -dbpass '.$self->o('password').
          ' -dbport '.$self->o('reference_db_port').
          ' -dbname '.$self->o('reference_db_name'),
      },
      -rc_name => 'default',
      -flow_into  => {
        1 => ['custom_add_meta_keys'],
      },
    },

    {
      -logic_name => 'custom_add_meta_keys',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd',
      -parameters => {
        db_conn => $self->o('reference_db'),
        sql => [
          'INSERT INTO meta (species_id,meta_key,meta_value) VALUES (1,"assembly.default","'.$self->o('assembly_name').'")',
          'INSERT INTO meta (species_id,meta_key,meta_value) VALUES (1,"assembly.name","'.$self->o('assembly_name').'")',
          'INSERT INTO meta (species_id,meta_key,meta_value) VALUES (1,"species.taxonomy_id","'.$self->o('taxon_id').'")',
        ],
      },
      -rc_name    => 'default',
      -flow_into => {
        1 => ['load_meta_info'],
      },
    },

    ####
    # Loading assembly with only the toplevel sequences loaded, it fetches the data from INSDC databases
    ####
    # Download the files and dir structure from the NCBI ftp site. Uses the link to a species in the ftp_link_file
    {
      -logic_name => 'process_assembly_info',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveProcessAssemblyReport',
      -parameters => {
        full_ftp_path => $self->o('assembly_ftp_path'),
        output_path   => $self->o('output_path'),
        target_db     => $self->o('reference_db'),
      },
      -rc_name    => '8GB',
      -max_retry_count => 0,
      -flow_into  => {
        1 => ['load_meta_info'],
      },
    },

    # Load some meta info and seq_region_synonyms
    {
      -logic_name => 'load_meta_info',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SqlCmd',
      -parameters => {
        db_conn => $self->o('reference_db'),
        sql => [
          'INSERT INTO meta (species_id, meta_key, meta_value) VALUES '.
          '(1, "species.stable_id_prefix", "'.$self->o('stable_id_prefix').'"),'.
          '(1, "species.url", "'.ucfirst($self->o('species_url')).'"),'.
          '(1, "species.division", "'.$self->o('species_division').'"),'.
          '(1, "genebuild.initial_release_date", NULL),'.
          '(1, "assembly.coverage_depth", "high"),'.
          '(1, "genebuild.id", '.$self->o('genebuilder_id').'),'.
	  '(1, "genebuild.method", "full_genebuild"),'.
	  '(1, "genebuild.method_display", "Ensembl Genebuild"),'.
          '(1, "assembly.provider_name", "'.$self->o('assembly_provider_name').'"),'.
          '(1, "assembly.provider_url", "'.$self->o('assembly_provider_url').'"),'.
          '(1, "annotation.provider_name", "'.$self->o('annotation_provider_name').'"),'.
          '(1, "annotation.provider_url", "'.$self->o('annotation_provider_url').'"),'.
          '(1, "species.production_name", "'.$self->o('production_name').'")',
        ],
      },
      -rc_name    => 'default',
      -flow_into  => {
        1 => ['load_taxonomy_info'],
      },
    },

    ####
    # Loading assembly with the full assembly representation, it fetches data from INSDC databases
    ####
    # Download the files and dir structure from the NCBI ftp site. Uses the link to a species in the ftp_link_file
    {
      -logic_name => 'download_assembly_info',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveDownloadNCBIFtpFiles',
      -parameters => {
        'full_ftp_path'             => $self->o('assembly_ftp_path'),
        'output_path'               => $self->o('output_path'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name    => 'default',
      -flow_into  => {
        1 => ['find_contig_accessions'],
      },
    },

    # Get the prefixes for all contigs from the AGP files
    {
      -logic_name => 'find_contig_accessions',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveFindContigAccessions',
      -parameters => {
        'contigs_source'            => $self->o('contigs_source'),
        'wgs_id'                    => $self->o('wgs_id'),
        'output_path'               => $self->o('output_path'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name => 'default',
      -flow_into => {
        1 => ['download_contigs'],
      },
    },

    # Download contig from NCBI
    {
      -logic_name => 'download_contigs',
      -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveDownloadContigs',
      -parameters => {
        'contigs_source' => $self->o('contigs_source'),
        'wgs_id' => $self->o('wgs_id'),
        'output_path' => $self->o('output_path'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name => 'default',
      -flow_into => {
        1 => ['load_contigs'],
      },
    },

    # Load the contigs into each reference db
    {
      -logic_name => 'load_contigs',
      -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveLoadSeqRegions',
      -parameters => {
        'coord_system_version' => $self->o('assembly_name'),
        'target_db' => $self->o('reference_db'),
        'output_path' => $self->o('output_path'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name => '4GB',
      -flow_into => {
        1 => ['load_assembly_info'],
      },
    },

    # Load the AGP files
    {
      -logic_name => 'load_assembly_info',
      -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveLoadAssembly',
      -parameters => {
        'target_db' => $self->o('reference_db'),
        'output_path' => $self->o('output_path'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name => 'default',
      -flow_into => {
        1 => ['set_toplevel'],
      },
    },

    # Set the toplevel
    {
      -logic_name => 'set_toplevel',
      -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveSetAndCheckToplevel',
      -parameters => {
        'target_db' => $self->o('reference_db'),
        'output_path' => $self->o('output_path'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
      },
      -rc_name => '2GB',
      -flow_into => {
        1 => ['load_meta_info_full'],
      },
    },

    # Load some meta info and seq_region_synonyms
    {
      -logic_name => 'load_meta_info_full',
      -module => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveSetMetaAndSeqRegionSynonym',
      -parameters => {
        'target_db' => $self->o('reference_db'),
        'output_path' => $self->o('output_path'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'primary_assembly_dir_name' => $self->o('primary_assembly_dir_name'),
        'meta_key_list' => {
          'assembly.accession' => $self->o('assembly_accession'),
          'assembly.coverage_depth' => 'high',
          'assembly.default' => $self->o('assembly_name'),
          'assembly.name' => $self->o('assembly_name'),
          'assembly.web_accession_source' => 'NCBI',
          'assembly.web_accession_type' => 'GenBank Assembly ID',
          'genebuild.id' => $self->o('genebuilder_id'),
	  'genebuild.method' => 'full_genebuild',
	  'genebuild.method_display' => 'Ensembl Genebuild',
          'assembly.provider_name' => $self->o('assembly_provider_name'),
          'assembly.provider_url' => $self->o('assembly_provider_url'),
          'annotation.provider_name' => $self->o('annotation_provider_name'),
          'annotation.provider_url' => $self->o('annotation_provider_url'),
          'species.production_name' => $self->o('production_name'),
          'species.taxonomy_id' => $self->o('taxon_id'),
        }
      },
      -rc_name => 'default',
      -flow_into => {
        1 => ['load_taxonomy_info'],
      },
    },

    {
      -logic_name => 'load_taxonomy_info',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveLoadTaxonomyInfo',
      -parameters => {
        'target_db'        => $self->o('reference_db'),
        'taxonomy_db'      => $self->o('taxonomy_db'),
      },
      -rc_name    => 'default',
      -flow_into  => {
        1 => ['load_mitochondrion'],
      },
    },

    {
      -logic_name => 'load_mitochondrion',
      -module     => 'Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveAssemblyLoading::HiveLoadMitochondrion',
      -parameters => {
        'target_db'        => $self->o('reference_db'),
        'output_path'      => $self->o('output_path'),
        'enscode_root_dir' => $self->o('enscode_root_dir'),
        'species_name'     => $self->o('species_name'),
      },
      -rc_name    => 'default',
      -flow_into  => {
        1 => ['create_faidx_genome_file'],
      },
    },

    {
      -logic_name => 'create_faidx_genome_file',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -rc_name => '1GB',
      -parameters => {
        cmd => 'if [ ! -s "'.$self->o('faidx_genome_file').'" ]; then perl '.$self->o('sequence_dump_script').' -dbhost '.$self->o('dna_db_host').' -dbuser '.$self->o('dna_db_user').' -dbport '.$self->o('dna_db_port').' -dbname '.$self->o('dna_db_name').' -coord_system_name '.$self->o('assembly_name').' -toplevel -onefile -header rnaseq -filename '.$self->o('faidx_genome_file').';fi',
      },
      -flow_into => {
        1 => [ 'create_faidx'],
      },
    },

    {
      -logic_name => 'create_faidx',
      -module     => 'Bio::EnsEMBL::Hive::RunnableDB::SystemCmd',
      -rc_name => '5GB',
      -parameters => {
        cmd => 'if [ ! -e "'.$self->o('faidx_genome_file').'.fai" ]; then '.$self->o('samtools_path').' faidx '.$self->o('faidx_genome_file').';fi',
      },
    },
  ];
}

sub resource_classes {
  my $self = shift;

  return {
    '1GB' => { LSF => $self->lsf_resource_builder('production', 1000)},
    '2GB' => { LSF => $self->lsf_resource_builder('production', 2000)},
    '4GB' => { LSF => $self->lsf_resource_builder('production', 4000)},
    '5GB' => { LSF => $self->lsf_resource_builder('production', 5000)},
    '8GB' => { LSF => $self->lsf_resource_builder('production', 8000)},
    'default' => { LSF => $self->lsf_resource_builder('production', 900)},
  }
}

1;


text:
layout: post
title:      "Approaching the Sinatra Portfolio Project"
date:       2018-05-17 14:20:32 -0400
# img:
# modalID:
category: Blog
---

My [Sinatra portfolio project](https://github.com/bcfsu/recipe-bookmarker) was much more complex than the CLI Data Gem, but, felt less overwhelming to complete.  With each project, I can feel myself developing a systematic approach to project planning, and problem solving.

**Project Prep and Set Up:**

The specs require more than one model class to interact with eachother.  I began building the idea for my application based on ideas that I could easily convert into models with simple relationships.  Since cooking and eating are always on my mind, I decided to create an application that can keep track of recipes and their associated websites.  I could imagine users logging in to their account to review new recipes that had been posted by other users that day, and deciding whether or not to bookmark them for later use.

After I could envision my plan, I used the [corneal gem](https://github.com/thebrianemory/corneal) to create a working application skeleton.

**Creating the Database:**

I decided to draw out my database and its tables before creating my migrations.  My first idea involved three classes:  User, Recipe, and UserRecipe.  I wanted to make sure Users could create their own recipe bookmarks, while simultaneously be able to save other users' recipes to their own collections.  I attempted to make these relationships work by implementing a has_many through: relationship, along with [aliasing in Active Record](https://unorientedobject.wordpress.com/2016/09/14/aliasing-and-options-in-rails-activerecord-associations/).

This created issues for me.  My relationships were flawed -- I tried to make a Recipe belong_to a single User with the alias `creator` (referencing a User by way of a `creator_id` foreign key) AND allow many Users bookmark the same recipe by way of the UserRecipe join table relationship.  I began noticing flaws in this relationship when I attempted to populate a user's created recipes AND recipes that they had bookmarked...  Perhaps I could have made it work with the aliases I had drawn out, but I ended up scrapping that idea and simplifying it to my final model relationships, using just two additional migrations to fix it up:

```
class User < ActiveRecord::Base
  has_many :bookmarks
  has_many :recipes

  has_secure_password
  validates_presence_of :username, :password_digest
  validates :username, uniqueness: true

end

class Recipe < ActiveRecord::Base
  belongs_to :user
  has_many :bookmarks

  validates_presence_of :name, :url
  validates :name, uniqueness: true

end

class Bookmark < ActiveRecord::Base
  belongs_to :user
  belongs_to :recipe

end

```

By separating User's Recipes and User's Bookmarks, I am able to better organize which Users are able to "CRUD" the Recipe resource, and which do not have access to do so.  It was easier to validate which actions a User had access to this way.  Any User is able to control what they have Bookmarked, but not all Users can edit or delete a Recipe that they have not created.

**Creating the MVC:**

It felt weird to break down the flow of user navigation on a website.  It's something I had not thought a lot about until I worked on this project.  Tiny details, like navigation links, slipped my mind until I dropped into my server to test out the code I had written.  I ended up including a "Log Out" link in the footer of the layout, and adding links to the user's homepage and the recipe homepage on each view.  The image below is a physical draft of how I imagined my views matching up with the routes in my application controllers:

![](https://s31.postimg.cc/8i7mdc7l7/20180517_121111.jpg)

**Stumbling Blocks:**

The biggest obstacle in seeing this project through was working through Active Record relationships and playing with "fake" data in the development stage.  I found that I was drawing up relationships and trying to see how they worked in the `tux` gem, but ended up confusing myself because I was working with OLD data that had not been persisted, or, relationships that were incorrect because they were created using my old model relationships.  I had to reset my database several times during this process.  It was challenging to work around this without a program to visualize the data I had in my development database.  In the future, I would use a database application to visualize my sqlite information.

Another stumbling block that I created for myself was a time crunch!  I pre-scheduled my project assessment to keep myself accountable and on track.  I am glad that I met my personal deadline, however, there are some flaws in my code that I was unable to seek assistance on due to my limited time frame.  Some of my code needs to be "DRYed up" and a lot of it can be refactored.

**Future Plans:**

I can see myself expanding this application in two big ways.

1. Adding a feature that scrapes the Recipe's URL for additional recipe information. The recipe summary would populate on the show page, so that a User could decide if she wants to navigate to the webpage or not.

2. Creating a stats page for the most popular Users. This page would let other users know who has the most recipes uploaded, or which User's recipes are the most frequently bookmarked by others.

**Final Thoughts:**

I love coding an idea from start to finish.  The Sinatra section came together for me in a big way during this project.  I have built a ton of confidence in myself during this project, more than the labs were ever able to do.  This project is by no means pretty, spectacularly unique or groundbreaking, or even that great! But, I made it all by myself, and it meets all the criteria that was set out for me.  After submitting this, I hope to explain my project's strengths, its areas of improvement, and to get feedback on how best to improve it.  I look forward to learning and improving.

[Here](https://www.youtube.com/watch?v=0Ufmqr4n6Wc&list=PLvoc254CB95PnHE-wEIpqMpxyuczJrlgW) are two videos in which I walk through my application, and then debug an error that occurs during the walkthrough.


text:
package db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyWeatherOpenHelper extends SQLiteOpenHelper {

	/**
	 *  Create table for Province
	 */
	public static final String CREATE_PROVINCE = "create table Province ("
			+ "id integer primary key autoincrement, "
			+ "province_name text, "
			+ "province_code text) ";

	/**
	 *  Create table for City
	 */
	public static final String CREATE_CITY = "create table City ("
			+ "id integer primary key autoincrement, "
			+ "city_name text, "
			+ "city_code text, "
			+ "province_id interger) ";

	/**
	 *  Create table for County
	 */
	public static final String CREATE_COUNTY = "create table County ("
			+ "id integer primary key autoincrement, "
			+ "county_name text, "
			+ "county_code text, "
			+ "city_id integer) ";

	public MyWeatherOpenHelper(Context context, String name, CursorFactory factory, int version){
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(CREATE_PROVINCE);
		db.execSQL(CREATE_CITY);
		db.execSQL(CREATE_COUNTY);

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}