text:
"""GDB support for Chrome types.

Add this to your gdb by amending your ~/.gdbinit as follows:
  python
  import sys
  sys.path.insert(0, "/path/to/tools/gdb/")
  import gdb_chrome
  end

Use
  (gdb) p /r any_variable
to print |any_variable| without using any printers.
"""

import datetime
import gdb
import gdb.printing
import os
import sys

sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    '..', '..', 'third_party', 'WebKit', 'Tools', 'gdb'))
try:
  import webkit
finally:
  sys.path.pop(0)

# When debugging this module, set the below variable to True, and then use
#   (gdb) python del sys.modules['gdb_chrome']
#   (gdb) python import gdb_chrome
# to reload.
_DEBUGGING = False

pp_set = gdb.printing.RegexpCollectionPrettyPrinter("chromium")

def typed_ptr(ptr):
    """Prints a pointer along with its exact type.

    By default, gdb would print just the address, which takes more
    steps to interpret.
    """
    # Returning this as a cast expression surrounded by parentheses
    # makes it easier to cut+paste inside of gdb.
    return '((%s)%s)' % (ptr.dynamic_type, ptr)

def yield_fields(val):
    """Use this in a printer's children() method to print an object's fields.

    e.g.
      def children():
        for result in yield_fields(self.val):
          yield result
    """
    try:
        fields = val.type.target().fields()
    except:
        fields = val.type.fields()
    for field in fields:
        if field.is_base_class:
            yield (field.name, val.cast(gdb.lookup_type(field.name)))
        else:
            yield (field.name, val[field.name])

class Printer(object):
    def __init__(self, val):
        self.val = val

class StringPrinter(Printer):
    def display_hint(self):
        return 'string'

class String16Printer(StringPrinter):
    def to_string(self):
        return webkit.ustring_to_string(self.val['_M_dataplus']['_M_p'])
pp_set.add_printer(
    'string16',
    '^string16|std::basic_string<(unsigned short|base::char16).*>$',
    String16Printer);

class GURLPrinter(StringPrinter):
    def to_string(self):
        return self.val['spec_']
pp_set.add_printer('GURL', '^GURL$', GURLPrinter)

class FilePathPrinter(StringPrinter):
    def to_string(self):
        return self.val['path_']['_M_dataplus']['_M_p']
pp_set.add_printer('FilePath', '^FilePath$', FilePathPrinter)

class SizePrinter(Printer):
    def to_string(self):
        return '%sx%s' % (self.val['width_'], self.val['height_'])
pp_set.add_printer('gfx::Size', '^gfx::(Size|SizeF|SizeBase<.*>)$', SizePrinter)

class PointPrinter(Printer):
    def to_string(self):
        return '%s,%s' % (self.val['x_'], self.val['y_'])
pp_set.add_printer('gfx::Point', '^gfx::(Point|PointF|PointBase<.*>)$',
                   PointPrinter)

class RectPrinter(Printer):
    def to_string(self):
        return '%s %s' % (self.val['origin_'], self.val['size_'])
pp_set.add_printer('gfx::Rect', '^gfx::(Rect|RectF|RectBase<.*>)$',
                   RectPrinter)

class SmartPtrPrinter(Printer):
    def to_string(self):
        return '%s%s' % (self.typename, typed_ptr(self.ptr()))

class ScopedPtrPrinter(SmartPtrPrinter):
    typename = 'scoped_ptr'
    def ptr(self):
        return self.val['impl_']['data_']['ptr']
pp_set.add_printer('scoped_ptr', '^scoped_ptr<.*>$', ScopedPtrPrinter)

class ScopedRefPtrPrinter(SmartPtrPrinter):
    typename = 'scoped_refptr'
    def ptr(self):
        return self.val['ptr_']
pp_set.add_printer('scoped_refptr', '^scoped_refptr<.*>$', ScopedRefPtrPrinter)

class LinkedPtrPrinter(SmartPtrPrinter):
    typename = 'linked_ptr'
    def ptr(self):
        return self.val['value_']
pp_set.add_printer('linked_ptr', '^linked_ptr<.*>$', LinkedPtrPrinter)

class WeakPtrPrinter(SmartPtrPrinter):
    typename = 'base::WeakPtr'
    def ptr(self):
        flag = ScopedRefPtrPrinter(self.val['ref_']['flag_']).ptr()
        if flag and flag['is_valid_']:
            return self.val['ptr_']
        return gdb.Value(0).cast(self.val['ptr_'].type)
pp_set.add_printer('base::WeakPtr', '^base::WeakPtr<.*>$', WeakPtrPrinter)

class CallbackPrinter(Printer):
    """Callbacks provide no usable information so reduce the space they take."""
    def to_string(self):
        return '...'
pp_set.add_printer('base::Callback', '^base::Callback<.*>$', CallbackPrinter)

class LocationPrinter(Printer):
    def to_string(self):
        return '%s()@%s:%s' % (self.val['function_name_'].string(),
                               self.val['file_name_'].string(),
                               self.val['line_number_'])
pp_set.add_printer('tracked_objects::Location', '^tracked_objects::Location$',
                   LocationPrinter)

class PendingTaskPrinter(Printer):
    def to_string(self):
        return 'From %s' % (self.val['posted_from'],)

    def children(self):
        for result in yield_fields(self.val):
            if result[0] not in ('task', 'posted_from'):
                yield result
pp_set.add_printer('base::PendingTask', '^base::PendingTask$',
                   PendingTaskPrinter)

class LockPrinter(Printer):
    def to_string(self):
        try:
            if self.val['owned_by_thread_']:
                return 'Locked by thread %s' % self.val['owning_thread_id_']
            else:
                return 'Unlocked'
        except gdb.error:
            return 'Unknown state'
pp_set.add_printer('base::Lock', '^base::Lock$', LockPrinter)

class TimeDeltaPrinter(object):
    def __init__(self, val):
        self._timedelta = datetime.timedelta(microseconds=int(val['delta_']))

    def timedelta(self):
        return self._timedelta

    def to_string(self):
        return str(self._timedelta)
pp_set.add_printer('base::TimeDelta', '^base::TimeDelta$', TimeDeltaPrinter)

class TimeTicksPrinter(TimeDeltaPrinter):
    def __init__(self, val):
        self._timedelta = datetime.timedelta(microseconds=int(val['us_']))
pp_set.add_printer('base::TimeTicks', '^base::TimeTicks$', TimeTicksPrinter)

class TimePrinter(object):
    def __init__(self, val):
        timet_offset = gdb.parse_and_eval(
            'base::Time::kTimeTToMicrosecondsOffset')
        self._datetime = (datetime.datetime.fromtimestamp(0) +
                          datetime.timedelta(microseconds=
                                             int(val['us_'] - timet_offset)))

    def datetime(self):
        return self._datetime

    def to_string(self):
        return str(self._datetime)
pp_set.add_printer('base::Time', '^base::Time$', TimePrinter)

class IpcMessagePrinter(Printer):
    def header(self):
        return self.val['header_'].cast(
            gdb.lookup_type('IPC::Message::Header').pointer())

    def to_string(self):
        message_type = self.header()['type']
        return '%s of kind %s line %s' % (
            self.val.dynamic_type,
            (message_type >> 16).cast(gdb.lookup_type('IPCMessageStart')),
            message_type & 0xffff)

    def children(self):
        yield ('header_', self.header().dereference())
        yield ('capacity_after_header_', self.val['capacity_after_header_'])
        for field in self.val.type.fields():
            if field.is_base_class:
                continue
            yield (field.name, self.val[field.name])
pp_set.add_printer('IPC::Message', '^IPC::Message$', IpcMessagePrinter)

class NotificationRegistrarPrinter(Printer):
    def to_string(self):
        try:
            registrations = self.val['registered_']
            vector_finish = registrations['_M_impl']['_M_finish']
            vector_start = registrations['_M_impl']['_M_start']
            if vector_start == vector_finish:
                return 'Not watching notifications'
            if vector_start.dereference().type.sizeof == 0:
                # Incomplete type: b/8242773
                return 'Watching some notifications'
            return ('Watching %s notifications; '
                    'print %s->registered_ for details') % (
                        int(vector_finish - vector_start),
                        typed_ptr(self.val.address))
        except gdb.error:
            return 'NotificationRegistrar'
pp_set.add_printer('content::NotificationRegistrar',
                   '^content::NotificationRegistrar$',
                   NotificationRegistrarPrinter)

class SiteInstanceImplPrinter(object):
    def __init__(self, val):
        self.val = val.cast(val.dynamic_type)

    def to_string(self):
        return 'SiteInstanceImpl@%s for %s' % (
            self.val.address, self.val['site_'])

    def children(self):
        yield ('id_', self.val['id_'])
        yield ('has_site_', self.val['has_site_'])
        if self.val['browsing_instance_']['ptr_']:
            yield ('browsing_instance_', self.val['browsing_instance_']['ptr_'])
        if self.val['process_']:
            yield ('process_', typed_ptr(self.val['process_']))
pp_set.add_printer('content::SiteInstanceImpl', '^content::SiteInstanceImpl$',
                   SiteInstanceImplPrinter)

class RenderProcessHostImplPrinter(object):
    def __init__(self, val):
        self.val = val.cast(val.dynamic_type)

    def to_string(self):
        pid = ''
        try:
            child_process_launcher_ptr = (
                self.val['child_process_launcher_']['impl_']['data_']['ptr'])
            if child_process_launcher_ptr:
                context = (child_process_launcher_ptr['context_']['ptr_'])
                if context:
                    pid = ' PID %s' % str(context['process_']['process_'])
        except gdb.error:
            # The definition of the Context type may not be available.
            # b/8242773
            pass
        return 'RenderProcessHostImpl@%s%s' % (self.val.address, pid)

    def children(self):
        yield ('id_', self.val['id_'])
        yield ('listeners_',
               self.val['listeners_']['data_'])
        yield ('worker_ref_count_', self.val['worker_ref_count_'])
        yield ('fast_shutdown_started_', self.val['fast_shutdown_started_'])
        yield ('deleting_soon_', self.val['deleting_soon_'])
        yield ('pending_views_', self.val['pending_views_'])
        yield ('visible_widgets_', self.val['visible_widgets_'])
        yield ('backgrounded_', self.val['backgrounded_'])
        yield ('widget_helper_', self.val['widget_helper_'])
        yield ('is_initialized_', self.val['is_initialized_'])
        yield ('browser_context_', typed_ptr(self.val['browser_context_']))
        yield ('sudden_termination_allowed_',
               self.val['sudden_termination_allowed_'])
        yield ('ignore_input_events_', self.val['ignore_input_events_'])
        yield ('is_guest_', self.val['is_guest_'])
pp_set.add_printer('content::RenderProcessHostImpl',
                   '^content::RenderProcessHostImpl$',
                   RenderProcessHostImplPrinter)

gdb.printing.register_pretty_printer(gdb, pp_set, replace=_DEBUGGING)


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php"
         backupGlobals="false"
         verbose="true">
  <filter>
    <whitelist>
        <directory suffix=".php">src/</directory>
    </whitelist>
  </filter>

  <testsuites>
    <testsuite name="PHPUnit">
      <directory suffix="Test.php">tests</directory>
    </testsuite>
  </testsuites>

  <logging>
    <log type="coverage-html" target="build/coverage" title="ValidationKit"
        charset="UTF-8" yui="true" highlight="true"
        lowUpperBound="35" highLowerBound="70"/>
    <log type="coverage-clover" target="build/logs/clover.xml"/>
    <log type="junit" target="build/logs/junit.xml"
        logIncompleteSkipped="false"/>
  </logging>
</phpunit>

redpajama_set_name: RedPajamaGithub


text:
<?php
	/**
	 * TransPerth GTFS stop/place class
	 * @since Version 3.8.7
	 * @package Railpage
	 * @author Michael Greenhill
	 */

	namespace Railpage\GTFS\AU\TransPerth;

	use Exception;
	use DateTime;
	use Zend\Http\Client;
	use Zend\Db\Sql\Sql;
	use Zend\Db\Sql\Select;
	use Zend\Db\Adapter\Adapter;
	use Railpage\GTFS\StopInterface;
	use Railpage\Place;

	/**
	 * GTFS stop for the AU\TransPerth GTFS provider
	 * @since Version 3.8.7
	 */

	class Stop implements StopInterface {

		/**
		 * Stop ID
		 * @var mixed $id
		 */

		public $id;

		/**
		 * Stop name
		 * @var string $name
		 */

		public $name;

		/**
		 * Stop code
		 * @var string $code
		 */

		public $code;

		/**
		 * Latitude
		 * @var double $lat
		 */

		public $lat;

		/**
		 * Longitude
		 * @var double $lon
		 */

		public $lon;

		/**
		 * Wheelchair boarding
		 * @var boolean $wheelchair_boarding
		 */

		public $wheelchair_boarding;

		/**
		 * Place object
		 * @var \Railpage\Place $Place
		 */

		public $Place;

		/**
		 * Constructor
		 * @since Version 3.8.7
		 * @param mixed $id
		 */

		public function __construct($id = false) {
			$this->Provider = new TransPerth;

			if (filter_var($id, FILTER_VALIDATE_INT)) {
				$result = $this->Provider->adapter->query("SELECT * FROM au_wa_stops WHERE stop_id = '" . $id . "' AND location_type = 1", Adapter::QUERY_MODE_EXECUTE);

				if ($result) {
					foreach ($result as $row) {
						$row = $row->getArrayCopy();

						$this->id = $row['stop_id'];
						$this->name = $row['stop_name'];
						$this->code = $row['stop_code'];
						$this->lat = $row['stop_lat'];
						$this->lon = $row['stop_lon'];
						$this->wheelchair_boarding = (bool) $row['wheelchair_boarding'];

						$this->Place = new Place($this->lat, $this->lon);
					}
				}
			}
		}

		/**
		 * Get the next departures for this stop
		 * @return array
		 */

		public function NextDepartures() {

		}
	}
?>


text:
package com.myapps.roadtrips.main.model;

import android.os.Parcel;
import android.os.Parcelable;

public class Hotel implements Parcelable {

	private String name;
	private String price;
	private String category;
	private String code;
	private String currency;
	private String lat;
	private String lon;
	private String roomType;
	private String board;
	private int night;
	private String company;

	public Hotel (Parcel parcel) {
		name = parcel.readString();
		price = parcel.readString();
		category = parcel.readString();
		code = parcel.readString();
		currency = parcel.readString();
		lat = parcel.readString();
		lon = parcel.readString();
		roomType = parcel.readString();
		board = parcel.readString();
		night = Integer.parseInt(parcel.readString());
		company = parcel.readString();
	}

	// We need to add a Creator
	public static final Parcelable.Creator<Hotel> CREATOR = new Parcelable.Creator<Hotel>() {

		@Override
		public Hotel createFromParcel(Parcel parcel) {
			return new Hotel(parcel);
		}

		@Override
		public Hotel[] newArray(int size) {
			return new Hotel[size];
		}
	};

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPrice() {
		return price;
	}

	public void setPrice(String price) {
		this.price = price;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getCurrency() {
		return currency;
	}

	public void setCurrency(String currency) {
		this.currency = currency;
	}

	public String getLat() {
		return lat;
	}

	public void setLat(String lat) {
		this.lat = lat;
	}

	public String getLon() {
		return lon;
	}

	public void setLon(String lon) {
		this.lon = lon;
	}

	public String getRoomType() {
		return roomType;
	}

	public void setRoomType(String roomType) {
		this.roomType = roomType;
	}

	public String getBoard() {
		return board;
	}

	public void setBoard(String board) {
		this.board = board;
	}

	public int getNight() {
		return night;
	}

	public void setNight(int night) {
		this.night = night;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	@Override
	public int describeContents() {
		return hashCode();
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeString(name);
		dest.writeString(price);
		dest.writeString(category);
		dest.writeString(code);
		dest.writeString(currency);
		dest.writeString(lat);
		dest.writeString(lon);
		dest.writeString(roomType);
		dest.writeString(board);
		dest.writeString(String.valueOf(night));
		dest.writeString(company);
	}
}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.2.3.5
description: >
    Set.prototype.entries ( )

    ...
    2. Return CreateSetIterator(S, "key+value").

    23.2.5.1 CreateSetIterator Abstract Operation

    ...
    2. If S does not have a [[SetData]] internal slot, throw a TypeError exception.
    ...
---*/

assert.throws(TypeError, function() {
  Set.prototype.entries.call(Set.prototype);
});

assert.throws(TypeError, function() {
  var s = new Set();
  s.entries.call(Set.prototype);
});


text:
require 'open3'
require 'gondler/version'
require 'gondler/env'
require 'gondler/package'
require 'gondler/gomfile'

module Gondler
  class << self
    def without(_without = nil)
      if block_given?
        _without, @without = without, _without
        yield
        @without = _without
      end
      @without || []
    end

    def env
      @env ||= Gondler::Env.new
    end
  end
end


text:
'use strict';
var express = require( 'express' );
const spawn = require( 'child_process' ).spawn;

var router = express.Router();

/* webhook POST endpoint */
router.post( '/', function( req, res, next ) {

  var status;
  var output;
  if( req.description && req.description.ok ) {

    try {
      /* here's where we do something useful */
      var stdout_val = [];
      var stderr_val = [];

      const myShell = spawn( req.description.on_webhook,
                             [req.description.git_ssh_url,
                              req.description.repopath,
                              req.description.reponame,
                              req.description.event_name,
                              req.description.ref] );

      /* send the payload to the spawned shell */
      myShell.stdin.write( JSON.stringify( req.description.payload ) );

      /* gather the results of the spawned shell */
      myShell.stdout.on( 'data', function( data ) {
        stdout_val.push( data.toString( 'utf8' ) );
      } );
      myShell.stderr.on( 'data', function( data ) {
        stderr_val.push( data.toString( 'utf8' ) );
      } );

      /* log the results of the spawned shell */
      myShell.on( 'close', function( code ) {
        var severity = (code === 0) ? 'notice' : 'warning';
        if( code !== 0 ) req.logger.log( severity, req.description.on_webhook + ' exited with ' + code );
        var output = stdout_val.join( '' ).replace( /\s*$/, '' );
        if( output.length > 0 ) {
          req.logger.log( severity, req.description.on_webhook + ' stdout: ' + output );
        }
        output = stderr_val.join( '' ).replace( /\s*$/, '' );
        if( output.length > 0 ) {
          req.logger.log( severity, req.description.on_webhook + ' stderr: ' + output );
        }
      } );
    }
    catch( exception ) {
      req.logger.error( 'error trying to spawn command' );
    }

    status = 200;
    if( req.query.describe ) {
      req.description.status  = status;
      req.description.message = 'ok.';
      output                  = JSON.stringify( req.description, null, 2 );
    }
    else output = JSON.stringify( {ok: true, status: 200, message: 'ok.'} );
  }
  else {
    status = 404;
    output = JSON.stringify( {ok: false, status: status, message: 'Not found.'} );
  }

  res.status( status ).send( output );
} );

module.exports = router;


text:
import time
from openerp.osv import osv
from openerp.report import report_sxw
from common_report_header import common_report_header

class aged_trial_report(report_sxw.rml_parse, common_report_header):

    def __init__(self, cr, uid, name, context):
        super(aged_trial_report, self).__init__(cr, uid, name, context=context)
        self.total_account = []
        self.localcontext.update({
            'time': time,
            'get_lines_with_out_partner': self._get_lines_with_out_partner,
            'get_lines': self._get_lines,
            'get_total': self._get_total,
            'get_direction': self._get_direction,
            'get_for_period': self._get_for_period,
            'get_company': self._get_company,
            'get_currency': self._get_currency,
            'get_partners':self._get_partners,
            'get_account': self._get_account,
            'get_fiscalyear': self._get_fiscalyear,
            'get_target_move': self._get_target_move,
        })

    def set_context(self, objects, data, ids, report_type=None):
        obj_move = self.pool.get('account.move.line')
        ctx = data['form'].get('used_context', {})
        ctx.update({'fiscalyear': False, 'all_fiscalyear': True})
        self.query = obj_move._query_get(self.cr, self.uid, obj='l', context=ctx)
        self.direction_selection = data['form'].get('direction_selection', 'past')
        self.target_move = data['form'].get('target_move', 'all')
        self.date_from = data['form'].get('date_from', time.strftime('%Y-%m-%d'))
        if (data['form']['result_selection'] == 'customer' ):
            self.ACCOUNT_TYPE = ['receivable']
        elif (data['form']['result_selection'] == 'supplier'):
            self.ACCOUNT_TYPE = ['payable']
        else:
            self.ACCOUNT_TYPE = ['payable','receivable']
        return super(aged_trial_report, self).set_context(objects, data, ids, report_type=report_type)

    def _get_lines(self, form):
        res = []
        move_state = ['draft','posted']
        if self.target_move == 'posted':
            move_state = ['posted']
        self.cr.execute('SELECT DISTINCT res_partner.id AS id,\
                    res_partner.name AS name \
                FROM res_partner,account_move_line AS l, account_account, account_move am\
                WHERE (l.account_id=account_account.id) \
                    AND (l.move_id=am.id) \
                    AND (am.state IN %s)\
                    AND (account_account.type IN %s)\
                    AND account_account.active\
                    AND ((reconcile_id IS NULL)\
                       OR (reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                    AND (l.partner_id=res_partner.id)\
                    AND (l.date <= %s)\
                    AND ' + self.query + ' \
                ORDER BY res_partner.name', (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, self.date_from,))
        partners = self.cr.dictfetchall()
        ## mise a 0 du total
        for i in range(7):
            self.total_account.append(0)
        #
        # Build a string like (1,2,3) for easy use in SQL query
        partner_ids = [x['id'] for x in partners]
        if not partner_ids:
            return []
        # This dictionary will store the debit-credit for all partners, using partner_id as key.

        totals = {}
        self.cr.execute('SELECT l.partner_id, SUM(l.debit-l.credit) \
                    FROM account_move_line AS l, account_account, account_move am \
                    WHERE (l.account_id = account_account.id) AND (l.move_id=am.id) \
                    AND (am.state IN %s)\
                    AND (account_account.type IN %s)\
                    AND (l.partner_id IN %s)\
                    AND ((l.reconcile_id IS NULL)\
                    OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                    AND ' + self.query + '\
                    AND account_account.active\
                    AND (l.date <= %s)\
                    GROUP BY l.partner_id ', (tuple(move_state), tuple(self.ACCOUNT_TYPE), tuple(partner_ids), self.date_from, self.date_from,))
        t = self.cr.fetchall()
        for i in t:
            totals[i[0]] = i[1]

        # This dictionary will store the future or past of all partners
        future_past = {}
        if self.direction_selection == 'future':
            self.cr.execute('SELECT l.partner_id, SUM(l.debit-l.credit) \
                        FROM account_move_line AS l, account_account, account_move am \
                        WHERE (l.account_id=account_account.id) AND (l.move_id=am.id) \
                        AND (am.state IN %s)\
                        AND (account_account.type IN %s)\
                        AND (COALESCE(l.date_maturity, l.date) < %s)\
                        AND (l.partner_id IN %s)\
                        AND ((l.reconcile_id IS NULL)\
                        OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                        AND '+ self.query + '\
                        AND account_account.active\
                    AND (l.date <= %s)\
                        GROUP BY l.partner_id', (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, tuple(partner_ids),self.date_from, self.date_from,))
            t = self.cr.fetchall()
            for i in t:
                future_past[i[0]] = i[1]
        elif self.direction_selection == 'past': # Using elif so people could extend without this breaking
            self.cr.execute('SELECT l.partner_id, SUM(l.debit-l.credit) \
                    FROM account_move_line AS l, account_account, account_move am \
                    WHERE (l.account_id=account_account.id) AND (l.move_id=am.id)\
                        AND (am.state IN %s)\
                        AND (account_account.type IN %s)\
                        AND (COALESCE(l.date_maturity,l.date) > %s)\
                        AND (l.partner_id IN %s)\
                        AND ((l.reconcile_id IS NULL)\
                        OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                        AND '+ self.query + '\
                        AND account_account.active\
                    AND (l.date <= %s)\
                        GROUP BY l.partner_id', (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, tuple(partner_ids), self.date_from, self.date_from,))
            t = self.cr.fetchall()
            for i in t:
                future_past[i[0]] = i[1]

        # Use one query per period and store results in history (a list variable)
        # Each history will contain: history[1] = {'<partner_id>': <partner_debit-credit>}
        history = []
        for i in range(5):
            args_list = (tuple(move_state), tuple(self.ACCOUNT_TYPE), tuple(partner_ids),self.date_from,)
            dates_query = '(COALESCE(l.date_maturity,l.date)'
            if form[str(i)]['start'] and form[str(i)]['stop']:
                dates_query += ' BETWEEN %s AND %s)'
                args_list += (form[str(i)]['start'], form[str(i)]['stop'])
            elif form[str(i)]['start']:
                dates_query += ' > %s)'
                args_list += (form[str(i)]['start'],)
            else:
                dates_query += ' < %s)'
                args_list += (form[str(i)]['stop'],)
            args_list += (self.date_from,)
            self.cr.execute('''SELECT l.partner_id, SUM(l.debit-l.credit), l.reconcile_partial_id
                    FROM account_move_line AS l, account_account, account_move am
                    WHERE (l.account_id = account_account.id) AND (l.move_id=am.id)
                        AND (am.state IN %s)
                        AND (account_account.type IN %s)
                        AND (l.partner_id IN %s)
                        AND ((l.reconcile_id IS NULL)
                          OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))
                        AND ''' + self.query + '''
                        AND account_account.active
                        AND ''' + dates_query + '''
                    AND (l.date <= %s)
                    GROUP BY l.partner_id, l.reconcile_partial_id''', args_list)
            partners_partial = self.cr.fetchall()
            partners_amount = dict((i[0],0) for i in partners_partial)
            for partner_info in partners_partial:
                if partner_info[2]:
                    # in case of partial reconciliation, we want to keep the left amount in the oldest period
                    self.cr.execute('''SELECT MIN(COALESCE(date_maturity,date)) FROM account_move_line WHERE reconcile_partial_id = %s''', (partner_info[2],))
                    date = self.cr.fetchall()
                    if date and args_list[-3] <= date[0][0] <= args_list[-2]:
                        # partial reconcilation
                        self.cr.execute('''SELECT SUM(l.debit-l.credit)
                                           FROM account_move_line AS l
                                           WHERE l.reconcile_partial_id = %s''', (partner_info[2],))
                        unreconciled_amount = self.cr.fetchall()
                        partners_amount[partner_info[0]] += unreconciled_amount[0][0]
                else:
                    partners_amount[partner_info[0]] += partner_info[1]
            history.append(partners_amount)

        for partner in partners:
            values = {}
            ## If choise selection is in the future
            if self.direction_selection == 'future':
                # Query here is replaced by one query which gets the all the partners their 'before' value
                before = False
                if future_past.has_key(partner['id']):
                    before = [ future_past[partner['id']] ]
                self.total_account[6] = self.total_account[6] + (before and before[0] or 0.0)
                values['direction'] = before and before[0] or 0.0
            elif self.direction_selection == 'past': # Changed this so people could in the future create new direction_selections
                # Query here is replaced by one query which gets the all the partners their 'after' value
                after = False
                if future_past.has_key(partner['id']): # Making sure this partner actually was found by the query
                    after = [ future_past[partner['id']] ]

                self.total_account[6] = self.total_account[6] + (after and after[0] or 0.0)
                values['direction'] = after and after[0] or 0.0

            for i in range(5):
                during = False
                if history[i].has_key(partner['id']):
                    during = [ history[i][partner['id']] ]
                # Ajout du compteur
                self.total_account[(i)] = self.total_account[(i)] + (during and during[0] or 0)
                values[str(i)] = during and during[0] or 0.0
            total = False
            if totals.has_key( partner['id'] ):
                total = [ totals[partner['id']] ]
            values['total'] = total and total[0] or 0.0
            ## Add for total
            self.total_account[(i+1)] = self.total_account[(i+1)] + (total and total[0] or 0.0)
            values['name'] = partner['name']

            res.append(values)

        total = 0.0
        totals = {}
        for r in res:
            total += float(r['total'] or 0.0)
            for i in range(5)+['direction']:
                totals.setdefault(str(i), 0.0)
                totals[str(i)] += float(r[str(i)] or 0.0)
        return res

    def _get_lines_with_out_partner(self, form):
        res = []
        move_state = ['draft','posted']
        if self.target_move == 'posted':
            move_state = ['posted']

        ## mise a 0 du total
        for i in range(7):
            self.total_account.append(0)
        totals = {}
        self.cr.execute('SELECT SUM(l.debit-l.credit) \
                    FROM account_move_line AS l, account_account, account_move am \
                    WHERE (l.account_id = account_account.id) AND (l.move_id=am.id)\
                    AND (am.state IN %s)\
                    AND (l.partner_id IS NULL)\
                    AND (account_account.type IN %s)\
                    AND ((l.reconcile_id IS NULL) \
                    OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                    AND ' + self.query + '\
                    AND (l.date <= %s)\
                    AND account_account.active ',(tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, self.date_from,))
        t = self.cr.fetchall()
        for i in t:
            totals['Unknown Partner'] = i[0]
        future_past = {}
        if self.direction_selection == 'future':
            self.cr.execute('SELECT SUM(l.debit-l.credit) \
                        FROM account_move_line AS l, account_account, account_move am\
                        WHERE (l.account_id=account_account.id) AND (l.move_id=am.id)\
                        AND (am.state IN %s)\
                        AND (l.partner_id IS NULL)\
                        AND (account_account.type IN %s)\
                        AND (COALESCE(l.date_maturity, l.date) < %s)\
                        AND ((l.reconcile_id IS NULL)\
                        OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                        AND '+ self.query + '\
                        AND account_account.active ', (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, self.date_from))
            t = self.cr.fetchall()
            for i in t:
                future_past['Unknown Partner'] = i[0]
        elif self.direction_selection == 'past': # Using elif so people could extend without this breaking
            self.cr.execute('SELECT SUM(l.debit-l.credit) \
                    FROM account_move_line AS l, account_account, account_move am \
                    WHERE (l.account_id=account_account.id) AND (l.move_id=am.id)\
                        AND (am.state IN %s)\
                        AND (l.partner_id IS NULL)\
                        AND (account_account.type IN %s)\
                        AND (COALESCE(l.date_maturity,l.date) > %s)\
                        AND ((l.reconcile_id IS NULL)\
                        OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                        AND '+ self.query + '\
                        AND account_account.active ', (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from, self.date_from))
            t = self.cr.fetchall()
            for i in t:
                future_past['Unknown Partner'] = i[0]
        history = []

        for i in range(5):
            args_list = (tuple(move_state), tuple(self.ACCOUNT_TYPE), self.date_from,)
            dates_query = '(COALESCE(l.date_maturity,l.date)'
            if form[str(i)]['start'] and form[str(i)]['stop']:
                dates_query += ' BETWEEN %s AND %s)'
                args_list += (form[str(i)]['start'], form[str(i)]['stop'])
            elif form[str(i)]['start']:
                dates_query += ' > %s)'
                args_list += (form[str(i)]['start'],)
            else:
                dates_query += ' < %s)'
                args_list += (form[str(i)]['stop'],)
            args_list += (self.date_from,)
            self.cr.execute('SELECT SUM(l.debit-l.credit)\
                    FROM account_move_line AS l, account_account, account_move am \
                    WHERE (l.account_id = account_account.id) AND (l.move_id=am.id)\
                        AND (am.state IN %s)\
                        AND (account_account.type IN %s)\
                        AND (l.partner_id IS NULL)\
                        AND ((l.reconcile_id IS NULL)\
                        OR (l.reconcile_id IN (SELECT recon.id FROM account_move_reconcile AS recon WHERE recon.create_date > %s )))\
                        AND '+ self.query + '\
                        AND account_account.active\
                        AND ' + dates_query + '\
                    AND (l.date <= %s)\
                    GROUP BY l.partner_id', args_list)
            t = self.cr.fetchall()
            d = {}
            for i in t:
                d['Unknown Partner'] = i[0]
            history.append(d)

        values = {}
        if self.direction_selection == 'future':
            before = False
            if future_past.has_key('Unknown Partner'):
                before = [ future_past['Unknown Partner'] ]
            self.total_account[6] = self.total_account[6] + (before and before[0] or 0.0)
            values['direction'] = before and before[0] or 0.0
        elif self.direction_selection == 'past':
            after = False
            if future_past.has_key('Unknown Partner'):
                after = [ future_past['Unknown Partner'] ]
            self.total_account[6] = self.total_account[6] + (after and after[0] or 0.0)
            values['direction'] = after and after[0] or 0.0

        for i in range(5):
            during = False
            if history[i].has_key('Unknown Partner'):
                during = [ history[i]['Unknown Partner'] ]
            self.total_account[(i)] = self.total_account[(i)] + (during and during[0] or 0)
            values[str(i)] = during and during[0] or 0.0

        total = False
        if totals.has_key( 'Unknown Partner' ):
            total = [ totals['Unknown Partner'] ]
        values['total'] = total and total[0] or 0.0
        ## Add for total
        self.total_account[(i+1)] = self.total_account[(i+1)] + (total and total[0] or 0.0)
        values['name'] = 'Unknown Partner'

        if values['total']:
            res.append(values)

        total = 0.0
        totals = {}
        for r in res:
            total += float(r['total'] or 0.0)
            for i in range(5)+['direction']:
                totals.setdefault(str(i), 0.0)
                totals[str(i)] += float(r[str(i)] or 0.0)
        return res

    def _get_total(self,pos):
        period = self.total_account[int(pos)]
        return period or 0.0

    def _get_direction(self,pos):
        period = self.total_account[int(pos)]
        return period or 0.0

    def _get_for_period(self,pos):
        period = self.total_account[int(pos)]
        return period or 0.0

    def _get_partners(self,data):
        # TODO: deprecated, to remove in trunk
        if data['form']['result_selection'] == 'customer':
            return self._translate('Receivable Accounts')
        elif data['form']['result_selection'] == 'supplier':
            return self._translate('Payable Accounts')
        elif data['form']['result_selection'] == 'customer_supplier':
            return self._translate('Receivable and Payable Accounts')
        return ''

class report_agedpartnerbalance(osv.AbstractModel):
    _name = 'report.account.report_agedpartnerbalance'
    _inherit = 'report.abstract_report'
    _template = 'account.report_agedpartnerbalance'
    _wrapped_report_class = aged_trial_report

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
// Copyright 2010-2022 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// [START program]
// CP-SAT example that solves an assignment problem.
package com.google.ortools.sat.samples;
// [START import]
import com.google.ortools.Loader;
import com.google.ortools.sat.CpModel;
import com.google.ortools.sat.CpSolver;
import com.google.ortools.sat.CpSolverStatus;
import com.google.ortools.sat.LinearExpr;
import com.google.ortools.sat.LinearExprBuilder;
import com.google.ortools.sat.Literal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
// [END import]

/** Assignment problem. */
public class AssignmentTeamsSat {
  public static void main(String[] args) {
    Loader.loadNativeLibraries();
    // Data
    // [START data]
    int[][] costs = {
        {90, 76, 75, 70},
        {35, 85, 55, 65},
        {125, 95, 90, 105},
        {45, 110, 95, 115},
        {60, 105, 80, 75},
        {45, 65, 110, 95},
    };
    final int numWorkers = costs.length;
    final int numTasks = costs[0].length;

    final int[] allWorkers = IntStream.range(0, numWorkers).toArray();
    final int[] allTasks = IntStream.range(0, numTasks).toArray();

    final int[] team1 = {0, 2, 4};
    final int[] team2 = {1, 3, 5};
    // Maximum total of tasks for any team
    final int teamMax = 2;
    // [END data]

    // Model
    // [START model]
    CpModel model = new CpModel();
    // [END model]

    // Variables
    // [START variables]
    Literal[][] x = new Literal[numWorkers][numTasks];
    // Variables in a 1-dim array.
    for (int worker : allWorkers) {
      for (int task : allTasks) {
        x[worker][task] = model.newBoolVar("x[" + worker + "," + task + "]");
      }
    }
    // [END variables]

    // Constraints
    // [START constraints]
    // Each worker is assigned to at most one task.
    for (int worker : allWorkers) {
      List<Literal> tasks = new ArrayList<>();
      for (int task : allTasks) {
        tasks.add(x[worker][task]);
      }
      model.addAtMostOne(tasks);
    }

    // Each task is assigned to exactly one worker.
    for (int task : allTasks) {
      List<Literal> workers = new ArrayList<>();
      for (int worker : allWorkers) {
        workers.add(x[worker][task]);
      }
      model.addExactlyOne(workers);
    }

    // Each team takes at most two tasks.
    LinearExprBuilder team1Tasks = LinearExpr.newBuilder();
    for (int worker : team1) {
      for (int task : allTasks) {
        team1Tasks.add(x[worker][task]);
      }
    }
    model.addLessOrEqual(team1Tasks, teamMax);

    LinearExprBuilder team2Tasks = LinearExpr.newBuilder();
    for (int worker : team2) {
      for (int task : allTasks) {
        team2Tasks.add(x[worker][task]);
      }
    }
    model.addLessOrEqual(team2Tasks, teamMax);
    // [END constraints]

    // Objective
    // [START objective]
    LinearExprBuilder obj = LinearExpr.newBuilder();
    for (int worker : allWorkers) {
      for (int task : allTasks) {
        obj.addTerm(x[worker][task], costs[worker][task]);
      }
    }
    model.minimize(obj);
    // [END objective]

    // Solve
    // [START solve]
    CpSolver solver = new CpSolver();
    CpSolverStatus status = solver.solve(model);
    // [END solve]

    // Print solution.
    // [START print_solution]
    // Check that the problem has a feasible solution.
    if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) {
      System.out.println("Total cost: " + solver.objectiveValue() + "\n");
      for (int worker : allWorkers) {
        for (int task : allTasks) {
          if (solver.booleanValue(x[worker][task])) {
            System.out.println("Worker " + worker + " assigned to task " + task
                + ".  Cost: " + costs[worker][task]);
          }
        }
      }
    } else {
      System.err.println("No solution found.");
    }
    // [END print_solution]
  }

  private AssignmentTeamsSat() {}
}


text:
using QTFK.Data.Factory.Metadata;

namespace QTFK.Data.Factory
{
    public interface IDbBuilder
    {
        TDB createDb<TDB>(IDbMetadata<TDB> dbMetadata) where TDB : class, IDB;
    }
}


text:
function fib(n) {
  return n < 2 ? 1 : fib(n - 1) + fib(n - 2);
}

function eternal_fib() {
  var started = Date.now();
  while(true) {
    fib(20);
    // Make page responsive by making a break every 100 ms.
    if (Date.now() - started >= 100) {
      setTimeout(eternal_fib, 0);
      return;
    }
  }
}

function run_fib() {
  // Let the page do initial rendering, then go.
  setTimeout(eternal_fib, 200);
}


text:
//
//  Copyright (C) 2013 Paolo Tosco
//
//  Copyright (C) 2004-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved @@
//  This file is part of the RDKit.
//  The contents are covered by the terms of the BSD license
//  which is included in the file license.txt, found at the root
//  of the RDKit source tree.
//
#ifndef _RD_MMFFBUILDER_H_
#define _RD_MMFFBUILDER_H_

#include <vector>
#include <string>
#include <boost/shared_array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/cstdint.hpp>

namespace ForceFields {
  class ForceField;
}

namespace RDKit {
  class ROMol;
  namespace MMFF {

    //! Builds and returns a MMFF force field for a molecule
    /*!

      \param mol              the molecule to use
      \param nonBondedThresh  the threshold to be used in adding non-bonded terms
                              to the force field. Any non-bonded contact whose current
			distance is greater than \c nonBondedThresh * the minimum value
			for that contact will not be included.
      \param confId     the optional conformer id, if this isn't provided, the molecule's
                        default confId will be used.
      \param ignoreInterfragInteractions if true, nonbonded terms will not be added between
                                         fragments

      \return the new force field. The client is responsible for free'ing this.
    */
    ForceFields::ForceField *constructForceField(ROMol &mol,
      double nonBondedThresh = 100.0, int confId = -1, bool ignoreInterfragInteractions = true);

    //! Builds and returns a MMFF force field for a molecule
    /*!

      \param mol        the molecule to use
      \param mmffMolProperties        pointer to a MMFFMolProperties (as obtained by a
                        call to setupMMFFForceField())
      \param nonBondedThresh  the threshold to be used in adding non-bonded terms
                        to the force field. Any non-bonded contact whose current
			distance is greater than \c nonBondedThresh * the minimum value
			for that contact will not be included.
      \param confId     the optional conformer id, if this isn't provided, the molecule's
                        default confId will be used.
      \param ignoreInterfragInteractions if true, nonbonded terms will not be added between
                                         fragments

      \return the new force field. The client is responsible for free'ing this.
    */
    ForceFields::ForceField *constructForceField(ROMol &mol, MMFFMolProperties *mmffMolProperties,
      double nonBondedThresh = 100.0, int confId = -1, bool ignoreInterfragInteractions = true);

    namespace Tools {
      enum {
        RELATION_1_2 = 0,
        RELATION_1_3 = 1,
        RELATION_1_4 = 2,
        RELATION_1_X = 3
      };
      // these functions are primarily exposed so they can be tested.
      void setTwoBitCell(boost::shared_array<boost::uint8_t> &res,
        unsigned int pos, boost::uint8_t value);
      boost::uint8_t getTwoBitCell
        (boost::shared_array<boost::uint8_t> &res, unsigned int pos);
      boost::shared_array<boost::uint8_t> buildNeighborMatrix(const ROMol &mol);
      void addBonds(const ROMol &mol,
        MMFFMolProperties *mmffMolProperties, ForceFields::ForceField *field);
      void addAngles(const ROMol &mol,
        MMFFMolProperties *mmffMolProperties, ForceFields::ForceField *field);
      void addStretchBend(const ROMol &mol,
        MMFFMolProperties *mmffMolProperties, ForceFields::ForceField *field);
      void addOop(const ROMol &mol,
        MMFFMolProperties *mmffMolProperties, ForceFields::ForceField *field);
      void addTorsions(const ROMol &mol,
        MMFFMolProperties *mmffMolProperties, ForceFields::ForceField *field,
        std::string torsionBondSmarts = "[!$(*#*)&!D1]~[!$(*#*)&!D1]");
      void addVdW(const ROMol &mol, int confId, MMFFMolProperties *mmffMolProperties,
        ForceFields::ForceField *field, boost::shared_array<boost::uint8_t> neighborMatrix,
        double nonBondedThresh = 100.0, bool ignoreInterfragInteractions = true);
      void addEle(const ROMol &mol, int confId, MMFFMolProperties *mmffMolProperties,
        ForceFields::ForceField *field, boost::shared_array<boost::uint8_t> neighborMatrix,
        double nonBondedThresh = 100.0, bool ignoreInterfragInteractions = true);
    }
  }
}

#endif


text:
@interface PodsDummy_Pods_PlaceHolderViewLib_Example : NSObject
@end
@implementation PodsDummy_Pods_PlaceHolderViewLib_Example
@end


text:
class Question
  include MongoMapper::Document

  key  :text, String
  many :token_impacts
end


text:
namespace DataConnect.Infrastructure.Fit.RawData
{
    internal class AntChannelId : BaseRawValue
    {

        public AntChannelId(long id) : base(id)
        {
        }
    }
}


text:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.views.generic.base import TemplateView
from django.conf.urls.static import static
from django.conf import settings

import allauthdemo.views

admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', TemplateView.as_view(template_name='visitor/landing-index.html'), name='landing_index'),
    url(r'^about$', TemplateView.as_view(template_name='visitor/landing-about.html'), name='landing_about'),
    url(r'^terms/$', TemplateView.as_view(template_name='visitor/terms.html'), name='website_terms'),
    url(r'^contact$', TemplateView.as_view(template_name='visitor/contact.html'), name='website_contact'),

    (r'^accounts/', include('allauth.urls')),
    url(r'^accounts/profile/$', 'allauthdemo.auth.views.account_profile', name='account_profile'),

    url(r'^member/$', allauthdemo.views.member_index, name='user_home'),
    url(r'^member/action$', allauthdemo.views.member_action, name='user_action'),

    url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)


text:
module Filter where

import qualified Data.Map.Strict as M

import qualified Data.EventList.Relative.TimeBody as EL
import qualified Sound.MIDI.File as File
import qualified Sound.MIDI.File.Event as E
import qualified Sound.MIDI.Message.Channel as CM
import qualified Sound.MIDI.Message.Channel.Voice as VM

type ChannelInstrumentMap = M.Map CM.Channel CM.Program

modifyFileWithMap :: ChannelInstrumentMap -> File.T -> File.T
modifyFileWithMap m (File.Cons t d tracks) =
  File.Cons t d $
    map (EL.mapBody (modifyEventWithMap m)) tracks

modifyEventWithMap :: ChannelInstrumentMap -> E.T -> E.T
modifyEventWithMap m evt =
  case evt of
       E.MIDIEvent msg -> E.MIDIEvent $ modifyChannelMessageWithMap m msg
       _               -> evt

modifyChannelMessageWithMap :: ChannelInstrumentMap -> CM.T -> CM.T
modifyChannelMessageWithMap m msg@(CM.Cons channel body) =
  case body of
       CM.Mode _     -> msg
       CM.Voice vmsg ->
         CM.Cons channel (CM.Voice $ modifyVoiceMessageWithMap m channel vmsg)

modifyVoiceMessageWithMap :: ChannelInstrumentMap -> CM.Channel ->
                             VM.T -> VM.T
modifyVoiceMessageWithMap m ch msg =
  case msg of
       VM.ProgramChange p ->
         VM.ProgramChange $ M.findWithDefault p ch m
       _                  ->
         msg


text:
PORTNAME=	System.Security.Cryptography.Csp
PORTVERSION=	1.0.0.0

NET_DEPENDS+=	System.Diagnostics.Debug>=1.0:${PORTSDIR}/dotnet/System.Diagnostics.Debug \
		System.IO.FileSystem>=1.0:${PORTSDIR}/dotnet/System.IO.FileSystem \
		System.Linq>=1.0:${PORTSDIR}/dotnet/System.Linq \
		System.Runtime>=1.0:${PORTSDIR}/dotnet/System.Runtime \
		System.Security.Cryptography.Algorithms>=1.0:${PORTSDIR}/dotnet/System.Security.Cryptography.Algorithms \
		System.Security.Cryptography.Primitives>=1.0:${PORTSDIR}/dotnet/System.Security.Cryptography.Primitives \
		System.Security.Cryptography.Encoding>=1.0:${PORTSDIR}/dotnet/System.Security.Cryptography.Encoding

post-patch:
	@${FIND} ${WRKSRC}/src/${PORTNAME}/src -name "*.Windows.cs" -delete

DOTNET_RESOURCE_COMMAND=cd ${WRKSRC}/src/${PORTNAME}/src/Resources && ${DOTNET_RESGEN} Strings.resx,FxResources.${PORTNAME}.SR.resources

DOTNET_REFERENCES+=	${DOTNET_REF}:${DOTNET_PATH}/System.Diagnostics.Debug.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.IO.FileSystem.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.Linq.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.Runtime.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.Security.Cryptography.Algorithms.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.Security.Cryptography.Primitives.dll \
			${DOTNET_REF}:${DOTNET_PATH}/System.Security.Cryptography.Encoding.dll

DOTNET_RESOURCES+=	${DOTNET_RES}:${WRKSRC}/src/${PORTNAME}/src/Resources/FxResources.${PORTNAME}.SR.resources

DOTNET_DEFINES+=	-nowarn:0436

DOTNET_FILES+=		${WRKSRC}/src/Common/src/Internal/Cryptography/Windows/CryptoThrowHelper.cs \
			${WRKSRC}/src/Common/src/Microsoft/Win32/SafeHandles/SafeHandleCache.cs \
			${WRKSRC}/src/Common/src/Microsoft/Win32/SafeHandles/SafeHandleZeroOrMinusOneIsInvalid.cs \
			${WRKSRC}/src/Common/src/Interop/Windows/Interop.Libraries.cs \
			${WRKSRC}/src/Common/src/Interop/Windows/Crypt32/Interop.FindOidInfo.cs

.include <../../dotnet/coreclr/corefx.common>


text:
<?php
/*
@author Lars Syfuß
*/

require("filteroptions.php"); // for testing
require("aggregation.php"); // for testing

$filteroptions = new filteroptions();
$aggregation = new aggregation();

// ### test getAggregationResult ###
$exampleRequest = "https://envirocar.org/api/stable/tracks?contains=2014-01-07T18:44:40Z,2014-01-05T01:19:02Z";
$jsonTracks = $filteroptions -> getFilterTracks($exampleRequest);

// Test calculateSD()
echo "Test  calculateSD()
";
$values = array(1,2,3,4,5);
$sd = $aggregation->calculateSD($values, true);
echo "

";

// Test getAvailablePhenomenons()
$decodedTracks = json_decode($jsonTracks, true); // decode tracks
$track = $decodedTracks["tracks"][0];
echo "Test getAvailablePhenomenons()
";
$aggregationResult = $aggregation->getAvailablePhenomenons($track, false, true);
echo "

";

// Test getAggregationResult()
echo "Test getAggregationResult()
";
$aggregationResult = $aggregation->getAggregationResult($jsonTracks, "CO2", true);
echo "

";

?>


text:
package org.majimena.petical.web.api.clinics.customers;

import mockit.Injectable;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Tested;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.majimena.petical.WebApplication;
import org.majimena.petical.TestUtils;
import org.majimena.petical.WebAppTestConfiguration;
import org.majimena.petical.config.SpringMvcConfiguration;
import org.majimena.petical.domain.Clinic;
import org.majimena.petical.domain.Customer;
import org.majimena.petical.domain.User;
import org.majimena.petical.domain.customer.CustomerCriteria;
import org.majimena.petical.security.ResourceCannotAccessException;
import org.majimena.petical.security.SecurityUtils;
import org.majimena.petical.service.CustomerService;
import org.majimena.petical.web.utils.PaginationUtils;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.validation.BindException;

import java.util.Arrays;
import java.util.Optional;

import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * @see ClinicCustomerController
 */
@RunWith(Enclosed.class)
public class ClinicCustomerControllerTest {

    private static Customer newCustomer() {
        return Customer.builder()
                .id("customer123")
                .clinic(Clinic.builder().id("c123").build())
                .user(User.builder().id("u123").build())
                .removed(Boolean.FALSE)
                .build();
    }

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @SpringApplicationConfiguration(classes = WebAppTestConfiguration.class)
    public static class GetAllTest {

        private MockMvc mockMvc;
        @Tested
        private ClinicCustomerController sut = new ClinicCustomerController();
        @Injectable
        private CustomerService customerService;
        @Injectable
        private CustomerValidator customerValidator;
        @Mocked
        private SecurityUtils securityUtils;

        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.standaloneSetup(sut)
                    .setHandlerExceptionResolvers(new SpringMvcConfiguration().restExceptionResolver())
                    .build();
        }

        @Test
        public void ページングされてデータが取得できること() throws Exception {
            CustomerCriteria criteria = CustomerCriteria.builder().clinicId("c123").build();
            Pageable pageable = PaginationUtils.generatePageRequest(1, 1);

            final Clinic clinic = Clinic.builder().id("c123").build();
            final Customer d1 = Customer.builder().id("c111").clinic(clinic).user(User.builder().id("u111").build()).build();
            final Customer d2 = Customer.builder().id("c222").clinic(clinic).user(User.builder().id("u222").build()).build();

            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c123");
                result = null;
                customerService.getCustomersByCustomerCriteria(criteria, pageable);
                result = new PageImpl(Arrays.asList(d1, d2), pageable, 2);
            }};

            mockMvc.perform(get("/api/v1/clinics/c123/customers")
                    .param("page", "1")
                    .param("per_page", "1"))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_JSON + ";charset=UTF-8"))
                    .andExpect(jsonPath("$.[0].id", is("c111")))
                    .andExpect(jsonPath("$.[0].clinic.id", is("c123")))
                    .andExpect(jsonPath("$.[0].user.id", is("u111")))
                    .andExpect(jsonPath("$.[1].id", is("c222")))
                    .andExpect(jsonPath("$.[1].clinic.id", is("c123")))
                    .andExpect(jsonPath("$.[1].user.id", is("u222")));
        }

        @Test
        public void 権限がない場合は401エラーとなること() throws Exception {
            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c999");
                result = new ResourceCannotAccessException();
            }};

            mockMvc.perform(get("/api/v1/clinics/c999/customers")
                    .param("page", "1")
                    .param("per_page", "1"))
                    .andDo(print())
                    .andExpect(status().isUnauthorized());
        }
    }

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @SpringApplicationConfiguration(classes = WebAppTestConfiguration.class)
    public static class GetTest {

        private MockMvc mockMvc;
        @Tested
        private ClinicCustomerController sut = new ClinicCustomerController();
        @Injectable
        private CustomerService customerService;
        @Injectable
        private CustomerValidator customerValidator;
        @Mocked
        private SecurityUtils securityUtils;

        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.standaloneSetup(sut)
                    .setHandlerExceptionResolvers(new SpringMvcConfiguration().restExceptionResolver())
                    .build();
        }

        @Test
        public void 該当するデータが取得できること() throws Exception {
            final Clinic clinic = Clinic.builder().id("c123").build();
            final Customer customer = Customer.builder().id("customer123").clinic(clinic).user(User.builder().id("u111").build()).build();

            new NonStrictExpectations() {{
                SecurityUtils.isUserInClinic("c123");
                result = true;
                customerService.getCustomerByCustomerId("customer123");
                result = Optional.ofNullable(customer);
            }};

            mockMvc.perform(get("/api/v1/clinics/c123/customers/customer123"))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.id", is("customer123")))
                    .andExpect(jsonPath("$.clinic.id", is("c123")))
                    .andExpect(jsonPath("$.user.id", is("u111")));
        }

        @Test
        public void 該当するデータがない場合は404エラーとなること() throws Exception {
            new NonStrictExpectations() {{
                SecurityUtils.isUserInClinic("c123");
                result = true;
                customerService.getCustomerByCustomerId("customer123");
                result = Optional.ofNullable(null);
            }};

            mockMvc.perform(get("/api/v1/clinics/c123/customers/customer123"))
                    .andDo(print())
                    .andExpect(status().isNotFound());
        }

        @Test
        public void 権限がない場合は401エラーとなること() throws Exception {
            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c999");
                result = new ResourceCannotAccessException();
                customerService.getCustomerByCustomerId("customer123");
                times = 0;
            }};

            mockMvc.perform(get("/api/v1/clinics/c999/customers/customer123"))
                    .andDo(print())
                    .andExpect(status().isUnauthorized());
        }

        @Test
        public void 取得したデータの権限が異なっている場合は401エラーとなること() throws Exception {
            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c123");
                result = new ResourceCannotAccessException();
            }};

            mockMvc.perform(get("/api/v1/clinics/c123/customers/customer123"))
                    .andDo(print())
                    .andExpect(status().isUnauthorized());
        }
    }

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @SpringApplicationConfiguration(classes = WebAppTestConfiguration.class)
    public static class PostTest {

        private MockMvc mockMvc;
        @Tested
        private ClinicCustomerController sut = new ClinicCustomerController();
        @Injectable
        private CustomerValidator customerValidator;
        @Injectable
        private CustomerService customerService;
        @Mocked
        private SecurityUtils securityUtils;

        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.standaloneSetup(sut)
                    .setHandlerExceptionResolvers(new SpringMvcConfiguration().restExceptionResolver())
                    .build();
        }

        @Test
        public void POSTしたデータが登録できること() throws Exception {
            Customer customer = newCustomer();

            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c123");
                result = null;
                customerValidator.validate(customer, (BindException) any);
                result = null;
                customerService.saveCustomer("c123", customer);
                result = customer;
            }};

            mockMvc.perform(post("/api/v1/clinics/c123/customers")
                    .contentType(TestUtils.APPLICATION_JSON_UTF8)
                    .content(TestUtils.convertObjectToJsonBytes(customer)))
                    .andDo(print())
                    .andExpect(status().isCreated())
                    .andExpect(jsonPath("$.id", is("customer123")))
                    .andExpect(jsonPath("$.activated", is(false)))
                    .andExpect(jsonPath("$.blocked", is(false)))
                    .andExpect(jsonPath("$.clinic.id", is("c123")))
                    .andExpect(jsonPath("$.user.id", is("u123")));
        }

        @Test
        public void 権限がない場合は401エラーとなること() throws Exception {
            Customer customer = newCustomer();

            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c999");
                result = new ResourceCannotAccessException();
            }};

            mockMvc.perform(post("/api/v1/clinics/c999/customers")
                    .contentType(TestUtils.APPLICATION_JSON_UTF8)
                    .content(TestUtils.convertObjectToJsonBytes(customer)))
                    .andDo(print())
                    .andExpect(status().isUnauthorized());
        }
    }

    @RunWith(SpringJUnit4ClassRunner.class)
    @WebAppConfiguration
    @SpringApplicationConfiguration(classes = WebApplication.class)
    public static class PutTest {

        private MockMvc mockMvc;
        @Tested
        private ClinicCustomerController sut = new ClinicCustomerController();
        @Injectable
        private CustomerValidator customerValidator;
        @Injectable
        private CustomerService customerService;
        @Mocked
        private SecurityUtils securityUtils;

        @Before
        public void setup() {
            mockMvc = MockMvcBuilders.standaloneSetup(sut)
                    .setHandlerExceptionResolvers(new SpringMvcConfiguration().restExceptionResolver())
                    .build();
        }

        @Test
        public void PUTしたデータが登録できること() throws Exception {
            Customer customer = newCustomer();
            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c123");
                result = null;
                customerValidator.validate(customer, (BindException) any);
                result = null;
                customerService.updateCustomer(customer);
                result = customer;
            }};

            mockMvc.perform(put("/api/v1/clinics/c123/customers/customer123")
                    .contentType(TestUtils.APPLICATION_JSON_UTF8)
                    .content(TestUtils.convertObjectToJsonBytes(customer)))
                    .andDo(print())
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.id", is("customer123")))
                    .andExpect(jsonPath("$.activated", is(false)))
                    .andExpect(jsonPath("$.blocked", is(false)))
                    .andExpect(jsonPath("$.clinic.id", is("c123")))
                    .andExpect(jsonPath("$.user.id", is("u123")));
        }

        @Test
        public void 権限がない場合は401エラーとなること() throws Exception {
            Customer customer = newCustomer();

            new NonStrictExpectations() {{
                SecurityUtils.throwIfDoNotHaveClinicRoles("c999");
                result = new ResourceCannotAccessException();
            }};

            mockMvc.perform(put("/api/v1/clinics/c999/customers/customer123")
                    .contentType(TestUtils.APPLICATION_JSON_UTF8)
                    .content(TestUtils.convertObjectToJsonBytes(customer)))
                    .andDo(print())
                    .andExpect(status().isUnauthorized());
        }
    }
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';

// Task service
angular.module('flowableApp').service('ProcessService', ['$http', '$q', '$rootScope', 'RelatedContentService',
    function ($http, $q, $rootScope, RelatedContentService) {

        var httpAsPromise = function(options) {
            var deferred = $q.defer();
            $http(options).
                success(function (response, status, headers, config) {
                    deferred.resolve(response);
                })
                .error(function (response, status, headers, config) {
                    deferred.reject(response);
                });
            return deferred.promise;
        };

        this.getProcessDefinitions = function(appDefinitionKey) {
            var url = FLOWABLE.CONFIG.contextRoot + '/app/rest/process-definitions?latest=true';
            if (appDefinitionKey) {
                url += '&appDefinitionKey=' + appDefinitionKey;
            }
            return httpAsPromise(
                {
                    method: 'GET',
                    url: url
                }
            );
        };

        this.createProcess = function(processData) {
            var deferred = $q.defer();
            $http({
                method: 'POST',
                url: FLOWABLE.CONFIG.contextRoot + '/app/rest/process-instances',
                data: processData
            }).success(function (response, status, headers, config) {
                $rootScope.$broadcast('new-process-created', response);
                deferred.resolve(response);
            }).error(function (response, status, headers, config) {
                $rootScope.addAlert(response.message, 'error');
                deferred.reject(response);
            });

            var promise = deferred.promise;
            return promise;
        };

        this.deleteProcess = function(processInstanceId) {
            var deferred = $q.defer();
            $http({
                method: 'DELETE',
                url: FLOWABLE.CONFIG.contextRoot + '/app/rest/process-instances/' + processInstanceId
            }).success(function (response, status, headers, config) {
                $rootScope.$broadcast('processinstance-deleted', response);
                deferred.resolve(response);
            }).error(function (response, status, headers, config) {
                $rootScope.addAlert(response.message, 'error');
                deferred.reject(response);
            });

            var promise = deferred.promise;
            return promise;
        }
    }]
);


text:
Usage
=====

.. code-block:: bash

   $ cd example
   $ python ps_pages_example.py

or

.. code-block:: bash

   $ cd example
   $ python setup.py develop
   $ pserve development.ini --reload

and goto http://localhost:6543/admin/

Auth example
------------

.. code-block:: bash

   $ pserve development_auth.ini --reload

and goto http://localhost:6543/admin/
and then http://localhost:6543/login


text:
@interface HellowWorldHud : CCLayer
{
	CCLabelTTF *label;
}

-(void)numCollectedChanged:(int)numCollected;

@end


text:
<?php

namespace Dry\ConsoleBundle;
use Symfony\Bundle\FrameworkBundle\Console\Application;

class KonsoleApplication extends Application {

}


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

<title>R-Index</title>
<meta name="date" content="2014-11-09">
<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 Letter

Next Letter

Frames

No Frames

All Classes

A C D E F G H I L M O P R S T U V W

R

redo() - Method in class edu.dynamic.dynamiz.controller.CommandAdd

redo() - Method in class edu.dynamic.dynamiz.controller.CommandDelete

redo() - Method in class edu.dynamic.dynamiz.controller.CommandMark

redo() - Method in class edu.dynamic.dynamiz.controller.CommandUnmark

redo() - Method in class edu.dynamic.dynamiz.controller.CommandUpdate

redo() - Method in interface edu.dynamic.dynamiz.controller.Undoable

REGEX_DATE - Static variable in class edu.dynamic.dynamiz.structure.MyDate

REGEX_DATETIME - Static variable in class edu.dynamic.dynamiz.structure.MyDateTime

removeEmptyStringsInArray(String[]) - Static method in class edu.dynamic.dynamiz.parser.Util

removeEmptyStringsInList(List<String>) - Static method in class edu.dynamic.dynamiz.parser.Util

removeItem(int) - Method in class edu.dynamic.dynamiz.storage.Storage

Removes the ToDoItem with the given ID from the list.

run() - Method in class edu.dynamic.dynamiz.controller.WriteToFileThread

run() - Method in class edu.dynamic.dynamiz.UI.UI

A C D E F G H I L M O P R S T U V W

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
package guru.nidi.android.support;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class CpuInfo {
    public enum ProcessorFamily {
        INTEL, ARM, UNKNOWN
    }

    private static final Map<String, List<String>> info = findInfo();

    public static Map<String, List<String>> getInfo() {
        return info;
    }

    public static ProcessorFamily getProcessorFamily() {
        ProcessorFamily res = familyOf(getInfo("Processor"));
        if (res == ProcessorFamily.UNKNOWN) {
            res = familyOf(getInfo("vendor_id"));
        }
        return res;
    }

    public static String getInfo(String key) {
        final List<String> values = info.get(key);
        return (values == null || values.isEmpty()) ? null : values.get(0);
    }

    private static ProcessorFamily familyOf(String value) {
        if (value != null && value.contains("ARM")) {
            return ProcessorFamily.ARM;
        }
        if (value != null && value.contains("Intel")) {
            return ProcessorFamily.INTEL;
        }
        return ProcessorFamily.UNKNOWN;
    }

    private static String run(String... cmd) {
        String result = "";
        BufferedReader in = null;
        try {
            ProcessBuilder builder = new ProcessBuilder(cmd);
            builder.redirectErrorStream(true);
            Process process = builder.start();
            process.waitFor();
            in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            while (in.ready()) {
                result += in.readLine() + "\n";
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            IoUtils.close(in);
        }
        return result;
    }

    private static Map<String, List<String>> findInfo() {
        final String raw = run("/system/bin/cat", "/proc/cpuinfo");
        final String[] lines = raw.split("\n");
        final Map<String, List<String>> info = new LinkedHashMap<>();
        for (String line : lines) {
            if (line.length() > 0) {
                int pos = line.indexOf(':');
                String key, value;
                if (pos < 0) {
                    key = line;
                    value = "";
                } else {
                    key = line.substring(0, pos).trim();
                    value = pos == line.length() - 1 ? "" : line.substring(pos + 1).trim();
                }
                List<String> old = info.get(key);
                if (old == null) {
                    old = new ArrayList<>();
                    info.put(key, old);
                }
                old.add(value);
            }
        }
        return info;
    }
}


text:
<?php

$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('test');
echo wddx_serialize_value($xml, 'Variables') . "\n";
echo "DONE";
?>