text:
from rpython.rlib.rstring import StringBuilder
from rpython.rlib import rmd5
from hippy import rpath
from rpython.rlib.objectmodel import we_are_translated
from hippy.module.serialize import SerializerMemo, unserialize_returning_dict
from rpython.rlib.rstring import assert_str0
from collections import OrderedDict
import time
import os

PHP_SESSION_DISABLED = 0
PHP_SESSION_NONE = 1
PHP_SESSION_ACTIVE = 2

SERIALIZE_HANDLERS = ('php',)

def serialize_hash(w_obj, var_hash):
    if w_obj in var_hash:
        var_no = var_hash[w_obj]
        return var_no, var_hash
    else:
        var_no = len(var_hash) + 1
        var_hash[w_obj] = var_no
        return var_no, var_hash

class Session(object):

    def __init__(self, interp):
        self.status = PHP_SESSION_NONE
        self.session_id = ""
        self.init_settings(interp)
        if self.auto_start:
            self.start(interp)

    def start(self, interp):
        if self.status == PHP_SESSION_NONE:
            if not self.serialize_handler in SERIALIZE_HANDLERS:
                interp.warn("session_start(): Cannot find "
                                   "serialization handler '%s' "
                                   "- session startup failed"
                                   % self.serialize_handler)
                return False
            if not self.session_id:
                self.create_id()
            self.init_settings(interp)
            self.status = PHP_SESSION_ACTIVE
            self.read_session_file(interp)
            return True
        return True

    def read_session_file(self, interp):
        space = interp.space
        cookie_path = interp.space.str_w(
            interp.config.get_ini_w('session.cookie_path'))
        w_cookie = self.get_cookie_var(interp).deref()
        w_cookie_id = space.getitem(w_cookie, space.wrap(self.name))
        if space.is_null(w_cookie_id):
            interp.header('Set-Cookie: %s=%s; path=%s' % (self.name,
                                                          self.session_id,
                                                          cookie_path), True,
                                                          False)
        else:
            cookie_id = space.str_w(w_cookie_id)
            self.session_id = cookie_id
        path = interp.space.str_w(interp.config.get_ini_w('session.save_path'))
        fname = self.name + "-" + self.session_id
        dest = rpath.join(path, [fname])
        try:
            f = open(dest)
            data = f.read(-1)
            f.close()
        except OSError:
            dct = None
        except IOError:
            dct = None
        else:
            dct = self.unserialize(interp, data)
        w_ses = self.get_session_var(interp)
        if dct is None:
            w_ses.store(space.new_array_from_rdict(OrderedDict()))
        else:
            d = OrderedDict()
            for k, w_v in dct.iteritems():
                d[k] = w_v
            w_ses.store(space.new_array_from_rdict(d))

    def create_session_file(self, interp, val):
        if self.status != PHP_SESSION_ACTIVE:
            return
        space = interp.space
        path = space.str_w(interp.config.get_ini_w('session.save_path'))
        fname = self.name + "-" + self.session_id
        dest = rpath.join(path, [fname])
        try:
            f = open(dest, "w")
            f.write(val)
            f.close()
        except OSError:
            interp.warn(
                "session_start(): open(%s, O_RDWR) failed")
            return
        except IOError, e:
            if not we_are_translated():
                interp.warn(
                    "session_start(): open(%s, O_RDWR) "
                    "failed: %s (%d)" % (dest, e.strerror, e.errno))
            return

    def create_id(self):
        d = rmd5.RMD5(str(time.time()))
        self.session_id = d.hexdigest()

    def destroy(self, interp):
        if self.status == PHP_SESSION_ACTIVE:
            path = interp.space.str_w(interp.config.get_ini_w('session.save_path'))
            fname = self.name + "-" + self.session_id
            dest = rpath.join(path, [fname])
            try:
                assert dest is not None
                dest = assert_str0(dest)
                os.remove(dest)
            except:
                pass
            self.session_id = ""
            self.status = PHP_SESSION_NONE

    def deactivate(self):
        if self.status == PHP_SESSION_ACTIVE:
            self.status = PHP_SESSION_NONE

    def init_settings(self, interp):
        config = interp.config
        space = interp.space
        self.name = space.str_w(config.get_ini_w('session.name'))
        self.auto_start = bool(space.int_w(config.get_ini_w(
            'session.auto_start')))
        self.cookie_lifetime = space.int_w(config.get_ini_w(
            'session.cookie_lifetime'))
        self.cookie_path = space.str_w(config.get_ini_w('session.cookie_path'))
        self.cookie_domain = space.str_w(config.get_ini_w(
            'session.cookie_domain'))
        self.cookie_secure = space.int_w(config.get_ini_w(
            'session.cookie_secure'))
        self.cookie_httponly = space.int_w(config.get_ini_w(
            'session.cookie_httponly'))
        self.cache_expire = space.int_w(config.get_ini_w(
            'session.cache_expire'))
        self.cache_limiter = space.str_w(config.get_ini_w(
            'session.cache_limiter'))
        self.save_path = space.str_w(config.get_ini_w('session.save_path'))
        w_module_name = config.get_ini_w('session.module_name')
        if w_module_name is None:
            self.module_name = None
        else:
            self.module_name = space.str_w(w_module_name)
        self.serialize_handler = space.str_w(config.get_ini_w(
            'session.serialize_handler'))

    def is_active(self):
        return self.status == PHP_SESSION_ACTIVE

    def write_close(self, interp):
        session_var = self.get_session_var(interp)
        serialize_val = self.serialize(interp, session_var)
        self.create_session_file(interp, serialize_val)
        self.deactivate()
        return serialize_val

    def get_session_var(self, interp):
        return interp.globals.get_var('_SESSION')

    def get_cookie_var(self, interp):
        return interp.globals.get_var('_COOKIE')

    def serialize(self, interp, w_ses):
        space = interp.space
        if not w_ses:
            return ""
        res = StringBuilder()
        memo = SerializerMemo()
        w_ses = w_ses.deref()
        with space.iter(w_ses.deref()) as itr:
            while not itr.done():
                w_key, w_value = itr.next_item(space)
                if space.is_integer(w_key):
                    num = space.int_w(w_key.as_number(space))
                    interp.notice("session_encode(): "
                                         "Skipping numeric key %d" % num)
                    continue
                key = space.str_w(w_key)

                if key.find('!') > 0:
                    continue
                res.append(key)
                res.append('|')
                w_value.serialize(space, res, memo)
        return res.build()

    def unserialize(self, interp, data):
        return unserialize_returning_dict(interp.space, data)

    def unset(self, interp):
        w_sess = self.get_session_var(interp)
        w_sess.store(interp.space.new_array_from_pairs([]))


text:
package com.github.aparsons.fink.util;

import org.junit.Test;

import java.util.HashSet;
import java.util.Set;

import static org.junit.Assert.*;

public class MinHashTest {

    @Test
    public void testMinHash() {
        Set<String> set1 = new HashSet<String>();
        set1.add("Gul");
        set1.add("Donnchad");
        set1.add("gull.donnchad@fake.com");

        Set<String> set2 = new HashSet<String>();
        set2.add("Darragh");
        set2.add("Eustathios");
        set2.add("aul");
        set2.add("aonnchad");
        set2.add("darragh.eustathios@fake.com");

        MinHash<String> minHash = new MinHash<String>(set1.size() + set2.size());
        System.out.println(minHash.similarity(set1, set2));
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * ActiveQuery class file.
 * @author Petra Barus <petra.barus@gmail.com>
 */

namespace UrbanIndo\Yii2\DynamoDb;

use yii\db\ActiveQueryInterface;
use yii\db\ActiveQueryTrait;
use yii\db\ActiveRelationTrait;

/**
 * ActiveQuery represents a [[Query]] associated with an [[ActiveRecord]] class.
 *
 * An ActiveQuery can be a normal query or be used in a relational context.
 *
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]].
 *
 * Normal Query
 * ------------
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
 * - [[column()]]: returns the value of the first column in the query result.
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
 * @author Petra Barus <petra.barus@gmail.com>
 */
class ActiveQuery extends Query implements ActiveQueryInterface
{

    use ActiveQueryTrait;
    use ActiveRelationTrait;

    /**
     * @event Event an event that is triggered when the query is initialized via [[init()]].
     */
    const EVENT_INIT = 'init';

    /**
     * Constructor.
     * @param mixed $modelClass The model class associated with this query.
     * @param array $config     Configurations to be applied to the newly created query object.
     */
    public function __construct($modelClass, array $config = [])
    {
        $this->modelClass = $modelClass;
        parent::__construct($config);
    }

    /**
     * Initializes the object.
     * This method is called at the end of the constructor. The default implementation will trigger
     * an [[EVENT_INIT]] event. If you override this method, make sure you call the parent implementation at the end
     * to ensure triggering of the event.
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->trigger(self::EVENT_INIT);
    }

    /**
     * Converts the raw query results into the format as specified by this query.
     * This method is internally used to convert the data fetched from database
     * into the format as required by this query.
     * @param array $rows The rows from response parsing.
     * @return array the converted query result
     */
    public function populate($rows)
    {
        if (empty($rows)) {
            return [];
        }

        $models = $this->createModels($rows);
        if (!$this->asArray) {
            foreach ($models as $model) {
                /* @var $model ActiveRecord */
                $model->setFindType($this->using);
                $model->afterFind();
            }
        }
        return $models;
    }

    /**
     * Prepares for building SQL.
     * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
     * You may override this method to do some final preparation work when converting a query into a SQL statement.
     * @param QueryBuilder $builder The query builder.
     * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
     */
    public function prepare(QueryBuilder $builder)
    {
        $builder;
        if (empty($this->from)) {
            /* @var $modelClass ActiveRecord */
            $modelClass = $this->modelClass;
            $tableName = $modelClass::tableName();
            $this->from = $tableName;
        }
        return $this;
    }

    /**
     * Executes query and returns a single row of result.
     * @param Connection $db The DB connection used to create the DB command.
     * If null, the DB connection returned by [[modelClass]] will be used.
     * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
     * the query result may be either an array or an ActiveRecord object. Null will be returned
     * if the query results in nothing.
     */
    public function one($db = null)
    {
        $row = parent::one($db);
        if ($row !== false) {
            $models = $this->populate([$row]);
            return reset($models) ?: null;
        } else {
            return null;
        }
    }

    /**
     * Executes query and returns all results as an array.
     * @param Connection $db The DB connection used to create the DB command.
     * If null, the DB connection returned by [[modelClass]] will be used.
     * @return array|ActiveRecord[] the query results. If the query results in nothing, an empty array will be returned.
     */
    public function all($db = null)
    {
        return parent::all($db);
    }
}


text:
type EventCallback = (event: any) => void;

export interface EditorSelection {
  win: Window;

  setRng: (rng: Range) => void;
  getRng: () => Range | null;
  getSel: () => Selection | null;
  select: (node: Node, content?: boolean) => Node;
  setCursorLocation: (node?: Node, offset?: number) => void;
  isCollapsed: () => boolean;
}

export type ContentFormat = 'raw' | 'text' | 'html' | 'tree';

export interface GetContentArgs {
  format?: ContentFormat;
  get?: boolean;
  content?: any;
  getInner?: boolean;
  no_events?: boolean;
  [key: string]: any;
}

export interface Editor {
  id: string;
  settings?: Record<string, any>;
  options?: any;
  inline: boolean;

  dom: any;
  editorCommands: any;
  selection: EditorSelection;
  windowManager: any;
  ui: {
    registry: any;
  };

  getBody: () => HTMLElement;
  getDoc: () => Document;
  getWin: () => Window;
  getContainer: () => HTMLElement;
  getContentAreaContainer: () => HTMLElement;
  getElement: () => HTMLElement;

  getContent: (args?: GetContentArgs) => string;
  setContent: (content: string) => void;

  execCommand: (command: string, ui?: boolean, value?: any, args?: any) => boolean;

  nodeChanged: () => void;
  focus: () => void;
  hasFocus: () => boolean;
  remove: () => void;
  getParam: <T>(key: string, defaultValue?: T, type?: string) => T;

  setProgressState: (state: boolean, time?: number) => void;

  on: (event: string, callback: EventCallback) => void;
  once: (event: string, callback: EventCallback) => void;
  off: (event: string, callback: EventCallback) => void;
}


text:
expression::expression()
{
  num_variables = 0;
}

void expression::increment_var_count()
{
  num_variables++;
}

int expression::get_var_count()
{
  return num_variables;
}

void expression::add_var(string key, string value)
{
  // TODO: Check to see if a variable of this name has already been
  // declared in this expression.  If it has, our var_count will get
  // all jacked up and then we will start popping the wrong values off
  // the stack.  That will get ugly.
  variables[key] = value;
  increment_var_count();
}

void expression::add_vars_to_stack(std::list<variable>& vstack)
{
  if (num_variables == 0)
    return;

  variable* new_var;

  for (std::map<string, string>::iterator var_iter = variables.begin();
       var_iter != variables.end(); var_iter++)
    {
      new_var = new variable;
      new_var->key = var_iter->first;
      new_var->value = var_iter->second;
      new_var->resolved = false;

      vstack.push_back(*new_var);
    }
}

void expression::setId(string newId)
{
  id = newId;
}

void expression::newSub(string newSub)
{
  sub_expressions.push_back(newSub);
}

string expression::getId()
{
  return id;
}

string expression::getValue()
{
  int number = rand() % sub_expressions.size();

  int i = 0;

  for (std::list<string>::iterator sub_iter = sub_expressions.begin();
       sub_iter != sub_expressions.end(); sub_iter++)
    {
      if (i == number)
        return *sub_iter;

      i++;
    }

  assert(false); // should NEVER get here
}


text:
"""URL conf for testing Expiring Tokens."""
from django.conf.urls import url

from rest_framework_expiring_authtoken.views import obtain_expiring_auth_token

urlpatterns = [
    url(r'^obtain-token/$', obtain_expiring_auth_token),
]


text:
export {
  default as ComponentEdit
} from './containers/component-edit-container';


text:
package utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class is meant for performance analysis. Once initialized, you can add new steps and see a
 * report or total execution time at the end.
 */
public class EventAnalyzer {
	private static final Logger logger = LoggerFactory.getLogger(EventAnalyzer.class);

	private final List<Long> timestamps = new ArrayList<>();

	private final List<String> labels = new ArrayList<>();

	public void before() {
		add("Before");
	}

	public void after() {
		add("After");
	}

	public void add(String label) {
		long currentTimestamp = getCurrentTimestamp();
		getTimestamps().add(currentTimestamp);
		getLabels().add(label);
		if (getTimestamps().size() != getLabels().size()) {
			logger.error(
				"After addition of label '{}', size of timestamps ({}) does not match size of labels ({}) ",
				new String[] { label, getTimestamps().size() + "", getLabels().size() + "" });
		}
	}

	private long getCurrentTimestamp() {
		return System.nanoTime();
	}

	public void report() {
		System.out.println("Number of registered events: " + getEventCount());
		System.out.println();
		System.out.println("Delta[ns] | Label");
		System.out.println("----------|------------------------");
		Long timestamp = null;
		for (int index = 0; index < getTimestamps().size(); index++) {
			long delta = timestamp != null ? getTimestamps().get(index) - timestamp : 0;
			System.out.format("%9d | %s\n", delta, getLabels().get(index));
			timestamp = getTimestamps().get(index);
		}
		System.out.println();
		System.out.println(
			"Difference between first and last event: " + getTotalExecutionTime() + "[ms]");
	}

	public long getTotalExecutionTime() {
		int lastIndex = timestamps.size() > 0 ? timestamps.size() - 1 : 0;
		if (lastIndex == 0) {
			return 0;
		}
		long deltaInNanoseconds = timestamps.get(lastIndex) - timestamps.get(0);
		return TimeUnit.NANOSECONDS.toMillis(deltaInNanoseconds);
	}

	public int getEventCount() {
		return getTimestamps().size();
	}

	List<Long> getTimestamps() {
		return timestamps;
	}

	List<String> getLabels() {
		return labels;
	}
}


text:
'use strict';

module.exports = number => {
  const src = number.toString();
  const maxIndex = src.length - 1;
  if (maxIndex > 0) {
    const max = Number(src[maxIndex]);
    for (let i = src.length - 2; i >= 0; i--) {
      if (Number(src[i]) < max) {
        return Number(src.substr(0, i) + src.charAt(maxIndex) + (src.substring(i, maxIndex) + src.substr(maxIndex + 1)).split('').sort().join(''));
      }
    }
  }
  return number;
};


text:
module ActionView
  module Helpers
    module SafeVideoEmbed
      def safe_video_embed(embed_code, opts = {})
        video_width = opts[:width] || '560'
        video_height = opts[:height] || '349'

        if embed_code[/player\.vimeo\.com\/video\/([^\/\?]*)/] || embed_code[/vimeo\.com\/(\d+)/]
          vimeo_id = $1
          return "".html_safe
        else
          if embed_code[/youtu\.be\/([^\?]*)/]
            youtube_id = $1
          else
            # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367
            embed_code[/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/]
            youtube_id = $5
          end

          return "".html_safe
        end
      end

    end
  end
end


text:
package br.com.ecodetech.integracao.xml;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import br.com.ecodetech.integracao.model.bean.NFE;
import br.com.ecodetech.integracao.model.bean.NFEItem;

public class XMLUtil {

	/**
	 * Metodo que recebe caminho e nome de um arquivo XML e devolve um String
	 * com seu conteudo
	 *
	 * @param nomeArquivo
	 * @return String com o conteudo do arquivo
	 */
	public static String fileToString(String nomeArquivo) {
		InputStream input;
		InputStreamReader reader;
		BufferedReader buffer;
		String texto = "", linha;
		try {
			input = new FileInputStream(nomeArquivo);
			reader = new InputStreamReader(input);
			buffer = new BufferedReader(reader);
			linha = buffer.readLine();
			while (linha != null) {
				// linha = linha.replace("<", "\n<");
				texto += linha;
				linha = buffer.readLine();
			}
			buffer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return texto;
	}

	public static NFE fileToNFE(String nomeArquivo) {
		NFE nota = new NFE();
		String texto = fileToString(nomeArquivo);
		String valor;
		int inicio, fim;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		// Id da notafiscal
		inicio = texto.indexOf("Id=") + 4;
		fim = texto.indexOf(" versao=", inicio) - 1;
		valor = texto.substring(inicio, fim);
		nota.setId(valor);

		// Versao da notafiscal
		inicio = texto.indexOf("=", fim) + 2;
		fim = texto.indexOf("\"", inicio);
		valor = texto.substring(inicio, fim);
		nota.setVersao(valor);

		// Unidade da federacao
		inicio = texto.indexOf("cUF") + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setcUF(Integer.parseInt(valor));

		// Codigo da NFE, gerado pelo emissor
		inicio = texto.indexOf("cNF", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setcNF(Long.parseLong(valor));

		// Natureza da operacao
		inicio = texto.indexOf("Op", fim) + 3;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setNatOp(valor);

		// Indicador de pagamento
		inicio = texto.indexOf("Pag", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setIndPag(Long.parseLong(valor));

		// Modalidade
		inicio = texto.indexOf("mod", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setMod(valor);

		// Serie
		inicio = texto.indexOf("serie", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setSerie(Integer.parseInt(valor));

		// Numero documento fiscal
		inicio = texto.indexOf("nNF", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setnNF(Integer.parseInt(valor));

		// Data de emissao
		inicio = texto.indexOf("dEmi", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setdEmi(Calendar.getInstance());
		try {
			nota.getdEmi().setTime(sdf.parse(valor));
		} catch (ParseException e) {
			e.printStackTrace();
		}

		inicio = texto.indexOf("tpNF", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setTpNF(Integer.parseInt(valor));

		inicio = texto.indexOf("cMunFG", fim) + 7;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setcMunFG(Long.parseLong(valor));

		inicio = texto.indexOf("tpImp", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setTpImp(Integer.parseInt(valor));

		inicio = texto.indexOf("tpEmis", fim) + 7;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setTpEmis(Integer.parseInt(valor));

		inicio = texto.indexOf("cDV", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setcDV(Integer.parseInt(valor));

		inicio = texto.indexOf("tpAmb", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setTpAmb(Integer.parseInt(valor));

		inicio = texto.indexOf("finNFe", fim) + 7;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setFinNFe(Integer.parseInt(valor));

		inicio = texto.indexOf("procEmi", fim) + 8;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setProcEmi(Integer.parseInt(valor));

		inicio = texto.indexOf("verProc", fim) + 8;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setVerProc(valor);

		//*********** EMITENTE **************//
		inicio = texto.indexOf("CNPJ", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiCNPJ(valor);

		inicio = texto.indexOf("xNome", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiNome(valor);

		inicio = texto.indexOf("xLgr", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndLgr(valor);

		inicio = texto.indexOf("nro", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndNum(valor);

		inicio = texto.indexOf("xBairro", fim) + 8;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndBairro(valor);

		inicio = texto.indexOf("cMun", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndCodMun(Integer.parseInt(valor));

		inicio = texto.indexOf("xMun", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndMunicipio(valor);

		inicio = texto.indexOf("UF", fim) + 3;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndUF(valor);

		inicio = texto.indexOf("CEP", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndCEP(Long.parseLong(valor));

		inicio = texto.indexOf("cPais", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndCodPais(Integer.parseInt(valor));

		inicio = texto.indexOf("xPais", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiEndPais(valor);

		inicio = texto.indexOf("IE", fim) + 3;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiIE(valor);

		inicio = texto.indexOf("IM", fim) + 3;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiIM(valor);

		inicio = texto.indexOf("CNAE", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiCNAE(Long.parseLong(valor));

		inicio = texto.indexOf("CRT", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setEmiCRT(Long.parseLong(valor));

		//*********** DESTINATÁRIO **************//

		inicio = texto.indexOf("CPF", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestCPF(valor);

		inicio = texto.indexOf("xNome", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestNome(valor);

		inicio = texto.indexOf("xLgr", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndLgr(valor);

		inicio = texto.indexOf("nro", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndNum(valor);

		inicio = texto.indexOf("xBairro", fim) + 8;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndBairro(valor);

		inicio = texto.indexOf("cMun", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndCodMun(Long.parseLong(valor));

		inicio = texto.indexOf("xMun", fim) + 5;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndMunicipio(valor);

		inicio = texto.indexOf("UF", fim) + 3;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndUF(valor);

		inicio = texto.indexOf("CEP", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndCEP(valor);

		inicio = texto.indexOf("cPais", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndCodPais(Integer.parseInt(valor));

		inicio = texto.indexOf("xPais", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setDestEndPais(valor);

		while (texto.indexOf("<det nItem=", fim)!=-1){
			NFEItem item = new NFEItem();
			item.getId().setIdNotaFiscal(nota.getId());

			inicio = texto.indexOf("nItem=", fim) + 7;
			fim = texto.indexOf("\"", inicio);
			valor = texto.substring(inicio, fim);
			item.getId().setIdItem(Long.parseLong(valor));

			inicio = texto.indexOf("cProd", fim) + 6;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setCodProduto(valor);

			inicio = texto.indexOf("xProd", fim) + 6;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setDescricao(valor);

			inicio = texto.indexOf("NCM", fim) + 4;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setNcm(Long.valueOf(valor));

			inicio = texto.indexOf("CFOP", fim) + 5;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setCfop(Integer.valueOf(valor));

			inicio = texto.indexOf("uCom", fim) + 5;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setuCom(valor);

			inicio = texto.indexOf("qCom", fim) + 5;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setqCom(Double.valueOf(valor));

			inicio = texto.indexOf("vUnCom", fim) + 7;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setvUnCom(new BigDecimal(valor));

			inicio = texto.indexOf("vProd", fim) + 6;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setvProd(new BigDecimal(valor));

			inicio = texto.indexOf("uTrib", fim) + 6;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setuTrib(valor);

			inicio = texto.indexOf("qTrib", fim) + 6;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setqTrib(Double.valueOf(valor));

			inicio = texto.indexOf("vUnTrib", fim) + 8;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setvUnTrib(new BigDecimal(valor));

			inicio = texto.indexOf("indTot", fim) + 7;
			fim = texto.indexOf("<", inicio);
			valor = texto.substring(inicio, fim);
			item.setIndTot(Integer.valueOf(valor));

			nota.getListaItens().add(item);
		}

		inicio = texto.indexOf("vServ", fim) + 6;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setIssqnServ(new BigDecimal(valor));

		inicio = texto.indexOf("vBC", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setIssqnBC(new BigDecimal(valor));

		inicio = texto.indexOf("vISS", fim) + 4;
		fim = texto.indexOf("<", inicio);
		valor = texto.substring(inicio, fim);
		nota.setIssqnISS(new BigDecimal(valor));

		return nota;
	}
}


text:
"""
1D GP with multinomial observations
"""

import os
import time
from collections import namedtuple
import numpy as np
from GPy.kern import RBF
# np.random.seed(1122122122)

from pgmult.gp import MultinomialGP, LogisticNormalGP, EmpiricalStickBreakingGPModel
from pgmult.utils import psi_to_pi, compute_uniform_mean_psi

import matplotlib.pyplot as plt
import brewer2mpl
colors = brewer2mpl.get_map("Set1", "Qualitative",  9).mpl_colors

K = 4           # Size of output observations
N_max = 10      # Number of observations per input

def initialize_test(N_max=10, true_model_class=MultinomialGP):
    D = 1           # Input dimensionality

    M_train = 100   # Number of observed training datapoints
    M_test = 20     # Number of observed test datapoints
    M = M_train + M_test
    l = 10.0        # Length scale of GP
    L = 120.0       # Length of observation sequence
    v = 1.0         # Variance of the GP

    # Initialize a grid of points at which to observe GP
    N = N_max * np.ones(M, dtype=np.int32)
    Z = np.linspace(0,L,M)[:,None]

    # Initialize the kernel
    kernel = RBF(1, lengthscale=l, variance=v)

    # Sample a GP
    true_model = true_model_class(K, kernel, D=D)
    X, psi = true_model.generate(Z=Z, N=N, full_output=True)
    pi = np.array([psi_to_pi(p) for p in psi])

    # Split the data into training and test
    Dataset = namedtuple("Dataset", ["K", "kernel", "Z", "X", "psi", "pi"])
    train = Dataset(K, kernel, Z[:M_train], X[:M_train], psi[:M_train], pi[:M_train])
    test = Dataset(K, kernel, Z[M_train:], X[M_train:], psi[M_train:], pi[M_train:])

    return train, test

def initialize_interactive_plot(model, train, test):
    plot_K = isinstance(model, LogisticNormalGP)

    # Make predictions at the training and testing data
    pi_train, psi_train, _ = \
            model.collapsed_predict(train.Z)

    pi_test, psi_test, _ = \
            model.collapsed_predict(test.Z)

    lim = 5

    # PLOT!
    plt.ion()
    fig, axs = plt.subplots(train.K, 2)
    lns = np.zeros((train.K,4), dtype=object)
    for k in range(train.K):
        if k == train.K-1 and not plot_K:
            pass
        else:
            ax = axs[k,0]

            # Plot the training data
            ax.plot(train.Z, train.psi[:,k], '-b', lw=2)
            lns[k,0] = ax.plot(train.Z, psi_train[:,k], '--b', lw=2)[0]

            # Plot the testing data
            ax.plot(test.Z, test.psi[:,k], '-r', lw=2)
            lns[k,1] = ax.plot(test.Z, psi_test[:,k], '--r', lw=2)[0]

            # Plot the zero line
            ax.plot(train.Z, np.zeros_like(train.Z), ':k')
            ax.plot(test.Z, np.zeros_like(test.Z), ':k')
            # ax.set_xlim(0, L)
            ax.set_ylim(-lim, lim)
            ax.set_title("$\psi_%d$" % (k+1))

        ax = axs[k,1]
        pi_emp_train = train.X / train.X.sum(axis=1).astype(np.float)[:,None]
        ax.bar(train.Z, pi_emp_train[:,k], width=1, color='k')
        ax.plot(train.Z, train.pi[:,k], '-b', lw=2)
        lns[k,2] = ax.plot(train.Z, pi_train[:,k], '--b', lw=2)[0]

        pi_emp_test = test.X / test.X.sum(axis=1).astype(np.float)[:,None]
        ax.bar(test.Z, pi_emp_test[:,k], width=1, color='k')
        ax.plot(test.Z, test.pi[:,k], '-r', lw=2)
        lns[k,3] = ax.plot(test.Z, pi_test[:,k], '--r', lw=2)[0]

        # ax.set_xlim(0,)
        ax.set_ylim(0,1)
        ax.set_title("$\pi_%d$" % (k+1))

    plt.show()
    plt.pause(1.0)

    return lns

def update_plot(lns, model, train, test):

    plot_K = isinstance(model, LogisticNormalGP)

    # Make predictions at the training and testing data
    pi_train, psi_train, _ = \
            model.collapsed_predict(train.Z)

    pi_test, psi_test, _ = \
            model.collapsed_predict(test.Z)

    for k in range(K):
        if k == K-1 and not plot_K:
            pass
        else:
            lns[k,0].set_data(train.Z, psi_train[:,k])
            lns[k,1].set_data(test.Z, psi_test[:,k])

        lns[k,2].set_data(train.Z, pi_train[:,k])
        lns[k,3].set_data(test.Z, pi_test[:,k])

    plt.pause(0.001)

### Inference
Results = namedtuple("Results", ["lls", "pred_lls", "pred_pis", "pred_psis", "timestamps"])
def fit_model(model, train_data, test_data, N_iter=100, lns=None):

    if isinstance(model, EmpiricalStickBreakingGPModel):
        return fit_empirical_model(model, train_data, test_data)

    lls = [model.log_likelihood()]
    pred_lls = [model.predictive_log_likelihood(test_data.Z, test_data.X)[0]]
    pred_pi, pred_psi, _ = model.collapsed_predict(test_data.Z)
    pred_pis = [pred_pi]
    pred_psis = [pred_psi]

    timestamps = [time.clock()]
    for itr in range(N_iter):
        print("Iteration ", itr)
        model.resample_model()

        # Collect samples
        lls.append(model.log_likelihood())
        pred_lls.append(model.predictive_log_likelihood(test_data.Z, test_data.X)[0])
        pred_pi, pred_psi, _ = model.collapsed_predict(test_data.Z)
        pred_pis.append(pred_pi)
        pred_psis.append(pred_psi)
        timestamps.append(time.clock())

        # Update plots
        if lns is not None:
            update_plot(lns, model, train_data, test_data)

    # Compute sample mean and std
    lls = np.array(lls)
    pred_lls = np.array(pred_lls)
    pred_pis = np.array(pred_pis)
    pred_psis = np.array(pred_psis)
    timestamps = np.array(timestamps)
    timestamps -= timestamps[0]

    return Results(lls, pred_lls, pred_pis, pred_psis, timestamps)

def fit_empirical_model(model, train, test):
    empirical_ll, _ = model.predictive_log_likelihood(train.Z, train.X)
    empirical_pred_ll, _ = model.predictive_log_likelihood(test.Z, test.X)
    pred_pi, pred_psi, _ = model.collapsed_predict(test.Z)
    pred_pis = np.array([pred_pi])
    pred_psis = np.array([pred_psi])
    # return Results(empirical_ll * np.ones(2),
    #                empirical_pred_ll * np.ones(2), [0, 1])
    return Results(empirical_ll * np.ones(2),
                   empirical_pred_ll * np.ones(2),
                   pred_pis, pred_psis, [0,1])

if __name__ == "__main__":

    train, test = initialize_test(N_max=N_max, true_model_class=MultinomialGP)

    # models = [EmpiricalStickBreakingGPModel, LogisticNormalGP, MultinomialGP]
    # labels = ["Emp GP", "LN GP", "LSB GP"]
    models = [EmpiricalStickBreakingGPModel, MultinomialGP]
    labels = ["Emp GP", "LSB GP"]

    results = []
    do_plot = False
    N_samples = 200
    for model_class in models:
        # Make a test model
        model = model_class(train.K, train.kernel, D=1)
        model.add_data(train.Z, train.X)

        # Initialize from the data
        model.initialize_from_data(initialize_to_mle=True)
        if isinstance(model, MultinomialGP):
            model.data_list[0]["psi"] = train.psi
            model.resample_omega()

        # Initialize plots
        if do_plot:
            lns = initialize_interactive_plot(model, train, test)
        else:
            lns = None

        # Inference
        res = fit_model(model, train, test,
                        N_iter=N_samples, lns=lns)
        results.append(res)

    fig, axs = plt.subplots(1,2)
    T_max = np.amax([np.amax(res.timestamps) for res in results])
    for ind, (res, label) in \
            enumerate(zip(results, labels)):
        axs[0].plot(res.timestamps, res.lls, color=colors[ind], label=label)
        axs[0].plot([0, T_max],
                 res.lls[len(res.lls)//2:].mean() * np.ones(2),
                 linestyle=":",
                 color=colors[ind])

        offset = len(res.pred_lls)//2
        axs[1].plot(res.timestamps, res.pred_lls, color=colors[ind], label=label)
        axs[1].plot([0, T_max],
                 res.pred_lls[offset:].mean() * np.ones(2),
                 linestyle=":",
                 color=colors[ind])

        # Plot the log-sum-exp of the pred_lls
        from scipy.misc import logsumexp
        expected_pred_ll =  logsumexp(res.pred_lls[offset:]) - np.log(len(res.pred_lls)-offset)
        axs[1].plot([0, T_max],
                    expected_pred_ll * np.ones(2),
                 linestyle="--",
                 color=colors[ind])

    axs[0].set_xlim(-1, T_max)
    axs[1].set_xlim(-1, T_max)
    plt.legend(loc="lower right")
    axs[0].set_xlabel("Time (s)")
    axs[0].set_ylabel("Log likelihood")
    axs[1].set_xlabel("Time (s)")
    axs[1].set_ylabel("Pred. Log likelihood")

    plt.ioff()
    plt.show()


text:
var Consul = require('..');
var consul = new Consul();

consul.status.peers(function (err, peers) {
  if (err) return console.error(err.stack);
  console.log('peers -- %j', peers);
});

consul.status.leader(function (err, leader) {
  if (err) return console.error(err.stack);
  console.log('leader -- %s', leader);
});


text:
module Debugger
  module RubyCoreSource
    VERSION = '1.2.3'
  end
end


text:
#ifndef org_mbi_gui_qt_usnavigation_Activator_h
#define org_mbi_gui_qt_usnavigation_Activator_h

#include <ctkPluginActivator.h>

#include "mitkTrackingDeviceSource.h"

#include "IO/mitkUSNavigationCombinedModalityPersistence.h"

namespace mitk {
class org_mbi_gui_qt_usnavigation_Activator :
  public QObject, public ctkPluginActivator
{
  Q_OBJECT
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
  Q_PLUGIN_METADATA(IID "org_mbi_gui_qt_usnavigation")
#endif
  Q_INTERFACES(ctkPluginActivator)

public:

  void start(ctkPluginContext* context);
  void stop(ctkPluginContext* context);

  static ctkPluginContext* GetContext();

private:
  static ctkPluginContext* m_Context;

  TrackingDeviceSource::Pointer m_VirtualTrackingDeviceSource;

  USNavigationCombinedModalityPersistence::Pointer m_USCombinedModalityPersistence;
}; // org_mbi_gui_qt_usnavigation_Activator

typedef org_mbi_gui_qt_usnavigation_Activator PluginActivator;
}

#endif // org_mbi_gui_qt_usnavigation_Activator_h


text:
import { isDate } from "../../time";

export interface Endable {
	end: Date;
}

export function isEndable(candidate: unknown) {
	return (
		Object.prototype.hasOwnProperty.call(candidate, "end") &&
		isDate((candidate as Endable).end)
	);
}


text:
/* You can add global styles to this file, and also import other style files */

html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

.amarillo{
    background-color: yellow;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 15px 15px 10px silver;
}

.amarillo:hover{
    background-color: black;
    color: white;
    padding: 10px;
    border-radius: 5px;
    box-shadow: 15px 15px 10px silver;
}


text:
.. _operating-kolla:

===============
Operating Kolla
===============

Upgrading
=========
TODO(all) fill this section out

Diagnostics
===========
TODO(all) fill this section out

Failure Recovery
================
TODO(all) fill this section out

Reconfiguration of an existing environment
==========================================
TODO(all) fill this section out

Tips and Tricks
===============
Kolla ships with several utilities intended to facilitate ease of operation.

``tools/cleanup-containers`` can be used to remove deployed containers from
the system. This can be useful when you want to do a new clean deployment. It
will preserve the registry and the locally built images in the registry,
but will remove all running Kolla containers from the local Docker daemon.
It also removes the named volumes.

``tools/cleanup-host`` can be used to remove remnants of network changes
triggered on the Docker host when the neutron-agents containers are launched.
This can be useful when you want to do a new clean deployment, particularly
one changing the network topology.

``tools/cleanup-images`` can be used to remove all Docker images built by
Kolla from the local Docker cache.


text:
from __future__ import division
'''
Created on Feb 16, 2015

@author: Christopher Henderson (chris@chenderson.org)
'''

class NormalizedRational(object):
    '''
        This class normalizes a point so that any other point that can land
        on the same line hashes to the same value.

        - All points on the x-axis are converted to (0, 1)
        - All points on the y-axis are converted to (1, 0)
        - The origin remains the origin.
        - All other points have their rational reduced. If the point
            lies within quadrants III or IV then they are flipped to I or II.

        @param int numerator
        @param int denominator
    '''
    def __init__(self, numerator, denominator):
        x_axis = numerator == 0 and denominator != 0
        y_axis = denominator == 0 and numerator != 0
        origin = numerator == 0 and denominator == 0
        if x_axis:
            self.rational = (0, 1)
        elif y_axis:
            self.rational = (1, 0)
        elif origin:
            self.rational = (0, 0)
        else:
            self.rational = self._normalizeRational(numerator, denominator)

    def _normalizeRational(self, numerator, denominator):
            #===================================================================
            # Euclid's algorithm for GCD.
            # https://en.wikipedia.org/wiki/Euclidean_algorithm
            # @TODO research a possibly fast approach.
            # @TODO attempt to implement https://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm
            #===================================================================
            GCD = abs(numerator)
            tempDenominator = abs(denominator)
            temp = 0
            while (tempDenominator > 0):
                temp = tempDenominator
                tempDenominator = GCD % tempDenominator
                GCD = temp
            return self._foldQuadrantsIIIandIV(numerator//GCD, denominator//GCD)

    def _foldQuadrantsIIIandIV(self, y, x):
        quadrantIII = y < 0 and x < 0
        quadrantIV = y < 0 and x > 0
        if quadrantIII or quadrantIV:
            return (y*-1, x*-1)
        else:
            return (y, x)

    def __eq__(self, other):
        if isinstance(other, NormalizedRational):
            return self.rational == other.rational
        elif isinstance(other, tuple):
            return self.rational == other
        elif isinstance(other, list) or isinstance(other, set):
            return self.rational == tuple(other)
        else:
            return False

    def __hash__(self):
        return hash(self.rational)

def getNumLines(points):
    lines = set()
    for point in points:
        lines.add(NormalizedRational(point[1], point[0]))
    if (0, 0) in lines and len(lines) is not 1:
        return len(lines) - 1
    else:
        return len(lines)


text:
package P01_Logger.models.appenders;

import P01_Logger.enums.ReportLevel;
import P01_Logger.interfaces.Appender;
import P01_Logger.interfaces.Layout;

public abstract class AbstractAppender implements Appender {

    private static final ReportLevel DEFAULT_REPORT_LEVEL_THRESHOLD = ReportLevel.INFO;

    private Layout layout;
    private ReportLevel reportLevel;
    int messageCount;

    protected AbstractAppender(Layout layout) {
        this.layout = layout;
        this.reportLevel = DEFAULT_REPORT_LEVEL_THRESHOLD;
    }

    @Override
    public Layout getLayout() {
        return this.layout;
    }

    @Override
    public void setReportLevel(ReportLevel reportLevel) {
        this.reportLevel = reportLevel;
    }

    @Override
    public ReportLevel getReportLevel() {
        return this.reportLevel;
    }

    @Override
    public abstract void append(String time, String message, ReportLevel reportLevel);

    @Override
    public String toString() {
        return ", Layout type: " + this.layout.getClass().getSimpleName()
                + ", Report level: " + this.reportLevel.name()
                + ", Messages appended: " + this.messageCount;
    }
}


text:
'use strict';

var stringIsEmpty = require("../util").stringIsEmpty;

function AuditStream() {
    this.str = '';
    this.startLine();
}

AuditStream.prototype.startLine = function () {
    this.str = '';
};

AuditStream.prototype.log = function (auditable) {
    var text = auditable.getAuditText();
    if (!stringIsEmpty(text) && this.str.length > 0) {
        this.str += ", "
    }

    this.str += text;
};

AuditStream.prototype.endLine = function () {
    console.log(this.str)
};

module.exports = AuditStream;


text:
import unittest
from oss_watchdog.file_oss import OssFileManager
import yaml, time, os, random, string, shutil

class OssFileManagerTest(unittest.TestCase):
    def setUp(self):
        f = open("../config.yaml")
        config = yaml.load(f)
        self.fm = OssFileManager(config["auth_key"],
                                 config["auth_key_secret"],
                                 config["endpoint"],
                                 config["bucket_name"])

        self._timestamp = str(int(time.time()))
        self._file_content_en = ''.join(random.sample(string.ascii_letters+string.digits, 16)) * 16
        self._file_content_ch = "重要的只有一点,那就是如何将绝无仅有的今日过得无以伦比。"
        self._root = "temp/test-root/"
        self._dir_en = self._root + "test-" + self._timestamp + "-GhostInTheShell/"
        self._dir_ch = self._root + "test-" + self._timestamp + "-攻壳机动队/"
        self._file_en = "test_" + self._timestamp + "_Tachikoma.txt"
        self._file_ch = "test_" + self._timestamp + "_塔奇克玛.txt"

        shutil.rmtree(self._root, True)
        os.mkdir(self._root)
        os.mkdir(self._dir_en)
        with open(self._dir_en + self._file_en, 'w') as file_en:
            file_en.write(self._file_content_en)
        with open(self._dir_en + self._file_ch, 'w') as file_ch:
            file_ch.write(self._file_content_ch)
        os.mkdir(self._dir_ch)
        with open(self._dir_ch + self._file_en, 'w') as file_en:
            file_en.write(self._file_content_en)
        with open(self._dir_ch + self._file_ch, 'w') as file_ch:
            file_ch.write(self._file_content_ch)

    def test_upload(self):
        res = self.fm.upload(self._dir_en + self._file_en,
                             self.fm.norm_path(self._dir_en + self._file_en))
        self.assertEqual(res.status, 200, "test_upload failed")

    def tearDown(self):
        self.fm = None

if __name__ == "__main__":
    unittest.main()


text:
package de.proteinms.xtandemparser.viewer;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * In the parameter dialog, the user can set the fragment ion mass accuracy.
 *
 * @author Thilo Muth
 */
public class ParametersDialog extends JDialog {

    private XTandemViewer parent;
    private JButton okBtn;
    private JButton cancelBtn;
    private JPanel bottomPnl;
    private JPanel centerPnl;
    private JLabel fragmentIonMassAccuracyLbl;
    private JTextField fragmentIonMassAccuracyTtf;

    /**
     * Constructs a parameter dialog for setting the fragment
     * ion mass accuracy.
     *
     * @param parent parent frame
     * @param modal modal state
     */
    public ParametersDialog(XTandemViewer parent, boolean modal) {
        this.parent = parent;
        setTitle(XTandemViewer.APPTITLE + " --- " + "Parameters");
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        Container cp = this.getContentPane();

        okBtn = new JButton("OK");
        okBtn.setPreferredSize(new Dimension(100, 20));
        okBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                okButtonActionPerformed();
            }
        });

        cancelBtn = new JButton("Cancel");
        cancelBtn.setPreferredSize(new Dimension(100, 20));
        cancelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed();
            }
        });

        // The main panel
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        bottomPnl = new JPanel();
        bottomPnl.add(okBtn);
        bottomPnl.add(cancelBtn);

        mainPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
        centerPnl = new JPanel();

        fragmentIonMassAccuracyLbl = new JLabel("Fragment Ion Mass Accuracy: ");
        fragmentIonMassAccuracyTtf = new JTextField(10);
        fragmentIonMassAccuracyTtf.setText(String.valueOf(parent.getFragmentIonMassAccuracy()));
        centerPnl.add(fragmentIonMassAccuracyLbl);
        centerPnl.add(fragmentIonMassAccuracyTtf);

        mainPanel.add(centerPnl, BorderLayout.CENTER);
        mainPanel.add(bottomPnl, BorderLayout.SOUTH);
        cp.add(mainPanel);

        pack();
        setSize(350, 100);
        setLocationRelativeTo(parent);
        setVisible(true);
    }

    /**
     * When the ok button is pressed, the parameters are given back to the main frame.
     */
    private void okButtonActionPerformed() {
        parent.setFragmentIonMassAccuracy(Double.valueOf(fragmentIonMassAccuracyTtf.getText()));
        parent.insertFiles(parent.getXTandemFile(), "user.home");
        this.setVisible(false);
        this.dispose();
    }

    /**
     * When the close button is pressed, the dialog is discarded.
     */
    private void closeButtonActionPerformed() {
        this.setVisible(false);
        this.dispose();
    }

    /**
     * Closes the help frame.
     */
    private void close() {
        this.dispose();
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">FunctionCallBuffer | guide4you</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

<meta name="description" content="A configurable web client for geo-applications. Uses OpenLayers. Suitable for mobile devices."><meta property="twitter:card" content="summary"><meta property="twitter:title" content="guide4you"><meta property="twitter:description" content="A configurable web client for geo-applications. Uses OpenLayers. Suitable for mobile devices.">

  Home

  Reference
  Source

    <input class="search-input">

CDebug

CFeaturePopup

CFeatureTooltip

CFunctionCallBuffer

CG4UMap

CL10N

CListenerOrganizerMixin

CMessageDisplay

CModule

CMove

CPopupModifierManager

CStyling

FmultiplyExtent

FcreateMapInternal

FgetRegisteredModules

FregisterModule

FasObject

FasyncImageLoad

FcheckFor

Feven

FfinishAllImages

FgetConfig

Fhtml2Text

Fmixin

FmixinAsClass

Fodd

Foffset

FrecursiveSelect

FshowInteractionActivity

FurlDirname

FurlIsAbsolute

FurlJoin

FurlNormalize

FurlRelative

Fcopy

FcopyDeep

Fmerge

FmergeDeep

FmergeWithDefaults

Ftake

FfilterText

FrestoreText

Vdefaults

VolEventTypes

VcssClasses

VkeyCodes

TAPIMapInteraction

TAPIOptions

TFeaturePopupOptions

TFeatureTooltipOptions

TG4UMapOptions

TL10NOptions

TLocalizable

TMessageConstructorOptions

TMessageDisplayOptions

TMessageReducedDisplayOptions

TMoveOptions

TSingleMoveOptions

TPopupContent

TShowWMSFeatureInfoOptions

TStyleLike

TStyleObject

TURLConfig

TURLLike

configuratorsCControlFactory

CLayerConfigurator

CLayerFactory

CMapConfigurator

CUIConfigurator

VLayerType

VSuperType

TControlFactoryOptions

TFeatureConfig

TSourceConfig

Tg4uLayerOptions

TKineticOptions

TLayerConfig

TMapConfig

TMobileLayoutOptions

TProjectionConfig

Tg4uViewOptions

TFloat

THideableElement

TPositionedElement

TPositioningOptions

controlsCActivatableMixin

CActiveGroup

CArrowButtons

CAttribution

CCombinedZoom

CZoom

CZoomSlider

CComposedControl

CControlLogicMixin

CGeolocationButton

CHelpButton

CInfoButton

CLanguageSwitcherButton

CLanguageSwitcherMenu

CLayerSelector

CLinkButton

CLogo

CMeasurementButton

CMobileControls

CMousePosition

COverviewMap

CPrintButton

CRewireMixin

CScaleLine

CShiftableComposedControl

CWindowDecorator

VControl

TArrowButtonOptions

TCombinedZoomOptions

TZoomOptions

TComposedControlOptions

Tg4uControlOptions

TGeolocationButtonOptions

THelpButtonOptions

TInfoButtonOptions

TLanguageSwitcherButtonOptions

TLanguageSwitcherMenuOptions

TLayerSelectorOptions

TLinkButtonOptions

TLogoOptions

TMeasurementButtonOptions

TMousePositionOptions

TOverviewMapOptions

TShiftableComposedControlOptions

TWindowDecoratorOptions

htmlCButtonBox

CDropdown

CHistory

CShield

CWindow

FaddTooltip

FgetInFront

TButtonBoxOptions

TDropdownOptions

TEntry

TElementPosition

TOnTopOptions

TShieldOptions

TWindowOptions

interactionsCFeatureSelect

CMapEventInteraction

layersCBaseLayerMixin

CEmptyBaseLayer

CGroupLayer

CLayerLoadProcessCountMixin

CProvideMapMixin

CBaseSilentGroupLayer

CSilentGroupLayer

VBaseTileLayer

VBaseLayerImage

VImageLayer

VTileLayer

TBaseLayerMixinOptions

TVectorLayerOptions

sourcesCClusterSource

CImageWMSSource

CTileWMSSource

CWMSFeatureInfoMixin

CQueryVectorSource

CQueryWMSMixin

CSourceServerVector

VQueryImageWMSSource

VQueryTileWMSSource

TQuerySourceOptions

TSourceServerVectorOptions

import {FunctionCallBuffer} from 'guide4you/src/FunctionCallBuffer.js'

  public
  class

  | source

FunctionCallBuffer

Gathers function calls made in a specified time or till the main loop is free again and only calls the function once

Constructor Summary

Public Constructor

      public

          constructor(func: function, bufferTime: number)

Member Summary

Private Members

      private

          bufferTime_: number

      private

          func_: function

      private

          timeout_: number

Timeout ID

Method Summary

Public Methods

      public

          call(params: any[])

Public Constructors

    public

    constructor(func: function, bufferTime: number)

      source

Params:

Name	Type	Attribute	Description

      func
      function

the function whichs call should be buffered

      bufferTime
      number

optional

default: 0

time of the buffer. If set to 0 it evaluates as soon as the main loop is free again

Private Members

    private

    bufferTime_: number

      source

    private

    func_: function

      source

    private

    timeout_: number

      source

Timeout ID

Public Methods

    public

    call(params: any[])

      source

Params:

Name	Type	Attribute	Description

      params
      any[]

  Generated by ESDoc(1.0.3)


text:
import { Component } from '@angular/core';
import { ColorService, Styles } from './../src';

@Component({
  selector: 'theme-demo-app',
  styles: [
    Styles.BasicStyles.baseElementStyles
  ],
  template: `<div class="${Styles.AlignStyles.alignTopClass}"><theme-hello-world></theme-hello-world></div>`
})
export class DemoComponent {
  constructor(public colors: ColorService) {}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

angular.module("eappApp").controller("ContactUsController", ["$rootScope", "$scope", "appService", "$http", function($rootScope, $scope, appService, $http)
{
    $scope.officeLongitude = -75.697530;
    $scope.officeLatitude = 45.495940;
    $scope.officeStreet = "76 Rue Jean-Perrin";
    $scope.officeCity = "Gatineau, QC";
    $scope.officePostcode = "J8V 2R2";
    $scope.officeContact = "infos@otiprix.com";

    $scope.Init = function()
    {
        $rootScope.isContact = true;

        $scope.InitializeMap();
    };

    $scope.InitializeMap = function()
    {
        var locations = [
        ['

Notre Bureau
76 Rue Jean-Perrin,
Gatineau, J8V 2R2

', 45.495940, -75.697530, 2]
        ];

        // Create the map
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 15,
            scrollwheel: true,
            navigationControl: true,
            mapTypeControl: true,
            scaleControl: false,
            draggable: true,
            styles: [ { "stylers": [ { "hue": "#000" },  {saturation: -200},
                {gamma: 0.50} ] } ],
            center: new google.maps.LatLng($scope.officeLatitude, $scope.officeLongitude),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });

        var infowindow = new google.maps.InfoWindow();

        var marker, i;

        for (i = 0; i < locations.length; i++) {

            marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map ,
            icon: appService.baseUrl.concat('/assets/img/marker.png')
            });

          google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
              infowindow.setContent(locations[i][0]);
              infowindow.open(map, marker);
            };
          })(marker, i));
        }

    };

    $scope.contact =
    {
        name : "",
        email : "",
        subject : "",
        comment : ""
    };

    $scope.contactus = function()
    {
        if($scope.contactusForm.$valid)
        {
            var formData = new FormData();
            formData.append("name", $scope.contact.name);
            formData.append("email", $scope.contact.email);
            formData.append("subject", $scope.contact.subject);
            formData.append("comment", $scope.contact.comment);

            $http.post(appService.siteUrl.concat("/home/contactus"), formData, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
            }).then(function(response)
            {
                if(response.data.result)
                {
                    $scope.message = "Votre message a bien été envoyé.";
                    $scope.contact =
                    {
                        name : "",
                        email : "",
                        subject : "",
                        comment : ""
                    };
                    $scope.contactusForm.$setPristine();
                    $scope.contactusForm.$setValidity();
                    $scope.contactusForm.$setUntouched();
                }
                else
                {
                    $scope.errorMessage = "Une erreur de serveur inattendue s'est produite. Veuillez réessayer plus tard.";
                }

            });
        }
    };

    angular.element(document).ready(function()
    {
        $scope.Init();
    });

}]);


text:
(function() {
    'use strict';

    angular
        .module('scientificweekApp')
        .controller('PersonDialogController', PersonDialogController);

    PersonDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', '$q', 'entity', 'Person', 'User'];

    function PersonDialogController ($timeout, $scope, $stateParams, $uibModalInstance, $q, entity, Person, User) {
        var vm = this;

        vm.person = entity;
        vm.clear = clear;
        vm.save = save;
        vm.users = User.query();

        $timeout(function (){
            angular.element('.form-group:eq(1)>input').focus();
        });

        function clear () {
            $uibModalInstance.dismiss('cancel');
        }

        function save () {
            vm.isSaving = true;
            if (vm.person.id !== null) {
                Person.update(vm.person, onSaveSuccess, onSaveError);
            } else {
                Person.save(vm.person, onSaveSuccess, onSaveError);
            }
        }

        function onSaveSuccess (result) {
            $scope.$emit('scientificweekApp:personUpdate', result);
            $uibModalInstance.close(result);
            vm.isSaving = false;
        }

        function onSaveError () {
            vm.isSaving = false;
        }

    }
})();


text:
#include "utils.h"
#include <stdlib.h>
#include <string.h>

namespace MinVR {

class Cxml
{
  public:
    Cxml();
    ~Cxml();
    // parse a string containg xml code
    bool parse_string(std::string xml_string);
  private:
    int m_cursor;
    int m_length;
    element* m_root_node;
    bool get_node(std::string  xml_string);
  public:
    element* get_root_element();
};

} // ending namespace MinVR

#endif // CXML_H

// TODO list -- Needed improvements to the Cxml parser.
//
//   - Limited entity support.  At least the basics: &, <, >, etc.
//
//   - Make a "printXML() method like printStructure(), for debugging.
//
//   - Support comments (again).  That is, restore the comment-processing
//     calls, and persuade the data index code to ignore them.
//
//   - Real entity support, where they can be defined.
//
//   - CDATA support (maybe have this already?)
//
//   - Add hook for pre-processing with xsltproc, and validation to a schema.
//
//   - Tidying and better documentation.
//
//   - Better errors.
//


text:
namespace EzApp.Tests.Core.TestClasses
{
    public class TestEntityCreateClientModel
    {
    }
}


text:
namespace Patterns.Creational.Prototype
{
    // "Prototype"
    abstract class Prototype
    {
        private string id;

        // Constructor
        public Prototype(string id)
        {
            this.id = id;
        }

        // Property
        public string Id
        {
            get { return id; }
        }

        public abstract Prototype Clone();
    }

    // "ConcretePrototype1"

    class ConcretePrototype1 : Prototype
    {
        // Constructor
        public ConcretePrototype1(string id)
            : base(id)
        {
        }

        public override Prototype Clone()
        {
            // Shallow copy
            return (Prototype)this.MemberwiseClone();
        }
    }

    // "ConcretePrototype2"

    class ConcretePrototype2 : Prototype
    {
        // Constructor
        public ConcretePrototype2(string id)
            : base(id)
        {
        }

        public override Prototype Clone()
        {
            // Shallow copy
            return (Prototype)this.MemberwiseClone();
        }
    }
}


text:
layout: page
title: Research Publications
---

{% include publications.html %}


text:
using BadMishka.DocumentFormat.LuceneIndex.Index;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace BadMishka.DocumentFormat.LuceneIndex.Search
{
    public class FuzzQuery : MultiTermQuery
    {
        private Term fuzzyTerm;

        public FuzzQuery(Term term)
            : base(term)
        {
            this.fuzzyTerm = term;
        }

        public override void Prepare(IndexReader reader)
        {
            try
            {
                this.SetEnum(new FuzzyTermEnum(reader, this.fuzzyTerm));
#pragma warning disable CS0168 // Variable is declared but never used
            }
            catch (IOException ex)
#pragma warning restore CS0168 // Variable is declared but never used
            {

            }
        }

        public override string ToString()
        {
            return base.ToString() + "~";
        }
    }
}


text:
package com.despectra.githubrepoview.activities;

import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.despectra.githubrepoview.LoginInfo;
import com.despectra.githubrepoview.R;
import com.despectra.githubrepoview.fragments.FriendsFragment;
import com.despectra.githubrepoview.fragments.LogoutDialog;

/**
 * Activity that contains different items list fragments
 */
public class MainActivity extends AppCompatActivity {

    private LogoutDialog.Callback mLogoutDialogCallback = new LogoutDialog.Callback() {
        @Override
        public void onLogoutConfirmed() {
            performLogout();
        }
    };
    private SearchView.OnQueryTextListener mSearchViewListener;
    private SearchView mSearchView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupAppBar();
        if(savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, new FriendsFragment(), FriendsFragment.class.getName())
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .commit();
        } else {
            LogoutDialog dialog =  (LogoutDialog) getFragmentManager().findFragmentByTag(LogoutDialog.TAG);
            if(dialog != null) {
                dialog.setCallback(mLogoutDialogCallback);
            }
        }
    }

    public void setupAppBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.appbar);
        setSupportActionBar(toolbar);
    }

    public void setSearchViewListener(SearchView.OnQueryTextListener listener) {
        mSearchViewListener = listener;
        if(mSearchView != null) {
            mSearchView.setOnQueryTextListener(mSearchViewListener);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        MenuItem searchItem = menu.findItem(R.id.search);
        mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        mSearchView.setOnQueryTextListener(mSearchViewListener);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.logout:
                showLogoutDialog();
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public void onBackPressed() {
        if(getFragmentManager().getBackStackEntryCount() == 0) {
            super.onBackPressed();
        } else {
            getFragmentManager().popBackStack();
        }
    }

    /**
     * Shows logout confirmation dialog
     */
    private void showLogoutDialog() {
        LogoutDialog dialog = (LogoutDialog) getFragmentManager().findFragmentByTag(LogoutDialog.TAG);
        if(dialog == null) {
            dialog = new LogoutDialog();
        }
        dialog.setCallback(mLogoutDialogCallback);
        dialog.show(getFragmentManager(), LogoutDialog.TAG);
    }

    /**
     * Logout action implementation
     * Remove all user credentials from shared preferences, switch to LoginActivity
     */
    private void performLogout() {
        LoginInfo.clearLoggedUser(this);

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}


text:
<?php

/* @Twig/Exception/exception.rdf.twig */
class __TwigTemplate_cd4742ff87e61a49fe68bc73d06586105ed62d5e20d2829f73f3077289c715bd extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = false;

        $this->blocks = array(
        );
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        // line 1
        $this->loadTemplate("@Twig/Exception/exception.xml.twig", "@Twig/Exception/exception.rdf.twig", 1)->display(array_merge($context, array("exception" => ($context["exception"] ?? null))));
    }

    public function getTemplateName()
    {
        return "@Twig/Exception/exception.rdf.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  19 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("", "@Twig/Exception/exception.rdf.twig", "C:\\College\\College\\Third year\\Second Semester\\WFDassignment\\NURLmanager\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\TwigBundle\\Resources\\views\\Exception\\exception.rdf.twig");
    }
}


text:
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/platform_device.h>

#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/partitions.h>

#include <asm/io.h>
#include <asm/hardware.h>
#include <asm/mach/flash.h>

#include <linux/reboot.h>

struct ixp2000_flash_info {
	struct		mtd_info *mtd;
	struct		map_info map;
	struct		mtd_partition *partitions;
	struct		resource *res;
	int		nr_banks;
};

static inline unsigned long flash_bank_setup(struct map_info *map, unsigned long ofs)
{
	unsigned long (*set_bank)(unsigned long) =
		(unsigned long(*)(unsigned long))map->map_priv_2;

	return (set_bank ? set_bank(ofs) : ofs);
}

#ifdef __ARMEB__
/*
 * Rev A0 and A1 of IXP2400 silicon have a broken addressing unit which
 * causes the lower address bits to be XORed with 0x11 on 8 bit accesses
 * and XORed with 0x10 on 16 bit accesses. See the spec update, erratum 44.
 */
static int erratum44_workaround = 0;

static inline unsigned long address_fix8_write(unsigned long addr)
{
	if (erratum44_workaround) {
		return (addr ^ 3);
	}
	return addr;
}
#else

#define address_fix8_write(x)	(x)
#endif

static map_word ixp2000_flash_read8(struct map_info *map, unsigned long ofs)
{
	map_word val;

	val.x[0] =  *((u8 *)(map->map_priv_1 + flash_bank_setup(map, ofs)));
	return val;
}

/*
 * We can't use the standard memcpy due to the broken SlowPort
 * address translation on rev A0 and A1 silicon and the fact that
 * we have banked flash.
 */
static void ixp2000_flash_copy_from(struct map_info *map, void *to,
			      unsigned long from, ssize_t len)
{
	from = flash_bank_setup(map, from);
	while(len--)
		*(__u8 *) to++ = *(__u8 *)(map->map_priv_1 + from++);
}

static void ixp2000_flash_write8(struct map_info *map, map_word d, unsigned long ofs)
{
	*(__u8 *) (address_fix8_write(map->map_priv_1 +
				      flash_bank_setup(map, ofs))) = d.x[0];
}

static void ixp2000_flash_copy_to(struct map_info *map, unsigned long to,
			    const void *from, ssize_t len)
{
	to = flash_bank_setup(map, to);
	while(len--) {
		unsigned long tmp = address_fix8_write(map->map_priv_1 + to++);
		*(__u8 *)(tmp) = *(__u8 *)(from++);
	}
}

static int ixp2000_flash_remove(struct platform_device *dev)
{
	struct flash_platform_data *plat = dev->dev.platform_data;
	struct ixp2000_flash_info *info = platform_get_drvdata(dev);

	platform_set_drvdata(dev, NULL);

	if(!info)
		return 0;

	if (info->mtd) {
		del_mtd_partitions(info->mtd);
		map_destroy(info->mtd);
	}
	if (info->map.map_priv_1)
		iounmap((void *) info->map.map_priv_1);

	kfree(info->partitions);

	if (info->res) {
		release_resource(info->res);
		kfree(info->res);
	}

	if (plat->exit)
		plat->exit();

	return 0;
}

static int ixp2000_flash_probe(struct platform_device *dev)
{
	static const char *probes[] = { "RedBoot", "cmdlinepart", NULL };
	struct ixp2000_flash_data *ixp_data = dev->dev.platform_data;
	struct flash_platform_data *plat;
	struct ixp2000_flash_info *info;
	unsigned long window_size;
	int err = -1;

	if (!ixp_data)
		return -ENODEV;

	plat = ixp_data->platform_data;
	if (!plat)
		return -ENODEV;

	window_size = dev->resource->end - dev->resource->start + 1;
	dev_info(&dev->dev, "Probe of IXP2000 flash(%d banks x %dMiB)\n",
		 ixp_data->nr_banks, ((u32)window_size >> 20));

	if (plat->width != 1) {
		dev_err(&dev->dev, "IXP2000 MTD map only supports 8-bit mode, asking for %d\n",
			plat->width * 8);
		return -EIO;
	}

	info = kmalloc(sizeof(struct ixp2000_flash_info), GFP_KERNEL);
	if(!info) {
		err = -ENOMEM;
		goto Error;
	}
	memzero(info, sizeof(struct ixp2000_flash_info));

	platform_set_drvdata(dev, info);

	/*
	 * Tell the MTD layer we're not 1:1 mapped so that it does
	 * not attempt to do a direct access on us.
	 */
	info->map.phys = NO_XIP;

	info->nr_banks = ixp_data->nr_banks;
	info->map.size = ixp_data->nr_banks * window_size;
	info->map.bankwidth = 1;

	/*
 	 * map_priv_2 is used to store a ptr to to the bank_setup routine
 	 */
	info->map.map_priv_2 = (unsigned long) ixp_data->bank_setup;

	info->map.name = dev->dev.bus_id;
	info->map.read = ixp2000_flash_read8;
	info->map.write = ixp2000_flash_write8;
	info->map.copy_from = ixp2000_flash_copy_from;
	info->map.copy_to = ixp2000_flash_copy_to;

	info->res = request_mem_region(dev->resource->start,
			dev->resource->end - dev->resource->start + 1,
			dev->dev.bus_id);
	if (!info->res) {
		dev_err(&dev->dev, "Could not reserve memory region\n");
		err = -ENOMEM;
		goto Error;
	}

	info->map.map_priv_1 = (unsigned long) ioremap(dev->resource->start,
			    	dev->resource->end - dev->resource->start + 1);
	if (!info->map.map_priv_1) {
		dev_err(&dev->dev, "Failed to ioremap flash region\n");
		err = -EIO;
		goto Error;
	}

#if defined(__ARMEB__)
	/*
	 * Enable erratum 44 workaround for NPUs with broken slowport
	 */

	erratum44_workaround = ixp2000_has_broken_slowport();
	dev_info(&dev->dev, "Erratum 44 workaround %s\n",
	       erratum44_workaround ? "enabled" : "disabled");
#endif

	info->mtd = do_map_probe(plat->map_name, &info->map);
	if (!info->mtd) {
		dev_err(&dev->dev, "map_probe failed\n");
		err = -ENXIO;
		goto Error;
	}
	info->mtd->owner = THIS_MODULE;

	err = parse_mtd_partitions(info->mtd, probes, &info->partitions, 0);
	if (err > 0) {
		err = add_mtd_partitions(info->mtd, info->partitions, err);
		if(err)
			dev_err(&dev->dev, "Could not parse partitions\n");
	}

	if (err)
		goto Error;

	return 0;

Error:
	ixp2000_flash_remove(dev);
	return err;
}

static struct platform_driver ixp2000_flash_driver = {
	.probe		= ixp2000_flash_probe,
	.remove		= ixp2000_flash_remove,
	.driver		= {
		.name	= "IXP2000-Flash",
	},
};

static int __init ixp2000_flash_init(void)
{
	return platform_driver_register(&ixp2000_flash_driver);
}

static void __exit ixp2000_flash_exit(void)
{
	platform_driver_unregister(&ixp2000_flash_driver);
}

module_init(ixp2000_flash_init);
module_exit(ixp2000_flash_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Deepak Saxena <dsaxena@plexity.net>");


text:
#include "sys_processor.h"
#include "hardware.h"

#ifndef _DEBUG_SYS_H
#define _DEBUG_SYS_H
#include "sys_processor.h"

#define WIN_TITLE 		"Cosmac Elf Emulator"										// Initial Window stuff
#define WIN_WIDTH		(32*8*4)
#define WIN_HEIGHT		(23*8*4+64)
#define WIN_BACKCOLOUR	0x004

// *******************************************************************************************************************************
//							These functions need to be implemented by the dependent debugger.
// *******************************************************************************************************************************

#define DEBUG_ARGUMENTS(ac,av) if (ac == 2) CPULoadBinary(argv[1]);					// Handle CLI arguments

#define DEBUG_CPURENDER(x) 	DBGXRender(x,0)											// Render the debugging display
#define DEBUG_VDURENDER(x)	DBGXRender(x,1)											// Render the game display etc.

#define DEBUG_RESET() 		CPUReset()												// Reset the CPU / Hardware.
#define DEBUG_HOMEPC()		((CPUGetStatus()->pc) & 0xFFFF) 						// Get PC Home Address (e.g. current PCTR value)

#define DEBUG_SINGLESTEP()	CPUExecuteInstruction()									// Execute a single instruction, return 0 or Frame rate on frame end.
#define DEBUG_RUN(b1,b2) 	CPUExecute(b1,b2) 										// Run a frame or to breakpoint, returns -1 if breakpoint
#define DEBUG_GETOVERBREAK() CPUGetStepOverBreakpoint()								// Where would we break to step over here. (0 == single step)

#define DEBUG_RAMSTART 		(0x0000)												// Initial RAM address for debugger.
#define DEBUG_SHIFT(d,v)	((((d) << 4) | v) & 0xFFFF)								// Shifting into displayed address.

#define DEBUG_KEYMAP(k,r)	HWIProcessKey(k,r)

void DBGXRender(int *address,int showDisplay);										// Render the debugger screen.
void DBGXRenderDisplay(void);
void DBGXLoad(char *file);

#endif


text:
static int ft_initialized = 0;
static FT_Library ft;

struct Font {
	struct Character charmap[128];
	GLuint tex_glyph;
	GLuint tex_atlas;
	unsigned tex_atlas_offset;
};

static void
shutdown_freetype(void)
{
	FT_Done_FreeType(ft);
	ft_initialized = 0;
}

static int
init_freetype(void)
{
	if (FT_Init_FreeType(&ft) != 0) {
		return 0;
	}
	atexit(shutdown_freetype);
	ft_initialized = 1;
	return 1;
}

static int
init_glyph_texture(struct Font *font, FT_Glyph *glyphs)
{
	GLubyte data[128][2];
	for (unsigned char c = 0; c < 128; c++) {
		struct Character *ch = &font->charmap[c];
		data[c][0] = ch->size[0];
		data[c][1] = ch->size[1];
	}

	glGenTextures(1, &font->tex_glyph);
	if (!font->tex_glyph) {
		err(ERR_OPENGL);
		return 0;
	}

	glBindTexture(GL_TEXTURE_1D, font->tex_glyph);
	// NOTE: `GL_NEAREST` is *mandatory* with integer textures.
	// http://stackoverflow.com/a/39578132/324790
	glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0);
	glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0);
	glTexImage1D(
		GL_TEXTURE_1D,
		0,
		GL_RG16UI,
		128,
		0,
		GL_RG_INTEGER,
		GL_UNSIGNED_BYTE,
		data
	);
	glBindTexture(GL_TEXTURE_1D, 0);

	if (glGetError() != GL_NO_ERROR) {
		glDeleteTextures(1, &font->tex_glyph);
		font->tex_glyph = 0;
		err(ERR_OPENGL);
		return 0;
	}

	return 1;
}

static int
init_atlas_texture(struct Font *font, FT_Glyph *glyphs)
{
	// compute the atlas height and step between glyphs
	unsigned atlas_w = 0, atlas_h = 0, atlas_s = 0;
	for (unsigned c = 0; c < 128; c++) {
		FT_Bitmap *bmp = &((FT_BitmapGlyph)glyphs[c])->bitmap;
		unsigned width = abs(bmp->pitch);
		unsigned height = bmp->rows;
		if (height > atlas_h) {
			atlas_h = height;
		}
		if (width > atlas_s) {
			atlas_s = width;
		}
	}
	font->tex_atlas_offset = atlas_s;
	atlas_w = atlas_s * 128;

	// texture data buffer
	unsigned char data[atlas_w * atlas_h];
	memset(data, 0, sizeof(data));

	// blit each glyph to atlas
	for (unsigned c = 0; c < 128; c++) {
		FT_Bitmap *bmp = &((FT_BitmapGlyph)glyphs[c])->bitmap;
		for (unsigned row = 0; row < bmp->rows; row++) {
			// NOTE: both FreeType and OpenGL assume the origin in
			// lower-left corner, thus, when copying the rows we
			// start from lower one and go up
			memcpy(
				data + (bmp->rows - row - 1) * atlas_w + c * atlas_s,
				bmp->buffer + row * bmp->pitch,
				abs(bmp->pitch)  // NOTE: pitch can be negative
			);
		}
	}

	// create the atlas texture
	glGenTextures(1, &font->tex_atlas);
	if (!font->tex_atlas) {
		err(ERR_OPENGL);
		return 0;
	}

	// setup the texture as single-component with no mipmaps
	glBindTexture(GL_TEXTURE_RECTANGLE, font->tex_atlas);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_BASE_LEVEL, 0);
	glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAX_LEVEL, 0);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexImage2D(
		GL_TEXTURE_RECTANGLE,
		0,
		GL_R8,
		atlas_w,
		atlas_h,
		0,
		GL_RED,
		GL_UNSIGNED_BYTE,
		data
	);
	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
	glBindTexture(GL_TEXTURE_RECTANGLE, 0);

	if (glGetError() != GL_NO_ERROR) {
		glDeleteTextures(1, &font->tex_glyph);
		font->tex_glyph = 0;
		err(ERR_OPENGL);
		return 0;
	}

	return 1;
}

static int
init_font(struct Font *font, FT_Face face)
{
	// initialize the charmap table
	memset(font->charmap, 0, sizeof(struct Character) * 128);

	// bitmaps copies
	FT_Glyph glyphs[128];

	for (unsigned char c = 0; c < 128; c++) {
		if (FT_Load_Char(face, c, FT_LOAD_RENDER) != 0 ||
		    FT_Get_Glyph(face->glyph, &glyphs[c]) != 0 ||
		    FT_Glyph_To_Bitmap(&glyphs[c], FT_RENDER_MODE_NORMAL, NULL, 0) != 0) {
			err(ERR_FREETYPE);
			return 0;
		}
		struct Character *ch = &font->charmap[c];
		ch->size[0] = face->glyph->bitmap.width;
		ch->size[1] = face->glyph->bitmap.rows;
		ch->bearing[0] = face->glyph->bitmap_left;
		ch->bearing[1] = face->glyph->bitmap_top;
		ch->advance = face->glyph->advance.x;
	}

	int ok = (
		init_glyph_texture(font, glyphs) &&
		init_atlas_texture(font, glyphs)
	);

	for (unsigned char c = 0; c < 128; c++) {
		FT_Done_Glyph(glyphs[c]);
	}

	return ok;
}

struct Font*
font_from_buffer(const void *data, size_t size, unsigned pt)
{
	assert(data != NULL);
	assert(size > 0);
	assert(pt > 0);

	FT_Face face = NULL;
	struct Font *font = NULL;

	if ((!ft_initialized && !init_freetype())) {
		err(ERR_FREETYPE);
		goto error;
	} else if (FT_New_Memory_Face(ft, (FT_Byte*)data, size, 0, &face) != 0 ||
	           FT_Set_Pixel_Sizes(face, 0, pt) != 0) {
		err(ERR_INVALID_FONT);
		goto error;
	} else if (!(font = malloc(sizeof(struct Font)))) {
		err(ERR_NO_MEM);
		goto error;
	} else if (!init_font(font, face)) {
		goto error;
	}

cleanup:
	if (face) {
		FT_Done_Face(face);
	}

	return font;

error:
	font_free(font);
	font = NULL;
	goto cleanup;
}

struct Font*
font_from_file(const char *filename, unsigned pt)
{
	assert(filename != NULL);
	assert(strlen(filename) > 0);
	assert(pt > 0);

	// attempt to read the font file
	char *data = NULL;
	size_t size = file_read(filename, &data);
	if (!size) {
		return NULL;
	}

	// create font from just read contents
	struct Font *font = font_from_buffer(data, size, pt);

	free(data);

	return font;
}

const struct Character*
font_get_char(struct Font *font, char c)
{
	assert(font != NULL);
	return &font->charmap[(int)c];
}

GLuint
font_get_glyph_texture(struct Font *font)
{
	assert(font != NULL);
	return font->tex_glyph;
}

GLuint
font_get_atlas_texture(struct Font *font)
{
	assert(font != NULL);
	return font->tex_atlas;
}

unsigned
font_get_atlas_offset(struct Font *font)
{
	assert(font != NULL);
	return font->tex_atlas_offset;
}

void
font_free(struct Font *font)
{
	if (font) {
		free(font);
	}
}


text:
package com.example.administrator.catemenu.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.administrator.catemenu.R;
import com.example.administrator.catemenu.adapter.SearchResultAdapter;
import com.example.administrator.catemenu.modle.SearchResult;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/28.
 */
public class SearchResultActivity extends Activity {
    ImageView imageViewBack;
    ListView listViewSearchResult;
    ListView listViewOtherTuijian;
    List<SearchResult> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        listViewSearchResult = (ListView) findViewById(R.id.search_result);
        listViewOtherTuijian = (ListView) findViewById(R.id.other_tuijian);
        list = getData();
        SearchResultAdapter searchResultAdapter = new SearchResultAdapter(this,list);
        listViewSearchResult.setAdapter(searchResultAdapter);
        listViewOtherTuijian.setAdapter(searchResultAdapter);
        imageViewBack = (ImageView) findViewById(R.id.search_result_back);
        imageViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchResultActivity.this,SearchActivity.class);
                startActivity(intent);
            }
        });
    }
    public List<SearchResult> getData(){
        list = new ArrayList<>();
        for (int i=0;i<5;i++){
            SearchResult searchResult = new SearchResult();
            searchResult.setImage(R.mipmap.shanyu2);
            searchResult.setCaiName("蒜仔烤鳝段");
            searchResult.setPublishPerson("某某");
            searchResult.setPublishTime("2016.11.22");
            list.add(searchResult);
        }
        return list;
    }
}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.cloudasset.v1p4beta1.model;

/**
 * A representation of a Google Cloud resource.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Asset API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudAssetV1p7beta1Resource extends com.google.api.client.json.GenericJson {

  /**
   * The content of the resource, in which some sensitive fields are removed and may not be present.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.Map<String, java.lang.Object> data;

  /**
   * The URL of the discovery document containing the resource's JSON schema. Example:
   * `https://www.googleapis.com/discovery/v1/apis/compute/v1/rest` This value is unspecified for
   * resources that do not have an API based on a discovery document, such as Cloud Bigtable.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String discoveryDocumentUri;

  /**
   * The JSON schema name listed in the discovery document. Example: `Project` This value is
   * unspecified for resources that do not have an API based on a discovery document, such as Cloud
   * Bigtable.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String discoveryName;

  /**
   * The location of the resource in Google Cloud, such as its zone and region. For more
   * information, see https://cloud.google.com/about/locations/.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String location;

  /**
   * The full name of the immediate parent of this resource. See [Resource
   * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) for more
   * information. For Google Cloud assets, this value is the parent resource defined in the [Cloud
   * IAM policy hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). Example:
   * `//cloudresourcemanager.googleapis.com/projects/my_project_123` For third-party assets, this
   * field may be set differently.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String parent;

  /**
   * The REST URL for accessing the resource. An HTTP `GET` request using this URL returns the
   * resource itself. Example: `https://cloudresourcemanager.googleapis.com/v1/projects/my-
   * project-123` This value is unspecified for resources without a REST API.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String resourceUrl;

  /**
   * The API version. Example: `v1`
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String version;

  /**
   * The content of the resource, in which some sensitive fields are removed and may not be present.
   * @return value or {@code null} for none
   */
  public java.util.Map<String, java.lang.Object> getData() {
    return data;
  }

  /**
   * The content of the resource, in which some sensitive fields are removed and may not be present.
   * @param data data or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setData(java.util.Map<String, java.lang.Object> data) {
    this.data = data;
    return this;
  }

  /**
   * The URL of the discovery document containing the resource's JSON schema. Example:
   * `https://www.googleapis.com/discovery/v1/apis/compute/v1/rest` This value is unspecified for
   * resources that do not have an API based on a discovery document, such as Cloud Bigtable.
   * @return value or {@code null} for none
   */
  public java.lang.String getDiscoveryDocumentUri() {
    return discoveryDocumentUri;
  }

  /**
   * The URL of the discovery document containing the resource's JSON schema. Example:
   * `https://www.googleapis.com/discovery/v1/apis/compute/v1/rest` This value is unspecified for
   * resources that do not have an API based on a discovery document, such as Cloud Bigtable.
   * @param discoveryDocumentUri discoveryDocumentUri or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setDiscoveryDocumentUri(java.lang.String discoveryDocumentUri) {
    this.discoveryDocumentUri = discoveryDocumentUri;
    return this;
  }

  /**
   * The JSON schema name listed in the discovery document. Example: `Project` This value is
   * unspecified for resources that do not have an API based on a discovery document, such as Cloud
   * Bigtable.
   * @return value or {@code null} for none
   */
  public java.lang.String getDiscoveryName() {
    return discoveryName;
  }

  /**
   * The JSON schema name listed in the discovery document. Example: `Project` This value is
   * unspecified for resources that do not have an API based on a discovery document, such as Cloud
   * Bigtable.
   * @param discoveryName discoveryName or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setDiscoveryName(java.lang.String discoveryName) {
    this.discoveryName = discoveryName;
    return this;
  }

  /**
   * The location of the resource in Google Cloud, such as its zone and region. For more
   * information, see https://cloud.google.com/about/locations/.
   * @return value or {@code null} for none
   */
  public java.lang.String getLocation() {
    return location;
  }

  /**
   * The location of the resource in Google Cloud, such as its zone and region. For more
   * information, see https://cloud.google.com/about/locations/.
   * @param location location or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setLocation(java.lang.String location) {
    this.location = location;
    return this;
  }

  /**
   * The full name of the immediate parent of this resource. See [Resource
   * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) for more
   * information. For Google Cloud assets, this value is the parent resource defined in the [Cloud
   * IAM policy hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). Example:
   * `//cloudresourcemanager.googleapis.com/projects/my_project_123` For third-party assets, this
   * field may be set differently.
   * @return value or {@code null} for none
   */
  public java.lang.String getParent() {
    return parent;
  }

  /**
   * The full name of the immediate parent of this resource. See [Resource
   * Names](https://cloud.google.com/apis/design/resource_names#full_resource_name) for more
   * information. For Google Cloud assets, this value is the parent resource defined in the [Cloud
   * IAM policy hierarchy](https://cloud.google.com/iam/docs/overview#policy_hierarchy). Example:
   * `//cloudresourcemanager.googleapis.com/projects/my_project_123` For third-party assets, this
   * field may be set differently.
   * @param parent parent or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setParent(java.lang.String parent) {
    this.parent = parent;
    return this;
  }

  /**
   * The REST URL for accessing the resource. An HTTP `GET` request using this URL returns the
   * resource itself. Example: `https://cloudresourcemanager.googleapis.com/v1/projects/my-
   * project-123` This value is unspecified for resources without a REST API.
   * @return value or {@code null} for none
   */
  public java.lang.String getResourceUrl() {
    return resourceUrl;
  }

  /**
   * The REST URL for accessing the resource. An HTTP `GET` request using this URL returns the
   * resource itself. Example: `https://cloudresourcemanager.googleapis.com/v1/projects/my-
   * project-123` This value is unspecified for resources without a REST API.
   * @param resourceUrl resourceUrl or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setResourceUrl(java.lang.String resourceUrl) {
    this.resourceUrl = resourceUrl;
    return this;
  }

  /**
   * The API version. Example: `v1`
   * @return value or {@code null} for none
   */
  public java.lang.String getVersion() {
    return version;
  }

  /**
   * The API version. Example: `v1`
   * @param version version or {@code null} for none
   */
  public GoogleCloudAssetV1p7beta1Resource setVersion(java.lang.String version) {
    this.version = version;
    return this;
  }

  @Override
  public GoogleCloudAssetV1p7beta1Resource set(String fieldName, Object value) {
    return (GoogleCloudAssetV1p7beta1Resource) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudAssetV1p7beta1Resource clone() {
    return (GoogleCloudAssetV1p7beta1Resource) super.clone();
  }

}