text:
var debug = require('debug')('carcass:fileRegister');

var fs = require('fs');
var path = require('path');
var mixable = require('mixable-object');

// Copied from bluebird.
function isPrimitive(val) {
  return val == null || val === true || val === false ||
    typeof val === 'string' || typeof val === 'number';
}

/**
 * Get or build a sub register for an object.
 */
function subRegister(obj, name) {
  var res;
  res = isPrimitive(obj[name]) ? {} : obj[name];
  return obj[name] = mixable(res).mixin(proto, 'register', 'extend');
}

/**
 * Try to handle with require().
 */
function registerMod(leaf, dir, name) {
  var modPath;
  try {
    modPath = require.resolve(dir);
  } catch (_error) {}
  if (modPath == null) {
    return false;
  }
  // Define a getter with the base name.
  name = path.basename(name, path.extname(name));
  Object.defineProperty(leaf, name, {
    configurable: true,
    enumerable: true,
    get: function () {
      if (require.cache[modPath] == null) {
        debug('loading %s.', modPath);
      }
      return require(modPath);
    }
  });
  return true;
}

/**
 * Try to handle as a directory.
 */
function registerDir(leaf, dir, name) {
  var files;
  try {
    files = fs.readdirSync(dir);
  } catch (_error) {}
  if (files == null) {
    return false;
  }
  if (name != null) {
    leaf = subRegister(leaf, name);
  }
  for (var i = 0, len = files.length; i < len; i++) {
    name = files[i];
    leaf.register(dir, name);
  }
  return true;
}

/**
 * Register.
 *
 * Map file structure to an object.
 *
 * @param {String} root the path to the file or directory
 * @param {String} ...names the names are not only path to the files but also path
 *   to the attributes
 *
 * @return {this}
 */
function register(root) {
  var leaf = this; // jscs:ignore safeContextKeyword
  // TODO: default base path?
  var dir = path.resolve(root);
  // Try as a directory if no name given.
  if (arguments.length <= 1) {
    registerDir(this, dir);
    return this;
  }
  // The names are not only path to the files but also path to the attributes.
  for (var i = 1, len = arguments.length - 1; i < len; i++) {
    var sub = arguments[i];
    leaf = subRegister(leaf, sub);
    dir = path.resolve(dir, sub);
  }
  // Only the last name is registered (others are used as the path; see above).
  var name = arguments[i++];
  dir = path.resolve(dir, name);
  // Handle with require if possible.
  if (registerMod(leaf, dir, name)) {
    return this;
  }
  // Handle as a directory if possible.
  registerDir(leaf, dir, name);
  return this;
}

// Keep enumerable as they're supposed to be used in real prototypes.
module.exports = {
  register: register,
  // Powered with merge() but for historic reasons named extend().
  extend: mixable.merge
};

// To be used with the sub registers, so put them innumerable.
var proto = Object.defineProperties({}, {
  register: {
    configurable: true,
    enumerable: false,
    value: register
  },
  extend: {
    configurable: true,
    enumerable: false,
    value: mixable.merge
  }
});


text:
from flask import Flask
from flask import request
import os
import requests
import socket
import sys

app = Flask(__name__)

TRACE_HEADERS_TO_PROPAGATE = [
    'X-Ot-Span-Context',
    'X-Request-Id',

    # Zipkin headers
    'X-B3-TraceId',
    'X-B3-SpanId',
    'X-B3-ParentSpanId',
    'X-B3-Sampled',
    'X-B3-Flags',

    # Jaeger header (for native client)
    "uber-trace-id"
]

@app.route('/service/<service_number>')
def hello(service_number):
  return ('Hello from behind Envoy (service {})! hostname: {} resolved'
          'hostname: {}\n'.format(os.environ['SERVICE_NAME'], socket.gethostname(),
                                  socket.gethostbyname(socket.gethostname())))

@app.route('/trace/<service_number>')
def trace(service_number):
  headers = {}
  # call service 2 from service 1
  if int(os.environ['SERVICE_NAME']) == 1:
    for header in TRACE_HEADERS_TO_PROPAGATE:
      if header in request.headers:
        headers[header] = request.headers[header]
    requests.get("http://localhost:9000/trace/2", headers=headers)
  return ('Hello from behind Envoy (service {})! hostname: {} resolved'
          'hostname: {}\n'.format(os.environ['SERVICE_NAME'], socket.gethostname(),
                                  socket.gethostbyname(socket.gethostname())))

if __name__ == "__main__":
  app.run(host='127.0.0.1', port=8080, debug=True)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="1dip" android:color="#36797f" />
            <gradient  android:angle="-90"  android:startColor="#73abd3" android:endColor="@color/colorPrimary"  />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="3dip" />
            <stroke android:width="1dip" android:color="#36797f" />
            <solid  android:color="#308d9e"/>
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="1dip" android:color="#36797f" />
            <gradient  android:angle="-90"  android:startColor="#73c5d3" android:endColor="@color/colorPrimary" />
        </shape>
    </item>
</selector>


text:
import { connect } from 'react-redux';
import TodoApp from '../TodoApp';
import { addTodo, removeTodo, toggleTodo, reciveTodos, saveTodos } from '../../actions/todo-actions'

function mapStateToProps(state) {
    return {

    };
}

function mapDispatchToProps(dispatch) {
    return {
        reciveTodos: () => dispatch(reciveTodos()),
    };
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(TodoApp);


text:
@interface LabelEBNFParserTest : SenTestCase

@end


text:
package com.vijaysharma.gezzoo.database;

import static com.vijaysharma.gezzoo.service.ObjectifyService.ofy;

import java.util.Collection;
import java.util.List;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Work;

public class DatabaseService {
	public static DatabaseService db() {
		return new DatabaseService(ofy());
	}

	private final Objectify service;
	public DatabaseService(Objectify service) {
		this.service = service;
	}

	public <T> QueryBuilder<T> newQuery(Class<T> clazz) {
		return new QueryBuilder<T>(service, clazz);
	}

	public <T> void save(T object) {
		service.save().entity(object).now();
	}

	public <T> T load(Class<T> clazz, String id) {
		return service.load().key(Key.create(clazz, id)).now();
	}

	public <T> T load(Class<T> clazz, Long id) {
		return service.load().key(Key.create(clazz, id)).now();
	}

	public <T> List<T> find(QueryBuilder<T> query) {
		return query.build().list();
	}

	public <T> T findOne(QueryBuilder<T> query) {
		return query.build().first().now();
	}

	public <T> void delete(Class<T> clazz, Collection<Long> ids) {
		service.delete().type(clazz).ids(ids).now();
	}

	public <T> T transaction(final Transaction<T> action) {
		return service.transact(new Work<T>() {
			@Override
			public T run() {
				return action.go();
			}
		});
	}
}


text:
title: SQL Designer Online
summary: SQL Designer allows users to create database designs, which can be saved/loaded and exported to SQL scripts. Various databases and languages are supported. Ability to import existing database design.
categories: tools
tags: sql designer online tool
date: 2021-09-08 09:09:09 +0000
layout: post
---

An SQL Tool Online to draw diagrams.

I drop a demo here [SQL Designer Online](https://ondras.zarovi.cz/sql/demo/).

The [Wiki here](https://github.com/ondras/wwwsqldesigner/wiki).

The [Github repository here](https://github.com/ondras/wwwsqldesigner).


text:
<?php namespace Illuminate\Contracts\Routing;

use Closure;

interface Registrar {

	/**
	 * Register a new GET route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function get($uri, $action);

	/**
	 * Register a new POST route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function post($uri, $action);

	/**
	 * Register a new PUT route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function put($uri, $action);

	/**
	 * Register a new DELETE route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function delete($uri, $action);

	/**
	 * Register a new PATCH route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function patch($uri, $action);

	/**
	 * Register a new OPTIONS route with the router.
	 *
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function options($uri, $action);

	/**
	 * Register a new route with the given verbs.
	 *
	 * @param  array|string  $methods
	 * @param  string  $uri
	 * @param  \Closure|array|string  $action
	 * @return void
	 */
	public function match($methods, $uri, $action);

	/**
	 * Route a resource to a controller.
	 *
	 * @param  string  $name
	 * @param  string  $controller
	 * @param  array   $options
	 * @return void
	 */
	public function resource($name, $controller, array $options = array());

	/**
	 * Create a route group with shared attributes.
	 *
	 * @param  array     $attributes
	 * @param  \Closure  $callback
	 * @return void
	 */
	public function group(array $attributes, Closure $callback);

	/**
	 * Register a new "before" filter with the router.
	 *
	 * @param  string|callable  $callback
	 * @return void
	 */
	public function before($callback);

	/**
	 * Register a new "after" filter with the router.
	 *
	 * @param  string|callable  $callback
	 * @return void
	 */
	public function after($callback);

	/**
	 * Register a new filter with the router.
	 *
	 * @param  string  $name
	 * @param  string|callable  $callback
	 * @return void
	 */
	public function filter($name, $callback);

}


text:
/** Because the query between two processes has three stages, --
 * send query, receive meta data, receive data, -- two state machines
 * are used to cope with the stages, one for send side, and the other
 * for receive side.
 *
 * To issue queries:
 *     In query.c, KMI_query_db is to send queries and receive query results.
 *     In iquery.c, KMI_iquery_db is to send queries; and KMI_test is
 *     to receive query results.
 *
 * To answer queries:
 *     _KMI_query_db_check in query.c is to receive query, and to send
 *     back results. Note iquery and query share the same
 *     _KMI_query_db_check.
 */
#include "kmi.h"

int _KMI_query_fn(void *extra_state, MPI_Status * status)
{
    status->MPI_SOURCE = MPI_UNDEFINED;
    status->MPI_TAG = MPI_UNDEFINED;
    MPI_Status_set_cancelled(status, 0);
    MPI_Status_set_elements(status, MPI_CHAR, 0);
    return 0;
}

int _KMI_free_fn(void *extra_state)
{
    return 0;
}

int _KMI_cancel_fn(void *extra_state, int complete)
{
    return 0;
}

inline int _KMI_iquery_db_helper(KMI_db_t db, char *str, long str_len,
                                 KMI_query_type_t type,
                                 KMI_error_tolerance_t etlr,
                                 KMI_request_t *request,
                                 KMI_hash_table_record_t **list, int *list_len,
                                 int i, int hash_key)
{
    int numprocs, myid;
    MPI_Comm_size(db->comm, &numprocs);
    MPI_Comm_rank(db->comm, &myid);
    int rc = 0;
    return rc;
}

int KMI_iquery_db(KMI_db_t db, char *str, long str_len,
                  KMI_query_type_t type,
                  KMI_error_tolerance_t etlr,
                  KMI_request_t *request,
                  KMI_hash_table_record_t **list, int *list_len)
{
    int numprocs, myid;
    MPI_Comm_size(db->comm, &numprocs);
    MPI_Comm_rank(db->comm, &myid);
    int rc = 0;
    int i;
    int hash_key;
#ifdef KMI_CONFIG_BINARY_STRING
    int str_bin_len;
    char *str_bin;
    KMI_str_ltr2bin(str, str_len, &str_bin, &str_bin_len);
#endif

    MPI_Grequest_start(_KMI_query_fn, _KMI_free_fn, _KMI_cancel_fn, NULL,
                       &(request->mpi_greq));

    *list_len = 0;
    /* FIXME: for now only one table is supported for iquery.
     * If iquery for multiple tables is needed, request will still be one,
     * but instead of one mpi_greq/sendreq/recvreq, multiple requests are
     * needed, one for each table.
     *
     * On the KMI_test side, instead of test one request, request corresponding
     * to each table should be checked use MPI_Testany.
     */
    for (i = 0; i < db->db_num_local_tb; i++) {
#ifdef KMI_CONFIG_SORTING
        /* splitter vector use 1-to-n mapping */
        int low, high;
        KMI_keyspace_splitter(db->tb[i], KMI_STRING, str_len, numprocs, &low,
                              &high);
        request->req_count = 0;
        request->unfinished_count = 0;
        request->low = low;
        request->high = high;
#ifdef DEBUG_PRINT
        printf("[%d]low:%d, high:%d\n", myid, low, high);
#endif
        if (high - low + 1 > KMI_MAX_NUM_SEND_REQ) {
            printf
                ("Splitter vector failed to limit query to less than %d processor\n",
                 KMI_MAX_NUM_SEND_REQ);
            printf("You can increase KMI_MAX_NUM_SEND_REQ in kmi.h\n");
            printf
                ("or find a better distributed sorting algorithm to solve this problem\n");
            exit(0);
        }
        for (hash_key = low; hash_key <= high; hash_key++) {
            request->hash_key = hash_key;
            request->myid = myid;
            request->db = db;
            request->list = list;
            request->list_len = list_len;
            if (hash_key == myid) {
                switch (type) {
                case KMI_QUERY_PREFIX:
                    _KMI_query_table_prefix(db->tb[i], KMI_STRING, str_len,
                                            etlr, list, list_len);
                    if (*list_len > 0)
                        rc = 1;
                    *(request->list_len) = *list_len;
                    break;
                default:
                    printf("query type unrecogonized\n");
                    return -101;
                }
            } else {
                /* send the query to the owner process */
                memcpy(request->query.str, KMI_STRING,
                       KMI_BIN_STR_LEN(str_len));
                request->query.str_len = str_len;
                request->query.from_id = myid;
                request->query.db_index = db->db_index;
                request->query.type = type;
                request->query.etlr = etlr;
                request->stage = 0;
#ifdef DEBUG_PRINT
                printf("[%d]send req to %d\n", myid, hash_key);
#endif
                MPI_Isend(&(request->query), sizeof(KMI_query_t), MPI_CHAR,
                          hash_key, KMI_QUERY_DAEMON_TAG, db->comm,
                          &(request->mpi_sendreq[request->req_count]));
                (request->req_count)++;
                (request->unfinished_count)++;
            }
        }
#else
        /* KMI_keyspace_partition use 1-to-1 mapping */
        hash_key = KMI_keyspace_partition(KMI_STRING, str_len, numprocs);
        request->hash_key = hash_key;
        request->myid = myid;
        request->db = db;
        request->list = list;
        request->list_len = list_len;
        if (hash_key == myid) {
            switch (type) {
            case KMI_QUERY_PREFIX:
                rc = _KMI_query_table_prefix(db->tb[i], KMI_STRING, str_len,
                                             etlr, list, list_len);
                *(request->list_len) = *list_len;
                break;
            default:
                printf("query type unrecogonized\n");
                return -101;
            }
        } else {
            /* send the query to the owner process */
            memcpy(request->query.str, KMI_STRING, KMI_BIN_STR_LEN(str_len));
            request->query.str_len = str_len;
            request->query.from_id = myid;
            request->query.db_index = db->db_index;
            request->query.type = type;
            request->query.etlr = etlr;
            request->stage = 0;
            MPI_Isend(&(request->query), sizeof(KMI_query_t), MPI_CHAR,
                      hash_key, KMI_QUERY_DAEMON_TAG, db->comm,
                      &(request->mpi_sendreq));
        }
#endif
    }

#ifdef KMI_CONFIG_BINARY_STRING
    kmi_free(str_bin);
#endif
    return rc;
}

inline void _KMI_test_complete(KMI_request_t *request, int *flag,
                               KMI_status_t *status)
{
    *flag = 1;
    MPI_Status_set_elements(status, MPI_CHAR, *(request->list_len));
    MPI_Grequest_complete(request->mpi_greq);
}

/** Test if the query is sent, then recv the meta-data response.
 */
inline void _KMI_test_stage0(KMI_request_t *request)
{
    int send_flag = 0;
#ifdef KMI_CONFIG_SORTING
    int index;
    MPI_Testany(request->req_count, request->mpi_sendreq, &index, &send_flag,
                MPI_STATUS_IGNORE);
    request->index = index;
    if (send_flag) {
        request->stage = 1;
        int src = request->index + request->low;
        if (request->myid <= request->high
            && request->myid >= request->low
            && src - request->low >= request->myid - request->low) {
            /* deal with the case when myid is in query range [low,high] */
            src = src + 1;
        }
#ifdef DEBUG_PRINT
        printf("[%d]src:%d, meta, index:%d,low:%d,high:%d\n", request->myid,
               src, request->index, request->low, request->high);
#endif
        MPI_Irecv(&(request->meta_recv), sizeof(KMI_query_meta_t),
                  MPI_CHAR, src, KMI_QUERY_META_TAG,
                  request->db->comm, &(request->mpi_recvreq));
    }
#else
    MPI_Test(&(request->mpi_sendreq), &send_flag, MPI_STATUS_IGNORE);
    if (send_flag) {
        request->stage = 1;
        MPI_Irecv(&(request->meta_recv), sizeof(KMI_query_meta_t),
                  MPI_CHAR, request->hash_key, KMI_QUERY_META_TAG,
                  request->db->comm, &(request->mpi_recvreq));
    }
#endif
}

/** Test if the meta-data is received, then recv the data.
 */
inline void _KMI_test_stage1(KMI_request_t *request)
{
    /* recv query result meta-data */
    int recv_flag = 0;
    MPI_Test(&(request->mpi_recvreq), &recv_flag, &(request->recv_status));
    if (recv_flag) {
        /* recv query result data */
        if (request->meta_recv.len > 0) {
            request->databuf =
                (char *) kmi_malloc(request->meta_recv.len * sizeof(char));
#ifdef KMI_CONFIG_SORTING
            int src = request->index + request->low;
            if (request->myid <= request->high
                && request->myid >= request->low
                && src - request->low >= request->myid - request->low) {
                /* deal with the case when myid is in query range [low,high] */
                src = src + 1;
            }
#ifdef DEBUG_PRINT
            printf("[%d]src:%d, data\n", request->myid, src);
#endif
            MPI_Irecv(request->databuf,
                      request->meta_recv.len * sizeof(char),
                      MPI_CHAR, src,
                      KMI_QUERY_DATA_TAG, request->db->comm,
                      &(request->mpi_recvreq));
#else
            MPI_Irecv(request->databuf,
                      request->meta_recv.len * sizeof(char),
                      MPI_CHAR, request->hash_key,
                      KMI_QUERY_DATA_TAG, request->db->comm,
                      &(request->mpi_recvreq));
#endif
            request->stage = 2;
        } else {
            request->stage = 3;
        }
    }
}

/** Test if the data is received, the form the list.
 */
inline void _KMI_test_stage2(KMI_request_t *request)
{
    int recv_flag = 0;
    MPI_Test(&(request->mpi_recvreq), &recv_flag, &(request->recv_status));
    if (recv_flag) {
        /* form a record list from databuf */
        if (request->meta_recv.count > 0) {
            int old_len = *(request->list_len);
            *(request->list_len) += request->meta_recv.count;
            if (old_len > 0) {
                *(request->list) = (KMI_hash_table_record_t *)
                    kmi_realloc(*(request->list), *(request->list_len) *
                                sizeof(KMI_hash_table_record_t));
            } else {
                *(request->list) = (KMI_hash_table_record_t *)
                    kmi_malloc(request->meta_recv.count *
                               sizeof(KMI_hash_table_record_t));
            }
            struct KMI_hash_table_record *new_list =
                (struct KMI_hash_table_record *)
                kmi_malloc(request->meta_recv.count *
                           sizeof(struct KMI_hash_table_record));
            int i;
            char *ptr_buf = request->databuf;
            for (i = 0; i < request->meta_recv.count; i++) {
                int *ptr_tmp = (int *) ptr_buf;
                new_list[i].str_len = ptr_tmp[0];
                new_list[i].count = ptr_tmp[1];
                new_list[i].rc_count = ptr_tmp[2];
                ptr_buf += 3 * sizeof(int);
                new_list[i].str =
                    (char *) kmi_malloc(new_list[i].str_len * sizeof(char));
                memcpy(new_list[i].str, ptr_buf,
                       KMI_BIN_STR_LEN(new_list[i].str_len));
                ptr_buf += KMI_BIN_STR_LEN(new_list[i].str_len);
                (*(request->list))[old_len + i] = &new_list[i];
            }
        }

        kmi_free(request->databuf);
        request->stage = 3;
    }
}

int KMI_test(KMI_request_t *request, int *flag, KMI_status_t *status)
{
    _KMI_query_db_check(request->db);
    if (request->hash_key == request->myid) {
        _KMI_test_complete(request, flag, status);
    } else {
        if (request->stage == 0)
            _KMI_test_stage0(request);
        if (request->stage == 1)
            _KMI_test_stage1(request);
        if (request->stage == 2)
            _KMI_test_stage2(request);
        if (request->stage == 3) {
#ifdef KMI_CONFIG_SORTING
            request->unfinished_count--;
            if (request->unfinished_count == 0)
                _KMI_test_complete(request, flag, status);
            else
                request->stage = 0;
#else
            _KMI_test_complete(request, flag, status);
#endif
        }
    }
    return 0;
}

int KMI_get_count(KMI_status_t *status, KMI_Datatype datatype, int *count)
{
    MPI_Get_count(status, datatype, count);
    return 0;
}

int KMI_testany(int count, KMI_request_t reqs[], int *indx,
                int *flag, KMI_status_t *status)
{
    return 0;
}


text:
1. Internal CMS system
2. Support new version of Android and iOS

# Louis Ferreira

1. Recruitment website for job listings, back in 1998
2. Admin interface for Domain Registrars

# Nicola du Toit

1. Siyavula's online maths and science practice service: Everything Maths and Everything Science.
2. an LMS for high school teachers, and a homework/quiz revision Android app.

# Luke Menzel

1. updating the homepage of GivenGain and standardizing the brand (as well as getting a brand manual in place).
2. Many things, but the biggest project currently is improving our site's Explore page from a UX point of view. The page serves as a way for people to find and support Causes and Activist projects and the ultimate goal is to convert them into donors. https://www.givengain.com/explore/ The new page needs to go live within the next 2 weeks.

# Alison Ritchie

1. Digital magazine
2. App Launch

# Deon Fourie

1. A brochure or a placeholder website
2. Moving a product's CSS structure to Sass/Compass

# Michelle Flynn

1. A design for a website that doesn't exist anymore http://www.christians.co.za/ - this was circa 2003-2005
2. A website for medical insurance https://www.getsavvi.co.za

# Dayne Tabraham

1. Brochure websites / promos
2. Cloud app registration

# Marieta van Tonder

- New to UX and hasn't worked on anything yet

# Justin Slack

1. A content portal for a University language course c. 1998
2. My personal website!

# Steve Barnett

1. Templates for Blogger sites.
2. Fufu, my Front-end Style Guide skeleton.


text:
#if !defined INCLUDED_dt_core_strpf_h_
#define INCLUDED_dt_core_strpf_h_

#if defined __cplusplus
extern "C" {
#endif	/* __cplusplus */

/* helpers */
static inline __attribute__((pure, const)) struct strpdt_s
strpdt_initialiser(void)
{
#if defined HAVE_SLOPPY_STRUCTS_INIT
	static const struct strpdt_s res = {};
#else
	static const struct strpdt_s res;
#endif	/* HAVE_SLOPPY_STRUCTS_INIT */
	return res;
}

#if defined INCLUDED_dt_core_h_
/**
 * Parse STR with the standard parser, put the end of the parsed string in EP.*/
extern struct dt_dt_s __strpdt_std(const char *str, char **ep);
#endif	/* INCLUDED_dt_core_h_ */

/* self-explanatory funs, innit? */
extern int
__strpdt_card(struct strpdt_s*, const char *sp, struct dt_spec_s s, char **ep);

extern size_t
__strfdt_card(
	char *buf, size_t bsz, struct dt_spec_s s,
	struct strpdt_s *d, struct dt_dt_s that);

extern size_t
__strfdt_dur(
	char *buf, size_t bsz, struct dt_spec_s s,
	struct strpdt_s *d, struct dt_dtdur_s that);

#if defined __cplusplus
}
#endif	/* __cplusplus */

#endif	/* INCLUDED_dt_core_strpf_h_ */


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class ButtonQuitController : MonoBehaviour {
    private Button _b;
    private AudioSource _aSource;
    private MenuSounds _sounds;

    // Use this for initialization
    void Start () {
        _sounds = GameObject.Find("LC").GetComponent<MenuSounds>();
        _aSource = GameObject.Find("LC").GetComponent<AudioSource>();
        _b = GetComponent<Button>();
        _b.onClick.AddListener(() => { Application.Quit(); });
	}

    public void OnHover()
    {
        if (_b.interactable)
            _aSource.PlayOneShot(_sounds.ButtonQuit);
    }
}


text:
Reports any access to the java.util.Collections
fields EMPTY_LIST, EMPTY_MAP
or EMPTY_SET. Those expressions can be replaced by method
calls to emptyList(),
emptyMap() and emptySet().
Such method calls prevent "unchecked" warnings by the compiler because the type parameters can be inferred.

This inspection only reports if the project or module is configured to use a
language level of 5.0 or higher.

Powered by InspectionGadgets


text:
@interface FireDataISO8601DateFormatter : ISO8601DateFormatter
+ (FireDataISO8601DateFormatter *)sharedFormatter;
@end


text:
title: Missionsnytt
date: 21/06/2019
---

#### Den första kyrkan vi hittar

Hemma i Aracaju i Brasilien grälade min mor och styvfar hela tiden. Med tiden tycktes grälen bli allt hårdare och mer högljudda. Min barndom var fylld av skrik och kaos. Jag växte upp utan Gud och gick aldrig i kyrkan.

En dag när jag var 18 år kom en vänlig dam på besök. Hon blev chockerad över det hon fick se och höra.

"Ni har en vacker familj, men ni saknar Gud i era liv", sa hon. "Följ med mig. Vi går till den första kyrkan som vi hittar."

Vi traskade iväg, min mor, styvfar, lillasyster, halvsyster, halvbror och jag. Den första kyrkan vi passerade tillhörde Adventistsamfundet, och vi gick in. Några ungdomar höll en serie evange-liska möten, och senare besökte de oss och studerade Bibeln med oss.

Jag var i skolan vid den tiden då ungdomarna besökte oss, så jag missade Bibelstudierna. Men min mor och mina syskon deltog och vi gick alla i kyrkan. Frid fyllde vårt hem. Men det varade inte länge. Snart började våra föräldrar gräla igen, och striderna mellan dem var värre än någonsin.

En dag stod min mor inte ut längre, så hon flyttade. Efter det slutade vi andra att gå i kyrkan. Jag ville inte lämna mina små halvsyskon, så jag stannade hos dem och min styvfar.

Det hade gått flera månader när telefonen ringde en kväll. En 26-årig affärsman som hette Rafael behövde en sekreterare och frågade om jag ville ha jobbet. Han hade besökt min skola den dagen och frågat rektorn om hon kunde rekommendera någon.

Jag tackade ja till jobbet.

Snart märkte jag att min nya chef inte var som de flesta människor jag kände. Han bad innan han började arbeta. Han åt inte vissa yper av mat. En dag när jag åkte i hans bil satte han på musik som jag kände igen från Adventkyrkan. Jag började sjunga med. Rafael hörde mig och frågade: "Känner du till Adventkyrkan?" Jag nickade.

Rafael sa att han var adventist och frågade om jag ville följa med honom till kyrkan. Först sa jag nej, men när han hade frågat några gånger gick jag till slut dit en sabbat. Efter det kunde jag inte sluta gå. Jag älskade att tillbe Gud i Adventkyrkan, och jag började studera Bibeln.

I februari 2017 döptes jag. Min tolvåriga halvbror, Jenivaldo, döptes några månader senare. Mina systrar märkte att jag bad och att mitt beteende hade förändrats till det bättre. De sa också att jag talade annorlunda. Båda systrarna, Yasmim som är 18 år och min halvsyster Evelim som är 15 år, blev döpta tillsammans.

Fem månader efter mitt dop friade Rafael till mig, och jag sa ja.

Jag ber att mina föräldrar också ska lära känna Jesus. Jag är aktiv inom barn- och musikverksamheterna i församlingen. Och mina systrar hjälper till i kyrkans reception. Vår bror är scout.

En del av den trettonde sabbatens missionsgåva kommer att användas till att hjälpa vår församling att få en ny byggnad där det finns plats åt alla de människor som vill fira gudstjänst hos oss varje sabbat. Tack för era gåvor!


text:
	<title>Learning Javascript</title>

	<meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

Test your reactions!

Click on the boxes and circles as quickly as you can!

You have not attempted yet.


text:
Read throughfully the [Directory structure](doc/directory-structure.md) before starting, else you're doomed to fail.

## Updates project

Get the last version of the project:

```bash
git pull -u origin master
```

Update the composant used:

```bash
cd ../jeece-dokuwiki-template
sudo npm update    # updates nodes.js
bower update       # updates Bower components
```

Be sure to follow a good [Git workflow](//wiki.jeece.fr/developpeur/git).

## Grunt tasks

Grunt is a task manager, use it to ease your development, checking your code and deploying your code. To run a grunt task named `mytask`, do `grunt mytask`.

Available tasks:
* `build`: build the whole project
* `clean`: clean the project (remove all symlinks and output files)
* `watch`: watch files to rebuild on change
* `start`: start working without wondering which task to perfom:
* `test-js`: validate Javascript

Note: since DokuWiki already compress the Javascript and CSS, it is not needed to do so with Grunt, although Grunt could do it pretty well.

[Previous section](directory-structure.md)


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<appender class="ch.qos.logback.core.ConsoleAppender" name="STDOUT">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<Pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
			</Pattern>
		</layout>
	</appender>
	<root level="debug">
		<appender-ref ref="STDOUT" />
	</root>
</configuration>


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('foodGenerator', [
    'ui.router',
    'ui.bootstrap',
    'dndLists',
    'foodGenerator.home',
    'foodGenerator.account',
    'foodGenerator.search',
    'foodGenerator.search.ingredients',
    'foodGenerator.search.recipes',
    'foodGenerator.mealPlanner',
    'foodGenerator.recipeDetail',
    'foodGenerator.shoppingList',
    'foodGenerator.terms',
    'foodGenerator.about',
    'foodGenerator.contact',
    'foodGenerator.privacy',
    'templates',
    'ngTagsInput'
])

    .config(function ($stateProvider, $urlRouterProvider, $httpProvider) {
        // For any unmatched url, redirect to /home
        $urlRouterProvider.otherwise("/home");

        $stateProvider
            .state('root', {
                abstract: true,
                templateUrl: "views/root/root.html"
            });

        //backend request error interceptor
        $httpProvider.interceptors.push('reqErrInterceptor');
        //auth interceptor
        $httpProvider.interceptors.push('authInterceptor');
    });


text:
package edu.emory.cci.aiw.cvrg.eureka.common.entity;

import java.util.Collections;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 *
 * @author Andrew Post
 */
@Entity
@Table(name = "neo4j_destinations")
public class Neo4jDestinationEntity extends DestinationEntity {
	@Column(nullable=false)
	private String dbHome;

	public String getDbHome() {
		return dbHome;
	}

	public void setDbHome(String dbHome) {
		this.dbHome = dbHome;
	}

	@Override
	public boolean isGetStatisticsSupported() {
		return true;
	}

	@Override
	public void accept(DestinationEntityVisitor visitor) {
		visitor.visit(this);
	}

	@Override
	public boolean isAllowingQueryPropositionIds() {
		return true;
	}

}


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m151001_194849_add_foreign_key_device_condition_id extends Migration
{
    public function up()
    {
	$this -> addForeignKey ( 'condition_id', 'device', 'condition_id', 'conditions', 'id');
    }

    public function down()
    {
        $this -> dropForeignKey ( 'condition_id', 'device' );

        return true;
    }
}


text:
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2021 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

#include <cursespp/curses_config.h>
#include <cursespp/Colors.h>
#include <cursespp/ScrollAdapterBase.h>
#include <sigslot/sigslot.h>
#include <deque>
#include <map>

namespace cursespp {
    class SimpleScrollAdapter : public ScrollAdapterBase {
        public:
            sigslot::signal1<SimpleScrollAdapter*> Changed;

            SimpleScrollAdapter();
            virtual ~SimpleScrollAdapter();

            size_t GetEntryCount() override;
            EntryPtr GetEntry(cursespp::ScrollableWindow* window, size_t index) override;

            void SetSelectable(bool selectable);
            void AddEntry(const std::string& entry);
            std::string StringAt(size_t index);

            /* virtual methods we define */
            virtual void AddEntry(EntryPtr entry);
            virtual void SetMaxEntries(const size_t size = 500);
            virtual void Clear();

        private:
            typedef std::deque<EntryPtr> EntryList; /* TODO: this is O(n) lookup */
            typedef EntryList::iterator Iterator;
            std::map<size_t, Color> indexToColor;
            EntryList entries;
            size_t maxEntries;
            bool selectable;
    };
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Xml;

using Microsoft.Build.Evaluation;
using Microsoft.Build.Construction;
using Microsoft.Build.Shared;

using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using Xunit;

namespace Microsoft.Build.UnitTests.OM.Construction
{
    ///
    /// Tests for the ProjectChooseElement class (and for ProjectWhenElement and ProjectOtherwiseElement)
    ///
    public class ProjectChooseElement_Tests
    {
        ///
        /// Read choose with unexpected attribute
        ///
        [Fact]
        public void ReadInvalidAttribute()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose X='Y'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with unexpected Condition attribute.
        /// Condition is not currently allowed on Choose.
        ///
        [Fact]
        public void ReadInvalidConditionAttribute()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose Condition='true'/>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with unexpected child
        ///
        [Fact]
        public void ReadInvalidChild()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <X/>
                        </Choose>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with a When containing no Condition attribute
        ///
        [Fact]
        public void ReadInvalidWhen()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <When>
                                <PropertyGroup><x/></PropertyGroup>
                            </When>
                            <Otherwise>
                                <PropertyGroup><y/></PropertyGroup>
                            </Otherwise>
                        </Choose>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with only an otherwise
        ///
        [Fact]
        public void ReadInvalidOnlyOtherwise()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <Otherwise/>
                        </Choose>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with two otherwises
        ///
        [Fact]
        public void ReadInvalidTwoOtherwise()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <Otherwise/>
                            <Otherwise/>
                        </Choose>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read choose with otherwise before when
        ///
        [Fact]
        public void ReadInvalidOtherwiseBeforeWhen()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <Otherwise/>
                            <When Condition='c'/>
                        </Choose>
                    </Project>
                ";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Read empty choose
        ///
        /// <remarks>
        /// One might think this should work but 2.0 required at least one When.
        /// </remarks>
        [Fact]
        public void ReadInvalidEmptyChoose()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose/>
                    </Project>
                ";

                ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
                ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);

                Assert.Null(Helpers.GetFirst(choose.Children));
            }
           );
        }
        ///
        /// Read choose with only a when
        ///
        [Fact]
        public void ReadChooseOnlyWhen()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <When Condition='c'/>
                        </Choose>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);

            Assert.Equal(1, Helpers.Count(choose.WhenElements));
            Assert.Null(choose.OtherwiseElement);
        }

        ///
        /// Read basic choose
        ///
        [Fact]
        public void ReadChooseBothWhenOtherwise()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <When Condition='c1'/>
                            <When Condition='c2'/>
                            <Otherwise/>
                        </Choose>
                    </Project>
                ";

            ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            ProjectChooseElement choose = (ProjectChooseElement)Helpers.GetFirst(project.Children);

            List<ProjectWhenElement> whens = Helpers.MakeList(choose.WhenElements);
            Assert.Equal(2, whens.Count);
            Assert.Equal("c1", whens[0].Condition);
            Assert.Equal("c2", whens[1].Condition);
            Assert.NotNull(choose.OtherwiseElement);
        }

        ///
        /// Test stack overflow is prevented.
        ///
        [Fact]
        public void ExcessivelyNestedChoose()
        {
            Assert.Throws<InvalidProjectFileException>(() =>
            {
                StringBuilder builder1 = new StringBuilder();
                StringBuilder builder2 = new StringBuilder();

                for (int i = 0; i < 52; i++)
                {
                    builder1.Append("<Choose><When Condition='true'>");
                    builder2.Append("</When></Choose>");
                }

                string content = "<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>";
                content += builder1.ToString();
                content += builder2.ToString();
                content += @"</Project>";

                ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
            }
           );
        }
        ///
        /// Setting a When's condition should dirty the project
        ///
        [Fact]
        public void SettingWhenConditionDirties()
        {
            string content = @"
                    <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' >
                        <Choose>
                            <When Condition='true'>
                              <PropertyGroup>

v1

                              </PropertyGroup>
                            </When>
                        </Choose>
                    </Project>
                ";

            Project project = new Project(XmlReader.Create(new StringReader(content)));
            ProjectChooseElement choose = Helpers.GetFirst(project.Xml.ChooseElements);
            ProjectWhenElement when = Helpers.GetFirst(choose.WhenElements);
            when.Condition = "false";

            Assert.Equal("v1", project.GetPropertyValue("p"));

            project.ReevaluateIfNecessary();

            Assert.Equal(String.Empty, project.GetPropertyValue("p"));
        }
    }
}


text:
layout: tag
section-type: tag
title: saturn
---
## Tag


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>
#include <assert.h>
#include <exception>

// UnityEngine.GUILayer
struct GUILayer_t999894339;
// UnityEngine.GUIElement
struct GUIElement_t4113441198;

#include "codegen/il2cpp-codegen.h"
#include "UnityEngine_UnityEngine_Vector33525329789.h"
#include "UnityEngine_UnityEngine_GUILayer999894339.h"

// UnityEngine.GUIElement UnityEngine.GUILayer::HitTest(UnityEngine.Vector3)
extern "C"  GUIElement_t4113441198 * GUILayer_HitTest_m3356120918 (GUILayer_t999894339 * __this, Vector3_t3525329789  ___screenPosition, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// UnityEngine.GUIElement UnityEngine.GUILayer::INTERNAL_CALL_HitTest(UnityEngine.GUILayer,UnityEngine.Vector3&)
extern "C"  GUIElement_t4113441198 * GUILayer_INTERNAL_CALL_HitTest_m4210766818 (Il2CppObject * __this /* static, unused */, GUILayer_t999894339 * ___self, Vector3_t3525329789 * ___screenPosition, const MethodInfo* method) IL2CPP_METHOD_ATTR;


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Akavache.Sqlite3.Internal;
using Splat;
using System.Threading.Tasks;
using System.Threading;
using System.Reactive.Disposables;

namespace Akavache.Sqlite3
{
    /// <summary>
    /// This class represents an IBlobCache backed by a SQLite3 database, and
    /// it is the default (and best!) implementation.
    /// </summary>
    public class SQLitePersistentBlobCache : IObjectBlobCache, IEnableLogger
    {
        public IScheduler Scheduler { get; private set; }
        public SQLiteConnection Connection { get; private set; }

        static readonly object disposeGate = 42;

        readonly IObservable<Unit> _initializer;
        SqliteOperationQueue opQueue;
        IDisposable queueThread;
        bool disposed = false;

        public SQLitePersistentBlobCache(string databaseFile, IScheduler scheduler = null)
        {
            Scheduler = scheduler ?? BlobCache.TaskpoolScheduler;

            BlobCache.EnsureInitialized();

            Connection = new SQLiteConnection(databaseFile, storeDateTimeAsTicks: true);
            _initializer = Initialize();
        }

        internal void ReplaceOperationQueue(SqliteOperationQueue queue)
        {
            _initializer.Wait();

            opQueue.Dispose();

            opQueue = queue;
            opQueue.Start();
        }

        readonly AsyncSubject<Unit> shutdown = new AsyncSubject<Unit>();
        public IObservable<Unit> Shutdown { get { return shutdown; } }

        public IObservable<Unit> Insert(string key, byte[] data, DateTimeOffset? absoluteExpiration = null)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");
            if (key == null || data == null) return Observable.Throw<Unit>(new ArgumentNullException());

            var exp = (absoluteExpiration ?? DateTimeOffset.MaxValue).UtcDateTime;
            var createdAt = Scheduler.Now.UtcDateTime;

            return _initializer
                .SelectMany(_ => BeforeWriteToDiskFilter(data, Scheduler))
                .SelectMany(encData => opQueue.Insert(new[] { new CacheElement() {
                    Key = key,
                    Value = encData,
                    CreatedAt = createdAt,
                    Expiration = exp,
                }}))
                .PublishLast().PermaRef();
        }

        public IObservable<byte[]> Get(string key)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<byte[]>("SqlitePersistentBlobCache");
            if (key == null) return Observable.Throw<byte[]>(new ArgumentNullException());

            return _initializer.SelectMany(_ => opQueue.Select(new[] { key }))
                .SelectMany(x => x.Count() == 1 ?
                    Observable.Return(x.First().Value) :
                    ExceptionHelper.ObservableThrowKeyNotFoundException<byte[]>(key))
                .SelectMany(x => AfterReadFromDiskFilter(x, Scheduler))
                .PublishLast().PermaRef();
        }

        public IObservable<IEnumerable<string>> GetAllKeys()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<List<string>>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.GetAllKeys())
                .PublishLast().PermaRef();
        }

        public IObservable<DateTimeOffset?> GetCreatedAt(string key)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<DateTimeOffset?>("SqlitePersistentBlobCache");
            if (key == null) return Observable.Throw<DateTimeOffset?>(new ArgumentNullException());

            return _initializer.SelectMany(_ => opQueue.Select(new[] { key }))
                .Select(x => x.Count() == 1 ?
                    (DateTimeOffset?)new DateTimeOffset(x.First().CreatedAt, TimeSpan.Zero) :
                    default(DateTimeOffset?))
                .PublishLast().PermaRef();
        }

        public IObservable<DateTimeOffset?> GetObjectCreatedAt<T>(string key)
        {
            return GetCreatedAt(key);
        }

        public IObservable<Unit> Flush()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.Flush())
                .PublishLast().PermaRef();
        }

        public IObservable<Unit> Invalidate(string key)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.Invalidate(new[] { key }))
                .PublishLast().PermaRef();
        }

        public IObservable<Unit> InvalidateAll()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.InvalidateAll())
                .PublishLast().PermaRef();
        }

        public IObservable<Unit> InsertObject<T>(string key, T value, DateTimeOffset? absoluteExpiration = null)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");
            if (key == null) return Observable.Throw<Unit>(new ArgumentNullException());

            var data = SerializeObject(value);
            var exp = (absoluteExpiration ?? DateTimeOffset.MaxValue).UtcDateTime;
            var createdAt = Scheduler.Now.UtcDateTime;

            return _initializer
                .SelectMany(_ => BeforeWriteToDiskFilter(data, Scheduler))
                .SelectMany(encData => opQueue.Insert(new[] { new CacheElement() {
                    Key = key,
                    TypeName = typeof(T).FullName,
                    Value = encData,
                    CreatedAt = createdAt,
                    Expiration = exp,
                }}))
                .PublishLast().PermaRef();
        }

        public IObservable<T> GetObject<T>(string key)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<T>("SqlitePersistentBlobCache");
            if (key == null) return Observable.Throw<T>(new ArgumentNullException());

            return _initializer.SelectMany(_ => opQueue.Select(new[] { key }))
                .SelectMany(x => x.Count() == 1 ?
                    Observable.Return(x.First().Value) :
                    ExceptionHelper.ObservableThrowKeyNotFoundException<byte[]>(key))
                .SelectMany(x => AfterReadFromDiskFilter(x, Scheduler))
                .SelectMany(x => DeserializeObject<T>(x))
                .PublishLast().PermaRef();
        }

        public IObservable<IEnumerable<T>> GetAllObjects<T>()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<IEnumerable<T>>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.SelectTypes(new[] { typeof(T).FullName })
                .SelectMany(x => x.ToObservable()
                    .SelectMany(y => AfterReadFromDiskFilter(y.Value, Scheduler))
                    .SelectMany(y => DeserializeObject<T>(y))
                    .ToList()))
                .PublishLast().PermaRef();
        }

        public IObservable<Unit> InvalidateObject<T>(string key)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");
            return Invalidate(key);
        }

        public IObservable<Unit> InvalidateAllObjects<T>()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.InvalidateTypes(new[] { typeof(T).FullName }))
                .PublishLast().PermaRef();
        }

        public IObservable<Unit> Vacuum()
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<Unit>("SqlitePersistentBlobCache");

            return _initializer.SelectMany(_ => opQueue.Vacuum())
                .PublishLast().PermaRef();
        }

        public void Dispose()
        {
            var disp = Interlocked.Exchange(ref queueThread, null);
            if (disp == null) return;

            var cleanup = Observable.Start(() =>
            {
                // NB: While we intentionally dispose the operation queue
                // from a background thread so that we don't park the UI
                // while we're waiting for background operations to
                // complete, we must serialize calls to sqlite3_close or
                // else SQLite3 will start throwing back "busy" at us.
                //
                // We intentionally serialize even the shutdown of the
                // background queue to be extra paranoid about not getting
                // 'busy' while cleaning up.
                lock (disposeGate)
                {
                    disp.Dispose();
                    opQueue.Dispose();
                    Connection.Dispose();
                }
            }, Scheduler);

            cleanup.Multicast(shutdown).PermaRef();
            disposed = true;
        }

        protected IObservable<Unit> Initialize()
        {
            var ret = Observable.Create<Unit>(async subj =>
            {
                // NB: This is in its own try block because depending on the
                // platform, we may not have a modern SQLite3, where these
                // PRAGMAs are supported. These aren't critical, so let them
                // fail silently
                try
                {
                    // NB: Setting journal_mode returns a row, nfi
                    Connection.ExecuteScalar<int>("PRAGMA journal_mode=WAL");
                    Connection.Execute("PRAGMA temp_store=MEMORY");
                    Connection.Execute("PRAGMA synchronous=OFF");
                }
                catch (SQLiteException)
                {
                }

                try
                {
                    Connection.CreateTable<CacheElement>();

                    var schemaVersion = GetSchemaVersion();

                    if (schemaVersion < 2)
                    {
                        Connection.Execute("ALTER TABLE CacheElement RENAME TO VersionOneCacheElement;");
                        Connection.CreateTable<CacheElement>();

                        var sql = "INSERT INTO CacheElement SELECT Key,TypeName,Value,Expiration,\"{0}\" AS CreatedAt FROM VersionOneCacheElement;";
                        Connection.Execute(String.Format(sql, BlobCache.TaskpoolScheduler.Now.UtcDateTime.Ticks));
                        Connection.Execute("DROP TABLE VersionOneCacheElement;");

                        Connection.Insert(new SchemaInfo() { Version = 2, });
                    }

                    // NB: We have to do this here because you can't prepare
                    // statements until you've got the backing table
                    opQueue = new SqliteOperationQueue(Connection, Scheduler);
                    queueThread = opQueue.Start();

                    subj.OnNext(Unit.Default);
                    subj.OnCompleted();
                }
                catch (Exception ex)
                {
                    subj.OnError(ex);
                }
            });

            return ret.PublishLast().PermaRef();
        }

        protected int GetSchemaVersion()
        {
            bool shouldCreateSchemaTable = false;
            int versionNumber = 0;

            try
            {
                versionNumber = Connection.ExecuteScalar<int>("SELECT Version from SchemaInfo ORDER BY Version DESC LIMIT 1");
            }
            catch (Exception)
            {
                shouldCreateSchemaTable = true;
            }

            if (shouldCreateSchemaTable)
            {
                Connection.CreateTable<SchemaInfo>();
                versionNumber = 1;
            }

            return versionNumber;
        }

        /// <summary>
        /// This method is called immediately before writing any data to disk.
        /// Override this in encrypting data stores in order to encrypt the
        /// data.
        /// </summary>
        /// <param name="data">The byte data about to be written to disk.</param>
        /// <param name="scheduler">The scheduler to use if an operation has
        /// to be deferred. If the operation can be done immediately, use
        /// Observable.Return and ignore this parameter.</param>
        /// <returns>A Future result representing the encrypted data</returns>
        protected virtual IObservable<byte[]> BeforeWriteToDiskFilter(byte[] data, IScheduler scheduler)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<byte[]>("SqlitePersistentBlobCache");

            return Observable.Return(data);
        }

        /// <summary>
        /// This method is called immediately after reading any data to disk.
        /// Override this in encrypting data stores in order to decrypt the
        /// data.
        /// </summary>
        /// <param name="data">The byte data that has just been read from
        /// disk.</param>
        /// <param name="scheduler">The scheduler to use if an operation has
        /// to be deferred. If the operation can be done immediately, use
        /// Observable.Return and ignore this parameter.</param>
        /// <returns>A Future result representing the decrypted data</returns>
        protected virtual IObservable<byte[]> AfterReadFromDiskFilter(byte[] data, IScheduler scheduler)
        {
            if (disposed) return ExceptionHelper.ObservableThrowObjectDisposedException<byte[]>("SqlitePersistentBlobCache");

            return Observable.Return(data);
        }

        byte[] SerializeObject<T>(T value)
        {
            var settings = Locator.Current.GetService<JsonSerializerSettings>() ?? new JsonSerializerSettings();
            var ms = new MemoryStream();
            var serializer = JsonSerializer.Create(settings);
            var writer = new BsonWriter(ms);

            serializer.Serialize(writer, new ObjectWrapper<T>() { Value = value });
            return ms.ToArray();
        }

        IObservable<T> DeserializeObject<T>(byte[] data)
        {
            var settings = Locator.Current.GetService<JsonSerializerSettings>() ?? new JsonSerializerSettings();
            var serializer = JsonSerializer.Create(settings);
            var reader = new BsonReader(new MemoryStream(data));
            var forcedDateTimeKind = BlobCache.ForcedDateTimeKind;

            if (forcedDateTimeKind.HasValue)
            {
                reader.DateTimeKindHandling = forcedDateTimeKind.Value;
            }

            try
            {
                try
                {
                    var boxedVal = serializer.Deserialize<ObjectWrapper<T>>(reader).Value;
                    return Observable.Return(boxedVal);
                }
                catch (Exception ex)
                {
                    this.Log().WarnException("Failed to deserialize data as boxed, we may be migrating from an old Akavache", ex);
                }

                var rawVal = serializer.Deserialize<T>(reader);
                return Observable.Return(rawVal);
            }
            catch (Exception ex)
            {
                return Observable.Throw<T>(ex);
            }
        }
    }

    class CacheElement
    {
        [PrimaryKey]
        public string Key { get; set; }

        [Indexed]
        public string TypeName { get; set; }

        public byte[] Value { get; set; }

        [Indexed]
        public DateTime Expiration { get; set; }

        public DateTime CreatedAt { get; set; }
    }

    class SchemaInfo
    {
        public int Version { get; set; }
    }

    interface IObjectWrapper {}
    class ObjectWrapper<T> : IObjectWrapper
    {
        public T Value { get; set; }
    }
}


text:
#include "trycmd_config.h"
#include "trycmd.h"
#include <assert.h>  /* assert. */
#include <stdio.h>   /* vfprintf, stderr. */
#include <stdarg.h>  /* va_list, va_start, va_end. */

int trycmd_debug_enabled = 0;

void trycmd_debug_init(void) {
    /*
     * Enable or disable diagnostic output according to the given environment.
     * If TRY_DEBUG is present and non-zero, then enable diagnostic message
     * output.
     */
    trycmd_debug_enabled = !!trycmd_getenv_i(N_("TRY_DEBUG"), 0);
}

void trycmd_debug(const char* const format, ...) {
    /* Check arguments. */
    assert("Unexpected NULL format" && (format != NULL));

    /* Print the given message if and only if debug is enabled. */
    if (trycmd_debug_enabled) {
        va_list ap;
        va_start(ap, format);
        vfprintf(stderr, format, ap);
        va_end(ap);
    }
}

/* EOF */


text:
package com.siriusit.spezg.multilib.storage.jpa;

import static org.junit.Assert.assertTrue;

import java.util.Date;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.unitils.UnitilsJUnit4TestClassRunner;
import org.unitils.dbunit.annotation.DataSet;
import org.unitils.spring.annotation.SpringApplicationContext;
import org.unitils.spring.annotation.SpringBeanByType;

import com.siriusit.spezg.multilib.storage.LoanRepository;
import com.siriusit.spezg.multilib.storage.PersonRepository;
import com.siriusit.spezg.multilib.storage.StatisticsRepository;
import com.siriusit.spezg.multilib.storage.UnitRepository;

@DataSet({ "/com/siriusit/spezg/multilib/jpa/Person.db.xml", "/com/siriusit/spezg/multilib/jpa/Unit.db.xml",
        "/com/siriusit/spezg/multilib/jpa/Loan.db.xml" })
@RunWith(UnitilsJUnit4TestClassRunner.class)
public class JpaStatisticsRepositoryTest {

    @SpringApplicationContext("classpath:com/siriusit/spezg/multilib/jpa/spring-config-domain-test.xml")
    private ApplicationContext applicationContext;
    @SpringBeanByType
    private StatisticsRepository statisticsRepository;
    @SpringBeanByType
    private PersonRepository personRepository;
    @SpringBeanByType
    private LoanRepository loanRepository;
    @SpringBeanByType
    private UnitRepository unitRepository;

    @Test
    public void testFindNumberOfUsers() {
        Integer initialNumberOfUsers = statisticsRepository.getStatistics().getNumberOfUsers();
        personRepository.createPerson("username", "11111111", "test@ntnu.no", "Consultant");
        assertTrue(statisticsRepository.getStatistics().getNumberOfUsers().equals(initialNumberOfUsers + 1));
    }

    @Test
    public void testFindNumberOfLoans() {
        Integer initialNumberOfLoans = statisticsRepository.getStatistics().getNumberOfLoans();
        loanRepository.createLoan(personRepository.findPersonByUsername("JoFerraro"),
                unitRepository.findUnitsByTitle("Title2").get(0), new Date(), new Date(), new Date());

        assertTrue(statisticsRepository.getStatistics().getNumberOfLoans().equals(initialNumberOfLoans + 1));
    }

    @Test
    public void testFindNumberOfTitles() {
        Integer initialNumberOfTitles = statisticsRepository.getStatistics().getNumberOfTitles();
        unitRepository.createUnit(personRepository.findPersonByUsername("JoFerraro"), "New Title", "New description");
        assertTrue(statisticsRepository.getStatistics().getNumberOfTitles().equals(initialNumberOfTitles + 1));
    }

    @Test
    public void testFindNumberOfActiveLoans() {
        Integer initialNumberOfActiveLoans = statisticsRepository.getStatistics().getNumberOfActiveLoans();
        loanRepository.createLoan(personRepository.findPersonByUsername("JoFerraro"),
                unitRepository.findUnitsByTitle("Title2").get(0), new Date(), null, new Date());

        assertTrue(statisticsRepository.getStatistics().getNumberOfActiveLoans().equals(initialNumberOfActiveLoans + 1));
    }

    @Test
    public void testSaveStatistics() {
        Integer initialNumberOfStatistics = statisticsRepository.getNumberOfStatistics();
        statisticsRepository.saveStatistics();
        assertTrue(statisticsRepository.getNumberOfStatistics().equals(initialNumberOfStatistics + 1));
    }
}


text:
package com.alifesoftware.instaclient.interfaces;

/**
 * Created by anujsaluja on 6/10/15.
 *
 * This interface is for a listener that is signaled
 * when Authentication process is complete
 *
 */
public interface IOauthListener {
    public void onSuccess();

    public void onFail(String error);
}


text:
/**
 * Provides the functionality to extract the text from a cell.
 */
export interface TextExtractor<TElement> {
    /**
     * Extracts the text from a cell.
     *
     * @param cell
     * The cell whose text is being extracted.
     *
     * @param table
     * The table of the cell.
     *
     * @param index
     * The index of the cell.
     */
    (cell: Element, table: TElement, index: number): string;
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "radiomoduleconnector.h"
#include "hmframe.h"

static const char *TAG = "RadioModuleConnector";

void readThreadProc(int fd, StreamParser *sp)
{
  int len;
  unsigned char buf[1];

  while (true)
  {
    int len = read(fd, buf, 1);
    if (len > 0)
    {
      sp->append(buf[0]);
    }
  }
}

RadioModuleConnector::RadioModuleConnector(int fd) : _fd(fd)
{

  using namespace std::placeholders;
  _streamParser = new StreamParser(false, std::bind(&RadioModuleConnector::_handleFrame, this, _1, _2));

  struct termios tty;
  if (tcgetattr(_fd, &tty) == 0)
  {
    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag |= CS8;
    tty.c_cflag &= ~CRTSCTS;
    tty.c_cflag |= CREAD | CLOCAL;

    tty.c_lflag &= ~ICANON;
    tty.c_lflag &= ~ECHO;
    tty.c_lflag &= ~ECHOE;
    tty.c_lflag &= ~ECHONL;
    tty.c_lflag &= ~ISIG;
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);

    tty.c_oflag &= ~OPOST;
    tty.c_oflag &= ~ONLCR;

    tty.c_cc[VTIME] = 1;
    tty.c_cc[VMIN] = 0;

    cfsetispeed(&tty, B115200);
    cfsetospeed(&tty, B115200);
    tcsetattr(_fd, TCSANOW, &tty);
  }
}

void RadioModuleConnector::start()
{
  _reader = new std::thread(readThreadProc, _fd, _streamParser);
  _reader->detach();
}

void RadioModuleConnector::stop()
{
}

void RadioModuleConnector::setFrameHandler(FrameHandler *frameHandler, bool decodeEscaped)
{
  _frameHandler = frameHandler;
  _streamParser->setDecodeEscaped(decodeEscaped);
}

void RadioModuleConnector::sendFrame(unsigned char *buffer, uint16_t len)
{
  write(_fd, buffer, len);
  fsync(_fd);
}

void RadioModuleConnector::_handleFrame(unsigned char *buffer, uint16_t len)
{
  FrameHandler *frameHandler = _frameHandler;

  if (frameHandler)
  {
    frameHandler->handleFrame(buffer, len);
  }
}


text:
require 'csv'
require 'json'
require 'optparse'
require 'socket'

help = <<-MSG

Usage: ./haproxy-stat [-b <backend-server>] [-c <current-server>] [-s <servers>] [-sock <socket file location>]

This script is a wrapper for parsing haproxy stats from its socket file.

Example usage:
./haproxy-stat -b hyperion -c titanium -s titanium,carbon

MSG

class HaproxyStat
  DEFAULT_SOCK = '/var/run/haproxy-stats.sock'

  attr_accessor :backend, :current_server, :servers, :socket

  def initialize(params = {})
    @backend = params[:backend]
    @current_server = params[:current_server]
    @servers = params[:servers]
    @socket = params[:socket] || DEFAULT_SOCK
  end

  def current_server_up?
    current_server_stats[0][:status] == 'UP'
  end

  def all_servers_up?
    all_server_stats.map { |s| s[:status] }.uniq == ['UP']
  end

  def some_servers_up?
    some_servers = servers - [current_server]

    backend_stats.
      select { |s| some_servers.include? s[:svname] }.
      map { |s| s[:status] }.
      uniq.
      include? 'UP'
  end

  private

  def current_server_stats
    backend_stats.select { |s| s[:svname] == current_server }
  end

  def all_server_stats
    backend_stats.select { |s| servers.include? s[:svname] }
  end

  def backend_stats
    @backend_stats ||= stats.select { |s| s[:_pxname] == backend && s[:_pxname] != 'BACKEND' }
  end

  def stats
    data = unixsock('show stat')
    csv = CSV.new(data, :headers => true, :header_converters => :symbol, :converters => :all)
    csv.to_a.map { |r| r.to_hash }
  end

  def unixsock(command)
    output = ''
    runs = 0

    begin
      ctl = UNIXSocket.open(socket)
      if ctl
        ctl.write "#{command}\r\n"
      else
        puts "cannot talk to #{socket}"
      end
    rescue Errno::EPIPE
      ctl.close
      sleep 0.5
      runs += 1
      if  runs < 4
        retry
      else
        puts "the unix socket at #{socket} closed before we could complete this request"
        exit 2
      end
    end
    while (line = ctl.gets)
      unless line =~ /Unknown command/
        output << line
      end
    end
    ctl.close

    output
  end
end

options = {
  :backend => nil,
  :current_server => nil,
  :servers => [],
  :socket => HaproxyStat::DEFAULT_SOCK
}

optparse = OptionParser.new do |opts|
  opts.banner = help

  opts.on('--backend=BACKEND', 'Haproxy backend server' ) do |backend|
    options[:backend] = backend
  end

  opts.on('--current-server=CURRENT_SERVER', 'Haproxy current server' ) do |server|
    options[:current_server] = server
  end

  opts.on('--servers=[x,y,z]', Array, 'Haproxy list of servers' ) do |servers|
    options[:servers] = servers
  end

  opts.on('--sock=SOCKET', 'Haproxy socket file') do |socket|
    options[:socket] = socket
  end

  opts.on( '-h', '--help', 'Display this screen' ) do
    puts opts
    exit
  end
end

optparse.parse!

unless options[:backend] && !options[:backend].empty?
  STDERR.print "ERROR: Missing argument for backend."
  exit 2
end

unless options[:current_server] && !options[:current_server].empty?
  STDERR.print "ERROR: Missing argument for current_server."
  exit 2
end

unless options[:servers] && options[:servers].any?
  STDERR.print "ERROR: Missing argument for servers."
  exit 2
end

haproxy_stat = HaproxyStat.new(options)

results = {
  current_server: haproxy_stat.current_server_up?,
  all_servers_up: haproxy_stat.all_servers_up?,
  some_servers_up: haproxy_stat.some_servers_up?
}

if haproxy_stat.all_servers_up? || haproxy_stat.some_servers_up?
  results[:msg] = 'READY'
  results[:ready] = true
  STDOUT.print results.to_json
  exit
else
  results[:msg] = 'NOT READY'
  results[:ready] = false
  STDERR.print results.to_json
  exit 1
end


text:
.class Lcom/android/internal/telephony/IccSmsInterfaceManager$1;
.super Landroid/os/Handler;
.source "IccSmsInterfaceManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/telephony/IccSmsInterfaceManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

# direct methods
.method constructor <init>(Lcom/android/internal/telephony/IccSmsInterfaceManager;)V
    .locals 0
    .param p1, "this$0"    # Lcom/android/internal/telephony/IccSmsInterfaceManager;

    .prologue
    .line 86
    iput-object p1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    invoke-direct {p0}, Landroid/os/Handler;-><init>()V

    return-void
.end method

# virtual methods
.method public handleMessage(Landroid/os/Message;)V
    .locals 6
    .param p1, "msg"    # Landroid/os/Message;

    .prologue
    const/4 v1, 0x1

    const/4 v2, 0x0

    .line 91
    iget v3, p1, Landroid/os/Message;->what:I

    packed-switch v3, :pswitch_data_0

    .line 88
    :goto_0
    return-void

    .line 93
    :pswitch_0
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Landroid/os/AsyncResult;

    .line 94
    .local v0, "ar":Landroid/os/AsyncResult;
    iget-object v3, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v3, v3, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    monitor-enter v3

    .line 95
    :try_start_0
    iget-object v4, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v5, v0, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-nez v5, :cond_0

    :goto_1
    iput-boolean v1, v4, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mSuccess:Z

    .line 96
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v1, v1, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    invoke-virtual {v1}, Ljava/lang/Object;->notifyAll()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :goto_2
    monitor-exit v3

    goto :goto_0

    :cond_0
    move v1, v2

    .line 95
    goto :goto_1

    .line 94
    :catchall_0
    move-exception v1

    monitor-exit v3

    throw v1

    .line 100
    .end local v0    # "ar":Landroid/os/AsyncResult;
    :pswitch_1
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Landroid/os/AsyncResult;

    .line 101
    .restart local v0    # "ar":Landroid/os/AsyncResult;
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v2, v1, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    monitor-enter v2

    .line 102
    :try_start_1
    iget-object v1, v0, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-nez v1, :cond_2

    .line 103
    iget-object v3, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v4, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v1, v0, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v1, Ljava/util/ArrayList;

    invoke-virtual {v4, v1}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->buildValidRawData(Ljava/util/ArrayList;)Ljava/util/ArrayList;

    move-result-object v1

    invoke-static {v3, v1}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->-set0(Lcom/android/internal/telephony/IccSmsInterfaceManager;Ljava/util/List;)Ljava/util/List;

    .line 105
    iget-object v3, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v1, v0, Landroid/os/AsyncResult;->result:Ljava/lang/Object;

    check-cast v1, Ljava/util/ArrayList;

    invoke-virtual {v3, v1}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->markMessagesAsRead(Ljava/util/ArrayList;)V

    .line 113
    :cond_1
    :goto_3
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v1, v1, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    invoke-virtual {v1}, Ljava/lang/Object;->notifyAll()V
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_1

    monitor-exit v2

    goto :goto_0

    .line 107
    :cond_2
    :try_start_2
    const-string/jumbo v1, "SMS"

    const/4 v3, 0x3

    invoke-static {v1, v3}, Landroid/telephony/Rlog;->isLoggable(Ljava/lang/String;I)Z

    move-result v1

    if-eqz v1, :cond_3

    .line 108
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    const-string/jumbo v3, "Cannot load Sms records"

    invoke-virtual {v1, v3}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->log(Ljava/lang/String;)V

    .line 110
    :cond_3
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    invoke-static {v1}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->-get0(Lcom/android/internal/telephony/IccSmsInterfaceManager;)Ljava/util/List;

    move-result-object v1

    if-eqz v1, :cond_1

    .line 111
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    invoke-static {v1}, Lcom/android/internal/telephony/IccSmsInterfaceManager;->-get0(Lcom/android/internal/telephony/IccSmsInterfaceManager;)Ljava/util/List;

    move-result-object v1

    invoke-interface {v1}, Ljava/util/List;->clear()V
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_1

    goto :goto_3

    .line 101
    :catchall_1
    move-exception v1

    monitor-exit v2

    throw v1

    .line 118
    .end local v0    # "ar":Landroid/os/AsyncResult;
    :pswitch_2
    iget-object v0, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v0, Landroid/os/AsyncResult;

    .line 119
    .restart local v0    # "ar":Landroid/os/AsyncResult;
    iget-object v3, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v3, v3, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    monitor-enter v3

    .line 120
    :try_start_3
    iget-object v4, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v5, v0, Landroid/os/AsyncResult;->exception:Ljava/lang/Throwable;

    if-nez v5, :cond_4

    :goto_4
    iput-boolean v1, v4, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mSuccess:Z

    .line 121
    iget-object v1, p0, Lcom/android/internal/telephony/IccSmsInterfaceManager$1;->this$0:Lcom/android/internal/telephony/IccSmsInterfaceManager;

    iget-object v1, v1, Lcom/android/internal/telephony/IccSmsInterfaceManager;->mLock:Ljava/lang/Object;

    invoke-virtual {v1}, Ljava/lang/Object;->notifyAll()V
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_2

    goto :goto_2

    .line 119
    :catchall_2
    move-exception v1

    monitor-exit v3

    throw v1

    :cond_4
    move v1, v2

    .line 120
    goto :goto_4

    .line 91
    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_1
        :pswitch_0
        :pswitch_2
        :pswitch_2
    .end packed-switch
.end method


text:
package com.wiley.elements.conditions.element;

import com.wiley.elements.TeasyElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;

import javax.annotation.Nullable;

public class ElementHasAttribute implements ExpectedCondition<Boolean> {

    private final TeasyElement el;
    private final String attrName;

    public ElementHasAttribute(TeasyElement el, String attrName) {
        this.el = el;
        this.attrName = attrName;
    }

    @Nullable
    @Override
    public Boolean apply(@Nullable WebDriver driver) {
        return el.getAttribute(attrName) != null;
    }

    @Override
    public String toString() {
        return String.format("Element '%s' does not have attribute '%s'!",
                el.toString(), attrName);
    }
}


text:
<?php namespace Mfn\Laravel\ViewObj;

use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;

class Provider extends ServiceProvider
{
    /**
     *
     */
    public function boot()
    {
        $this->publishes([$this->configPath() => config_path('view-obj.php')]);

        /** @var BladeCompiler $blade */
        $blade = $this
            ->app
            ->make('view')
            ->getEngineResolver()
            ->resolve('blade')
            ->getCompiler();

        $blade->directive('view_obj', function ($expression) {
            return "<?php echo view_obj{$expression}->render(); ?>";
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom($this->configPath(), 'view-obj');

        $this->app->singleton(ViewObj::class);
    }

    /**
     * @return string
     */
    public function configPath()
    {
        return __DIR__ . '/../config/view-obj.php';
    }
}


text:
from django.conf.urls.defaults import url, patterns

# a Noop "view"
override_view = lambda *args, **kwargs: None

urlpatterns = patterns('',
    url(
        r'/view1',
        'override_view',
        name='view1',
    ),
)


text:
"""Copyright (C) 2021-2022 Advanced Micro Devices, Inc. All rights reserved.

   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 cop-
   ies 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 IM-
   PLIED, 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 CONNE-
   CTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""

import re
import sys
import os
import platform
import subprocess
import argparse
import pathlib
from xml.dom import minidom
from fnmatch import fnmatchcase

SCRIPT_VERSION = 0.1

args = {}
param = {}
OS_info = {}
var_subs = {}

vcpkg_script = [ 'mkdir %IDIR%', 'cd %IDIR%', 'tdir %IDIR%\\vcpkg',
                'git clone -b 2022.05.10 https://github.com/microsoft/vcpkg', 'cd vcpkg', 'bootstrap-vcpkg.bat -disableMetrics' ]

xml_script = [ 'cd %IDIR%', '%XML%' ]

def parse_args():
    """Parse command-line arguments"""
    parser = argparse.ArgumentParser(description="""
    Checks build arguments
    """)
    # parser.add_argument('--install', required=False, default = True,  action='store_true',
    #                     help='Install dependencies (optional, default: True)')
    parser.add_argument('-i', '--install_dir', type=str, required=False, default = ("C:\\github" if os.name == "nt" else "./build/deps"),
                        help='Install directory path (optional, default: C:\\github)')
    # parser.add_argument('-v', '--verbose', required=False, default = False, action='store_true',
    #                     help='Verbose install (optional, default: False)')
    return parser.parse_args()

def os_detect():
    global OS_info
    if os.name == "nt":
        OS_info["ID"] = platform.system()
    else:
        inf_file = "/etc/os-release"
        if os.path.exists(inf_file):
            with open(inf_file) as f:
                for line in f:
                    if "=" in line:
                        k,v = line.strip().split("=")
                        OS_info[k] = v.replace('"','')
    OS_info["NUM_PROC"] = os.cpu_count()
    print(OS_info)

def create_dir(dir_path):
    if os.path.isabs(dir_path):
        full_path = dir_path
    else:
        full_path = os.path.join( os.getcwd(), dir_path )
    return pathlib.Path(full_path).mkdir(parents=True, exist_ok=True)

def delete_dir(dir_path) :
    if (not os.path.exists(dir_path)):
        return
    if os.name == "nt":
        return run_cmd( "RMDIR" , f"/S /Q {dir_path}")
    else:
        linux_path = pathlib.Path(dir_path).absolute()
        return run_cmd( "rm" , f"-rf {linux_path}")

def run_cmd(cmd):
    global args
    if (cmd.startswith('cd ')):
        return os.chdir(cmd[3:])
    if (cmd.startswith('mkdir ')):
        return create_dir(cmd[6:])
    cmdline = f"{cmd}"
    print(cmdline)
    proc = subprocess.run(cmdline, check=True, stderr=subprocess.STDOUT, shell=True)
    return proc.returncode

def install_deps( os_node ):
    global var_subs

    if os.name == "nt":
        vc_node = os_node.getElementsByTagName('vcpkg')
        if vc_node:
            cwd = pathlib.os.curdir
            cmdline = "cd %IDIR%\\vcpkg"
            cd_vcpkg = cmdline.replace('%IDIR%', args.install_dir)
            run_cmd(cd_vcpkg)
            for p in vc_node[0].getElementsByTagName('pkg'):
                name = p.getAttribute('name')
                package = p.firstChild.data
                if name:
                    print( f'***\n*** VCPKG Installing: {name}\n***' )
                raw_cmd = p.firstChild.data
                var_cmd = raw_cmd.format_map(var_subs)
                error = run_cmd( f'vcpkg.exe install {var_cmd}')
            os.chdir(cwd)
    else:
        cwd = pathlib.os.curdir
        create_dir( args.install_dir )
        # TODO
        os.chdir( cwd )

    pip_node = os_node.getElementsByTagName('pip')
    if pip_node:
        for p in pip_node[0].getElementsByTagName('pkg'):
            name = p.getAttribute('name')
            package = p.firstChild.data
            if name:
                print( f'***\n*** Pip Installing: {name}\n***' )
            raw_cmd = p.firstChild.data
            var_cmd = raw_cmd.format_map(var_subs)
            error = run_cmd( f'pip install {var_cmd}')

def run_install_script(script, xml):
    '''executes a simple batch style install script, the scripts are defined at top of file'''
    global OS_info
    global args
    global var_subs
    #
    cwd = pathlib.os.curdir

    fail = False
    for i in range(len(script)):
        cmdline = script[i]
        cmd = cmdline.replace('%IDIR%', args.install_dir)
        if cmd.startswith('tdir '):
            if pathlib.Path(cmd[5:]).exists():
                return 0 # all further cmds skipped
            else:
                continue
        error = False
        if cmd.startswith('%XML%'):
            fileversion = xml.getElementsByTagName('fileversion')
            if len(fileversion) == 0:
                print("WARNING: Could not find the version of this xml configuration file.")
            elif len(fileversion) > 1:
                print("WARNING: Multiple version tags found.")
            else:
                version = float(fileversion[0].firstChild.data)
                if version > SCRIPT_VERSION:
                    print(f"ERROR: This xml requires script version >= {version}, running script version {SCRIPT_VERSION}")
                    exit(1)

            for var in xml.getElementsByTagName('var'):
                name = var.getAttribute('name')
                if var.hasAttribute('value'):
                    val = var.getAttribute('value')
                elif var.firstChild is not None:
                    val = var.firstChild.data
                else:
                    val = ""
                var_subs[name] = val

            for os_node in xml.getElementsByTagName('os'):
                os_names = os_node.getAttribute('names')
                os_list = os_names.split(',')
                if (OS_info['ID'] in os_list) or ("all" in os_list):
                    error = install_deps( os_node )
        else:
            error = run_cmd(cmd)
        fail = fail or error

    if (fail):
        if (cmd == "%XML%"):
            print(f"FAILED xml dependency installation!")
        else:
            print(f"ERROR running: {cmd}")
        if (os.curdir != cwd):
            os.chdir( cwd )
        return 1
    if (os.curdir != cwd):
        os.chdir( cwd )
    return 0

def installation():
    global vcpkg_script
    global xml_script
    global xmlDoc

    # install
    cwd = os.curdir

    xmlPath = os.path.join( cwd, 'rdeps.xml')
    xmlDoc = minidom.parse( xmlPath )

    scripts = []

    if os.name == "nt" and xmlDoc.getElementsByTagName('vcpkg'):
        scripts.append( vcpkg_script )
    scripts.append( xml_script )

    for i in scripts:
        if (run_install_script(i, xmlDoc)):
            #print("Failure in script. ABORTING")
            if (os.curdir != cwd):
                os.chdir( cwd )
            return 1
    if (os.curdir != cwd):
        os.chdir( cwd )
    return 0

def main():
    global args

    os_detect()
    args = parse_args()

    installation()

if __name__ == '__main__':
    main()


text:
package org.appfuse.model;

import java.util.Date;

public class Robot extends BaseObject {
	private static final long serialVersionUID = 2585185402614849107L;

	private Long id;
	private String designation;
	private Date dateOfBuild;
	private Boolean qualityCheckPassed;
	private User owner;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getDesignation() {
		return designation;
	}

	public void setDesignation(String designation) {
		this.designation = designation;
	}

	public Date getDateOfBuild() {
		return dateOfBuild;
	}

	public void setDateOfBuild(Date dateOfBuild) {
		this.dateOfBuild = dateOfBuild;
	}

	public Boolean getQualityCheckPassed() {
		return qualityCheckPassed;
	}

	public void setQualityCheckPassed(Boolean qualityCheckPassed) {
		this.qualityCheckPassed = qualityCheckPassed;
	}

	public User getOwner() {
		return owner;
	}

	public void setOwner(User owner) {
		this.owner = owner;
	}
}


text:
<?php

use Phinx\Migration\AbstractMigration;
use Cake\Auth\DefaultPasswordHasher;

class UsersSeed extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function up()
    {
		$faker = \Faker\Factory::create();
		$populator = new Faker\ORM\CakePHP\Populator($faker);

		$populator->addEntity('Users', 1, [
			'username' => 'super',
			'group_id' => 1,
			'password' => function (){
				$hasher = new DefaultPasswordHasher();
				return $hasher->hash('super');
			},
			'created' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			},
			'modified' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			}
		]);
		$populator->execute();

		$populator->addEntity('Users', 1, [
			'username' => 'admin',
			'group_id' => 2,
			'password' => function (){
				$hasher = new DefaultPasswordHasher();
				return $hasher->hash('admin');
			},
			'created' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			},
			'modified' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			}
		]);
		$populator->execute();

		$populator->addEntity('Users', 1, [
			'username' => 'manager',
			'group_id' => 3,
			'password' => function (){
				$hasher = new DefaultPasswordHasher();
				return $hasher->hash('manager');
			},
			'created' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			},
			'modified' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			}
		]);
		$populator->execute();

		$populator->addEntity('Users', 1, [
			'username' => 'user',
			'group_id' => 4,
			'password' => function (){
				$hasher = new DefaultPasswordHasher();
				return $hasher->hash('user');
			},
			'created' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			},
			'modified' => function() use ($faker) {
				return $faker->dateTimeBetween($startDate = 'now', $endDate = 'now');
			}
		]);
		$populator->execute();
    }
}