text:
class CreateSpells < ActiveRecord::Migration
  def change
    create_table :spells do |t|
      t.belongs_to :user
      t.string :name
      t.text :description

      t.timestamps null: false
    end

    add_index :spells, :user_id
  end
end


text:
<template name="bootstrap_magic_preview_form_states">

Alerts

            ×
            Error Change a few things up and try submitting again.

            ×
            Success You successfully read this important alert message.

            ×
            Information This alert needs your attention, but it's not super important.

Inputs colored

    Input with success
    <input type="text" class="form-control" id="inputSuccess">

    Input with warning
    <input type="text" class="form-control" id="inputWarning">

    Input with error
    <input type="text" class="form-control" id="inputError">

Fusce dapibus, tellus ac cursus commodo, tortor mauris nibh.

Nullam id dolor id nibh ultricies vehicula ut id elit.

Etiam porta sem malesuada magna mollis euismod.

Donec ullamcorper nulla non metus auctor fringilla.

Duis mollis, est non commodo luctus, nisi erat porttitor ligula.

Maecenas sed diam eget risus varius blandit sit amet non magna.

Labels

Example heading New

  Default
  Primary
  Success
  Info
  Warning
  Danger

</template>

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Archivo Actividad_model, contiene la clase para manejar la tabla Actividad de la base de datos.
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Modelo Actividad el cual contendrá las funciones para gestionar la tabla Actividad
 * de la base de datos.
 *
 * @package aplication/models
 * @author Andrés David Montoya Aguirre <admont28@gmail.com>
 * @link https://github.com/admont28 Perfil del autor.
 * @version 1.0 Versión inicial de la clase.
 */
class Actividad_model extends CI_Model {
	/**
	 * Constante que almacenará el nombre de la tabla Actividad.
	 */
	const TABLE_NAME = "Actividad";
	/**
	 * Constante que almacenará el nombre de la llave primaria de la tabla Actividad.
	 */
	const TABLE_PK_NAME = "idActividad";

	/**
	 * Función __construct del modelo Actividad_model.
	 *
	 * Esta función se ejecuta cuando se crea una instancia de este modelo (Actividad_model).
	 * La función ejecuta el constructor de la clase padre (CI_Model).
	 * La función carga los archivos necesarios para gestionar la base de datos.
	 *
	 * @access public
	 * @return void
	 */
	public function __construct(){
		parent::__construct();
		$this->load->database();
	}

	/**
	 * Función obtenerActividadesTipoHerida del modelo Actividad_model.
	 *
	 * La función realiza una consulta a la base de datos para obtener las actividades relacionadas con un tipo de herida en específico.
	 * @param  integer $idTipoHerida Entero que identifica unívocamente al tipo de herida.
	 *
	 * @access public
	 * @return array|boolean     Retorna un arreglo con el resultado de la consulta si existe al menos 1 registro, de lo contrario retorna false.
	 */
	public function obtenerActividadesTipoHerida($idTipoHerida){
		//$query = "SELECT * FROM Actividad A, TipoHeridaActividad T WHERE T.TipoHerida_idTipoHerida = $tipo_herida AND T.Actividad_idAcitivdad = A.idActividad";
		// SELECT * FROM `Actividad`, `TipoHeridaActividad`, `FactorRiesgoActividad` WHERE `TipoHeridaActividad`.`TipoHerida_idTipoHerida` = '1' AND `FactorRiesgoActividad`.`FactorRiesgo_idFactorRiesgo` = 1 AND ( `FactorRiesgoActividad`.`Actividad_idActividad` = `Actividad`.`idActividad` OR `TipoHeridaActividad`.`Actividad_idActividad` = `Actividad`.`idActividad`)
		$this->db->from("Actividad , TipoHeridaActividad");
		$this->db->where("TipoHeridaActividad.TipoHerida_idTipoHerida", $idTipoHerida);
		$this->db->where("TipoHeridaActividad.Actividad_idActividad = Actividad.idActividad");
		$this->db->order_by("orden_tipoheridaactividad", "asc");
		$resultado = $this->db->get();
		if($resultado->num_rows() > 0 ) return $resultado->result();
        else return false;
	}

	/**
	 * Función obtenerActividadesFactorRiesgo del modelo Actividad_model.
	 *
	 * La función realiza una consulta a la base de datos para obtener las actividades relacionadas con un factor de riesgo en específico.
	 * @param  Integer $idFactorRiesgo Entero que identifica unívocamente al factor de riesgo.
	 *
	 * @access public
	 * @return array|boolean     Retorna un arreglo con el resultado de la consulta si existe al menos 1 registro, de lo contrario retorna false.
	 */
	public function obtenerActividadesFactorRiesgo($idFactorRiesgo){
		$this->db->from("Actividad , FactorRiesgoActividad");
		$this->db->where("FactorRiesgoActividad.FactorRiesgo_idFactorRiesgo", $idFactorRiesgo);
		$this->db->where("FactorRiesgoActividad.Actividad_idActividad = Actividad.idActividad");
		$resultado = $this->db->get();
		if($resultado->num_rows() > 0 )return $resultado->result();
        else return false;
	}

	/**
	 * Función contar_registros del modelo Actividad_model.
	 *
	 * Esta función se encarga de contar la cantidad de registros en la tabla Actividad.
	 *
	 * @access public
	 * @return integer Retorna la cantidad de resultados obtenidos.
	 */
	public function contar_registros(){
        $this->db->select('*');
        $this->db->from(self::TABLE_NAME);
        return $this->db->count_all_results();
    }

    /**
     * Función obtener_resultados del modelo Actividad_model.
	 *
	 * Esta función se encarga de obtener los factores de riesgo dado cierto limite e inicio.
	 *
	 * @access public
     * @param  integer $limit limite de la consulta.
     * @param  integer $start inicio de la consulta.
     * @return Array          Retorna un arreglo de objetos con las actividades encontradas.
     */
    public function obtener_resultados($limit=100,$start=0){
        $this->db->select('*');
        $this->db->from(self::TABLE_NAME);
        $this->db->order_by(self::TABLE_PK_NAME, 'DESC');
        $this->db->limit($limit, $start);
        $query = $this->db->get();
        return $query->result();
    }

    /**
     * Función obtener_por_id del modelo Actividad_model.
	 *
	 * Esta función se encarga de obtener una actividad dado su id.
	 *
	 * @access public
     * @param  integer $idActividad Id único de la actividad.
     * @return mixed              Retorna la actvidad si la encuentra, de lo contrario retorna null.
     */
    public function obtener_por_id($idActividad){
    	$factorRiesgo = $this->db->get_where(self::TABLE_NAME, array(self::TABLE_PK_NAME => $idActividad));
    	if($factorRiesgo->num_rows() == 1){
			return $factorRiesgo->row();
		}
		return null;
    }

    /**
     * Función eliminar_por_id del modelo Actividad_model.
	 *
	 * Esta función se encarga de eliminar una actividad dado su id.
	 * La función recibe un parámetro para indicar si sebe eliminar la imagen asociada a la actividad del servidor o si solo debe ser eliminada de la base de datos.
	 *
	 * @access public
     * @param  integer $idActividad Identificación única de la actividad.
     * @param boolean $eliminar_imagen Valor booleano para indicar si se debe intentar eliminar la imagen asociada a la actividad o solo eliminar la actividad de la base de datos.
     * @return boolean                 Retorna true si se pudo eliminar, sino retorna false.
     */
    public function eliminar_por_id($idActividad, $eliminar_imagen = true){
    	$this->db->trans_start(); // Inicio de la transacción.
    	$this->load->model('TipoHeridaActividad_model');
    	$this->load->model('FactorRiesgoActividad_model');
		$this->db->delete(TipoHeridaActividad_model::TABLE_NAME, array(self::TABLE_NAME."_".self::TABLE_PK_NAME => $idActividad));
    	$this->db->delete(FactorRiesgoActividad_model::TABLE_NAME, array(self::TABLE_NAME."_".self::TABLE_PK_NAME => $idActividad));
		$resultado = $this->db->delete(self::TABLE_NAME, array(self::TABLE_PK_NAME => $idActividad));
		$this->db->trans_complete(); // Fin de la transacción.

		if ($this->db->trans_status() === FALSE){
		    return false;
		}
		if($eliminar_imagen){
			$this->eliminar_directorio("./assets/img/actividad/".$idActividad);
		}
		return true;
	}

	/**
     * Función eliminar_directorio del modelo Actividad_model.
     *
     * Esta función se encarga de eliminar un directorio y todo su contenido del servidor.
     *
     * @access private
     * @param  string $dir Path del directorio que se desea eliminar, pj: ./assets/img
     * @return void      No retorna nada, solo elimina el directorio y sus archivos.
     */
    private function eliminar_directorio($dir) {
	    if(!$dh = @opendir($dir)) return;
	    while (false !== ($current = readdir($dh))) {
	        if($current != '.' && $current != '..') {
	            //echo 'Se ha borrado el archivo '.$dir.'/'.$current.'
';
	            if (!@unlink($dir.'/'.$current))
	                $this->eliminar_directorio($dir.'/'.$current);
	        }
	    }
	    closedir($dh);
	    //echo 'Se ha borrado el directorio '.$dir.'
';
	    @rmdir($dir);
	}

	/**
	 * Función crear_actividad del modelo Actividad_model.
	 *
	 * Esta función se encarga de insertar en la base de datos una nueva actividad.
	 *
	 * @access public
	 * @param  string $nombre      Nombre de la nueva actividad.
	 * @param  string $descripcion Descripción de la nueva actividad.
	 * @param  string $precaucion  precaucion de la nueva actividad.
	 * @param  string $imagen      Nombre de la imagen asociada a la actividad.
	 * @return integer             Retorna el id del actividad insertado.
	 */
	public function crear_actividad($nombre, $descripcion, $precaucion, $imagen){
		$datos = array(
			'nombre_actividad'      => $nombre,
			'descripcion_actividad' => $descripcion,
			'precaucion_actividad'  => $precaucion,
			'imagen_actividad'      => $imagen
		);
		$this->db->insert(self::TABLE_NAME, $datos);
		$idActividad = $this->db->insert_id();
		$datos = array(
			'imagen_actividad'      => "actividad/".$idActividad."/".$imagen
		);
		$this->db->where(self::TABLE_PK_NAME, $idActividad);
		$this->db->update(self::TABLE_NAME, $datos);
		return $idActividad;
	}

	/**
     * Función editar_actividad del modelo Actividad_model.
     *
     * Esta función se encarga de editar una actividad en la base datos, así como la eliminación de la imagen anterior, si es que ha editado la imagen.
     *
     * @access public
     * @param  integer $idActividad  	Identificación única de la actividad.
     * @param  string $nombre        	Nombre de la actividad editada.
     * @param  string $descripcion   	Descripción de la actividad editada.
     * @param  string $precaucion 		Precaucion de la actividad editada.
     * @param  string $nombre_imagen 	Nombre de la nueva imagen de la actividad, si viene vació no se editará el nombre de la imagen.
     * @return boolean                Retorna true si pudo editar el actividad, de lo contrario retorna false.
     */
    public function editar_actividad($idActividad, $nombre, $descripcion, $precaucion, $nombre_imagen){
    	if(trim($nombre_imagen) == ""){
    		$data = array(
				'nombre_actividad'      => $nombre,
				'descripcion_actividad' => $descripcion,
				'precaucion_actividad'  => $precaucion
    		);
    	}else{
    		$actividad = $this->db->get_where(self::TABLE_NAME, array(self::TABLE_PK_NAME => $idActividad));
	    	if($actividad->num_rows() == 1){
				$actividad = $actividad->row();
    			unlink("./assets/img/".$actividad->imagen_actividad);
    			$data = array(
					'nombre_actividad'      => $nombre,
					'descripcion_actividad' => $descripcion,
					'precaucion_actividad'  => $precaucion,
					'imagen_actividad'      => "actividad/".$idActividad."/".$nombre_imagen
	    		);
			}
    	}
    	$this->db->where(self::TABLE_PK_NAME, $idActividad);
		return $this->db->update(self::TABLE_NAME, $data);
    }
}// Fin de la clase Actividad_model
/* End of file Actividad_model.php */
/* Location: ./application/models/Actividad_model.php */


text:
<!DOCTYPE html>

  {% include head.html %}

    {% include header.html %}

          {{ content }}

    {% include footer.html %}
    {% include js.html %}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>CMSIS-RTOS RTX: osTimerDef_t Struct Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="cmsis.css" rel="stylesheet" type="text/css" />

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="stylsheetf" rel="stylesheet" type="text/css" />

CMSIS-RTOS RTX
    Version 4.75

CMSIS-RTOS RTX: Real-Time Operating System for Cortex-M processor-based devices

RTX

Main Page

Usage and Description

Reference

Data Structures

Data Structure Index

Data Fields

Data Fields

osTimerDef_t Struct Reference

Timer Definition structure contains timer parameters.
 More...

Data Fields

os_ptimer 	ptimer

 	start address of a timer function

void * 	timer

 	pointer to internal data

Description

Note

CAN BE CHANGED: os_timer_def is implementation specific in every CMSIS-RTOS.

Field Documentation

          os_ptimer ptimer

          void* timer

osTimerDef_t

Generated on Wed Sep 24 2014 12:17:11 for CMSIS-RTOS RTX by ARM Ltd. All rights reserved.


text:
function getOutputBySkill(skillName, currentValue){
    let outputVal = "";
    switch(skillName){
        case "acrobatics":
            outputVal += "{{Acrobatics=[[1d20+" + currentValue + "]]}} ";
            break;
        case "athletics":
            outputVal += "{{Athletics=[[1d20+" + currentValue + "]]}} ";
            break;
        case "bluff":
            outputVal += "{{Bluff=[[1d20+" + currentValue + "]]}} ";
            break;
        case "computers":
            outputVal += "{{Computers=[[1d20+" + currentValue + "]]}} ";
            break;
        case "culture":
            outputVal += "{{Culture=[[1d20+" + currentValue + "]]}} ";
            break;
        case "diplomacy":
            outputVal += "{{Diplomacy=[[1d20+" + currentValue + "]]}} ";
            break;
        case "disguise":
            outputVal += "{{Disguise=[[1d20+" + currentValue + "]]}} ";
            break;
        case "engineering":
            outputVal += "{{Engineering=[[1d20+" + currentValue + "]]}} ";
            break;
        case "intimidate":
            outputVal += "{{Intimidate=[[1d20+" + currentValue + "]]}} ";
            break;
        case "lifescience":
            outputVal += "{{Life Science=[[1d20+" + currentValue + "]]}} ";
            break;
        case "medicine":
            outputVal += "{{Medicine=[[1d20+" + currentValue + "]]}} ";
            break;
        case "mysticism":
            outputVal += "{{Mysticism=[[1d20+" + currentValue + "]]}} ";
            break;
        case "perception":
            outputVal += "{{Perception=[[1d20+" + currentValue + "]]}} ";
            break;
        case "physicalscience":
            outputVal += "{{Physical Science=[[1d20+" + currentValue + "]]}} ";
            break;
        case "piloting":
            outputVal += "{{Piloting=[[1d20+" + currentValue + "]]}} ";
            break;
        case "sensemotive":
            outputVal += "{{Sense Motive=[[1d20+" + currentValue + "]]}} ";
            break;
        case "sleightofhand":
            outputVal += "{{Sleight Of Hand=[[1d20+" + currentValue + "]]}} ";
            break;
        case "stealth":
            outputVal += "{{Stealth=[[1d20+" + currentValue + "]]}} ";
            break;
        case "survival":
            outputVal += "{{Survival=[[1d20+" + currentValue + "]]}} ";
            break;
    }
    return outputVal;
}

function getOutputBySave(saveName, currentValue){
    let outputVal = "";
    switch(saveName){
        case "fortitude":
            outputVal += "{{Fortitude=[[1d20+" + currentValue + "]]}} ";
            break;
        case "reflex":
            outputVal += "{{Reflex=[[1d20+" + currentValue + "]]}} ";
            break;
        case "will":
            outputVal += "{{Will=[[1d20+" + currentValue + "]]}} ";
            break;
    }
    return outputVal;
}

// find character sent via API call
function getChar(charName){
    let character = findObjs({
        _type: "character",
        name: charName,
    })[0];
    if(character) return character;
    switch(charName){
        case 'Player Account':
            return findObjs({_type: "character",name: "Teste McButtface",})[0];
        case 'Rogue Physicist':
            return findObjs({_type: "character",name: "Riemann 2",})[0];
        case 'Logan G.':
            return findObjs({_type: "character",name: "Delta 1",})[0];
        case 'Josh F.':
            return findObjs({_type: "character",name: "Leb",})[0];
        case 'Ryan K.':
            return findObjs({_type: "character",name: "Roze",})[0];
        default:
            return null;
    }
}

// get attributes associated with character
function getAttrs(charObj){
    return findObjs({
        _type: "attribute",
        _characterid: charObj.get("id"),
    });
}

on("chat:message", function(msg){
    if(msg.type != "api") return;

    if(msg.content.indexOf("!skillChecks ") !== -1){
        let char = getChar(msg.content.replace("!skillChecks ",""));
        let skillString = "{{name=" + char.get("name") + "'s Skills}} ";
        let attributes = getAttrs(char);

        // if attribute name starts with "skill-" and is greater than 0,
        // add it to the skillString
        _.each(attributes, function(att){
            let attName = att.get("name");
            let attCurrent = att.get("current");
            if(attName.indexOf("skill-") !== -1 && attCurrent > 0){
                let skillName = attName.replace("skill-","");
                skillString += getOutputBySkill(skillName, attCurrent);
            }
        });
        skillString += "{{Default=[[1d20]]}}"

        sendChat("character|" + char.get("id"), "/w gm &{template:default} " + skillString);
    }else if(msg.content.indexOf("!saves ") !== -1){
        let char = getChar(msg.content.replace("!saves ",""));
        let saveString = "{{name=" + char.get("name") + "'s Saves}} ";
        let attributes = getAttrs(char);

        // if attribute name starts with "save-" then add it to the saveString
        _.each(attributes, function(att){
            let attName = att.get("name");
            let attCurrent = att.get("current");
            if(attName.indexOf("save-") !== -1){
                let saveName = attName.replace("save-","");
                saveString += getOutputBySave(saveName, attCurrent);
            }
        });

        sendChat("character|" + char.get("id"), "/w gm &{template:default} " + saveString);
    }
});


text:
img.min {
    width: 180px;
    height: 140px;
    object-fit: cover; /* Do not scale the image */
    object-position: center; /* Center the image within the element */
    float:left;
}

.my-offer{
    padding:5px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    overflow: hidden;
}

.info {
    width:400px;

}

li{
    list-style: none;
}

.remove-offer-btn{
    height: 50px;
    margin-top: 40px;
}


text:
import { injectAsyncReducer } from 'store';
import { matchWhenNotAuthed } from "routes";

export default (store) => ({
  path: 'restore_password',
  getComponent:(location, cb) => {
    Promise.all([
      System.import('pages/RestorePassword'),
      System.import('pages/RestorePassword/reducer')
    ]).then(([component, reducer]) => {
      injectAsyncReducer(store, 'restorePassword', reducer.default);
      cb(null, component.default);
    });
  },
  onEnter: matchWhenNotAuthed(store)
})


text:
package com.qtfreet.devasimpleapp.ui.activity;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.qtfreet.devasimpleapp.R;
import com.qtfreet.devasimpleapp.ui.App;
import com.qtfreet.devasimpleapp.ui.adapter.FragmentAdapter;
import com.qtfreet.devasimpleapp.ui.fragment.GirlsFragment;
import com.qtfreet.devasimpleapp.ui.fragment.TextFragment;
import com.qtfreet.devasimpleapp.update.CheckUpdate;
import com.qtfreet.devasimpleapp.utils.Utils;
import com.qtfreet.devasimpleapp.wiget.ActionSheetDialog;

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

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.title_name)
    TextView toolbarTitle;
    @Bind(R.id.view_pager)
    ViewPager viewPager;
    @Bind(R.id.tab)
    TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
        App.getInstance().addActivity(MainActivity.this);
    }

    private void initData() {

        List<String> titles = new ArrayList<>();
        titles.add("Gankio");
        titles.add("Android");
        titles.add("iOS");

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new GirlsFragment());
        fragments.add(TextFragment.newFragment(TextFragment.TYPE_ANDROID));
        fragments.add(TextFragment.newFragment(TextFragment.TYPE_IOS));

        tabLayout.addTab(tabLayout.newTab().setText(titles.get(0)));
        tabLayout.addTab(tabLayout.newTab().setText(titles.get(1)));
        tabLayout.addTab(tabLayout.newTab().setText(titles.get(2)));

        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(), fragments, titles));
        tabLayout.setupWithViewPager(viewPager);
    }

    private void initView() {
        ButterKnife.bind(this);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            if (toolbarTitle != null) {
                getSupportActionBar().setDisplayShowTitleEnabled(false);
                toolbarTitle.setText(R.string.main_title);
            }
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View headerView = navigationView.getHeaderView(0);
        ImageView header = (ImageView) headerView.findViewById(R.id.header_view);
        header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ActionSheetDialog(MainActivity.this)
                        .builder()
                        .setTitle(getString(R.string.change_header))
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(false).addSheetItem(getString(R.string.take_pic), ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        Toast.makeText(MainActivity.this, "该功能并没有实现=。=", Toast.LENGTH_SHORT).show();
                    }
                }).addSheetItem(getString(R.string.take_from_pic), ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        Toast.makeText(MainActivity.this, "该功能并没有实现=。=", Toast.LENGTH_SHORT).show();
                    }
                }).show();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //捕获返回键按下的事件
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Utils.showDialog(this, "确定要退出了吗?");
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.setting) {
//            startActivity(SettingActivity.class);
            Toast.makeText(MainActivity.this, "该功能并没有实现=。=", Toast.LENGTH_SHORT).show();
        } else if (id == R.id.nav_check) {
            CheckUpdate.getInstance().startCheck(this);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}


text:
import numpy as np

import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Linear
from paddle.fluid.dygraph.base import to_variable

from test_dist_base import runtime_main, TestParallelDyGraphRunnerBase

np.random.seed(2021)
paddle.seed(1024)

batch_size = 4
batch_num = 1000

class SimpleNet(fluid.Layer):
    def __init__(self):
        super().__init__()
        self.net_a = paddle.nn.Sequential(
            paddle.nn.Linear(10, 20),
            paddle.nn.Linear(20, 20),
            paddle.nn.Linear(20, 5),
        )
        self.net_b = paddle.nn.Sequential(
            paddle.nn.Linear(10, 20),
            paddle.nn.Linear(20, 20),
            paddle.nn.Linear(20, 5),
        )
        self.net_unused = Linear(10, 20)
        self.step = 0

    def forward(self, x):
        if self.step % 2 == 0:
            return self.net_a(x)
        else:
            return self.net_b(x)

        self.step = self.step + 1

def fake_sample_reader():
    def __reader__():
        for i in range(batch_num):
            x_data = np.random.random_sample((10,)).astype('float32')
            yield x_data

    return __reader__

class TestSimpleNet(TestParallelDyGraphRunnerBase):
    def get_model(self):
        model = SimpleNet()
        train_reader = paddle.batch(
            fake_sample_reader(), batch_size=batch_size, drop_last=True
        )
        optimizer = paddle.optimizer.SGD(
            learning_rate=0.001, parameters=model.parameters()
        )
        return model, train_reader, optimizer

    def run_one_loop(self, model, optimizer, batch):
        x_data = np.array([x for x in batch])
        x_data = x_data.reshape((-1, 10))
        x = to_variable(x_data)
        out = model(x)
        loss = out.sum() / len(batch)
        return loss

if __name__ == "__main__":
    runtime_main(TestSimpleNet)


text:
"""Tests for the test tooling
"""
import pytest

from civis.tests import mocks

def test_client_mock_attributeerror():
    mock_client = mocks.create_client_mock()
    with pytest.raises(AttributeError):
        mock_client.not_an_endpoint()

def test_client_mock_bad_parameter():
    mock_client = mocks.create_client_mock()
    mock_client.tables.list(database_id=1)  # Valid parameter
    with pytest.raises(TypeError):
        mock_client.tables.list(db_id=1)  # Invalid parameter


text:
#import <objc/runtime.h>
#import "OCMockObject.h"
#import "OCPartialMockObject.h"
#import "NSMethodSignature+OCMAdditions.h"
#import "NSObject+OCMAdditions.h"
#import "OCMFunctionsPrivate.h"
#import "OCMInvocationStub.h"
#import "NSInvocation+OCMAdditions.h"

@implementation OCPartialMockObject

#pragma mark  Initialisers, description, accessors, etc.

- (id)initWithObject:(NSObject *)anObject
{
    if(anObject == nil)
        [NSException raise:NSInvalidArgumentException format:@"Object cannot be nil."];

    Class const class = [self classToSubclassForObject:anObject];
    [self assertClassIsSupported:class];
	[super initWithClass:class];
	realObject = [anObject retain];
    [self prepareObjectForInstanceMethodMocking];
	return self;
}

- (NSString *)description
{
	return [NSString stringWithFormat:@"OCPartialMockObject(%@)", NSStringFromClass(mockedClass)];
}

- (NSObject *)realObject
{
	return realObject;
}

#pragma mark  Helper methods

- (void)assertClassIsSupported:(Class)class
{
    NSString *classname = NSStringFromClass(class);
    NSString *reason = nil;
    if([classname hasPrefix:@"__NSTagged"] || [classname hasPrefix:@"NSTagged"])
        reason = [NSString stringWithFormat:@"OCMock does not support partially mocking tagged classes; got %@", classname];
    else if([classname hasPrefix:@"__NSCF"])
        reason = [NSString stringWithFormat:@"OCMock does not support partially mocking toll-free bridged classes; got %@", classname];

    if(reason != nil)
        [[NSException exceptionWithName:NSInvalidArgumentException reason:reason userInfo:nil] raise];
}

- (Class)classToSubclassForObject:(id)object
{
    /* object_getClass() gives us the actual class backing the object, whereas [object class]
     * is sometimes overridden, by KVO or CoreData, for example, to return a subclass.
     *
     * With KVO, if we replace and subclass the actual class, as returned by object_getClass(),
     * we lose notifications. So, in that case only, we return the class reported by the class
     * method.
     */

    if([object observationInfo] != NULL)
        return [object class];

    return object_getClass(object);
}

#pragma mark  Extending/overriding superclass behaviour

- (void)stopMocking
{
    if(realObject != nil)
    {
        Class partialMockClass = object_getClass(realObject);
        OCMSetAssociatedMockForObject(nil, realObject);
        object_setClass(realObject, [self mockedClass]);
        [realObject release];
        realObject = nil;
        OCMDisposeSubclass(partialMockClass);
    }
    [super stopMocking];
}

- (void)addStub:(OCMInvocationStub *)aStub
{
    [super addStub:aStub];
    if(![aStub recordedAsClassMethod])
        [self setupForwarderForSelector:[[aStub recordedInvocation] selector]];
}

- (void)addInvocation:(NSInvocation *)anInvocation
{
    // If the mock invokes a method on the real object we end up here a second time, but because
    // the mock has added the invocation already we do not want to add it again.
    if((invocationFromMock == nil) || ([anInvocation selector] != [invocationFromMock selector]))
        [super addInvocation:anInvocation];
}

- (void)handleUnRecordedInvocation:(NSInvocation *)anInvocation
{
	// In the case of an init that is called on a mock we must return the mock instance and
	// not the realObject if the underlying init returns the realObject because at the call site
	// ARC will have retained the target and the release/retain count must balance. If we return
	// the realObject, then realObject will be over released and the mock will leak. Equally if
	// we are called on the realObject we need to make sure not to return the mock.
	id targetReceivingInit = nil;
	if([anInvocation methodIsInInitFamily])
	{
		targetReceivingInit = [anInvocation target];
		[realObject retain];
	}

	invocationFromMock = anInvocation;
	[anInvocation invokeWithTarget:realObject];
    invocationFromMock = nil;

	if(targetReceivingInit)
	{
		id returnVal;
		[anInvocation getReturnValue:&returnVal];
		if(returnVal == realObject)
		{
			[anInvocation setReturnValue:&self];
			[realObject release];
			[self retain];
		}
		[targetReceivingInit release];
	}
}

#pragma mark  Subclass management

- (void)prepareObjectForInstanceMethodMocking
{
    OCMSetAssociatedMockForObject(self, realObject);

    /* dynamically create a subclass and set it as the class of the object */
    Class subclass = OCMCreateSubclass(mockedClass, realObject);
    object_setClass(realObject, subclass);

    /* point forwardInvocation: of the object to the implementation in the mock */
	Method myForwardMethod = class_getInstanceMethod([self mockObjectClass], @selector(forwardInvocationForRealObject:));
	IMP myForwardIMP = method_getImplementation(myForwardMethod);
    class_addMethod(subclass, @selector(forwardInvocation:), myForwardIMP, method_getTypeEncoding(myForwardMethod));

    /* do the same for forwardingTargetForSelector, remember existing imp with alias selector */
    Method myForwardingTargetMethod = class_getInstanceMethod([self mockObjectClass], @selector(forwardingTargetForSelectorForRealObject:));
    IMP myForwardingTargetIMP = method_getImplementation(myForwardingTargetMethod);
    IMP originalForwardingTargetIMP = [mockedClass instanceMethodForSelector:@selector(forwardingTargetForSelector:)];
    class_addMethod(subclass, @selector(forwardingTargetForSelector:), myForwardingTargetIMP, method_getTypeEncoding(myForwardingTargetMethod));
    class_addMethod(subclass, @selector(ocmock_replaced_forwardingTargetForSelector:), originalForwardingTargetIMP, method_getTypeEncoding(myForwardingTargetMethod));

    /* We also override the -class method to return the original class */
    Method myObjectClassMethod = class_getInstanceMethod([self mockObjectClass], @selector(classForRealObject));
    const char *objectClassTypes = method_getTypeEncoding(myObjectClassMethod);
    IMP myObjectClassImp = method_getImplementation(myObjectClassMethod);
    class_addMethod(subclass, @selector(class), myObjectClassImp, objectClassTypes);

    /* Adding forwarder for most instance methods to allow for verify after run */
    NSArray *methodBlackList = @[@"class", @"forwardingTargetForSelector:", @"methodSignatureForSelector:", @"forwardInvocation:",
            @"allowsWeakReference", @"retainWeakReference", @"isBlock", @"retainCount", @"retain", @"release", @"autorelease"];
    [NSObject enumerateMethodsInClass:mockedClass usingBlock:^(Class cls, SEL sel) {
        if(OCMIsAppleBaseClass(cls) || OCMIsApplePrivateMethod(cls, sel))
            return;
        if([methodBlackList containsObject:NSStringFromSelector(sel)])
            return;
        @try
        {
            [self setupForwarderForSelector:sel];
        }
        @catch(NSException *e)
        {
            // ignore for now
        }
    }];
}

- (void)setupForwarderForSelector:(SEL)sel
{
    SEL aliasSelector = OCMAliasForOriginalSelector(sel);
    if(class_getInstanceMethod(object_getClass(realObject), aliasSelector) != NULL)
        return;

    Method originalMethod = class_getInstanceMethod(mockedClass, sel);
    /* Might be NULL if the selector is forwarded to another class */
    IMP originalIMP = (originalMethod != NULL) ? method_getImplementation(originalMethod) : NULL;
    const char *types = (originalMethod != NULL) ? method_getTypeEncoding(originalMethod) : NULL;
    // TODO: check the fallback implementation is actually sufficient
    if(types == NULL)
        types = ([[mockedClass instanceMethodSignatureForSelector:sel] fullObjCTypes]);

    Class subclass = object_getClass([self realObject]);
    IMP forwarderIMP = [mockedClass instanceMethodForwarderForSelector:sel];
    class_replaceMethod(subclass, sel, forwarderIMP, types);
	class_addMethod(subclass, aliasSelector, originalIMP, types);
}

// Implementation of the -class method; return the Class that was reported with [realObject class] prior to mocking
- (Class)classForRealObject
{
    // in here "self" is a reference to the real object, not the mock
    OCPartialMockObject *mock = OCMGetAssociatedMockForObject(self);
    if(mock == nil)
        [NSException raise:NSInternalInconsistencyException format:@"No partial mock for object %p", self];
    return [mock mockedClass];
}

- (id)forwardingTargetForSelectorForRealObject:(SEL)sel
{
	// in here "self" is a reference to the real object, not the mock
    OCPartialMockObject *mock = OCMGetAssociatedMockForObject(self);
    if(mock == nil)
        [NSException raise:NSInternalInconsistencyException format:@"No partial mock for object %p", self];
    if([mock handleSelector:sel])
        return self;

    return [self ocmock_replaced_forwardingTargetForSelector:sel];
}

//  Make the compiler happy in -forwardingTargetForSelectorForRealObject: because it can't find the message…
- (id)ocmock_replaced_forwardingTargetForSelector:(SEL)sel
{
    return nil;
}

- (void)forwardInvocationForRealObject:(NSInvocation *)anInvocation
{
	// in here "self" is a reference to the real object, not the mock
    OCPartialMockObject *mock = OCMGetAssociatedMockForObject(self);
    if(mock == nil)
        [NSException raise:NSInternalInconsistencyException format:@"No partial mock for object %p", self];

    if([mock handleInvocation:anInvocation] == NO)
    {
        [anInvocation setSelector:OCMAliasForOriginalSelector([anInvocation selector])];
        [anInvocation invoke];
    }
}

#pragma mark    Verification handling

- (NSString *)descriptionForVerificationFailureWithMatcher:(OCMInvocationMatcher *)matcher quantifier:(OCMQuantifier *)quantifier invocationCount:(NSUInteger)count
{
    SEL matcherSel = [[matcher recordedInvocation] selector];
    __block BOOL stubbingMightHelp = NO;
    [NSObject enumerateMethodsInClass:mockedClass usingBlock:^(Class cls, SEL sel) {
        if(sel == matcherSel)
            stubbingMightHelp = OCMIsAppleBaseClass(cls) || OCMIsApplePrivateMethod(cls, sel);
    }];

    NSString *description = [super descriptionForVerificationFailureWithMatcher:matcher quantifier:quantifier invocationCount:count];
    if(stubbingMightHelp)
    {
        description = [description stringByAppendingFormat:@" Adding a stub for the method may resolve the issue, e.g. `OCMStub([mockObject %@]).andForwardToRealObject()`", [matcher description]];
    }
    return description;
}

@end


text:
import Instruction from './Instruction'
import Transition from '../Transition'

import RegisterArgument from '../arguments/RegisterArgument'

import { POP, IX, IY, BC, DE, HL, AF, SP, PC} from './constants'

class Pop extends Instruction {
    constructor(opcode, cycles, register) {
        super(opcode, cycles, POP, [RegisterArgument(register)])
        this.register = register
    }

    process(state) {
        return new Transition().
            withWordRegister(PC, state.registers.PC + this.size).
            withWordRegister(SP, state.registers.SP + 2).
            withWordRegister(this.register, state.getMemoryWord(state.registers.SP)).
            withCycles(this.cycles)
    }
}

export const name = POP
export const description = 'Pop/transfer value from stack to target: POP target'
export const instructions = [
    new Pop(0xdde1, 14, IX),
    new Pop(0xfde1, 14, IY)
].
    concat([BC, DE, HL, AF].map((register, i) => new Pop(0xc1 + (i << 4), 10, register)))


text:
package alien4cloud.test.utils;

import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import alien4cloud.security.model.Role;

public class SecurityTestUtils {

    public static void setTestAuthentication(Role role) {
        Authentication auth = new TestingAuthenticationToken(role.name().toLowerCase(), "", role.name());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

}


text:
require 'wavefront-sdk/support/mixins'
require_relative 'base'

module WavefrontCli
  #
  # CLI coverage for part of the v2 'usage' API. The rest is in the
  # 'ingestionpolicy' command.
  #
  class Usage < WavefrontCli::Base
    include Wavefront::Mixins

    def do_export_csv
      t_start = options[:start] ? parse_time(options[:start]) : default_start
      t_end = options[:end] ? parse_time(options[:end]) : nil
      wf.export_csv(t_start, t_end)
    end

    def default_start
      parse_time(Time.now - 60 * 60 * 24)
    end
  end
end


text:
package eu.sig.handsontraining.filetree;

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

public interface FileTreeNode {
    boolean isDirectory();

    File getFile();

    String getSource() throws IOException;

    List<FileTreeNode> getChildren();
}


text:
#include "core/error/error.inl"
#include "core/platform.h"
#include "core/thread/condition_variable.h"
#include "core/thread/mutex.h"
#include <new>

#if CROWN_PLATFORM_POSIX
	#include <pthread.h>
#elif CROWN_PLATFORM_WINDOWS
	#include <windows.h>
#endif

namespace crown
{
struct Private
{
#if CROWN_PLATFORM_POSIX
	pthread_cond_t cond;
#elif CROWN_PLATFORM_WINDOWS
	CONDITION_VARIABLE cv;
#endif
};

ConditionVariable::ConditionVariable()
{
	CE_STATIC_ASSERT(sizeof(_data) >= sizeof(*_priv));
	_priv = new (_data) Private();

#if CROWN_PLATFORM_POSIX
	int err = pthread_cond_init(&_priv->cond, NULL);
	CE_ASSERT(err == 0, "pthread_cond_init: errno = %d", err);
	CE_UNUSED(err);
#elif CROWN_PLATFORM_WINDOWS
	InitializeConditionVariable(&_priv->cv);
#endif
}

ConditionVariable::~ConditionVariable()
{
#if CROWN_PLATFORM_POSIX
	int err = pthread_cond_destroy(&_priv->cond);
	CE_ASSERT(err == 0, "pthread_cond_destroy: errno = %d", err);
	CE_UNUSED(err);
#elif CROWN_PLATFORM_WINDOWS
	// Do nothing
#endif
	_priv->~Private();
}

void ConditionVariable::wait(Mutex& mutex)
{
#if CROWN_PLATFORM_POSIX
	int err = pthread_cond_wait(&_priv->cond, (pthread_mutex_t*)mutex.native_handle());
	CE_ASSERT(err == 0, "pthread_cond_wait: errno = %d", err);
	CE_UNUSED(err);
#elif CROWN_PLATFORM_WINDOWS
	SleepConditionVariableCS(&_priv->cv, (CRITICAL_SECTION*)mutex.native_handle(), INFINITE);
#endif
}

void ConditionVariable::signal()
{
#if CROWN_PLATFORM_POSIX
	int err = pthread_cond_signal(&_priv->cond);
	CE_ASSERT(err == 0, "pthread_cond_signal: errno = %d", err);
	CE_UNUSED(err);
#elif CROWN_PLATFORM_WINDOWS
	WakeConditionVariable(&_priv->cv);
#endif
}

} // namespace crown


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="">
  <meta name="author" content="">

  <link href="../../assets/css/vendor/morris.css" rel="stylesheet">
  <link href="../../assets/css/vendor/bootstrap.css" rel="stylesheet">
  <link href="../../assets/css/vendor/font-awesome.css" rel="stylesheet">
  <link href="../../assets/css/vendor/font-awesome-ie7.css" rel="stylesheet">
  <link href="../../assets/css/vendor/codemirror.css" rel="stylesheet">
  <link href="../../assets/css/plato.css" rel="stylesheet">
  <link href="../../assets/css/plato-file.css" rel="stylesheet">

    Plato on Github

        Report Home

memory.js

Maintainability

74.14

Lines of code

102

Difficulty

39.11

Estimated Errors

0.64

Function weight

By Complexity

By SLOC

    <textarea id="file-source" class="col-md-12">'use strict'

var _ = require('./helpers')

/**
 * High level basic memory register implementation
 * based on a pool allocation strategy
 */

exports = module.exports = Memory

function Memory(basePool) {
  this.pool = {}
  if (_.isObject(basePool)) {
    this.push(basePool)
  }
}

Memory.prototype.allocate = function (address, data) {
  if (address) {
    this.pool[address] = data
  }
  return this
}

Memory.prototype.push = function (data) {
  _.extend(this.pool, _.clone(data))
}

Memory.prototype.isAllocated = function (address) {
  return this.fetch(address) !== undefined
}

Memory.prototype.free = function (address) {
  if (_.has(this.pool, address) && this.pool[address] !== undefined) {
    // set as undefined, delete operator has a performance hit on JS engines
    this.pool[address] = undefined
  }
  return this
}

Memory.prototype.fetch = function (address) {
  var path, node

  if (typeof address === 'string') {
    node = this.pool[address]
    if (node === undefined) {
      path = address.split('.')
      if (path.length > 1) {
        node = findNode(this.pool, path)
      }
    }
  }

  return node
}

Memory.prototype.size = function () {
  var size = 0

  _.forEach(this.pool, function (node) {
    if (node !== undefined) {
      size += 1
    }
  })

  return size
}

Memory.prototype.flush = function () {
  this.pool = {}
  return this
}

function findNode(obj, path) {
  var i, l, node, current

  for (i = 0, l = path.length; i < l; i += 1) {
    current = obj[path[i]]
    if (hasMetaData(current)) {
      current = current['$$body']
    }
    if (current !== undefined && isLatest(i)) {
      node = current
      break;
    }
    if (!_.isObject(current)) {
      break;
    }
    obj = current
  }

  return node

  function isLatest() {
    return i === path.length - 1
  }
}

function hasMetaData(obj) {
  return _.has(obj, '$$attributes') || _.has(obj, '$$name')
}</textarea>

.


text:
@interface KBRPCRegistration ()
@property NSMapTable *registrations;
@end

@implementation KBRPCRegistration

- (MPRequestHandler)requestHandlerForMethod:(NSString *)method {
  NSMapTable *registration = [self.registrations objectForKey:method];
  MPRequestHandler requestHandler = [registration objectForKey:@"requestHandler"];
  return requestHandler;
}

- (void)registerMethod:(NSString *)method requestHandler:(MPRequestHandler)requestHandler {
  if (!_registrations) _registrations = [NSMapTable strongToStrongObjectsMapTable];

  NSAssert(![_registrations objectForKey:method], @"Method already registered");

  NSMapTable *registration = [NSMapTable strongToStrongObjectsMapTable];
  [registration setObject:requestHandler forKey:@"requestHandler"];

  [_registrations setObject:registration forKey:method];
}

@end


text:
// Package liboneview -
package liboneview

import "strings"

// The sum of the API versions give a unique API combined version
const (
	Ver1    = 228 // OV api version (120) + ICSP api version (108)
	Ver2    = 308 // OV api version (200) + ICSP api version (108)
	Unknown = -1
)

// Driver Version
type Version int

// Supported versions
const (
	API_VER1        Version = Ver1
	API_VER2        Version = Ver2
	API_VER_UNKNOWN Version = Unknown
)

// verstringlist - String list description of supported drivers
var verstringlist = [...]string{
	"HP OneView 120,HP ICSP 108",
	"HP OneView 200,HP ICSP 108",
	"Unknown",
}

// verintlist - Integer list description of supported drivers
var verintlist = [...]int{
	Ver1,
	Ver2,
	Unknown,
}

func (o Version) EqualV(v Version) bool { return (int(o) == v.Integer()) }

// String helper for state
func (o Version) Integer() int { return int(o) }

// String helper for state
func (o Version) String() string {
	for i, ver := range verintlist {
		if ver == int(o) {
			return verstringlist[i]
		}
	}
	return verstringlist[len(verstringlist)-1]
}

// Equal helper for state
func (o Version) Equal(s string) bool { return (strings.ToUpper(s) == strings.ToUpper(o.String())) }

type verMap map[int]bool

var validVersion verMap

// init the version mapping
func init() {
	validVersion = map[int]bool{
		Ver1: true,
		Ver2: true,
	}
}

// IsVersionValid -  tests if the combination of OV and ICSP REST APIs are compatible for this driver
func IsVersionValid(ver int) bool {
	return validVersion[ver]
}

// CalculateVersion - calculate the current version
func (o Version) CalculateVersion(ovversion int, icspversion int) Version {
	var cver int
	cver = ovversion + icspversion
	for _, ver := range verintlist {
		if ver == cver {
			return Version(cver)
		}
	}
	return Version(Unknown)
}


text:
package org.ofbiz.common;

import java.util.LinkedList;
import java.util.List;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityTypeUtil;
import org.ofbiz.entity.util.EntityUtilProperties;

/**
 * Common Workers
 */
public final class CommonWorkers {

    private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());

    private CommonWorkers() {}

    public static List<GenericValue> getCountryList(Delegator delegator) {
        List<GenericValue> geoList = new LinkedList<>();
        String defaultCountry = EntityUtilProperties.getPropertyValue("general", "country.geo.id.default", delegator);
        GenericValue defaultGeo = null;
        if (UtilValidate.isNotEmpty(defaultCountry)) {
            try {
                defaultGeo = EntityQuery.use(delegator).from("Geo").where("geoId", defaultCountry).cache().queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, "Cannot lookup Geo", module);
            }
        }

        List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("geoTypeId", EntityOperator.EQUALS, "COUNTRY"));
        List<String> countriesAvailable = StringUtil.split(EntityUtilProperties.getPropertyValue("general", "countries.geo.id.available", delegator), ",");
        List<String> countriesUnAvailable = StringUtil.split(EntityUtilProperties.getPropertyValue("general", "countries.geo.id.unavailable", delegator), ",");
        if (UtilValidate.isNotEmpty(countriesAvailable)) {
            // only available countries (we don't verify the list of geoId in countries.geo.id.available)
            exprs.add(EntityCondition.makeCondition("geoId", EntityOperator.IN, countriesAvailable));
        }

        if(UtilValidate.isNotEmpty(countriesUnAvailable)){
            exprs.add(EntityCondition.makeCondition("geoId", EntityOperator.NOT_IN, countriesUnAvailable));
        }

        List<GenericValue> countriesList = new LinkedList<>();
        try {
            countriesList = EntityQuery.use(delegator).from("Geo").where(exprs).orderBy("geoName").cache(true).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot lookup Geo", module);
        }
        if (defaultGeo != null) {
            geoList.add(defaultGeo);
            boolean removeDefaultGeo = UtilValidate.isEmpty(countriesList);
            if (!removeDefaultGeo) {
                for (GenericValue country  : countriesList) {
                    if (country.get("geoId").equals(defaultGeo.get("geoId"))) {
                        removeDefaultGeo = true;
                    }
                }
            }
            if (removeDefaultGeo) {
                geoList.remove(0); // Remove default country to avoid double rows in drop-down, from 1st place to keep alphabetical order
            }
            geoList.addAll(countriesList);
        } else {
            geoList = countriesList;
        }
        return geoList;
    }

    // SCIPIO 2.1.0: Added new method to get specific countryGeoIds.
    // Convenient while working with countriesExtraPreOptions/countriesExtraPostOptions in countries.ftl
    public static List<GenericValue> getCountryList(Delegator delegator, List<String> countryGeoIds) {
        List<GenericValue> countriesList = UtilMisc.newList();
        try {
            for (String countryGeoId : countryGeoIds) {
                GenericValue country = EntityQuery.use(delegator).from("Geo").where("geoId", countryGeoId).cache(true).queryOne();
                if (UtilValidate.isNotEmpty(country) && country.getString("geoTypeId").equals("COUNTRY")) {
                    countriesList.add(country);
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot lookup Geo", module);
        }

        return countriesList;
    }

    public static List<GenericValue> getStateList(Delegator delegator) {
        List<GenericValue> geoList = new LinkedList<>();
        EntityCondition condition = EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "TERRITORY"),
                EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"));
        try {
            geoList = EntityQuery.use(delegator).from("Geo").where(condition).orderBy("geoName").cache(true).queryList();
        } catch (GenericEntityException e) {
            Debug.logError(e, "Cannot lookup State Geos: " + e.toString(), module);
        }
        return geoList;
    }

    public static List<GenericValue> getAssociatedStateList(Delegator delegator, String country) {
        return getAssociatedStateList(delegator, country, null);
    }

    /**
     * Returns a list of regional geo associations.
     */
    public static List<GenericValue> getAssociatedStateList(Delegator delegator, String country, String listOrderBy) {
        if (UtilValidate.isEmpty(country)) {
            // Load the system default country
            country = EntityUtilProperties.getPropertyValue("general", "country.geo.id.default", delegator);
        }

        if (UtilValidate.isEmpty(listOrderBy)) {
            listOrderBy = "geoId";
        }
        List<String> sortList = UtilMisc.toList(listOrderBy);

        List<GenericValue> geoList = new LinkedList<>();
        try {
            // Check if the country is a country group and get recursively the
            // states
            List<GenericValue> regionList = EntityQuery.use(delegator)
                                                       .from("GeoAssocAndGeoToWithState")
                                                       .where("geoIdFrom", country, "geoAssocTypeId", "GROUP_MEMBER", "geoTypeId", "GROUP")
                                                       .orderBy(sortList)
                                                       .cache(true)
                                                       .queryList();
            if (regionList.size() == 1) {
                for (GenericValue region : regionList) {
                    List<GenericValue> tmpState = EntityQuery.use(delegator)
                                                             .from("GeoAssocAndGeoTo")
                                                             .where("geoId", region.getString("geoIdFrom"))
                                                             .orderBy(sortList)
                                                             .cache(true)
                                                             .queryList();
                    for (GenericValue state : tmpState) {
                        geoList.addAll(getAssociatedStateList(delegator, state.getString("geoIdFrom"), listOrderBy));
                    }
                }
            }

            // get all related states
            EntityCondition stateProvinceFindCond = EntityCondition.makeCondition(
                    EntityCondition.makeCondition("geoIdFrom", country),
                    EntityCondition.makeCondition("geoAssocTypeId", "REGIONS"),
                    EntityCondition.makeCondition(EntityOperator.OR, EntityCondition.makeCondition("geoTypeId", "STATE"), EntityCondition.makeCondition("geoTypeId", "PROVINCE"), EntityCondition.makeCondition("geoTypeId", "MUNICIPALITY"),
                            EntityCondition.makeCondition("geoTypeId", "TERRITORY"), EntityCondition.makeCondition("geoTypeId", "COUNTY")));
            geoList.addAll(EntityQuery.use(delegator)
                                      .from("GeoAssocAndGeoToWithState")
                                      .where(stateProvinceFindCond)
                                      .orderBy(sortList)
                                      .cache(true)
                                      .queryList()
                          );
        } catch (GenericEntityException e){
            Debug.logError(e, "Cannot lookup Geo", module);
        }

        return geoList;
    }

    /**
     * A generic method to be used on Type enities, e.g. ProductType.  Recurse to the root level in the type hierarchy
     * and checks if the specified type childType has parentType as its parent somewhere in the hierarchy.
     *
     * @param delegator       The Delegator object.
     * @param entityName      Name of the Type entity on which check is performed.
     * @param primaryKey      Primary Key field of the Type entity.
     * @param childType       Type value for which the check is performed.
     * @param parentTypeField Field in Type entity which stores the parent type.
     * @param parentType      Value of the parent type against which check is performed.
     * @return boolean value based on the check results.
     *
     * @deprecated Moved to {@link org.ofbiz.entity.util.EntityTypeUtil#hasParentType(Delegator, String, String, String, String, String) EntityTypeUtil}
     */
    @Deprecated
    public static boolean hasParentType(Delegator delegator, String entityName, String primaryKey, String childType, String parentTypeField, String parentType) {
        return EntityTypeUtil.hasParentType(delegator, entityName, primaryKey, childType, parentTypeField, parentType);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace JSharp.Java.Ast
{
    class AutoDisposeIndentedTextWriter : System.CodeDom.Compiler.IndentedTextWriter
    {
        public AutoDisposeIndentedTextWriter(TextWriter writer)
            : base(writer)
        {
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            if (InnerWriter != null)
                InnerWriter.Dispose();
        }
    }

}


text:
define([ 'angular' ], function(angular) {
    'use strict';

    /*
     * "App"
     */
    var phonecatApp = angular.module('phoneCatApp', [ 'ngRoute', 'phonecatAnimations', 'phonecatControllers',
	    'phonecatFilters', 'phonecatServices' ]);

    phonecatApp.config([ '$routeProvider', function($routeProvider) {
	$routeProvider.when('/phones', {
	    templateUrl : 'partials/phone-list.html',
	    controller : 'PhoneListCtrl'
	}).when('/phones/:phoneId', {
	    templateUrl : 'partials/phone-detail.html',
	    controller : 'PhoneDetailCtrl'
	}).otherwise({
	    redirectTo : '/phones'
	});
    } ]);

    /*
     * "Controllers"
     */
    var phonecatControllers = angular.module('phonecatControllers', []);

    phonecatControllers.controller('PhoneListCtrl', [ '$scope', 'Phone', function($scope, Phone) {
	$scope.phones = Phone.query();
	$scope.orderProp = 'age';
    } ]);

    phonecatControllers.controller('PhoneDetailCtrl', [ '$scope', '$routeParams', 'Phone',
	    function($scope, $routeParams, Phone) {
		$scope.phone = Phone.get({
		    phoneId : $routeParams.phoneId
		}, function(phone) {
		    $scope.mainImageUrl = phone.images[0];
		});

		$scope.setImage = function(imageUrl) {
		    $scope.mainImageUrl = imageUrl;
		};
	    } ]);

    /*
     * "Filters"
     */
    angular.module('phonecatFilters', []).filter('checkmark', function() {
	return function(input) {
	    return input ? '\u2713' : '\u2718';
	};
    });

    /* Services */
    var phonecatServices = angular.module('phonecatServices', [ 'ngResource' ]);

    phonecatServices.factory('Phone', [ '$resource', function($resource) {
	return $resource('phones/:phoneId.json', {}, {
	    query : {
		method : 'GET',
		params : {
		    phoneId : 'phones'
		},
		isArray : true
	    }
	});
    } ]);

    /*
     * "Animations"
     */
    var phonecatAnimations = angular.module('phonecatAnimations', [ 'ngAnimate' ]);

    phonecatAnimations.animation('.phone', function() {

	var animateUp = function(element, className, done) {
	    if (className != 'active') {
		return;
	    }
	    element.css({
		position : 'absolute',
		top : 500,
		left : 0,
		display : 'block'
	    });

	    jQuery(element).animate({
		top : 0
	    }, done);

	    return function(cancel) {
		if (cancel) {
		    element.stop();
		}
	    };
	}

	var animateDown = function(element, className, done) {
	    if (className != 'active') {
		return;
	    }
	    element.css({
		position : 'absolute',
		left : 0,
		top : 0
	    });

	    jQuery(element).animate({
		top : -500
	    }, done);

	    return function(cancel) {
		if (cancel) {
		    element.stop();
		}
	    };
	}

	return {
	    addClass : animateUp,
	    removeClass : animateDown
	};
    });

});


text:
An unofficial CLI for modifying the Gandi email forwarders.

## Setup
* API key for the Gandi domain API
* Python (tested with 2.7.9)

## Usage
```
# To list the current forwarders for a domain (example.com)
./gandi-forwarders.py -k "MyAPIKey" -D example.com

# To update the forwarders for a domain with the forwarders in forwardings.txt
./gandi-forwarders.py -k "MyAPIKey" -D example.com -f forwardings.txt
```

It is recommended to list the current forwarders and pipe it to a file, modify the file and then update the server with the modified file.

## Options
### API key
* `-k` option or `GANDI_API_KEY` environment variable (option takes precedence)
* Required, can be obtained from [Gandi's website](https://wiki.gandi.net/en/xml-api/activate)

### Domain
* `-D` option
* Required
* The domain who's forwarders should be fetched/modified

### Input File
* `-f` option
* Optional, ommit to fetch and print the current forwardings
* The file in the specified forwarding displaying what the target forwardings are

### Dry Run
* `--dry-run` flag
* Optional, include to not make any changes to the server, only print what would happen

## Process
1. Fetch the current list of forwardings from the server
2. Fetch the new list of forwardings from the input file
3. Compare the two and work out which forwardings need to be created, updated or deleted (or can be skipped)
4. Try to make the required changes. If a forwarding can't be deleted (because other addresses are forwarding to it) or can't be created/updated (because it's destinations aren't all created), skip it
5. If some changes failed but others succeeded, try step 4 again with the remaining forwardings.
6. If all the changes are completed, finish successfully. If some changes are failing and nothing is changing, abort and finish unsuccessfully.

## File format
* Blank lines and lines starting with a `#` are ignored
* One forwarder per line
* Forwarders must be in the following format `source -> destination1, destination2...`
  - Source email address (forward from)
  - `->`
  - Comma seperated list of destination email addresses (forward to)
* If a source/destination email address is in the current domain (i.e., the value of the "domain" option), the domain can be ommitted.
  - E.g., for the `example.com` domain, `foo@` is equivalent to `foo@example.com`

## File format examples
```
# Forward foo@example.com to bar@domain.com
foo@example.com -> bar@domain.com

# Shorthand for forwarding foo@example.com to bar@example.com
foo@ -> bar@

# Forward foo@example.com to bar@example.com and foo@domain.com
foo@ -> bar@, foo@domain.com
```


text:
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const {database, username, password, host} = require('../config').database;

const sequelize = new Sequelize(database, username, password, {
  host,
  dialect: 'postgres',
  define: {
    underscored: true,
    underscoredAll: true
  }
});

fs.readdirSync(__dirname)
  .map((name) => path.join(__dirname, name))
  .filter((filename) => filename !== __filename)
  .forEach((filename) => sequelize.import(filename));

Object.keys(sequelize.models).forEach((name) => {
  const Model = sequelize.models[name];
  if (Model.associate) {
    Model.associate(sequelize.models);
  }
});

sequelize.sync();

module.exports = sequelize;


text:
package org.sakaiproject.contentreview.exception;

public class QueueException extends java.lang.Exception {

	public QueueException(String arg0) {
		super(arg0);
	}

	public QueueException() {
		super();
	}

	public QueueException(String arg0, Throwable arg1) {
		super(arg0, arg1);
	}

	public QueueException(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}
}


text:
'use strict';

var _ = require('lodash');

var EventEmitter = require('drip').EnhancedEmitter;

class Formatter extends EventEmitter {
	constructor(file, logger, flags) {
		super();

		file = file || '<input>';

		this.file = file;
		this.logger = logger || Formatter.LOGGER;

		this.flags = flags || {};

		if (_.isFunction(this.init)) {
			this.init.apply(this, arguments);
		}

		Formatter.emit('init', this);
	}

	format(contents) {
		return contents;
	}

	log(line, msg, type, props) {
		this.logger.log(line, msg, this.file, type, props);
	}
}

_.assign(Formatter, EventEmitter.prototype);

EventEmitter.call(Formatter);

Formatter.LOGGER = console;

Formatter._registered = {};

Formatter.create = function(obj) {
	if (!_.isObject(obj)) {
		throw Error('You must pass an object to Formatter.create');
	}

	var constructor = Formatter._getConstructor(obj);

	var proto = Object.create(Formatter.prototype);

	var customProto = obj.prototype;

	delete obj.prototype;

	_.assign(proto, customProto);

	proto.constructor = constructor;

	_.assign(constructor.prototype, proto);

	Formatter._verifyId(obj);
	Formatter._verifyExtensions(obj);

	_.assign(constructor, obj);

	Formatter._registered[obj.id] = constructor;

	return constructor;
};

Formatter._getConstructor = function(obj) {
	var constructor;

	if (obj.hasOwnProperty('constructor')) {
		constructor = obj.constructor;

		delete obj.constructor;
	}
	else {
		constructor = class extends Formatter {
		};
	}

	return constructor;
};

Formatter._verifyId = function(obj) {
	var id = obj.id;

	if (!id || Formatter._registered.hasOwnProperty(id)) {
		var errMsg = `The id: "${id}" is already taken`;

		if (!id) {
			errMsg = 'You must give this formatter an id with the id property';
		}

		throw Error(errMsg);
	}
};

Formatter._verifyExtensions = function(obj) {
	var includes = obj.includes;

	if (!_.isRegExp(includes)) {
		throw Error('The includes property must be a RegExp Object');
	}
};

module.exports = Formatter;


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.onsemi.matrix.android" >

    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <permission android:name="com.onsemi.matrix.android.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.onsemi.matrix.android.permission.C2D_MESSAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name="com.onsemi.matrix.android.ui.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.onsemi.matrix.android.ui.SettingsActivity"
            android:label="@string/title_settings" />

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.onsemi.matrix.android" />
            </intent-filter>
        </receiver>
        <service
            android:name="com.onsemi.matrix.android.pushnotification.PNGcmListenerService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:name="com.onsemi.matrix.android.pushnotification.PNInstanceIDListenerService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.android.gms.iid.InstanceID"/>
            </intent-filter>
        </service>
        <service
            android:name="com.onsemi.matrix.android.pushnotification.RegistrationIntentService"
            android:exported="false">
        </service>
    </application>
</manifest>


text:
class BreakablePot : public BaseUnit {
public:
	BreakablePot();
	BreakablePot(Object* object_);
	~BreakablePot();

	// @Override
	virtual void HandleMessage(MessageChunk messageChunk);

	//[[PROPERTY]]//
	inline void SetDeathEffect(std::string prefabName);

	//[[PROPERTY]]//
	void SetHasPotLoot();

	//[[PROPERTY]]//
	void AddLinkage(std::string dirStr);
	void AddLinkage(unsigned char dir);

	virtual bool CanBeKilledBy(ObjectIdType id, glm::vec3 source);

	static inline ComponentIdType GetTypeId()  { return BaseUnit::GetTypeId(); }

protected:
	virtual void start();
	virtual void end();
	virtual void update();

	// @Override
	virtual void Kill();

private:
	void init();
	void destroy();

	void generateDeathEffect();
	void activateDeathEffect();

	void tryLoot();

	void chainReaction();
	void checkChainAtCell(int x, int z, int elevation);

	std::string deathEffect;
	ObjectIdType deathEffectObjId;

	ObjectIdType potLootId;
	unsigned char linkages;
};

void BreakablePot::SetDeathEffect(std::string prefabName)  {
	this->deathEffect = prefabName;
	this->generateDeathEffect();
}

#endif // BREAKABLEPOT_H


text:
<?php

include "vimeo/vimeo.php";
include "VimeoApi.php";

$oVimeoApi = new VimeoApi();

$oVideoInfo = $oVimeoApi->getInfoByVideoId($_GET['id']);
echo json_encode($oVideoInfo->video);


text:
package net.sf.sitemonitoring.entity;

import java.io.Serializable;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Entity
@Table(name = "monit_page")
public class Page implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue
	private int id;

	private String name;

	@OneToMany(mappedBy = "page", orphanRemoval = true)
	private List<Check> checks;

}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Ber. naturw. Augsburg 29: 289 (1887)

#### Original name
Clavaria dissipabilis Britzelm., 1887

### Remarks
null


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.09.04 at 12:32:21 오후 KST
//

package com.athena.chameleon.engine.entity.xml.ejbjar.jeus.v5_0;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for propertyType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="propertyType">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="key" type="{http://www.w3.org/2001/XMLSchema}token"/>
 *         <element name="value" type="{http://www.w3.org/2001/XMLSchema}token"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "propertyType", propOrder = {
    "key",
    "value"
})
public class PropertyType {

    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "token")
    protected String key;
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "token")
    protected String value;

    /**
     * Gets the value of the key property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the value of the key property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setKey(String value) {
        this.key = value;
    }

    /**
     * Gets the value of the value property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getValue() {
        return value;
    }

    /**
     * Sets the value of the value property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setValue(String value) {
        this.value = value;
    }

}


text:
using System.Globalization;
using System.Windows.Media;

namespace WpfMath.Colors
{
    internal class HtmlColorParser : SingleComponentColorParser
    {
        protected override Color? ParseSingleComponent(string component)
        {
            var isRgb = component.Length == 6;
            var isRgba = component.Length == 8;
            if (!isRgb && !isRgba)
                return null;

            if (!int.TryParse(component, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var colorCode))
                return null;

            if (isRgb)
            {
                var r = (byte) ((colorCode & 0xFF0000) >> 16);
                var g = (byte) ((colorCode & 0xFF00) >> 8);
                var b = (byte) (colorCode & 0xFF);
                return Color.FromRgb(r, g, b);
            }
            else
            {
                var r = (byte) ((colorCode & 0xFF0000) >> 24);
                var g = (byte) ((colorCode & 0xFF00) >> 16);
                var b = (byte) ((colorCode & 0xFF) >> 8);
                var a = (byte) (colorCode & 0xFF);
                return Color.FromArgb(a, r, g, b);
            }
        }
    }
}


text:
import { connect } from 'react-redux';
import { doGetSync, selectGetSyncIsPending, selectSyncApplyPasswordError } from 'lbryinc';
import { selectUserEmail } from 'redux/selectors/user';
import { doSetClientSetting } from 'redux/actions/settings';
import { doSignOut, doHandleSyncComplete } from 'redux/actions/app';
import SyncPassword from './view';

const select = state => ({
  getSyncIsPending: selectGetSyncIsPending(state),
  email: selectUserEmail(state),
  passwordError: selectSyncApplyPasswordError(state),
});

const perform = dispatch => ({
  getSync: (password, cb) => dispatch(doGetSync(password, cb)),
  setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
  handleSyncComplete: (error, hasDataChanged) => dispatch(doHandleSyncComplete(error, hasDataChanged)),
  signOut: () => dispatch(doSignOut()),
});

export default connect(select, perform)(SyncPassword);


text:
<?php

class Google_Service_Gmail_FilterCriteria extends Google_Model
{
  public $excludeChats;
  public $from;
  public $hasAttachment;
  public $negatedQuery;
  public $query;
  public $size;
  public $sizeComparison;
  public $subject;
  public $to;

  public function setExcludeChats($excludeChats)
  {
    $this->excludeChats = $excludeChats;
  }
  public function getExcludeChats()
  {
    return $this->excludeChats;
  }
  public function setFrom($from)
  {
    $this->from = $from;
  }
  public function getFrom()
  {
    return $this->from;
  }
  public function setHasAttachment($hasAttachment)
  {
    $this->hasAttachment = $hasAttachment;
  }
  public function getHasAttachment()
  {
    return $this->hasAttachment;
  }
  public function setNegatedQuery($negatedQuery)
  {
    $this->negatedQuery = $negatedQuery;
  }
  public function getNegatedQuery()
  {
    return $this->negatedQuery;
  }
  public function setQuery($query)
  {
    $this->query = $query;
  }
  public function getQuery()
  {
    return $this->query;
  }
  public function setSize($size)
  {
    $this->size = $size;
  }
  public function getSize()
  {
    return $this->size;
  }
  public function setSizeComparison($sizeComparison)
  {
    $this->sizeComparison = $sizeComparison;
  }
  public function getSizeComparison()
  {
    return $this->sizeComparison;
  }
  public function setSubject($subject)
  {
    $this->subject = $subject;
  }
  public function getSubject()
  {
    return $this->subject;
  }
  public function setTo($to)
  {
    $this->to = $to;
  }
  public function getTo()
  {
    return $this->to;
  }
}


text:
package com.navercorp.pinpoint.metric.web.util.metric;

import com.navercorp.pinpoint.metric.web.model.chart.SystemMetricPoint;
import com.navercorp.pinpoint.metric.web.util.TimeWindow;

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

/**
 * @author minwoo.jung
 */
public class TimeSeriesBuilder<T extends Number> {

    private final TimeWindow timeWindow;
    private final UncollectedDataCreator<T> uncollectedDataCreator;

    public TimeSeriesBuilder(TimeWindow timeWindow, UncollectedDataCreator<T> uncollectedDataCreator) {
        this.timeWindow = Objects.requireNonNull(timeWindow, "timeWindow");
        this.uncollectedDataCreator = Objects.requireNonNull(uncollectedDataCreator, "uncollectedDataCreator");
    }

    public List<SystemMetricPoint<T>> build(List<SystemMetricPoint<T>> systemMetricDataList) {
        List<SystemMetricPoint<T>> filledSystemMetricPointList = createInitialPoints();

        for (SystemMetricPoint<T> systemMetricPoint : systemMetricDataList) {
            int timeslotIndex = this.timeWindow.getWindowIndex(systemMetricPoint.getXVal());
            if (timeslotIndex < 0 || timeslotIndex >= timeWindow.getWindowRangeCount()) {
                continue;
            }
            filledSystemMetricPointList.set(timeslotIndex, systemMetricPoint);
        }

        return filledSystemMetricPointList;
    }

    private List<SystemMetricPoint<T>> createInitialPoints() {
        int numTimeslots = (int) this.timeWindow.getWindowRangeCount();
        List<SystemMetricPoint<T>> pointList = new ArrayList<>(numTimeslots);

        for (long timestamp : this.timeWindow) {
            pointList.add(uncollectedDataCreator.createUnCollectedPoint(timestamp));
        }

        return pointList;
    }
}


text:
> Persist report rendering outputs for later access

## Basics
Everytime you call jsreport API to render report, you will get back stream with report content. This is usefull when you want to display report directly to the user or you want to store the result in your data storage for later use. But sometimes you just don't want the report in the time of generation and you don't want to store it on your own. In this case you can use `Reports` extension and let the jsreport store the report for you.

The reports extension uses [blob storage](/learn/blob-storages) abstraction for reports blobs persistence. This by default stores reports to the file system. Check the documentation if you want to store reports to a different destination.

## API

Reports extension is not used by default for all rendering requests and you need to specify it for every request separately.

To use `reports` extension you need extend rendering request in a following way:

> `POST:` https://jsreport-host/api/report
> `BODY:`
>```js
   {
      "template": { "name" : "My template" },
      "data" : { ... },
      "options": {
	      "reports": { "save": true }
      }
   }
>```

This will create a `Report` entity you can use in jsreport studio as well as in OData API. Additionally it will add custom header `Permanent-Link` to the response which you can later use to actually download the report content.

The stored report entity name is by default inherited from the template name. However, you can customize it by passing`{ "options": { "reportName": "yourCustomName" }` in the request body.

The name of the stored file/blob is by default inherited from the entity unique _id. This can be customized using `{ "options": { "reports": { "save": true, "blobName": "myfilename" } }`

## Async
Sending rendering request with `options.reports.save = true` will instruct the extension to save the report and add `Permanent-Link` header to the response, but the rendering is still synchronous and you receive response back after the process is finished. If you want to start the rendering process  asynchronously and receive the responds immediately you should set `options.reports.async = true`.

> `POST:` https://jsreport-host/api/report
> `BODY:`
>```js
   {
      "template": { "name" : "My template" },
      "data" : { ... },
      "options": {
	      "reports": { "async": true }
      }
   }
>```

In this case you receive response with `Location` header containing url to the rendering status page. It will be something like `http://jsreport-host/reports/id/status`. You can then ping the status page to check if the rendering is done. In that case the response status will be `201` and the location header will contain address to the stored report.

## Public reports
The stored reports are protected by [authentication](/learn/authentication) as any other entity by default. However, you can expose the report to the public by adding `options.reports.public=true` to the rendering request.

> `POST:` https://jsreport-host/api/report
> `BODY:`
>```js
   {
      "template": { "name" : "My template" },
      "data" : { ... },
      "options": {
	      "reports": {  "save": true,  "public": true  }
      }
   }
>```

In this case the returned `Permanent-Link` will be public url bypassing the authentication.

## Cleanup
The reports stored from async calls are forever persisted by default. You can change this and enable automatic old reports clean up. This can be done through config.
```json
{
  "extensions": {
    "reports": {
      // how often the cleanup runs
      "cleanInterval": "5m",
      // how much old reports should be deleted
      "cleanThreshold": "1d",
      // how many deletes are processed in parallel (this avoids putting too much pressure on the database), defaults to 10
      "cleanParallelLimit": 10
    }
  }
}
```
Be aware the auto cleanup logic removes also the reports produced through scheduling extension.

## OData

You can use standard OData API to manage and query report entities. For example you can query all reports using:
> `GET` http://jsreport-host/odata/reports


text:
package org.deepjava.ssa.instruction;

import org.deepjava.host.StdStreams;
import org.deepjava.ssa.SSAInstructionMnemonics;
import org.deepjava.ssa.SSAValue;

public abstract class SSAInstruction implements SSAInstructionMnemonics {
	protected SSAValue[] operands;
	public SSAValue result;
	public int ssaOpcode;
	public int bca = -1; // used for debugging, marks bca of associated bytecode instruction
	public int machineCodeOffset = -1; // used for debugging, e.g. step into and used for fixups of catch clauses
	public SSAInstruction freePhi; // used for freeing registers of phi-functions in loops

	public abstract void setOperands(SSAValue[] operands);
	public abstract SSAValue[] getOperands();

	public void print(int level) {
		StdStreams.vrbPrintIndent(level);
		StdStreams.vrb.println(toString());
	}

}


text:
//
//  UGConnection.h
//  UGAPIApp
//
//  Created by Tim Burks on 3/30/13.
//
//
#import <Foundation/Foundation.h>

@class UGHTTPResult;

@interface UGConnection : NSObject

// These three properties tie a  UGConnection to a specific application instance
@property (nonatomic, strong) NSString *server;
@property (nonatomic, strong) NSString *organization;
@property (nonatomic, strong) NSString *application;

// As a convenience, a sharedConnection object is available,
// but any number of UGConnection objects may be created and separately configured.
+ (UGConnection *) sharedConnection;

// Query helper: construct query dictionary from arguments
- (NSMutableDictionary *) queryWithString:(NSString *) queryString
                                    limit:(int) limit
                                startUUID:(NSString *) startUUID
                                   cursor:(NSString *) cursor
                                 reversed:(BOOL) reversed;

// Authentication helper: call this method with the result of a getAccessToken request.
- (BOOL) authenticateWithResult:(UGHTTPResult *) result;

// Authentication helper: use this to confirm that a connection has a usable access token.
- (BOOL) isAuthenticated;

//
// Usergrid API methods
//
// The following calls return NSMutableURLRequest objects that can be used to make Usergrid API calls.
// We recommend (but do not require) that they be made with instances of the UGHTTPClient class.
//
// The goal here is to directly expose the complete Usergrid API.
//
// This follows http://apigee.com/docs/usergrid/content/app-services-resources
//

// Access tokens http://apigee.com/docs/usergrid/content/accesstoken

- (NSMutableURLRequest *) getAccessTokenForAdminWithUsername:(NSString *) username
                                                    password:(NSString *) password;

- (NSMutableURLRequest *) getAccessTokenForOrganizationWithClientID:(NSString *) clientID
                                                       clientSecret:(NSString *) clientSecret;

- (NSMutableURLRequest *) getAccessTokenForApplicationWithUsername:(NSString *) username
                                                          password:(NSString *) password;

- (NSMutableURLRequest *) getAccessTokenForApplicationWithClientID:(NSString *) clientID
                                                      clientSecret:(NSString *) clientSecret;

// Admin users http://apigee.com/docs/usergrid/content/admin-user

- (NSMutableURLRequest *) createAdminUserWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) updateAdminUser:(NSString *) adminUserIdentifier
                               withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) getAdminUser:(NSString *) adminUserIdentifier;

- (NSMutableURLRequest *) setPasswordForAdminUser:(NSString *) adminUserIdentifier
                                          toValue:(NSString *) password;

- (NSMutableURLRequest *) initiatePasswordResetForAdminUser;

- (NSMutableURLRequest *) completePasswordResetForAdminUserWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) activateAdminUser:(NSString *) adminUserIdentifier
                                  withToken:(NSString *) token
                   sendingConfirmationEmail:(BOOL) sendingConfirmationEmail;

- (NSMutableURLRequest *) reactivateAdminUser:(NSString *) adminUserIdentifier;

- (NSMutableURLRequest *) getActivityFeedForAdminUser:(NSString *) adminUserIdentifier;

// Client authorization http://apigee.com/docs/usergrid/content/client-authorization

- (NSMutableURLRequest *) authorizeClient:(NSString *) clientIdentifier withResponseType:(NSString *) responseType;

// Organizations and Applications http://apigee.com/docs/usergrid/content/organization

- (NSMutableURLRequest *) createOrganizationWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) getOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) activateOrganization:(NSString *) organizationIdentifier
                                     withToken:(NSString *) token
                      sendingConfirmationEmail:(BOOL) sendingConfirmationEmail;

- (NSMutableURLRequest *) reactivateOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) generateClientCredentialsForOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getClientCredentialsForOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getActivityFeedForOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) createApplicationInOrganization:(NSString *) organizationIdentifier
                                               withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deleteApplication:(NSString *) applicationIdentifier
                             inOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) generateClientCredentialsForApplication:(NSString *) applicationIdentifier
                                                   inOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getClientCredentialsForApplication:(NSString *) applicationIdentifier
                                              inOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getApplicationsInOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) addAdminUser:(NSString *) adminUserIdentifier
                        toOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getAdminUsersInOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) removeAdminUser:(NSString *) adminUserIdentifier
                         fromOrganization:(NSString *) organizationIdentifier;

- (NSMutableURLRequest *) getApplication:(NSString *) applicationIdentifier
                          inOrganization:(NSString *) organizationIdentifier;

// Activity http://apigee.com/docs/usergrid/content/activity

- (NSMutableURLRequest *) createActivityForUser:(NSString *) userIdentifier
                                     withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) createActivityForGroup:(NSString *) groupIdentifier
                                      withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) createActivityForFollowersOfUser:(NSString *) userIdentifier
                                                   inGroup:(NSString *) groupIdentifier
                                                withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) getActivitiesForUser:(NSString *) userIdentifier;

- (NSMutableURLRequest *) getActivitiesForGroup:(NSString *) groupIdentifier;

- (NSMutableURLRequest *) getActivityFeedForUser:(NSString *) userIdentifier;

- (NSMutableURLRequest *) getActivityFeedForGroup:(NSString *) groupIdentifier;

// Assets

- (NSMutableURLRequest *) getDataForAsset:(NSString *) assetIdentifier;

- (NSMutableURLRequest *) postData:(NSData *) data
                          forAsset:(NSString *) assetIdentifier;

// Collections (aka General-purpose endpoints) http://apigee.com/docs/usergrid/content/general-purpose-endpoints

- (NSMutableURLRequest *) createEntityInCollection:(NSString *) collection
                                        withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) getEntity:(NSString *) entityIdentifier
                       inCollection:(NSString *) collection;

- (NSMutableURLRequest *) updateEntity:(NSString *) entityIdentifier
                          inCollection:(NSString *) collection
                            withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deleteEntity:(NSString *) entityIdentifier
                          inCollection:(NSString *) collection;

- (NSMutableURLRequest *) getEntitiesInCollection:(NSString *) collection
                                            limit:(int) limit;

- (NSMutableURLRequest *) getEntitiesInCollection:(NSString *) collection
                                       usingQuery:(NSDictionary *) query;

- (NSMutableURLRequest *) updateEntitiesInCollection:(NSString *) collection
                                          usingQuery:(NSDictionary *) query
                                          withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deleteEntitiesInCollection:(NSString *) collection;

- (NSMutableURLRequest *) deleteEntitiesInCollection:(NSString *) collection
                                          usingQuery:(NSDictionary *) query;

// Devices http://apigee.com/docs/usergrid/content/device

// there are no device-specific methods

// Events and Counters http://apigee.com/docs/usergrid/content/events-and-counters

- (NSMutableURLRequest *) createEventWithValues:(NSDictionary *) values;

// Groups http://apigee.com/docs/usergrid/content/group

- (NSMutableURLRequest *) createGroupWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) addUser:(NSString *) userIdentifier
                          toGroup:(NSString *) groupIdentifier;

- (NSMutableURLRequest *) getGroup:(NSString *) groupIdentifier;

- (NSMutableURLRequest *) updateGroup:(NSString *) groupIdentifier
                           withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deleteUser:(NSString *) userIdentifier
                           fromGroup:(NSString *) groupIdentifier;

- (NSMutableURLRequest *) deleteGroup:(NSString *) groupIdentifier;

- (NSMutableURLRequest *) getUsersInGroup:(NSString *) groupIdentifier;

// Roles http://apigee.com/docs/usergrid/content/role

- (NSMutableURLRequest *) createRoleWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) getRoles;

- (NSMutableURLRequest *) deleteRole:(NSString *) roleName;

- (NSMutableURLRequest *) getPermissionsForRole:(NSString *) roleName;

- (NSMutableURLRequest *) addPermissionsToRole:(NSString *) roleName
                                    withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deletePermissionsFromRole:(NSString *) roleName
                                       usingPattern:(NSString *) pattern;

- (NSMutableURLRequest *) addUser:(NSString *)userIdentifier
                           toRole:(NSString *)roleName;

- (NSMutableURLRequest *) getUsersInRole:(NSString *) roleName;

- (NSMutableURLRequest *) deleteUser:(NSString *) userIdentifier
                            fromRole:(NSString *) roleName;

// Users http://apigee.com/docs/usergrid/content/user

- (NSMutableURLRequest *) createUserWithValues:(NSDictionary *) values;

- (NSMutableURLRequest *) setPasswordForUser:(NSString *) username
                                  toPassword:(NSString *) newPassword
                                fromPassword:(NSString *) oldPassword;

- (NSMutableURLRequest *) getUser:(NSString *) username;

- (NSMutableURLRequest *) updateUser:(NSString *) username
                          withValues:(NSDictionary *) values;

- (NSMutableURLRequest *) deleteUser:(NSString *) username;

- (NSMutableURLRequest *) getUsersUsingQuery:(NSDictionary *) query;

- (NSMutableURLRequest *) connectEntity:(NSString *) entity1
                           inCollection:(NSString *) collection
                               toEntity:(NSString *) entity2
                    throughRelationship:(NSString *) relationship;

- (NSMutableURLRequest *) disconnectEntity:(NSString *) entity1
                              inCollection:(NSString *) collection
                                fromEntity:(NSString *) entity2
                       throughRelationship:(NSString *) relationship;

- (NSMutableURLRequest *) getConnectionsToEntity:(NSString *) entity
                                    inCollection:(NSString *) collection
                             throughRelationship:(NSString *) relationship
                                      usingQuery:(NSDictionary *) query;

@end


text:
package org.apache.hadoop.hbase.regionserver.idx.support.arrays;

import org.apache.hadoop.hbase.io.HeapSize;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ClassSize;

/**
 * An interface for an array list, typically used as a key store.
 *
 * @param <T> the element type
 */
public interface List<T> extends Iterable<T>, BinarySearch.Searchable<T>,
        HeapSize {

    long FIXED_OVERHEAD =
            ClassSize.align(ClassSize.ARRAY + Bytes.SIZEOF_INT + ClassSize.OBJECT);

    /**
     * Adds the element to the end of the list.
     *
     * @param e the new element
     */
    void add(byte[] e);

    /**
     * Sets the specified index to the nominated value.
     *
     * @param index    the list index
     * @param newValue the value
     */
    void set(int index, byte[] newValue);

    /**
     * Inserts at the specified index to the list.
     *
     * @param index    the index to insert
     * @param newValue the value to insert
     */
    void insert(int index, byte[] newValue);

    /**
     * Checks if the list is empty.
     *
     * @return true if the list is empty
     */
    boolean isEmpty();

    /**
     * Returns the current number of elements in this list.
     *
     * @return the number of elements.
     */
    int size();

}


text:
'use strict';

angular.module('users').controller('TeacherdashboardController', ['$scope', '$location', 'Authentication',
	function($scope, $location, Authentication) {
        $scope.user = Authentication.user;

        // If user is not signed in then redirect back home
        if (!$scope.user) $location.path('/');

        $scope.isEditing = 'Off';

        $scope.assignments = [
            {
                isComplete: true,
                isVisible: true,
                course: 'BUS 443',
                title: 'Homework Assignment #3',
                dueDate: '2/18/2015'
            },
            {
                isComplete: false,
                isVisible: true,
                course: 'BUS 440',
                title: 'Chocolate Heaven Case Study',
                dueDate: '2/29/2015'
            },
            {
                isComplete: false,
                isVisible: false,
                course: 'BUS 440',
                title: 'Homework Assignment #4',
                dueDate: '2/27/2015'
            }
        ];

        $scope.addAssignment = function () {
            $scope.assignments.push({isComplete: false, isVisible: true, title: '', dueDate: 'dd/mm/yyyy'});
        };

        $scope.saveAssignment = function () {
            $scope.assignments.$save($scope.assignments).then(function (data) {
            });
        };
    }
]);


text:
package org.abs.annotation;

public enum KeyType {
	UUID, SEQUENCE,MAX,NULL
}