text:
layout: post
title:  Matplotlib quick reference
categories: [Data Visualization]
excerpt: Matplotlib quick reference
---
Create multiple plots within a fig
```py
fig, axes = plt.subplots(no_of_rows, no_of_cols)
```
Flatten the axes array to ease iteration
```py
flat_axes = np.array(axes).ravel()
```
Set x & y labels
```py
axis.set(xlabel="date", ylabel="price")
```
Position legend
```py
axis.legend(bbox_to_anchor=(1.01, 1), borderaxespad=0, loc="upper right")
```
Draw multiple graph types on the same subplot
```py
ax2 = axis.twinx()
```
Fix fig size (clipping and/or overflow)
```py
plt.tight_layout()
```
Save the figure
```py
fig.savefig("plot.png", dpi=100)
```
Close the plot to release memory
>> Especially useful when many plots are needed.
```py
plt.close(fig)
```


text:
<configuration>

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"/>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="INFO">
        <appender-ref ref="console" />
    </root>

</configuration>

redpajama_set_name: RedPajamaGithub


text:
namespace ParentLoadSoftDelete.DataAccess.ERLevel
{
    public partial class E07_Country_ChildDto
    {
    }
}


text:
  Loeuilley est
       un village
       géographiquement positionné dans le département de Haute-Saône en Franche-Comté. Elle totalisait 117 habitants en 2008.

À proximité de Loeuilley sont positionnées géographiquement les communes de
Champagne-sur-Vingeanne située à 1 km, 242 habitants,
Blagny-sur-Vingeanne localisée à 3 km, 126 habitants,
Oisilly à 4 km, 131 habitants,
Fontenelle située à 4 km, 127 habitants,
Attricourt située à 2 km, 36 habitants,
Licey-sur-Vingeanne située à 2 km, 94 habitants,
 entre autres. De plus, Loeuilley est située à seulement 26 km de Quetigny.

Si vous pensez emmenager à Loeuilley, vous pourrez facilement trouver une maison à vendre.

Le parc d'habitations, à Loeuilley, était réparti en 2011 en cinq appartements et 47 maisons soit
 un marché plutôt équilibré.


text:
title: Toxidromes by Vital Signs
authors:
    - Michelle Lin, MD
created: 2010/11/19
updates: null
categories:
    - Toxicology
---

# Toxidromes by Vital Signs

## Bradycardia

**PACED**

- **P**ropranolol/ beta-blockers, **P**oppies (opiates), **P**ropoxyphene,**P**hysostigmine
- **A**nticholinesterases, **A**ntiarrhythmics
- **C**lonidine, **C**alcium channel blockers
- **E**thanol or other alcohols
- **D**igoxin, digitalis

## Tachycardia

**FAST**

- **F**ree base or other cocaine forms, **F**reon
- **A**nticholinergics, **A**ntihistamine, **A**ntipsychotic, **A**mphetamines, **A**lcohol withdrawal
- **S**ympathomimentics, **S**olvent use, **S**trychnine
- **T**heophylline, **T**CAs, **T**hyroid hormones

## Hypothermia

**COOLS**

- **C**arbon monoxide
- **O**pioids
- **O**ral hypoglycemics and insulin
- **L**iquor (alcohol)
- **S**edative-hypnotics

## Hyperthermia

**NASA**

- **N**euroleptic malignant syndrome, **N**icotine
- **A**ntihistamine, **A**lcohol withdrawal
- **S**alicylates, **S**ympathomimetics, **S**erotonin syndrome
- **A**nticholinergics, **A**ntidepressants, **A**ntipsychotics

## Hypotension

**CRASH**

- **C**lonidine, **C**alcium channel blockers
- **R**odenticides (has arsenic, cyanide)
- **A**ntidepressants, **A**minophylline, **A**ntihypertensives
- **S**edative-hypnotics
- **H**eroin or other opiate

## Hypertension

**CT SCAN**

- **C**ocaine
- **T**hyroid supplements
- **S**ympathomimetics
- **C**affeine
- **A**nticholinergics, **A**mphetamines
- **N**icotine

## Tachypnea

**PANT**

- **P**CP, **P**araquat, **P**neumonitis (chemical), **P**hosgene
- **A**SA and other salicylates
- **N**oncardiogenic pulmonary edema, **N**erve agents
- **T**oxin-mediated metabolic acidosis

## Bradypnea

**SLOW**

- **S**edative-hypnotics
- **L**iquor (alcohols)
- **O**pioids
- **W**eed (marijuana)

## References

- [Erickson TB, Thompson TM, Lu JJ.The approach to the patient with an unknown overdose. Emerg Med Clin North Am. 2007 May;25(2):249-81](http://www.ncbi.nlm.nih.gov/pubmed/?term=17482020)


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

import com.lades.sihv.controller.person.PessoaCheckExistLogin;
import com.lades.sihv.controller.person.PessoaCheckExistCpfCnpj;
import com.lades.sihv.controller.person.PessoaCheckCPF;
import com.lades.sihv.controller.person.PessoaCheckCNPJ;
import com.lades.sihv.controller.person.PessoaPadraoCaracter;
//import com.lades.sihv.controller.pessoa.PessoaMetodosDeCadastro;
//import com.lades.sihv.model.Fisica;
//import com.lades.sihv.model.Juridica;
//import com.lades.sihv.model.Pessoa;
//import com.lades.sihv.model.Telefone;
//import com.lades.sihv.model.User;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

/**
 *
 * @author thiberius
 */
@ManagedBean(name = "MBpessoa")
@ViewScoped
public class MBpessoa extends AbstractBean {

//    private Pessoa pessoa;
//    private Fisica fisica;
//    private Juridica juridica;
//    private final List<Telefone> telefoneList = new ArrayList<>();
//    private boolean viewTelefone2;
//    private boolean viewTelefone3;
//    private User user;
//    private boolean mudancaCpfCnpj = true;
//    private boolean cpfOpcional = true;
//    private boolean rgOpcional = true;
//    private String numCRMV1 = "";
//    private String numCRMV2 = "";
//    /*Os dois atributos serão utilizado para
//    a concatenação do CRMV do medico veterinário*/
//
// /*Os método e variáveis abaixo são utilizados para controlar a visibilidade
//    de campos para cadastro de clientes e usuários do sistema*/
//    private String tipoPessoa = "cliente";
//
//    public boolean getTipoPessoa() {
//        boolean var = true;
//        switch (tipoPessoa) {
//            case "cliente":
//                var = true;
//                break;
//            case "user":
//                var = false;
//                break;
//        }
//        return var;
//    }
//
//    public void prepararAdicionarUSER() {
//        tipoPessoa = "user";
//    }
//
//    public void cadastrarUserMedico() {
//        getUser().setUserTipo("MEDICO");
//        checkDadosUserPessoa("Residente");
//    }
//
//    public void cadastrarUserTecnico() {
//        getUser().setUserTipo("TÉCNICO");
//        checkDadosUserPessoa("Funcionário/técnico");
//    }
//
//    public void cadastrarUserAluno() {
//        getUser().setUserTipo("ALUNO");
//        checkDadosUserPessoa("Recepcionista");
//    }
//
//    private void checkDadosUserPessoa(String mensageTIPO) {
//        getUser().setUserNick(getUser().getUserNick().toLowerCase());
//        boolean checkCPF, existCpfCnpj, existLogin;
//        checkCPF = ObjPessoaCheckCPF().checkCPF(pessoa);
//        existCpfCnpj = ObjCheckExistCpfCnpj().checkExistCpfCnpj(pessoa, mudancaCpfCnpj);
//        existLogin = ObjCheckExistLogin().checkExistingLogin(pessoa, user);
//        if (checkCPF && existCpfCnpj && existLogin) {
//            ObjPessoaPadraoCaracter().padraoCaracter(pessoa);
//            cadastrarUser(mensageTIPO);
//        }
//    }
//
//    private void cadastrarUser(String mensageTIPO) {
//        try {
//            PessoaMetodosDeCadastro obj = ObjPessoaMetodosDeCadastro();
//            obj.cadastrarPessoa(pessoa);
//            obj.cadastrarPessoaFisica(pessoa, fisica);
//            obj.cadastrarTelefones(pessoa, telefoneList);
//            obj.cadastrarUser(pessoa, user, numCRMV1, numCRMV2);
//            getObjMessage().info("Cadastro efetuado!", mensageTIPO + " cadastrado com sucesso.");
//            getObjTools().blockBackWizad();//Bloqueio do botão back do Wizard PrimeFAces
//            getObjTools().setShowButtonPrint(true);
//        } catch (Exception e) {
//            getObjMessage().warn("Erro ao efetuar cadastro!", e.getMessage()
//                    + "\nVerifique os dados e tente novamente!");
//        }
//    }
//
//    public void cadastrarCliente() {
//        try {
//            PessoaMetodosDeCadastro obj = ObjPessoaMetodosDeCadastro();
//            boolean checkCpfCnpj, existCpfCnpj, emptyCpfCnpj;
//            emptyCpfCnpj = pessoa.getCpfCnpj().isEmpty();
//
//            if (mudancaCpfCnpj && emptyCpfCnpj && !cpfOpcional) {
//                do {
//                    obj.cpfRandom(pessoa);
//                    checkCpfCnpj = ObjCheckExistCpfCnpj().checkExistCpfCnpj(pessoa, mudancaCpfCnpj);
//                } while (!checkCpfCnpj);
//            } else if (mudancaCpfCnpj) {
//                checkCpfCnpj = ObjPessoaCheckCPF().checkCPF(pessoa);
//            } else {
//                checkCpfCnpj = ObjPessoaCheckCNPJ().checkCNPJ(pessoa);
//            }
//
//            existCpfCnpj = ObjCheckExistCpfCnpj().checkExistCpfCnpj(pessoa, mudancaCpfCnpj);
//
//            if (checkCpfCnpj && existCpfCnpj) {
//                ObjPessoaPadraoCaracter().padraoCaracter(pessoa);
//                obj.cadastrarPessoa(pessoa);
//                obj.cadastrarTelefones(pessoa, telefoneList);
//                obj.cadastrarCliente(pessoa);
//                if (mudancaCpfCnpj) {
//                    obj.cadastrarPessoaFisica(pessoa, fisica);
//                } else {
//                    obj.cadastrarPessoaJuridica(pessoa, getJuridica());
//                }
//
//                getObjTools().blockBackWizad();//Bloqueio do botão back do Wizard PrimeFAces
//                getObjMessage().info("Cadastro efetuado!", "Cliente cadastrado com sucesso.");
//                getObjTools().setShowButtonPrint(true); //Habilitando visibilidade do botão para impressão
//            }
//        } catch (Exception e) {
//            getObjMessage().warn("Erro ao efetuar cadastro!", e.getMessage()
//                    + "\nVerifique os dados e tente novamente!");
//        }
//    }
//
//    private PessoaCheckExistLogin ObjCheckExistLogin() {
//        return new PessoaCheckExistLogin();
//    }
//
//    private PessoaCheckCPF ObjPessoaCheckCPF() {
//        return new PessoaCheckCPF();
//    }
//
//    private PessoaCheckCNPJ ObjPessoaCheckCNPJ() {
//        return new PessoaCheckCNPJ();
//    }
//
//    private PessoaCheckExistCpfCnpj ObjCheckExistCpfCnpj() {
//        return new PessoaCheckExistCpfCnpj();
//    }
//
//    private PessoaPadraoCaracter ObjPessoaPadraoCaracter() {
//        return new PessoaPadraoCaracter();
//    }
//
//    private PessoaMetodosDeCadastro ObjPessoaMetodosDeCadastro() {
//        return new PessoaMetodosDeCadastro();
//    }
//
//    /* O métodos GETs e SETs utilizados para persistir usuários do sistema e clientes */
//    public Pessoa getPessoa() {
//        if (pessoa == null) {
//            pessoa = new Pessoa();
//        }
//        return pessoa;
//    }
//
//    public void setPessoa(Pessoa pessoa) {
//        this.pessoa = pessoa;
//    }
//
//    public Fisica getFisica() {
//        if (fisica == null) {
//            fisica = new Fisica();
//        }
//        return fisica;
//    }
//
//    public void setFisica(Fisica fisica) {
//        this.fisica = fisica;
//    }
//
//    public Juridica getJuridica() {
//        if (juridica == null) {
//            juridica = new Juridica();
//        }
//        return juridica;
//    }
//
//    public void setJuridica(Juridica juridica) {
//        this.juridica = juridica;
//    }
//
//    public Telefone getTelefoneList(int index) {
//        if (telefoneList.isEmpty()) {
//            telefoneList.add(index, new Telefone());
//        } else if (telefoneList.size() < (index+1)) {
//            telefoneList.add(index, new Telefone());
//        }
//        return telefoneList.get(index);
//    }
//
//    public User getUser() {
//        if (user == null) {
//            user = new User();
//        }
//        return user;
//    }
//    //--------------------------------------------------------------------
//
//    /*GETS & SETs para o campo temporário de CRMV do medico veterinário*/
//    public String getNumCRMV1() {
//        return numCRMV1;
//    }
//
//    public void setNumCRMV1(String numCRMV1) {
//        this.numCRMV1 = numCRMV1;
//    }
//
//    public String getNumCRMV2() {
//        return numCRMV2;
//    }
//
//    public void setNumCRMV2(String numCRMV2) {
//        this.numCRMV2 = numCRMV2;
//    }
//
//    public String getCRMVcompleto() {
//        return numCRMV1 + " " + numCRMV2;
//    }
//    //-----------------------------------------------------------------------
//
//    public boolean isMudancaCpfCnpj() {
//        return mudancaCpfCnpj;
//    }
//
//    public void setMudancaCpfCnpj(boolean mudancaCpfCnpj) {
//        this.mudancaCpfCnpj = mudancaCpfCnpj;
//    }
//
//    //-----------------------------------------------------------------------
//    public boolean isCpfOpcional() {
//        return cpfOpcional;
//    }
//
//    public void setCpfOpcional(boolean cpfOpcional) {
//        if (cpfOpcional == false && rgOpcional == false) {
//            rgOpcional = true;
//        }
//        this.cpfOpcional = cpfOpcional;
//    }
//
//    public boolean isRgOpcional() {
//        return rgOpcional;
//    }
//
//    public void setRgOpcional(boolean rgOpcional) {
//        if (rgOpcional == false && cpfOpcional == false) {
//            cpfOpcional = true;
//        }
//        this.rgOpcional = rgOpcional;
//    }
//
//    //-----------------------------------------------------------------------
//    public boolean isViewTelefone2() {
//        return viewTelefone2;
//    }
//
//    public void setViewTelefone2(boolean viewTelefone2) {
//        this.viewTelefone2 = viewTelefone2;
//    }
//
//    public boolean isViewTelefone3() {
//        if (viewTelefone2 == false) {
//            viewTelefone3 = false;
//        }
//        return viewTelefone3;
//    }
//
//    public void setViewTelefone3(boolean viewTelefone3) {
//        this.viewTelefone3 = viewTelefone3;
//    }
}


text:
'use strict'
const authenticatedTransaction = require('../utilities/authenticatedTransaction')
const escapeForLike = require('../utilities/escapeForLike')
const crypto = require('./crypto')
const sendPasswordResetEmail = require('./sendPasswordResetEmail')
const AuthenticationError = require('../../../errors/authenticationError')
const MalformedRequestError = require('../../../errors/malformedRequestError')
const NoSuchResourceError = require('../../../errors/noSuchResourceError')
const validate = require('../../../utilities/validate')
const { funcs: vf } = validate

module.exports = (knex, emailer) => args =>
  authenticatedTransaction(knex, args.auth, (trx, authUser) =>

    validate(args.body, {
      emailAddress: [
        vf.notUndefined('You must provide an email address to perform a password update or to reset the password.'),
        vf.notNull('You must provide an email address to perform a password update or to reset the password.'),
        vf.emailAddress('The email address must be an email address.')
      ],
      password: [
        vf.string('The password must be a string.'),
        vf.minLength('The password must not be shorter than eight characters.', 8),
        vf.maxLength('The password must not be longer than thirty characters.', 30)
      ],
      passwordResetKey: [
        vf.notUndefined('You must provide a password reset key to perform a password update or null to reset the password.'),
        vf.string('The password reset key must be a string.'),
        vf.matchesRegex('The password reset key must be thirty alphanumeric characters.', /^[A-Za-z0-9]{30}$/)
      ]
    })
    .then(() =>

      // Get the existing user.
      trx
        .from('users')
        .where('emailAddress', 'ilike', escapeForLike(args.body.emailAddress))
        .select(['emailAddress', 'id', 'passwordResetKeyHash'])
    )
    .then(users => {
      if (!users.length) {
        throw new NoSuchResourceError()
      }
      const oldUser = users[0]

      const {
        emailAddress,
        password,
        passwordResetKey
      } = args.body

      // generating a new password reset key
      if (passwordResetKey === null) {
        // Generate a key.
        const key = crypto.generatePasswordResetKey()
        // Set the key hash.
        return trx
          .from('users')
          .where('id', oldUser.id)
          .update({
            passwordResetKeyHash: key.hash
          })
          .then(() =>
            sendPasswordResetEmail(emailer, emailAddress, key.key)
          )
          // Send the password reset email. Note that the transaction can still fail at this point.

      // setting password using a password reset key
      } else if (password) {
        // Verify the provided password reset key against the hash in the existing user.
        if (
          !passwordResetKey ||
          !oldUser.passwordResetKeyHash ||
          !crypto.verifyPasswordResetKey(passwordResetKey, oldUser.passwordResetKeyHash)
        )
          throw new AuthenticationError()
        // Do the update.
        return trx
          .from('users')
          .where('id', oldUser.id)
          .update({
            passwordHash: crypto.hashPassword(password),
            passwordResetKeyHash: null
          })

      // Those are the only options. Otherwise, throw.
      } else {
        throw new MalformedRequestError()
      }

    })
    .then(() => null)
  )


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.IdentityModel.TestUtils;

namespace Microsoft.IdentityModel.KeyVaultExtensions.Tests
{
    public class KeyWrapProviderTheoryData : TheoryDataBase
    {
        public string Algorithm { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Oanda.RestV20.Client;
using Oanda.RestV20.Model;
using RestSharp;

namespace Oanda.RestV20.Api
{
    public partial class DefaultApi
    {
        /// <summary>
        /// Pending Orders List all pending Orders in an Account
        /// </summary>
        /// <exception cref="Oanda.RestV20.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The authorization bearer token previously obtained by the client</param>
        /// <param name="accountID">Account Identifier</param>
        /// <param name="acceptDatetimeFormat">Format of DateTime fields in the request and response. (optional)</param>
        /// <returns>JSON string response</returns>
        public string ListPendingOrdersAsJson(string authorization, string accountID, string acceptDatetimeFormat = null)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
                throw new ApiException(400, "Missing required parameter 'authorization' when calling DefaultApi->ListPendingOrders");
            // verify the required parameter 'accountID' is set
            if (accountID == null)
                throw new ApiException(400, "Missing required parameter 'accountID' when calling DefaultApi->ListPendingOrders");

            var localVarPath = "/accounts/{accountID}/pendingOrders";
            var localVarPathParams = new Dictionary<String, String>();
            var localVarQueryParams = new Dictionary<String, String>();
            var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<String, String>();
            var localVarFileParams = new Dictionary<String, FileParameter>();
            Object localVarPostBody = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (accountID != null) localVarPathParams.Add("accountID", Configuration.ApiClient.ParameterToString(accountID)); // path parameter
            if (authorization != null) localVarHeaderParams.Add("Authorization", Configuration.ApiClient.ParameterToString(authorization)); // header parameter
            if (acceptDatetimeFormat != null) localVarHeaderParams.Add("Accept-Datetime-Format", Configuration.ApiClient.ParameterToString(acceptDatetimeFormat)); // header parameter

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                localVarPathParams, localVarHttpContentType);

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("ListPendingOrders", localVarResponse);
                if (exception != null) throw exception;
            }

            return localVarResponse.Content;
        }

        /// <summary>
        /// Create Order Create an Order for an Account
        /// </summary>
        /// <exception cref="Oanda.RestV20.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The authorization bearer token previously obtained by the client</param>
        /// <param name="accountID">Account Identifier</param>
        /// <param name="createOrderBody"></param>
        /// <param name="acceptDatetimeFormat">Format of DateTime fields in the request and response. (optional)</param>
        /// <returns>ApiResponse of InlineResponse201</returns>
        public ApiResponse<InlineResponse201> CreateOrder(string authorization, string accountID, string createOrderBody, string acceptDatetimeFormat = null)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
                throw new ApiException(400, "Missing required parameter 'authorization' when calling DefaultApi->CreateOrder");
            // verify the required parameter 'accountID' is set
            if (accountID == null)
                throw new ApiException(400, "Missing required parameter 'accountID' when calling DefaultApi->CreateOrder");
            // verify the required parameter 'createOrderBody' is set
            if (createOrderBody == null)
                throw new ApiException(400, "Missing required parameter 'createOrderBody' when calling DefaultApi->CreateOrder");

            var localVarPath = "/accounts/{accountID}/orders";
            var localVarPathParams = new Dictionary<String, String>();
            var localVarQueryParams = new Dictionary<String, String>();
            var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<String, String>();
            var localVarFileParams = new Dictionary<String, FileParameter>();
            Object localVarPostBody = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (accountID != null) localVarPathParams.Add("accountID", Configuration.ApiClient.ParameterToString(accountID)); // path parameter
            if (authorization != null) localVarHeaderParams.Add("Authorization", Configuration.ApiClient.ParameterToString(authorization)); // header parameter
            if (acceptDatetimeFormat != null) localVarHeaderParams.Add("Accept-Datetime-Format", Configuration.ApiClient.ParameterToString(acceptDatetimeFormat)); // header parameter

            localVarPostBody = createOrderBody; // json

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("CreateOrder", localVarResponse);
                if (exception != null) throw exception;
            }

            return new ApiResponse<InlineResponse201>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (InlineResponse201)Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse201)));
        }

        /// <summary>
        /// Replace Order Replace an Order in an Account by simultaneously cancelling it and creating a replacement Order
        /// </summary>
        /// <exception cref="Oanda.RestV20.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The authorization bearer token previously obtained by the client</param>
        /// <param name="accountID">Account Identifier</param>
        /// <param name="orderSpecifier">The Order Specifier</param>
        /// <param name="replaceOrderBody">Specification of the replacing Order. The replacing order must have the same type as the replaced Order.</param>
        /// <param name="acceptDatetimeFormat">Format of DateTime fields in the request and response. (optional)</param>
        /// <returns>ApiResponse of InlineResponse2011</returns>
        public ApiResponse<InlineResponse2011> ReplaceOrder(string authorization, string accountID, string orderSpecifier, string replaceOrderBody, string acceptDatetimeFormat = null)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
                throw new ApiException(400, "Missing required parameter 'authorization' when calling DefaultApi->ReplaceOrder");
            // verify the required parameter 'accountID' is set
            if (accountID == null)
                throw new ApiException(400, "Missing required parameter 'accountID' when calling DefaultApi->ReplaceOrder");
            // verify the required parameter 'orderSpecifier' is set
            if (orderSpecifier == null)
                throw new ApiException(400, "Missing required parameter 'orderSpecifier' when calling DefaultApi->ReplaceOrder");
            // verify the required parameter 'replaceOrderBody' is set
            if (replaceOrderBody == null)
                throw new ApiException(400, "Missing required parameter 'replaceOrderBody' when calling DefaultApi->ReplaceOrder");

            var localVarPath = "/accounts/{accountID}/orders/{orderSpecifier}";
            var localVarPathParams = new Dictionary<String, String>();
            var localVarQueryParams = new Dictionary<String, String>();
            var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var localVarFormParams = new Dictionary<String, String>();
            var localVarFileParams = new Dictionary<String, FileParameter>();
            Object localVarPostBody = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
            if (localVarHttpHeaderAccept != null)
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (accountID != null) localVarPathParams.Add("accountID", Configuration.ApiClient.ParameterToString(accountID)); // path parameter
            if (orderSpecifier != null) localVarPathParams.Add("orderSpecifier", Configuration.ApiClient.ParameterToString(orderSpecifier)); // path parameter
            if (authorization != null) localVarHeaderParams.Add("Authorization", Configuration.ApiClient.ParameterToString(authorization)); // header parameter
            if (acceptDatetimeFormat != null) localVarHeaderParams.Add("Accept-Datetime-Format", Configuration.ApiClient.ParameterToString(acceptDatetimeFormat)); // header parameter

            localVarPostBody = replaceOrderBody; // json

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("ReplaceOrder", localVarResponse);
                if (exception != null) throw exception;
            }

            return new ApiResponse<InlineResponse2011>(localVarStatusCode,
                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (InlineResponse2011)Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2011)));
        }

    }
}


text:
package com.github.redvasily.mapmapper;

import org.immutables.value.Value;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

@Value.Immutable
public interface BuilderInfo {
  Class builderClass();
  Constructor constructor();
  Map<String, Field> fields();
  Method buildMethod();
  Field initBits();
}


text:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using WebCounterInDb.Data;

namespace WebCounterInDb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var db = new UsersDbContext();
            var usersCount = db.UsersCount.FirstOrDefault();
            usersCount.Count += 1;
            db.SaveChanges();

            Response.Clear();
            Bitmap generatedImage = new Bitmap(200, 20);
            Graphics gr = Graphics.FromImage(generatedImage);
            gr.DrawString(string.Format("Users in application: {0}", usersCount.Count), new Font("Arial", 13.4f), Brushes.MediumSeaGreen, 0, 0);

            Response.ContentType = "image/gif";
            generatedImage.Save(Response.OutputStream, ImageFormat.Gif);
        }
    }
}


text:
#ifndef DecodingImageGenerator_h
#define DecodingImageGenerator_h

#include "SkImageGenerator.h"
#include "SkImageInfo.h"

#include "platform/PlatformExport.h"
#include "wtf/RefPtr.h"
#include "wtf/CheckedArithmetic.h"

class SkData;

namespace blink {

class ImageFrameGenerator;

// Implements SkImageGenerator and used by SkPixelRef to populate a discardable
// memory with decoded pixels.
//
// This class does not own an ImageDecode. It does not own encoded data. It serves
// as and adapter to ImageFrameGenerator which actually performs decoding.
class PLATFORM_EXPORT DecodingImageGenerator final : public SkImageGenerator {
public:
    static SkImageGenerator* create(SkData*);

    DecodingImageGenerator(PassRefPtr<ImageFrameGenerator>, const SkImageInfo&, size_t index);
    ~DecodingImageGenerator() override;

    void setGenerationId(size_t id) { m_generationId = id; }

protected:
    SkData* onRefEncodedData() override;
#ifdef SK_LEGACY_IMAGE_GENERATOR_ENUMS_AND_OPTIONS
	Result onGetPixels(const SkImageInfo&, void* pixels, size_t rowBytes, const Options&, SkPMColor ctable[], int* ctableCount) override;
#endif
    bool onGetYUV8Planes(SkISize sizes[3], void* planes[3], size_t rowBytes[3], SkYUVColorSpace*) override;

private:
    RefPtr<ImageFrameGenerator> m_frameGenerator;
    size_t m_frameIndex;
    size_t m_generationId;
};

} // namespace blink

#endif // DecodingImageGenerator_h_


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Web.Razor.Parser.SyntaxTree;
using Microsoft.Internal.Web.Utils;

namespace System.Web.Razor.Generator
{
    public class SectionCodeGenerator : BlockCodeGenerator
    {
        public SectionCodeGenerator(string sectionName)
        {
            SectionName = sectionName;
        }

        public string SectionName { get; private set; }

        public override void GenerateStartBlockCode(Block target, CodeGeneratorContext context)
        {
            string startBlock = context.BuildCodeString(cw =>
            {
                cw.WriteStartMethodInvoke(context.Host.GeneratedClassContext.DefineSectionMethodName);
                cw.WriteStringLiteral(SectionName);
                cw.WriteParameterSeparator();
                cw.WriteStartLambdaDelegate();
            });
            context.AddStatement(startBlock);
        }

        public override void GenerateEndBlockCode(Block target, CodeGeneratorContext context)
        {
            string startBlock = context.BuildCodeString(cw =>
            {
                cw.WriteEndLambdaDelegate();
                cw.WriteEndMethodInvoke();
                cw.WriteEndStatement();
            });
            context.AddStatement(startBlock);
        }

        public override bool Equals(object obj)
        {
            SectionCodeGenerator other = obj as SectionCodeGenerator;
            return other != null &&
                   base.Equals(other) &&
                   String.Equals(SectionName, other.SectionName, StringComparison.Ordinal);
        }

        public override int GetHashCode()
        {
            return HashCodeCombiner.Start()
                .Add(base.GetHashCode())
                .Add(SectionName)
                .CombinedHash;
        }

        public override string ToString()
        {
            return "Section:" + SectionName;
        }
    }
}


text:
<?php

class CPassBox extends CInput {

	public function __construct($name = 'password', $value = '', $size = 50, $maxlength = 255) {
		parent::__construct('password', $name, $value);
		$this->setAttribute('size', $size);
		$this->setAttribute('maxlength', $maxlength);
	}
}


text:
import React from 'react';
import { render } from 'react-dom';
import { PSClickWrap } from '../../src';
import './styles.css';

class Demo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      signerIdValue: '',
      clickwrapStyle: 'full',
      needsAgreeWarning: false,
      dynamicRenderData: {
        user_token_value: 'enter your email above to update this text',
        another_token_value: 'lorem ipsum',
        last_token_value: '$9999',
      },
      hasAgreed: false,
    };
  }

  static onEventMethod = (name, ...args) => {
    console.log(`${name} prop callback called for PSClickwrap with parameters: `, [...args]);
  };

  static onError = (...args) => {
    if (args[0] === 'Command aborted on: validationTask, Error: missing_signer_id') {
      alert('Please enter a signer ID (email address) before agreeing.');
    }
    Demo.onEventMethod('onError', ...args);
  };

  handleChangeSignerId = (e) => {
    this.setState({ signerIdValue: e.target.value });
  };

  updateRenderData = () => {
    this.setState((state) => ({
      dynamicRenderData: {
        ...state.dynamicRenderData,
        another_token_value: 'This value was updated through user interaction!',
        last_token_value: '$1,000,000',
      },
    }));
  };

  updateClickwrapStyle = (e) => {
    this.setState({ clickwrapStyle: e.target.value });
  };

  onUpdateSignerId = (...args) => {
    this.setState((state) => ({
      dynamicRenderData: {
        ...state.dynamicRenderData,
        user_token_value: args[0],
      },
    }));
    Demo.onEventMethod('onSetSignerId', ...args);
  };

  onValid = (...args) => {
    this.setState({ hasAgreed: true });
    Demo.onEventMethod('onValid', ...args);
  };

  onInvalid = (...args) => {
    this.setState({ hasAgreed: false });
    Demo.onEventMethod('onInvalid', ...args);
  };

  onClickSubmit = () => {
    const { hasAgreed } = this.state;
    if (hasAgreed) {
      alert(
        'Thanks for trying out the React SDK! (It does not actually bind you to anything, just a demo :)!',
      );
    } else {
      this.setState({ needsAgreeWarning: true });
    }
  };

  render() {
    const {
      clickwrapStyle,
      dynamicRenderData,
      needsAgreeWarning,
      hasAgreed,
      signerIdValue,
    } = this.state;
    return (

        <link
          rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
          crossOrigin="anonymous"
        />

Ironclad Clickwrap React SDK - Example Clickwrap

          View project on GitHub

          Email address
          <input
            type="email"
            id="email"
            placeholder="Enter an email address"
            className="form-control"
            onBlur={this.handleChangeSignerId}
          />

        <button className="btn btn-primary" type="button" onClick={this.updateRenderData}>
          Change render data

        </button>

          PSClickwrap Style:

            <button
              type="button"
              className={`btn btn-primary btn-sm ${clickwrapStyle === 'full' ? 'active' : ''}`}
              value="full"
              onClick={this.updateClickwrapStyle}
            >
              Full

            </button>
            <button
              type="button"
              className={`btn btn-primary btn-sm ${clickwrapStyle === 'scroll' ? 'active' : ''}`}
              value="scroll"
              onClick={this.updateClickwrapStyle}
            >
              Scroll

            </button>
            <button
              type="button"
              className={`btn btn-primary btn-sm ${clickwrapStyle === 'checkbox' ? 'active' : ''}`}
              value="checkbox"
              onClick={this.updateClickwrapStyle}
            >
              Checkbox

            </button>
            <button
              type="button"
              className={`btn btn-primary btn-sm ${clickwrapStyle === 'combined' ? 'active' : ''}`}
              value="combined"
              onClick={this.updateClickwrapStyle}
            >
              Combined

            </button>
            <button
              type="button"
              className={`btn btn-primary btn-sm ${clickwrapStyle === 'embedded' ? 'active' : ''}`}
              value="embedded"
              onClick={this.updateClickwrapStyle}
            >
              Embedded

            </button>

        <PSClickWrap
          accessId={process.env.PACTSAFE_ACCESS_ID}
          groupKey="example-web-group"
          confirmationEmail
          displayImmediately={false}
          testMode
          dynamic
          signerId={signerIdValue}
          renderData={dynamicRenderData}
          clickWrapStyle={clickwrapStyle}
          onValid={this.onValid}
          onSent={(...args) => Demo.onEventMethod('onSent', ...args)}
          onInvalid={this.onInvalid}
          onDisplayed={(...args) => Demo.onEventMethod('onDisplayed', ...args)}
          onError={Demo.onError}
          onSetSignerId={this.onUpdateSignerId}
          onSet={(...args) => Demo.onEventMethod('onSet', ...args)}
          onRendered={(...args) => Demo.onEventMethod('onRendered', ...args)}
          onRetrieved={(...args) => Demo.onEventMethod('onRetrieved', ...args)}
        />
        {needsAgreeWarning && (

          Please agree to all contracts with an email address above before submitting!

        )}
        <button
          className={`btn btn-primary ${hasAgreed ? '' : 'disabled'}`}
          type="submit"
          onClick={this.onClickSubmit}
        >
          Submit
        </button>

    );
  }
}

render(<Demo />, document.querySelector('#demo'));


text:
The plugin for Hazelcast fetches nodes belonging to a given service from the Consul server.

**Currently works from Hazelcast 3.6-EA !**

In order to get this plugin running, you must place the JAR on the classpath along with this above build of Hazelcast. Then you must alter the cluster.xml like this:

 ```
 <join>
    <multicast enabled="false">
        .....................
    </multicast>

    <discovery-strategies>
	<discovery-strategy class="de.neofonie.hazelcast.consul.ConsulDiscovery" enabled="true">
	  <properties>
	      <property name ="host">localhost</property>
	      <property name ="port">8500</property>
	      <property name ="name">your-hazelcast-service</property>
	  </properties>
	</discovery-strategy>
    </discovery-strategies>
</join>
```

It is important to know that you must register you Hazelcast service in Consul along with the appropriate port (e.g. 5901). The ConsulDiscovery will read all IPs from this service together with their ports!

# Credits and Authors

Forked from the original repo: https://github.com/decoomanj

Authors:
- Jan De Cooman
- Guiquan Weng

Thanks to Christoph Engelbert from Hazelcast for the support.


text:
package cn.lambdacraft.deathmatch.block;

import ic2.api.item.ISpecialElectricItem;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.util.ForgeDirection;
import cn.lambdacraft.core.block.TileElectricStorage;
import cn.liutils.api.util.RegUtils;

/**
 *
 * @author WeAthFolD, Rikka
 *
 */
public class TileHealthCharger extends TileElectricStorage implements IInventory {

    public static final int ENERGY_MAX = 30000, EFFECT_MAX = 14400,
            PROGRESS_TIME = 100, HEALTH_MAX = 100; // 1.25 batbox, 4-6 potions
    public boolean isUsing = false;
    public HashSet<EntityPlayer> chargers = new HashSet();
    public int mainEff = 0, sideEff = 0;
    public int prgAddMain = 0, prgAddSide = 0;
    private int sideEffectId = 0;
    private int ticksExisted;
    private int lastActivationTick;

    public static Set<Integer> availableIds = new HashSet();
    static {
        availableIds.add(Potion.digSpeed.id);
        availableIds.add(Potion.damageBoost.id);
        availableIds.add(Potion.fireResistance.id);
        availableIds.add(Potion.invisibility.id);
        availableIds.add(Potion.jump.id);
        availableIds.add(Potion.moveSpeed.id);
        availableIds.add(Potion.nightVision.id);
        availableIds.add(Potion.resistance.id);
        availableIds.add(Potion.waterBreathing.id);
    }

    /**
     * Slot 0:涓昏嵂姘存Ы銆� Slot 1:鍓嵂姘存Ы銆� Slot 2:鏀剧數姹犳Ы銆�
     */
    public ItemStack slots[] = new ItemStack[3];
    public int currentBehavior;
    public boolean isRSActivated;

    public boolean canUse() {
        return currentEnergy > 0 && (sideEff > 0 || mainEff > 0);
    }

    public void startUsing(EntityPlayer player) {
        chargers.add(player);
        worldObj.playSoundAtEntity(player, "lambdacraft:entities.medshot", 0.5F, 1.0F);
        lastActivationTick = ticksExisted;
        isUsing = true;
    }

    public void stopUsing(EntityPlayer player) {
        chargers.remove(player);
        lastActivationTick = ticksExisted;
        if(ticksExisted - lastActivationTick > 20)
            worldObj.playSoundAtEntity(player, "lambdacraft:entities.medshotno", 0.5F, 1.0F);
        if (chargers.size() == 0)
            isUsing = false;
    }

    public enum EnumBehavior {
        NONE, RECEIVEONLY, EMIT;

        @Override
        public String toString() {
            switch (this) {
            case NONE:
                return "rs.donothing.name";
            case RECEIVEONLY:
                return "rs.reciveonly.name";
            case EMIT:
                return "rs.emit.name";
            default:
                return "rs.donothing.name";
            }
        }
    }

    public void nextBehavior() {
        currentBehavior = currentBehavior == 4 ? 0 : currentBehavior + 1;
    }

    public TileHealthCharger() {
        super(2, ENERGY_MAX);

    }

    @Override
    public void updateEntity() {
        super.updateEntity();
        ++ticksExisted;
        if (worldObj.isRemote)
            return;
        int energyReq = ENERGY_MAX - currentEnergy;

        if (currentEnergy < 0)
            currentEnergy = 0;

        /**
         *
         * Charge the energy into tileentity
         */
        if (currentEnergy < ENERGY_MAX
                && !(!this.isRSActivated && this.getCurrentBehavior() == EnumBehavior.RECEIVEONLY)) {
            ItemStack sl = slots[2];
            if (sl != null && sl.getItem() == Items.redstone) {
                if (energyReq > 500) {
                    this.decrStackSize(2, 1);
                }
                currentEnergy += 500;
            } else if (sl != null && sl.getItem() instanceof ISpecialElectricItem) {
                ISpecialElectricItem item = (ISpecialElectricItem) sl.getItem();
                if (item.canProvideEnergy(sl)) {
                    double cn = energyReq < 128 ? energyReq : 128;
                    cn = item.getManager(sl).discharge(sl, cn, 2, false, false, false);
                    currentEnergy += cn;
                }
            }
        }

        // 澶勭悊F閿娇鐢ㄨ涓�
        if (this.isUsing) {

            for (EntityPlayer charger : chargers) {
                currentEnergy -= 5;// 5EU/T per player
                this.doHealing(charger);
                if (worldObj.getWorldTime() % 15 == 0) {
                    worldObj.playSoundAtEntity(charger,
                            "lambdacraft:entities.medcharge", 0.3F, 1.0F);
                }
                if (currentEnergy <= 0) {
                    this.chargers.clear();
                    this.isUsing = false;
                    worldObj.playSoundAtEntity(charger,
                            "lambdacraft:entities.medshotno", 0.5F, 1.0F);
                }
            }

        }

        if (slots[0] != null && slots[0].getItem() == Items.potionitem) {
            int dmg = slots[0].getItemDamage();
            List<PotionEffect> list = Items.potionitem.getEffects(dmg);
            PotionEffect effect = list.get(0);
            if (mainEff < HEALTH_MAX) {
                if (effect.getPotionID() == Potion.heal.getId()) {

                    if (currentEnergy > 5) {
                        currentEnergy -= 5;
                        prgAddMain++;
                    } else
                        currentEnergy = 0;
                    if (prgAddMain >= PROGRESS_TIME) {
                        this.setInventorySlotContents(0, null);
                        mainEff += (effect.getAmplifier() == 0 ? 12 : 18);
                        prgAddMain = 0;
                    }

                } else if (effect.getPotionID() == Potion.regeneration.getId()) {

                    if (currentEnergy > 5) {
                        currentEnergy -= 5;
                        prgAddMain++;
                    } else
                        currentEnergy = 0;
                    if (prgAddMain >= PROGRESS_TIME) {
                        this.setInventorySlotContents(0, null);
                        if (dmg == 8193)
                            mainEff += 36;
                        else if (dmg == 8257)
                            mainEff += 96;
                        else if (dmg == 8225)
                            mainEff += 38;
                        prgAddMain = 0;
                    }

                } else
                    prgAddMain = 0;
            }
            if (mainEff > TileHealthCharger.HEALTH_MAX)
                mainEff = HEALTH_MAX;
        } else prgAddMain = 0;

        if (slots[1] != null && slots[1].getItem() == Items.potionitem) {

            int dmg = slots[1].getItemDamage();
            List<PotionEffect> list = Items.potionitem.getEffects(dmg);
            PotionEffect effect = list.get(0);
            if (TileHealthCharger.availableIds.contains(effect.getPotionID())
                    && sideEff < EFFECT_MAX) {
                if (this.sideEffectId == 0
                        || effect.getPotionID() == sideEffectId
                        || this.sideEff == 0) {
                    this.sideEffectId = effect.getPotionID();
                    if (currentEnergy > 5) {
                        currentEnergy -= 5;
                        prgAddSide++;
                    }
                    if (prgAddSide >= PROGRESS_TIME) {
                        this.setInventorySlotContents(1, null);
                        sideEff += effect.getDuration();
                        prgAddSide = 0;
                    }
                } else
                    prgAddSide = 0;
            }
            if (sideEff > TileHealthCharger.EFFECT_MAX)
                sideEff = EFFECT_MAX;

        } else prgAddSide = 0;
    }

    public static Field fldDuration;
    static {
        try {
            fldDuration = RegUtils.getObfField(PotionEffect.class, "duration", "field_76460_b");
        } catch(Exception e) {
            e.printStackTrace();
            //NOPE
        }
    }

    public void doHealing(EntityPlayer charger) {
        if (mainEff > 0 && charger.getHealth() < 20) {
            if (worldObj.getWorldTime() % 10 == 0) {
                charger.heal(1);
                this.mainEff -= 1;
            }
        }
        if (sideEff > 0 && sideEffectId != 0) {
            int amt = sideEff > 10 ? 10 : sideEff;
            this.sideEff -= amt;
            PotionEffect eff = charger
                    .getActivePotionEffect(Potion.potionTypes[sideEffectId]);
            if (eff != null) {
                try {
                    fldDuration.set(eff, (Integer)fldDuration.get(eff) + amt);
                } catch(Exception e) {
                    e.printStackTrace();
                }
                charger.addPotionEffect(eff);
            } else
                charger.addPotionEffect(new PotionEffect(sideEffectId, amt, 0));
        }
    }

    @Override
    public int getSizeInventory() {
        return 3;
    }

    @Override
    public ItemStack getStackInSlot(int i) {
        return slots[i];
    }

    @Override
    public ItemStack decrStackSize(int slot, int amt) {
        ItemStack stack = getStackInSlot(slot);
        if (stack != null) {
            if (stack.stackSize <= amt) {
                setInventorySlotContents(slot, null);
            } else {
                stack = stack.splitStack(amt);
                if (stack.stackSize == 0) {
                    setInventorySlotContents(slot, null);
                }
            }
        }
        return stack;
    }

    @Override
    public ItemStack getStackInSlotOnClosing(int slot) {
        ItemStack stack = getStackInSlot(slot);
        if (stack != null) {
            setInventorySlotContents(slot, null);
        }
        return stack;
    }

    @Override
    public void setInventorySlotContents(int i, ItemStack itemstack) {
        this.slots[i] = itemstack;
    }

    @Override
    public String getInventoryName() {
        return "armorcharger";
    }

    @Override
    public int getInventoryStackLimit() {
        return 64;
    }

    @Override
    public boolean isUseableByPlayer(EntityPlayer entityplayer) {
        return entityplayer.getDistanceSq(xCoord + 0.5, yCoord + 0.5,
                zCoord + 0.5) <= 64;
    }

    @Override
    public boolean isItemValidForSlot(int i, ItemStack itemstack) {
        if (i <= 3 && !(itemstack.getItem() instanceof ISpecialElectricItem))
            return false;
        return true;
    }

    /**
     * Reads a tile entity from NBT.
     */
    @Override
    public void readFromNBT(NBTTagCompound nbt) {
        super.readFromNBT(nbt);
        slots = this.restoreInventory(nbt, "inv", slots.length);
        currentEnergy = nbt.getInteger("energy");
        mainEff = nbt.getShort("mainEff");
        sideEff = nbt.getShort("sideEff");
        prgAddMain = nbt.getShort("prgAddMain");
        prgAddSide = nbt.getShort("prgAddSide");
        sideEffectId = nbt.getByte("sideEfeectId");
    }

    /**
     * Writes a tile entity to NBT.
     */
    @Override
    public void writeToNBT(NBTTagCompound nbt) {
        super.writeToNBT(nbt);
        this.storeInventory(nbt, slots, "inv");
        nbt.setInteger("energy", currentEnergy);
        nbt.setShort("mainEff", (short) mainEff);
        nbt.setShort("sideEff", (short) sideEff);
        nbt.setShort("prgAddMain", (short) prgAddMain);
        nbt.setShort("prgAddSide", (short) prgAddSide);
        nbt.setByte("sideEffectId", (byte) sideEffectId);
    }

    @Override
    public boolean acceptsEnergyFrom(TileEntity paramTileEntity,
            ForgeDirection paramDirection) {
        return !(getCurrentBehavior() == EnumBehavior.RECEIVEONLY && !this.isRSActivated);
    }

    public EnumBehavior getCurrentBehavior() {
        return getBehavior(currentBehavior);
    }

    private EnumBehavior getBehavior(int i) {
        switch (i) {
        case 0:
            return EnumBehavior.NONE;
        case 1:
            return EnumBehavior.RECEIVEONLY;
        case 2:
            return EnumBehavior.EMIT;
        }
        return EnumBehavior.NONE;
    }

    @Override
    public int getSinkTier() {
        return 1;
    }

    @Override
    public boolean hasCustomInventoryName() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void openInventory() {
        // TODO Auto-generated method stub

    }

    @Override
    public void closeInventory() {
        // TODO Auto-generated method stub

    }

}


text:
<?php

namespace App\Action;

use Psr\Log\LoggerInterface;
use Slim\Http\Request;
use Slim\Http\Response;
use App\Factory\NoteFactory;
use App\Repository\NoteRepository;

/**
 * Class NotesAction.
 */
final class NotesAction
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    private $logger;

    /**
     * @var \App\Factory\NoteFactory
     */
    private $factory;

    /**
     * @var \App\Repository\NoteRepository
     */
    private $repository;

    /**
     * @param \Psr\Log\LoggerInterface       $logger
     * @param \App\Factory\NoteFactory       $factory
     * @param \App\Repository\NoteRepository $repository
     */
    public function __construct(LoggerInterface $logger, NoteFactory $factory, NoteRepository $repository)
    {
        $this->logger = $logger;
        $this->factory = $factory;
        $this->repository = $repository;
    }

    /**
     * @param \Slim\Http\Request  $request
     * @param \Slim\Http\Response $response
     * @param array               $args
     *
     * @return \Slim\Http\Response
     */
    public function addNote(Request $request, Response $response, $args)
    {
        $this->logger->info('NotesAction: add note');

        $new_note = $this->factory->createNewNote($request->getParsedBody());
        if (!empty($new_note)) {
            $response = $response->withHeader('Location', '/notes/'.$new_note->id)
                                 ->withJson(array('info' => 'Created'), 201);
        } else {
            $response = $response->withJson(array('info' => 'Bad Request'), 400);
        }

        return $response;
    }

    /**
     * @param \Slim\Http\Request  $request
     * @param \Slim\Http\Response $response
     * @param array               $args
     *
     * @return \Slim\Http\Response
     */
    public function getAllNotes(Request $request, Response $response, $args)
    {
        $this->logger->info('NotesAction: get all notes');

        $notes = $this->repository->getAllNotes();
        if (!empty($notes) && $notes->count() > 0) {
            $response = $response->withJson(array('data' => $notes));
        } else {
            $response = $response->withJson(array('info' => 'Not Found'), 404);
        }

        return $response;
    }

    /**
     * @param \Slim\Http\Request  $request
     * @param \Slim\Http\Response $response
     * @param array               $args
     *
     * @return \Slim\Http\Response
     */
    public function getNote(Request $request, Response $response, $args)
    {
        $this->logger->info('NotesAction: get note');

        $note = $this->repository->getNote($args['id']);
        if (!empty($note)) {
            $response = $response->withJson(array('data' => $note));
        } else {
            $response = $response->withJson(array('info' => 'Not Found'), 404);
        }

        return $response;
    }

    /**
     * @param \Slim\Http\Request  $request
     * @param \Slim\Http\Response $response
     * @param array               $args
     *
     * @return \Slim\Http\Response
     */
    public function deleteNote(Request $request, Response $response, $args)
    {
        $this->logger->info('NotesAction: note deleted');

        $count = $this->repository->deleteNote($args['id']);
        if ($count > 0) {
            $response = $response->withJson(array('info' => 'ok'));
        } else {
            $response = $response->withJson(array('info' => 'Not Found'), 404);
        }

        return $response;
    }
}


text:
#import "NSObject.h"

@class NSMutableSet, NSObject<OS_dispatch_source>;

// Not exported
@interface AirPlayReceiverContext : NSObject
{
    struct AirPlayReceiverSessionPrivate *_session;
    unsigned char _receiverUIStarted;
    unsigned int _receiverUISessionID;
    unsigned char _audioStarted;
    struct OpaqueAUGraph *_graph;
    unsigned char _useLegacyOutput;
    int _mainConverterNode;
    struct OpaqueAudioComponentInstance *_mainConverterUnit;
    double _mainNextSampleTime;
    unsigned char _useAltOutput;
    int _altConverterNode;
    struct OpaqueAudioComponentInstance *_altConverterUnit;
    double _altNextSampleTime;
    int _mixerNode;
    struct OpaqueAudioComponentInstance *_mixerUnit;
    unsigned char _useVarispeed;
    int _varispeedNode;
    struct OpaqueAudioComponentInstance *_varispeedUnit;
    unsigned char _useInput;
    struct OpaqueAudioComponentInstance *_inputUnit;
    char *_inputBuffer;
    unsigned long long _inputMaxLen;
    unsigned char _inputEnabled;
    unsigned char _inputStarted;
    double _inputNextSampleTime;
    int _outputNode;
    struct OpaqueAudioComponentInstance *_outputUnit;
    unsigned char _audioLoopback;
    NSObject<OS_dispatch_source> *_ducker;
    struct __CFString *_displayUUID;
    struct IONotificationPort *_hidNotifier;
    unsigned int _hidIterator;
    NSMutableSet *_hidDevices;
    unsigned int _powerAssertion;
}

- (void)_handleMediaServicesWereReset:(id)arg1;
- (void)_handleAudioInterruption:(id)arg1;

@end


text:
/**
 * This class is generated by jOOQ
 */
package de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.daos;

/**
 * This class is generated by jOOQ.
 */
@javax.annotation.Generated(value    = { "http://www.jooq.org", "3.4.4" },
                            comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class InitiatorDao extends org.jooq.impl.DAOImpl<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records.InitiatorRecord, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator, org.jooq.Record2<java.lang.Integer, java.lang.Integer>> {

	/**
	 * Create a new InitiatorDao without any configuration
	 */
	public InitiatorDao() {
		super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Initiator.INITIATOR, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator.class);
	}

	/**
	 * Create a new InitiatorDao with an attached configuration
	 */
	public InitiatorDao(org.jooq.Configuration configuration) {
		super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Initiator.INITIATOR, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator.class, configuration);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected org.jooq.Record2<java.lang.Integer, java.lang.Integer> getId(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator object) {
		return compositeKeyRecord(object.getInitiativeId(), object.getMemberId());
	}

	/**
	 * Fetch records that have initiative_id IN (values)
	 */
	public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator> fetchByInitiativeId(java.lang.Integer... values) {
		return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Initiator.INITIATOR.INITIATIVE_ID, values);
	}

	/**
	 * Fetch records that have member_id IN (values)
	 */
	public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator> fetchByMemberId(java.lang.Integer... values) {
		return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Initiator.INITIATOR.MEMBER_ID, values);
	}

	/**
	 * Fetch records that have accepted IN (values)
	 */
	public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Initiator> fetchByAccepted(java.lang.Boolean... values) {
		return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Initiator.INITIATOR.ACCEPTED, values);
	}
}


text:
package org.apache.camel.component.netty.http;

import io.netty.handler.codec.http.FullHttpRequest;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.http.HttpMethods;
import org.junit.Test;

public class NettyHttpBindingUseRelativePathInPostTest extends BaseNettyTest {

    @Test
    public void testSendToNetty() throws Exception {
        Exchange exchange = template.request("netty-http:http://localhost:{{port}}/myapp/myservice?query1=a&query2=b&useRelativePath=true", exchange1 -> {
            exchange1.getIn().setBody("b1=x&b2=y");
            exchange1.getIn().setHeader("content-type", "application/x-www-form-urlencoded");
            exchange1.getIn().setHeader(Exchange.HTTP_METHOD, HttpMethods.POST);
        });
        // convert the response to a String
        String body = exchange.getMessage().getBody(String.class);
        assertEquals("Request message is OK", body);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws Exception {
                from("netty-http:http://localhost:{{port}}/myapp/myservice").process(exchange -> {
                    String body = exchange.getIn().getBody(String.class);

                    // for unit testing make sure we got right message
                    assertEquals("The body message is wrong", "b1=x&b2=y", body);
                    assertEquals("Get a wrong query parameter from the message header", "a", exchange.getIn().getHeader("query1"));
                    assertEquals("Get a wrong query parameter from the message header", "b", exchange.getIn().getHeader("query2"));
                    assertEquals("Get a wrong form parameter from the message header", "x", exchange.getIn().getHeader("b1"));
                    assertEquals("Get a wrong form parameter from the message header", "y", exchange.getIn().getHeader("b2"));
                    assertEquals("Get a wrong form parameter from the message header", "localhost:" + getPort(), exchange.getIn().getHeader("host"));

                    NettyHttpMessage in = (NettyHttpMessage) exchange.getIn();
                    FullHttpRequest request = in.getHttpRequest();
                    assertEquals("Relative path not used in POST", "/myapp/myservice?query1=a&query2=b", request.uri());

                    // send a response
                    exchange.getMessage().getHeaders().clear();
                    exchange.getMessage().setHeader(Exchange.CONTENT_TYPE, "text/plain");
                    exchange.getMessage().setBody("Request message is OK");
                });
            }
        };
    }

}


text:
"""Control brightness with keyboard."""
import sys
from pathlib import Path

from i3_helpers import sh, sh_no_block

BRIGHTNESS_DIR = Path('/sys/class/backlight/intel_backlight')
if not BRIGHTNESS_DIR.is_dir():
    raise FileNotFoundError("Missing brightness directory!")

def control_brightness(how, level):
    """Control brightness level."""
    _change_brightness(how, level)
    _send_notification()
    return 0

def _change_brightness(how, level):
    cmd = f'xbacklight -{how} {level}'
    sh(cmd)

def _send_notification():
    brightness = _get_brightness()
    max_brightness = _get_brightness(maximum=True)
    bright_perc = int((brightness / max_brightness) * 100)
    bar = '─' * int(bright_perc / 5)

    not_cmd = [
        'dunstify',
        '-i',
        'display-brightness',
        '-t',
        '2000',
        '-r',
        '1753',
        '-u',
        'normal',
        f'   {bar}  {bright_perc}%',
    ]
    sh_no_block(not_cmd)

def _get_brightness(maximum=False):
    basename = '{}brightness'.format('' if not maximum else 'max_')
    brightness_file = BRIGHTNESS_DIR / basename
    with brightness_file.open() as f:
        brightness = f.read()
    return int(brightness)

if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument('--direction', '-d', required=True)
    parser.add_argument('--level', '-l', type=int, default=5)
    args = parser.parse_args()

    control_brightness(args.direction, args.level)
    sys.exit(0)


text:
var GeoJSON = require('mongoose-geojson-schema');
var mongoose = require('mongoose'),
	Schema = mongoose.Schema,
	passportLocalMongoose = require('passport-local-mongoose');

var User = new Schema({
	name: String,
	username: { type: String, required: true, unique: true },
	gender: {type: String, required: true},
	password: { type: String, required: true },
	created_at: Date,
	lastActivity: Date,
	location: {
		type: {
			type: String,
			default: 'Point'
		},
		coordinates: {
			type: []
		}
	}
});

// User.insure({location:"2dsphere"})

// index: {
// 	type: '2dsphere',
// 	sparse: true
// }

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);


text:
/* ----------------------------------------------------------- */
/*                                                             */
/*                          ___                                */
/*                       |_| | |_/   SPEECH                    */
/*                       | | | | \   RECOGNITION               */
/*                       =========   SOFTWARE                  */
/*                                                             */
/*                                                             */
/* ----------------------------------------------------------- */
/* developed at:                                               */
/*                                                             */
/*      Speech Vision and Robotics group                       */
/*      Cambridge University Engineering Department            */
/*      http://svr-www.eng.cam.ac.uk/                          */
/*                                                             */
/*      Entropic Cambridge Research Laboratory                 */
/*      (now part of Microsoft)                                */
/*                                                             */
/* ----------------------------------------------------------- */
/*         Copyright: Microsoft Corporation                    */
/*          1995-2000 Redmond, Washington USA                  */
/*                    http://www.microsoft.com                 */
/*                                                             */
/*              2002  Cambridge University                     */
/*                    Engineering Department                   */
/*                                                             */
/*   Use of this software is governed by a License Agreement   */
/*    ** See the file License for the Conditions of Use  **    */
/*    **     This banner notice must not be removed      **    */
/*                                                             */
/* ----------------------------------------------------------- */
/*         File: HModel.h  HMM Model Definition Data Type      */
/* ----------------------------------------------------------- */

/* !HVER!HModel:   3.4.1 [CUED 12/03/09] */

#ifndef _HMODEL_H_
#define _HMODEL_H_

#ifdef __cplusplus
extern "C" {
#endif

/*
   The following types define the in-memory representation of a HMM.
   All HMM's belong to a HMMSet which includes a macro table for
   rapidly mapping macro/hmm names into structures.
*/

#define MACHASHSIZE 250007   /* Size of each HMM Set macro hash table */
#define PTRHASHSIZE  513   /* Size of each HMM Set ptr map hash table */
#define MINMIX  1.0E-5     /* Min usable mixture weight */
#define LMINMIX -11.5129254649702     /* log(MINMIX) */

#define MINDLOGP 0.000001  /* prob = exp(shortform/DLOGSCALE) */
#define DLOGSCALE -2371.8  /* = 32767/ln(MINDLOGP) */
#define DLOGZERO 32767

#define MixFloor(hset)            ( MINMIX )

#ifdef WIN32
#define XFORM HTK_XFORM
#endif

/* ------------------ Master Model File Info ----------------- */

typedef struct _MMFInfo *MILink;

typedef struct _MMFInfo{
   Boolean isLoaded;       /* true if contents are loaded */
   char *fName;            /* MMF file name */
   int fidx;               /* MMF file index */
   MILink next;            /* next external file name in list */
} MMFInfo;

/* -------------------- HMM Definition ----------------------- */

enum _DurKind {NULLD, POISSOND, GAMMAD, RELD, GEND};
typedef enum _DurKind DurKind;

enum _HSetKind {PLAINHS, SHAREDHS, TIEDHS, DISCRETEHS};
typedef enum _HSetKind HSetKind;

typedef struct {
   SVector mean;        /* mean vector */
   CovKind ckind;       /* kind of covariance */
   Covariance cov;      /* covariance matrix or vector */
   float gConst;        /* Precomputed component of b(x) */
   int mIdx;            /* MixPDF index */
   int nUse;            /* usage counter */
   int stream;          /* enables multi-stream semi-tied transforms */
   SVector vFloor;      /* enables flooring for multiple semi-tied transforms */
   Ptr info;            /* hook to hang information from */
   Ptr hook;            /* general hook */
} MixPDF;

typedef struct {        /* 1 of these per mixture per stream */
   float weight;        /* mixture weight */
   MixPDF *mpdf;        /* -> mixture pdf */
} MixtureElem;

typedef union {         /* array[1..numMixtures] of Mixture */
   MixtureElem *cpdf;    /* PLAINHS or SHAREDHS */
   Vector tpdf;          /* TIEDHS */
   ShortVec dpdf;        /* DISCRETE */
} MixtureVector;

typedef struct{         /* used for tied mixture prob calculations */
   short index;          /* mixture index */
   float prob;           /* mixture prob scaled by maxP */
}TMProb;

typedef struct {        /* A Tied Mixture "Codebook" */
   LabId mixId;          /* id of macro base name */
   short nMix;           /* num mixtures M in set */
   short topM;           /* num TMProbs actually used */
   MixPDF ** mixes;      /* array[1..M] of MixPDF */
   LogFloat maxP;        /* max log mixture prob */
   TMProb *probs;        /* array[1..M] of TMProb */
} TMixRec;

typedef struct {        /* 1 of these per stream */
   int nMix;            /* num mixtures in this stream */
   MixtureVector spdf;  /* Mixture Vector */
   Ptr hook;            /* general hook */
}StreamElem;

typedef struct {
   SVector weights;     /* vector of stream weights */
   StreamElem *pdf;     /* array[1..numStreams] of StreamElem */
   SVector dur;         /* vector of state duration params, if any */
   int sIdx;            /* State index */
   int nUse;            /* usage counter */
   Ptr hook;            /* general hook */
   int stateCounter;    /* # of state occurrences */
} StateInfo;

typedef struct {        /* 1 of these per state */
   StateInfo *info;     /* information for this state */
} StateElem;

typedef struct {
   struct _HMMSet *owner;  /* owner of this model */
   short numStates;        /* includes entry and exit states */
   StateElem *svec;        /* array[2..numStates-1] of StateElem */
   SVector dur;            /* vector of model duration params, if any */
   SMatrix transP;         /* transition matrix (logs) */
   int tIdx;               /* Transition matrix index */
   int nUse;               /* num logical hmm's sharing this def */
   Ptr hook;               /* general hook */
} HMMDef;

typedef HMMDef * HLink;

/* --------------------- Enumerated Types -------------------- */

enum _XFormKind {MLLRMEAN, MLLRCOV, MLLRVAR, CMLLR, SEMIT};
typedef enum _XFormKind XFormKind;

enum _AdaptKind {TREE, BASE};
typedef enum _AdaptKind AdaptKind;

enum _BaseClassKind {MIXBASE, MEANBASE, COVBASE};
typedef enum _BaseClassKind BaseClassKind;

/* -------------- Regression Tree Definition ----------------- */

typedef struct _ItemRec *ILink;

typedef struct _ItemRec {
   HLink owner;      /* HMM owning this item */
   Ptr item;         /* -> to a HMM structure */
   ILink next;
}ItemRec;

typedef struct {
  char* mmfIdMask;     /* mask of model sets that appropriate for */
  BaseClassKind bkind; /* type of parameters applicable to */
  IntVec swidth;       /* stream width size */
  int numClasses;      /* number of baseclasses */
  ILink *ilist;        /* 1..numClasses of ilists */
  int nUse;            /* usage counter */
  char *fname;         /* filename of where the baseclass was loaded */
} BaseClass;

typedef struct _RegNode {
  float nodeOcc;            /* occupancy for this node */
  int vsize;                /* vector size associated with the baseclasses of this node */
  int nodeIndex;            /* index number of node */
  int numChild;             /* number of children - 0 if terminal */
  struct _RegNode **child;  /* children of this node NULL if terminal */
  IntVec baseClasses;       /* if a terminal node the set of baseclasses else NULL */
  Ptr info;                 /* hook to hang information from */
} RegNode ;

typedef struct RegTree {
  int numNodes;        /* number of non-terminal nodes in tree */
  int numTNodes;       /* number of terminal nodes in tree */
  BaseClass *bclass;   /* baseclass associated with this regression tree */
  RegNode *root;       /* pointer to the root node of the tree */
  Boolean valid;       /* is it valid to generate a transform at the root node */
                       /* handles multiple stream adaptation issues */
  float thresh;        /* split threshold to determine stopping in tree */
  char *fname;         /* filename of where the regTree was loaded */
} RegTree;

/* ----------------- Transform Definition -------------------- */

typedef struct {       /* occupancy is always used */
  Boolean accSum;      /* accumulate the sum of the observations */
  Boolean accSumSq;    /* accumulate sum-squared (diag) of the observations */
  Boolean accBTriMat;  /* accumulate weighted outer-product of observations */
  RegTree regTree;     /* the regression tree used for transform */
} XFormAccInfo;

typedef union {
   Matrix wgt;          /* for interpolated transforms */
   IntVec assign;        /* for hard assignments  */
} AdaptWgt;

typedef struct {
  int vecSize;         /* must be matched to a stream width! */
  IntVec blockSize;    /* block sizes in the linear transform */
  SMatrix* xform;      /* 1..numBlocks matrix transforms */
  SVector bias;        /* bias vector, if no bias equals NULL */
  float det;           /* determinant of linxform */
  int nUse;            /* usage counter */
  SVector vFloor;      /* used for SEMIT variance flooring */
} LinXForm;

typedef struct {
  int numXForms;       /* number of transforms in this xformset */
  XFormKind xkind;     /* transform kind (MLLRMEAN, CMLLR etc */
  LinXForm **xforms;   /* 1..numTrans linear transforms */
  int nUse;            /* usage counter */
} XFormSet;

typedef struct _AdaptXForm {
  char* xformName;                  /* name of the transform (macroname) */
  char *fname;                      /* filename of where the xform was loaded */
  struct _AdaptXForm  *swapXForm;    /* has this transform been swapped with parent */
  MemHeap *mem;                     /* heap used for storing transform */
  AdaptKind akind;                  /* adaptation kind */
  BaseClass *bclass;                /* base class for which transform applicable */
  RegTree *rtree;                   /* regression tree to be used for adaptation */
  int nUse;                         /* usage counter */
  XFormAccInfo *info;               /* information abbout the accumulates for this transform */
  struct _AdaptXForm *parentXForm;  /* parent transform, NULL if no parent parenttransform */
  XFormSet  *xformSet;              /* set of linear transforms */
  AdaptWgt  xformWgts;              /* set of weights for all the base classes */
  struct _HMMSet *hset;                     /* transform is linked with a model set */
} AdaptXForm;

typedef struct {
  char* xformName;     /* name of the transform (macroname) */
  char* mmfIdMask;     /* mask of model sets that appropriate for */
  char *fname;         /* filename of where the input xform was loaded */
  ParmKind pkind;      /* parameter kind for xform to be applied to */
  Boolean preQual;     /* is this applied prior to qualifiers? */
  LinXForm *xform;     /* actual transform to be applied */
  int nUse;            /* usage counter */
} InputXForm;

/* ---------------------- Macros/HMM Hashing ------------------- */

/*
   Every macro, logical HMM defn and physical HMM defn has an
   entry in a macro table.  The macro types are:
     l logHMM     u mean      v variance  i invcovar  p pdf
     h phyHMM     d duration  t transP    m mixpdf    s state
     x xform      w strm wts  o options   c lltcovar  * deleted
     r regtree    b baseclass a adaptXfrm j inputXfm  f linXfm
     g xformSet   y xformBias
   a HMMDef will have exactly 1 phyHMM macro referencing it but it can
   have 0 or more logHMM macros referencing it.
*/

typedef struct _MacroDef *MLink;

typedef struct _MacroDef{
   MLink next;             /* next cell in hash table */
   char type;              /* type of macro [hluvixdtmps*] */
   short fidx;             /* idx of MMF file (0 = SMF) */
   LabId id;               /* name of macro */
   Ptr structure;          /* -> shared structure or HMM Def */
} MacroDef;

typedef struct _PtrMap {   /* used for finding macros via ptr's */
   struct _PtrMap *next;   /* next cell in hash table */
   Ptr ptr;                /* the structure */
   MLink m;                /* macro def for this structure */
} PtrMap;

/* ---------------------- HMM Sets ----------------------------- */

typedef struct _HMMSet{
   MemHeap *hmem;          /* memory heap for this HMM Set */
   Boolean *firstElem;     /* first element added to hmem during MakeHMMSet*/
   char *hmmSetId;         /* identifier for the hmm set */
   MILink mmfNames;        /* List of external file names */
   int numLogHMM;          /* Num of logical HMM's */
   int numPhyHMM;          /* Num of distinct physical HMM's */
   int numFiles;           /* total number of ext files */
   int numMacros;          /* num macros used in this set */
   MLink * mtab;           /* Array[0..MACHASHSIZE-1]OF MLink */
   PtrMap ** pmap;         /* Array[0..PTRHASHSIZE-1]OF PtrMap* */
   Boolean allowTMods;     /* true if HMMs can have Tee Models */
   Boolean optSet;         /* true if global options have been set */
   short vecSize;          /* dimension of observation vectors */
   short swidth[SMAX];     /* [0]=num streams,[i]=width of stream i */
   ParmKind pkind;         /* kind of obs vector components */
   DurKind dkind;          /* kind of duration model (model or state) */
   CovKind ckind;          /* cov kind - only global in V1.X */
   HSetKind hsKind;        /* kind of HMM set */
   TMixRec tmRecs[SMAX];   /* array[1..S]of tied mixture record */
   int numStates;          /* Number of states in HMMSet */
   int numSharedStates;    /* Number of shared states in HMMSet */
   int numMix;             /* Number of mixture components in HMMSet */
   int numSharedMix;       /* Number of shared mixtures in HMMSet */
   int numTransP;          /* Number of distinct transition matrices */
   int ckUsage[NUMCKIND];  /* Number of components using given ckind */
   InputXForm *xf;         /* Input transform of HMMSet */
   AdaptXForm *semiTied;   /* SemiTied transform associated with model set */
   short projSize;         /* dimension of vector to update */

   /* Adaptation information accumulates */
   Boolean attRegAccs;   /* have the set of accumulates been attached */
   Boolean attXFormInfo; /* have the set of adapt info been attached */
   Boolean attMInfo;     /* have the set of adapt info been attached */
   AdaptXForm *curXForm;
   AdaptXForm *parentXForm;

   /* Added to support LogWgts */
   Boolean logWt;       /* Component weights are stored as Logs */

   /* Added to support delayed loading of the semi-tied transform */
   char *semiTiedMacro;  /* macroname of semi-tied transform */

} HMMSet;

/* --------------------------- Initialisation ---------------------- */

void InitModel(void);
/*
   Initialise the module
*/

/* --------------- Input XForm DIrectory access -------------------- */

/* EXPORT->AddInXFormDir: Add given file directory to set */
void  AddInXFormDir(HMMSet *hset, char *dirname);

/* ---------------- Macro Related Manipulations -------------------- */

void QuantiseObservation(HMMSet *hset, Observation *obs, int frame);

MLink NewMacro(HMMSet *hset, short fidx, char type, LabId id, Ptr structure);
/*
   Create a new macro definition for given HMM set with given values
   and insert it into the associated macro table.  Return a pointer to
   it.
*/

void DeleteMacro(HMMSet *hset, MLink p);
void DeleteMacroStruct(HMMSet *hset, char type, Ptr structure);
/*
   Mark macro definition [for given structure] as deleted (ie type='*')
*/

MLink FindMacroName(HMMSet *hset, char type, LabId id);
/*
   Find the macro def of given name in hset.  Return NULL if
   not found.  This uses a fast hashtable lookup.
*/

MLink FindMacroStruct(HMMSet *hset, char type, Ptr structure);
/*
   Return macro definition for given structure. The first
   request for this structure requires a slow exhaustive
   search through whole macro table.  The ptr is then added
   to a hashtable stored in hset so that subsequent
   requests are fast.
*/

Boolean HasMacros(HMMSet *hset, char * types);
/*
   Returns true if shared structure macros (other than regular
   hmmdefs) have been used in any HMM in set.  If types is not NULL,
   then a string containing all the different macro types is also
   returned.
*/

void SetVFloor(HMMSet *hset, Vector *vFloor, float minVar);
/*
   Initialise a set of variance floor vectors.  Marks varFloor vectors
   as used then if vFloor!=NULL and macro ~v "varFloorN"
   exists then vFloor[N] is set to this vector; otherwise a vector of
   length hset->swidth[s] is created in vFloor[s] and all its
   components are set to minVar.
*/

void ApplyVFloor(HMMSet *hset);
/*
   Apply the variance floors in hset to all covariances in the model set
*/

void PrintHMMProfile(FILE *f, HLink hmm);
/*
   Print a profile (num states, streams, mixes, etc) to f of
   given HMM definition.
*/

void PrintHSetProfile(FILE *f, HMMSet *hset);
/*
   Print a profile to f of given HMM set.
*/

/* ------------------- HMM Set Load/Store ---------------------- */

/* the basic sequence needed to create a HMM set is
      CreateHMMSet {AddMMF} (MakeHMMSet | MakeOneHMM) LoadHMMSet
*/

void CreateHMMSet(HMMSet *hset, MemHeap *heap, Boolean allowTMods);
/*
   Create a HMMSet using given heap.  This routine simply
   initialises the basic HMMSet structure. It must be followed by
   a call to either MakeOneHMM or MakeHMMSet.
*/

MILink AddMMF(HMMSet *hset, char *fname);
/*
   Add MMF file to HMM set (must not be already in MMF list).  This is
   mainly used for pre-specifying definition files but it can also be
   used to force loading of supplementary information coded as macros
   such as variance floors.  Returns a pointer to added MMFInfo
   record.  AddMMF can be used before or after a call to MakeOneHMM or
   MakeHMMSet.  However, it must not be called after LoadHMMSet.
*/

ReturnStatus MakeHMMSet(HMMSet *hset, char *fname);
/*
   Make a HMMSet by reading the file fname.  Each line of fname
   should contain the logical name of a HMM optionally followed by a
   physical name.  If no physical name is given it is assumed to be
   the same as the logical name.  This routine creates the macro hash
   table, macro definitions for each HMM and HMMDef structures.  It
   does NOT load the actual HMM definitions.
*/

ReturnStatus MakeOneHMM(HMMSet *hset, char *hname);
/*
   As above but hname is a single HMM definition which is used
   to create a singleton HMM set
*/

ReturnStatus LoadHMMSet(HMMSet *hset, char *hmmDir, char *hmmExt);
/*
   Load any preloaded MMF files.  Scan the physical list of hset and
   for each HMM def which is still unloaded, the physical name is
   modified by the given hmmDir and hmmExt, if any, and the resulting
   file is loaded.
*/

void ResetHMMSet(HMMSet *hset);
/*
  Returns HMMSet to state it was in after calling CreateHMMSet.
  Frees memory on hmem, (and logicalHeap if HMM_STORE enabled) etc.
*/

void SaveInOneFile(HMMSet *hset, char *fname);
/*
   Called before SaveHMMSet to ignore all original file names and store
   the entire HMM set in a single file.
*/

ReturnStatus SaveHMMSet(HMMSet *hset, char *hmmDir, char *hmmExt, char *macroExt, Boolean binary);
/*
   Store the given HMM set.  Each HMM def and macro is stored in the
   same file as it was loaded from except that if hmmDir is specified
   then it replaces the original location of the file.  In the case of
   individual HMM files only, the original extension if any is
   replaced by the given hmmExt if any.  If the HMM set is TIEDHS or
   DISCRETEHS then the mix weights are stored in a compact form.  If
   binary is set then all output uses compact binary mode.
*/

ReturnStatus SaveHMMList(HMMSet *hset, char *fname);
/*
   Save a HMM list in fname describing given HMM set
*/

/* -------------- Shared Structure "Seen" Flags -------------- */

/* When scanning HMM sets, it is convenient to mark certain objects
   as "seen".  The nUse and nMix fields are used for this.  If either
   is -ve then the attached object seen. */
Boolean IsSeen(int flag);
/*
   return true if flag is set (ie. -ve)
*/

void Touch(int *flag);
void Untouch(int *flag);
/*
   set or clear given flag (see also TouchV/UntouchV in HMem)
*/

typedef enum {CLR_HMMS,CLR_STATES,CLR_STREAMS,CLR_ALL} ClearDepth;

void ClearSeenFlags(HMMSet *hset, ClearDepth depth);
/*
   Clear all the seen flags in hset (ie all nUse and nMix fields)
   downto given level.
*/

/* ----------------- General HMM Operations --------------------- */

int MaxMixtures(HLink hmm);
int MaxMixInSet(HMMSet *hset);
/*
   Returns max number of mixtures in given HMM or set of HMMs
*/

int MaxMixInS(HLink hmm, int s);
int MaxMixInSetS(HMMSet *hset, int s);
/*
   Returns max number of mixtures in given stream in given HMM or set of HMMs
*/

int MaxStatesInSet(HMMSet *hset);
/*
   Returns max number of states in any HMM in set of HMMs
*/

char *DurKind2Str(DurKind dkind, char *buf);
char *CovKind2Str(CovKind ckind, char *buf);
/*
   Utility routines to convert enum types to strings.  In each case,
   string is stored in *buf and pointer to buf is returned
*/

/* ------------- HMM Output Probability Calculations --------------- */

void PrecomputeTMix(HMMSet *hset, Observation *x, float tmThresh, int topM);
/*
   Precompute the tied mixture probs stored in hset->tmRecs.  The
   array of mix probs is scaled by the max prob and sorted.  If topM>0
   then it is set in each stream, otherwise all mixes within tmThresh
   of the max are used
*/

LogFloat  OutP(Observation *x, HLink hmm, int state);
LogFloat POutP(HMMSet *hset, Observation *x, StateInfo *si);
/*
   Return the log output probability of observation x in given
   state of given model
*/

LogFloat SOutP(HMMSet *hset, int s, Observation *x, StreamElem *se);
/*
   Return Stream log output prob of stream s of observation x
*/

/*
   Return Mixture log output probability for given vector x.
*/

Boolean PDEMOutP(Vector otvs, MixPDF *mp, LogFloat *mixp, LogFloat xwtdet);
LogFloat MOutP(Vector x, MixPDF *mp);
LogFloat IDOutP(Vector x, int vecSize, MixPDF *mp);
short DProb2Short(float p);

#ifdef PDE_STATS
/*
   Get PDE stats
*/
void PrintPDEstats();
#endif

/*
   Convert prob p to scaled log prob = ln(p)*DLOGSCALE
*/

LogFloat Short2DProb(short s);
/*
   Convert scaled log prob (s) to prob p = exp(s/DLOGSCALE)
*/

void FixFullGConst(MixPDF *mp, LogFloat ldet);
void FixLLTGConst(MixPDF *mp);
void FixInvDiagGConst(MixPDF *mp);
void FixDiagGConst(MixPDF *mp);
/*
   Set the gConst for the specific mixture component.  In the
   case of FullGConst, ldet is passed as a parameter since it
   will often have just been calculated during a cov inversion.
*/

void FixGConsts(HLink hmm);
/*
   Sets all gConst values in the given HMM
*/

void FixAllGConsts(HMMSet *hset);
/*
   Sets all gConst values in all HMMs in set
*/

LogFloat MixLogWeight(HMMSet *hset, float weight);
float MixWeight(HMMSet *hset, float weight);
/*
  Get the log-weight
*/

/* ---------------------- XForm support code ---------------------- */

/* EXPORT->LoadInputXForm: loads, or returns, the specified transform */
InputXForm *LoadInputXForm(HMMSet *hset, char* macroname, char* fname);

/* EXPORT->SaveInputXForm: outputs an individual transform */
void SaveInputXForm(HMMSet *hset, InputXForm *xf, char *fname, Boolean binary);

/* EXPORT->LoadOneXForm: loads, or returns, the specified transform */
AdaptXForm *LoadOneXForm(HMMSet *hset, char* macroname, char* fname);

/* EXPORT->SaveOneXForm: outputs an individual transform */
void SaveOneXForm(HMMSet *hset, AdaptXForm *xform, char *fname, Boolean binary);

/* EXPORT->SaveAllXForms: outputs all generated transforms */
void SaveAllXForms(HMMSet *hset, char *fname, Boolean binary);

/* EXPORT->LoadBaseClass: loads, or returns, the specified baseclass */
BaseClass *LoadBaseClass(HMMSet *hset, char* macroname, char *fname);

/* EXPORT->LoadRegTree: loads, or returns, the specified regression tree */
RegTree *LoadRegTree(HMMSet *hset, char* macroname, char *fname);

/* EXPORT-> CreateXFormMacro: creates a macro for a transform. */
void CreateXFormMacro(HMMSet *hset,AdaptXForm *xform, char* macroname);

/* EXPORT-> XFormKind2Str: Return string representation of enum XFormKind */
char *XFormKind2Str(XFormKind xkind, char *buf);

/* EXPORT-> AdaptKind2Str: Return string representation of enum AdaptKind */
char *AdaptKind2Str(AdaptKind akind, char *buf);

/* EXPORT-> BaseClassKind2Str: Return string representation of enum BaseClassKind */
char *BaseClassKind2Str(BaseClassKind bkind, char *buf);

/* EXPORT-> Str2BaseClassKind: parse the string into the correct baseclass */
BaseClassKind Str2BaseClassKind(char *str);

/* EXPORT-> Str2XFormKind: parse the string into the correct xform kind */
XFormKind Str2XFormKind(char *str);

/* EXPORT-> Str2AdaptKind: parse the string into the correct xform kind */
AdaptKind Str2AdaptKind(char *str);

#ifdef __cplusplus
}
#endif

#endif  /* _HMODEL_H_ */

/* ------------------------- End of HModel.h --------------------------- */


text:
package programmersguide.workingwithasposepdf.workingwithtext.extracttextfromallpagesofpdf.java;

import com.aspose.pdf.*;

public class ExtractTextFromAllPagesofPDF
{
    public static void main(String[] args) throws Exception
    {
        // The path to the documents directory.
        String dataDir = "src/programmersguide/workingwithasposepdf/workingwithtext/extracttextfromallpagesofpdf/data/";

        //open document
        com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document(dataDir + "input.pdf");
        //create TextAbsorber object to extract text
        com.aspose.pdf.TextAbsorber textAbsorber = new com.aspose.pdf.TextAbsorber();

        //accept the absorber for all the pages
        pdfDocument.getPages().accept(textAbsorber);

        //In order to extract text from specific page of document, we need to specify the particular page using its index against accept(..) method.
        //accept the absorber for particular PDF page
        //pdfDocument.getPages().get_Item(1).accept(textAbsorber);

        //get the extracted text
        String extractedText = textAbsorber.getText();

        // create a writer and open the file
        java.io.FileWriter writer = new java.io.FileWriter(new java.io.File(dataDir + "extracted_text.out.txt"));
        writer.write(extractedText);
        // write a line of text to the file
        //tw.WriteLine(extractedText);
        // close the stream
        writer.close();

        //Print message
        System.out.println("Text extracted successfully. Check output file.");
    }
}


text:
package com.google.cloud.solutions.spannerddl.parser;

/** Abstract Syntax Tree parser object for "create_index_statement" token */
import com.google.cloud.solutions.spannerddl.diff.ASTTreeUtils;

public class ASTcreate_index_statement extends SimpleNode
    implements Comparable<ASTcreate_index_statement> {

  public ASTcreate_index_statement(int id) {
    super(id);
  }

  public ASTcreate_index_statement(DdlParser p, int id) {
    super(p, id);
  }

  public String getIndexName() {
    return ASTTreeUtils.getChildByType(children, ASTname.class).toString();
  }

  @Override
  public String toString() {
    StringBuilder ret = new StringBuilder("CREATE");
    for (Node child : children) {
      switch (child.getId()) {
        case DdlParserTreeConstants.JJTUNIQUE_INDEX:
        case DdlParserTreeConstants.JJTNULL_FILTERED:
        case DdlParserTreeConstants.JJTCOLUMNS:
        case DdlParserTreeConstants.JJTSTORED_COLUMN_LIST:
          ret.append(" ");
          ret.append(child);
          break;
        case DdlParserTreeConstants.JJTNAME:
          ret.append(" INDEX ");
          ret.append(child);
          break;
        case DdlParserTreeConstants.JJTTABLE:
          ret.append(" ON ");
          ret.append(child);
          break;
        case DdlParserTreeConstants.JJTINDEX_INTERLEAVE_CLAUSE:
          ret.append(", ");
          ret.append(child);
          break;
        default:
          throw new IllegalArgumentException("Unknown node ID " + child.getClass());
      }
    }
    return ret.toString();
  }

  @Override
  public int compareTo(ASTcreate_index_statement other) {
    return this.getIndexName().compareTo(other.getIndexName());
  }

  @Override
  public boolean equals(Object other) {
    if (other instanceof ASTcreate_index_statement) {
      // lazy: compare text rendering.
      return this.toString().equals(other.toString());
    }
    return false;
  }
}