text:
using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Reflection;
using System.Text;

namespace Orleans.Runtime
{
    /// <summary>
    /// Formats values for logging purposes.
    /// </summary>
    public static class LogFormatter
    {
        public const int MAX_LOG_MESSAGE_SIZE = 20000;
        private const string TIME_FORMAT = "HH:mm:ss.fff 'GMT'"; // Example: 09:50:43.341 GMT
        private const string DATE_FORMAT = "yyyy-MM-dd " + TIME_FORMAT; // Example: 2010-09-02 09:50:43.341 GMT - Variant of UniversalSortableDateTimePattern
        private static readonly ConcurrentDictionary<Type, Func<Exception, string>> exceptionDecoders = new ConcurrentDictionary<Type, Func<Exception, string>>();

        /// <summary>
        /// Utility function to convert a <c>DateTime</c> object into printable data format used by the Logger subsystem.
        /// </summary>
        /// <param name="date">The <c>DateTime</c> value to be printed.</param>
        /// <returns>Formatted string representation of the input data, in the printable format used by the Logger subsystem.</returns>
        public static string PrintDate(DateTime date)
        {
            return date.ToString(DATE_FORMAT, CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Parses a date.
        /// </summary>
        /// <param name="dateStr">The date string.</param>
        /// <returns>The parsed date.</returns>
        public static DateTime ParseDate(string dateStr)
        {
            return DateTime.ParseExact(dateStr, DATE_FORMAT, CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Utility function to convert a <c>DateTime</c> object into printable time format used by the Logger subsystem.
        /// </summary>
        /// <param name="date">The <c>DateTime</c> value to be printed.</param>
        /// <returns>Formatted string representation of the input data, in the printable format used by the Logger subsystem.</returns>
        public static string PrintTime(DateTime date)
        {
            return date.ToString(TIME_FORMAT, CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Utility function to convert an exception into printable format, including expanding and formatting any nested sub-expressions.
        /// </summary>
        /// <param name="exception">The exception to be printed.</param>
        /// <returns>Formatted string representation of the exception, including expanding and formatting any nested sub-expressions.</returns>
        public static string PrintException(Exception exception)
        {
            return exception == null ? String.Empty : PrintException_Helper(exception, 0, true);
        }

        /// <summary>
        /// Configures the exception decoder for the specified exception type.
        /// </summary>
        /// <param name="exceptionType">The exception type to configure a decoder for.</param>
        /// <param name="decoder">The decoder.</param>
        public static void SetExceptionDecoder(Type exceptionType, Func<Exception, string> decoder)
        {
            exceptionDecoders.TryAdd(exceptionType, decoder);
        }

        private static string PrintException_Helper(Exception exception, int level, bool includeStackTrace)
        {
            if (exception == null) return String.Empty;
            var sb = new StringBuilder();
            sb.Append(PrintOneException(exception, level, includeStackTrace));
            if (exception is ReflectionTypeLoadException)
            {
                Exception[] loaderExceptions =
                    ((ReflectionTypeLoadException)exception).LoaderExceptions;
                if (loaderExceptions == null || loaderExceptions.Length == 0)
                {
                    sb.Append("No LoaderExceptions found");
                }
                else
                {
                    foreach (Exception inner in loaderExceptions)
                    {
                        // call recursively on all loader exceptions. Same level for all.
                        sb.Append(PrintException_Helper(inner, level + 1, includeStackTrace));
                    }
                }
            }
            else if (exception is AggregateException)
            {
                var innerExceptions = ((AggregateException)exception).InnerExceptions;
                if (innerExceptions == null) return sb.ToString();

                foreach (Exception inner in innerExceptions)
                {
                    // call recursively on all inner exceptions. Same level for all.
                    sb.Append(PrintException_Helper(inner, level + 1, includeStackTrace));
                }
            }
            else if (exception.InnerException != null)
            {
                // call recursively on a single inner exception.
                sb.Append(PrintException_Helper(exception.InnerException, level + 1, includeStackTrace));
            }
            return sb.ToString();
        }

        private static string PrintOneException(Exception exception, int level, bool includeStackTrace)
        {
            if (exception == null) return String.Empty;
            string stack = String.Empty;
            if (includeStackTrace && exception.StackTrace != null)
                stack = String.Format(Environment.NewLine + exception.StackTrace);

            string message = exception.Message;
            var excType = exception.GetType();

            Func<Exception, string> decoder;
            if (exceptionDecoders.TryGetValue(excType, out decoder))
                message = decoder(exception);

            return String.Format(Environment.NewLine + "Exc level {0}: {1}: {2}{3}",
                level,
                exception.GetType(),
                message,
                stack);
        }
    }
}


text:
require 'mimemagic'
require 'opium/model/connectable'

module Opium
  class File
    include Opium::Model::Connectable

    no_object_prefix!

    class << self
      def model_name
        @model_name ||= ActiveModel::Name.new( self )
      end

      def upload( file, options = {} )
        request_options = build_request_options( file, options )
        attributes = send( :http, :post, request_options ) do |request|
          request.body = Faraday::UploadIO.new( file, request_options[:headers][:content_type] )
        end
        options[:sent_headers] ? attributes : new(attributes)
      end

      def to_ruby( object )
        return if object.nil? || object == ''
        return object if object.is_a?( self )
        object = ::JSON.parse( object ) if object.is_a?( String )
        if object.is_a?( Hash ) && (has_key_of_value( object, :__type, 'File' ) || has_keys( object, :url, :name ))
          new( object )
        else
          fail ArgumentError, "could not convert #{ object.inspect } to an Opium::File"
        end
      end

      def to_parse( object )
        return unless object
        fail ArgumentError, "could not convert #{ object.inspect } to a Parse File object" unless object.is_a?( self ) && object.name
        {
          __type: 'File',
          name: object.name
        }.with_indifferent_access
      end

      private

      # Note that MimeMagic returns application/zip for the more recent MS Office file types,
      # hence the extra check.
      def build_request_options( file, options )
        {}.tap do |result|
          mime_type = options.fetch( :content_type, MimeMagic.by_magic(file) )
          mime_type = MimeMagic.by_path(file) if mime_type == 'application/zip'
          result[:id] = parameterize_name( options[:original_filename] || ::File.basename( file ) )
          result[:headers] = { content_type: mime_type.to_s, content_length: file.size.to_s }
          result[:sent_headers] = options[:sent_headers] if options.key? :sent_headers
        end
      end

      def has_key_of_value( object, key, value )
        (object[key] || object[key.to_s]) == value
      end

      def has_keys( object, *keys )
        object.keys.all? {|key| keys.include?( key.to_s ) || keys.include?( key.to_sym )}
      end

      def parameterize_name( name )
        without_extension, extension = ::File.basename( name, '.*' ), ::File.extname( name )
        without_extension.parameterize + extension
      end
    end

    def initialize( attributes = {} )
      attributes.with_indifferent_access.each do |k, v|
        send( :"#{k}=", v ) unless k == '__type'
      end
    end

    def delete( options = {} )
      fail "cannot delete #{ self.inspect }, as there is no name" unless self.name
      self.class.with_heightened_privileges do
        self.class.http_delete self.name, options
      end.tap { self.freeze }
    end

    attr_reader :name, :url

    def mime_type
      @mime_type ||= MimeMagic.by_path( url ) if url
    end

    def inspect
      "#<#{ self.class.model_name.name } name=#{ name.inspect } url=#{ url.inspect } mime_type=#{ (mime_type ? mime_type.type : nil).inspect }>"
    end

    def to_parse
      self.class.to_parse( self )
    end

    private

    attr_writer :name, :url
  end
end

redpajama_set_name: RedPajamaGithub


text:
package ksl.lab.compass;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import com.google.android.gms.location.LocationListener;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;

import ksl.lab.compass.service.LocationServiceAdapter;
import ksl.lab.compass.util.LocationUtils;

public class CommActivity extends AppCompatActivity {

    // This is used for logCat filtering
    private static final String TAG = "COMM_ACTIVITY";

    private EditText clientText;
    private EditText commText;
    private EditText serverAddress;
    private Button sendButton;
    private Button loginButton;

    private WebSocketClient conn;
    private LocationServiceAdapter locationService;
    private LocationListener locationListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comm);
        Toolbar toolbar = (Toolbar) findViewById(R.id.comm_toolbar);
        setSupportActionBar(toolbar);

        // Server Connection View
        serverAddress = (EditText) findViewById(R.id.address);
        serverAddress.setText(R.string.default_server);

        // Client View
        clientText = (EditText) findViewById(R.id.client_text);
        commText = (EditText) findViewById(R.id.comm_text);
        commText.setMovementMethod(ScrollingMovementMethod.getInstance());
        sendButton = (Button) findViewById(R.id.send_button);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send(clientText.getText().toString());
                clientText.setText("");
            }
        });

        Switch serverSwitch = (Switch) findViewById(R.id.login_switch);
        serverSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    login();
                } else {
                    login();
                }
            }
        });

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                // print(LocationUtils.toString(location));
                send(location);
            }
        };

        locationService = new LocationServiceAdapter(this, locationListener);
        locationService.loadInstanceState(savedInstanceState);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_comm, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_nav_compass:
                //Code to run when the Create Order item is clicked
                startActivity(new Intent(this, CompassActivity.class));
                return true;

            case R.id.action_gps_toggle:
                if (locationService.isUpdateEnabled()) {
                    locationService.stopLocationUpdates(locationListener);
                    locationService.setUpdateEnabled(false);
                    Toast.makeText(this,
                        getResources().getString(R.string.location_update_stop),
                        Toast.LENGTH_LONG).show();
                } else {
                    locationService.startLocationUpdates(locationListener);
                    locationService.setUpdateEnabled(true);
                    Toast.makeText(this,
                        getResources().getString(R.string.location_update_start),
                        Toast.LENGTH_LONG).show();
                }
                return true;

            case R.id.action_settings:
                //Code to run when the settings item is clicked
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void send(Location location) {
        if (conn != null && conn.getConnection().isOpen()) {
            conn.send(LocationUtils.toShortString(location));
            send("Track sent to server.");
        } else {
            commText.append("Connection is inactive" + System.lineSeparator());
        }
    }

    /**
     * Sends a message/data to the server.
     * The current server implementation effectively broadcasts this message to all connected clients.
     */
    private void send(String message) {
        if (conn != null && conn.getConnection().isOpen()) {
            conn.send(message);
        } else {
            commText.append("Connection is inactive" + System.lineSeparator());
        }
    }

    /**
     * Connects the user to the server.
     * Authentication tbd
     */
    private void login() {

        if (conn != null) {
            if (conn.getConnection().isOpen()) {
                print("Disconnecting...");
                conn.close();
                return;
            }
        }

        URI uri = null;
        try {
            uri = new URI(serverAddress.getText().toString());
        } catch (Exception e) {
            Snackbar.make(
                    serverAddress,
                    e.getMessage(),
                    Snackbar.LENGTH_INDEFINITE);
        }

        if (uri == null) return;

        // Create the connection
        conn = new WSClient(uri);
        conn.connect();

        locationService.startLocationUpdates(locationListener);
    }

    /**
     * Prints the specified message to the main comm view.
     * This can be invoked from a background thread.
     * @param message the message to be displayed
     */
    private void print(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                commText.append(message + System.lineSeparator());
                commText.setSelection(commText.getText().length());
            }
        });
    }

    /**
     * Starts all services including intensive API connections such as Google Services
     * @Flow: Activity
     */
    @Override
    protected void onStart() {
        super.onStart();
        locationService.start();
    }

    /**
     * Stop all services, including intensive API connections such as such as Google Services
     * @Flow: Activity
     */
    @Override
    protected void onStop() {
        locationService.stop();
        super.onStop();
    }

    @Override
    protected void onResume(){
        super.onResume();
        locationService.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationService.resume();
    }

    @Override
    protected void onSaveInstanceState(Bundle currentState) {
        super.onSaveInstanceState(currentState);
        locationService.saveInstanceState(currentState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedState) {
        super.onSaveInstanceState(savedState);
        locationService.loadInstanceState(savedState);
    }

    /**
     * Web Socket client
     * Connects to the server using the specified address and
     * DRAFT 17 of the WebSocket specification.
     *
     * Current implementation echoes the message/data sent from clients.
     * Goal is to process information and update compass/waypoint as applicable
     */
    private class WSClient extends WebSocketClient {

        /**
         * Create a new WebSocket client using the specified address.
         * Using WebSocket draft 17
         *
         * @param address the server websocket address. Protocol starts with ws://
         * @see Draft_17
         */
        public WSClient(URI address) {
            super(address, new Draft_17());
        }

        @Override
        public void onOpen(ServerHandshake handshake) {
            print("Connection established.");
        }

        @Override
        public void onMessage(final String message) {
            print(message);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            print("Connection closed.");
        }

        @Override
        public void onError(final Exception ex) {
            print("Error: " + ex.getMessage());
        }
    }
}


text:
namespace math
{

class random
{
public:

	random();
	random(size_t seed);

	// returns an int [0..INT_MAX]
	virtual int Next();

	// returns an int [0..max]
	virtual int Next(int max);

	// returns an int [min..max]
	virtual int Next(int min, int max);

	// returns a double [0..1)
	virtual double NextDouble();

	// returns a random number [0..1)
	virtual double Sample();

private:

	size_t SampleInternal();
	double SampleForLargeRange();

	size_t m_seedArray[56];
	size_t m_inext;
	size_t m_inextp;

};

} // math


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>uk.nhs.ciao</groupId>
  <artifactId>ciao-docs-transformer</artifactId>
  <versioning>
    <release>0.1</release>
    <versions>
      <version>0.1</version>
    </versions>
    <lastUpdated>20160304164506</lastUpdated>
  </versioning>
</metadata>


text:
from swgpy.object import *

def create(kernel):
	result = Tangible()

	result.template = "object/tangible/wearables/dress/shared_dress_s10.iff"
	result.attribute_template_id = 11
	result.stfName("wearables_name","dress_s10")

	#### BEGIN MODIFICATIONS ####
	####  END MODIFICATIONS  ####

	return result


text:
namespace Ui{
	class page_main;
};

class page_main : public PageWidget{
	Q_OBJECT
public:
	page_main(QWidget *parent);
	~page_main();

	virtual void setPreviousPage(QString id);
	void clearlineEdit();

public slots:
	void SaveSettings();
	void LoadSettings(int screennum = -1);
	void updateIcons();

private:
	Ui::page_main *ui;
	QList<PAGEINFO> INFO;
	QShortcut *findShort;
	void UpdateItems(QString search);

private slots:
	void showFind();
	void itemTriggered(QTreeWidgetItem*, int);
	void searchChanged(QString);
};
#endif


text: {% extends "v12/online_licence/reg/email_val/give_email.html" %}


text:
using System.Web.Mvc;
using System.Web.Routing;

namespace BackBox.Api
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}


text:
struct alloc_stat;
typedef int (*sort_fn_t)(struct alloc_stat *, struct alloc_stat *);

static int			alloc_flag;
static int			caller_flag;

static int			alloc_lines = -1;
static int			caller_lines = -1;

static bool			raw_ip;

static int			*cpunode_map;
static int			max_cpu_num;

struct alloc_stat {
	u64	call_site;
	u64	ptr;
	u64	bytes_req;
	u64	bytes_alloc;
	u32	hit;
	u32	pingpong;

	short	alloc_cpu;

	struct rb_node node;
};

static struct rb_root root_alloc_stat;
static struct rb_root root_alloc_sorted;
static struct rb_root root_caller_stat;
static struct rb_root root_caller_sorted;

static unsigned long total_requested, total_allocated;
static unsigned long nr_allocs, nr_cross_allocs;

#define PATH_SYS_NODE	"/sys/devices/system/node"

static int init_cpunode_map(void)
{
	FILE *fp;
	int i, err = -1;

	fp = fopen("/sys/devices/system/cpu/kernel_max", "r");
	if (!fp) {
		max_cpu_num = 4096;
		return 0;
	}

	if (fscanf(fp, "%d", &max_cpu_num) < 1) {
		pr_err("Failed to read 'kernel_max' from sysfs");
		goto out_close;
	}

	max_cpu_num++;

	cpunode_map = calloc(max_cpu_num, sizeof(int));
	if (!cpunode_map) {
		pr_err("%s: calloc failed\n", __func__);
		goto out_close;
	}

	for (i = 0; i < max_cpu_num; i++)
		cpunode_map[i] = -1;

	err = 0;
out_close:
	fclose(fp);
	return err;
}

static int setup_cpunode_map(void)
{
	struct dirent *dent1, *dent2;
	DIR *dir1, *dir2;
	unsigned int cpu, mem;
	char buf[PATH_MAX];

	if (init_cpunode_map())
		return -1;

	dir1 = opendir(PATH_SYS_NODE);
	if (!dir1)
		return -1;

	while ((dent1 = readdir(dir1)) != NULL) {
		if (dent1->d_type != DT_DIR ||
		    sscanf(dent1->d_name, "node%u", &mem) < 1)
			continue;

		snprintf(buf, PATH_MAX, "%s/%s", PATH_SYS_NODE, dent1->d_name);
		dir2 = opendir(buf);
		if (!dir2)
			continue;
		while ((dent2 = readdir(dir2)) != NULL) {
			if (dent2->d_type != DT_LNK ||
			    sscanf(dent2->d_name, "cpu%u", &cpu) < 1)
				continue;
			cpunode_map[cpu] = mem;
		}
		closedir(dir2);
	}
	closedir(dir1);
	return 0;
}

static int insert_alloc_stat(unsigned long call_site, unsigned long ptr,
			     int bytes_req, int bytes_alloc, int cpu)
{
	struct rb_node **node = &root_alloc_stat.rb_node;
	struct rb_node *parent = NULL;
	struct alloc_stat *data = NULL;

	while (*node) {
		parent = *node;
		data = rb_entry(*node, struct alloc_stat, node);

		if (ptr > data->ptr)
			node = &(*node)->rb_right;
		else if (ptr < data->ptr)
			node = &(*node)->rb_left;
		else
			break;
	}

	if (data && data->ptr == ptr) {
		data->hit++;
		data->bytes_req += bytes_req;
		data->bytes_alloc += bytes_alloc;
	} else {
		data = malloc(sizeof(*data));
		if (!data) {
			pr_err("%s: malloc failed\n", __func__);
			return -1;
		}
		data->ptr = ptr;
		data->pingpong = 0;
		data->hit = 1;
		data->bytes_req = bytes_req;
		data->bytes_alloc = bytes_alloc;

		rb_link_node(&data->node, parent, node);
		rb_insert_color(&data->node, &root_alloc_stat);
	}
	data->call_site = call_site;
	data->alloc_cpu = cpu;
	return 0;
}

static int insert_caller_stat(unsigned long call_site,
			      int bytes_req, int bytes_alloc)
{
	struct rb_node **node = &root_caller_stat.rb_node;
	struct rb_node *parent = NULL;
	struct alloc_stat *data = NULL;

	while (*node) {
		parent = *node;
		data = rb_entry(*node, struct alloc_stat, node);

		if (call_site > data->call_site)
			node = &(*node)->rb_right;
		else if (call_site < data->call_site)
			node = &(*node)->rb_left;
		else
			break;
	}

	if (data && data->call_site == call_site) {
		data->hit++;
		data->bytes_req += bytes_req;
		data->bytes_alloc += bytes_alloc;
	} else {
		data = malloc(sizeof(*data));
		if (!data) {
			pr_err("%s: malloc failed\n", __func__);
			return -1;
		}
		data->call_site = call_site;
		data->pingpong = 0;
		data->hit = 1;
		data->bytes_req = bytes_req;
		data->bytes_alloc = bytes_alloc;

		rb_link_node(&data->node, parent, node);
		rb_insert_color(&data->node, &root_caller_stat);
	}

	return 0;
}

static int perf_evsel__process_alloc_event(struct perf_evsel *evsel,
					   struct perf_sample *sample)
{
	unsigned long ptr = perf_evsel__intval(evsel, sample, "ptr"),
		      call_site = perf_evsel__intval(evsel, sample, "call_site");
	int bytes_req = perf_evsel__intval(evsel, sample, "bytes_req"),
	    bytes_alloc = perf_evsel__intval(evsel, sample, "bytes_alloc");

	if (insert_alloc_stat(call_site, ptr, bytes_req, bytes_alloc, sample->cpu) ||
	    insert_caller_stat(call_site, bytes_req, bytes_alloc))
		return -1;

	total_requested += bytes_req;
	total_allocated += bytes_alloc;

	nr_allocs++;
	return 0;
}

static int perf_evsel__process_alloc_node_event(struct perf_evsel *evsel,
						struct perf_sample *sample)
{
	int ret = perf_evsel__process_alloc_event(evsel, sample);

	if (!ret) {
		int node1 = cpunode_map[sample->cpu],
		    node2 = perf_evsel__intval(evsel, sample, "node");

		if (node1 != node2)
			nr_cross_allocs++;
	}

	return ret;
}

static int ptr_cmp(struct alloc_stat *, struct alloc_stat *);
static int callsite_cmp(struct alloc_stat *, struct alloc_stat *);

static struct alloc_stat *search_alloc_stat(unsigned long ptr,
					    unsigned long call_site,
					    struct rb_root *root,
					    sort_fn_t sort_fn)
{
	struct rb_node *node = root->rb_node;
	struct alloc_stat key = { .ptr = ptr, .call_site = call_site };

	while (node) {
		struct alloc_stat *data;
		int cmp;

		data = rb_entry(node, struct alloc_stat, node);

		cmp = sort_fn(&key, data);
		if (cmp < 0)
			node = node->rb_left;
		else if (cmp > 0)
			node = node->rb_right;
		else
			return data;
	}
	return NULL;
}

static int perf_evsel__process_free_event(struct perf_evsel *evsel,
					  struct perf_sample *sample)
{
	unsigned long ptr = perf_evsel__intval(evsel, sample, "ptr");
	struct alloc_stat *s_alloc, *s_caller;

	s_alloc = search_alloc_stat(ptr, 0, &root_alloc_stat, ptr_cmp);
	if (!s_alloc)
		return 0;

	if ((short)sample->cpu != s_alloc->alloc_cpu) {
		s_alloc->pingpong++;

		s_caller = search_alloc_stat(0, s_alloc->call_site,
					     &root_caller_stat, callsite_cmp);
		if (!s_caller)
			return -1;
		s_caller->pingpong++;
	}
	s_alloc->alloc_cpu = -1;

	return 0;
}

typedef int (*tracepoint_handler)(struct perf_evsel *evsel,
				  struct perf_sample *sample);

static int process_sample_event(struct perf_tool *tool __maybe_unused,
				union perf_event *event,
				struct perf_sample *sample,
				struct perf_evsel *evsel,
				struct machine *machine)
{
	struct thread *thread = machine__findnew_thread(machine, event->ip.pid);

	if (thread == NULL) {
		pr_debug("problem processing %d event, skipping it.\n",
			 event->header.type);
		return -1;
	}

	dump_printf(" ... thread: %s:%d\n", thread->comm, thread->pid);

	if (evsel->handler.func != NULL) {
		tracepoint_handler f = evsel->handler.func;
		return f(evsel, sample);
	}

	return 0;
}

static struct perf_tool perf_kmem = {
	.sample		 = process_sample_event,
	.comm		 = perf_event__process_comm,
	.ordered_samples = true,
};

static double fragmentation(unsigned long n_req, unsigned long n_alloc)
{
	if (n_alloc == 0)
		return 0.0;
	else
		return 100.0 - (100.0 * n_req / n_alloc);
}

static void __print_result(struct rb_root *root, struct perf_session *session,
			   int n_lines, int is_caller)
{
	struct rb_node *next;
	struct machine *machine = &session->machines.host;

	printf("%.102s\n", graph_dotted_line);
	printf(" %-34s |",  is_caller ? "Callsite": "Alloc Ptr");
	printf(" Total_alloc/Per | Total_req/Per   | Hit      | Ping-pong | Frag\n");
	printf("%.102s\n", graph_dotted_line);

	next = rb_first(root);

	while (next && n_lines--) {
		struct alloc_stat *data = rb_entry(next, struct alloc_stat,
						   node);
		struct symbol *sym = NULL;
		struct map *map;
		char buf[BUFSIZ];
		u64 addr;

		if (is_caller) {
			addr = data->call_site;
			if (!raw_ip)
				sym = machine__find_kernel_function(machine, addr, &map, NULL);
		} else
			addr = data->ptr;

		if (sym != NULL)
			snprintf(buf, sizeof(buf), "%s+%" PRIx64 "", sym->name,
				 addr - map->unmap_ip(map, sym->start));
		else
			snprintf(buf, sizeof(buf), "%#" PRIx64 "", addr);
		printf(" %-34s |", buf);

		printf(" %9llu/%-5lu | %9llu/%-5lu | %8lu | %8lu | %6.3f%%\n",
		       (unsigned long long)data->bytes_alloc,
		       (unsigned long)data->bytes_alloc / data->hit,
		       (unsigned long long)data->bytes_req,
		       (unsigned long)data->bytes_req / data->hit,
		       (unsigned long)data->hit,
		       (unsigned long)data->pingpong,
		       fragmentation(data->bytes_req, data->bytes_alloc));

		next = rb_next(next);
	}

	if (n_lines == -1)
		printf(" ...                                | ...             | ...             | ...    | ...      | ...   \n");

	printf("%.102s\n", graph_dotted_line);
}

static void print_summary(void)
{
	printf("\nSUMMARY\n=======\n");
	printf("Total bytes requested: %lu\n", total_requested);
	printf("Total bytes allocated: %lu\n", total_allocated);
	printf("Total bytes wasted on internal fragmentation: %lu\n",
	       total_allocated - total_requested);
	printf("Internal fragmentation: %f%%\n",
	       fragmentation(total_requested, total_allocated));
	printf("Cross CPU allocations: %lu/%lu\n", nr_cross_allocs, nr_allocs);
}

static void print_result(struct perf_session *session)
{
	if (caller_flag)
		__print_result(&root_caller_sorted, session, caller_lines, 1);
	if (alloc_flag)
		__print_result(&root_alloc_sorted, session, alloc_lines, 0);
	print_summary();
}

struct sort_dimension {
	const char		name[20];
	sort_fn_t		cmp;
	struct list_head	list;
};

static LIST_HEAD(caller_sort);
static LIST_HEAD(alloc_sort);

static void sort_insert(struct rb_root *root, struct alloc_stat *data,
			struct list_head *sort_list)
{
	struct rb_node **new = &(root->rb_node);
	struct rb_node *parent = NULL;
	struct sort_dimension *sort;

	while (*new) {
		struct alloc_stat *this;
		int cmp = 0;

		this = rb_entry(*new, struct alloc_stat, node);
		parent = *new;

		list_for_each_entry(sort, sort_list, list) {
			cmp = sort->cmp(data, this);
			if (cmp)
				break;
		}

		if (cmp > 0)
			new = &((*new)->rb_left);
		else
			new = &((*new)->rb_right);
	}

	rb_link_node(&data->node, parent, new);
	rb_insert_color(&data->node, root);
}

static void __sort_result(struct rb_root *root, struct rb_root *root_sorted,
			  struct list_head *sort_list)
{
	struct rb_node *node;
	struct alloc_stat *data;

	for (;;) {
		node = rb_first(root);
		if (!node)
			break;

		rb_erase(node, root);
		data = rb_entry(node, struct alloc_stat, node);
		sort_insert(root_sorted, data, sort_list);
	}
}

static void sort_result(void)
{
	__sort_result(&root_alloc_stat, &root_alloc_sorted, &alloc_sort);
	__sort_result(&root_caller_stat, &root_caller_sorted, &caller_sort);
}

static int __cmd_kmem(void)
{
	int err = -EINVAL;
	struct perf_session *session;
	const struct perf_evsel_str_handler kmem_tracepoints[] = {
		{ "kmem:kmalloc",		perf_evsel__process_alloc_event, },
    		{ "kmem:kmem_cache_alloc",	perf_evsel__process_alloc_event, },
		{ "kmem:kmalloc_node",		perf_evsel__process_alloc_node_event, },
    		{ "kmem:kmem_cache_alloc_node", perf_evsel__process_alloc_node_event, },
		{ "kmem:kfree",			perf_evsel__process_free_event, },
    		{ "kmem:kmem_cache_free",	perf_evsel__process_free_event, },
	};

	session = perf_session__new(input_name, O_RDONLY, 0, false, &perf_kmem);
	if (session == NULL)
		return -ENOMEM;

	if (perf_session__create_kernel_maps(session) < 0)
		goto out_delete;

	if (!perf_session__has_traces(session, "kmem record"))
		goto out_delete;

	if (perf_session__set_tracepoints_handlers(session, kmem_tracepoints)) {
		pr_err("Initializing perf session tracepoint handlers failed\n");
		return -1;
	}

	setup_pager();
	err = perf_session__process_events(session, &perf_kmem);
	if (err != 0)
		goto out_delete;
	sort_result();
	print_result(session);
out_delete:
	perf_session__delete(session);
	return err;
}

static int ptr_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	if (l->ptr < r->ptr)
		return -1;
	else if (l->ptr > r->ptr)
		return 1;
	return 0;
}

static struct sort_dimension ptr_sort_dimension = {
	.name	= "ptr",
	.cmp	= ptr_cmp,
};

static int callsite_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	if (l->call_site < r->call_site)
		return -1;
	else if (l->call_site > r->call_site)
		return 1;
	return 0;
}

static struct sort_dimension callsite_sort_dimension = {
	.name	= "callsite",
	.cmp	= callsite_cmp,
};

static int hit_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	if (l->hit < r->hit)
		return -1;
	else if (l->hit > r->hit)
		return 1;
	return 0;
}

static struct sort_dimension hit_sort_dimension = {
	.name	= "hit",
	.cmp	= hit_cmp,
};

static int bytes_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	if (l->bytes_alloc < r->bytes_alloc)
		return -1;
	else if (l->bytes_alloc > r->bytes_alloc)
		return 1;
	return 0;
}

static struct sort_dimension bytes_sort_dimension = {
	.name	= "bytes",
	.cmp	= bytes_cmp,
};

static int frag_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	double x, y;

	x = fragmentation(l->bytes_req, l->bytes_alloc);
	y = fragmentation(r->bytes_req, r->bytes_alloc);

	if (x < y)
		return -1;
	else if (x > y)
		return 1;
	return 0;
}

static struct sort_dimension frag_sort_dimension = {
	.name	= "frag",
	.cmp	= frag_cmp,
};

static int pingpong_cmp(struct alloc_stat *l, struct alloc_stat *r)
{
	if (l->pingpong < r->pingpong)
		return -1;
	else if (l->pingpong > r->pingpong)
		return 1;
	return 0;
}

static struct sort_dimension pingpong_sort_dimension = {
	.name	= "pingpong",
	.cmp	= pingpong_cmp,
};

static struct sort_dimension *avail_sorts[] = {
	&ptr_sort_dimension,
	&callsite_sort_dimension,
	&hit_sort_dimension,
	&bytes_sort_dimension,
	&frag_sort_dimension,
	&pingpong_sort_dimension,
};

#define NUM_AVAIL_SORTS	((int)ARRAY_SIZE(avail_sorts))

static int sort_dimension__add(const char *tok, struct list_head *list)
{
	struct sort_dimension *sort;
	int i;

	for (i = 0; i < NUM_AVAIL_SORTS; i++) {
		if (!strcmp(avail_sorts[i]->name, tok)) {
			sort = memdup(avail_sorts[i], sizeof(*avail_sorts[i]));
			if (!sort) {
				pr_err("%s: memdup failed\n", __func__);
				return -1;
			}
			list_add_tail(&sort->list, list);
			return 0;
		}
	}

	return -1;
}

static int setup_sorting(struct list_head *sort_list, const char *arg)
{
	char *tok;
	char *str = strdup(arg);

	if (!str) {
		pr_err("%s: strdup failed\n", __func__);
		return -1;
	}

	while (true) {
		tok = strsep(&str, ",");
		if (!tok)
			break;
		if (sort_dimension__add(tok, sort_list) < 0) {
			error("Unknown --sort key: '%s'", tok);
			free(str);
			return -1;
		}
	}

	free(str);
	return 0;
}

static int parse_sort_opt(const struct option *opt __maybe_unused,
			  const char *arg, int unset __maybe_unused)
{
	if (!arg)
		return -1;

	if (caller_flag > alloc_flag)
		return setup_sorting(&caller_sort, arg);
	else
		return setup_sorting(&alloc_sort, arg);

	return 0;
}

static int parse_caller_opt(const struct option *opt __maybe_unused,
			    const char *arg __maybe_unused,
			    int unset __maybe_unused)
{
	caller_flag = (alloc_flag + 1);
	return 0;
}

static int parse_alloc_opt(const struct option *opt __maybe_unused,
			   const char *arg __maybe_unused,
			   int unset __maybe_unused)
{
	alloc_flag = (caller_flag + 1);
	return 0;
}

static int parse_line_opt(const struct option *opt __maybe_unused,
			  const char *arg, int unset __maybe_unused)
{
	int lines;

	if (!arg)
		return -1;

	lines = strtoul(arg, NULL, 10);

	if (caller_flag > alloc_flag)
		caller_lines = lines;
	else
		alloc_lines = lines;

	return 0;
}

static int __cmd_record(int argc, const char **argv)
{
	const char * const record_args[] = {
	"record", "-a", "-R", "-f", "-c", "1",
	"-e", "kmem:kmalloc",
	"-e", "kmem:kmalloc_node",
	"-e", "kmem:kfree",
	"-e", "kmem:kmem_cache_alloc",
	"-e", "kmem:kmem_cache_alloc_node",
	"-e", "kmem:kmem_cache_free",
	};
	unsigned int rec_argc, i, j;
	const char **rec_argv;

	rec_argc = ARRAY_SIZE(record_args) + argc - 1;
	rec_argv = calloc(rec_argc + 1, sizeof(char *));

	if (rec_argv == NULL)
		return -ENOMEM;

	for (i = 0; i < ARRAY_SIZE(record_args); i++)
		rec_argv[i] = strdup(record_args[i]);

	for (j = 1; j < (unsigned int)argc; j++, i++)
		rec_argv[i] = argv[j];

	return cmd_record(i, rec_argv, NULL);
}

int cmd_kmem(int argc, const char **argv, const char *prefix __maybe_unused)
{
	const char * const default_sort_order = "frag,hit,bytes";
	const struct option kmem_options[] = {
	OPT_STRING('i', "input", &input_name, "file", "input file name"),
	OPT_CALLBACK_NOOPT(0, "caller", NULL, NULL,
			   "show per-callsite statistics", parse_caller_opt),
	OPT_CALLBACK_NOOPT(0, "alloc", NULL, NULL,
			   "show per-allocation statistics", parse_alloc_opt),
	OPT_CALLBACK('s', "sort", NULL, "key[,key2...]",
		     "sort by keys: ptr, call_site, bytes, hit, pingpong, frag",
		     parse_sort_opt),
	OPT_CALLBACK('l', "line", NULL, "num", "show n lines", parse_line_opt),
	OPT_BOOLEAN(0, "raw-ip", &raw_ip, "show raw ip instead of symbol"),
	OPT_END()
	};
	const char * const kmem_usage[] = {
		"perf kmem [<options>] {record|stat}",
		NULL
	};
	argc = parse_options(argc, argv, kmem_options, kmem_usage, 0);

	if (!argc)
		usage_with_options(kmem_usage, kmem_options);

	symbol__init();

	if (!strncmp(argv[0], "rec", 3)) {
		return __cmd_record(argc, argv);
	} else if (!strcmp(argv[0], "stat")) {
		if (setup_cpunode_map())
			return -1;

		if (list_empty(&caller_sort))
			setup_sorting(&caller_sort, default_sort_order);
		if (list_empty(&alloc_sort))
			setup_sorting(&alloc_sort, default_sort_order);

		return __cmd_kmem();
	} else
		usage_with_options(kmem_usage, kmem_options);

	return 0;
}


text:
require "rails/dev_caching"

module Rails
  module Command
    class DevCommand < Base # :nodoc:
      def help
        say "rails dev:cache # Toggle development mode caching on/off."
      end

      def cache
        Rails::DevCaching.enable_by_file
      end
    end
  end
end


text:
@interface TollLocation : MTLModel <MTLJSONSerializing>

//@property (nonatomic)double longitude;
//@property (nonatomic)double latitude;
@property (nonatomic)BOOL closest;
@property (nonatomic, copy)NSString *tmsName;
@property (nonatomic, copy)NSString *direction;
@property (nonatomic, copy)NSString *title;
@property (nonatomic, copy)NSString *desc;
@property (nonatomic)NSInteger entryID;

@end


text:
import sys
from zoo.models.image.imageclassification import ImageClassifier
from zoo.pipeline.api.keras.layers import Activation
from zoo.pipeline.api.keras.models import Sequential
from zoo.feature.image import ImageSet
from zoo.common.nncontext import init_nncontext
from optparse import OptionParser

def predict(model_path, image_path, top_n):
    sc = init_nncontext("Image classification inference example using int8 quantized model")
    images = ImageSet.read(image_path, sc, image_codec=1)
    model = ImageClassifier.load_model(model_path)
    output = model.predict_image_set(images)
    label_map = model.get_config().label_map()

    # list of images composing uri and results in tuple format
    predicts = output.get_predict().collect()

    sequential = Sequential()
    sequential.add(Activation("softmax", input_shape=predicts[0][1][0].shape))
    for pre in predicts:
        (uri, probs) = pre
        out = sequential.forward(probs[0])
        sortedProbs = [(prob, index) for index, prob in enumerate(out)]
        sortedProbs.sort()
        print("Image : %s, top %d prediction result" % (uri, top_n))
        for i in range(top_n):
            print("\t%s, %f" % (label_map[sortedProbs[999 - i][1]], sortedProbs[999 - i][0]))

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("--model", type=str, dest="model_path",
                      help="The path to the downloaded int8 model snapshot")
    parser.add_option("--image", type=str, dest="image_path",
                      help="The local folder path that contains images for prediction")
    parser.add_option("--topN", type=int, dest="topN", default=5,
                      help="The top N classes with highest probabilities as output")

    (options, args) = parser.parse_args(sys.argv)
    predict(options.model_path, options.image_path, options.topN)


text:
help_message () {
	echo ""
	echo "Usage: metaWRAP reassemble_bins [options] -o output_dir -b bin_folder -1 reads_1.fastq -2 reads_2.fastq"
	echo ""
	echo "Options:"
	echo ""
	echo "	-b STR		folder with metagenomic bins"
	echo "	-o STR		output directory"
	echo "	-1 STR          forward reads to use for reassembly"
	echo "	-2 STR          reverse reads to use for reassembly"
	echo ""
	echo "	-t INT		number of threads (default=1)"
	echo "	-m INT		memory in GB (default=40)"
	echo "	-c INT		minimum desired bin completion %"
	echo "	-x INT		maximum desired bin contamination %"
	echo "	-l INT		minimum contig length to be included in reassembly (default=500)"
	echo ""
	echo "	--strict-cut-off	maximum allowed SNPs for strict read mapping (default=2)"
	echo "	--permissive-cut-off	maximum allowed SNPs for permissive read mapping (default=5)"
	echo "	--skip-checkm		dont run CheckM to assess bins"
	echo "	--parallel		run spades reassembly in parallel, but only using 1 thread per bin"
	echo "";}

comm () { ${SOFT}/print_comment.py "$1" "-"; }
error () { ${SOFT}/print_comment.py "$1" "*"; exit 1; }
warning () { ${SOFT}/print_comment.py "$1" "*"; }
announcement () { ${SOFT}/print_comment.py "$1" "#"; }

# these functions are for parallelizing the reassembly
open_sem(){
    mkfifo pipe-$$
    exec 3<>pipe-$$
    rm pipe-$$
    local i=$1
    for((;i>0;i--)); do
        printf %s 000 >&3
    done
}
run_with_lock(){
    local x
    read -u 3 -n 3 x && ((0==x)) || exit $x
    (
    "$@"
    printf '%.3d' $? >&3
    )&
}

########################################################################################################
########################               LOADING IN THE PARAMETERS                ########################
########################################################################################################

# setting scripts and databases from config file (should be in same folder as main script)
config_file=$(which config-metawrap)
source $config_file

# default params
threads=1; mem=40; comp=70; cont=10; len=500
bins=None; f_reads=None; r_reads=None; out=None
# long options defaults
strict_max=2; permissive_max=5
run_checkm=true
run_parallel=false
# load in params
OPTS=`getopt -o ht:m:o:x:c:l:b:1:2: --long help,parallel,skip-checkm,strict-cut-off,permissive-cut-off -- "$@"`
# make sure the params are entered correctly
if [ $? -ne 0 ]; then help_message; exit 1; fi

# loop through input params
while true; do
        case "$1" in
                -t) threads=$2; shift 2;;
                -m) mem=$2; shift 2;;
                -o) out=$2; shift 2;;
		-x) cont=$2; shift 2;;
		-c) comp=$2; shift 2;;
		-b) bins=$2; shift 2;;
		-l) len=$2; shift 2;;
		-1) f_reads=$2; shift 2;;
		-2) r_reads=$2; shift 2;;
                -h | --help) help_message; exit 0; shift 1;;
		--strict-cut-off) strict_max=$2; shift 2;;
		--permissive-cut-off) permissive_max=$2; shift 2;;
		--skip-checkm) run_checkm=false; shift 1;;
		--parallel) run_parallel=true; shift 1;;
                --) help_message; exit 1; shift; break ;;
                *) break;;
        esac
done

########################################################################################################
########################           MAKING SURE EVERYTHING IS SET UP             ########################
########################################################################################################

# check if all parameters are entered
if [ $out = None ] || [  $bins = None ] || [ $f_reads = None ] || [ $r_reads = None ] ; then
	comm "Some non-optional parameters were not entered"
	help_message; exit 1
fi

# Checks for correctly configures meta-scripts folder
if [ ! -s $SOFT/sort_contigs.py ]; then
	error "The folder $SOFT doesnt exist. Please make sure config.sh is in the same filder as the mains scripts and all the paths in the config.sh file are correct"
fi

########################################################################################################
########################               BEGIN REASSEMBLY PIPELINE!               ########################
########################################################################################################
announcement "BEGIN PIPELINE!"
comm "setting up output folder and copying over bins..."
if [ ! -d $out ]; then
        mkdir $out;
else
        warning "Warning: $out already exists!"
fi

if [ -d ${out}/original_bins ]; then rm -r ${out}/original_bins; fi
cp -r $bins ${out}/original_bins
if [ ! -d ${out}/binned_assembly ]; then mkdir ${out}/binned_assembly; fi

# combinde the bins into one big assembly file
if [ -s ${out}/binned_assembly/assembly.fa ]; then rm ${out}/binned_assembly/assembly.fa; fi
for i in $(ls ${out}/original_bins); do cat ${out}/original_bins/$i >> ${out}/binned_assembly/assembly.fa; done

########################################################################################################
########################        RECRUITING READS TO BINS FOR REASSEMBLY         ########################
########################################################################################################
announcement "RECRUITING READS TO BINS FOR REASSEMBLY"

ulimit -n 10000
if [[ $? -ne 0 ]]; then
	ULIMIT=$(ulimit -n)
	warning "Your operating system will allow you to process up to $ULIMIT files at a time. If this is number is less than 4X times of the number of bins you are reassembling, you will likely get an error. Try re-assembling a smaller number of bins."
fi

if [[ ! -s ${out}/binned_assembly/assembly.fa.amb ]]; then
	comm "Indexing the assembly"
	bwa index ${out}/binned_assembly/assembly.fa
	if [[ $? -ne 0 ]]; then error "BWA failed to index $i"; fi

	if [ -d ${out}/reads_for_reassembly ]; then rm -r ${out}/reads_for_reassembly; fi
	mkdir ${out}/reads_for_reassembly

	comm "Aligning all reads back to entire assembly and splitting reads into individual fastq files based on their bin membership"
	bwa mem -t $threads ${out}/binned_assembly/assembly.fa $f_reads $r_reads \
	 | ${SOFT}/filter_reads_for_bin_reassembly.py ${out}/original_bins ${out}/reads_for_reassembly $strict_max $permissive_max
	if [[ $? -ne 0 ]]; then error "Something went wrong with pulling out reads for reassembly..."; fi
else
	comm "WARNING: Looks like the assembly was already indexed. Skipping indexing, and also skipping splitting the reads, because it is assumed you already got to this stage. Will proceed directly to assembly. This is because your output folder $out already has outputs from previous runs. If this is not what you intended, re-run the module with a new output folder, or clear $out."
fi

########################################################################################################
########################             REASSEMBLING BINS WITH SPADES              ########################
########################################################################################################
announcement "REASSEMBLING BINS WITH SPADES"
mkdir ${out}/reassemblies

assemble () {
	bin_name=${1%_*}
	if [[ -s ${out}/reassemblies/${bin_name}/scaffolds.fasta ]]; then
		comm "Looks like $bin_name was already re-assembled. Skipping..."
	else
		tmp_dir=${out}/reassemblies/${bin_name}.tmp
		mkdir $tmp_dir
		comm "NOW REASSEMBLING ${bin_name}"
		spades.py -t $2 -m $mem --tmp $tmp_dir --careful \
		--untrusted-contigs ${out}/original_bins/${bin_name%.*}.fa \
		-1 ${out}/reads_for_reassembly/${1%_*}_1.fastq \
		-2 ${out}/reads_for_reassembly/${1%_*}_2.fastq \
		-o ${out}/reassemblies/${bin_name}

		if [[ ! -s ${out}/reassemblies/${bin_name}/scaffolds.fasta ]]; then
	                warning "Something went wrong with reassembling ${bin_name}"
		else
			comm "${bin_name} was reassembled successfully!"
			rm -r $tmp_dir
		fi
	fi
}

if [ "$run_parallel" = true ]; then
	open_sem $threads
	for i in $(ls ${out}/reads_for_reassembly/ | grep _1.fastq); do
		run_with_lock assemble $i 1
	done

	wait
	sleep 1
	comm "all assemblies complete"
fi

if [ "$run_parallel" = false ]; then
	for i in $(ls ${out}/reads_for_reassembly/ | grep _1.fastq); do
		assemble $i $threads
	done

	comm "all assemblies complete"
fi

# removing short contigs and placing reassemblies in the final folder
comm "Finalizing reassemblies"
mkdir ${out}/reassembled_bins
for i in $( ls ${out}/reassemblies/ ); do
	spades_folder=${out}/reassemblies/$i
	bin_name=${spades_folder##*/}

	#remove shortest contigs (probably artifacts...)
	if [ -s ${out}/reassemblies/${bin_name}/scaffolds.fasta ]; then
		${SOFT}/rm_short_contigs.py $len\
		 ${out}/reassemblies/${bin_name}/scaffolds.fasta\
		 > ${out}/reassemblies/${bin_name}/long_scaffolds.fasta

		if [ -s ${out}/reassemblies/${bin_name}/long_scaffolds.fasta ]; then
			echo "$bin_name was reassembled! Processing..."
			mv ${out}/reassemblies/${bin_name}/long_scaffolds.fasta\
			${out}/reassembled_bins/${bin_name}.fa
		else
			comm "$bin_name was reassembled, but did not yeild contigs $len bp. It is possible there were not enough reads."
		fi
	else
		comm "$bin_name was not successfully reassembled. It is possible there were not enough reads."
	fi
done

if [[ $(ls ${out}/reassembled_bins/ | wc -l) -lt 1 ]]; then
	error "None of the bins were successfully reassembled. ${out}/reassembled_bins/ is empty."
else
	comm "Looks like the reassemblies went well. Now to see if they made the bins better or worse..."
fi

if [ "$run_checkm" = true ]; then
	########################################################################################################
	########################             RUN CHECKM ON REASSEMBLED BINS             ########################
	########################################################################################################
	announcement "RUN CHECKM ON REASSEMBLED BINS"

	# determine --pplacer_threads count. It is either the max thread count or RAM/4, whichever is higher
	ram_max=$(($mem / 40))
	if (( $ram_max < $threads )); then
		p_threads=$ram_max
	else
		p_threads=$threads
	fi
	comm "There is $mem RAM and $threads threads available, and each pplacer thread uses ~40GB, so I will use $p_threads threads for pplacer"

	# copy over original bins
	for base in $( ls ${out}/original_bins/ | grep "\.fa$" ); do
		i=${out}/original_bins/$base
		cp $i ${out}/reassembled_bins/${base%.*}.orig.fa
	done

	comm "Running CheckM on best bins (reassembled and original)"
	if [[ -d ${out}/reassembled_bins.checkm ]]; then rm -r ${out}/reassembled_bins.checkm; fi
	mkdir ${out}/tmp
	checkm lineage_wf -x fa ${out}/reassembled_bins ${out}/reassembled_bins.checkm -t $threads --tmpdir ${out}/tmp --pplacer_threads $p_threads
	if [[ ! -s ${out}/reassembled_bins.checkm/storage/bin_stats_ext.tsv ]]; then error "Something went wrong with running CheckM. Exiting..."; fi
	${SOFT}/summarize_checkm.py ${out}/reassembled_bins.checkm/storage/bin_stats_ext.tsv | (read -r; printf "%s\n" "$REPLY"; sort) > ${out}/reassembled_bins.stats
	if [[ $? -ne 0 ]]; then error "Cannot make checkm summary file. Exiting."; fi
	rm -r ${out}/tmp

	########################################################################################################
        ########################          FINDING THE BEST VERSION OF EACH BIN          ########################
	########################################################################################################
	announcement "FINDING THE BEST VERSION OF EACH BIN"

	if [ ! -d ${out}/reassembled_best_bins ]; then mkdir ${out}/reassembled_best_bins; fi
	for i in $(${SOFT}/choose_best_bin.py ${out}/reassembled_bins.stats $comp $cont); do
		echo "Copying best bin: $i"
		cp ${out}/reassembled_bins/${i}.fa ${out}/reassembled_best_bins
	done

	o=$(ls -l ${out}/reassembled_best_bins | grep orig | wc -l)
	s=$(ls -l ${out}/reassembled_best_bins | grep strict | wc -l)
	p=$(ls -l ${out}/reassembled_best_bins | grep permissive | wc -l)

	announcement "Reassembly results are in! $s bins were improved with 'strict' reassembly, $p bins were improved with 'permissive' reassembly, and $o bins were not improved by any reassembly, and thus will stay the same."

	if [[ $(ls ${out}/reassembled_best_bins | wc -l) -gt 0 ]]; then
		comm "Seems that the reassembly went well. You will find the final, best, reassembled bins in ${out}/reassembled_bins, and all intermediate files in ${out}/work_files (which we recomend you delete to save space after you confirm that the pipeline worked)"
		mkdir ${out}/work_files
		mv ${out}/reassembled_bins ${out}/work_files/
		mv ${out}/reassembled_bins.checkm ${out}/work_files/
		mv ${out}/reassembled_bins.stats ${out}/work_files/
		mv ${out}/reads_for_reassembly ${out}/work_files/
		mv ${out}/binned_assembly ${out}/work_files/
		mv ${out}/reassemblies ${out}/work_files/
		#rm -r ${out}/original_bins
		mv ${out}/reassembled_best_bins ${out}/reassembled_bins
	else
		error "there are no good bins found in ${out}/reassembled_best_bins - something went wrong with choosing the best bins between the reassemblies."
	fi

	comm "Re-running CheckM on the best reasembled bins."
	if [[ -d ${out}/reassembled_bins.checkm ]]; then rm -r ${out}/reassembled_bins.checkm; fi
	mkdir ${out}/tmp
        checkm lineage_wf -x fa ${out}/reassembled_bins ${out}/reassembled_bins.checkm -t $threads --tmpdir ${out}/tmp --pplacer_threads $p_threads
        if [[ ! -s ${out}/reassembled_bins.checkm/storage/bin_stats_ext.tsv ]]; then error "Something went wrong with running CheckM. Exiting..."; fi
	rm -r ${out}/tmp
        comm "Finalizing CheckM stats..."
        ${SOFT}/summarize_checkm.py ${out}/reassembled_bins.checkm/storage/bin_stats_ext.tsv | (read -r; printf "%s\n" "$REPLY"; sort) > ${out}/reassembled_bins.stats
        if [[ $? -ne 0 ]]; then error "Cannot make checkm summary file. Exiting."; fi

        comm "Making CheckM plot of ${out}/reassembled_bins bins"
        checkm bin_qa_plot -x fa ${out}/reassembled_bins.checkm ${out}/reassembled_bins ${out}/reassembled_bins.plot
        if [[ ! -s ${out}/reassembled_bins.plot/bin_qa_plot.png ]]; then warning "Something went wrong with making the CheckM plot. Exiting."; fi
        mv ${out}/reassembled_bins.plot/bin_qa_plot.png ${out}/reassembled_bins.png
        rm -r ${out}/reassembled_bins.plot

	comm "you will find the info on the final reassembled bins in ${out}/reassembled_bins.stats, and a figure summarizing it in ${out}/reassembled_bins.png"

	comm "making reassembly N50, compleiton, and contamination summary plots."
	head -n 1 ${out}/work_files/reassembled_bins.stats > ${out}/original_bins.stats
	grep orig ${out}/work_files/reassembled_bins.stats >> ${out}/original_bins.stats
	${SOFT}/plot_reassembly.py $out $comp $cont ${out}/reassembled_bins.stats ${out}/original_bins.stats
	if [[ $? -ne 0 ]]; then error "Something went wrong with plotting the reassembly summary plots. Exiting..."; fi
fi

comm "you will find the final bins in ${out}/reassembled_bins"
########################################################################################################
########################    REASSEMBLY PIPELINE SUCCESSFULLY FINISHED!!!        ########################
########################################################################################################
announcement "BIN REASSEMBLY PIPELINE SUCCESSFULLY FINISHED!!!"


text:
package com.google.bitcoin.bouncycastle.crypto.util;

import com.google.bitcoin.bouncycastle.asn1.ASN1InputStream;
import com.google.bitcoin.bouncycastle.asn1.ASN1Object;
import com.google.bitcoin.bouncycastle.asn1.ASN1OctetString;
import com.google.bitcoin.bouncycastle.asn1.ASN1Sequence;
import com.google.bitcoin.bouncycastle.asn1.DERBitString;
import com.google.bitcoin.bouncycastle.asn1.DEREncodable;
import com.google.bitcoin.bouncycastle.asn1.DERInteger;
import com.google.bitcoin.bouncycastle.asn1.DERObject;
import com.google.bitcoin.bouncycastle.asn1.DERObjectIdentifier;
import com.google.bitcoin.bouncycastle.asn1.DEROctetString;
import com.google.bitcoin.bouncycastle.asn1.nist.NISTNamedCurves;
import com.google.bitcoin.bouncycastle.asn1.oiw.ElGamalParameter;
import com.google.bitcoin.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import com.google.bitcoin.bouncycastle.asn1.pkcs.DHParameter;
import com.google.bitcoin.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import com.google.bitcoin.bouncycastle.asn1.sec.SECNamedCurves;
import com.google.bitcoin.bouncycastle.asn1.teletrust.TeleTrusTNamedCurves;
import com.google.bitcoin.bouncycastle.asn1.x509.AlgorithmIdentifier;
import com.google.bitcoin.bouncycastle.asn1.x509.DSAParameter;
import com.google.bitcoin.bouncycastle.asn1.x509.RSAPublicKeyStructure;
import com.google.bitcoin.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import com.google.bitcoin.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import com.google.bitcoin.bouncycastle.asn1.x9.X962NamedCurves;
import com.google.bitcoin.bouncycastle.asn1.x9.X962Parameters;
import com.google.bitcoin.bouncycastle.asn1.x9.X9ECParameters;
import com.google.bitcoin.bouncycastle.asn1.x9.X9ECPoint;
import com.google.bitcoin.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import com.google.bitcoin.bouncycastle.crypto.params.AsymmetricKeyParameter;
import com.google.bitcoin.bouncycastle.crypto.params.DHParameters;
import com.google.bitcoin.bouncycastle.crypto.params.DHPublicKeyParameters;
import com.google.bitcoin.bouncycastle.crypto.params.DSAParameters;
import com.google.bitcoin.bouncycastle.crypto.params.DSAPublicKeyParameters;
import com.google.bitcoin.bouncycastle.crypto.params.ECDomainParameters;
import com.google.bitcoin.bouncycastle.crypto.params.ECPublicKeyParameters;
import com.google.bitcoin.bouncycastle.crypto.params.ElGamalParameters;
import com.google.bitcoin.bouncycastle.crypto.params.ElGamalPublicKeyParameters;
import com.google.bitcoin.bouncycastle.crypto.params.RSAKeyParameters;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;

/**
 * Factory to create asymmetric public key parameters for asymmetric ciphers
 * from range of ASN.1 encoded SubjectPublicKeyInfo objects.
 */
public class PublicKeyFactory
{
    /**
     * Create a public key from a SubjectPublicKeyInfo encoding
     *
     * @param keyInfoData the SubjectPublicKeyInfo encoding
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
    public static AsymmetricKeyParameter createKey(
        byte[] keyInfoData)
        throws IOException
    {
        return createKey(
            SubjectPublicKeyInfo.getInstance(
                ASN1Object.fromByteArray(keyInfoData)));
    }

    /**
     * Create a public key from a SubjectPublicKeyInfo encoding read from a stream
     *
     * @param inStr the stream to read the SubjectPublicKeyInfo encoding from
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
    public static AsymmetricKeyParameter createKey(
        InputStream inStr)
        throws IOException
    {
        return createKey(
            SubjectPublicKeyInfo.getInstance(
                new ASN1InputStream(inStr).readObject()));
    }

    /**
     * Create a public key from the passed in SubjectPublicKeyInfo
     *
     * @param keyInfo the SubjectPublicKeyInfo containing the key data
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
    public static AsymmetricKeyParameter createKey(
        SubjectPublicKeyInfo    keyInfo)
        throws IOException
    {
        AlgorithmIdentifier     algId = keyInfo.getAlgorithmId();

        if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption)
            || algId.getObjectId().equals(X509ObjectIdentifiers.id_ea_rsa))
        {
            RSAPublicKeyStructure   pubKey = new RSAPublicKeyStructure((ASN1Sequence)keyInfo.getPublicKey());

            return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
        }
        else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)
                 || algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber))
        {
            DHParameter params = new DHParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
            DERInteger  derY = (DERInteger)keyInfo.getPublicKey();

            BigInteger lVal = params.getL();
            int l = lVal == null ? 0 : lVal.intValue();
            DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);

            return new DHPublicKeyParameters(derY.getValue(), dhParams);
        }
        else if (algId.getObjectId().equals(OIWObjectIdentifiers.elGamalAlgorithm))
        {
            ElGamalParameter    params = new ElGamalParameter((ASN1Sequence)keyInfo.getAlgorithmId().getParameters());
            DERInteger          derY = (DERInteger)keyInfo.getPublicKey();

            return new ElGamalPublicKeyParameters(derY.getValue(), new ElGamalParameters(params.getP(), params.getG()));
        }
        else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)
                 || algId.getObjectId().equals(OIWObjectIdentifiers.dsaWithSHA1))
        {
            DERInteger derY = (DERInteger)keyInfo.getPublicKey();
            DEREncodable de = keyInfo.getAlgorithmId().getParameters();

            DSAParameters parameters = null;
            if (de != null)
            {
                DSAParameter params = DSAParameter.getInstance(de.getDERObject());
                parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
            }

            return new DSAPublicKeyParameters(derY.getValue(), parameters);
        }
        else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey))
        {
            X962Parameters      params = new X962Parameters((DERObject)keyInfo.getAlgorithmId().getParameters());
            ECDomainParameters  dParams = null;

            if (params.isNamedCurve())
            {
                DERObjectIdentifier oid = (DERObjectIdentifier)params.getParameters();
                X9ECParameters      ecP = X962NamedCurves.getByOID(oid);

                if (ecP == null)
                {
                    ecP = SECNamedCurves.getByOID(oid);

                    if (ecP == null)
                    {
                        ecP = NISTNamedCurves.getByOID(oid);

                        if (ecP == null)
                        {
                            ecP = TeleTrusTNamedCurves.getByOID(oid);
                        }
                    }
                }

                dParams = new ECDomainParameters(
                                            ecP.getCurve(),
                                            ecP.getG(),
                                            ecP.getN(),
                                            ecP.getH(),
                                            ecP.getSeed());
            }
            else
            {
                X9ECParameters ecP = new X9ECParameters(
                            (ASN1Sequence)params.getParameters());
                dParams = new ECDomainParameters(
                                            ecP.getCurve(),
                                            ecP.getG(),
                                            ecP.getN(),
                                            ecP.getH(),
                                            ecP.getSeed());
            }

            DERBitString    bits = keyInfo.getPublicKeyData();
            byte[]          data = bits.getBytes();
            ASN1OctetString key = new DEROctetString(data);

            X9ECPoint       derQ = new X9ECPoint(dParams.getCurve(), key);

            return new ECPublicKeyParameters(derQ.getPoint(), dParams);
        }
        else
        {
            throw new RuntimeException("algorithm identifier in key not recognised");
        }
    }
}


text:
package org.apache.activemq.artemis.core.transaction;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.xa.Xid;

import org.apache.activemq.artemis.core.server.MessageReference;
import org.apache.activemq.artemis.core.server.ServerMessage;
import org.apache.activemq.artemis.core.transaction.impl.XidImpl;
import org.apache.activemq.artemis.utils.json.JSONArray;
import org.apache.activemq.artemis.utils.json.JSONObject;

public abstract class TransactionDetail {

   public static final String KEY_CREATION_TIME = "creation_time";

   public static final String KEY_XID_AS_BASE64 = "xid_as_base64";

   public static final String KEY_XID_FORMAT_ID = "xid_format_id";

   public static final String KEY_XID_GLOBAL_TXID = "xid_global_txid";

   public static final String KEY_XID_BRANCH_QUAL = "xid_branch_qual";

   public static final String KEY_TX_RELATED_MESSAGES = "tx_related_messages";

   public static final String KEY_MSG_OP_TYPE = "message_operation_type";

   public static final String KEY_MSG_BODY_BUFFER = "message_body";

   public static final String KEY_MSG_TYPE = "message_type";

   public static final String KEY_MSG_PROPERTIES = "message_properties";

   private final Xid xid;
   private final Transaction transaction;
   private final Long creationTime;

   public TransactionDetail(Xid xid, Transaction tx, Long creation) {
      this.xid = xid;
      this.transaction = tx;
      this.creationTime = creation;
   }

   public JSONObject toJSON() throws Exception {
      DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM);
      JSONObject detailJson = new JSONObject();

      detailJson.put(KEY_CREATION_TIME, dateFormat.format(new Date(this.creationTime)));
      detailJson.put(KEY_XID_AS_BASE64, XidImpl.toBase64String(this.xid));
      detailJson.put(KEY_XID_FORMAT_ID, this.xid.getFormatId());
      detailJson.put(KEY_XID_GLOBAL_TXID, new String(this.xid.getGlobalTransactionId()));
      detailJson.put(KEY_XID_BRANCH_QUAL, new String(this.xid.getBranchQualifier()));

      JSONArray msgsJson = new JSONArray();

      List<TransactionOperation> txops = null;

      if (this.transaction != null) {
         txops = this.transaction.getAllOperations();
      }

      detailJson.put(KEY_TX_RELATED_MESSAGES, msgsJson);
      if (txops == null) {
         return detailJson;
      }

      for (TransactionOperation op : txops) {
         String opClassName = op.getClass().getName();
         String opType = null;
         if (opClassName.equals("org.apache.activemq.artemis.core.postoffice.impl.PostOfficeImpl$AddOperation")) {
            opType = "(+) send";
         }
         else if (opClassName.equals("org.apache.activemq.artemis.core.server.impl.QueueImpl$RefsOperation")) {
            opType = "(-) receive";
         }

         List<MessageReference> msgs = op.getRelatedMessageReferences();
         if (msgs == null) {
            continue;
         }

         for (MessageReference ref : msgs) {
            JSONObject msgJson = new JSONObject();
            msgsJson.put(msgJson);

            msgJson.put(KEY_MSG_OP_TYPE, opType);

            ServerMessage msg = ref.getMessage().copy();

            msgJson.put(KEY_MSG_TYPE, decodeMessageType(msg));
            msgJson.put(KEY_MSG_PROPERTIES, decodeMessageProperties(msg));
         }
      }
      return detailJson;
   }

   public abstract String decodeMessageType(ServerMessage msg);

   public abstract Map<String, Object> decodeMessageProperties(ServerMessage msg);
}


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateGeonamesModificationsTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::create( 'geonames_modifications', function ( Blueprint $table ) {
            $table->engine = 'MyISAM';
            $table->increments('id');                   // Primary key of this table. Can't be geonameid, as a location can have n modifications.
            $table->date('date');                       // The date of the modification
            $table->integer('geonameid');               // geonameid         : integer id of record in geonames database
            $table->string('name', 200);                // name              : name of geographical point (utf8) varchar(200)
            $table->string('asciiname', 200);           // asciiname         : name of geographical point in plain ascii characters, varchar(200)
            $table->string('alternatenames', 10000);    // alternatenames    : alternatenames, comma separated, ascii names automatically transliterated, convenience attribute from alternatename table, varchar(10000)
            $table->decimal('latitude', 10, 8);         // latitude          : latitude in decimal degrees (wgs84)
            $table->decimal('longitude', 11, 8);        // longitude         : longitude in decimal degrees (wgs84)
            $table->string('feature_class', 1);         // feature class     : see http://www.geonames.org/export/codes.html, char(1)
            $table->string('feature_code', 10);         // feature code      : see http://www.geonames.org/export/codes.html, varchar(10)
            $table->string('country_code', 2);          // country code      : ISO-3166 2-letter country code, 2 characters
            $table->string('cc2', 200);                 // cc2               : alternate country codes, comma separated, ISO-3166 2-letter country code, 200 characters
            $table->string('admin1_code', 20);          // admin1 code       : fipscode (subject to change to iso code), see exceptions below, see file admin1Codes.txt for display names of this code; varchar(20)
            $table->string('admin2_code', 80);          // admin2 code       : code for the second administrative division, a county in the US, see file admin2Codes.txt; varchar(80)
            $table->string('admin3_code', 20);          // admin3 code       : code for third level administrative division, varchar(20)
            $table->string('admin4_code', 20);          // admin4 code       : code for fourth level administrative division, varchar(20)
            $table->bigInteger('population');           // population        : bigint (8 byte int)
            $table->integer('elevation');          // elevation         : in meters, integer
            $table->integer('dem');                     // dem               : digital elevation model, srtm3 or gtopo30, average elevation of 3''x3'' (ca 90mx90m) or 30''x30'' (ca 900mx900m) area in meters, integer. srtm processed by cgiar/ciat.
            $table->string('timezone', 40);             // timezone          : the iana timezone id (see file timeZone.txt) varchar(40)
            $table->date('modification_date');          // modification date : date of last modification in yyyy-MM-dd format
            $table->timestamps();                       // Laravel's created_at and updated_at timestamp fields.
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        Schema::dropIfExists( 'geonames_modifications' );
    }
}