text:
#include <string.h>

#include "CSparseMatrix_internal.h"
#include "AffineVariationalInequalities.h"
#include "AVI_Solvers.h"
#include "NumericsMatrix.h"
#include "numerics_verbose.h"
#include "SiconosSets.h"

#ifdef HAVE_PATHVI

#include "PATHVI_helpers.h"
#include "PATHVI_SDK/include/vi_consts.h"
#include "PATHVI_SDK/include/csc_matrix.h"
#include "PATHVI_SDK/include/vi_scheduler.h"
#include "PATHVI_SDK/include/vi_solver_pathvi.h"
#include "PATHVI_SDK/include/printv.h"

static void pathvi_csc_transfert(struct csc_matrix *primjac, CSparseMatrix* M)
{
  size_t n = primjac->n;
  size_t nnz = primjac->nnz;

  /*  Easy copy */
  memcpy(primjac->x, M->x, nnz * sizeof(double));

  /*  we may have to change the behavior based on the type used for integers */
  if (sizeof(primjac->i) != sizeof(CS_INT))
  {
    for (size_t i = 0; i < nnz; ++i)
    {
      primjac->i[i] = (PATHVI_INDX_TYPE)M->i[i];
    }

    for (size_t i = 0; i <= n; ++i)
    {
      primjac->j[i] = (PATHVI_INDX_TYPE)M->p[i];
    }
  }
  else
  {
    memcpy(primjac->i, M->i, nnz * sizeof(CS_INT));
    memcpy(primjac->j, M->p, n+1 * sizeof(CS_INT));
  }

}

static int pathvi_evaluate_function(struct vi_desc *desc, double *primvar, double *primfunc)
{
  SN_generic_pathvi_env* env = (SN_generic_pathvi_env*)vi_desc_get_controller(desc);
  AffineVariationalInequalities* AVI = (AffineVariationalInequalities*) env->problem;

  memcpy(primfunc, AVI->q, AVI->size * sizeof(double));
  NM_gemv(1.0, AVI->M, primvar, 1., primfunc);

  return 0;
}

static int pathvi_evaluate_jacobian(struct vi_desc *desc, double *primvar, double *primfunc, struct csc_matrix *primjac)
{
  SN_generic_pathvi_env* env = (SN_generic_pathvi_env*)vi_desc_get_controller(desc);
  AffineVariationalInequalities* AVI = (AffineVariationalInequalities*) env->problem;

  size_t n = AVI->size;

  switch (AVI->M->storageType)
  {
  case NM_DENSE:
  {
    size_t nnz = AVI->M->size0 * AVI->M->size1;

    break;
  }
  case NM_SPARSE:
  {
    CSparseMatrix* M = NM_csc(AVI->M);
    CS_INT nnz = M->p[n];

    /* check dimenstions */
    if (M->n > primjac->max_n) { primjac->max_n = M->n; primjac->j = (PATHVI_INDX_TYPE*)realloc(primjac->j, (M->n+1) * sizeof(primjac->j)); }

    if (nnz > primjac->max_nnz)
    {
      primjac->max_nnz = nnz;
      primjac->i = (PATHVI_INDX_TYPE*)realloc(primjac->i, nnz * sizeof(primjac->i));
      primjac->x = (double*)realloc(primjac->x, nnz * sizeof(double));
    }

    /*  Update the size */
    csc_size(primjac, M->m, M->n, nnz);

    break;
  }
  default:
    numerics_error_nonfatal("evaluate_jacobian", "Unsupported matrix storage type %d\n", AVI->M->storageType);
    return -1;
  }

  return 0;
}

static int pathavi_get_jacobian_nnz(struct vi_desc *desc, int *nnz)
{
  SN_generic_pathvi_env* env = (SN_generic_pathvi_env*)vi_desc_get_controller(desc);
  *nnz = (int)NM_nnz(((AffineVariationalInequalities*) env->problem)->M);
  return 0;
}

static int pathavi_get_jacobian_structure(struct vi_desc *desc, struct csc_matrix *primjac)
{
  SN_generic_pathvi_env* env = (SN_generic_pathvi_env*)vi_desc_get_controller(desc);
  NumericsMatrix *M = ((AffineVariationalInequalities*) env->problem)->M;

  CSparseMatrix* Mcsc = NM_csc(M);

  if ((primjac->struct_mask & CSC_STRUCT_FIXED) &&
      !(primjac->struct_mask & CSC_STRUCT_FILLED)) {
    for (size_t i = 0; i <= env->n; ++i) {
      primjac->j[i] = Mcsc->p[i];
    }

    for (size_t i = 0; i < Mcsc->p[env->n]; ++i) {
      primjac->i[i] = Mcsc->i[i];
    }

    csc_size(primjac, env->n, env->n, Mcsc->p[env->n]);
    primjac->struct_mask |= CSC_STRUCT_FILLED;
  }

  return 0;
}

int avi_pathavi(AffineVariationalInequalities* problem, double *z, double *w, SolverOptions* options)
{
  int info = 0;
  bool use_scheduler = false;

  int nb_cstr = 0;
  int nnz_H = 0;
  double* lambda = NULL;

  if (problem->poly.set->id == SICONOS_SET_POLYHEDRON_UNIFIED)
  {
    nb_cstr = problem->poly.unif->A->size0;
    nnz_H = (int)NM_nnz(problem->poly.unif->A);
    lambda = (double*) calloc(nb_cstr, sizeof(double));
  }
  else
  {
    numerics_error_nonfatal("avi_pathavi", "unsupported set type %d", problem->poly.set->id);
    return -1;
  }

  SN_generic_pathvi_env env = {
    .problem = problem,
    .n = problem->size,
    .m = nb_cstr,
    .z = z,
    .F = w,
    .lambda = lambda
  };

  struct vi_desc_operations vi_ops = {
    .get_row_name           = &pathvi_get_row_name,
    .get_col_name           = &pathvi_get_col_name,
    .get_primvar            = &pathvi_get_z,
    .set_primvar            = &pathvi_set_z,
    .get_prim_marginal      = &pathvi_get_F,
    .set_prim_marginal      = &pathvi_set_F,
    .get_dualvar            = &pathvi_get_lambda,
    .set_dualvar            = &pathvi_set_lambda,
    .evaluate_function      = &pathvi_evaluate_function,
    .evaluate_jacobian      = &pathvi_evaluate_jacobian,
    .get_jacobian_nnz       = &pathavi_get_jacobian_nnz,
    .get_jacobian_structure = &pathavi_get_jacobian_structure
  };

  struct printv_operations printv_ops = {
    .print       = &pathvi_print
  };

  set_printv_operations(&printv_ops);

  struct vi_desc * pathvi_obj = vi_desc_create(nb_cstr, problem->size, NM_nnz(problem->M), nnz_H, &env, &vi_ops);
  pathvi_obj->nlflag = 0;

  if (problem->lb)
  {
    memcpy(pathvi_obj->primlower, problem->lb, env.n*sizeof(double));
  }
  else
  {
    for (size_t i = 0; i < env.n; ++i) pathvi_obj->primlower[i] = -INF;
  }

  if (problem->ub)
  {
    memcpy(pathvi_obj->primupper, problem->ub, env.n*sizeof(double));
  }
  else
  {
    for (size_t i = 0; i < env.n; ++i) pathvi_obj->primupper[i] = INF;
  }

  if (problem->poly.set)
  {
    if (problem->poly.set->id == SICONOS_SET_POLYHEDRON_UNIFIED)
    {
      polyhedron_unified* p = problem->poly.unif;
      pathvi_csc_transfert(pathvi_obj->A, NM_csc(p->A));

      memcpy(pathvi_obj->b, p->b, env.m*sizeof(double));

      for (size_t i = 0; i < env.m; ++i)
      {
        switch (p->type[i])
        {
        case SICONOS_LE:
        {
          pathvi_obj->sense[i] = 'L';
          pathvi_obj->duallower[i] = -INF;
          pathvi_obj->dualupper[i] = 0.;
          break;
        }
        case SICONOS_EQ:
        {
          pathvi_obj->sense[i] = 'E';
          pathvi_obj->duallower[i] = -INF;
          pathvi_obj->dualupper[i] = INF;
          break;
        }
        case SICONOS_GE:
        {
          pathvi_obj->sense[i] = 'G';
          pathvi_obj->duallower[i] = 0.;
          pathvi_obj->dualupper[i] = INF;
          break;
        }
        default:
        {
          numerics_error_nonfatal("avi_pathavi", "unsupported constraint type %c", p->type[i]);
          info = EINVAL;
          goto _exit;
        }
        }
      }

      // We should not do this
      csc_transpose(pathvi_obj->negAt, pathvi_obj->A);
      csc_negate(pathvi_obj->negAt);
    }
    else
    {
      numerics_error_nonfatal("avi_pathavi", "unsupported set type %d", problem->poly.set->id);
      return -1;
    }

  }

  // bug youngdae
  pathvi_register_options(pathvi_obj->opt);

  option_set_d(pathvi_obj->opt, "convergence_tolerance", options->dparam[0]);

  // Solve the problem
  if (use_scheduler)
  {
    struct vi_scheduler *sched = vi_scheduler_create(VI_SOLVER_PATHVI, pathvi_obj);
    int sinfo = vi_scheduler_run(sched);
    info = vi_scheduler_get_status(sched);
    vi_scheduler_free(&sched);
  }
  else
  {
    struct vi_solver *avi = vi_solver_create(VI_SOLVER_PATHVI, pathvi_obj);
    int sinfo = avi->ops->solve(avi);
    info = avi->status;
    vi_solver_free(&avi);
  }

_exit:

  return info;
}

#else

int avi_pathavi(AffineVariationalInequalities* problem, double *z, double *w, SolverOptions* options)
{
  numerics_error_nonfatal("avi_pathavi", "PATHVI not enabled");
  return -1;
}

#endif /*  HAVE_PATHVI */


text:
'''Provider for standard io_operations, intended for use by Handlers.'''

import os
import shutil
import zipfile

class IOProvider():
    '''State and Behavior supporting IO operations.'''
    def __init__(self, input_path, output_path):
        ''' Initializes the IO Provider.

        Keywords:
        input_path: String representation of path on disk where docs reside.
        output_path: String representation of path on disk where docsite should be placed.
        '''
        self.__base_output_path = output_path
        self.__base_input_path = input_path
        return

    def peek(self, document):
        '''Gets the first ten lines of a document,
           either from disk or from cache if previously peeked.
        '''
        # avoid duplicate file peeks
        if hasattr(document, "peek_buffer"):
            return document.peek_buffer
        else:
            try:
                with open(self.__doc_source_path(document)) as file:
                    buff = ""
                    count = 0
                    for line in file:
                        buff += line
                        count += 1
                        if count > 10:
                            break
                    document.peek_buffer = buff
            except UnicodeDecodeError:
                document.peek_buffer = ""
        return document.peek_buffer

    def read(self, document):
        '''Reads a document.
           Caching because documents may be read again by indexer
        '''
        if hasattr(document, "read_buffer"):
            return document.read_buffer
        else:
            document.read_buffer = self.__read_unicode_file(document)
        return document.read_buffer

    def copy_file(self, source_path, dest_path, relative=True):
        '''Copies a file from source to destination.
           If relative is True or unspecified, the root source & dest paths are prepended.
        '''
        if relative:
            rel_source = os.path.join(self.__base_input_path, source_path)
            rel_dest = os.path.join(self.__base_output_path, dest_path)
            shutil.copyfile(rel_source, rel_dest)
        else:
            shutil.copyfile(source_path, dest_path)
        return

    def copy_directory(self, source_path, dest_path, relative=True):
        '''Copies a directory from source to destination.
           If relative is True or unspecified, the root source & dest paths are prepended.
        '''
        if relative:
            source_path = os.path.join(self.__base_input_path, source_path)
            dest_path = os.path.join(self.__base_output_path, dest_path)
        if not os.path.exists(dest_path):
            os.makedirs(dest_path)
            shutil.copystat(source_path, dest_path)
        entitities = os.listdir(source_path)
        for entity in entitities:
            source = os.path.join(source_path, entity)
            destination = os.path.join(dest_path, entity)
            if os.path.isdir(source):
                self.copy_directory(source, destination, relative)
            else:
                shutil.copy2(source, destination)
        return
    def zip_directory(self, document):
        '''
        Writes a zip file containing files from source directory
        'zipname' should be set in document.data
        document is assumed to be a directory
        '''
        zipname = ""
        if 'zipname' in document.data:
            zipname = document.data['zipname']
        else:
            zipname = "output"
        source = self.__doc_source_path(document)
        output = os.path.join(self.__base_output_path, document.get_file_name(name=True,path=True))
        output = os.path.join(output, zipname)
        shutil.make_archive(output, 'zip', source)

    def write_blob(self, blob, dest_path, relative=True):
        '''Writes an object to the destination path, either binary or text as appropriate.
           If relative is True or unspecified, the site's bases output path is prepended to path.
        '''
        if relative:
            dest_path = os.path.join(self.__base_output_path, dest_path)
        if not os.path.exists(os.path.dirname(dest_path)):
            os.makedirs(os.path.dirname(dest_path))
        if isinstance(blob, str):
            with open(dest_path, 'w+') as handle:
                handle.write(blob)
        else:
            with open(dest_path, 'wb+') as handle:
                handle.write(blob)
        return

    def get_static_dir(self):
        ''' returns absolute path of static output directory'''
        return os.path.join(self.__base_output_path, "static")

    def get_base_output_path(self):
        return self.__base_output_path

    def get_doc_size(self, document):
        '''Returns the size of the input file for a particular document'''
        if len(document.children) > 0:
            return 0 # ignore directories
        return os.stat(self.__doc_source_path(document)).st_size

    def __read_binary_file(self, document):
        with open(self.__doc_source_path(document), 'rb') as handle:
            blob = handle.read()
        return blob

    def __read_unicode_file(self, document):
        try:
            with open(self.__doc_source_path(document), 'r') as handle:
                doc_string = handle.read()
                doc_string = ''.join(doc_string.splitlines(True)) # fix for Windows Newline
        except UnicodeDecodeError: # fall back to binary on failure
            return self.__read_binary_file(document)
        return doc_string

    def __doc_source_path(self, document):
        return os.path.join(self.__base_input_path, document.get_file_name(name=True,path=True))

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>WriteBasicConfigVersionFile — CMake 3.3.2 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.3.2 Documentation" href="../index.html" />
    <link rel="up" title="cmake-modules(7)" href="../manual/cmake-modules.7.html" />
    <link rel="next" title="WriteCompilerDetectionHeader" href="WriteCompilerDetectionHeader.html" />
    <link rel="prev" title="Use_wxWindows" href="Use_wxWindows.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.3.2 Documentation »

cmake-modules(7) »

WriteBasicConfigVersionFile¶

WRITE_BASIC_CONFIG_VERSION_FILE( filename
  [VERSION major.minor.patch]
  COMPATIBILITY (AnyNewerVersion|SameMajorVersion)
  )

Deprecated, see WRITE_BASIC_PACKAGE_VERSION_FILE(), it is identical.

Previous topic

Use_wxWindows

Next topic

WriteCompilerDetectionHeader

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.3.2 Documentation »

cmake-modules(7) »

        © Copyright 2000-2015 Kitware, Inc..
      Created using Sphinx 1.4a0+.


text:
"""The user service is a simple user storage which allows users to
authenticate. This is currently a dummy implementation with ony in-memory
storage.

Similar to store.py but uses more of the REST framework."""
import hashlib
import uuid
from datetime import timedelta
import sys
import logging
import paste.urlmap
from wsgiservice import Resource, mount, validate, expires, raise_201, get_app

def get_hashed(password):
    SALT = 'some_pwd_salt'
    return hashlib.sha1(SALT + password).hexdigest()

logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)

users = {}

@mount('/{id}')
@validate('id', re=r'[-0-9a-zA-Z]{36}', doc='User ID, must be a valid UUID.')
class User(Resource):
    NOT_FOUND = (KeyError,)

    @expires(timedelta(days=1))
    def GET(self, id):
        "Return the document indicated by the ID."
        return users[id]

    @validate('email', doc="User's email. This is the unique identifier of a user.")
    @validate('password', doc="User's password.")
    def PUT(self, id, email=None, password=None):
        """Overwrite or create the document indicated by the ID. Parameters
        are passed as key/value pairs in the POST data."""
        users.setdefault(id, {'id': id})
        if email:
            users[id]['email'] = email
        if password:
            users[id]['password'] = get_hashed(password)
        return {'id': id, 'saved': True}

    def DELETE(self, id):
        "Delete the document indicated by the ID."
        del users[id]
        return {'id': id, 'deleted': True}

    def to_text_xml(self, retval):
        if isinstance(retval, dict) and 'saved' in retval:
            return '<status saved="{0}"><id>{1}</id></status>'.format(
                retval['saved'], retval['id'])
        elif isinstance(retval, dict) and 'deleted' in retval:
            return '<status deleted="{0}"><id>{1}</id></status>'.format(
                retval['deleted'], retval['id'])
        else:
            return Resource.to_text_xml(self, retval)

@mount('/')
class Users(Resource):
    @validate('email', doc="User's email. This is the unique identifier of a user.")
    @validate('password', doc="User's password.")
    def POST(self, email, password):
        """Create a new document, assigning a unique ID. Parameters are
        passed in as key/value pairs in the POST data."""
        id = str(uuid.uuid4())
        res = self.get_resource(User)
        self.response.body_raw = res.PUT(id, email, password)
        raise_201(self, id)

@mount('/auth/{email}')
@validate('email', doc="User's email. This is the unique identifier of a user.")
@validate('password', doc="User's password.")
class UserEmailView(Resource):
    """Authenticate users."""
    @expires(timedelta(hours=4))
    def POST(self, email, password, request):
        """Checks if the given user/password combination is correct. Returns
        the user hash if successful, returns False otherwise."""
        the_user = self.getUser(email)
        if the_user and the_user.get('password', '') == get_hashed(password):
            return users
        else:
            return False

    def getUser(self, email):
        """Returns the user with the given email address."""
        for u in users:
            if email == users[u].get('email'):
                return users[u]
        return None

userapp = get_app(globals())

app = paste.urlmap.URLMap()
app['/1'] = userapp

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    print "Running on port 8000"
    make_server('', 8000, app).serve_forever()


text:
namespace shell {

class PlatformViewIOS final : public HeadlessPlatformViewIOS {
 public:
  explicit PlatformViewIOS(PlatformView::Delegate& delegate,
                           blink::TaskRunners task_runners,
                           FlutterViewController* owner_controller_,
                           FlutterView* owner_view_);

  ~PlatformViewIOS() override;

  FlutterViewController* GetOwnerViewController() const;

  void RegisterExternalTexture(int64_t id, NSObject<FlutterTexture>* texture);

  fml::scoped_nsprotocol<FlutterTextInputPlugin*> GetTextInputPlugin() const;

  void SetTextInputPlugin(
      fml::scoped_nsprotocol<FlutterTextInputPlugin*> plugin);

 private:
  FlutterViewController* owner_controller_;  // weak reference.
  FlutterView* owner_view_;                  // weak reference.
  std::unique_ptr<IOSSurface> ios_surface_;
  PlatformMessageRouter platform_message_router_;
  std::unique_ptr<AccessibilityBridge> accessibility_bridge_;
  fml::scoped_nsprotocol<FlutterTextInputPlugin*> text_input_plugin_;
  fml::closure firstFrameCallback_;

  // |shell::PlatformView|
  std::unique_ptr<Surface> CreateRenderingSurface() override;

  // |shell::PlatformView|
  sk_sp<GrContext> CreateResourceContext() const override;

  // |shell::PlatformView|
  void SetSemanticsEnabled(bool enabled) override;

  // |shell::PlatformView|
  void SetAccessibilityFeatures(int32_t flags) override;

  // |shell::PlatformView|
  void UpdateSemantics(
      blink::SemanticsNodeUpdates update,
      blink::CustomAccessibilityActionUpdates actions) override;

  // |shell::PlatformView|
  std::unique_ptr<VsyncWaiter> CreateVSyncWaiter() override;

  FML_DISALLOW_COPY_AND_ASSIGN(PlatformViewIOS);
};

}  // namespace shell

#endif  // SHELL_PLATFORM_IOS_PLATFORM_VIEW_IOS_H_


text:
/*global brackets, define */

define(function (require, exports, module) {
    "use strict";

    var PREFERENCES_KEY     = "brackets-snippets",
        _                   = brackets.getModule("thirdparty/lodash"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager"),
        prefs               = PreferencesManager.getExtensionPrefs(PREFERENCES_KEY);

    var defaultPreferences = {
        "autoBackupTime": {
            "type": "integer", "value": 10
        },
    };

    _.each(defaultPreferences, function (definition, key) {
        if (definition.os && definition.os[brackets.platform]) {
            prefs.definePreference(key, definition.type, definition.os[brackets.platform].value);
        } else {
            prefs.definePreference(key, definition.type, definition.value);
        }
    });
    prefs.save();

    prefs.getAll = function () {
        var obj = {};
        _.each(defaultPreferences, function (definition, key) {
            obj[key] = this.get(key);
        }, this);
        return obj;
    };

    prefs.getDefaults = function () {
        var obj = {};
        _.each(defaultPreferences, function (definition, key) {
            var defaultValue;
            if (definition.os && definition.os[brackets.platform]) {
                defaultValue = definition.os[brackets.platform].value;
            } else {
                defaultValue = definition.value;
            }
            obj[key] = defaultValue;
        }, this);
        return obj;
    };

    prefs.persist = function (key, value) {
        this.set(key, value);
        this.save();
    };

    module.exports = prefs;
});


text:
set -e
set -x
rm -rf /tmp/asd
coverage run --parallel-mode --include="*shutit*" $(which shutit) skeleton \
	--shutitfiles Dockerfile1 \
	--name /tmp/asd \
	--domain shutit.tk \
	--delivery bash \
	--pattern bash
pushd /tmp/asd
./run.sh "$@"
popd


text:
ModMusic::ModMusic()
    : module_(NULL), player_(NULL)
{}

ModMusic::~ModMusic()
{
    close();
    dumb_exit();
}

bool ModMusic::openFromMemory(const char *data, long size)
{
    close();
    module_ = dumb_read_xm_quick(dumbfile_open_memory(data, size));

    if (module_ != NULL)
    {
        initialize(NB_CHANNELS, SAMPLING_RATE);
        return true;
    }

    return false;
}

sf::Time ModMusic::getDuration() const
{
    return sf::seconds(static_cast<float>(duh_get_length(module_) / SAMPLES_PER_SEC));
}

void ModMusic::close()
{
    if (player_ != NULL)
    {
        duh_end_sigrenderer(player_);
        player_ = NULL;
    }
    if (module_ != NULL)
    {
        unload_duh(module_);
        module_ = NULL;
    }
}

void ModMusic::onSeek(sf::Time time_offset)
{
    long position = static_cast<long>(time_offset.asSeconds() * SAMPLES_PER_SEC);
    player_ = duh_start_sigrenderer(module_, 0, NB_CHANNELS, position);
}

bool ModMusic::onGetData(Chunk &data)
{
    float delta = float(SAMPLES_PER_SEC) / SAMPLING_RATE;

    duh_render(player_, 16, 0, 1.0f, delta, BUFFER_SIZE / 2, samples_);

    data.samples = samples_;
    data.sampleCount = BUFFER_SIZE;
    return true;
}


text:
package consul_test

import (
	"errors"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/hashicorp/consul/api"
	"github.com/stretchr/testify/assert"
	"github.com/stripe/veneur/v14/discovery/consul"
)

type ConsulRoundTripper struct {
	HealthGotCalled bool
	Response        string
}

func (roundTripper *ConsulRoundTripper) RoundTrip(
	request *http.Request,
) (*http.Response, error) {
	if request.URL.Path != "/v1/health/service/service-name" {
		return nil, errors.New("invalid request path")
	}

	response, err := ioutil.ReadFile(roundTripper.Response)
	if err != nil {
		return nil, err
	}

	recorder := httptest.NewRecorder()
	recorder.Write(response)
	recorder.Code = http.StatusOK
	roundTripper.HealthGotCalled = true

	return recorder.Result(), nil
}

func TestConsulZeroHosts(t *testing.T) {
	roundTripper := &ConsulRoundTripper{
		Response: "testdata/health_service_zero.json",
	}
	config := api.DefaultConfig()
	config.HttpClient = &http.Client{
		Transport: roundTripper,
	}
	client, err := consul.NewConsul(config)
	assert.NoError(t, err)

	_, err = client.GetDestinationsForService("service-name")
	if assert.Error(t, err) {
		assert.Equal(t, "received no hosts from Consul", err.Error())
	}
}

func TestConsulOneHost(t *testing.T) {
	roundTripper := &ConsulRoundTripper{
		Response: "testdata/health_service_one.json",
	}
	config := api.DefaultConfig()
	config.HttpClient = &http.Client{
		Transport: roundTripper,
	}
	client, err := consul.NewConsul(config)
	assert.NoError(t, err)

	destinations, err := client.GetDestinationsForService("service-name")
	assert.NoError(t, err)

	assert.True(t, roundTripper.HealthGotCalled)
	if assert.Len(t, destinations, 1) {
		assert.Equal(t, "10.1.10.12:8000", destinations[0])
	}
}

func TestConsulTwoHosts(t *testing.T) {
	roundTripper := &ConsulRoundTripper{
		Response: "testdata/health_service_two.json",
	}
	config := api.DefaultConfig()
	config.HttpClient = &http.Client{
		Transport: roundTripper,
	}
	client, err := consul.NewConsul(config)
	assert.NoError(t, err)

	destinations, err := client.GetDestinationsForService("service-name")
	assert.NoError(t, err)

	assert.True(t, roundTripper.HealthGotCalled)
	if assert.Len(t, destinations, 2) {
		assert.Equal(t, "10.1.10.12:8000", destinations[0])
		assert.Equal(t, "10.1.10.13:8000", destinations[1])
	}
}


text:
layout: page
title: Hannah Harmon's 58th Birthday
date: 2016-05-24
author: Robert Schmidt
tags: weekly links, java
status: published
summary: Praesent luctus molestie nunc, sit amet dictum.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 10/15/2016
  endDate: 10/18/2016
  ctyhocn: HILSCHX
  groupCode: HH5B
published: true
---
Nulla dictum ultricies ante. Pellentesque congue egestas rutrum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent dapibus accumsan aliquet. Nunc odio ex, porta non lobortis sodales, tincidunt sed arcu. Ut sodales tellus tortor, eget pharetra dolor congue in. In et justo lobortis tellus gravida finibus sit amet nec elit. Proin ipsum enim, mollis sed congue nec, bibendum quis sem. Vivamus faucibus, dolor fermentum aliquet pretium, sem odio vestibulum est, ac convallis nisi tortor vel erat. Nam rutrum iaculis lectus, non bibendum urna sodales at. Donec vitae dolor eget sem aliquet rhoncus non non augue. Duis justo nunc, varius ut sapien vel, posuere sodales diam. Nulla facilisi.
Nunc viverra augue at augue placerat finibus. Nam commodo sit amet ex eget pretium. Curabitur eget lacus rutrum quam eleifend lacinia nec at ipsum. Vivamus sollicitudin mattis ex ac consectetur. Donec quis ullamcorper felis. Proin at ipsum at dui aliquet semper sed non ante. Fusce diam nibh, rutrum nec bibendum vel, consectetur sed ante.

* Maecenas non quam commodo, ornare nibh non, condimentum nulla
* Curabitur sed massa sit amet magna sagittis tincidunt.

Nunc tempor, mauris vel condimentum scelerisque, tellus tellus convallis erat, eu aliquet augue lorem id sapien. Praesent nec egestas lorem, at bibendum est. Nulla facilisi. Cras elementum erat nec nisl vehicula, in sagittis sapien sagittis. Aliquam dictum, lacus sit amet posuere bibendum, ligula velit efficitur nisi, quis luctus ante sapien non metus. Cras pretium non leo sed commodo. Vestibulum pharetra eros mi, non consequat nisl vestibulum in.


text:
namespace sc2 {

bool TestSnapshots(int argc, char** argv);

}


text:
package org.training.equals.example02;

/**
 * Please read the contract of {@link Object#equals(Object)} (link below) to
 * understand what that method is doing by default
 *
 * @author nikelblue
 * @see Object#equals(Object)
 * @see http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals%28java.lang.Object%29
 */
public class PointTest {

	public static void main(String[] args) {
		Point p1 = new Point(1,2);
		Point p2 = p1; //p2 is same instance as p1
		Point p3 = new Point(1,2);

		//Operator == returns 'true' only if both 'points' are same instance.
		System.out.printf("p1 == p2: %s\n", p1 == p2);
		//equals still returns true if both points are same instance, which means
		//we didn't break the initial behavior
		System.out.printf("p1.equals(p2): %s\n", p1.equals(p2));

		//They are not same instance (p3 has been created again with new)
		System.out.printf("p1 == p3: %s\n", p1 == p3);
		//This time equals is smarter and checks if both points coordinates are the same
		System.out.printf("p1.equals(p3): %s\n", p1.equals(p3));
	}

}


text:
package blade.migrate.liferay70;

import blade.migrate.api.FileMigrator;
import blade.migrate.core.JavaFileChecker;
import blade.migrate.core.JavaFileMigrator;
import blade.migrate.core.SearchResult;

import java.io.File;
import java.util.List;

import org.osgi.service.component.annotations.Component;

@Component(
	property = {
		"file.extensions=java,jsp,jspf",
		"problem.summary=All Social Networking APIs previously exposed as Liferay Portal API in 6.2 have been move out from portal-service into separate OSGi modules",
		"problem.tickets=LPS-50752",
		"problem.title=Social Networking APIs migrated to OSGi module",
		"problem.url="
	},
	service = FileMigrator.class
)
public class SocialNetworkingLegacyAPI extends JavaFileMigrator {

	private static final String[] SERVICE_API_PREFIXES =  {
		"com.liferay.socialnetworking.service.MeetupsEntry",
		"com.liferay.socialnetworking.service.MeetupsRegistration",
		"com.liferay.socialnetworking.service.WallEntry",

	};

	@Override
	protected List<SearchResult> searchJavaFile(File file, JavaFileChecker javaFileChecker) {
		return javaFileChecker.findServiceAPIs(SERVICE_API_PREFIXES);
	}
}


text:
/**
 *
 */
package fr.utbm.to52.smarthome.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Basic static function for IO
 * @author Alexandre Guyon
 *
 */
public class BasicIO {

	/**
	 * Read a file passed on argument
	 * @param file The file to read
	 * @return String of the file
	 */
	public static String readFile(String file){
		File f = new File(file);
		String content = "";

		if(f.exists() && f.canRead()){
			try {
				content = readBufferedReader(new BufferedReader(new FileReader(f)));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return content;
	}

	/**
	 * Read input stream
	 * @param is The input stream to read
	 * @return String corresponding to the stream
	 */
	public static String readInputStream(InputStream is){
		return readInputStreamReader(new InputStreamReader(is));
	}

	/**
	 * Read input stream
	 * @param is The input stream reader to read
	 * @return String corresponding to the stream
	 */
	public static String readInputStreamReader(InputStreamReader is){
		return readBufferedReader(new BufferedReader(is));
	}

	/**
	 * Read buffered reader
	 * @param reader The buffered reader reader to read
	 * @return String corresponding to the stream
	 */
	public static String readBufferedReader(BufferedReader reader){
		String content = "";
		try{
			String line = null;
			do{
				line = reader.readLine();
				if(line != null)
					content += line;
			}while(line != null);
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * Get string from inputstream
	 * @param is InputStream to read
	 * @return String from inputstream
	 */
	public static String getStringFromInput(InputStream is) {
		String content = readInputStream(is);
		try {
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * Write content to a file
	 * @param path The path to the file
	 * @param content The content to write
	 */
	public static void write(String path, String content){
		try {

			FileWriter fw = new FileWriter(path);
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.flush();
			fw.flush();
			bw.close();
			fw.close();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}


text:
var envelope_Module_Factory = function () {
  var envelope = {
    name: 'envelope',
    defaultElementNamespaceURI: 'http:\/\/schemas.xmlsoap.org\/soap\/envelope\/',
    typeInfos: [{
        localName: 'Fault',
        propertyInfos: [{
            name: 'faultcode',
            required: true,
            elementName: {
              localPart: 'faultcode'
            },
            typeInfo: 'QName'
          }, {
            name: 'faultstring',
            required: true,
            elementName: {
              localPart: 'faultstring'
            }
          }, {
            name: 'faultactor',
            elementName: {
              localPart: 'faultactor'
            }
          }, {
            name: 'detail',
            elementName: {
              localPart: 'detail'
            },
            typeInfo: '.Detail'
          }]
      }, {
        localName: 'Detail',
        typeName: 'detail',
        propertyInfos: [{
            name: 'otherAttributes',
            type: 'anyAttribute'
          }, {
            name: 'any',
            minOccurs: 0,
            collection: true,
            mixed: false,
            type: 'anyElement'
          }]
      }, {
        localName: 'Body',
        propertyInfos: [{
            name: 'otherAttributes',
            type: 'anyAttribute'
          }, {
            name: 'any',
            minOccurs: 0,
            collection: true,
            mixed: false,
            type: 'anyElement'
          }]
      }, {
        localName: 'Header',
        propertyInfos: [{
            name: 'otherAttributes',
            type: 'anyAttribute'
          }, {
            name: 'any',
            minOccurs: 0,
            collection: true,
            mixed: false,
            type: 'anyElement'
          }]
      }, {
        localName: 'Envelope',
        propertyInfos: [{
            name: 'otherAttributes',
            type: 'anyAttribute'
          }, {
            name: 'header',
            elementName: 'Header',
            typeInfo: '.Header'
          }, {
            name: 'body',
            required: true,
            elementName: 'Body',
            typeInfo: '.Body'
          }, {
            name: 'any',
            minOccurs: 0,
            collection: true,
            mixed: false,
            type: 'anyElement'
          }]
      }],
    elementInfos: [{
        typeInfo: '.Body',
        elementName: 'Body'
      }, {
        typeInfo: '.Header',
        elementName: 'Header'
      }, {
        typeInfo: '.Envelope',
        elementName: 'Envelope'
      }, {
        typeInfo: '.Fault',
        elementName: 'Fault'
      }]
  };
  return {
    envelope: envelope
  };
};
if (typeof define === 'function' && define.amd) {
  define([], envelope_Module_Factory);
}
else {
  var envelope_Module = envelope_Module_Factory();
  if (typeof module !== 'undefined' && module.exports) {
    module.exports.envelope = envelope_Module.envelope;
  }
  else {
    var envelope = envelope_Module.envelope;
  }
}


text:
This data model demonstrate the following:

- Providing the minimum model definitions to generate data
- Using the `document_index` variable

There is 1 type of model that will be generated

- [Users](#users)

##### users

```json
{
  "id": "user_0",
  "type": "user",
  "user_id": 0,
  "first_name": "Alia",
  "last_name": "Lesch",
  "email_address": "Trevion39@yahoo.com",
  "phone": "(831) 627-7628",
  "active": true,
  "created_on": "2016-04-05T19:46:56.000Z"
}
```

### Usage Examples

Below is a variety of commands that can be used on this data model, all of the examples assume that you are in the `simple/` directory:

Generate JSON files and output them to a `output/` directory

```bash
[simple]$ fakeit directory output models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 0.json
```

---

Generate YAML files and output them to a `output/` directory

```bash
[simple]$ fakeit directory --format yaml output models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 0.yaml
```

---

Generate CSON files and output them to a `output/` directory

```bash
[simple]$ fakeit directory --format cson output models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 0.cson
```

---

Generate a single JSON document and output it to the console

```bash
[simple]$ fakeit console --count 1 models/*
{
  "id": "user_0",
  "type": "user",
  "user_id": 0,
  "first_name": "Robb",
  "last_name": "McGlynn",
  "email_address": "Gage90@hotmail.com",
  "phone": "(223) 615-9090",
  "active": false,
  "created_on": "2016-03-30T00:34:01.000Z"
}
```

---

Generate JSON files, save them to a zip archive named `export.zip` and output the zip file to the output directory

```bash
[simple]$ fakeit directory --format json output/export.zip models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 export.zip
```

---

Generate a CSV file for the simple model and save it to the output directory

```bash
[simple]$ fakeit directory --format csv output models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 Users.csv
```

---

Generate a CSV file for the simple model and save it to a zip archived named `export.zip` and output the zip file to the output directory

```bash
[simple]$ fakeit directory --format csv output/export.zip models/*
[simple]$ ls output | awk '{print "\011",$NF}'
	 export.zip
```

---

Generate JSON documents and output them to a Couchbase Server using the defaults of a server running at `127.0.0.1` in the bucket `default`

```bash
[simple]$ fakeit couchbase models/*
```

---

Generate JSON documents and output them to Couchbase Server running at `192.168.1.101` in the bucket `simple` with the password of `secret`

```bash
[simple]$ fakeit couchbase --server 192.168.1.101 --bucket simple --password secret models/*
```

---

Generate JSON documents and output them to a Couchbase Sync Gateway running at `localhost` into a `simple` bucket with guest access enabled.

```bash
[simple]$ fakeit sync-gateway --server http://localhost:4984 --bucket simple models/*
```

---

Generate JSON documents and output them to a Couchbase Sync Gateway running at `localhost:4984` into a `simple` bucket using [Custom (Indirect) Authentication](http://developer.couchbase.com/documentation/mobile/current/develop/guides/sync-gateway/administering-sync-gateway/authenticating-users/index.html).

```bash
[simple]$ fakeit sync-gateway --server http://localhost:4984 --bucket simple  --username jdoe --password supersecret models/*
```


text:
var express = require('express');
var app = express();

app.get('/launch', function (req, res) {
  var tube = req.query.tube;
  var date = new Date(Date.now());
  console.log('launch request received for: '+ tube + ' at '+ date);
  res.send('launched '+ tube);
});

app.listen(9999, function () {
  console.log('Test server listening on port 9999!');
});


text:
/**
 * @fileoverview Helper functions to reduce the amount of code directly typed
 * in the demo page.
 * @author battlehorse@google.com (Riccardo Govoni)
 */

/**
 * Global reference to an instance of the Editor class.
 * @type {Editor}
 */
var editor;

/**
 * Prepares the demo editor, loads all the necessary libraries,
 * loads the data to populate the demo and invokes a callback afterward.
 *
 * @param {Window} win The window containing the demo contents.
 * @param {Document} doc The document containing the demo contents.
 * @param {Function} callback The callback to invoke upon completion.
 */
function prepareDemo(win, doc, callback) {
  var jq = win.jQuery;
  var code = CodeMirror(doc.getElementById('code'), {
    mode: 'javascript',
    onKeyEvent: function(unused_code, evt) {
      if (evt.type == 'keydown' && evt.ctrlKey && (evt.keyCode == 98 || evt.keyCode == 66)) {
        // Ctrl-b pressed. Execute the current contents.
        jq('#execute').click();
        return true;
      }
    }
  });

  editor = new Editor(code, win, doc);

  jq('#execute').button().click(function() {
    jq('#errors').empty().hide();
    try {
      eval(code.getValue());
    } catch(err) {
      jq('#errors').html(String(err)).show();
    }
  });
  jq('#toggleSections').buttonset();
  jq('#toggleSectionCode').click(function() {
    jq('#demoArea').hide();
    jq('#codeArea').show().css('right', 0);
  });
  jq('#toggleSectionBoth').click(function() {
    jq('#codeArea').show().css('right', '450px');
    jq('#demoArea').show().css('left', '450px');
  });
  jq('#toggleSectionDemo').click(function() {
    jq('#codeArea').hide();
    jq('#demoArea').show().css('left', 0);
  });

  callback(editor, win, doc);
}

/**
 * Inject a stylesheet in a document.
 * @param {Document} doc The document where to inject the stylesheets.
 * @param {string} stylesheet The URL of the stylesheet to load.
 */
function injectStyle(doc, stylesheet) {
  var head = doc.getElementsByTagName('head')[0];
  var link = doc.createElement('link');
  link.setAttribute('rel', 'stylesheet');
  link.href = stylesheet;
  head.appendChild(link);
}

/**
 * Injects an additional library in the page (identified by srcFile) and invokes
 * a callback once injection completes.
 *
 * @param {Document} doc the Document where to inject the library.
 * @param {string} srcFile the library to load.
 * @param {Function} callback Function to invoke once the library has been
 *     loaded.
 */
function loadLibrary(doc, srcFile, callback) {
  var script = doc.createElement("script");
  script.src = srcFile;
  script.type = "text/javascript";
  script.executed = false;
  var head = doc.getElementsByTagName('head')[0];
  head.appendChild(script);
  script.onreadystatechange = function() {
    if (script.readyState == 'loaded' || script.readyState == 'complete') {
      if (!script.executed) {
        callback();
      }
    }
  };
  script.onload = function() {
    if (!script.executed) {
      script.executed = true;
      callback();
    }
  };
}

/**
 * Inject multiple additional libraries in the page, in the requested
 * order.
 *
 * @param {Document} doc the Document where to inject the libraries.
 * @param {Array.<string>} srcFiles The libraries to inject.
 * @param {Function} callback Function to invoke once all the libraries
 *     have been loaded.
 * @param {number} opt_count Counter to keep track of the libraries
 *     loaded so far.
 */
function loadLibraries(doc, srcFiles, callback, opt_count) {
  opt_count = opt_count || 0;
  if (opt_count == srcFiles.length) {
    callback();
  } else {
    loadLibrary(doc, srcFiles[opt_count], function() {
      loadLibraries(doc, srcFiles, callback, opt_count+1);
    });
  }
}

/**
 * Samples manager for the live Editor slide.
 * @constructor
 */
var Editor = function(code, win, doc) {
  this.code_ = code;
  this.win_ = win;
  this.$_ = this.win_.jQuery;
  this.doc_ = doc;

  this.shortcuts_ = {};
};

Editor.prototype.addShortCut = function(name, code, content) {
  var self = this;
  this.$_('<a />', {'href': '#'}).html(name).click(function() {
    if (typeof(code) != 'string') {
      code = self.$_(code).text();
    }
    self.code_.setValue(code);
    self.$_('#content').empty();
    if (content) {
      self.$_('#content').html(content.cloneNode(true));
    }
    self.$_('#execute').click();
    return false;
  }).appendTo(this.$_('#shortcuts'));
};

Editor.prototype.addShortCutFromFile = function(htmlFile) {
  var iframe = this.doc_.createElement('IFRAME');
  iframe.style.display = 'none';
  iframe.src = htmlFile;
  this.doc_.body.appendChild(iframe);
};


text:
layout: post
date: 2016-02-06 21:00:00 CET
title: How to use Hash#to_proc in Ruby?
tags: [Ruby]
comments: true
---

Hash#to_proc has been introduced in [Ruby 2.3.0 release](https://www.ruby-lang.org/en/news/2015/12/25/ruby-2-3-0-released/). I really like this method. It reminds obtaining a value from a HashMap in Clojure.

{% highlight clojure %}
=> ({:a 1} :a)
1
{% endhighlight %}

We simply "call" hash-map with `:a` keyword as a parameter to get the `:a`'s keyword value. Thanks to `Hash#to_proc` method, in Ruby now we can do almost the same thing.

{% highlight ruby %}
irb(main):001:0> {a: 1}.to_proc.call(:a)
=> 1
{% endhighlight %}

Of course for getting a value from hash it's much easier to use `#[]` but sometimes `#to_proc` is just as useful and allows you to simplify the code.
### Here's how I use it in wildlife

Let's say I'm not sure what the name of the key is, but what I really need to know is the value.

{% highlight ruby %}
irb(main):001:0> ENV.keys.grep(/shell/i).map(&ENV.to_hash)
=> ["/usr/local/opt/bash/bin/bash", "bash"]
irb(main):002:0> ENV.keys.grep(/shell/i)
=> ["SHELL", "RBENV_SHELL"]
{% endhighlight %}

Rails console using ActiveRecord::AttributeMethods#attributes method.

{% highlight ruby %}
[1] (main)> attrs = User.last.attributes
[2] (main)> attrs.keys.grep(/name/).map(&attrs)
=> ["Radek", "Molenda"]
{% endhighlight %}

Before Ruby 2.3.0 you would need to do something like that:

{% highlight ruby %}
[3] (main)> keys = attrs.keys.grep(/name/)
=> ["first_name", "last_name"]
[4] (main)> attrs.values_at(*keys)
=> ["Radek", "Molenda"]
{% endhighlight %}

Happy coding!


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

  <context:property-placeholder/>

  <bean id="containerWrapper"
        class="org.fcrepo.http.commons.test.util.ContainerWrapper"
        init-method="start" destroy-method="stop" p:port="${fcrepo.dynamic.test.port:8080}"
        p:configLocation="classpath:web.xml"/>

</beans>


text:
/*
 * mobile textinput unit tests
 */
(function($){
	module( "jquery.mobile.forms.textinput.js" );

	test( "inputs without type specified are enhanced", function(){
		ok( $( "#typeless-input" ).hasClass( "ui-input-text" ) );
	});

	$.mobile.page.prototype.options.keepNative = "textarea.should-be-native";

	// not testing the positive case here since's it's obviously tested elsewhere
	test( "textarea in the keepNative set shouldn't be enhanced", function() {
		ok( !$("textarea.should-be-native").is("ui-input-text") );
	});

	asyncTest( "textarea should autogrow on document ready", function() {
		var test = $( "#init-autogrow" );

		setTimeout(function() {
			ok( $( "#reference-autogrow" )[0].clientHeight < test[0].clientHeight, "the height is greater than the reference text area with no content" );
			ok( test[0].clientHeight > 100, "autogrow text area's height is greater than any style padding");
			start();
		}, 400);
	});

	asyncTest( "textarea should autogrow when text is added via the keyboard", function() {
		var test = $( "#keyup-autogrow" ),
			originalHeight = test[0].clientHeight;

		test.keyup(function() {
			setTimeout(function() {
				ok( test[0].clientHeight > originalHeight, "the height is greater than original with no content" );
				ok( test[0].clientHeight > 100, "autogrow text area's height is greater any style/padding");
				start();
			}, 400);
		});

		test.val("foo\n\n\n\n\n\n\n\n\n\n\n\n\n\n").trigger("keyup");
	});

	asyncTest( "text area should auto grow when the parent page is loaded via ajax", function() {
		$.testHelper.pageSequence([
			function() {
				$("#external").click();
			},

			function() {
				setTimeout(function() {
					ok($.mobile.activePage.find( "textarea" )[0].clientHeight > 100, "text area's height has grown");
					window.history.back();
				}, 1000);
			},

			function() {
				start();
			}
		]);
	});
})(jQuery);


text:
.. sidebar:: ToC

   .. contents::

.. _tutorial-basics:

Basics
------

Alphabets
~~~~~~~~~

In SeqAn, alphabets are value types that can take a limited number of values and which hence can be mapped to a range of natural numbers.
We can retrieve the number of different values of an alphabet, the alphabet size, by the metafunction :dox:`FiniteOrderedAlphabetConcept#ValueSize`.
Another useful metafunction called :dox:`AlphabetConcept#BitsPerValue` can be used to determine the number of bits needed to store a value of a given alphabet.
The order of a character in the alphabet (i.e. its corresponding natural number) can be retrieved by calling the function :dox:`FiniteOrderedAlphabetConcept#ordValue`.
In SeqAn, several standard alphabets are already predefined, for example :dox:`Dna` :dox:`Dna5`, :dox:`Rna`, :dox:`Rna5`, :dox:`Iupac`, :dox:`AminoAcid`, ....

Let's start with a simple task. We want to write a program that outputs all letters of the predefined :dox:`AminoAcid` alphabet.
First we include the corresponding header files and specify that we are using the namespace ``seqan``.

.. includefrags:: core/demos/tutorial/basics/show_alphabets.cpp
   :fragment: includes

Next, we will define a template function ``template<typename TAlphabet> void showAllLettersOfMyAlphabet(TAlphabet const&)`` which will iterate over all the characters of the alphabet and outputs them.
For this, we need to determine the alphabet size using the metafunction :dox:`FiniteOrderedAlphabetConcept#ValueSize ValueSize<TAlphabet>::VALUE`.
Then we increment a counter from 0 to the alphabet size minus one and output the counter as well as the corresponding letter of the alphabet using a conversion constructor.

.. includefrags:: core/demos/tutorial/basics/show_alphabets.cpp
   :fragment: showAllLettersOfMyAlphabet

In the main program we simply call the above function using a number of alphabets that are predefined in SeqAn.

.. includefrags:: core/demos/tutorial/basics/show_alphabets.cpp
   :fragment: main

This program produces the following output:

.. code-block:: console

     darwin10.0 : ./show_alphabets
    0,A  1,R  2,N  3,D  4,C  5,Q  6,E  7,G  8,H  9,I  10,L  11,K  12,M  13,F  14,P  15,S  16,T  17,W  18,Y  19,V  20,B  21,Z  22,X  23,*
    0,A  1,C  2,G  3,T
    0,A  1,C  2,G  3,T  4,N

Iterators
~~~~~~~~~

An iterator is an object that is used to browse through the values of a container.
The metafunction :dox:`ContainerConcept#Iterator` can be used to determine an appropriate iterator type given a container.
Some containers offer several kinds of iterators, which can be selected by an optional argument of Iterator.
For example, the tag :dox:`ContainerIteratorTags#Standard` can be used to get an iterator type that resembles the C++ standard random access iterator.
The more elaborated :dox:`RootedIteratorConcept Rooted\ Iterator`, i.e., an iterator that knows its container, can be selected by specifying the :dox:`ContainerIteratorTags#Rooted` tag.

Rooted iterators offer some convenience for the user: They offer additional functions like :dox:`RootedIteratorConcept#container` for determining the container on which the iterator works, and they simplify the interface for other functions like :dox:`RootedIteratorConcept#atEnd`.
Moreover, rooted iterators may change the container's length or capacity, which makes it possible to implement a more intuitive variant of a remove algorithm.

While rooted iterators can usually be converted into standard iterators, it is not always possible to convert standard iterators back into rooted iterators, since standard iterators may lack the information about the container they work on.
Therefore, many functions that return iterators like :dox:`ContainerConcept#begin` or :dox:`ContainerConcept#end` return rooted iterators instead of standard iterators; this way, they can be used to set both rooted and standard iterator variables.
Alternatively it is possible to specify the returned iterator type explicitly by passing the iterator kind as a tag argument.

The following code piece shows examples for creating Iterators for :dox:`ContainerConcept Containers`.
If no iterator kind is specified, the metafunction :dox:`ContainerConcept#Iterator` assumes :dox:`ContainerIteratorTags#Standard` and the function :dox:`ContainerConcept#begin` assumes :dox:`ContainerIteratorTags#Rooted`.
Both ``it1`` and ``it2`` are standard iterators, whereas ``it3`` and ``it4`` are rooted iterators.

.. code-block:: cpp

    String<char> str = "ACME";
    Iterator<String<char> >::Type it1 = begin(str); //a standard iterator
    Iterator<String<char>, Standard>::Type it2 = begin(str);  //same as above
    Iterator<String<char>, Rooted>::Type it3 = begin(str);  //a rooted iterator
    Iterator<String<char>, Rooted>::Type it4 = begin(str, Rooted());  //same as above

.. comment

    An iterator is stable if it stays valid even if its container is expanded, otherwise it is unstable. For example, the standard iterator of :dox:`AllocString` – which is a simple pointer to a value in the string – is unstable, since during the expansion of an Alloc String, all values are moved to new memory addresses.
    A typical implementation of stable iterators for strings stores the position instead of a pointer to the current value.
    The :dox:`Iterator` metafunction called with the [seqan:"Tag.Iterator Spec" Stable] tag returns a type for stable iterators.

    Stable tag does not appear in Doku. Clarify with Andreas.

Assignment 1
^^^^^^^^^^^^

.. container:: assignment

   Type
     Transfer

   Objective

      Write a program which does the following:
        #. Create an amino acid string of the following sequence: "MQDRVKRPMNAFIVWSRDQRRKMALEN".
        #. Iterate through the sequence and replace all 'R' with 'A'.
        #. Create a second string where you count the number of occurrences of each amino acid.
        #. Iterate through the latter string and output the frequency table.

   Hints

      After a few hours browsing through the demos you should be able to solve this.

   Solution

      .. container:: foldable

         In this assignment we practice the use of alphabets, iterators and metafunctions in SeqAn. We start by including the seqan basic header and enter the namespace ``seqan`` to avoid writing it as a prefix (as we do with the namespace ``std`` in this example).
         In the ``main`` function we first define a a type ``TAmincoAcidString`` which is a ``String<AminoAcid>`` (Note the SeqAn naming conventions).
         Then we define a variable ``sourceSeq`` of this type and initialize it with a string constant.

         .. comment

            Add link to naming conventions

         .. includefrags:: core/demos/tutorial/basics/strings.cpp
            :fragment: create-string

         Then we define an iterator type using the SeqAn metafunction :dox:`ContainerConcept#Iterator`.
         Using the correct iterator we iterate over our amino acid string using the SeqAn functions :dox:`ContainerConcept#begin`, :dox:`ContainerConcept#end`, and :dox:`InputIteratorConcept#goNext`.
         In the body of the while loop we use the SeqAn function :dox:`IteratorAssociatedTypesConcept#value` to access the value the iterator is pointing to.
         Note that this function returns a reference which allows us to replace the occurrence of all ``R``'s with ``A``'s.
         So at this point we have solved parts a) and b) of the assignment.

         .. includefrags:: core/demos/tutorial/basics/strings.cpp
            :fragment: iterate-and-replace

         In the next part of the code we want to count, how often a specific letter of the alphabet occurs in the string.
         To obtain the size type of the used alphabet we call the SeqAn metafunction :dox:`ContainerConcept#Size Size` and define a :dox:`String` of that type to hold the counters.
         The :dox:`String` has here basically the same functionality as a STL ``vector``.
         Since alphabets are mapped to a contiguous interval of the natural numbers, we can initialize the counter up to the size of the alphabet which we obtain by a call to the SeqAn metafunction :dox:`ContainerConcept#ValueSize ValueSize`.
         We then iterate over the amino acid string and increment the counter for the corresponding letter of the alphabet.
         In order to know the corresponding natural number of an alphabet letter, we use the SeqAn function :dox:`FiniteOrderedAlphabetConcept#ordValue`.
         Note the use of the :dox:`IteratorAssociatedTypesConcept#value` function.
         In this example one could also use the ``operator[]`` to write ``counter[ordValue(value(it))]++``.

         .. includefrags:: core/demos/tutorial/basics/strings.cpp
            :fragment: count-occurrences

         Finally we iterate through the counter String and output the i-th aminoacid (by calling a constructor with the letter's ordinal value) ad its frequency.

         .. includefrags:: core/demos/tutorial/basics/strings.cpp
            :fragment: frequency-table

         The result looks like this:

         .. code-block:: console

             $darwin10.0 : basics//strings
             M,Q,D,A,V,K,A,P,M,N,A,F,I,V,W,S,A,D,Q,A,A,K,M,A,L,E,N,
             A:7
             R:0
             N:2
             D:2
             C:0
             Q:2
             E:1
             G:0
             H:0
             I:1
             L:1
             K:2
             M:3
             F:1
             P:1
             S:1
             T:0
             W:1
             Y:0
             V:2
             B:0
             Z:0
             X:0
             *:0

Memory Allocation
~~~~~~~~~~~~~~~~~

Controlling memory allocation is one of the big advantages of C++ compared to other programming languages as for example Java.
Depending on the size of objects and the pattern they are allocated during the program execution, certain memory allocation strategies have advantages compared to others.
SeqAn supports a variety of memory allocation strategies.

The two functions :dox:`Allocator#allocate` and :dox:`Allocator#deallocate` are used in SeqAn to allocate and deallocate dynamic memory.
Both functions take an allocator as an argument.
An :dox:`Allocator` is an object that is responsible for allocated memory.
The default implementations of :dox:`Allocator#allocate` and :dox:`Allocator#deallocate` completely ignore the allocator but simply call the basic operators ``new`` and ``delete``.
Although in principle every kind of object can be used as allocator, typically the object that stores the pointer to the allocated memory is used as allocator.
For example, if memory is allocated for an :dox:`AllocString Alloc String`, this string itself acts as allocator.
A memory block should be deallocated using the same allocator object as it was allocated for.
The following allocators are available in SeqAn and support the :dox:`Allocator#clear` function.
This function deallocates at once all memory blocks that were previously
allocated.

| :dox:`SimpleAllocator Simple Allocator`
|    General purpose allocator.
| :dox:`SinglePoolAllocator Single Pool Allocator`
|    Allocator that pools memory blocks of specific size. Blocks of different sizes are not pooled.
| :dox:`MultiPoolAllocator Multi Pool Allocator`
|    Allocator that pools memory blocks. Only blocks up to a certain size are pooled. The user can specify the size limit in a template argument.

The function :dox:`Allocator#allocate` has an optional argument to specify the intended allocator usage for the requested memory.
The user can
thereby specialize :dox:`Allocator#allocate` for different allocator applications.
For example, the tag :dox:`AllocatorUsageTags#TagAllocateTemp` specifies that the memory will only be used temporarily, whereas :dox:`AllocatorUsageTags#TagAllocateStorage` indicates that the memory will be used in the long run for storing values of a container.

SeqAn also offers more complex allocators which support the function :dox:`Allocator#clear`.
The library predefines some allocator specializations for different uses (see above).
Most of these allocators are pool allocators.
A pool allocator implements its own memory management.
It reserves storage for multiple memory blocks at a time and recycles deallocated blocks.
This reduces the number of expensive ``new`` and ``delete`` calls and speeds up the allocation and deallocation.

Assignment 2
^^^^^^^^^^^^

.. container:: assignment

   Type
     Application

   Objective

      Write a program which compares the runtimes of the :dox:`SimpleAllocator Simple Allocator` and the :dox:`MultiPoolAllocator Multi Pool Allocator` for pool sizes (10,100,1000) for allocating and deallocating memory.

   Hint

      .. container:: foldable

         For timing the allocation you can use :dox:`sysTime`.

   Solution

      .. container:: foldable

         We start in this assignment by including the ``basic.h`` SeqAn header and defining two different allocators, one :dox:`MultiPoolAllocator Multi Pool Allocator` and one :dox:`SimpleAllocator Simple Allocator`.

         .. includefrags:: core/demos/tutorial/basics/allocator.cpp
            :fragment: definitions

         Given these fixed allocators we allocate now various size blocks, namely of size 10, 100, and 1000.
         We repeat the allocation a number of times and then clear the allocated memory.
         For each of the block sizes we output the system time needed to allocate and clear the memory.

         .. includefrags:: core/demos/tutorial/basics/allocator.cpp
            :fragment: time-measurements

         Running this program results in the following output which shows the advantage of the :dox:`MultiPoolAllocator Multi Pool Allocator`:

         .. code-block:: console

            $ darwin10.0 : cd ~/seqan/projects/library/demos/tutorial
            $ darwin10.0 : ./basics/allocator
            Allocating and clearing 100000 times blocks of size 10 with MultiPool Allocator took 0.00200295
            Allocating and clearing 100000 times blocks of size 10 with Standard Allocator took 0.0451179
            Allocating and clearing 100000 times blocks of size 100 with MultiPool Allocator took 0.0599239
            Allocating and clearing 100000 times blocks of size 100 with Standard Allocator took 0.127033
            Allocating and clearing 100000 times blocks of size 1000 with MultiPool Allocator took 0.368732
            Allocating and clearing 100000 times blocks of size 1000 with Standard Allocator took 0.560434


text:
import { Routes } from '@angular/router'

import { ViewContentComponent } from './view-content'
import { ViewCategoriesComponent } from './view-categories'
import { GalleryComponent } from '.'

export const routes: Routes = [
    {
        path: 'gallery', component: GalleryComponent, children: [
            { path: '', component: ViewCategoriesComponent },
            { path: 'view-content/:category', component: ViewContentComponent },
        ]
    }
];


text:
from __future__ import unicode_literals

from future.utils import itervalues

class SubscribeID(object):

    def __init__(self, subject, sid):
        self.subject = subject
        self.sid = sid

    def unsubscribe(self):
        self.subject.unsubscribe(self.sid)

class Subject(object):
    """Object presents subject of observer pattern

    """

    def __init__(self):
        self.observers = {}
        self._sn = 0

    def subscribe(self, observer):
        """Subscribe an observer to this subject and return a subscription id

        """
        sid = self._sn
        self.observers[sid] = observer
        self._sn += 1
        return SubscribeID(self, sid)

    def unsubscribe(self, sid):
        """Disconnect an observer from this subject

        """
        if sid not in self.observers:
            raise KeyError(
                'Cannot disconnect a observer does not connected to subject'
            )
        del self.observers[sid]

    def __call__(self, *args, **kwargs):
        """Notify all observers which observe this subject

        """
        for observer in list(itervalues(self.observers)):
            observer(*args, **kwargs)


text: Playing around with https://github.com/nicnocquee/appolo ✨