text:
package org.markdownwriterfx.options;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.TextField;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import org.markdownwriterfx.Messages;
import org.markdownwriterfx.util.Item;
import org.markdownwriterfx.util.Utils;
import org.tbee.javafx.scene.layout.fxml.MigPane;

/**
 * General options pane
 *
 * @author Karl Tauber
 */
class GeneralOptionsPane
	extends MigPane
{
	@SuppressWarnings("unchecked")
	GeneralOptionsPane() {
		initComponents();

		Font titleFont = Font.font(16);
		editorSettingsLabel.setFont(titleFont);
		fileSettingsLabel.setFont(titleFont);

		// font family
		fontFamilyField.getItems().addAll(getMonospacedFonts());
		fontFamilyField.getSelectionModel().select(0);
		fontFamilyField.setButtonCell(new FontListCell());
		fontFamilyField.setCellFactory(p -> new FontListCell());

		// font size
		fontSizeField.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(Options.MIN_FONT_SIZE, Options.MAX_FONT_SIZE));

		// line separator
		String defaultLineSeparator = System.getProperty( "line.separator", "\n" );
		String defaultLineSeparatorStr = defaultLineSeparator.replace("\r", "CR").replace("\n", "LF");
		lineSeparatorField.getItems().addAll(
			new Item<>(Messages.get("GeneralOptionsPane.platformDefault", defaultLineSeparatorStr), null),
			new Item<>(Messages.get("GeneralOptionsPane.sepWindows"), "\r\n"),
			new Item<>(Messages.get("GeneralOptionsPane.sepUnix"), "\n"));

		// encoding
		encodingField.getItems().addAll(getAvailableEncodings());

		// file extensions
		markdownFileExtensionsField.setPromptText(Options.DEF_MARKDOWN_FILE_EXTENSIONS);
	}

	/**
	 * Return a list of all the mono-spaced fonts on the system.
	 *
	 * @author David D. Clark http://clarkonium.net/2015/07/finding-mono-spaced-fonts-in-javafx/
	 */
	private static Collection<String> getMonospacedFonts() {

		// Compare the layout widths of two strings. One string is composed
		// of "thin" characters, the other of "wide" characters. In mono-spaced
		// fonts the widths should be the same.

		final Text thinTxt = new Text("1 l"); // note the space
		final Text thikTxt = new Text("MWX");

		List<String> fontFamilyList = Font.getFamilies();
		List<String> monospacedFonts = new ArrayList<>();

		for (String fontFamilyName : fontFamilyList) {
			Font font = Font.font(fontFamilyName, FontWeight.NORMAL, FontPosture.REGULAR, 14.0d);
			thinTxt.setFont(font);
			thikTxt.setFont(font);
			if (thinTxt.getLayoutBounds().getWidth() == thikTxt.getLayoutBounds().getWidth())
				monospacedFonts.add(fontFamilyName);
		}

		return monospacedFonts;
	}

	private Collection<Item<String>> getAvailableEncodings() {
		SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();

		ArrayList<Item<String>> values = new ArrayList<>(1 + availableCharsets.size());
		values.add(new Item<>(Messages.get("GeneralOptionsPane.platformDefault", Charset.defaultCharset().name()), null));
		for (String name : availableCharsets.keySet())
			values.add(new Item<>(name, name));
		return values;
	}

	void load() {
		// editor settings
		fontFamilyField.getSelectionModel().select(Options.getFontFamily());
		fontSizeField.getValueFactory().setValue(Options.getFontSize());
		showLineNoCheckBox.setSelected(Options.isShowLineNo());
		showWhitespaceCheckBox.setSelected(Options.isShowWhitespace());
		showImagesEmbeddedCheckBox.setSelected(Options.isShowImagesEmbedded());

		// file settings
		lineSeparatorField.setValue(new Item<>(Options.getLineSeparator(), Options.getLineSeparator()));
		encodingField.setValue(new Item<>(Options.getEncoding(), Options.getEncoding()));
		markdownFileExtensionsField.setText(Options.getMarkdownFileExtensions());
	}

	void save() {
		// editor settings
		Options.setFontFamily(fontFamilyField.getSelectionModel().getSelectedItem());
		Options.setFontSize(fontSizeField.getValue());
		Options.setShowLineNo(showLineNoCheckBox.isSelected());
		Options.setShowWhitespace(showWhitespaceCheckBox.isSelected());
		Options.setShowImagesEmbedded(showImagesEmbeddedCheckBox.isSelected());

		// file settings
		Options.setLineSeparator(lineSeparatorField.getValue().value);
		Options.setEncoding(encodingField.getValue().value);
		Options.setMarkdownFileExtensions(Utils.defaultIfEmpty(
				markdownFileExtensionsField.getText().trim(),
				Options.DEF_MARKDOWN_FILE_EXTENSIONS));
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		editorSettingsLabel = new Label();
		fontFamilyLabel = new Label();
		fontFamilyField = new ComboBox<>();
		fontSizeLabel = new Label();
		fontSizeField = new Spinner<>();
		showLineNoCheckBox = new CheckBox();
		showWhitespaceCheckBox = new CheckBox();
		showImagesEmbeddedCheckBox = new CheckBox();
		fileSettingsLabel = new Label();
		Label lineSeparatorLabel = new Label();
		lineSeparatorField = new ComboBox<>();
		Label lineSeparatorLabel2 = new Label();
		Label encodingLabel = new Label();
		encodingField = new ComboBox<>();
		Label markdownFileExtensionsLabel = new Label();
		markdownFileExtensionsField = new TextField();

		//======== this ========
		setCols(
			"[indent,fill]0" +
			"[fill]" +
			"[fill]" +
			"[grow,fill]");
		setRows(
			"[]" +
			"[]" +
			"[]" +
			"[]" +
			"[]" +
			"[]para" +
			"[]" +
			"[]" +
			"[]" +
			"[]para");

		//---- editorSettingsLabel ----
		editorSettingsLabel.setText(Messages.get("GeneralOptionsPane.editorSettingsLabel.text"));
		add(editorSettingsLabel, "cell 0 0 2 1");

		//---- fontFamilyLabel ----
		fontFamilyLabel.setText(Messages.get("GeneralOptionsPane.fontFamilyLabel.text"));
		fontFamilyLabel.setMnemonicParsing(true);
		add(fontFamilyLabel, "cell 1 1");

		//---- fontFamilyField ----
		fontFamilyField.setVisibleRowCount(20);
		add(fontFamilyField, "cell 2 1");

		//---- fontSizeLabel ----
		fontSizeLabel.setText(Messages.get("GeneralOptionsPane.fontSizeLabel.text"));
		fontSizeLabel.setMnemonicParsing(true);
		add(fontSizeLabel, "cell 1 2");
		add(fontSizeField, "cell 2 2,alignx left,growx 0");

		//---- showLineNoCheckBox ----
		showLineNoCheckBox.setText(Messages.get("GeneralOptionsPane.showLineNoCheckBox.text"));
		add(showLineNoCheckBox, "cell 1 3 3 1,alignx left,growx 0");

		//---- showWhitespaceCheckBox ----
		showWhitespaceCheckBox.setText(Messages.get("GeneralOptionsPane.showWhitespaceCheckBox.text"));
		add(showWhitespaceCheckBox, "cell 1 4 3 1,alignx left,growx 0");

		//---- showImagesEmbeddedCheckBox ----
		showImagesEmbeddedCheckBox.setText(Messages.get("GeneralOptionsPane.showImagesEmbeddedCheckBox.text"));
		add(showImagesEmbeddedCheckBox, "cell 1 5 3 1,alignx left,growx 0");

		//---- fileSettingsLabel ----
		fileSettingsLabel.setText(Messages.get("GeneralOptionsPane.fileSettingsLabel.text"));
		add(fileSettingsLabel, "cell 0 6 2 1");

		//---- lineSeparatorLabel ----
		lineSeparatorLabel.setText(Messages.get("GeneralOptionsPane.lineSeparatorLabel.text"));
		lineSeparatorLabel.setMnemonicParsing(true);
		add(lineSeparatorLabel, "cell 1 7");
		add(lineSeparatorField, "cell 2 7");

		//---- lineSeparatorLabel2 ----
		lineSeparatorLabel2.setText(Messages.get("GeneralOptionsPane.lineSeparatorLabel2.text"));
		add(lineSeparatorLabel2, "cell 3 7");

		//---- encodingLabel ----
		encodingLabel.setText(Messages.get("GeneralOptionsPane.encodingLabel.text"));
		encodingLabel.setMnemonicParsing(true);
		add(encodingLabel, "cell 1 8");

		//---- encodingField ----
		encodingField.setVisibleRowCount(20);
		add(encodingField, "cell 2 8");

		//---- markdownFileExtensionsLabel ----
		markdownFileExtensionsLabel.setText(Messages.get("GeneralOptionsPane.markdownFileExtensionsLabel.text"));
		markdownFileExtensionsLabel.setMnemonicParsing(true);
		add(markdownFileExtensionsLabel, "cell 1 9");
		add(markdownFileExtensionsField, "cell 2 9 2 1");
		// JFormDesigner - End of component initialization  //GEN-END:initComponents

		// TODO set this in JFormDesigner as soon as it supports labelFor
		fontFamilyLabel.setLabelFor(fontFamilyField);
		fontSizeLabel.setLabelFor(fontSizeField);
		lineSeparatorLabel.setLabelFor(lineSeparatorField);
		encodingLabel.setLabelFor(encodingField);
		markdownFileExtensionsLabel.setLabelFor(markdownFileExtensionsField);
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private Label editorSettingsLabel;
	private Label fontFamilyLabel;
	private ComboBox<String> fontFamilyField;
	private Label fontSizeLabel;
	private Spinner<Integer> fontSizeField;
	private CheckBox showLineNoCheckBox;
	private CheckBox showWhitespaceCheckBox;
	private CheckBox showImagesEmbeddedCheckBox;
	private Label fileSettingsLabel;
	private ComboBox<Item<String>> lineSeparatorField;
	private ComboBox<Item<String>> encodingField;
	private TextField markdownFileExtensionsField;
	// JFormDesigner - End of variables declaration  //GEN-END:variables

	//---- class FontListCell -------------------------------------------------

	private static class FontListCell
		extends ListCell<String>
	{
		@Override
		protected void updateItem(String fontFamily, boolean empty) {
			super.updateItem(fontFamily, empty);

			if (!empty) {
				setText(fontFamily);
				setFont(Font.font(fontFamily));
			} else
				setText(null);
		}
	}
}


text:
title: Documentación
spdx-id: documentacion
nickname: Documentación
source:
lang: es

description: La Documentación, generalmente identificada en el archivo README.md (o .txt) sirve para explicar a otros desarrolladores para qué sirve la herramienta, cómo funciona y los pasos para reutilizarla o adaptarla. En esta sección explicamos cómo generar una buena documentación. De manera resumida, la documentación debe contener

requirements:
- Descripción y contexto
- Guía de usuario
- Guía de instalación
- Autores
- Licencias (código y doc)

expected:
- Cómo contribuir
- Código de conducta
- Insignias (badges)
- Versión
- Reconocimientos

sidebar: Es importante documentar para asegurar el mantenimiento, la sostetinibilidad y la reutilización de la herramienta.

nota: Si eres empleado del BID y estas trabando con código, aquí podrás encontrar información que te será útil.

links:
- Guía Markdown
- Plantilla Readme

---
Para facilitar el trabajo, puedes hacer click **[aquí]((https://github.com/EL-BID/Plantilla-de-repositorio))** para ver la plantilla de Readme que proponemos.

## ¿Qué información debo incluir en el archivo README?
Aunque no existe un formato estándar, estas son las secciones necesarias más comunes para disponer de un README completo. Opcionalmente, esta información puede ir en otros documentos o archivos, pero ello debe estar referenciado en el README.

* **Descripción y contexto:**
Descripción de las funcionalidades, el contexto donde fue desarrollado y los problemas de desarrollo que ayudó a resolver.

*   **Guía de usuario:**
Paso a paso dirigido al usuario final sobre cómo empezar a usar la herramienta digital. Si esta información es demasiado extensa, puede ir en un documento aparte, pero es una buena práctica nombrarlo en la documentación.

*	**Guía de instalación:**
Instrucciones de instalación para reutilizar y configurar la herramienta digital. Esta sección está dirigida a desarrolladores. Se deben especificar:

	* Los requisitos del sistema operativo para la compilación (versiones específicas de librerías, software de gestión de paquetes y dependencias, SDKs y compiladores, etc.).

	* Las dependencias propias del proyecto, tanto externas como internas (orden de compilación de sub-módulos, configuración de ubicación de librerías dinámicas, etc.).

	* Pasos específicos para la compilación del código fuente y ejecución de tests unitarios en caso de que el proyecto disponga de ellos.

*	**Autores**
Sección para dar créditos a los colaboradores de la herramienta.

*	**Licencia para el código de la herramienta:**
Permisos que se otorgan a terceros para reutilizar la herramienta digital. Debe especificar el tipo de licencia y hacer referencia al archivo license.txt o licencia.txt con el contenido de la licencia. (Leer más sobre cómo licenciar [aquí](https://el-bid.github.io/guia-de-publicacion/documents/licenciamiento/))

*	**Licencia para la documentación de la herramienta:**
Recomendamos el uso de las licencias creative commons para el licenciamiento de la documentación de las herramientas.
La CC0-1.0, CC-BY-4.0 y CC-BY-SA-4.0 por ejemplo son licencias abiertas que se utilizan para material que no es de software, desde conjuntos de datos hasta videos. Tenga en cuenta que CC-BY-4.0 y CC-BY-SA-4.0 no deben usarse para el software.

Para herramientas desarrolladas por el BID por el momento recomendamos usar la Creative Commons IGO 3.0 Attribution-NonCommercial-NoDerivative (CC-IGO 3.0 BY-NC-ND).

## ¿A quién va dirigida la documentación?
La audiencia principal de la documentación son desarrolladores. No obstante, la sección de la guía de usuario va dirigida a los usuarios finales de la herramienta. Si esta sección es muy compleja, es una buena práctica dedicar un documento específico para esto. Aunque en el archivo Readme se debe especificar la existencia de esta documentación extra.

## ¿Dónde se guarda y qué formato debo utilizar?
Se guarda en un archivo con el nombre README.md. Debe estar visible en la carpeta principal de la herramienta digital y en formato markdown. En [este link](http://joedicastro.com/pages/markdown.html) puedes ver una guía de cómo usar markdown. Es un formato de escritura simple para archivos de texto planos.

### ¿Existe una plantilla de un archivo README.md?
El proyecto Código para el Desarrollo dispone de una plantilla para que uses como punto de partida.
[Plantilla README.md](https://github.com/EL-BID/Plantilla-de-repositorio)

## ¿Qué secciones se pueden añadir para acabar de completar la documentación?
A continuación se describen las secciones ideales que puedes añadir a la documentación para completar la misma.

*	**Cómo contribuir**
Sección que explica a nuevos desarrolladores el proceso para contribuir a proyectos.

*	**Código de conducta**
El código de conducta establece las normas sociales, reglas y responsabilidades que los individuos y organizaciones deben seguir al interactuar de alguna manera con la herramienta digital o su comunidad. Es una buena práctica para crear un ambiente de respeto e inclusión en las contribuciones al proyecto. La plataforma Github premia y ayuda a los repositorios dispongan de este archivo. Al crear CODE_OF_CONDUCT.md puedes empezar desde una plantilla sugerida por ellos. Aquí tienes una plantilla propuesta por Contributor Convenant que puedes usar para tu proyecto.

*	**Insignias (badges)**
Las insignias (badges) pequeñas imágenes incrustadas en el README.md que especifican de una manera legible y concisa el estado de la herramienta.  Existen insignias para el estado de desarrollo, el número de descargas, el versionado, sociales u otras.
En este link podrás encontrar información [https://shields.io/](https://shields.io/)

* **Versión**
Indica un listado de las versiones de las herramientas digital y las funcionalidades añadidas a cada versión.

* **Reconocimientos**
Reconocimientos a otras personas u organizaciones que hayan contribuido de alguna forma al proyecto 3.

## ¿Existe algún otro tipo de documentación a parte del README.md?
A parte de la documentación más técnica dirigida a desarrolladores, puedes ofrecer una guía de usuario. Si se trata de documentación muy extensa y muy detallada es buena práctica ponerla en un archivo diferente y especificarlo en el README.md.

## ¿Qué otras buenas prácticas se recomiendan en relación a la documentacón?
Si consideras que las secciones de **guía de usuario** y la **guía de instalación** son más complejas, puedes alojarla en una página web dedicada a ello. Para ello puedes utilizar la funcionalidad de **[Github-pages](https://pages.github.com/)**. Las siguientes herramientas pueden servir para facilitar esta tarea:
- **[Readthedocs](https://readthedocs.org/):** Servicio de alojamiento de documentación gratuíto. (Ver ejemplo de [Textar](http://textar.readthedocs.io/en/latest/README.html))
- **[Gitbook](https://www.gitbook.com/)**: Servicio gratuito para escribir, colaborar y publicar contenido online de manera sencilla.
- **[Jekyll](https://jekyllrb.com/)**: Compilador de páginas web estáticas. (Esta página está creada con Jekyll)

redpajama_set_name: RedPajamaGithub


text:
package com.dtstack.jlogstash.filters;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * Reason: TODO ADD REASON(可选)
 * Date: 2016年8月31日 下午1:53:39
 * Company: www.dtstack.com
 * @author sishu.yss
 *
 */
class IP {
    public static String randomIp() {
        Random r = new Random();
        StringBuffer str = new StringBuffer();
        str.append(r.nextInt(1000000) % 255);
        str.append(".");
        str.append(r.nextInt(1000000) % 255);
        str.append(".");
        str.append(r.nextInt(1000000) % 255);
        str.append(".");
        str.append(0);
        return str.toString();
    }

    public static void main(String[] args){
    	IP.load("17monipdb.dat");
        System.out.println(IP.find("78.16.49.15"));
    }

    public static boolean enableFileWatch = false;

    private static int offset;
    private static int[] index = new int[256];
    private static ByteBuffer dataBuffer;
    private static ByteBuffer indexBuffer;
//    private static Long lastModifyTime = 0L;
//    private static File ipFile ;
    private static InputStream fin;
    private static ReentrantLock lock = new ReentrantLock();

    @SuppressWarnings("static-access")
	public static void load(String filename){
    	fin =  IP.class.getClassLoader().getSystemResourceAsStream(filename);
        load();
    }

    public static String[] find(String ip) {
        int ip_prefix_value = new Integer(ip.substring(0, ip.indexOf(".")));
        long ip2long_value  = ip2long(ip);
        int start = index[ip_prefix_value];
        int max_comp_len = offset - 1028;
        long index_offset = -1;
        int index_length = -1;
        byte b = 0;
        for (start = start * 8 + 1024; start < max_comp_len; start += 8) {
            if (int2long(indexBuffer.getInt(start)) >= ip2long_value) {
                index_offset = bytesToLong(b, indexBuffer.get(start + 6), indexBuffer.get(start + 5), indexBuffer.get(start + 4));
                index_length = 0xFF & indexBuffer.get(start + 7);
                break;
            }
        }

        byte[] areaBytes;

        lock.lock();
        try {
            dataBuffer.position(offset + (int) index_offset - 1024);
            areaBytes = new byte[index_length];
            dataBuffer.get(areaBytes, 0, index_length);
        } finally {
            lock.unlock();
        }
        String[] result =new String(areaBytes, Charset.forName("UTF-8")).split("\t", -1);
        return result;
    }

    private static void load() {
        lock.lock();
        try {
            dataBuffer = ByteBuffer.allocate(Long.valueOf(fin.available()).intValue());
            int readBytesLength;
            byte[] chunk = new byte[4096];
            while (fin.available() > 0) {
                readBytesLength = fin.read(chunk);
                dataBuffer.put(chunk, 0, readBytesLength);
            }
            dataBuffer.position(0);
            int indexLength = dataBuffer.getInt();
            byte[] indexBytes = new byte[indexLength];
            dataBuffer.get(indexBytes, 0, indexLength - 4);
            indexBuffer = ByteBuffer.wrap(indexBytes);
            indexBuffer.order(ByteOrder.LITTLE_ENDIAN);
            offset = indexLength;

            int loop = 0;
            while (loop++ < 256) {
                index[loop - 1] = indexBuffer.getInt();
            }
            indexBuffer.order(ByteOrder.BIG_ENDIAN);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (fin != null) {
                    fin.close();
                }
            } catch (IOException e){
                e.printStackTrace();
            }
            lock.unlock();
        }
    }

    private static long bytesToLong(byte a, byte b, byte c, byte d) {
        return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
    }

    private static int str2Ip(String ip)  {
        String[] ss = ip.split("\\.");
        int a, b, c, d;
        a = Integer.parseInt(ss[0]);
        b = Integer.parseInt(ss[1]);
        c = Integer.parseInt(ss[2]);
        d = Integer.parseInt(ss[3]);
        return (a << 24) | (b << 16) | (c << 8) | d;
    }

    private static long ip2long(String ip)  {
        return int2long(str2Ip(ip));
    }

    private static long int2long(int i) {
        long l = i & 0x7fffffffL;
        if (i < 0) {
            l |= 0x080000000L;
        }
        return l;
    }
}


text:
package org.apache.cassandra.index.sasi.disk;

import org.junit.Assert;
import org.junit.Test;

public class KeyOffsetsTest
{
    @Test
    public void testDuplicates()
    {
        KeyOffsets offsets = new KeyOffsets();
        long[] arr = new long[]{ 1, 2, 3, 4, 5, 6 };
        offsets.put(1, arr);
        Assert.assertArrayEquals(offsets.get(1), arr);
        offsets.put(1, arr);
        Assert.assertArrayEquals(offsets.get(1), arr);
        for (long l : arr)
            offsets.put(1, l);
        Assert.assertArrayEquals(offsets.get(1), arr);

        for (long l : arr)
            offsets.put(2, l);
        Assert.assertArrayEquals(offsets.get(2), arr);
        offsets.put(2, arr);
        Assert.assertArrayEquals(offsets.get(2), arr);
        offsets.put(2, arr);
        Assert.assertArrayEquals(offsets.get(2), arr);
    }

}


text:
<!DOCTYPE html>

	<meta name="generator" content="Hugo 0.48" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/css/style.css">

<meta property="fb:pages" content="267523766781017" />
<title>All American Muslim</title>
<link rel="canonical" href="https://www.allamericanmuslim.com/">
<meta property="og:locale" content="en-us">
<meta property="og:title" content="All American Muslim">
<meta property="og:site_name" content="All American Muslim">
<meta property="og:description" content="">
<meta property="og:url" content="https://www.allamericanmuslim.com/">

<meta property="og:type" content="article">

<meta property="fb:app_id" content="347123062352978">
<meta http-equiv="cleartype" content="on">
<meta name="description" content="">

All American Muslim

Home

DMCA

How American Rapper Dave East Embraced Islam

Sheikh Dies on Live TV while Reciting Quran

A Lesson in Happiness

China Just Banned Newborn Muslim Names for More Than 10 Million Chinese Muslims

Israel just bombed Syria .. Many Killed Among Assad Forces

MTV Presenter Kristiane Backer Journey to Islam

Muslim Girl Has Perfect Response to White Man's Racist Attack at Mall

Pennsylvania Girl Tells her Dad She Wants to Stop Wearing Hijab, His Response Is Brilliant

I Lived and Worked for 10 years in Muslim Majority Countries. Here is What I Experienced

Muslim American Judge Found Dead in New York River

Meet Lisa The Convert who Launched Macy's First Muslim Clothing Line

How Hijab Lead A Playboy Model To Islam

« First

‹ Prev

...

23

24

25

26

27

...

Next ›

Last »


text:
#pragma once

#ifdef UWP
#include "pch.h"
#endif

class MarchingCube
{
public:

protected:

private:
};


text:
#!/usr/bin/env perl
# Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

use strict;
use warnings;

use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use Bio::EnsEMBL::Utils::Exception qw(throw);
use Getopt::Long;

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

view_alignment

=head1 DESCRIPTION

This script downloads alignments from a compara database, creates a gap4
database and brings up a contig editor for each alignment block found. This
allows the alignment to be scrolled and viewed in detail. Additional
information such as genes, conserved regions and repeats can be highlighted.

=head1 SETUP

The location of view_alignment must be in your path.
For example:

in bash:

export PATH=$HOME/src/ensembl_main/ensembl_compara/scripts/view_alignment:$PATH

in csh:

setenv PATH $HOME/src/ensembl_main/ensembl_compara/scripts/view_alignment:$PATH

The Staden Package environment must be set up:

eg
export STADENROOT=/software/badger/opt/staden_production
source /software/badger/opt/staden_production/staden.profile

It will only run under X windows.

=head1 SYNPOSIS

view_alignment --help

view_alignment
    [--mfa_file multi fasta file]
    [--reg_conf registry_configuration_file]
    [--dbname compara_database]
    [--alignment_type alignment_type]
    [--set_of_species species1:species2:species3...]
    [--species_set_name name]
    [--method_link_species_set_id method_link_species_set_id]
    [--genomic_align_block_id genomic_align_block_id]
    [--species species]
    [--seq_region seq_region]
    [--seq_region_start start]
    [--seq_region_end end]
    [--gap4 gap4_database]
    [--display_scores]
    [--display_constrained_element_tags]
    [--display_exon_tags]
    [--display_gene_tags]
    [--display_start_end_tags]
    [--display_repeat_feature repeat1:repeat2:repeat3]
    [--file_of_repeat_feature file containing list of repeat features]
    [--pairwise_dbname pairwise_dbname]
    [--pairwise_url pairwise_url]
    [--expand_alignments]
    [--template_display]

=head1 OPTIONS

=head2 GETTING HELP

=over

=item B<[--help]>

  Prints help message and exits.

=back

=head2 CONFIGURATION

=over

=item B<[--mfa_file multi fasta file]>

Display the alignment from a multi fasta file. No other arguments required.

=item B<[--reg_conf registry_configuration_file]>

The Bio::EnsEMBL::Registry configuration file. If none is given,
the one set in ENSEMBL_REGISTRY will be used if defined, if not
~/.ensembl_init will be used. An example file (reg_public.conf) is given in this
directory

=item B<--dbname compara_db_name_or_alias>

The compara database to query. You can use either the original name or any of
the aliases given in the registry_configuration_file.

=item B<--compara_url url>

The location of the compara database can be defined using a url of the form:
mysql://user@host:Port/database_name

=item B<--url url>

The location of the core (species) databses can be defined using a url of the form:
mysql://user@host:Port/release_number
If the compara database is not defined by either the dbname or compara_url, the compara database in the release defined by release_number is used.

=item B<[--alignment_type]>

This should be an exisiting method_link_type eg PECAN, TRANSLATED_BLAT_NET, (B)LASTZ_NET, EPO, EPO_LOW_COVERAGE

=item B<[--set_of_species]>

The set of species used in the alignment. These should be the same as defined
in the registry configuration file aliases. The species should be separated by
a colon e.g. human:rat

=item B<[--species_set_name]>

The name defining the set of species eg mammals, amniotes, primates, fish, birds

=item B<[--method_link_species_set_id | mlss_id]>

Instead of defining the species_set or species_set_name and alignment_type, you can enter the
method_link_species_set_id instead

=item B<[--species]>

The reference species used to define the seq_region, seq_region_start and
seq_region_end. Should be the same as defined in the registry configuration
file alias.

=item B<[--seq_region]>

The name of the seq_region e.g. "17"

=item B<[--seq_region_start]>

The start of the region of interest.

=item B<[--seq_region_end]>

The end of the region of interest

=item B<--strand>

The strand, 1 for the forward strand, -1 for the reverse. Default 1.

=item B<[--genomic_align_block_id | gab_id]>

It is also possible to simply enter the genomic_align_block_id. This option
will ignore the seq_region arguments

=item B<[--display_constrained_element_tags]>

Tags (shown as coloured blocks in the contig editor) are created showing the
position of constrained elements (conserved regions) and their 'rejected
substitution' score. Only valid if conservation scores have been calculated for
the alignment. These are shown on the "consensus line" with a tag name of "CELE".

=item B<[--display_scores]>

A tag (shown as a coloured block in the contig editor) is created for each
base that has a conservation value and shows the conservation score. This can
produce a lot of tags which can take a long time to be read in. Only valid if
conservation scores have been calculated for the alignment. The tag is of type
"CSCO"

=item B<[--display_start_end_tags]>

This options tags the first and last base in each GenomicAlign region with a tag type of "FIRST" and "LAST".

=item B<[--repeat_feature]>

Valid repeat feature name eg "MIR".
Tags (shown as coloured blocks in the contig editor) are created for each
repeat found. Repeats have a tag type of "REPT". The repeats should be separated by a colon.

=item B<[--file_of_repeat_feature]>

A file containing a list of valid repeat feature names.
Tags (shown as coloured blocks in the contig editor) are created for each
repeat found. Repeats have a tag type of "REPT".

=item B<[--display_exon_tags]>

Tags (shown as coloured blocks in the contig editor) are created showing the
position of coding exons. The tag is of type "EXON",

=item B<[--display_gene_tags]>

Tags (shown as coloured blocks in the contig editor) are created showing the
position of genes. The tag is of type "GENE".

=item B<[--display_utr_tags]>

Tags (shown as coloured blocks in the contig editor) are created showing the
position of utr regions. The tag is of type "UTR".

=item B<[--pairwise_mlss_id --pairwise_dbname --pairwise_url]>

Tags (shown as coloured blocks in the contig editor) are created showing the
position of the corresponding pairwise blocks defined by the database and mlss_id.
This can be used to map pairwise blocks onto a multiple alignment. The tag is of type "GALN"

=item B<[--expand_alignments]>

Write the individual alignments for the low coverage species on separate lines.

=item B<[--template_display]>

Automatically bring up a template display. Useful for looking at an overall
view of tags

=item B<[--gap4]>

A gap4 database name. This is of the format database_name.version_number e.g.
dbname.0 If a name is not given, a default name is
generated of the form gap4_compara_ and then either the genomic_align_block_id
or "$seq_region_$seq_region_start_$seq_region_end" with a version value of 0.
If the database does not already exist, the script will create a new gap4
database. If the gap4 database does exist, no alignments will be added to the database
and the database will simply be opened.

=back

=head2 EXAMPLES

Using the public Ensembl database server, creating a database called a.0:
view_alignment --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type EPO_LOW_COVERAGE --species_set_name mammals --species human --seq_region 13 --seq_region_start 32911298 --seq_region_end 32913363 --gap4 a.0

Tag coding exons and constrained elements and bring up the template display:
view_alignment --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type EPO_LOW_COVERAGE --species_set_name mammals --species human --seq_region 13 --seq_region_start 32911298 --seq_region_end 32913363 --display_constrained_element_tag --display_exon_tags --template_display --gap4 a.0

Tag coding exons and utr regions
perl ~/src/ensembl_main/ensembl-compara/scripts/view_alignment/view_alignment.pl --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type EPO_LOW_COVERAGE --species_set_name mammals --species human --seq_region 22 --seq_region_start 17596942 --seq_region_end 17602420 --display_utr_tags --display_exon_tags --gap4 a.0

Using alignment genomic align block id:
view_alignment --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --genomic_align_block_id 6220000028031 --gap4 a.0

Tag conservation scores (small region only)
view_alignment --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type PECAN --species_set_name amniotes --species human --seq_region 13 --seq_region_start 32911776 --seq_region_end 32911894 --display_constrained_element_tag --display_scores --gap4 a.0

Tag repeat features
perl ~/src/ensembl_main/ensembl-compara/scripts/view_alignment/view_alignment.pl --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type EPO_LOW_COVERAGE --species_set_name mammals --species human --seq_region 22 --seq_region_start 17596942 --seq_region_end 17602420 --display_repeat_feature MIR3:trf:dust  --gap4 a.0

View pairwise blocks
perl ~/src/ensembl_main/ensembl-compara/scripts/view_alignment/view_alignment.pl --url mysql://anonymous@ensembldb.ensembl.org:5306/70 --alignment_type EPO_LOW_COVERAGE --species_set_name mammals --species human --seq_region 22 --seq_region_start 17596942 --seq_region_end 17602420 --pairwise_mlss_id 577 --pairwise_url mysql://anonymous@ensembldb.ensembl.org:5306/ensembl_compara_70 --gap4 a.0

=head2 HELP WITH GAP4

For more information on gap4, please visit the web site:

http://staden.sourceforge.net/

or click on the help button on the contig editor.

To remove the contig editor, press the "Quit" button.

Useful commands in the editor are:

To view the alignment in slice coordinates, you can set a sequence to be the
reference and set its start position to be 1 by right clicking the mouse over
the name of the species in the left hand box and selecting "Set as reference
sequence". This has the effect of ignoring padding characters.

To highlight differences between the sequences, select "Settings" from the menubar and select "Highlight Disagreements".

Tidying up:

A gap4 database consists of 4 files: db_name.version, db_name.version.aux,
db_name.version.log and db_name.version.BUSY eg a.0 a.0.aux a.0.log a.0.BUSY.
If you wish to delete a gap4 database all these files should be deleted.

=cut

my $reg_conf;
my $dbname = "";
my $compara_url;
my $urls;
my $help;
my $alignment_type = "";
my $set_of_species = "";
my $species;
my $method_link_species_set_id = undef;
my $seq_region = undef;
my $seq_region_start = undef;
my $seq_region_end = undef;
my $align_gab_id = undef;
my $gap4_db = undef;
my $disp_conservation_scores = undef;
my $disp_constrained_tags = undef;
my $set_of_repeat_features = undef;
my $file_of_repeat_features = undef;
my $disp_start_end_tags = undef;
my $disp_exon_tags = undef;
my $disp_utr_tags;
my $disp_gene_tags = undef;
my $template_display = 0;
my $_fofn_name = "ensembl_fofn";
my $_array_files;
my $_file_list;
my $exp_line_len = 67;
my $mfa_file;
my $pairwise_mlss_id;
my $pairwise_dbname;
my $pairwise_url;
my $expand_all_alignments = 0;
my $strand = 1;
my $species_set_name;

GetOptions(
     "help" => \$help,
     "reg_conf=s" => \$reg_conf,
     "dbname=s" => \$dbname,
     "compara_url=s" => \$compara_url,
     "url=s" => \@$urls,
     "alignment_type=s" => \$alignment_type,
     "set_of_species=s" => \$set_of_species,
     "species_set_name=s" => \$species_set_name,
     "method_link_species_set_id|mlss_id=i" => \$method_link_species_set_id,
     "genomic_align_block_id|gab_id=i" => \$align_gab_id,
     "species=s" => \$species,
     "seq_region=s" => \$seq_region,
     "seq_region_start=i" => \$seq_region_start,
     "seq_region_end=i" => \$seq_region_end,
     "strand=i" => \$strand,
     "gap4=s" => \$gap4_db,
     "display_scores" => \$disp_conservation_scores,
     "display_constrained_element_tags" => \$disp_constrained_tags,
     "display_exon_tags" => \$disp_exon_tags,
     "display_utr_tags" => \$disp_utr_tags,
     "display_gene_tags" => \$disp_gene_tags,
     "display_start_end_tags" => \$disp_start_end_tags,
     "display_repeat_feature=s" => \$set_of_repeat_features,
     "file_of_repeat_feature=s" => \$file_of_repeat_features,
     "template_display" => \$template_display,
     "mfa_file=s" => \$mfa_file,
     "pairwise_mlss_id=i" => \$pairwise_mlss_id,
     "pairwise_dbname=s" => \$pairwise_dbname,
     "pairwise_url=s" => \$pairwise_url,
     "expand_alignments" => \$expand_all_alignments,
  );

if ($help) {
  exec("/usr/bin/env perldoc $0");
}

#if a gap4_db is defined and exists, then bring up the contig editor
#immediately without doing any assembly.
if (defined $gap4_db) {
    if (-e $gap4_db) {
	print "Database $gap4_db already exists. Bringing up contig editor\n";
	system "view_alignment.tcl $gap4_db [] $template_display";
	exit;
    }
}

my $reg = "Bio::EnsEMBL::Registry";

$reg->no_version_check(1);

# Configure the Bio::EnsEMBL::Registry
# Uses $reg_conf if supplied. Uses ENV{ENSMEBL_REGISTRY} instead if defined.
# Uses ~/.ensembl_init if all the previous fail.

#Load in alignment from multi fasta file
if (defined $mfa_file) {
    load_multi_fasta_file($mfa_file);
    exit;
}

#Load registry from configuration file
my $compara_dba;
if ($reg_conf) {
    $reg->load_all($reg_conf, 1);
    if ($dbname) {
        $compara_dba = $reg->get_DBAdaptor($dbname, "compara");
    } else {
        $compara_dba = $reg->get_DBAdaptor("Multi", "compara");
    }
}

#Set up compara_dba from url
if ($compara_url) {
    $compara_dba = new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(-url=>$compara_url);
}

#Load core databases if defined via url
if ($urls) {
    foreach my $url (@$urls) {
	$reg->load_registry_from_url($url);
    }
    #Use default compara database if not defined
    $compara_dba = $reg->get_DBAdaptor("Multi", "compara") unless (defined $compara_dba);
}

#Getting Bio::EnsEMBL::Compara::GenomicAlignBlockAdaptor
my $genomic_align_block_adaptor = $compara_dba->get_GenomicAlignBlockAdaptor();

#Getting Bio::EnsEMBL::Compara::GenomicAlignTreeAdaptor
my $genomic_align_tree_adaptor = $compara_dba->get_GenomicAlignTreeAdaptor();
throw ("No genomic_align_tree adaptor") if (!$genomic_align_tree_adaptor);

# Getting Bio::EnsEMBL::Compara::MethodLinkSpeciesSetAdaptor
my $method_link_species_set_adaptor = $compara_dba->get_MethodLinkSpeciesSetAdaptor();
throw ("No method_link_species_set") if (!$method_link_species_set_adaptor);

# Getting Bio::EnsEMBL::Compara::AlignAdaptor
my $align_slice_adaptor = $compara_dba->get_AlignSliceAdaptor();
throw ("No align_slice") if (!$align_slice_adaptor);

# Getting all the Bio::EnsEMBL::Compara::GenomeDB objects
my $genome_db_adaptor = $compara_dba->get_GenomeDBAdaptor();
throw("No genome_db adaptor") if (!$genome_db_adaptor);

# Getting Bio::EnsEMBL::Compara::ConservationScore object
my $cs_adaptor;
if ($disp_conservation_scores) {
    $cs_adaptor = $compara_dba->get_ConservationScoreAdaptor();
    throw ("No conservation scores available\n") if (!$cs_adaptor);
}

my $repeat_feature_adaptor;

#unique identifier for each sequence
my $_seq_num = 1;

#scientific name of reference species
my $species_name;

if (defined $species) {
    my $this_meta_container_adaptor = $reg->get_adaptor($species, 'core', 'MetaContainer');
    throw("Registry configuration file has no data for connecting to <$species>")
      if (!$this_meta_container_adaptor);
    #$species_name = $this_meta_container_adaptor->get_scientific_name;
    $species_name = $this_meta_container_adaptor->get_production_name;
}

#if have alignment genomic align block id
if (defined $align_gab_id) {
    my $genomic_align_block = $genomic_align_block_adaptor->fetch_by_dbID($align_gab_id);
    throw ("Invalid genomic_align_block_id") if (!$genomic_align_block);
    my $contig_num = $_seq_num;
    #if $species is set, use that as reference genomic align else used first
    my $gas = $genomic_align_block->get_all_GenomicAligns;

    #set first ga as reference. Complement if necessary
    $genomic_align_block->reference_genomic_align($gas->[0]);
    if (defined $species_name) {
	foreach my $ga (@$gas) {
	    if ($ga->dnafrag->genome_db->name eq $species_name) {
		$genomic_align_block->reference_genomic_align($ga);
	    }
	}
    }

    if (defined($genomic_align_block->reference_genomic_align) && $genomic_align_block->reference_genomic_align->dnafrag_strand == -1) {

	#this was commented out - don't know why because looking at a block, I need
	#this
	$genomic_align_block->reverse_complement();
    }
    my $align_slice = $align_slice_adaptor->fetch_by_GenomicAlignBlock($genomic_align_block, 1, "restrict");

    #convert to tree if necessary so I get the correct alignments for 2X genomes
    if ($genomic_align_block->method_link_species_set->method->class =~ /GenomicAlignTree/) {
	$genomic_align_block = $genomic_align_tree_adaptor->fetch_by_GenomicAlignBlock($genomic_align_block);
#	print "found tree \n";
    } else {
#	print "found block\n";
    }

    #convert to tree if necessary so I get the correct alignments for 2X genomes
    writeExperimentFiles($genomic_align_block, $align_slice, $contig_num, 1);

    open (FOFN, ">$_fofn_name") || die "ERROR writing ($_fofn_name) file\n";
    print FOFN "$_file_list";
    close (FOFN);

    if (!defined $gap4_db) {
	$gap4_db = "gap4_compara_" . $align_gab_id . ".0";
    }

    system "view_alignment.tcl $gap4_db $_fofn_name $template_display";

    #remove experiment files
    unlink @$_array_files;
    #remove file of filenames
    unlink $_fofn_name;
    exit;
}

my $genome_dbs;
foreach my $this_species (split(":", $set_of_species)) {
    my $genome_db = $genome_db_adaptor->fetch_by_registry_name($this_species);

    # Add Bio::EnsEMBL::Compara::GenomeDB object to the list
    push(@$genome_dbs, $genome_db);
}

#Find from species and alignment type
my $method_link_species_set;
if ($method_link_species_set_id) {
    $method_link_species_set = $method_link_species_set_adaptor->fetch_by_dbID($method_link_species_set_id);
    throw("The database do not contain any data for method link species set id $method_link_species_set_id!") if (!$method_link_species_set);
} elsif ($alignment_type && $species_set_name) {
    $method_link_species_set = $method_link_species_set_adaptor->fetch_by_method_link_type_species_set_name($alignment_type, $species_set_name);
    throw("The database do not contain any $alignment_type data for species_set_name $species_set_name!") if (!$method_link_species_set);
} elsif ($alignment_type && $genome_dbs) {
    $method_link_species_set = $method_link_species_set_adaptor->fetch_by_method_link_type_GenomeDBs($alignment_type, $genome_dbs);
    throw("The database do not contain any $alignment_type data for $set_of_species!") if (!$method_link_species_set);
}

#Fetching slice for species
my $slice;
my $genomic_align_blocks;
my $slice_adaptor;

if ($seq_region) {
    $slice_adaptor = $reg->get_adaptor($species, 'core', 'Slice');
    throw("Registry configuration file has no data for connecting to <$species>") if (!$slice_adaptor);

    #Prevent trying to display an entire chromosome
    throw ("Must define seq_region_start and seq_region_end") if (!$seq_region_start || !$seq_region_end);

    $slice = $slice_adaptor->fetch_by_region('toplevel', $seq_region, $seq_region_start, $seq_region_end, $strand);
	throw("No Slice can be created with coordinates $seq_region:$seq_region_start-$seq_region_end") if (!$slice);

    # Fetching all the GenomicAlignBlock corresponding to this Slice:
    $genomic_align_blocks =
	$genomic_align_block_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice($method_link_species_set, $slice);
} else {
    throw ("Either a genomic_align_block_id or a seq_region must be defined");
}

#write experiment files for each alignment found
foreach my $genomic_align_block (@$genomic_align_blocks) {
    my $contig_num = $_seq_num;

    #print "GAB " . $genomic_align_block->dbID . " start " . $genomic_align_block->reference_genomic_align->dnafrag_start . " end " . $genomic_align_block->reference_genomic_align->dnafrag_end . "\n";

    if ($genomic_align_block->method_link_species_set->method->class =~ /GenomicAlignTree/) {
	$genomic_align_block = $genomic_align_tree_adaptor->fetch_by_GenomicAlignBlock($genomic_align_block);
    }

    my $genomic_align = $genomic_align_block->reference_genomic_align;
    my $restricted_gab = $genomic_align_block->restrict_between_reference_positions($slice->start, $slice->end, $genomic_align);

    #don't use restricted gab here because this causes problems elsewhere
    #since the new gab doesn't retain all the information of the original gab
    #such as original strand
    my $align_slice = $align_slice_adaptor->fetch_by_Slice_MethodLinkSpeciesSet($slice, $method_link_species_set, 1, "restrict");

    #Write experiment files
    writeExperimentFiles($restricted_gab, $align_slice, $contig_num, 1);
}

open (FOFN, ">$_fofn_name") || die "ERROR writing ($_fofn_name) file\n";
print FOFN "$_file_list";
close (FOFN);

#Automatically create gap4 database name
if (!defined $gap4_db) {
    $gap4_db = "gap4_compara_" . $seq_region . "_" . $seq_region_start . "_" . $seq_region_end . ".0";
}

#call tcl interface to gap4 to create a gap4 database and bring up a contig
#editor for each genomic_align_block
system "view_alignment.tcl $gap4_db $_fofn_name $template_display";

#remove experiment files
unlink @$_array_files;
#remove file of filenames
unlink $_fofn_name;

sub writeExperimentFiles {
    my ($gab, $align_slice, $contig_num, $new_contig) = @_;
    my $done_once = 0;

    my $repeat_feature_list;
    if (defined $set_of_repeat_features) {
	foreach my $repeat (split(":", $set_of_repeat_features)) {
	    $repeat_feature_list->{lc($repeat)} = 1;
	}
    }
    if (defined $file_of_repeat_features) {
	open FILE, "< $file_of_repeat_features" or die "Can't open file $file_of_repeat_features: $!\n";
	while (<FILE>) {
	    my $line = $_;
	    chomp $line;
	    $repeat_feature_list->{lc($line)} = 1;
	}
	close FILE;
    }

    #writeSequences($align_slice, $contig_num, $new_contig);

    #need to condense down the alignments from the target species into one alignment
    my $segments;
    my $tree_ga;
    if ($gab->isa('Bio::EnsEMBL::Compara::GenomicAlignTree')) {
        #use GenomicAlignTree
        #to expand all alignments
        if ($expand_all_alignments) {
            foreach my $this_node (@{$gab->get_all_sorted_genomic_align_nodes()}) {
                my $genomic_align_group = $this_node->genomic_align_group;
                next if (!$genomic_align_group);
                my $new_genomic_aligns = [];

                foreach my $this_genomic_align (@{$genomic_align_group->get_all_GenomicAligns}) {
                    push @$segments, $this_genomic_align;
                }
            }
        } else {
            #to compact all the alignments
            #order according to tree. Need to define ref species
            foreach my $this_genomic_align_tree (@{$gab->get_all_sorted_genomic_align_nodes()}) {
                next if (!$this_genomic_align_tree->genomic_align_group);
                push(@{$segments}, $this_genomic_align_tree->genomic_align_group);
            }
        }
    } else {
        $segments = $gab->get_all_GenomicAligns;
    }

    #create mfa file of multiple alignment from genomic align block
    foreach my $this_segment (@{$segments}) {

	my $filename = "ensembl_$_seq_num" . ".exp";
	my $aligned_sequence = $this_segment->aligned_sequence;
	next if (!defined $aligned_sequence);

	$aligned_sequence =~ tr/-/*/;
	$aligned_sequence =~ s/(.{60})/$1\n/g;
	$aligned_sequence =~ s/(.*)/     $1/g;

        open my $exp_fh, ">$filename" or die "ERROR writing ($filename) file\n";

	my $name;
	if (UNIVERSAL::isa($this_segment, "Bio::EnsEMBL::Compara::GenomicAlignTree")) {
	    $name = $this_segment->genomic_align_group->genome_db->name;
	} else {
	    $name = $this_segment->genome_db->name;
	}

	$name =~ tr/ /_/;
	#print "name $name\n";
	#print "name " . $name . " " . $aligned_sequence . "\n";
	if ($new_contig) {
	    $contig_num = $name . "_" . $_seq_num;
	}
	print $exp_fh "ID   " . $name . "_$_seq_num\n";
	if ($new_contig) {
	    print $exp_fh "AP   *new* + 0 0\n";
	} else {
	    print $exp_fh "AP   $contig_num + 0 0\n";
	}

	my $genomic_aligns;
	if (UNIVERSAL::isa($this_segment, "Bio::EnsEMBL::Compara::GenomicAlignTree")) {
	    $genomic_aligns = $this_segment->genomic_align_group->get_all_GenomicAligns;
        } elsif (UNIVERSAL::isa($this_segment, "Bio::EnsEMBL::Compara::GenomicAlignGroup")) {
            #When have GenomicAlignTree when $expand_all_alignments is false
            $genomic_aligns = $this_segment->get_all_GenomicAligns;
	} else {
	    $genomic_aligns->[0] = $this_segment;
	}
	foreach my $genomic_align (@$genomic_aligns) {
            #print "GENOMIC ALIGN " . $genomic_align->dnafrag->genome_db->name . "\n";

	    #write gene tags
	    if (defined $disp_gene_tags) {
		my $slice = $genomic_align->get_Slice;
		next if (!defined $slice);
                my $gene_array = getGenes($slice);
                writeFeats("gene", $gene_array, $genomic_align, $exp_fh);
	    }

	    #write exon tags
	    if (defined $disp_exon_tags) {
		#my $min_length = 57;
		my $min_length = 1;

		my $slice = $genomic_align->get_Slice;
		next unless (defined $slice);
		my $exon_array = getCodingExons($slice, $min_length);
                writeFeats("exon", $exon_array, $genomic_align, $exp_fh);
            }

            #write utr tags
            if ($disp_utr_tags) {
                my $slice = $genomic_align->get_Slice;
		next unless(defined $slice);
		my $utr_array = getUtrs($slice);
                writeFeats("utr", $utr_array, $genomic_align, $exp_fh);
            }

	    #write constrained element tags
	    #only do once (written on consensus)
	    if (!$done_once && $disp_constrained_tags) {
		    writeConstrainedBlocks($align_slice, $exp_fh);
	    }

	    #write conservation score tags
	    #only do once (written on consensus)
	    if (!$done_once && $disp_conservation_scores) {
		writeConservationScores($align_slice, $exp_fh);
	    }

	    #write repeat feature tags
	    if (defined $set_of_repeat_features || defined $file_of_repeat_features) {
		foreach my $a_slice (@{$align_slice->get_all_Slices}) {
		    my $original_feature = $a_slice->get_all_underlying_Slices($a_slice->start, $a_slice->end)->[0];

		    #need to find the current genomic_align in the align_slice list.
		    if ($a_slice->genome_db->name eq $genomic_align->genome_db->name && $original_feature->seq_region_name eq $genomic_align->dnafrag->name && $original_feature->start == $genomic_align->dnafrag_start && $original_feature->end == $genomic_align->dnafrag_end) {

			writeRepeatFeatures($a_slice, $gab->length, $repeat_feature_list, $exp_fh);
		    }
		}
	    }

	    #write start/end tags
	    if ($disp_start_end_tags) {
		writeStartEndTags($genomic_align,$exp_fh);
	    }

	    #write pairwise blocks on reference sequence
	    if (defined $pairwise_mlss_id) {
                my $p_mlss_adaptor;
                my $pairwise_compara_dba;

                if ($pairwise_dbname) {
                    $pairwise_compara_dba = $reg->get_adaptor($pairwise_dbname, 'compara');
                } elsif ($pairwise_url) {
                    $pairwise_compara_dba = new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(-url=>$pairwise_url);
                }

		if ($genomic_align == $gab->reference_genomic_align) {
                    writePairwiseBlocks($pairwise_compara_dba, $genomic_align, $pairwise_mlss_id, $exp_fh);
                } else {
                    my $pairwise_name;
                    my $p_mlss_adaptor = $pairwise_compara_dba->get_MethodLinkSpeciesSetAdaptor();
                    throw ("No method_link_species_set") if (!$p_mlss_adaptor);

                    my $pairwise_mlss = $p_mlss_adaptor->fetch_by_dbID($pairwise_mlss_id);
                    throw("The database do not contain any data for method link species set id $method_link_species_set_id!") if (!$pairwise_mlss);

                    #find the non-reference pairwise name
                    foreach my $spp (@{$pairwise_mlss->species_set_obj->genome_dbs}) {
                        if ($spp->name ne $species_name) {
                            $pairwise_name = $spp->name;
                            last;
                        }
                    }
                    if ($pairwise_name eq $genomic_align->genome_db->name) {
                        writePairwiseBlocks($pairwise_compara_dba, $genomic_align, $pairwise_mlss_id, $exp_fh);
                    }
                }
            }
        }

	#write out sequence
	print $exp_fh "SQ\n";
	print $exp_fh "$aligned_sequence\n";
	print $exp_fh "//";
	close($exp_fh);
	$_file_list .= "$filename\n";
	push @$_array_files, $filename;
	$_seq_num++;
	$new_contig = 0;
        $done_once = 1;
    }
}

#convert from chromosome coords to alignment coords
#returns $chr_pos in alignment coords
sub findAlignPos {
    my ($chr_pos, $total_chr_pos, $cigar_line) = @_;

    #Cigar_line must contain at least one M
    if ($cigar_line !~ /M/) {
        return $chr_pos;
    }

    my @cig = ( $cigar_line =~ /(\d*[GMDXI])/g );

    my $i = 0;

    my ($cigType, $cigLength);
    my $total_pos = 0;
    my $align_pos;
    my $last_total_pos; #Deal with the end of low coverage genomic_aligns which may end in D and X

    #convert chr_pos into alignment coords
    while ($total_chr_pos <= $chr_pos && $i < @cig) {
	#print "i $i $cig[$i]\n";
	my $cigElem = $cig[$i++];
	if (! defined $cigElem) {
	    #print "total_chr_pos $total_chr_pos chr_pos $chr_pos i $i\n";
	    next;
	}

	$cigType = substr( $cigElem, -1, 1 );
	$cigLength = substr( $cigElem, 0 ,-1 );
	$cigLength = 1 unless ($cigLength =~ /^\d+$/);

	if ($cigType ne "I") {
	    $total_pos += $cigLength;
	}
	if( $cigType eq "M" || $cigType eq "I") {
	    $total_chr_pos += $cigLength;

            $last_total_pos = $total_pos;
	}
    }
    my $start_offset = $total_chr_pos - $chr_pos;

    if ($cigType eq "M") {
	$align_pos = $total_pos - $start_offset + 1;
    } else {
        $align_pos = $last_total_pos; #Catch the case when finished the cigar_line which does not end with M
    }
    return $align_pos;
}

#get genes
sub getGenes {
    my ($slice) = @_;

    my @genes;
    foreach my $gene (@{$slice->get_all_Genes}) {
        $gene->seqname("GENE");
        push @genes, $gene;
    }
    my $gene_array = [sort {$a->start <=> $b->start} @genes];
    return $gene_array;
}

#return all coding exons in slice above min_length
sub getCodingExons {
    my ($slice, $min_length) = @_;

    if (!defined $min_length) {
	$min_length = 1;
    }

    my @exons;
    my $gene_cnt = 0;
    my $trans_cnt = 0;
    foreach my $gene (@{$slice->get_all_Genes}) {
	#only select protein coding exons
	if (lc($gene->biotype) eq "protein_coding") {

	    #get transcripts
	    foreach my $trans (@{$gene->get_all_Transcripts}) {

		#get translated exons with start and end exons truncated to
		#CDS regions
		foreach my $exon (@{$trans->get_all_translateable_Exons}) {
		    unless (defined $exon->stable_id) {
			warn("COREDB error: does not contain exon stable id for translation_id ".$exon->dbID."\n");
			next;
		    }
		    #only store exons of at least $min_length
		    if (($exon->end - $exon->start + 1) >= $min_length) {
			if ($exon->end >= 1 && $exon->start <= ($slice->end-$slice->start+1)) {
                            $exon->seqname("EXON"); #tag name for contig editor
			    push @exons, $exon;
			}
		    }
		}
	    }
	}
    }

    my $exon_array = [sort {$a->start <=> $b->start} @exons];
    return $exon_array;
}

#get utrs
sub getUtrs {
    my ($slice) = @_;

    my $all_features;

    my $genes = $slice->get_all_Genes_by_type('protein_coding');
    foreach my $this_gene (@$genes) {
        my $transcripts = $this_gene->get_all_Transcripts;
        foreach my $this_transcript (@$transcripts) {
            next if ($this_transcript->biotype ne "protein_coding");
            foreach my $exon (@{$this_transcript->get_all_Exons}) {
                my ($start, $end);
                #5' utr
                next if (!$this_transcript->coding_region_start);
                if ($exon->start < $this_transcript->coding_region_start) {
                    $start = $exon->start;
                    if ($exon->end < $this_transcript->coding_region_start) {
                        $end = $exon->end;
                    } else {
                        $end = $this_transcript->coding_region_start-1;
                    }
                    my $utr = new Bio::EnsEMBL::Exon(-start => $start,
                                                     -end => $end,
                                                     -slice => $slice,
                                                     -strand => $this_transcript->strand,
                                                     -stable_id => $exon->stable_id,
                                                     -seqname => "UTRS"); #tag name for contig editor
                    if ($utr->end - $utr->start >= 0) {
                        push @$all_features, $utr;
                    }
                }
                #3' utr
                next if (!$this_transcript->coding_region_end);
                if ($exon->end > $this_transcript->coding_region_end) {
                    $end = $exon->end;
                    if ($exon->start > $this_transcript->coding_region_end) {
                        $start = $exon->start;
                    } else {
                        $start = $this_transcript->coding_region_end+1;
                    }
                    my $utr = new Bio::EnsEMBL::Exon(-start => $start,
                                                     -end => $end,
                                                     -slice => $slice,
                                                     -strand => $this_transcript->strand,
                                                     -stable_id => $exon->stable_id,
                                                     -seqname => "UTRS"); #tag name for contig editor
                    if ($utr->end - $utr->start >= 0) {
                        push @$all_features, $utr;
                    }
                }
            }
        }
    }
    my $utr_array;
    if ($all_features) {
        $utr_array = [sort {$a->start <=> $b->start} @$all_features];
    }
    return $utr_array;

}

#Write exon/gene/utr features
sub writeFeats {
    my ($feat_name, $feat_array, $genomic_align, $exp_fh) = @_;

    foreach my $feat (@$feat_array) {

        my $slice = $genomic_align->get_Slice;

        #trim feat at start and end of slice
        my $f_start = $feat->start;
        my $f_end = $feat->end;
        if ($feat->start < 1) {
            $f_start = 1;
        }
        if ($feat->end > $slice->length) {
            $f_end = $slice->length;
        }

        #convert into alignment coords
        my $feat_start = findAlignPos($f_start, 1, $genomic_align->cigar_line);
        my $feat_end = findAlignPos($f_end, 1, $genomic_align->cigar_line);

        my $tag_name = $feat->seqname;

        printf($exp_fh "TG   %s + %d..%d %s %s %s:%d-%d:%d\n", $tag_name, $feat_start, $feat_end, $feat_name, $feat->stable_id, $genomic_align->dnafrag->name, ($feat->start + $slice->start - 1), ($feat->end + $slice->start - 1), $feat->strand);
    }
}

#add CELE tag on the consensus for each constrained element.
sub writeConstrainedBlocks {
    my ($align_slice, $exp_fh) = @_;

    my $cons_elems = $align_slice->get_all_ConstrainedElements();

    foreach my $cons_elem (@$cons_elems) {
	printf($exp_fh "TC   CELE + %d..%d Constrained element score=%d\n",
	       $cons_elem->start,
	       $cons_elem->end,
	       $cons_elem->score);
    }
}

#add CSCO tag on each base on the consensus. Use with care! Can take a long
#time
sub writeConservationScores {
    my ($align_slice, $exp_fh) = @_;

    my $cons_scores = $align_slice->get_all_ConservationScores($align_slice->get_all_Slices()->[0]->length, "MAX", 1);
    my $i;
    foreach my $cons_score (@$cons_scores) {
	if ($cons_score->diff_score) {
	    $i = $cons_score->position;
	    printf($exp_fh "TC   CSCO + %d..%d score=%.3f\n", $i, $i, $cons_score->diff_score);
	}
	$i++;
    }
}

#add REPT tags on each species for repeat features
#in repeat_feature_list
sub writeRepeatFeatures {
    my ($a_slice, $gab_length, $repeat_feature_list, $exp_fh) = @_;

    my $repeat_features = $a_slice->get_all_RepeatFeatures;
    foreach my $repeat_feature (@$repeat_features) {
	my $name = $repeat_feature->repeat_consensus->name;
	if ($repeat_feature_list->{lc($name)}) {
	    $name .= " length=" .  $repeat_feature->length . " strand=" .$repeat_feature->strand . " score= " . $repeat_feature->score . " hstart " . $repeat_feature->hstart . " hend " . $repeat_feature->hend;
	    my $start = $repeat_feature->start;
	    if ($start < 1) {
		$start = 1;
	    }
	    my $end = $repeat_feature->end;
	    if ($end > $gab_length) {
		$end = $gab_length;
	    }
            printf($exp_fh "TG   REPT + %d..%d %s\n", $start, $end, $name);
	}
    }
}

#add a START and STOP tag to the first and last base of each genomic_align. Useful if
#trying to find the first and last base of a sequence!
sub writeStartEndTags {
    my ($genomic_align, $exp_fh) = @_;

    my $start = findAlignPos($genomic_align->dnafrag_start,
			     $genomic_align->dnafrag_start,
			     $genomic_align->cigar_line);
    my $end = findAlignPos($genomic_align->dnafrag_end,
			   $genomic_align->dnafrag_start,
			   $genomic_align->cigar_line);

    printf($exp_fh "TG   FIRS + %d..%d Start %s %d\n", $start, $start, $genomic_align->dnafrag->name, $genomic_align->dnafrag_start);
    printf($exp_fh "TG   LAST + %d..%d End %s %d\n", $end, $end, $genomic_align->dnafrag->name, $genomic_align->dnafrag_end);
}

#add GALN tag on the consensus for each constrained element.
sub writePairwiseBlocks {
    my ($pairwise_compara_dba, $genomic_align, $pairwise_mlss_id, $exp_fh) = @_;

    my $gab_adaptor = $pairwise_compara_dba->get_GenomicAlignBlockAdaptor();
    throw ("No genomic_align_blocks") if (!$gab_adaptor);

    my $mlss_adaptor = $pairwise_compara_dba->get_MethodLinkSpeciesSetAdaptor();
    throw ("No method_link_species_set") if (!$mlss_adaptor);

    my $pairwise_mlss = $mlss_adaptor->fetch_by_dbID($pairwise_mlss_id);
    throw("The database do not contain any data for method link species set id $method_link_species_set_id!")
    if (!$pairwise_mlss);

    my $ref_slice = $genomic_align->get_Slice;
    my $gabs = 	$gab_adaptor->fetch_all_by_MethodLinkSpeciesSet_Slice($pairwise_mlss, $genomic_align->get_Slice,undef,undef,1);

    foreach my $gab (@$gabs) {
	my $ga = $gab->reference_genomic_align;
	my $non_ref = $gab->get_all_non_reference_genomic_aligns->[0];

	my @pairwise_ref_slices;

	if ($genomic_align->dnafrag->coord_system_name ne $ga->dnafrag->coord_system_name) {
	    my $projections = $ga->get_Slice->project($genomic_align->dnafrag->coord_system_name);
	    foreach my $proj (@$projections) {
		my $new_slice = $proj->to_Slice();
		#print "new slice " . $new_slice->start . " " . $new_slice->end . $new_slice->name . "\n";
		push @pairwise_ref_slices, $proj->to_Slice();
	    }
 	} else {
	    $pairwise_ref_slices[0] = $ga->get_Slice;
	}
	foreach my $pairwise_ref_slice (@pairwise_ref_slices) {

	    my $start = findAlignPos($pairwise_ref_slice->start,
				     $genomic_align->dnafrag_start,
				     $genomic_align->cigar_line);
	    my $end = findAlignPos($pairwise_ref_slice->end,
				   $genomic_align->dnafrag_start,
				   $genomic_align->cigar_line);

	    printf($exp_fh "TG   GALN + %d..%d %s start=%d end=%d non-ref %s start=%d end=%d\n", $start, $end, $ga->dnafrag->name, $ga->dnafrag_start, $ga->dnafrag_end, $non_ref->dnafrag->name, $non_ref->dnafrag_start, $non_ref->dnafrag_end);
	}
    }
}

#Load a msa file directly, no databases needed
sub load_multi_fasta_file {
    my ($mfa_file) = @_;

    my $exp_name;
    my $new_contig = 1;
    my $contig_num;

    open FILE, "< $mfa_file" or die "Can't open file $mfa_file: $!\n";
    while (<FILE>) {
	my $line = $_;
	chomp $line;
	#ignore comments
	next if ($line =~ /^;/);
	if ($line =~ /^>/) {
	    $line =~ tr/>//d;
	    if (defined $exp_name){
		print EXP "//\n";
		close (EXP);
		push @$_array_files, $exp_name;
		$_file_list .= "$exp_name\n";
	    }
	    #only take the first word (stop at |)

	    #Normal case
	    #my ($name) = $line =~ /(\w*)/;

	    #Hack when have multiple species lines in single block
	    my $name = $line;
	    $name =~ s/\//_/;

	    #$exp_name = $line . ".exp";
	    $exp_name = $name . ".exp";
	    if (length($exp_name) >= 255) {
		$exp_name = substr $exp_name, 0, 254;
	    }
	    open (EXP, ">$exp_name") || die "ERROR writing ($exp_name) file\n";
	    #print EXP "ID   $line\n";
	    print EXP "ID   $name\n";

	    if ($new_contig) {
		print EXP "AP   *new* + 0 0\n";
		#$contig_num = $line;
		$contig_num = $name;
		$new_contig = 0;
	    } else {
		print EXP "AP   $contig_num + 0 0\n";
	    }
	    print EXP "SQ\n";
	    print "Creating $exp_name\n";

	} else {
	    $line =~ tr/-/*/;
	    print EXP "     $line\n";
	}
    }
    print EXP "//\n";
    close (EXP);
    push @$_array_files, $exp_name;
    $_file_list .= "$exp_name\n";

    open (FOFN, ">$_fofn_name") || die "ERROR writing ($_fofn_name) file\n";
    print FOFN "$_file_list";
    close (FOFN);

    if (!defined $gap4_db) {
	$gap4_db = "gap4_compara_" . $mfa_file . ".0";
    }

    system "view_alignment.tcl $gap4_db $_fofn_name $template_display";

    #remove experiment files
    unlink @$_array_files;
    #remove file of filenames
    unlink $_fofn_name;
}


text:
package Condition;

public class BurnedCondition extends UnhealthyCondition {
}


text:
#ifndef MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_INCLUDE_AUDIO_NETWORK_ADAPTOR_CONFIG_H_
#define MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_INCLUDE_AUDIO_NETWORK_ADAPTOR_CONFIG_H_

#include <stddef.h>

#include "absl/types/optional.h"

namespace webrtc {

struct AudioEncoderRuntimeConfig {
  AudioEncoderRuntimeConfig();
  AudioEncoderRuntimeConfig(const AudioEncoderRuntimeConfig& other);
  ~AudioEncoderRuntimeConfig();
  AudioEncoderRuntimeConfig& operator=(const AudioEncoderRuntimeConfig& other);
  bool operator==(const AudioEncoderRuntimeConfig& other) const;
  absl::optional<int> bitrate_bps;
  absl::optional<int> frame_length_ms;
  // Note: This is what we tell the encoder. It doesn't have to reflect
  // the actual NetworkMetrics; it's subject to our decision.
  absl::optional<float> uplink_packet_loss_fraction;
  absl::optional<bool> enable_fec;
  absl::optional<bool> enable_dtx;

  // Some encoders can encode fewer channels than the actual input to make
  // better use of the bandwidth. |num_channels| sets the number of channels
  // to encode.
  absl::optional<size_t> num_channels;

  // This is true if the last frame length change was an increase, and otherwise
  // false.
  // The value of this boolean is used to apply a different offset to the
  // per-packet overhead that is reported by the BWE. The exact offset value
  // is most important right after a frame length change, because the frame
  // length change affects the overhead. In the steady state, the exact value is
  // not important because the BWE will compensate.
  bool last_fl_change_increase = false;
};

}  // namespace webrtc

#endif  // MODULES_AUDIO_CODING_AUDIO_NETWORK_ADAPTOR_INCLUDE_AUDIO_NETWORK_ADAPTOR_CONFIG_H_


text:
import os
import csv
import json
import yaml

import numpy
from numpy import loadtxt

file_name_json = 'input.json'
file_name_yaml = 'input.yaml'
file_name_csv = 'input.csv'

data = dict()

with open(file_name_csv, 'r') as csvfile:
    d_reader = csv.DictReader(csvfile)
    dict_list = []

    headers = d_reader.fieldnames
    print(headers)

    for x in d_reader:
        dict_list.append(x)

    with open(file_name_json, 'w') as f_json:
        json.dump(dict_list,f_json)

    with open(file_name_yaml, 'w') as f_yaml:
        output = yaml.dump(dict_list, default_flow_style=False, explicit_start=True)
        yaml.dump(output,f_yaml)

with open(file_name_yaml, 'r') as f_yaml:
    yaml_str = yaml.load(f_yaml)
    print(type(yaml_str))


text:
/*
 * $Id$
 */

#ifndef PLATFORM_H
#define PLATFORM_H 1

#warning ***********************************************************
#warning  Using platform.h is deprecated. See common/common_util.
#warning  -- aragorn, 2006/03/15
#warning ***********************************************************

#include "unix/setproctitle.h"
#include "unix/sb_fopen.h"
#include "unix/sb_open.h"
#include "unix/sb_lockfile.h"
#include "unix/sb_tstat.h"
#include "unix/flock.h"
#include "unix/hash.h"
#include "generic/msort.h"
#include "generic/queue.h"
#include "generic/qsort2.h"
#include "generic/connect_nonb.h"
#include "generic/sz_string.h"
#include "generic/str_misc.h"
#include "generic/md5_global.h"
#include "generic/md5.h"

#include "unix/os-aix-dso.h"

#endif


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

@namespace xlink url("http://www.w3.org/1999/xlink");

Documentation {
  display: block;
  font-family: Verdana, sans-serif;
  font-size: 11pt;
  margin: 8px;
}
Author {
  display: block;
  font-size: 90%;
}
Author:before {
  content: "Author: ";
  font-weight: bold;
}
UpdateDate {
  display: block;
  font-size: 90%;
}
UpdateDate:before {
  content: "Updated: ";
  font-weight: bold;
}
Title {
  display: block;
  font-size: 250%;
  font-weight: bold;
  letter-spacing: -1.25pt;
  margin-top: 0;
  margin-bottom: .5em;
}
SectionHeading {
  display: block;
  font-size: 125%;
  font-weight: bold;
  margin-top: 2em;
  margin-bottom: .5em;
}
Body {
  display: block;
  margin-top: 1em;
  margin-bottom: .5em;
}
SectionHeading + Body {  /* body after section heading */
  margin-top: 0;
}
Components {
  display: block;
  margin-top: 1em;
  margin-left: .5in;
  border: dotted 1px black;
}
:link:hover {
  background-color: blue;
  color: white;
  cursor: pointer;
}

/* workaround for above rule not working */
*[xlink|type] {
  cursor: pointer;
}

/* workaround for above rule not working */
*[xlink|show="replace"] {
  cursor: pointer;
}

Term {
  display: block;
  font-weight: bold;
  background-color: lightyellow;
  padding-left: .5em;
}
Definition {
  display: block;
  margin-left: 40px;
}
Interfaces, Characteristics, Items, Categories {
  display: block;
  margin-left: 40px;
  list-style-position: outside;
  list-style-type: disc;
}
Purposes {
  display: block;
  margin-left: 40px;
  list-style-position: outside;
  list-style-type: decimal;
  counter-reset: -html-counter 0;
}
Interface, Characteristic, Purpose, Item, Category {
  display: list-item;
}
RunIn {
  display: inline;
  font-weight: bold;
}
Note {
  width: 2in;
  height: auto;
  float: right;
  font-size: 90%;
  margin-left: 1em;
  margin-right: .5em;
  border-top: solid 2px black;
  border-bottom: solid 1px black;
  padding: .5em 0;
}
Note:before {
  content: "Note";
  font-weight: bold;
  display: inline;
  background-color: black;
  color: white;
  margin-right: .25em;
  padding: .5em .25em 0 .25em;
}


text:
using namespace std;

bool operator == (v8::Local<v8::String> str,const char* value)
{
    return Nan::Equals(str,Nan::New<v8::String>(value).ToLocalChecked()).ToChecked();
}

const TopoDS_Shape& Shape::shape()  const
{
    return shape_;
}

void Shape::setShape( const TopoDS_Shape& shape)
{
    shape_ = shape;
}


text:
using System.Collections.ObjectModel;
using System.Linq;
using PcapDotNet.Base;

namespace PcapDotNet.Packets.Gre
{
    /// <summary>
    /// RFC 1702.
    /// Represents a source route entry consisting of a list of Autonomous System numbers and indicates an AS source route.
    /// </summary>
    public sealed class GreSourceRouteEntryAs : GreSourceRouteEntry
    {
        /// <summary>
        /// Initializes using the given AS numbers and the next as number index.
        /// </summary>
        /// <param name="asNumbers">Autonomous System numbers of the source route.</param>
        /// <param name="nextAsNumberIndex">The next AS number index in the source route.</param>
        public GreSourceRouteEntryAs(ReadOnlyCollection<ushort> asNumbers, int nextAsNumberIndex)
        {
            _asNumbers = asNumbers;
            _nextAsNumberIndex = nextAsNumberIndex;
        }

        /// <summary>
        /// The Address Family field contains a two octet value which indicates the syntax and semantics of the Routing Information field.
        /// </summary>
        public override GreSourceRouteEntryAddressFamily AddressFamily
        {
            get { return GreSourceRouteEntryAddressFamily.AsSourceRoute; }
        }

        /// <summary>
        /// The SRE Length field contains the number of octets in the SRE.
        /// </summary>
        public override byte PayloadLength
        {
            get { return (byte)(AsNumbers.Count * sizeof(ushort)); }
        }

        /// <summary>
        /// The SRE Offset field indicates the octet offset from the start of the Routing Information field to the first octet of the active entry in Source Route Entry to be examined.
        /// </summary>
        public override byte PayloadOffset
        {
            get { return (byte)(NextAsNumberIndex * sizeof(ushort)); }
        }

        /// <summary>
        /// True iff the AS numbers are equal.
        /// </summary>
        protected override bool EqualsPayloads(GreSourceRouteEntry other)
        {
            return AsNumbers.SequenceEqual(((GreSourceRouteEntryAs)other).AsNumbers);
        }

        /// <summary>
        /// The xor of the hash code of the AS numbers.
        /// </summary>
        protected override int PayloadHashCode
        {
            get { return AsNumbers.UShortsSequenceGetHashCode(); }
        }

        /// <summary>
        /// Autonomous System numbers of the source route.
        /// </summary>
        public ReadOnlyCollection<ushort> AsNumbers
        {
            get { return _asNumbers; }
        }

        /// <summary>
        /// The next AS number index in the source route.
        /// </summary>
        public int NextAsNumberIndex
        {
            get { return _nextAsNumberIndex; }
        }

        /// <summary>
        /// The next AS number.
        /// </summary>
        public ushort NextAsNumber
        {
            get { return AsNumbers[NextAsNumberIndex]; }
        }

        /// <summary>
        /// Writes the payload to the given buffer in the given offset.
        /// </summary>
        /// <param name="buffer">The buffer to write the payload to.</param>
        /// <param name="offset">The offset in the buffer to start writing.</param>
        protected override void WritePayload(byte[] buffer, int offset)
        {
            foreach (ushort asNumber in AsNumbers)
                buffer.Write(ref offset, asNumber, Endianity.Big);
        }

        internal GreSourceRouteEntryAs(ushort[] asNumbers, int nextAsNumberIndex)
            : this(asNumbers.AsReadOnly(), nextAsNumberIndex)
        {
        }

        private readonly ReadOnlyCollection<ushort> _asNumbers;
        private readonly int _nextAsNumberIndex;
    }
}


text:
const { resolve } = require('path')
const uniqueId = require('uniqid')
const isEmpty = require('lodash.isempty')
const { relativeTo } = require('@nuxt/utils')

// Because this module override the client.js copy from v2.11.0
// if nuxt official update client.js maybe some features won't work
// so enableVersion is a list of version which can use the same client.js
const enableVersion = ['2.11.0']

const checkVersion = (nuxtVersion = '', skip = false) => {
    return skip || enableVersion.includes(nuxtVersion)
}

const CORSHeaders = {
    'Access-Control-Allow-Origin': '*'
}

/**
 * Nuxt module for micro frontend using such as single-SPA or qiankun
 *
 * @param {Object} moduleOptions
 * @param {string} [moduleOptions.path = 'mfe.js'] - the MFE lifecycle hook file path relative to rootDir
 * @param {boolean} [moduleOptions.force = false] - skip version check and force to use this module
 * @param {boolean} [moduleOptions.unique = false] - create a unique name scope under window in umd library
 * @param {object} [moduleOptions.headers = CORSHeaders] - develop environment allow CORS for qiankun fetch resource
 */
module.exports = function (moduleOptions) {
    const { rootDir, MFE, mode, buildDir } = this.options

    // MFE means micro frontend
    const options = ({
        ...MFE,
        ...moduleOptions
    })

    const usingMFE = !isEmpty(options) || MFE === true

    const { path = 'mfe.js', force = false, headers = {} } = options

    options.path = relativeTo(buildDir, path)

    const APP = require(resolve(rootDir, 'package.json'))

    // eslint-disable-next-line prefer-const
    let { name = uniqueId('nuxt'), dependencies: { nuxt: nuxtVersion } } = APP

    if (!usingMFE || mode !== 'spa' || !checkVersion(nuxtVersion, force)) {
        return
    }

    if (options.unique) {
        name = uniqueId(name)
    }

    // extend webpack config to output umd library
    this.extendBuild((config, { isDev }) => {
        config.output = Object.assign(config.output, {
            library: `${name}-[name]`,
            libraryTarget: 'umd',
            jsonpFunction: `webpackJsonp_${name}`
        })
    })

    this.addTemplate({
        src: resolve(__dirname, 'router.js'),
        fileName: 'router.js',
        options
    })
    this.addTemplate({
        src: resolve(__dirname, 'client.js'),
        fileName: 'client.js',
        options
    })

    // set absolute resource for html entry to fetch sub application correctly
    this.nuxt.hook('listen', (server, { url = '' }) => {
        const { dev, build: { publicPath } } = this.options
        url = url.endsWith('/') ? url.slice(0, -1) : url
        if (dev) {
            this.options.build.publicPath = `${url}${publicPath}`
        }
    })

    // Access-Control-Allow-Origin for builded files
    const devMiddlewareHeaders = this.options.build.devMiddleware.headers || {}
    const fullHeaders = this.options.build.devMiddleware.headers = { ...CORSHeaders, ...headers, ...devMiddlewareHeaders }

    // Access-Control-Allow-Origin specify for HOST:PORT/index.html
    this.nuxt.hook('render:route', (url, result, context) => {
        for (const header in fullHeaders) {
            if (Object.prototype.hasOwnProperty.call(fullHeaders, header)) {
                context.res.setHeader(header, fullHeaders[header])
            }
        }
    })

    this.nuxt.hook('build:templates', ({ templatesFiles, templateVars, resolve }) => {
        templateVars = Object.assign(templateVars, { MFE: options })
    })
}

module.exports.meta = require('../package.json')


text:
layout: post
title: Java中用js解析json
tags: ScriptEngineManager Java javascript
categories: java
published: java
---

在java中如何解析json?fastjson?jackson?那未免太无趣了

其实我们可以试试ScriptEngine

~~~java
public class NashornTest {

    private static String json = "[{name:'A',age:'18'},{name:'B',age:'19'},{name:'C',age:'30'}]";

    private static String script =
            "function parse(json){" +
            "   var names = new Array();" +
            "   for(var i in json){" +
            "       names.push(json[i].name);" +
            "   }" +
            "   return names;" +
            "};" +
            "parse(" + json + ");";

    public static void main(String[] args) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName( "JavaScript" );

        Map<String,String> result = (Map<String,String>)engine.eval(script);
        result.forEach((k,v) -> System.out.println(v));
    }
}
~~~

输出:

A

B

C

> 代码中使用了 [lambda](http://blog.rainynight.top/2014-12-13/java-newfeature/# lambda)


text:
{% capture puppetdb_version %}master{% endcapture %}

PuppetDB NEXT

This documentation is for an unreleased version of PuppetDB! If you are running PuppetDB from source on the master branch, this is the documentation for you; otherwise, please see the documentation for the latest official release.

General Information

Overview & Requirements

Frequently Asked Questions

Release Notes

Versioning Policy

Known Issues

Community Add-ons

Installation

Migrating Existing Data

Installing via Puppet Module

Installing From Packages

Installing from Source

Upgrading PuppetDB

Connecting Puppet Masters

Connecting Standalone Puppet

Configuration

Configuring PuppetDB

puppetdb.conf: Configuring a Puppet/PuppetDB Connection

Setting Up SSL for PostgreSQL

Usage/Admin

Using PuppetDB

Maintaining and Tuning

Migrating Data

Anonymizing Data

Scaling Recommendations

Debugging with Remote REPL

Load Testing

Troubleshooting

KahaDB Corruption

Low Catalog Duplication

API

Overview

Query Tutorial

Curl Tips

Query API Version 4

Upgrading from Version 3

Query Structure

Available Operators

Query Paging

Nodes Endpoint

Environments Endpoint

Factsets Endpoint

Facts Endpoint

Fact-Names Endpoint

Fact-Paths Endpoint

Fact-Contents Endpoint

Catalogs Endpoint

Resources Endpoint

Edges Endpoint

Reports Endpoint

Events Endpoint

Event Counts Endpoint

Aggregate Event Counts Endpoint

Metadata API Version 1

Version Endpoint

Server Time Endpoint

Command API Version 1

Commands Endpoint

Metrics API Version 1

Metrics Endpoint

Wire Formats

Catalog Wire Format - v6

Facts Wire Format - v4

Report Wire Format - v5

Deactivated Node Wire Format - v3


text:
package net.robig.stlab.util.config;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

import net.robig.logging.Logger;

public abstract class AbstractValue<E extends Object> {
	public E value=null;
	public String key=null;
	private Logger log=new Logger(this);
	static private JSONSerializer serializer = new JSONSerializer();
	private JSONDeserializer<E> deserializer = new JSONDeserializer<E>();
	protected List<IValueChangeListener> valueChangeListeners = null;

	public AbstractValue(String key, E value) {
		this.value=value;
		this.key=key;
	}

	public AbstractValue(String key) {
		this.key=key;
	}

	public void setValue(E v){
		if(this.value.equals(v)) return;
		this.value=v;
		postSetValue();
	}

	public E getValue(){
		return value;
	}

	public String toString(){
		return serializer.deepSerialize(value);
	}
	public void fromString(String s){
		value=deserializer.deserialize(s);
	}

	public void postSetValue() {
		ObjectConfig.setAbstractValue(key, this);
		notifyChangeListeners();
		onValueChange();
	}

	protected static String serializeMemberVariables(Object o){
		String ret=o.getClass().getName();
		for(Field f: o.getClass().getDeclaredFields()){
			try{
				ret+=";"+f.getName()+"="+
					f.toGenericString()+":"+
					f.get(o);
			}catch(Exception e){

			}
		}
		return ret;
	}

	protected static Object deserializeMemberVariables(String dataString){
		String[] data=dataString.split(";");
		if(data.length>0){
			String type=data[0];
			try{
				Class<?> clazz=AbstractValue.class.getClassLoader().loadClass(type);
				Object o=clazz.newInstance();
				for(int i=1;i<data.length;i++){
					String[] mv=data[i].split("=",2);
					if(mv.length==2){
						String methodName=mv[0];
						String value=mv[1];
						clazz.getField(methodName);
					}
				}

			}catch(Exception e){

			}
		}
		return null;
	}

	protected void onValueChange(){

	}

	protected void notifyChangeListeners() {
		if(valueChangeListeners==null)return;
		for(IValueChangeListener l: valueChangeListeners){
			l.valueChanged(this);
		}
	}

	public void addChangeListener(IValueChangeListener l){
		if(valueChangeListeners==null) valueChangeListeners=new ArrayList<IValueChangeListener>();
		valueChangeListeners.add(l);
	}
}


text:
package com.matrixxun.starry;

import android.app.Activity;
import android.content.Context;
import android.os.SystemClock;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.animation.Interpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;

public class PullToZoomListView extends ListView implements OnScrollListener {

    private static final int INVALID_VALUE = -1;
    private static float DEFAULT_MIN_SCALE = 1.0f;

    private static final String TAG = "PullToZoomListView";

    int mActivePointerId = INVALID_VALUE;

    private FrameLayout mHeaderContainer;
    private ImageView mHeaderImage;
    private ImageView mShadow;

    private int mScreenHeight;
    private int mHeaderHeight;

    float mLastMotionY = INVALID_VALUE;
    float mLastScale = INVALID_VALUE;
    float mMaxScale = INVALID_VALUE;

    private OnScrollListener mOnScrollListener;
    private ScalingRunnable mScalingRunnable = new ScalingRunnable();

    private boolean mScrollable = true;
    private boolean mShowHeaderImage = true;
    private boolean mZoomable = true;

    private static final Interpolator sInterpolator = new Interpolator() {
        public float getInterpolation(float t) {
            t -= DEFAULT_MIN_SCALE;
            return (t * t * t * t * t) + DEFAULT_MIN_SCALE;
        }
    };

    class ScalingRunnable implements Runnable {
        long mDuration;
        boolean mIsFinished = true;
        float mScale;
        long mStartTime;

        public boolean isFinished() {
            return mIsFinished;
        }

        public void abortAnimation() {
            mIsFinished = true;
        }

        public void startAnimation(long duration) {
            mStartTime = SystemClock.currentThreadTimeMillis();
            mDuration = duration;
            mScale = ((float) mHeaderContainer.getBottom()) / ((float) mHeaderHeight);
            mIsFinished = false;
            post(this);
        }

        public void run() {
            if (!mIsFinished && ((double) mScale) > 1.0d) {
                float scale = mScale - ((mScale - DEFAULT_MIN_SCALE) * sInterpolator.getInterpolation((((float) SystemClock.currentThreadTimeMillis()) - ((float) mStartTime)) / ((float) mDuration)));
                ViewGroup.LayoutParams params = mHeaderContainer.getLayoutParams();
                if (scale <= DEFAULT_MIN_SCALE) {
                    mIsFinished = true;
                    params.height = mHeaderHeight;
                } else {
                    params.height = (int) (((float) mHeaderHeight) * scale);
                }
                mHeaderContainer.setLayoutParams(params);
                post(this);
            }
        }
    }

    public PullToZoomListView(Context context) {
        super(context);
    }

    public PullToZoomListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PullToZoomListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        init(getContext());
    }

    private void init(Context context) {
        DisplayMetrics metrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mScreenHeight = metrics.heightPixels;
        mHeaderContainer = new FrameLayout(context);
        mHeaderImage = new ImageView(context);
        int width = metrics.widthPixels;
        setHeaderViewSize(width, (int) ((((float) width) / 16.0f) * 9.0f));//Screen Ratio = 16:9
        mShadow = new ImageView(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.BOTTOM;
        mShadow.setLayoutParams(params);
        mHeaderContainer.addView(mHeaderImage);
        mHeaderContainer.addView(mShadow);
        addHeaderView(mHeaderContainer);
        super.setOnScrollListener(this);
    }

    public ImageView getHeaderView() {
        return mHeaderImage;
    }

    public void setShadow(int resId) {
        if (mShowHeaderImage) {
            mShadow.setBackgroundResource(resId);
        }
    }

    public void setHeaderViewSize(int width, int height) {
        if (mShowHeaderImage) {
            ViewGroup.LayoutParams params = mHeaderContainer.getLayoutParams();
            if (params == null) {
                params = new AbsListView.LayoutParams(width, height);
            }
            params.width = width;
            params.height = height;
            mHeaderContainer.setLayoutParams(params);
            mHeaderHeight = height;
        }
    }

    public void setZoomable(boolean zoomable) {
        if (mShowHeaderImage) {
            mZoomable = zoomable;
        }
    }

    public boolean isZoomable() {
        return mZoomable;
    }

    public void setScrollable(boolean scrollable) {
        if (mShowHeaderImage) {
            mScrollable = scrollable;
        }
    }

    public boolean isScrollable() {
        return mScrollable;
    }

    public void hideHeaderImage() {
        mShowHeaderImage = false;
        mZoomable = false;
        mScrollable = false;
        removeHeaderView(mHeaderContainer);
    }

    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (mHeaderHeight == 0) {
            mHeaderHeight = mHeaderContainer.getHeight();
        }
    }

    private void reset() {
        mActivePointerId = INVALID_VALUE;
        mLastMotionY = INVALID_VALUE;
        mMaxScale = INVALID_VALUE;
        mLastScale = INVALID_VALUE;
    }

    public boolean onInterceptTouchEvent(MotionEvent ev) {
        if (!mZoomable) {
            return super.onInterceptTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mActivePointerId = ev.getPointerId(0);
                mMaxScale = ((float) mScreenHeight) / ((float) mHeaderHeight);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                reset();
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                mActivePointerId = ev.getPointerId(ev.getActionIndex());
                break;
            case MotionEvent.ACTION_POINTER_UP:
                onSecondaryPointerUp(ev);
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    public boolean onTouchEvent(MotionEvent ev) {
        if (!mZoomable) {
            return super.onTouchEvent(ev);
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScalingRunnable.mIsFinished) {
                    mScalingRunnable.abortAnimation();
                }
                mLastMotionY = ev.getY();
                mActivePointerId = ev.getPointerId(0);
                mMaxScale = ((float) mScreenHeight) / ((float) mHeaderHeight);
                mLastScale = ((float) mHeaderContainer.getBottom()) / ((float) mHeaderHeight);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                reset();
                endScaling();
                break;
            case MotionEvent.ACTION_MOVE:
                int activePointerIndex = ev.findPointerIndex(mActivePointerId);
                if (activePointerIndex != INVALID_VALUE) {
                    if (mLastMotionY == INVALID_VALUE) {
                        mLastMotionY = ev.getY(activePointerIndex);
                    }
                    if (mHeaderContainer.getBottom() < mHeaderHeight) {
                        mLastMotionY = ev.getY(activePointerIndex);
                        break;
                    }
                    ViewGroup.LayoutParams params = mHeaderContainer.getLayoutParams();
                    float scale = ((((((float) mHeaderContainer.getBottom()) + (ev.getY(activePointerIndex) - mLastMotionY)) / ((float) mHeaderHeight)) - mLastScale) / 2.0f) + mLastScale;
                    if (((double) mLastScale) > 1.0d || scale >= mLastScale) {
                        mLastScale = Math.min(Math.max(scale, DEFAULT_MIN_SCALE), mMaxScale);
                        params.height = (int) (((float) mHeaderHeight) * mLastScale);
                        if (params.height < mScreenHeight) {
                            mHeaderContainer.setLayoutParams(params);
                        }
                        mLastMotionY = ev.getY(activePointerIndex);
                        return super.onTouchEvent(ev);
                    }
                    params.height = mHeaderHeight;
                    mHeaderContainer.setLayoutParams(params);
                    return super.onTouchEvent(ev);
                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                int index = ev.getActionIndex();
                mLastMotionY = ev.getY(index);
                mActivePointerId = ev.getPointerId(index);
                break;
            case MotionEvent.ACTION_POINTER_UP:
                onSecondaryPointerUp(ev);
                mLastMotionY = ev.getY(ev.findPointerIndex(mActivePointerId));
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void onSecondaryPointerUp(MotionEvent ev) {
        int pointerIndex = (ev.getAction() & MotionEventCompat.ACTION_POINTER_INDEX_MASK) >> 8;
        if (ev.getPointerId(pointerIndex) == mActivePointerId) {
            int newPointerIndex = pointerIndex == 0 ? 1 : 0;
            mLastMotionY = ev.getY(newPointerIndex);
            mActivePointerId = ev.getPointerId(newPointerIndex);
        }
    }

    private void endScaling() {
        if (mHeaderContainer.getBottom() >= mHeaderHeight) {
            mScalingRunnable.startAnimation(180);
        }
    }

    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (mOnScrollListener != null) {
            mOnScrollListener.onScrollStateChanged(view, scrollState);
        }
    }

    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (mScrollable) {
            float scrollY = (float) (mHeaderHeight - mHeaderContainer.getBottom());
            if (scrollY > 0.0f && scrollY < ((float) mHeaderHeight)) {
                mHeaderImage.scrollTo(0, -((int) (((double) scrollY) * 0.65d)));
            } else if (mHeaderImage.getScrollY() != 0) {
                mHeaderImage.scrollTo(0, 0);
            }
        }
        if (mOnScrollListener != null) {
            mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
        }
    }

    public void setOnScrollListener(OnScrollListener l) {
        mOnScrollListener = l;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/menu_tutorial"
        android:orderInCategory="999"
        android:title="@string/menu_tutorial"
        app:showAsAction="never" />

    <item
        android:id="@+id/menu_about"
        android:orderInCategory="9999"
        android:title="@string/menu_about"
        app:showAsAction="never" />

</menu>


text:
{% load staticfiles %}

<link rel="stylesheet" type="text/css" href="{% static 'politician/style.css' %}" />

{{ politician_on_stage.first_name }} {{ politician_on_stage.last_name }}

{% if error_message %}
{{ error_message }}
{% endif %}

edit hashtags


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Haddow_Whitney_Lab1_CP3_XML
{
    public class Patent
    {
        public Patent() { } //default constructor

        public Patent(int number, string appNumber, string description, DateTime filingDate, string inventor, string inventor2)
        {
            Number = number;
            AppNumber = appNumber;
            Description = description;
            FilingDate = filingDate;
            Inventor = inventor;
            Inventor2 = inventor2;
        }

        public int Number { get; set; }

        public string AppNumber { get; set; }

        public string Description { get; set; }

        public DateTime FilingDate { get; set; }

        public string Inventor { get; set; }

        public string Inventor2 { get; set; }

        public string GetPatentString(string sep)
        {
            return Number.ToString() + sep + AppNumber + sep + Description + sep +
                FilingDate.ToString("yyyy-MM-dd") + sep +
                Inventor + sep + Inventor2;
        }
    }
}