text:
class AuthNetImporter < Sinatra::Base

  Dotenv.load
  require 'pry'
  require_relative 'receipt'
  require_relative 'cc_report'

  PORT  = 9393
  CONSUMER_KEY = ENV['QBO_API_CONSUMER_KEY']
  CONSUMER_SECRET = ENV['QBO_API_CONSUMER_SECRET']

  set :port, PORT
  use Rack::Session::Pool

  QboApi.production = true

  use OmniAuth::Builder do
    provider :quickbooks, CONSUMER_KEY, CONSUMER_SECRET
  end

  helpers do

    def title
      "Quickbooks Import"
    end

  end

  #code is ordered by sequence of execution

  get '/' do
    @app_center = QboApi::APP_CENTER_BASE
    @auth_data = oauth_data
    @port = PORT
    erb :index
  end

  get '/get_qb_info' do
    if session[:token]
      api = QboApi.new(oauth_data)
      @cust = api.query(%{select * from Customer})
      @classes = api.query(%{select * from Class})
      @item = api.query(%{select * from Item}) #for items and default fee
    else
      redirect '/'
    end
    erb :get_qb_info, layout: :layout
  end

  post '/set_qb_info' do
    session[:default_customer] = params["default_customer"]
    session[:default_class] = params["default_class"]
    session[:default_item_id] = params["default_item"]
    session[:default_fee_item] = params["default_fee_item"]
    redirect '/choose_file'
  end

  #get csv file info

  get '/choose_file' do
    erb :choose_file, layout: :layout
  end

  post '/set_file' do
    session[:file] = params["file_name"]
    session[:position] = 0
    redirect :new_receipt
  end

  #get info for parsing the csv

  get '/new_receipt' do
    session[:position] = session[:position] || 0
    if session[:token]
      api = QboApi.new(oauth_data)
      @default_item = api.get :item, session[:default_item_id]
      @fee_item = api.get :item, session[:default_fee_item]
      @customer = api.get :customer, session[:default_customer]
      @class = api.query(%{select * from Class where Id = '#{session[:default_class]}'})
      #get params for each deposit
      erb :new_receipt, layout: :layout
    end
  end

  #step 7 review and decide to post to Quickbooks

  post "/create_receipt" do
    @date = params[:trans_date]
    @fee = params[:fee_amount]
    @num_trans = params[:num_transactions]
    @receipt_total = params[:receipt_total]
    r = Receipt.new(session[:file], {num: @num_trans.to_i,
                                  fee: @fee,
                                  date: @date,
                                  tot: @receipt_total,
                                  place: session[:position].to_i,
                                  item: session[:default_item_id],
                                  customer: session[:default_customer],
                                  fee_item: session[:default_fee_item],
                                  receipt_class: session[:default_class]
                                  })
    @receipt = r.data
    @calculated_total = get_receipt_total @receipt
    session[:prev_pos] = session[:position]
    session[:position] += @num_trans.to_i
    session[:current_receipt] = @receipt
    erb :create_receipt, layout: :layout
  end

  post '/send_to_quickbooks' do
    @receipt = session[:current_receipt]
    puts @receipt
    if session[:token]
      puts "Authorized!"
      api = QboApi.new(oauth_data)
      response = api.create :salesreceipt, payload: session[:current_receipt]
      puts response
    else
      puts "not authorized"
    end
    redirect :new_receipt
  end

  get '/skip_receipt' do
    redirect :new_receipt
  end

  get '/try_again' do
    session[:position] = session[:prev_pos]
    redirect :new_receipt
  end

  ##  Credit Card report sequence

  #get file and statement date
    get '/prepare_report' do
      if session[:token]
        erb :prepare_report, layout: :layout
      else
        redirect "/"
      end
    end

    post '/process_report' do
      if session[:token]
        session[:file] = params[:report_file]
        trans = CSV.read(params[:report_file], headers: true, header_converters: :symbol)
        session[:count] = trans.count
        session[:statement_date] = params[:statement_date]
        session[:accounts] = get_accounts(trans)
        session[:classes] = get_classes(trans)
        session[:total] = get_total(trans)
        redirect :map_accounts
      else
        redirect "/"
      end
    end

    def get_classes(trans)
      classes = []
      trans.each do |t|
        classes.push(t[:program])
      end
      classes.uniq
    end

    def get_accounts(trans)
      accounts = []
      trans.each do |t|
        accounts.push(t[:account])
      end
      accounts.uniq
    end

    def get_total(transactions)
      total = 0
      transactions.each do |t|
        total += t[:amount].to_f
      end
      total.round(2).to_s
    end

  #map accounts

    get "/map_accounts" do
      api = QboApi.new(oauth_data)
      @accounts = session[:accounts]
      @cc_account = api.query(%{select * from Account where AccountType = 'Credit Card'})
      @expense_accounts = api.query(%{select * from Account where AccountType = 'Expense'})
      erb :map_accounts, layout: :layout
    end

    post "/set_cc_accounts" do

      api = QboApi.new(oauth_data)
      cc_acct = api.get :account, params[:credit_card_account]
      session[:cc_account] = {name: cc_acct["Name"], val: cc_acct["Id"]}
      params.delete("credit_card_account")
      session[:accounts] = get_account_names(params.to_json)
      redirect :map_classes
    end

  #map classes

    get "/map_classes" do
      api = QboApi.new(oauth_data)
      @classes = session[:classes]
      @qb_classes = api.query(%{select * from Class})
      erb :map_classes, layout: :layout
    end

    post "/set_cc_classes" do
      session[:classes] = get_class_names(params.to_json)
      redirect "/build_cc_report"
    end

    #api.get :customer, session[:default_customer]
    #get names of accounts and classes
    def get_account_names(data)
      new_accounts_hash = {}
      api = QboApi.new(oauth_data)
      JSON.parse(data).each do |k,v|
        this_account = api.get :account, v
        new_accounts_hash[k] = {val: v, name: this_account["Name"]}
      end
      new_accounts_hash
    end

    def get_class_names(data)
      new_classes_hash = {}
      api = QboApi.new(oauth_data)
      JSON.parse(data).each do |k, v|
        this_class = api.query(%{select * from Class where Id = '#{v}'})
        new_classes_hash[k] = {val: v, name: this_class["QueryResponse"]["Class"].first["Name"]}
      end
      new_classes_hash
    end

  #build

    get "/build_cc_report" do
      if session[:token]
        report = Report.new(session[:file], {cc_account: (session[:cc_account]),
                                        accounts: (session[:accounts]),
                                        classes: (session[:classes]),
                                        statement_date: session[:statement_date],
                                        count: session[:count],
                                        total: session[:total]})
        @data = report.data
        session[:report] = @data
        erb :report, layout: :layout
      else
        redirect "/"
      end
    end

    post '/send_cc_to_quickbooks' do
      if session[:token]
        puts "Authorized!"
        puts session[:report]
        api = QboApi.new(oauth_data)
        response = api.create :purchase, payload: session[:report]
        puts response
      else
        puts "not authorized"
      end
      redirect "/"
    end

    ##FRP import
    #get file

    get '/donation_file' do
      erb :donation_file, layout: :layout
    end

    post '/set_donation_file' do
      #session[:file] = params["file_name"]
      trans = CSV.read(params["file_name"], headers: true, header_converters: :symbol)
      session[:classes] = get_classes(trans)
      session[:items] = get_items(trans)
    end

    # get_items(trans, term)
    #   items = []
    #   trans.each do |t|
    #     items.push(t[])

    def get_classes(trans)
      classes = []
      trans.each do |t|
        classes.push(t[:program])
      end
      classes.uniq
    end
    # post '/process_report' do
    #   if session[:token]
    #     session[:file] = params[:report_file]
    #     trans = CSV.read(params[:report_file], headers: true, header_converters: :symbol)
    #     session[:count] = trans.count
    #     session[:statement_date] = params[:statement_date]
    #     session[:accounts] = get_accounts(trans)
    #     session[:classes] = get_classes(trans)
    #     session[:total] = get_total(trans)
    #     redirect :map_accounts
    #   else
    #     redirect "/"
    #   end
    # end

  def oauth_data
    {
      consumer_key: CONSUMER_KEY,
      consumer_secret: CONSUMER_SECRET,
      token: session[:token],
      token_secret: session[:secret],
      realm_id: session[:realm_id]
    }
  end

  get '/auth/quickbooks/callback' do
    auth = env["omniauth.auth"][:credentials]
    session[:token] = auth[:token]
    session[:secret] = auth[:secret]
    session[:realm_id] = params['realmId']
    '<!DOCTYPE html>'
  end

  def get_receipt_total(receipt)
    total = 0
    receipt["Line"].each do |l|
      total += l["Amount"].to_i
    end
    total
  end

  get '/employees' do
    api = QboApi.new(oauth_data)
    @employees = api.query(%{select * from Employee})
    csv = CSV.open("employees.csv", 'w', {col_sep: ",", quote_char: '\'' })
    arr = []
    #binding.pry
    @employees["QueryResponse"]["Employee"].each do |e|
      arr << e["GivenName"]
      arr << e["FamilyName"]
      if e["PrimaryAddr"]
        arr << e["PrimaryAddr"]["Line1"]
        arr << e["PrimaryAddr"]["Line2"] || ""
        arr << e["PrimaryAddr"]["City"]
        arr << e["PrimaryAddr"]["CountrySubDivisionCode"]
        arr << e["PrimaryAddr"]["PostalCode"]
      else
        arr << ""
        arr << ""
        arr << ""
        arr << ""
        arr << ""
      end
      arr << e["SSN"]
      if e["PrimaryEmailAddr"]
        arr << e["PrimaryEmailAddr"]["Address"]
      else
        arr << ""
      end
      arr << "\n"
    end
    csv << arr
    csv.close
    erb :employees, layout: :layout
  end

end


text:
package org.opensingular.form.provider;

import org.opensingular.form.SIComposite;
import org.opensingular.form.SIList;
import org.opensingular.form.SInstance;
import org.opensingular.form.STypeComposite;
import org.opensingular.form.SingularFormException;
import org.opensingular.form.util.transformer.SCompositeListBuilder;
import org.opensingular.form.util.transformer.Value;
import org.opensingular.form.util.transformer.Value.Content;

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

public interface SSimpleProvider extends SimpleProvider<Content, SInstance> {

    @Override
    default List<Content> load(SInstance ins) {

        STypeComposite typeComposite = null;

        if (ins instanceof SIList) {
            typeComposite = (STypeComposite) ((SIList) ins).getElementsType();
        } else if (ins instanceof SIComposite) {
            typeComposite = (STypeComposite) ins.getType();
        }

        if (typeComposite == null) {
            throw new SingularFormException("Não foi possivel obter o tipo da instancia", ins);
        }

        final SSimpleProviderListBuilder builder = new SSimpleProviderListBuilder(new SCompositeListBuilder(typeComposite, ins));
        final List<Content>         listMap = new ArrayList<>();

        fill(builder);
        builder.getList().forEach(i -> listMap.add(Value.dehydrate(i)));

        return listMap;
    }

    void fill(SSimpleProviderListBuilder builder);

}

redpajama_set_name: RedPajamaGithub


text:
name: "\U0001F680Feature request"
about: Suggest an idea for io-ts
---

## 🚀 Feature request

### Current Behavior

<!-- A clear and concise description of what is the current behavior / use.  -->

### Desired Behavior

<!-- A clear and concise description of what you want to happen.  -->

### Suggested Solution

<!-- Suggest a solution that the community/maintainers/you may take to enable the desired behavior  -->

<!-- NOTE: Feature Requests without suggested solutions may not be addressed or treated with the same level of urgency as those that have suggested solutions. -->

### Who does this impact? Who is this for?

<!-- Who is this for? All users? TypeScript users? Beginners? Advanced? Yourself? People using X, Y, X, etc.? -->

### Describe alternatives you've considered

<!-- A clear and concise description of any alternative solutions or features you've considered.  -->

### Additional context

<!-- Add any other context or links about the feature request here. -->

### Your environment

<!-- PLEASE FILL THIS OUT -->

| Software   | Version(s) |
| ---------- | ---------- |
| io-ts      |            |
| fp-ts      |            |
| TypeScript |            |


text:
using System;
using EatVillagers.WolfLab.Logic.Models;
using EatVillagers.WolfLab.Logic.Models.Enums;

namespace EatVillagers.WolfLab.Logic.RoleStrategies
{
    /// <summary>
    /// This exists as a placeholder for players who haven't been assigned a role
    /// yet. If this role makes it into the game somehow, it will throw exceptions
    /// becuase that shouldn't happen.
    /// </summary>
    public class SpectatorRole : RoleBase
    {
        public SpectatorRole(PlayerModel player) : base(player)
        {
        }

        public override void ExecuteDayAction()
        {
            throw new InvalidOperationException("No players with 'SpectatorRole' should be present in the game.");
        }

        public override Roles Role()
        {
            return Roles.Villager;
        }
    }
}


text:
UnityPractice
=============

Learning 3D Game Development with Unity4 book Example and Practice


text:
namespace OpenApoc
{

void InitialGameStateExtractor::extractVehicleEquipment(GameState &state, Difficulty)
{
	auto &data = this->ufo2p;

	// FIXME: Track these as some things (the weapon icon?) seem to be ordered by when they're
	// defined
	int weapon_count = 0;
	int engine_count = 0;
	int general_count = 0;

	for (unsigned i = 0; i < data.vehicle_equipment->count(); i++)
	{
		auto e = mksp<VEquipmentType>();
		auto edata = data.vehicle_equipment->get(i);

		e->name = data.vehicle_equipment_names->get(i);
		UString id = UString::format("%s%s", VEquipmentType::getPrefix(), canon_string(e->name));

		e->id = id;

		// Some data fields are common for all equipment types
		switch (edata.usable_by)
		{
			case VEHICLE_EQUIPMENT_USABLE_GROUND:
				e->users.insert(EquipmentUserType::Ground);
				break;
			case VEHICLE_EQUIPMENT_USABLE_AIR:
				e->users.insert(EquipmentUserType::Air);
				break;
			case VEHICLE_EQUIPMENT_USABLE_GROUND_AIR:
				e->users.insert(EquipmentUserType::Ground);
				e->users.insert(EquipmentUserType::Air);
				break;
			case VEHICLE_EQUIPMENT_USABLE_AMMO:
				// FIXME: Not sure what 'AMMO' usable is used for?
				e->users.insert(EquipmentUserType::Ammo);
				break;
			default:
				LogWarning("Unexpected 'usable_by' %d for ID %s", static_cast<int>(edata.usable_by),
				           id.cStr());
				continue;
		}
		e->weight = edata.weight;
		// FIXME: max_ammo 0xffff is used for 'no ammo' (IE automatically-recharging stuff)

		e->max_ammo = edata.max_ammo;
		e->ammo_type = UString::format("%d", (int)edata.ammo_type);
		// Force all sprites into the correct palette by using A_RANDOM_VEHICLES_BACKGROUND pcx
		//(I assume the parts of the palette used for this are the same on all?)
		e->equipscreen_sprite = fw().data->loadImage(UString::format(
		    "PCK:xcom3/ufodata/vehequip.pck:xcom3/ufodata/vehequip.tab:%d:xcom3/ufodata/vhawk.pcx",
		    (int)edata.sprite_idx));
		e->equipscreen_size = {edata.size_x, edata.size_y};
		e->manufacturer = {&state, data.getOrgId(edata.manufacturer)};
		e->store_space = edata.store_space;

		switch (edata.type)
		{
			case VEHICLE_EQUIPMENT_TYPE_ENGINE:
			{
				auto engData = data.vehicle_engines->get(edata.data_idx);
				e->type = VEquipmentType::VEquipmentClass::Engine;
				e->power = engData.power;
				e->top_speed = engData.top_speed;
				engine_count++;
				break;
			}
			case VEHICLE_EQUIPMENT_TYPE_WEAPON:
			{
				auto wData = data.vehicle_weapons->get(edata.data_idx);
				e->type = VEquipmentType::VEquipmentClass::Weapon;
				e->speed = wData.speed;
				e->damage = wData.damage;
				e->accuracy = wData.accuracy;
				e->fire_delay = wData.fire_delay;
				e->tail_size = wData.tail_size;
				e->guided = wData.guided != 0 ? true : false;
				e->turn_rate = wData.turn_rate;
				e->range = wData.range;
				e->firing_arc_1 = wData.firing_arc_1;
				e->firing_arc_2 = wData.firing_arc_2;
				e->point_defence = wData.point_defence != 0 ? true : false;
				e->fire_sfx =
				    fw().data->loadSample(UString::format("RAWSOUND:%d", (int)wData.fire_sfx));
				e->explosion_graphic = wData.explosion_graphic;
				e->icon = fw().data->loadImage(UString::format(
				    "PCK:xcom3/ufodata/vs_obs.pck:xcom3/ufodata/vs_obs.tab:%d", weapon_count));

				auto projectile_sprites = data.projectile_sprites->get(wData.projectile_image);
				for (int i = 0; i < e->tail_size; i++)
				{
					UString sprite_path = "";
					if (projectile_sprites.sprites[i] != 255)
					{
						sprite_path = UString::format("bulletsprites/city/%02u.png",
						                              (unsigned)projectile_sprites.sprites[i]);
					}
					else
					{
						sprite_path = ""; // a 'gap' in the projectile trail
					}
					e->projectile_sprites.push_back(fw().data->loadImage(sprite_path));
				}
				weapon_count++;
				break;
			}
			case VEHICLE_EQUIPMENT_TYPE_GENERAL:
			{
				auto gData = data.vehicle_general_equipment->get(edata.data_idx);
				e->type = VEquipmentType::VEquipmentClass::General;
				e->accuracy_modifier = gData.accuracy_modifier;
				e->cargo_space = gData.cargo_space;
				e->passengers = gData.passengers;
				e->alien_space = gData.alien_space;
				e->missile_jamming = gData.missile_jamming;
				e->shielding = gData.shielding;
				e->cloaking = gData.cloaking != 0 ? true : false;
				e->teleporting = gData.teleporting != 0 ? true : false;
				general_count++;
				break;
			}
			default:
				LogError("Unexpected vequipment type %d for ID %s", (int)e->type, id.cStr());
		}

		state.vehicle_equipment[id] = e;
	}
}

} // namespace OpenApoc


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ServiceProviderFactory</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

service.provider

Class ServiceProviderFactory

java.lang.Object

service.provider.ServiceProviderFactory

public class ServiceProviderFactory
extends java.lang.Object

This class helps to choose a service provider.

Author:

M. Usman Iftikhar, Yifan Ruan

Constructor Summary

Constructors

Constructor and Description

ServiceProviderFactory()

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static ServiceProvider
createServiceProvider()

This method helps to choose a service provider from list of available service providers.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ServiceProviderFactory

public ServiceProviderFactory()

Method Detail

createServiceProvider

public static ServiceProvider createServiceProvider()

This method helps to choose a service provider from list of available service providers.

Returns:

ServiceProvider  the specific service provider

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php
namespace app\modules\shop\controllers;

use Yii;
use yii\web\Controller;
use app\modules\shop\models\Item;

class ManageController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionItem()
    {
        $source = json_decode(file_get_contents('https://api.greencubes.org/main/items'));

        $grid = [];
        foreach($source as $line):
            $id = ($line->data === 0)?$line->id:$line->id.'.'.$line->data;
            $status = '';

            $item = Item::find()->where(['id_primary' => $line->id, 'id_meta' => $line->data])->one();
            if(!$item)
            {
                $item = new Item();
                $item->id_primary = $line->id;
                $item->id_meta = $line->data;
                $item->alias = $line->id . ($line->data !== 0 ? ('.'.$line->data) : null);
                $item->name = $line->name;
                if($item->save())
                    $status = '';
                else
                    $status = '';
            } else {
                $item->name = $line->name;
                $item->save();
            }

            $icon = $_SERVER{'DOCUMENT_ROOT'}.'/web/images/items/'.$id.'.png';
            if (!file_exists($icon))
            {
                if(file_put_contents($icon, file_get_contents($line->image_url)))
                    $status .= '';
                else
                    $status .= '';
            }

            $grid[] = ['id' => $id, 'name' => $line->name, 'status' => $status];
        endforeach;

        return $this->render('item', [
            'grid' => $grid,
        ]);
    }
}


text:
Matlab JSON v0.2
================

This package contains Matlab class to serialize/decode matlab object in
json format. The software uses org.json java package to convert json to
java object and then translates it into Matlab object.

API
---

All functions are scoped under `json` namespace.

    startup Initialize runtime environment.
    dump    Encode matlab value into a JSON string.
    load    Load matlab value from a JSON string.
    read    Load a matlab value from a JSON file.
    write   Write a matlab value into a JSON file.

Usage
-----

Add path to the directory containing `+json` before use, and call
`json.startup`.

    >> addpath /path/to/matlab-json
    >> json.startup

To serialize matlab object:

    >> X = struct('field1', magic(2), 'field2', 'hello');
    >> S = json.dump(X);
    >> disp(S);
    {"field2":"hello","field1":[[1,3],[4,2]]}

To decode json string:

    >> X = json.load(S);
    >> disp(X);
        field2: 'hello'
        field1: [2x2 double]

To read from or write to a json file.

    >> json.write(X, '/path/to/file.json');
    >> X = json.read('/path/to/file.json');

Note
----

Due to the multiple ways to represent an array in Matlab (i.e., numeric
array, cell array, or struct array), it is impossible to represent
everything in a compatible format. For example, a json string "[[1,2],[3,4]]"
can be interpreted in different ways in Matlab, such as [1,2;3,4], {1,2;3,4},
{[1,2],[3,4]}, etc. Because of this, `json.load` does not always yield the
exactly same input to `json.dump`.

This implementation is designed to maximize the ease of data exchange. For
that purpose, by default, json parser assumes the following.

 * Native arrays precede a cell array. "[1,2]" is [1,2] in matlab.
 * Row-major order. e.g., "[[1,2],[3,4]]" is [1,2;3,4] in matlab.
 * N-D array is a nested json array.
 * Any other ambiguous arrays are treated as cell array. "[]" is {}.

For example, a nested array with the same sized elements is treated as an N-D
array.

    >> x = json.load('[[[1,2],[3,4]],[[5,6],[7,8]]]')

    x(:,:,1) =
         1     2
         3     4

    x(:,:,2) =
         5     6
         7     8

The `json.load` function can optionally take an option to specify column-major
interpretation or cell-array precedence. Check `help json.load` for details.

Test
----

To run a test, use `test_all` function in the `test` directory.

    >> addpath('test');
    >> test_all;

License
-------

You may redistribute this software under BSD license.

Version
-------

 * 0.2 API changed to functions from a class.
 * 0.1 Initial release.

Links
-----

JSON in Java: http://json.org/java/


text:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { AlertService, AuthenticationService } from '../services/index';

@Component({
    selector: 'app-login',
    moduleId: module.id,
    templateUrl: 'login.component.html',
    styleUrls: ['./login.component.css']

})

export class LoginComponent implements OnInit {
    model: any = {};
    loading = false;
    returnUrl: string = 'menu';

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private authenticationService: AuthenticationService,
        private alertService: AlertService) { }

    ngOnInit() {
        // reset login status
        this.authenticationService.logout();

        // get return url from route parameters or default to '/'

        this.returnUrl = this.route.snapshot.queryParams[''] || '/';
    }

    login() {
        this.loading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
            data => {
                this.router.navigate(['menu']);
            },
            error => {
                console.log('error');
                this.alertService.error(error._body);
                this.loading = false;
            });
    }
}


text:
'use strict'

var binding = process.binding('os');

module.exports = {
	syncIO : syncIO,
};

function syncIO(func, args) {
	return binding[func].apply(binding, args);
}


text:
import pygame
from pygame.locals import *

def main():
	"Opens a window and prints events to the terminal. Closes on ESC or QUIT."
	pygame.init()
	screen = pygame.display.set_mode((640, 480))
	pygame.display.set_caption("JOYTEST")
	clock = pygame.time.Clock()
	joysticks = []
	for i in range(0, pygame.joystick.get_count()):
		joysticks.append(pygame.joystick.Joystick(i))
		joysticks[-1].init()
		print "Detected joystick '",joysticks[-1].get_name(),"'"
		print joysticks[i].get_numhats()
	while 1:
		clock.tick(60)
		print joysticks[0].get_hat(0)

		for event in pygame.event.get():
			if event.type == QUIT:
				print "Received event 'Quit', exiting."
				return
			elif event.type == KEYDOWN and event.key == K_ESCAPE:
				print "Escape key pressed, exiting."
				return
			elif event.type == KEYDOWN:
				print "Keydown,",event.key
			elif event.type == KEYUP:
				print "Keyup,",event.key
			elif event.type == MOUSEMOTION:
				print "Mouse movement detected."
			elif event.type == MOUSEBUTTONDOWN:
				print "Mouse button",event.button,"down at",pygame.mouse.get_pos()
			elif event.type == MOUSEBUTTONUP:
				print "Mouse button",event.button,"up at",pygame.mouse.get_pos()
			elif event.type == JOYAXISMOTION:
				print "Joystick '",joysticks[event.joy].get_name(),"' axis",event.axis,"motion."
			elif event.type == JOYBUTTONDOWN:
				print "Joystick '",joysticks[event.joy].get_name(),"' button",event.button,"down."
			elif event.type == JOYBUTTONUP:
				print "Joystick '",joysticks[event.joy].get_name(),"' button",event.button,"up."
			elif event.type == JOYHATMOTION:
				print "Joystick '",joysticks[event.joy].get_name(),"' hat",event.hat," moved.", event.value

if __name__ == "__main__":
        main()


text:
package org.gark87.yajom.example.test

import org.gark87.yajom.example.to.Person
import org.scalatest.FunSuite
import org.scalatest.BeforeAndAfter

class MapperTest extends FunSuite with BeforeAndAfter {
  var person: Person = null

  before {
    person = new Person
  }
}


text:
"""
Provides API logic relevant to users
"""
from flask_restful import reqparse, Resource

import auth
import util

from main import API
from model import User, UserValidator
from api.helpers import ArgumentValidator, make_list_response,\
        make_empty_ok_response, default_parser, to_compare_date
from flask import request, g
from pydash import _
from api.decorators import model_by_key, user_by_username, authorization_required, admin_required

@API.resource('/api/v1/users')
class UsersAPI(Resource):
    """Gets list of users. Uses ndb Cursor for pagination. Obtaining users is executed
    in parallel with obtaining total count via *_async functions
    """
    def get(self):
        parser = default_parser()
        args = parser.parse_args()
        compare, date = to_compare_date(args.newer, args.older, args.orderBy)

        users_query = User.qry(order_by_date=args.orderBy, compare_date=compare, date=date, time_offset=args.offset)
        users_future = users_query.fetch_page_async(args.size, start_cursor=args.cursor)

        total_count_future = users_query.count_async(keys_only=True) if args.total else False
        users, next_cursor, more = users_future.get_result()
        users = [u.to_dict(include=User.get_public_properties()) for u in users]
        total_count = total_count_future.get_result() if total_count_future else False
        return make_list_response(users, next_cursor, more, total_count)

@API.resource('/api/v1/users/<string:username>')
class UserByUsernameAPI(Resource):
    @user_by_username
    def get(self, username):
        """Loads user's properties. If logged user is admin it loads also non public properties"""
        if auth.is_admin():
            properties = User.get_private_properties()
        else:
            properties = User.get_public_properties()
        return g.user_db.to_dict(include=properties)

@API.resource('/api/v1/users/<string:key>')
class UserByKeyAPI(Resource):
    @authorization_required
    @model_by_key
    def put(self, key):
        """Updates user's properties"""
        update_properties = ['name', 'bio', 'email', 'location', 'avatar_url', 'facebook', 'github',
                             'gplus', 'linkedin', 'twitter', 'instagram']
        if auth.is_admin():
            update_properties += ['verified', 'active', 'admin']

        new_data = _.pick(request.json, update_properties)
        g.model_db.populate(**new_data)
        g.model_db.put()
        #return make_empty_ok_response()
        if auth.is_admin():
            properties = User.get_private_properties()
        else:
            properties = User.get_public_properties()
        return g.model_db.to_dict(include=properties)

    @authorization_required
    @model_by_key
    def post(self, key):
        """Updates user's properties"""
        update_properties = ['name', 'bio', 'email', 'location', 'avatar_url', 'facebook', 'github',
                             'gplus', 'linkedin', 'twitter', 'instagram']
        if auth.is_admin():
            update_properties += ['verified', 'active', 'admin']

        new_data = _.pick(request.json, update_properties)
        g.model_db.populate(**new_data)
        g.model_db.put()
        #return make_empty_ok_response()
        if auth.is_admin():
            properties = User.get_private_properties()
        else:
            properties = User.get_public_properties()
        return g.model_db.to_dict(include=properties)

    @admin_required
    @model_by_key
    def delete(self, key):
        """Deletes user"""
        g.model_key.delete()
        return make_empty_ok_response()

@API.resource('/api/v1/users/<string:key>/password')
class UserPasswordAPI(Resource):
    @authorization_required
    @model_by_key
    def post(self, key):
        """Changes user's password"""
        parser = reqparse.RequestParser()
        parser.add_argument('currentPassword', type=UserValidator.create('password', required=False), dest='current_password')
        parser.add_argument('newPassword', type=UserValidator.create('password'), dest='new_password')
        args = parser.parse_args()
        # Users, who signed up via social networks have empty password_hash, so they have to be allowed
        # to change it as well
        if g.model_db.password_hash != '' and not g.model_db.has_password(args.current_password):
            raise ValueError('Given password is incorrect.')
        g.model_db.password_hash = util.password_hash(args.new_password)
        g.model_db.put()
        return make_empty_ok_response()


text:
'use strict';
var async = require('async');
var _und = require('underscore');
var path = require('path');

// for optional route error handler
var routeErrorHandlerPath = path.join(global.ngServer.application.root,'lib/routeErrorHandler.js');
exports.routeErrorHandler = undefined;
try {
    exports.routeErrorHandler = require(routeErrorHandlerPath);
} catch (err) {
}

/**
 * Given a handler function and optional 'pre' and 'post' functions this function will
 * return a single handler(req,res) function that correctly chains the provided
 * functions so they run in a series. Though all the parameters are actually passed in a
 * parameter object, the param documentation for this function describes the parameter
 * object.
 *
 * @param {function|function[]} aHandlerFn an HTTP handler function taking params (req,res,cb)
 * which are the standard node.js HTTP request and response objects plus a callback
 * to indicate when the handler function is completed.
 * @param {function|function[]} [beforeFns] Function(s) to run before aHandlerFn also
 * taking arguments (req,res,cb).
 * @param {function|function[]} [afterFns] Function(s) to run after aHandlerFn also
 * taking a arguments (req,res,cb).
 * @param {function} [requestCallback] A callback function that will be called when the
 * current HTTP request completes. It will be called with a single error argument
 * if an error occured.
 * @param {object} [filters] An object containing global filters. Optional.
 * @param {string[]} [excludeFilters] An optional array of strings indicating which set of globals filters
 * to NOT apply.
 * @returns {function} A function to execute when clients request the route.
 */
exports.chainRequestHandlers = function(params, cb) {
    if (!params) {
        logger.warn('chainRequestHandlers received NO paramters, returning null.');
        return null;
    }

    var util = require('util');
    var file = params.file || '(no file)';
    var routeName = params.routeName || '(no route)';
    var aHandlerFn = params.aHandlerFn;
    var beforeFns = params.beforeFns;
    var afterFns = params.afterFns;
    var filters = params.filters;
    var excludeFilters = params.excludeFilters || [];
    var excludeAllFilters = params.excludeAllFilters || false;
    var requestCallback = cb;

    logger.debug('chainRequestHandlers processing file: '+file+', routeName: '+routeName);

    if('function' !== typeof aHandlerFn && !_und.isArray(aHandlerFn)) {
        logger.warn('chainRequestHandlers received a bad aHandlerFn, route not processed. '+
            'aHandlerFn: '+typeof aHandlerFn+' : '+util.inspect(aHandlerFn));
        return null;
    }

    // normalize beforeFns and afterFns to arrays (they can be arrays or a single function)
    // we make them all arrays to simplify processing
    if (typeof aHandlerFn === 'function')
        aHandlerFn = [ aHandlerFn ];
    if (typeof afterFns === 'function')
        afterFns = [ afterFns ];
    if (typeof beforeFns === 'function')
        beforeFns = [ beforeFns ];

    // more normalization of inputs, it makes processing easier.
    if (filters) {
        if (filters.before && !_und.isArray(filters.before))
            filters.before = [ filters.before ];
        if (filters.around && !_und.isArray(filters.around))
            filters.around = [ filters.around ];
        if (filters.after && !_und.isArray(filters.after))
            filters.after = [ filters.after ];
    }

    // We place all the functions, global filters + route-specific function into
    // one of the two following arrays, beforeArray are functions that execute, in
    // order, before the route 'action' and after is the same, but after the route
    // 'action'.
    var beforeArray = [];
    var afterArray = [];

    // First we process the global before and around filters respectively
    if (! excludeAllFilters) {
        applyFilter(filters, 'before', routeName, excludeFilters, beforeArray);
        applyFilter(filters, 'around', routeName, excludeFilters, beforeArray);
    }

    // Handle the route's before functions
    // Then are the route-specific functions to run before aHandlerFn
    if (beforeFns && _und.isArray(beforeFns)) {
        beforeArray = beforeArray.concat(beforeFns);
    }

    // Handle the route's after functions
    // First are the controller-specific function that run after aHandlerFn
    if (afterFns && _und.isArray(afterFns)) {
        afterArray = afterArray.concat(afterFns);
    }

    // Next are the global around and after filters respectively
    if (! excludeAllFilters) {
        applyFilter(filters, 'around', routeName, excludeFilters, afterArray);
        applyFilter(filters, 'after',  routeName, excludeFilters, afterArray);
    }

    /* - Uncomment if you want to see what is running
     try {
     // debugging display functions to be run in order that they are run
     logger.debug('********************************************************************************');
     logger.debug('Before chain');
     beforeArray.forEach(function(element, index, array) {
     logger.debug(index + ':\n' + element.toString());
     });

     logger.debug('During chain');
     aHandlerFn.forEach(function(element, index, array) {
     logger.debug(index + ':\n' + element.toString());
     });

     logger.debug('After chain');
     afterArray.forEach(function(element, index, array) {
     logger.debug(index + ':\n' + element.toString());
     });
     logger.debug('********************************************************************************');
     } catch(err) {
     }
     */

    // We return a funtion to be executed when the route is requested by clients.
    return function(req, res) {

        // process before, during and after functions
        function asyncApply(fn){ return async.apply(fn,req,res); }
        var funcChains = [beforeArray, aHandlerFn, afterArray].map(function(arr){
            return arr.map(function (fn){
                return async.apply(fn,req,res);
            });
        });

        // put them all together
        var funcChain = _und.flatten(funcChains);

        // execute the set of all functions and call the user-specified callback when done or
        // upon an error.
        function setUpAndCallChain() {
            async.series(
                funcChain,
                function(err){
                    requestCallback(err);
                    if (err && !res.headerSent) {
                        console.error('ERROR:'+util.inspect(err));
                        if (err.code) {
                            var message = err.responseMessage || err.message || 'Internal Server Error';
                            res.send(message, err.code);
                        } else {
                            res.send('Internal Server Error(500)', 500);
                        }
                    }
                }
            );
        }

        // create a domain to catch errors and pass data, if there is a route
        // error handler
        if (global.ngServer.error && global.ngServer.error.routeErrorHandlerExists && exports.routeErrorHandler) {

            var ngRequest = require('../util/domain').create();

            // set the domain to catch any exceptions or errors
            ngRequest.on('error', function(err) {
                if (exports.routeErrorHandler.errorHandler) {
                    exports.routeErrorHandler.errorHandler(err, req, res, function(err) {
                        ngRequest.dispose();    // dispose of the domain
                    });
                } else {
                    ngRequest.dispose();    // dispose of the domain
                }
            });

            // run the express middleware in a domain because we have a route error handler
            ngRequest.run(setUpAndCallChain);
        } else {
            // Don't run the middleware in a domain, if there is no route error handler
            setUpAndCallChain();
        }
    };
};

/**
 * applyFilter applies a global filter for a single route and will exclude the application if
 * the route is in excludeFilters. If the route is included, the global filter's function is
 * placed in the function array.
 * @param {object} filters An object containing before, around and after filters, each with a
 * name and an action.
 * @param {string} whichFilter A string with either 'before', 'around' or 'after', to specifiy which
 * filter to process.
 * @param {string} routeName The name of the route being processed. This would be the path part of
 * the URL.
 * @param {string[]} excludeFilter An array of route names indicating which filters this route is
 * excluding.
 * @param {function[]} fnArray An array of functions to be run when clients request the route.
 */
function applyFilter(filters, whichFilter, routeName, excludeFilters, fnArray) {

    var util= require('util');

    // There may be no filters defined, or this filter may not be defined or
    // this filter may be in the set of excludeFilters for this route
    if (filters === undefined || filters[whichFilter] === undefined ||
        !PassesFilterQualifiers(routeName, filters[whichFilter])) {
        logger.debug('applyFilter not found: \''+whichFilter+'\' for route: '+routeName+'. '+
            'This is expected if you have no filters defined.');
        return;
    }

    // we really expected an array
    if (!_und.isArray(filters[whichFilter])) {
        logger.warn('applyFilter not found: \''+whichFilter+'\' for route: '+routeName+
            ' expected an array of filters, received: '+util.inspect(filters[whichFilter]));
        return;
    }

    logger.debug('applyFilter is processing '+whichFilter+' for route: '+routeName);

    // process each entry in this filter
    for (var i=0; i<filters[whichFilter].length; ++i) {
        // check if this filter's name is in the route's excludeFilters array, if so do not add it
        if (excludeFilters.indexOf(filters[whichFilter][i].name) === -1) {
            // now check if this route passes this filter's except/only clauses
            if (PassesFilterQualifiers(routeName, filters[whichFilter][i])) {
                logger.debug('Adding '+filters[whichFilter][i].name+' to route: '+routeName);
                fnArray.push(filters[whichFilter][i].action);
            } else {
                logger.debug('Excluding '+filters[whichFilter][i].name+' from route: '+routeName+' based on filter qualifiers (except/only)');
            }
        } else {
            logger.debug('Excluding '+filters[whichFilter][i].name+' from route: '+routeName+' due to route\'s exclude filters.');
        }
    }
}

/**
 * A convenience function to contain the logic for passing both except and only filters.
 * Remember, you can have only except or only qualifiers, not both. Passing the filter means
 * the function can be chained for execution.
 * @param {string} routeName The name of the route being tested for passing the filter.
 * @param {object} gfilter A global filter type either before, around or after.
 * @returns {boolean} True, if the function passes and can be chained, false otherwise.
 */
function PassesFilterQualifiers(routeName, filter) {
    var result = true;

    // A filter may be either a single object with the form:
    // {
    //      name: 'Filter Name',
    //      action: filterFunc,
    //      except: [ routeName1, routeName2,...],
    //      only: [ routeName1, routeName2,...]
    // };
    // Though you only have either an except or only, not both.
    //
    if (_und.isArray(filter)) {
        result = false;
        // We test every filter against the current route name, looking at the
        // except and only clauses. A single failure means do not process this route.
        for (var i=0; i<filter.length; ++i) {
            result |= CheckOneQualifier(routeName, filter[i]);
        }
    } else if (_und.isObject(filter)) {
        result = CheckOneQualifier(routeName, filter);
    }

    return result;
}

/**
 * For a given route name and filter, this function will check if the route
 * should be processed or excluded from processing, depending on the except and
 * only clauses in the given filter. If there is no filter or no except or only
 * clauses, then we process the route.
 * @param {string} routeName The name of the route, e.g. the path.
 * @param {object} filter One of the filter objects for before, around or after.
 * @returns {boolean} True, if the route should be processed and false otherwise.
 */
function CheckOneQualifier(routeName, filter) {

    var util = require('util');

    // if there is no filter, we should process the route
    if (!filter)
        return true;

    // if there are no except and no only qualifiers, process the route
    if (filter.except === undefined && filter.only === undefined)
        return true;

    // if there are exceptions and the exceptions are an array, then we
    // check if the route name is NOT in the index, and if so, we
    // process the route.
    if (filter.except !== undefined && _und.isArray(filter.except)) {
        if (filter.except.indexOf(routeName) === -1) {
            return true;
        } else {
            return false;
        }
        // If there is an only clause and it's an array as we expect then
        // if the route is in the only filter, we process the route.
    } else if (filter.only !== undefined && _und.isArray(filter.only)) {
        if (filter.only.indexOf(routeName) > -1) {
            return true;
        } else {
            return false;
        }
    }

    return true; // return true because we can't filter on except or only
}


text:
function web_search() {
  emulate -L zsh

  # define search engine URLS
  typeset -A urls
  urls=(
    $ZSH_WEB_SEARCH_ENGINES
    google      "https://www.google.com/search?q="
    bing        "https://www.bing.com/search?q="
    yahoo       "https://search.yahoo.com/search?p="
    duckduckgo  "https://www.duckduckgo.com/?q="
    startpage   "https://www.startpage.com/do/search?q="
    yandex      "https://yandex.ru/yandsearch?text="
    github      "https://github.com/search?q="
    baidu       "https://www.baidu.com/s?wd="
    ecosia      "https://www.ecosia.org/search?q="
    goodreads   "https://www.goodreads.com/search?q="
    qwant       "https://www.qwant.com/?q="
    givero      "https://www.givero.com/search?q="
    stackoverflow  "https://stackoverflow.com/search?q="
    wolframalpha   "https://www.wolframalpha.com/input/?i="
    archive     "https://web.archive.org/web/*/"
    scholar        "https://scholar.google.com/scholar?q="
  )

  # check whether the search engine is supported
  if [[ -z "$urls[$1]" ]]; then
    echo "Search engine '$1' not supported."
    return 1
  fi

  # search or go to main page depending on number of arguments passed
  if [[ $# -gt 1 ]]; then
    # build search url:
    # join arguments passed with '+', then append to search engine URL
    url="${urls[$1]}${(j:+:)@[2,-1]}"
  else
    # build main page url:
    # split by '/', then rejoin protocol (1) and domain (2) parts with '//'
    url="${(j://:)${(s:/:)urls[$1]}[1,2]}"
  fi

  open_command "$url"
}

alias bing='web_search bing'
alias google='web_search google'
alias yahoo='web_search yahoo'
alias ddg='web_search duckduckgo'
alias sp='web_search startpage'
alias yandex='web_search yandex'
alias github='web_search github'
alias baidu='web_search baidu'
alias ecosia='web_search ecosia'
alias goodreads='web_search goodreads'
alias qwant='web_search qwant'
alias givero='web_search givero'
alias stackoverflow='web_search stackoverflow'
alias wolframalpha='web_search wolframalpha'
alias archive='web_search archive'
alias scholar='web_search scholar'

#add your own !bang searches here
alias wiki='web_search duckduckgo \!w'
alias news='web_search duckduckgo \!n'
alias youtube='web_search duckduckgo \!yt'
alias map='web_search duckduckgo \!m'
alias image='web_search duckduckgo \!i'
alias ducky='web_search duckduckgo \!'

# other search engine aliases
if [[ ${#ZSH_WEB_SEARCH_ENGINES} -gt 0 ]]; then
  typeset -A engines
  engines=($ZSH_WEB_SEARCH_ENGINES)
  for key in ${(k)engines}; do
    alias "$key"="web_search $key"
  done
  unset engines key
fi


text:
package com.google.errorprone.bugpatterns.flogger;

import static com.google.errorprone.util.ASTHelpers.getType;

import com.google.errorprone.VisitorState;
import com.sun.source.tree.Tree;
import com.sun.tools.javac.code.Type;

/** Analysis helpers for flogger. */
final class FloggerHelpers {

  private static final char STRING_FORMAT = 's';

  static char inferFormatSpecifier(Tree piece, VisitorState state) {
    Type type = getType(piece);
    return inferFormatSpecifier(type, state);
  }

  static char inferFormatSpecifier(Type type, VisitorState state) {
    if (type == null) {
      return STRING_FORMAT;
    }
    switch (state.getTypes().unboxedTypeOrType(type).getKind()) {
      case INT:
      case LONG:
        return 'd';
      case FLOAT:
      case DOUBLE:
        return 'g';
      case BOOLEAN:
        // %b is identical to %s in Flogger, but not in String.format, so it might be risky
        // to train people to prefer it. (In format() a Boolean "null" becomes "false",)
        return STRING_FORMAT;
      default:
        return STRING_FORMAT;
    }
  }

  private FloggerHelpers() {}
}


text:
package io.spine.server.event.model.given.subscriber;

import io.spine.core.CommandContext;
import io.spine.core.Subscribe;
import io.spine.model.contexts.projects.command.SigCreateProject;
import io.spine.model.contexts.projects.rejection.ProjectRejections.SigCannotCreateProject;
import io.spine.server.event.AbstractEventSubscriber;

/**
 * A subscriber that has Rejection events subscriptions.
 */
public final class RejectionSubscriber extends AbstractEventSubscriber {

    @Subscribe
    void rejectionWithCommand(SigCannotCreateProject rejection,
                              SigCreateProject command) {
        // do nothing.
    }

    @Subscribe
    void rejectionWithCommandAndCtx(SigCannotCreateProject rejection,
                                    SigCreateProject cmd,
                                    CommandContext ctx) {
        // do nothing.
    }

    @Subscribe
    void rejectionWithoutCommand(SigCannotCreateProject rejection) {
        // do nothing.
    }

    @Subscribe
    void rejectionWithCtx(SigCannotCreateProject rejection,
                          CommandContext ctx) {
        // do nothing.
    }
}


text:
#include <hpl_adc_async.h>
#include <hpl_adc_dma.h>
#include <hpl_adc_sync.h>
#include <utils_assert.h>
#include <utils_repeat_macro.h>
#include <hpl_adc_config.h>

#ifndef CONF_ADC_0_ENABLE
#define CONF_ADC_0_ENABLE 0
#endif
#ifndef CONF_ADC_1_ENABLE
#define CONF_ADC_1_ENABLE 0
#endif

/**
 * \brief Macro is used to fill ADC configuration structure based on its number
 *
 * \param[in] n The number of structures
 */

#define ADC_CONFIGURATION(n)                                                                                \
	{                                                                                \
		(n),                                                                                \
		    (CONF_ADC_##n##_RUNSTDBY << ADC_CTRLA_RUNSTDBY_Pos) | (CONF_ADC_##n##_ONDEMAND << ADC_CTRLA_ONDEMAND_Pos)  \
		        | (CONF_ADC_##n##_SLAVEEN << ADC_CTRLA_SLAVEEN_Pos),                                                   \
		    ADC_CTRLB_PRESCALER(CONF_ADC_##n##_PRESCALER),                                                             \
		    (CONF_ADC_##n##_REFCOMP << ADC_REFCTRL_REFCOMP_Pos) | ADC_REFCTRL_REFSEL(CONF_ADC_##n##_REFSEL),           \
		    (CONF_ADC_##n##_WINMONEO << ADC_EVCTRL_WINMONEO_Pos)                                                       \
		        | (CONF_ADC_##n##_RESRDYEO << ADC_EVCTRL_RESRDYEO_Pos)                                                 \
		        | (CONF_ADC_##n##_STARTINV << ADC_EVCTRL_STARTINV_Pos)                                                 \
		        | (CONF_ADC_##n##_FLUSHINV << ADC_EVCTRL_FLUSHINV_Pos)                                                 \
		        | (CONF_ADC_##n##_STARTEI << ADC_EVCTRL_STARTEI_Pos)                                                   \
		        | (CONF_ADC_##n##_FLUSHEI << ADC_EVCTRL_FLUSHEI_Pos),                                                  \
		    ADC_INPUTCTRL_MUXNEG(CONF_ADC_##n##_MUXNEG) | ADC_INPUTCTRL_MUXPOS(CONF_ADC_##n##_MUXPOS),                 \
		    ADC_CTRLC_DUALSEL(CONF_ADC_##n##_DUALSEL) | ADC_CTRLC_WINMODE(CONF_ADC_##n##_WINMODE)                      \
		        | (CONF_ADC_##n##_R2R << ADC_CTRLC_R2R_Pos) | ADC_CTRLC_RESSEL(CONF_ADC_##n##_RESSEL)                  \
		        | (CONF_ADC_##n##_CORREN << ADC_CTRLC_CORREN_Pos) | (CONF_ADC_##n##_FREERUN << ADC_CTRLC_FREERUN_Pos)  \
		        | (CONF_ADC_##n##_LEFTADJ << ADC_CTRLC_LEFTADJ_Pos)                                                    \
		        | (CONF_ADC_##n##_DIFFMODE << ADC_CTRLC_DIFFMODE_Pos),                                                 \
		    ADC_AVGCTRL_ADJRES(CONF_ADC_##n##_ADJRES) | ADC_AVGCTRL_SAMPLENUM(CONF_ADC_##n##_SAMPLENUM),               \
		    (CONF_ADC_##n##_OFFCOMP << ADC_SAMPCTRL_OFFCOMP_Pos) | ADC_SAMPCTRL_SAMPLEN(CONF_ADC_##n##_SAMPLEN),       \
		    ADC_WINLT_WINLT(CONF_ADC_##n##_WINLT), ADC_WINUT_WINUT(CONF_ADC_##n##_WINUT),                              \
		    ADC_GAINCORR_GAINCORR(CONF_ADC_##n##_GAINCORR), ADC_OFFSETCORR_OFFSETCORR(CONF_ADC_##n##_OFFSETCORR),      \
		    CONF_ADC_##n##_DBGRUN << ADC_DBGCTRL_DBGRUN_Pos, ADC_SEQCTRL_SEQEN(CONF_ADC_##n##_SEQEN),                  \
	}

/**
 * \brief ADC configuration
 */
struct adc_configuration {
	uint8_t                  number;
	hri_adc_ctrla_reg_t      ctrl_a;
	hri_adc_ctrlb_reg_t      ctrl_b;
	hri_adc_refctrl_reg_t    ref_ctrl;
	hri_adc_evctrl_reg_t     ev_ctrl;
	hri_adc_inputctrl_reg_t  input_ctrl;
	hri_adc_ctrlc_reg_t      ctrl_c;
	hri_adc_avgctrl_reg_t    avg_ctrl;
	hri_adc_sampctrl_reg_t   samp_ctrl;
	hri_adc_winlt_reg_t      win_lt;
	hri_adc_winut_reg_t      win_ut;
	hri_adc_gaincorr_reg_t   gain_corr;
	hri_adc_offsetcorr_reg_t offset_corr;
	hri_adc_dbgctrl_reg_t    dbg_ctrl;
	hri_adc_seqctrl_reg_t    seq_ctrl;
};

#define ADC_AMOUNT (CONF_ADC_0_ENABLE + CONF_ADC_1_ENABLE)

/**
 * \brief Array of ADC configurations
 */
static const struct adc_configuration _adcs[] = {
#if CONF_ADC_0_ENABLE == 1
    ADC_CONFIGURATION(0),
#endif
#if CONF_ADC_1_ENABLE == 1
    ADC_CONFIGURATION(1),
#endif
};

static void _adc_set_reference_source(void *const hw, const adc_reference_t reference);

/**
 * \brief Retrieve ordinal number of the given adc hardware instance
 */
static uint8_t _adc_get_hardware_index(const void *const hw)
{
	return ((uint32_t)hw - (uint32_t)ADC0) >> 10;
}

/** \brief Return the pointer to register settings of specific ADC
 *  \param[in] hw_addr The hardware register base address.
 *  \return Pointer to register settings of specific ADC.
 */
static uint8_t _adc_get_regs(const uint32_t hw_addr)
{
	uint8_t n = _adc_get_hardware_index((const void *)hw_addr);
	uint8_t i;

	for (i = 0; i < sizeof(_adcs) / sizeof(struct adc_configuration); i++) {
		if (_adcs[i].number == n) {
			return i;
		}
	}

	ASSERT(false);
	return 0;
}

/**
 * \brief Retrieve IRQ number for the given hardware instance
 */
static uint8_t _adc_get_irq_num(const struct _adc_async_device *const device)
{
	return ADC0_IRQn + _adc_get_hardware_index(device->hw);
}

/**
 * \brief Init irq param with the given afec hardware instance
 */
static void _adc_init_irq_param(const void *const hw, struct _adc_async_device *dev)
{
}

/**
 * \brief Initialize ADC
 *
 * \param[in] hw The pointer to hardware instance
 * \param[in] i The number of hardware instance
 */
static int32_t _adc_init(void *const hw, const uint8_t i)
{
	uint16_t calib_reg = 0;
	if (hw == ADC0) {
		calib_reg = ADC_CALIB_BIASREFBUF((*(uint32_t *)ADC0_FUSES_BIASREFBUF_ADDR >> ADC0_FUSES_BIASREFBUF_Pos))
		            | ADC_CALIB_BIASCOMP((*(uint32_t *)ADC0_FUSES_BIASCOMP_ADDR >> ADC0_FUSES_BIASCOMP_Pos));
	} else if (hw == ADC1) {
		calib_reg = ADC_CALIB_BIASREFBUF((*(uint32_t *)ADC1_FUSES_BIASREFBUF_ADDR >> ADC1_FUSES_BIASREFBUF_Pos))
		            | ADC_CALIB_BIASCOMP((*(uint32_t *)ADC1_FUSES_BIASCOMP_ADDR >> ADC1_FUSES_BIASCOMP_Pos));
	}

	if (!hri_adc_is_syncing(hw, ADC_SYNCBUSY_SWRST)) {
		if (hri_adc_get_CTRLA_reg(hw, ADC_CTRLA_ENABLE)) {
			hri_adc_clear_CTRLA_ENABLE_bit(hw);
			hri_adc_wait_for_sync(hw, ADC_SYNCBUSY_ENABLE);
		}
		hri_adc_write_CTRLA_reg(hw, ADC_CTRLA_SWRST);
	}
	hri_adc_wait_for_sync(hw, ADC_SYNCBUSY_SWRST);

	hri_adc_write_CALIB_reg(hw, calib_reg);
	hri_adc_write_CTRLB_reg(hw, _adcs[i].ctrl_b);
	hri_adc_write_REFCTRL_reg(hw, _adcs[i].ref_ctrl);
	hri_adc_write_EVCTRL_reg(hw, _adcs[i].ev_ctrl);
	hri_adc_write_INPUTCTRL_reg(hw, _adcs[i].input_ctrl);
	hri_adc_write_CTRLC_reg(hw, _adcs[i].ctrl_c);
	hri_adc_write_AVGCTRL_reg(hw, _adcs[i].avg_ctrl);
	hri_adc_write_SAMPCTRL_reg(hw, _adcs[i].samp_ctrl);
	hri_adc_write_WINLT_reg(hw, _adcs[i].win_lt);
	hri_adc_write_WINUT_reg(hw, _adcs[i].win_ut);
	hri_adc_write_GAINCORR_reg(hw, _adcs[i].gain_corr);
	hri_adc_write_OFFSETCORR_reg(hw, _adcs[i].offset_corr);
	hri_adc_write_DBGCTRL_reg(hw, _adcs[i].dbg_ctrl);
	hri_adc_write_SEQCTRL_reg(hw, _adcs[i].seq_ctrl);
	hri_adc_write_CTRLA_reg(hw, _adcs[i].ctrl_a);

	return ERR_NONE;
}

/**
 * \brief De-initialize ADC
 *
 * \param[in] hw The pointer to hardware instance
 */
static inline void _adc_deinit(void *hw)
{
	hri_adc_clear_CTRLA_ENABLE_bit(hw);
	hri_adc_set_CTRLA_SWRST_bit(hw);
}

/**
 * \brief Initialize ADC
 */
int32_t _adc_sync_init(struct _adc_sync_device *const device, void *const hw)
{
	ASSERT(device);

	device->hw = hw;

	return _adc_init(hw, _adc_get_regs((uint32_t)hw));
}

/**
 * \brief Initialize ADC
 */
int32_t _adc_async_init(struct _adc_async_device *const device, void *const hw)
{
	int32_t init_status;

	ASSERT(device);

	init_status = _adc_init(hw, _adc_get_regs((uint32_t)hw));
	if (init_status) {
		return init_status;
	}
	device->hw = hw;
	_adc_init_irq_param(hw, device);
	NVIC_DisableIRQ(_adc_get_irq_num(device));
	NVIC_ClearPendingIRQ(_adc_get_irq_num(device));
	NVIC_EnableIRQ(_adc_get_irq_num(device));

	return ERR_NONE;
}

/**
 * \brief Initialize ADC
 */
int32_t _adc_dma_init(struct _adc_dma_device *const device, void *const hw)
{
	ASSERT(device);

	device->hw = hw;

	return _adc_init(hw, _adc_get_regs((uint32_t)hw));
}

/**
 * \brief De-initialize ADC
 */
void _adc_sync_deinit(struct _adc_sync_device *const device)
{
	_adc_deinit(device->hw);
}

/**
 * \brief De-initialize ADC
 */
void _adc_async_deinit(struct _adc_async_device *const device)
{
	NVIC_DisableIRQ(_adc_get_irq_num(device));
	NVIC_ClearPendingIRQ(_adc_get_irq_num(device));

	_adc_deinit(device->hw);
}

/**
 * \brief De-initialize ADC
 */
void _adc_dma_deinit(struct _adc_dma_device *const device)
{
	_adc_deinit(device->hw);
}

/**
 * \brief Enable ADC
 */
void _adc_sync_enable_channel(struct _adc_sync_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_set_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Enable ADC
 */
void _adc_async_enable_channel(struct _adc_async_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_set_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Enable ADC
 */
void _adc_dma_enable_channel(struct _adc_dma_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_set_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Disable ADC
 */
void _adc_sync_disable_channel(struct _adc_sync_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_clear_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Disable ADC
 */
void _adc_async_disable_channel(struct _adc_async_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_clear_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Disable ADC
 */
void _adc_dma_disable_channel(struct _adc_dma_device *const device, const uint8_t channel)
{
	(void)channel;

	hri_adc_clear_CTRLA_ENABLE_bit(device->hw);
}

/**
 * \brief Return address of ADC DMA source
 */
uint32_t _adc_get_source_for_dma(struct _adc_dma_device *const device)
{
	return (uint32_t) & (((Adc *)(device->hw))->RESULT.reg);
}

/**
 * \brief Retrieve ADC conversion data size
 */
uint8_t _adc_sync_get_data_size(const struct _adc_sync_device *const device)
{
	return hri_adc_read_CTRLC_RESSEL_bf(device->hw) == ADC_CTRLC_RESSEL_8BIT_Val ? 1 : 2;
}

/**
 * \brief Retrieve ADC conversion data size
 */
uint8_t _adc_async_get_data_size(const struct _adc_async_device *const device)
{
	return hri_adc_read_CTRLC_RESSEL_bf(device->hw) == ADC_CTRLC_RESSEL_8BIT_Val ? 1 : 2;
}

/**
 * \brief Retrieve ADC conversion data size
 */
uint8_t _adc_dma_get_data_size(const struct _adc_dma_device *const device)
{
	return hri_adc_read_CTRLC_RESSEL_bf(device->hw) == ADC_CTRLC_RESSEL_8BIT_Val ? 1 : 2;
}

/**
 * \brief Check if conversion is done
 */
bool _adc_sync_is_channel_conversion_done(const struct _adc_sync_device *const device, const uint8_t channel)
{
	(void)channel;

	return hri_adc_get_interrupt_RESRDY_bit(device->hw);
}

/**
 * \brief Check if conversion is done
 */
bool _adc_async_is_channel_conversion_done(const struct _adc_async_device *const device, const uint8_t channel)
{
	(void)channel;

	return hri_adc_get_interrupt_RESRDY_bit(device->hw);
}

/**
 * \brief Check if conversion is done
 */
bool _adc_dma_is_conversion_done(const struct _adc_dma_device *const device)
{
	return hri_adc_get_interrupt_RESRDY_bit(device->hw);
}

/**
 * \brief Make conversion
 */
void _adc_sync_convert(struct _adc_sync_device *const device)
{
	hri_adc_set_SWTRIG_START_bit(device->hw);
}

/**
 * \brief Make conversion
 */
void _adc_async_convert(struct _adc_async_device *const device)
{
	hri_adc_set_SWTRIG_START_bit(device->hw);
}

/**
 * \brief Make conversion
 */
void _adc_dma_convert(struct _adc_dma_device *const device)
{
	hri_adc_set_SWTRIG_START_bit(device->hw);
}

/**
 * \brief Retrieve the conversion result
 */
uint16_t _adc_sync_read_channel_data(const struct _adc_sync_device *const device, const uint8_t channel)
{
	(void)channel;

	return hri_adc_read_RESULT_reg(device->hw);
}

/**
 * \brief Retrieve the conversion result
 */
uint16_t _adc_async_read_channel_data(const struct _adc_async_device *const device, const uint8_t channel)
{
	(void)channel;

	return hri_adc_read_RESULT_reg(device->hw);
}

/**
 * \brief Set reference source
 */
void _adc_sync_set_reference_source(struct _adc_sync_device *const device, const adc_reference_t reference)
{
	_adc_set_reference_source(device->hw, reference);
}

/**
 * \brief Set reference source
 */
void _adc_async_set_reference_source(struct _adc_async_device *const device, const adc_reference_t reference)
{
	_adc_set_reference_source(device->hw, reference);
}

/**
 * \brief Set reference source
 */
void _adc_dma_set_reference_source(struct _adc_dma_device *const device, const adc_reference_t reference)
{
	_adc_set_reference_source(device->hw, reference);
}

/**
 * \brief Set resolution
 */
void _adc_sync_set_resolution(struct _adc_sync_device *const device, const adc_resolution_t resolution)
{
	hri_adc_write_CTRLC_RESSEL_bf(device->hw, resolution);
}

/**
 * \brief Set resolution
 */
void _adc_async_set_resolution(struct _adc_async_device *const device, const adc_resolution_t resolution)
{
	hri_adc_write_CTRLC_RESSEL_bf(device->hw, resolution);
}

/**
 * \brief Set resolution
 */
void _adc_dma_set_resolution(struct _adc_dma_device *const device, const adc_resolution_t resolution)
{
	hri_adc_write_CTRLC_RESSEL_bf(device->hw, resolution);
}

/**
 * \brief Set channels input sources
 */
void _adc_sync_set_inputs(struct _adc_sync_device *const device, const adc_pos_input_t pos_input,
                          const adc_neg_input_t neg_input, const uint8_t channel)
{
	(void)channel;

	hri_adc_write_INPUTCTRL_MUXPOS_bf(device->hw, pos_input);
	hri_adc_write_INPUTCTRL_MUXNEG_bf(device->hw, neg_input);
}

/**
 * \brief Set channels input sources
 */
void _adc_async_set_inputs(struct _adc_async_device *const device, const adc_pos_input_t pos_input,
                           const adc_neg_input_t neg_input, const uint8_t channel)
{
	(void)channel;

	hri_adc_write_INPUTCTRL_MUXPOS_bf(device->hw, pos_input);
	hri_adc_write_INPUTCTRL_MUXNEG_bf(device->hw, neg_input);
}

/**
 * \brief Set channels input source
 */
void _adc_dma_set_inputs(struct _adc_dma_device *const device, const adc_pos_input_t pos_input,
                         const adc_neg_input_t neg_input, const uint8_t channel)
{
	(void)channel;

	hri_adc_write_INPUTCTRL_MUXPOS_bf(device->hw, pos_input);
	hri_adc_write_INPUTCTRL_MUXNEG_bf(device->hw, neg_input);
}

/**
 * \brief Set thresholds
 */
void _adc_sync_set_thresholds(struct _adc_sync_device *const device, const adc_threshold_t low_threshold,
                              const adc_threshold_t up_threshold)
{
	hri_adc_write_WINLT_reg(device->hw, low_threshold);
	hri_adc_write_WINUT_reg(device->hw, up_threshold);
}

/**
 * \brief Set thresholds
 */
void _adc_async_set_thresholds(struct _adc_async_device *const device, const adc_threshold_t low_threshold,
                               const adc_threshold_t up_threshold)
{
	hri_adc_write_WINLT_reg(device->hw, low_threshold);
	hri_adc_write_WINUT_reg(device->hw, up_threshold);
}

/**
 * \brief Set thresholds
 */
void _adc_dma_set_thresholds(struct _adc_dma_device *const device, const adc_threshold_t low_threshold,
                             const adc_threshold_t up_threshold)
{
	hri_adc_write_WINLT_reg(device->hw, low_threshold);
	hri_adc_write_WINUT_reg(device->hw, up_threshold);
}

/**
 * \brief Set gain
 */
void _adc_sync_set_channel_gain(struct _adc_sync_device *const device, const uint8_t channel, const adc_gain_t gain)
{
	(void)device, (void)channel, (void)gain;
}

/**
 * \brief Set gain
 */
void _adc_async_set_channel_gain(struct _adc_async_device *const device, const uint8_t channel, const adc_gain_t gain)
{
	(void)device, (void)channel, (void)gain;
}

/**
 * \brief Set gain
 */
void _adc_dma_set_channel_gain(struct _adc_dma_device *const device, const uint8_t channel, const adc_gain_t gain)
{
	(void)device, (void)channel, (void)gain;
}

/**
 * \brief Set conversion mode
 */
void _adc_sync_set_conversion_mode(struct _adc_sync_device *const device, const enum adc_conversion_mode mode)
{
	if (ADC_CONVERSION_MODE_FREERUN == mode) {
		hri_adc_set_CTRLC_FREERUN_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_FREERUN_bit(device->hw);
	}
}

/**
 * \brief Set conversion mode
 */
void _adc_async_set_conversion_mode(struct _adc_async_device *const device, const enum adc_conversion_mode mode)
{
	if (ADC_CONVERSION_MODE_FREERUN == mode) {
		hri_adc_set_CTRLC_FREERUN_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_FREERUN_bit(device->hw);
	}
}

/**
 * \brief Set conversion mode
 */
void _adc_dma_set_conversion_mode(struct _adc_dma_device *const device, const enum adc_conversion_mode mode)
{
	if (ADC_CONVERSION_MODE_FREERUN == mode) {
		hri_adc_set_CTRLC_FREERUN_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_FREERUN_bit(device->hw);
	}
}

/**
 * \brief Set differential mode
 */
void _adc_sync_set_channel_differential_mode(struct _adc_sync_device *const device, const uint8_t channel,
                                             const enum adc_differential_mode mode)
{
	(void)channel;

	if (ADC_DIFFERENTIAL_MODE_DIFFERENTIAL == mode) {
		hri_adc_set_CTRLC_DIFFMODE_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_DIFFMODE_bit(device->hw);
	}
}

/**
 * \brief Set differential mode
 */
void _adc_async_set_channel_differential_mode(struct _adc_async_device *const device, const uint8_t channel,
                                              const enum adc_differential_mode mode)
{
	(void)channel;

	if (ADC_DIFFERENTIAL_MODE_DIFFERENTIAL == mode) {
		hri_adc_set_CTRLC_DIFFMODE_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_DIFFMODE_bit(device->hw);
	}
}

/**
 * \brief Set differential mode
 */
void _adc_dma_set_channel_differential_mode(struct _adc_dma_device *const device, const uint8_t channel,
                                            const enum adc_differential_mode mode)
{
	(void)channel;

	if (ADC_DIFFERENTIAL_MODE_DIFFERENTIAL == mode) {
		hri_adc_set_CTRLC_DIFFMODE_bit(device->hw);
	} else {
		hri_adc_clear_CTRLC_DIFFMODE_bit(device->hw);
	}
}

/**
 * \brief Set window mode
 */
void _adc_sync_set_window_mode(struct _adc_sync_device *const device, const adc_window_mode_t mode)
{
	hri_adc_write_CTRLC_WINMODE_bf(device->hw, mode);
}

/**
 * \brief Set window mode
 */
void _adc_async_set_window_mode(struct _adc_async_device *const device, const adc_window_mode_t mode)
{
	hri_adc_write_CTRLC_WINMODE_bf(device->hw, mode);
}

/**
 * \brief Set window mode
 */
void _adc_dma_set_window_mode(struct _adc_dma_device *const device, const adc_window_mode_t mode)
{
	hri_adc_write_CTRLC_WINMODE_bf(device->hw, mode);
}

/**
 * \brief Retrieve threshold state
 */
void _adc_sync_get_threshold_state(const struct _adc_sync_device *const device, adc_threshold_status_t *const state)
{
	*state = hri_adc_get_interrupt_WINMON_bit(device->hw);
}

/**
 * \brief Retrieve threshold state
 */
void _adc_async_get_threshold_state(const struct _adc_async_device *const device, adc_threshold_status_t *const state)
{
	*state = hri_adc_get_interrupt_WINMON_bit(device->hw);
}

/**
 * \brief Retrieve threshold state
 */
void _adc_dma_get_threshold_state(const struct _adc_dma_device *const device, adc_threshold_status_t *const state)
{
	*state = hri_adc_get_interrupt_WINMON_bit(device->hw);
}

/**
 * \brief Enable/disable ADC channel interrupt
 */
void _adc_async_set_irq_state(struct _adc_async_device *const device, const uint8_t channel,
                              const enum _adc_async_callback_type type, const bool state)
{
	(void)channel;

	void *const hw = device->hw;

	if (ADC_ASYNC_DEVICE_MONITOR_CB == type) {
		hri_adc_write_INTEN_WINMON_bit(hw, state);
	} else if (ADC_ASYNC_DEVICE_ERROR_CB == type) {
		hri_adc_write_INTEN_OVERRUN_bit(hw, state);
	} else if (ADC_ASYNC_DEVICE_CONVERT_CB == type) {
		hri_adc_write_INTEN_RESRDY_bit(hw, state);
	}
}

/**
 * \brief Retrieve ADC sync helper functions
 */
void *_adc_get_adc_sync(void)
{
	return (void *)NULL;
}

/**
 * \brief Retrieve ADC async helper functions
 */
void *_adc_get_adc_async(void)
{
	return (void *)NULL;
}

/**
 * \brief Set ADC reference source
 *
 * \param[in] hw The pointer to hardware instance
 * \param[in] reference The reference to set
 */
static void _adc_set_reference_source(void *const hw, const adc_reference_t reference)
{
	bool enabled = hri_adc_get_CTRLA_ENABLE_bit(hw);

	hri_adc_clear_CTRLA_ENABLE_bit(hw);
	hri_adc_write_REFCTRL_REFSEL_bf(hw, reference);

	if (enabled) {
		hri_adc_set_CTRLA_ENABLE_bit(hw);
	}
}


text:
var path = require('path');
var http = require('http');
var logger = require('morgan');
var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');

var router = require('./router');
var config = require('./config');

// create express instance
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// logger
app.use(logger('dev'));

// parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.raw({type: 'application/x-www-form-urlencoded'}));
app.use(cookieParser());

// template directory
app.use(express.static(path.join(__dirname, 'static')));

// session
var redisStore = require('connect-redis')(session);
app.use(session({
    secret: 'mxx',
    resave: false,
    saveUninitialized: true,
    store: new redisStore(),
    cookie: {maxAge: 1000 * 60 * 60 * 24} //null to create a browser-session
}));

// top level router, all views and apis go there
app.use('/', router);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
} else {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });
}

/* ========================================================================== */

// mail module, send and receive email in background
var mail = require('./mail');
var service = config.mail[config.mail.service];
service.auth = config.mail.auth;
/*
initMailConfig need this:
{
    imap: {
       host: 'imap.qq.com',
       port: 993
    },
    smtp: {
       host: 'smtp.qq.com',
       port: 465
    },
    auth: {
       username: 'Ziming Ltd.',
       mailaddr: 's.ziming@qq.com',
       password: 's19z26m13'
    }
}
*/

mail.initMailConfig(service);
mail.startGettingMail();
mail.startSender(service);

// mail.stopGettingMail();
// mail.initMailConfig(service);
// mail.startGettingMail();

//mail.sendMail('<lmysoar@hotmail.com>', 'hi', 'sent by node.js', function(err, info) {
//    console.log(err, info.response);
//});

var db = require('./database')(
    config.database.name,
    config.database.username,
    config.database.password,
    config.database.config
);
global.db = db;

global.myError = require('./errors');
global.myUtil = require('./utils');
global.myConfig = require('./config');
global.myMail = mail;

http.createServer(app).listen(8000, 'localhost', function() {
    console.log('Server starts listening on port 8000.');
});


text:
package com.linfaxin.pullrefreshloadrecyclerview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.linfaxin.recyclerview.PullRefreshLoadRecyclerView;

/**
 * Created by linfaxin on 15/10/2.
 */
public class PullToRefreshActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        PullRefreshLoadRecyclerView recyclerView = new PullRefreshLoadRecyclerView(this);
        setContentView(recyclerView);

        recyclerView.setLoadMoreView(null);//disable load more
        DemoAdapter adapter = new DemoAdapter();
        recyclerView.setAdapter(adapter);
        adapter.initData();
    }
}


text:
@interface FoodViewController : UIViewController

@end


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Networks_ListPeeringRoutes_sync]
    using Google.Api.Gax;
    using Google.Cloud.Compute.V1;
    using System;

    public sealed partial class GeneratedNetworksClientSnippets
    {
        /// <summary>Snippet for ListPeeringRoutes</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListPeeringRoutesRequestObject()
        {
            // Create client
            NetworksClient networksClient = NetworksClient.Create();
            // Initialize request argument(s)
            ListPeeringRoutesNetworksRequest request = new ListPeeringRoutesNetworksRequest
            {
                Direction = "",
                Region = "",
                OrderBy = "",
                Project = "",
                Network = "",
                PeeringName = "",
                Filter = "",
                ReturnPartialSuccess = false,
            };
            // Make the request
            PagedEnumerable<ExchangedPeeringRoutesList, ExchangedPeeringRoute> response = networksClient.ListPeeringRoutes(request);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (ExchangedPeeringRoute item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ExchangedPeeringRoutesList page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ExchangedPeeringRoute item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<ExchangedPeeringRoute> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (ExchangedPeeringRoute item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END compute_v1_generated_Networks_ListPeeringRoutes_sync]
}


text:
function isiOS() {
  return /iPhone|iPad|iPod/i.test(navigator.userAgent);
}

function isAndroid() {
  return /Android/i.test(navigator.userAgent);
}

function isMobile() {
  return isAndroid() || isiOS();
}

async function setupCamera() {
  video = document.getElementById('video');

  const stream = await navigator.mediaDevices.getUserMedia({
    'audio': false,
    'video': {facingMode: 'user', width: videoWidth, height: videoHeight},
  });
  video.srcObject = stream;

  await new Promise((resolve) => {
    video.onloadedmetadata = () => {
      resolve(video);
    };
  });

  video.play();
  video.width = videoWidth;
  video.height = videoHeight;
}

function createStatsPanel() {
  stats = new Stats();
  stats.customFpsPanel =
      stats.addPanel(new Stats.Panel('(Model FPS)      ', '#0ff', '#002'));
  stats.showPanel(stats.domElement.children.length - 1);

  statusEl.appendChild(stats.domElement);

  const statsPanes = statusEl.querySelectorAll('canvas');

  for (let i = 0; i < statsPanes.length; ++i) {
    statsPanes[i].style.width = '140px';
    statsPanes[i].style.height = '80px';
  }
}

async function createDepthModel() {
  return tf.loadGraphModel(
      'https://storage.googleapis.com/tfjs-testing/depth/depth_model/model.json');
}

async function createDepthEstimationModel() {
  return depthEstimation.createEstimator(
      depthEstimation.SupportedModels.ARPortraitDepth, {runtime: 'tfjs'});
}

async function createFaceModel() {
  return faceDetection.createDetector(
      faceDetection.SupportedModels.MediaPipeFaceDetector, {runtime: 'tfjs'});
}

async function setupPage() {
  await setupCamera();
  model = await createDepthModel();
  estimator = await createDepthEstimationModel();
  faceDetector = await createFaceModel();
  await setupDatGui();
  createStatsPanel();
  init();
}

function beginEstimateSegmentationStats() {
  startInferenceTime = (performance || Date).now();
}

function endEstimateSegmentationStats() {
  const endInferenceTime = (performance || Date).now();
  inferenceTimeSum += endInferenceTime - startInferenceTime;
  ++numInferences;

  const panelUpdateMilliseconds = 1000;
  if (endInferenceTime - lastPanelUpdate >= panelUpdateMilliseconds) {
    const averageInferenceTime = inferenceTimeSum / numInferences;
    inferenceTimeSum = 0;
    numInferences = 0;
    stats.customFpsPanel.update(
        1000.0 / averageInferenceTime, 120 /* maxValue */);
    lastPanelUpdate = endInferenceTime;
  }
}


text:
<!DOCTYPE html>

	<meta content="width=device-width, initial-scale=1, user-scalable=no" name="viewport" />
	<title>
		UI Components
	</title>
	<link href="../../../lib/tau/wearable/theme/default/tau.css" rel="stylesheet" />
	<link href="../../../lib/tau/wearable/theme/default/tau.circle.css" media="all and (-tizen-geometric-shape: circle)" rel="stylesheet" />
	<link href="../../../css/style.css" rel="stylesheet" />
	<link href="../../../css/style.circle.css" media="all and (-tizen-geometric-shape: circle)" rel="stylesheet" />

				Progress

						Small Progress

						Medium Progress

						Large Progress

						Full Progress

						Progress thickness


text:
import sys
from PyQt4 import QtGui, QtCore
from FlatCAMApp import App
from multiprocessing import freeze_support
import VisPyPatches

if sys.platform == "win32":
    # cx_freeze 'module win32' workaround
    import OpenGL.platform.win32

def debug_trace():
    """
    Set a tracepoint in the Python debugger that works with Qt
    :return: None
    """
    from PyQt4.QtCore import pyqtRemoveInputHook
    #from pdb import set_trace
    pyqtRemoveInputHook()
    #set_trace()

# All X11 calling should be thread safe otherwise we have strange issues
# QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads)
# NOTE: Never talk to the GUI from threads! This is why I commented the above.

if __name__ == '__main__':
    freeze_support()

    debug_trace()
    VisPyPatches.apply_patches()

    app = QtGui.QApplication(sys.argv)
    fc = App()
    sys.exit(app.exec_())


text:
from nova.openstack.common import log as logging
from webob import Request, Response
import json
import copy

from cimibase import Controller, Consts
from cimibase import CimiXMLSerializer
from cimibase import make_response_data
from cimibase import get_request_data
from cimiutils import concat, get_err_response
from cimiutils import match_up, sub_path
from nova.api.openstack.wsgi import XMLDictSerializer, JSONDictSerializer

LOG = logging.getLogger(__name__)

class NetworkInterfaceCtrler(Controller):
    """
    Handles machine request.
    """
    def __init__(self, conf, app, req, tenant_id, *args):
        super(NetworkInterfaceCtrler, self).__init__(conf, app, req,
                                tenant_id, *args)
        self.os_path = '/%s/servers' % (tenant_id)
        self.metadata = Consts.NETWORK_METADATA

class NetworkInterfaceColCtrler(Controller):
    """
    Handles machine collection request.
    """
    def __init__(self, conf, app, req, tenant_id, *args):
        super(NetworkInterfaceColCtrler, self).__init__(conf,
            app, req, tenant_id, *args)
        self.os_path = '/%s/servers' % (tenant_id)
        self.entity_uri = 'MachineNetworkInterfacesCollection'
        self.metadata = Consts.NETWORK_COL_METADATA

    def _get_entry(self, data, id):

        def _make_entry(key, source_key, entries):
            adds = {}
            match_up(adds, data, 'addr', source_key)
            if adds.get('addr'):
                entry = {}
                name = 'MachineNetworkInterfacesCollectionEntry'
                entry['id'] = concat(self.tenant_id, '/', name,
                                     '/', id, '/', key)
                entry['resourceURI'] = concat(self.uri_prefix,
                    '/', name,)
                name = 'MachineNetworkInterfaceAddressesCollection'
                entry['addresses'] = {'href': concat(self.tenant_id,
                    '/', name, '/', id, '/', key)}
                entries.append(entry)

        entries = []
        _make_entry('private', 'addresses/private', entries)
        _make_entry('public',  'addresses/public', entries)
        return entries

    # Use GET to handle all container read related operations.
    def GET(self, req, *parts):
        """
        Handle GET machine request
        """

        env = self._fresh_env(req)
        env['PATH_INFO'] = concat(self.os_path, '/', parts[0])

        new_req = Request(env)
        res = new_req.get_response(self.app)

        if res.status_int == 200:
            data = json.loads(res.body).get('server')

            body = {}
            body['id'] = concat(self.tenant_id,
                                '/networkInterfacesCollection/',
                                parts[0])
            body['resourceURI'] = concat(self.uri_prefix, '/', self.entity_uri)
            body['entries'] = self._get_entry(data, parts[0])

            if self.res_content_type == 'application/xml':
                response_data = {'Collection': body}
            else:
                response_data = body

            new_content = make_response_data(response_data,
                                             self.res_content_type,
                                             self.metadata,
                                             self.uri_prefix)
            resp = Response()
            self._fixup_cimi_header(resp)
            resp.headers['Content-Type'] = self.res_content_type
            resp.status = 200
            resp.body = new_content

            return resp
        else:
            return res


text:
 - Add support for generes SQSD daemons
 - Update various dependencies for security
 - Expand Docker detection to include Docker Compose bridge networking
 - Add support for FIFO queues

## [v.3.0.0] - 2021-02-22
 - Update to AWS SDK V3
 - Closes [issue #104](https://github.com/active-elastic-job/active-elastic-job/issues/104)
 - Drop support for Ruby <2.5
 - Drop support for Rails <5
 - Add support for Ruby 3
 - Add support for Rails 6
 - Replace TravisCI with GitHub Actions

## [v.2.0.1] - 2017-02-05
 - Closes [issue #51](https://github.com/active-elastic-job/active-elastic-job/issues/51) Lazy loading of AWS credentials in order to prevent slowing down of Rails start up time.

## [v.2.0.0] - 2016-11-27
 - Closes [issue #40](https://github.com/active-elastic-job/active-elastic-job/issues/40) Thanks to @masonjeffreys for the inspiration.
 - Makes processing of jobs opt-in per default.
 - Simplifies set up by using AWS instance profiles per default.

## [v.1.7.0] - 2016-11-05
 - Closes [issue #42](https://github.com/active-elastic-job/active-elastic-job/issues/42)
 - Closes [issue #33](https://github.com/active-elastic-job/active-elastic-job/issues/33)

## [v.1.6.3] - 2016-11-05
 - Closes [issue #41](https://github.com/active-elastic-job/active-elastic-job/issues/41)

## [v.1.6.1] - 2016-05-24
 - Closes [issue #35](https://github.com/active-elastic-job/active-elastic-job/issues/35)

## [v.1.6.0] - 2016-04-21
 - Support Docker environments
 - Closes [issue #26](https://github.com/active-elastic-job/active-elastic-job/issues/26)
 - Support common environment variable names
 - Closes [issue #31](https://github.com/active-elastic-job/active-elastic-job/issues/31)

## [v.1.5.0] - 2016-04-13
- Support Rails 5 applications
 - Closes [issue #28](https://github.com/active-elastic-job/active-elastic-job/issues/28)
 - Acknowledgments: Many thanks to Matt D from San Jose.

## [v1.4.4] - 2016-04-06
- Support Rails application configured to force SSL
 - Closes [issue #25](https://github.com/active-elastic-job/active-elastic-job/issues/25)

## [v1.4.3] - 2016-03-06
- Skip SQS MD5 digest verification if not necessary
 - Closes [issue #21](https://github.com/active-elastic-job/active-elastic-job/issues/21)

## [v1.4.2] - 2016-02-18
- Escalate errors to make debugging easier

## [v1.4.0] - 2016-02-09
- Disable middleware that processes SQS daemon request with an environment variable
 - Closes [issue #12](https://github.com/active-elastic-job/active-elastic-job/issues/12)
- Check if SQS daemon request originates from localhost
 - Closes [issue #13]((https://github.com/active-elastic-job/active-elastic-job/issues/13)

## [v1.3.2] - 2016-02-08
- Fix worker environments running Puma servers. Remove underscore from header.
 - Close [issue #15](https://github.com/active-elastic-job/active-elastic-job/issues/15)

## [v1.3.1] - 2016-02-07

- Fix backwards incompatibility
 - Refers to [issue #10](https://github.com/active-elastic-job/active-elastic-job/issues/10)

- [Performance improvements](https://github.com/active-elastic-job/active-elastic-job/commit/1f1c72d6d10a3e0c42ad305b29afb1d55fcb2561)

## [v1.3.0] - 2016-02-06

- Verify MD5 hashes responses from SQS API
 - Closes issue [issue #4](https://github.com/active-elastic-job/active-elastic-job/issues/4)

- Cache queue urls
 - Closes issue [issue #3](https://github.com/active-elastic-job/active-elastic-job/issues/3)

- Avoid interfering with other aws-sqsd requests
 - Closes issue [issue #9](https://github.com/active-elastic-job/active-elastic-job/issues/9)


text:
<?php

use common\models\user\UserProfile;
use common\widgets\PhoneInput;
use yii\widgets\ActiveForm;

/* @var ActiveForm $form */
/* @var UserProfile $model */

?>

<?= $form->field($model, 'firstname')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'lastname')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'pesel')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'tax_office')->textInput(['maxlength' => true]) ?>

<div class="row">
	<?= $form->field($model, 'phone', ['options' => ['class' => 'col-md-2']])->widget(PhoneInput::class) ?>

	<?= $form->field($model, 'phone_2', ['options' => ['class' => 'col-md-2']])->widget(PhoneInput::class) ?>
</div>

<?= $form->field($model, 'email_hidden_in_frontend_issue')->checkbox() ?>

<?= $form->field($model, 'gender')->radioList(UserProfile::getGendersNames()) ?>


text:
module NewIssuable
  attr_reader :issuable, :user

  def objects_found?(issuable_id, user_id)
    set_user(user_id)
    set_issuable(issuable_id)

    user && issuable
  end

  # rubocop: disable CodeReuse/ActiveRecord
  def set_user(user_id)
    @user = User.find_by(id: user_id) # rubocop:disable Gitlab/ModuleWithInstanceVariables

    log_error(User, user_id) unless @user # rubocop:disable Gitlab/ModuleWithInstanceVariables
  end
  # rubocop: enable CodeReuse/ActiveRecord

  # rubocop: disable CodeReuse/ActiveRecord
  def set_issuable(issuable_id)
    @issuable = issuable_class.find_by(id: issuable_id) # rubocop:disable Gitlab/ModuleWithInstanceVariables

    log_error(issuable_class, issuable_id) unless @issuable # rubocop:disable Gitlab/ModuleWithInstanceVariables
  end
  # rubocop: enable CodeReuse/ActiveRecord

  def log_error(record_class, record_id)
    Rails.logger.error("#{self.class}: couldn't find #{record_class} with ID=#{record_id}, skipping job") # rubocop:disable Gitlab/RailsLogger
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>ExtensionParameter</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.plugin

Class ExtensionParameter

java.lang.Object

org.jetel.plugin.ExtensionParameter

public class ExtensionParameter
extends java.lang.Object

This class represents extension's parameter. It could be only string value, although now is possible
 to assign to one key array of values.

Constructor Summary

Constructors

Constructor and Description

ExtensionParameter()

ExtensionParameter(java.lang.String value)

Method Summary

Methods

Modifier and Type
Method and Description

void
addValue(java.lang.String value)

java.lang.String
getString()

java.util.List<java.lang.String>
getValues()

boolean
isEmpty()

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

ExtensionParameter

public ExtensionParameter()

ExtensionParameter

public ExtensionParameter(java.lang.String value)

Method Detail

isEmpty

public boolean isEmpty()

addValue

public void addValue(java.lang.String value)

getValues

public java.util.List<java.lang.String> getValues()

getString

public java.lang.String getString()

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
package com.jetbrains.edu.coursecreator.projectView;

import com.intellij.ide.projectView.ViewSettings;
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode;
import com.intellij.ide.util.treeView.AbstractTreeNode;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.edu.coursecreator.CCUtils;
import com.jetbrains.edu.learning.EduPluginConfigurator;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.courseFormat.Course;
import com.jetbrains.edu.learning.courseFormat.StudyItem;
import com.jetbrains.edu.learning.projectView.DirectoryNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class CCDirectoryNode extends DirectoryNode {
  public CCDirectoryNode(@NotNull Project project,
                         PsiDirectory value,
                         ViewSettings viewSettings) {
    super(project, value, viewSettings);
  }

  @Override
  public boolean canNavigate() {
    return true;
  }

  @Nullable
  @Override
  public AbstractTreeNode modifyChildNode(AbstractTreeNode childNode) {
    final AbstractTreeNode node = super.modifyChildNode(childNode);
    if (node != null) return node;
    Object value = childNode.getValue();
    if (value instanceof PsiElement) {
      PsiFile psiFile = ((PsiElement) value).getContainingFile();
      VirtualFile virtualFile = psiFile.getVirtualFile();

      Course course = StudyTaskManager.getInstance(myProject).getCourse();
      if (course == null) {
        return null;
      }
      EduPluginConfigurator configurator = EduPluginConfigurator.INSTANCE.forLanguage(course.getLanguageById());
      if (configurator == null) {
        return new CCStudentInvisibleFileNode(myProject, psiFile, myViewSettings);
      }
      if (!CCUtils.isTestsFile(myProject, virtualFile)) {
        return new CCStudentInvisibleFileNode(myProject, psiFile, myViewSettings);
      }
    }
    return null;
  }

  @Override
  public PsiDirectoryNode createChildDirectoryNode(StudyItem item, PsiDirectory value) {
    return new CCDirectoryNode(myProject, value, myViewSettings);
  }
}


text:
goog.provide('Zlib.InflateStream');

//-----------------------------------------------------------------------------

/** @define {boolean} export symbols. */
var ZLIB_INFLATE_STREAM_EXPORT = false;

//-----------------------------------------------------------------------------

//goog.require('Zlib.Adler32');
goog.require('Zlib.RawInflateStream');

goog.scope(function() {

/**
 * @param {!(Uint8Array|Array)} input deflated buffer.
 * @constructor
 */
Zlib.InflateStream = function(input) {
  /** @type {!(Uint8Array|Array)} */
  this.input = input === void 0 ? new (USE_TYPEDARRAY ? Uint8Array : Array)() : input;
  /** @type {number} */
  this.ip = 0;
  /** @type {Zlib.RawInflateStream} */
  this.rawinflate = new Zlib.RawInflateStream(this.input, this.ip);
  /** @type {Zlib.CompressionMethod} */
  this.method;
  /** @type {!(Array|Uint8Array)} */
  this.output = this.rawinflate.output;
};

/**
 * decompress.
 * @return {!(Uint8Array|Array)} inflated buffer.
 */
Zlib.InflateStream.prototype.decompress = function(input) {
  /** @type {!(Uint8Array|Array)} inflated buffer. */
  var buffer;
  /** @type {number} adler-32 checksum */
  var adler32;

  // 新しい入力を入力バッファに結合する
  // XXX Array, Uint8Array のチェックを行うか確認する
  if (input !== void 0) {
    if (USE_TYPEDARRAY) {
      var tmp = new Uint8Array(this.input.length + input.length);
      tmp.set(this.input, 0);
      tmp.set(input, this.input.length);
      this.input = tmp;
    } else {
      this.input = this.input.concat(input);
    }
  }

  if (this.method === void 0) {
    if(this.readHeader() < 0) {
      return new (USE_TYPEDARRAY ? Uint8Array : Array)();
    }
  }

  buffer = this.rawinflate.decompress(this.input, this.ip);
  this.ip = this.rawinflate.ip;

  // verify adler-32
  /*
  if (this.verify) {
    adler32 =
      input[this.ip++] << 24 | input[this.ip++] << 16 |
      input[this.ip++] << 8 | input[this.ip++];

    if (adler32 !== Zlib.Adler32(buffer)) {
      throw new Error('invalid adler-32 checksum');
    }
  }
  */

  return buffer;
};

/**
 * @return {!(Uint8Array|Array)} current output buffer.
 */
Zlib.InflateStream.prototype.getBytes = function() {
  return this.rawinflate.getBytes();
};

Zlib.InflateStream.prototype.readHeader = function() {
  var ip = this.ip;
  var input = this.input;

  // Compression Method and Flags
  var cmf = input[ip++];
  var flg = input[ip++];

  if (cmf === void 0 || flg === void 0) {
    return -1;
  }

  // compression method
  switch (cmf & 0x0f) {
    case Zlib.CompressionMethod.DEFLATE:
      this.method = Zlib.CompressionMethod.DEFLATE;
      break;
    default:
      throw new Error('unsupported compression method');
  }

  // fcheck
  if (((cmf << 8) + flg) % 31 !== 0) {
    throw new Error('invalid fcheck flag:' + ((cmf << 8) + flg) % 31);
  }

  // fdict (not supported)
  if (flg & 0x20) {
    throw new Error('fdict flag is not supported');
  }

  this.ip = ip;
};

//*****************************************************************************
// export
//*****************************************************************************
if (ZLIB_INFLATE_STREAM_EXPORT) {
  goog.exportSymbol('Zlib.InflateStream', Zlib.InflateStream);
  goog.exportSymbol(
    'Zlib.InflateStream.prototype.decompress',
    Zlib.InflateStream.prototype.decompress
  );
  goog.exportSymbol(
    'Zlib.InflateStream.prototype.getBytes',
    Zlib.InflateStream.prototype.getBytes
  );
}

// end of scope
});

/* vim:set expandtab ts=2 sw=2 tw=80: */


text:
/**
 *  @module exception
 *  @memberof internals
 *  @see module:internals
 *  @see module:core
 *  @see module:app
 *  @description
 *  Dependes on module:internals.logger
 *  Provides handlers for catching and reporting all uncaught Angular exceptions..
 */
(function (projectName, angular) {

  'use strict';

  angular
    .module('internals.exception', ['internals.logger']);

})(window.projectName = window.projectName || {}, angular);