text:
var IndexFile = require('lib/natural/wordnet/index_file'),
  DataFile = require('lib/natural/wordnet/data_file'),
  WordNet = require('lib/natural/wordnet/wordnet');

describe('wordnet', function() {
  describe('index_file', function() {
    it('should build a valid url', function() {
      var indexFile = new IndexFile('./spec/test_data/wordnet', 'http://wordnet.naturalnode.com/', 'noun');
      expect(indexFile.url.href).toBe('http://wordnet.naturalnode.com/index.noun.gz');
    });

    it('should miss a record', function() {
      var indexFile = new IndexFile('./spec/test_data/wordnet', 'http://wordnet.naturalnode.com/', 'noun');
      indexFile.lookup('aac', function(result) {
        expect(result).toBeNull();
        asyncSpecDone();
      });

      asyncSpecWait();
    });

    it('should find a record', function() {
      var indexFile = new IndexFile('./spec/test_data/wordnet', 'http://wordnet.naturalnode.com/', 'noun');
      indexFile.lookup('pass', function(result) {
        expect(result.lemma).toBe('pass');
        expect(result.pos).toBe('n');
        expect(result.ptrSymbol.length == 5);
        expect(result.synsetOffset.length == 16);
        asyncSpecDone();
      });

      asyncSpecWait();
    });
  });

  describe('data_file', function() {
    it('should find a record', function() {
      var dataFile = new DataFile('./spec/test_data/wordnet/', 'http://wordnet.naturalnode.com/', 'noun');

      dataFile.get(1740, function(data) {
        expect(data.lemma).toBe('entity');
        expect(data.ptrs.length).toBe(3);
        asyncSpecDone();
      });

      asyncSpecWait();
    });
  });

  it('should look up a word', function() {
    var wordnet = new WordNet('./spec/test_data/wordnet/', 'http://wordnet.naturalnode.com/');

    wordnet.lookup('entity', function(records) {
      expect(records.length).toBe(1);
      expect(records[0].lemma).toBe('entity');
      asyncSpecDone();
    });

    asyncSpecWait();
  });

  it('should handle a miss', function() {
    var wordnet = new WordNet('./spec/test_data/wordnet/', 'http://wordnet.naturalnode.com/');

    wordnet.lookup('argombiszki', function(records) {
      expect(records.length).toBe(0);
      asyncSpecDone();
    });

    asyncSpecWait();
  });

  it('should get a word', function() {
    var wordnet = new WordNet('./spec/test_data/wordnet/', 'http://wordnet.naturalnode.com/');

    wordnet.get(1740, 'n', function(record) {
      expect(record.lemma).toBe('entity');
      asyncSpecDone();
    });

    asyncSpecWait();
  });
});


text:
package main

import (
	"flag"
	"fmt"
	"log"
	redis "github.com/phpor/goredis"
	"time"
)

func main() {
	flag.Parse()
	fmt.Printf("\n\n=== Bench synchclient ================ %d Concurrent Clients -- %d opts each --- \n\n", *workers, *opcnt)
	for _, task := range tasks {
		benchTask(task, *opcnt, *workers, true)
	}
}

// ----------------------------------------------------------------------------
// types and props
// ----------------------------------------------------------------------------

// workers option.  default is equiv to -w=10 on command line
var workers = flag.Int("w", 10, "number of concurrent workers")

// opcnt option.  default is equiv to -n=2000 on command line
var opcnt = flag.Int("n", 2000, "number of task iterations per worker")

// array of Tasks to run in sequence
// Add a task to the list to bench to the runner.
// Tasks are run in sequence.
var tasks = []taskSpec{
	taskSpec{doPing, "PING"},
	taskSpec{doSet, "SET"},
	taskSpec{doGet, "GET"},
	taskSpec{doIncr, "INCR"},
	taskSpec{doDecr, "DECR"},
	taskSpec{doLpush, "LPUSH"},
	taskSpec{doLpop, "LPOP"},
	taskSpec{doRpush, "RPUSH"},
	taskSpec{doRpop, "RPOP"},
}

// ----------------------------------------------------------------------------
// benchmarker
// ----------------------------------------------------------------------------

// redis task function type def
type redisTask func(id string, signal chan int, client redis.Client, iterations int)

// task info
type taskSpec struct {
	task redisTask
	name string
}

func benchTask(taskspec taskSpec, iterations int, workers int, printReport bool) (delta time.Duration, err error) {
	signal := make(chan int, workers) // Buffering optional but sensible.
	clients, e := makeConcurrentClients(workers)
	if e != nil {
		return 0, e
	}
	t0 := time.Now()
	for i := 0; i < workers; i++ {
		id := fmt.Sprintf("%d", i)
		go taskspec.task(id, signal, clients[i], iterations)
	}
	for i := 0; i < workers; i++ {
		<-signal
	}
	delta = time.Now().Sub(t0)
	for i := 0; i < workers; i++ {
		clients[i].Quit() // will be deprecated soon
	}

	if printReport {
		report("concurrent "+taskspec.name, delta, iterations*workers)
	}

	return
}

func makeConcurrentClients(workers int) (clients []redis.Client, err error) {
	clients = make([]redis.Client, workers)
	for i := 0; i < workers; i++ {
		spec := redis.DefaultSpec().Db(13).Password("go-redis")
		client, e := redis.NewSynchClientWithSpec(spec)
		if e != nil {
			log.Println("Error creating client for worker: ", e)
			return nil, e
		}
		clients[i] = client
	}
	return
}

func report(cmd string, delta time.Duration, cnt int) {
	fmt.Printf("---\n")
	fmt.Printf("cmd: %s\n", cmd)
	fmt.Printf("%d iterations of %s in %d msecs\n", cnt, cmd, delta/time.Millisecond)
	fmt.Printf("---\n\n")
}

// ----------------------------------------------------------------------------
// redis tasks
// ----------------------------------------------------------------------------

func doPing(id string, signal chan int, client redis.Client, cnt int) {
	for i := 0; i < cnt; i++ {
		client.Ping()
	}
	signal <- 1
}
func doIncr(id string, signal chan int, client redis.Client, cnt int) {
	key := "ctr-" + id
	for i := 0; i < cnt; i++ {
		client.Incr(key)
	}
	signal <- 1
}
func doDecr(id string, signal chan int, client redis.Client, cnt int) {
	key := "ctr-" + id
	for i := 0; i < cnt; i++ {
		client.Decr(key)
	}
	signal <- 1
}
func doSet(id string, signal chan int, client redis.Client, cnt int) {
	key := "set-" + id
	value := []byte("foo")
	for i := 0; i < cnt; i++ {
		client.Set(key, value)
	}
	signal <- 1
}
func doGet(id string, signal chan int, client redis.Client, cnt int) {
	key := "set-" + id
	for i := 0; i < cnt; i++ {
		client.Get(key)
	}
	signal <- 1
}
func doLpush(id string, signal chan int, client redis.Client, cnt int) {
	key := "list-L-" + id
	value := []byte("foo")
	for i := 0; i < cnt; i++ {
		client.Lpush(key, value)
	}
	signal <- 1
}
func doLpop(id string, signal chan int, client redis.Client, cnt int) {
	key := "list-L-" + id
	for i := 0; i < cnt; i++ {
		client.Lpop(key)
	}
	signal <- 1
}

func doRpush(id string, signal chan int, client redis.Client, cnt int) {
	key := "list-R-" + id
	value := []byte("foo")
	for i := 0; i < cnt; i++ {
		client.Rpush(key, value)
	}
	signal <- 1
}
func doRpop(id string, signal chan int, client redis.Client, cnt int) {
	key := "list-R" + id
	for i := 0; i < cnt; i++ {
		client.Rpop(key)
	}
	signal <- 1
}

redpajama_set_name: RedPajamaGithub


text:
//=============================================================================
/**
 *  @file     test_end_event_loop.cpp
 *
 *  $Id: test_end_event_loop.cpp 93639 2011-03-24 13:32:13Z johnnyw $
 *
 *  This program tests the event loop mechanism of the
 *  Proactor. To end the event loop, threads that are blocked in
 *  waiting for completions are  woken up and the event loop comes
 *  to the end. This is tested in this program.
 *  Threads are doing <run_event_loop> with/without time_out
 *  values and the main thread calls <end_event_loop>.
 *  make
 *  ./test_end_event_loop
 *
 *  @author  Alexander Babu Arulanthu <alex@cs.wustl.edu>
 */
//=============================================================================

#include "ace/OS_NS_unistd.h"
#include "ace/Proactor.h"
#include "ace/Task.h"
#include "ace/WIN32_Proactor.h"
#include "ace/POSIX_Proactor.h"
#include "ace/OS_main.h"

#if defined (ACE_HAS_WIN32_OVERLAPPED_IO) || defined (ACE_HAS_AIO_CALLS)
// This only works on Win32 platforms and on Unix platforms supporting
// POSIX aio calls.

/**
 * @class My_Task:
 *
 * @brief Contains thread functions which execute event loops. Each
 * thread waits for a different signal.
 */
class My_Task: public ACE_Task <ACE_NULL_SYNCH>
{
public:
  // Constructor.
  My_Task (void)
    : time_flag_ (0)
    {}

  /// Destructor.
  virtual ~My_Task (void) {}

  //FUZZ: disable check_for_lack_ACE_OS
  // If time_flag is zero do the eventloop indefinitely, otherwise do
  // it for finite amount of time (13secs!!!).
  int open (void *timed_event_loop)
    {
  //FUZZ: enble check_for_lack_ACE_OS

      // Set the local variable.
      if (timed_event_loop == 0)
        this->time_flag_ = 0;
      else
        this->time_flag_ = 1;

      // Spawn the threads.
      if (this->activate (THR_NEW_LWP, 5) == -1)
        ACE_ERROR_RETURN ((LM_ERROR,
                           "%N:%l:%p\n",
                           "My_Task:open: <activate> failed"),
                          -1);

      return 0;
    }

  // Thread function.
  int svc (void)
    {
      ACE_DEBUG ((LM_DEBUG,
                  "(%P|%t):Starting svc routine\n"));

      if (this->time_flag_)
        {
          ACE_DEBUG ((LM_DEBUG,
                      "(%P|%t):Going to do *timed* <run_event_loop>\n"));

          ACE_Time_Value run_time (13);

          if (ACE_Proactor::instance ()->run_event_loop (run_time) == -1)
            ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t):%p.\n",
                               "<Proactor::run_event_loop> failed"),
                              -1);
        }
      else
        {
          ACE_DEBUG ((LM_DEBUG,
                      "(%P|%t):Going to do *indefinite* <run_event_loop>\n"));

          if (ACE_Proactor::instance ()->run_event_loop () == -1)
            ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t):%p.\n",
                               "<Proactor::run_event_loop> failed"),
                              -1);
        }
      return 0;
    };

private:
  /// If zero, indefinite event loop, otherwise timed event loop.
  int time_flag_;
};

int
ACE_TMAIN (int argc, ACE_TCHAR *argv [])
{
  ACE_UNUSED_ARG (argc);
  ACE_UNUSED_ARG (argv);

  ACE_DEBUG ((LM_DEBUG,
              "(%P | %t):Test starts\n"));

  // Let us get the singleton proactor created here. This is very
  // important. This will mask the signal used in the Proactor masked
  // for the main thread (and all the threads).
  ACE_Proactor *proactor = ACE_Proactor::instance ();
  ACE_UNUSED_ARG (proactor);

  My_Task task1, task2;

  // Test the indefinite run event loop.
  if (task1.open (0) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%N:%l:(%P | %t):Failed to <open> the task\n"),
                      1);

  // Test the indefinite run event loop. Just pass a non-zero.
  if (task2.open ((void *)&task2) == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%N:%l:(%P | %t):Failed to <open> the task\n"),
                      1);

  // Give a gap.
  ACE_OS::sleep (3);

  // End the event loop.
  if (ACE_Proactor::instance ()->end_event_loop () == -1)
    ACE_ERROR_RETURN ((LM_ERROR,
                       "%N:%l:(%P | %t):Failed to <end_event_loop>\n"),
                      1);

  ACE_Thread_Manager::instance ()->wait ();

  ACE_DEBUG ((LM_DEBUG,
              "(%P | %t):Test ends\n"));
  return 0;
}

#else /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */

int
ACE_TMAIN (int, ACE_TCHAR *[])
{
  ACE_DEBUG ((LM_DEBUG,
              "This example cannot work with AIOCB_Proactor.\n"));
  return 1;
}

#endif /* ACE_HAS_WIN32_OVERLAPPED_IO || ACE_HAS_AIO_CALLS */


text:
[![Build Status](https://secure.travis-ci.org/hotchpotch/pry-clipboard.png?branch=master)](http://travis-ci.org/hotchpotch/pry-clipboard)

Pry clipboard utility.

Copy history/result to clipboard.

## Installation

    $ gem install pry-clipboard

## Recommend setting

Your ~/.pryrc

```ruby
begin
  require 'pry-clipboard'
  # aliases
  Pry.config.commands.alias_command 'ch', 'copy-history'
  Pry.config.commands.alias_command 'cr', 'copy-result'
rescue LoadError => e
  warn "can't load pry-clipboard"
end
```

## Usage

```ruby
require 'pry-clipboard'
copy-history --help
copy-result --help
paste --help
```

### Copy history to clipboard

```ruby
pry(main)> def fib(n)
pry(main)*   n < 2 ? n : fib(n-1) + fib(n-2)
pry(main)* end
> nil
pry(main)> fib(10)
=> 55
pry(main)> copy-history
-*-*- Copy history to clipboard -*-*-
fib(10)
```

### Copy history to clipboard with result

```ruby
[5] pry(main)> fib(10)
=> 55
[6] pry(main)> copy-history -l
-*-*- Copy history to clipboard -*-*-
fib(10)
#=> 55
```

### Copy result

```ruby
pry(main)> 'hello' * 3
=> "hellohellohello"
pry(main)> copy-result
-*-*- Copy result to clipboard -*-*-
hellohellohello
```

### paste

```ruby
pry(main)> Clipboard.copy '3 * 5'
=> "3 * 5"
pry(main)> paste
=> 15
```

### N / --head / --tail options

```ruby
pry(main)> history --tail 10
 4: fib(10)
 5: copy-history
 6: copy-history -l
 7: fib(10)
 8: copy-history -l
 9: 'hello' * 3
10: copy-result
11: history --tail 10
12: copy-result --tail 3
13: copy-history --tail 3
pry(main)> copy-history 9
-*-*- Copy history to clipboard -*-*-
'hello' * 3
pry(main)> copy-history -tail 5
-*-*- Copy history to clipboard -*-*-
copy-result
history --tail 10
copy-result --tail 3
copy-history --tail 3
history --tail 10
```

### --range option

```ruby
pry(main)> history --head 10
 1: def fib(n)
 2:   n < 2 ? n : fib(n-1) + fib(n-2)
 3: end
 4: fib(10)
 5: copy-history
 6: copy-history -l
 7: fib(10)
 8: copy-history -l
 9: 'hello' * 3
10: copy-result
pry(main)> copy-history --range 1..4
-*-*- Copy history to clipboard -*-*-
def fib(n)
  n < 2 ? n : fib(n-1) + fib(n-2)
end
fib(10)
```

### --grep option

```ruby
pry(main)> copy-history --grep def
-*-*- Copy history to clipboard -*-*-
def fib(n)
def hello
```

## Author

* Yuichi Tateno


text:
<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
if (isset($pageTitle)) {
    $pageTitleDisplay = $pageTitle;
} else {
    $pageTitleDisplay = "Home";
}
?>
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <?PHP
        if ($_SERVER['SERVER_NAME'] == 'vysproindia.com') {
            ?>

            <?PHP
        }
        ?>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title><?PHP echo $pageTitleDisplay; ?> | Vyspro India-Vysya Professionals Association</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
        <link rel="apple-touch-icon" href="touch-icon-iphone.png" />
        <link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png" />
        <link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png" />
        <link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png" />
        <meta name="description" content="The VYSPRO is an association of Professionals from 8 professions. These are Chartered Accountants, Company Secretaries, Cost Accountants, Doctors, Advocates, Engineers,MBA's and MCAs." />
        <meta name="keywords" content="arya vysya sangam, arya vysya, arya vysya Vyspro India, Vyspro, aryavysya, aryavyshya, arya vysya community, online arya vysya, vysya, vaishya, gupta, komati,arya vysya gothralu, arya vysya satralu, arya vysya satram, kanyaka parameshwari,vasavi matha, arya vysya social service, arya vysya donations, arya vysya activities, relationship, arya vysya caste,hindu religion,Free Registration" />
        <meta name="author" content="Vyspro-India" />

        <meta property="og:title" content=""/>
        <meta property="og:image" content=""/>
        <meta property="og:url" content=""/>
        <meta property="og:site_name" content=""/>
        <meta property="og:description" content=""/>
        <meta name="twitter:title" content="" />
        <meta name="twitter:image" content="" />
        <meta name="twitter:url" content="" />
        <meta name="twitter:card" content="" />

        <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Roboto+Slab:300,400" rel="stylesheet">

        <link rel="stylesheet" href="/css/animate.css">

        <link rel="stylesheet" href="/css/icomoon.css">

        <link  rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

        <link rel="stylesheet" href="/css/magnific-popup.css">

        <link rel="stylesheet" href="/css/owl.carousel.min.css">
        <link rel="stylesheet" href="/css/owl.theme.default.min.css">

        <link rel="stylesheet" href="/css/flexslider.css">

        <link rel="stylesheet" href="/css/pricing.css">

        <link rel="stylesheet" href="/css/style.css">

        <?PHP
        if (isset($customCSS)) {
            echo $customCSS;
        }
        ?>

                                <?PHP
                                if (isset($showVIFLogo) && $showVIFLogo == 1) {
                                    ?>

                                    <?PHP
                                }
                                ?>

                                    +91 868 882 8969
vysproindia@gmail.com

                <?PHP
                if (isset($_SESSION['eventsDisplay']) && is_array($_SESSION['eventsDisplay'])) {
                    ?>

                                <?PHP
//                                echo "
";
//                                print_r($_SESSION);
//                                echo "
";
                                foreach ($_SESSION['eventsDisplay'] as $hearderevents) {
                                    ?>

<?PHP echo date('d-M-Y', strtotime($hearderevents['event_starttime'])) . " - " . $hearderevents['event_name']; ?>

                                    <?PHP
                                }
                                ?>

                    <?PHP
                }
                ?>

                                        Vyspro-India

Home

                                        About us

Spirit of VysPro-India

About Vyspro

Committee Members

President Message

Past Presidents

Office Bearers

Members

Advisors

                                        VIF

About VIF

Founder Trustees

Life Trustees

Vyspro in News

Events

Knowledge Corner

Testimonials

Contact

Become a Member


text:
package com.netflix.discovery.shared.dns;

import javax.annotation.Nullable;
import java.util.List;

import com.netflix.discovery.endpoint.DnsResolver;

/**
 * @author Tomasz Bak
 */
public class DnsServiceImpl implements DnsService {
    @Override
    public String resolveIp(String hostName) {
        return DnsResolver.resolve(hostName);
    }

    @Nullable
    @Override
    public List<String> resolveARecord(String rootDomainName) {
        return DnsResolver.resolveARecord(rootDomainName);
    }
}


text:
package net.devh.boot.grpc.examples.security.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * An example server application that demonstrates basic auth security.
 *
 * @author Daniel Theuke (daniel.theuke@heuboe.de)
 */
@SpringBootApplication
public class SecurityGrpcServerApplication {

    public static void main(final String[] args) {
        SpringApplication.run(SecurityGrpcServerApplication.class, args);
    }

}


text:
//
//  GTLDriveCommentReplyList.m
//

// ----------------------------------------------------------------------------
// NOTE: This file is generated from Google APIs Discovery Service.
// Service:
//   Drive API (drive/v2)
// Description:
//   The API to interact with Drive.
// Documentation:
//   https://developers.google.com/drive/
// Classes:
//   GTLDriveCommentReplyList (0 custom class methods, 3 custom properties)

#import "GTLDriveCommentReplyList.h"

#import "GTLDriveCommentReply.h"

// ----------------------------------------------------------------------------
//
//   GTLDriveCommentReplyList
//

@implementation GTLDriveCommentReplyList
@dynamic items, kind, nextPageToken;

+ (NSDictionary *)arrayPropertyToClassMap {
  NSDictionary *map =
    [NSDictionary dictionaryWithObject:[GTLDriveCommentReply class]
                                forKey:@"items"];
  return map;
}

+ (void)load {
  [self registerObjectClassForKind:@"drive#commentReplyList"];
}

@end


text:
<?php

namespace conquer\oauth2\console;

use yii\console\Controller;
use conquer\oauth2\models\AuthorizationCode;
use conquer\oauth2\models\RefreshToken;
use conquer\oauth2\models\AccessToken;

/**
 * @author Andrey Borodulin
 */
class Oauth2Controller extends Controller
{
    public function actionIndex()
    {

    }

    public function actionClear()
    {
        AuthorizationCode::deleteAll(['<', 'expires', time()]);
        RefreshToken::deleteAll(['<', 'expires', time()]);
        AccessToken::deleteAll(['<', 'expires', time()]);
    }
}


text:
<?php

class GgMemberCfCalcMapBuilder {

	const CLASS_NAME = 'lib.model.map.GgMemberCfCalcMapBuilder';

	private $dbMap;

	public function isBuilt()
	{
		return ($this->dbMap !== null);
	}

	public function getDatabaseMap()
	{
		return $this->dbMap;
	}

	public function doBuild()
	{
		$this->dbMap = Propel::getDatabaseMap('propel');

		$tMap = $this->dbMap->addTable('gg_member_cf_calc');
		$tMap->setPhpName('GgMemberCfCalc');

		$tMap->setUseIdGenerator(true);

		$tMap->addPrimaryKey('ID', 'Id', 'string', CreoleTypes::BIGINT, true, null);

		$tMap->addColumn('UID', 'Uid', 'string', CreoleTypes::BIGINT, true, null);

		$tMap->addColumn('AMOUNT', 'Amount', 'double', CreoleTypes::DECIMAL, true, 15);

	}
}


text:
#import "UIView.h"

@class NSAttributedString, NSError, NSString, UIButton, UIImageView, UILabel;

@interface QLGenericView : UIView
{
    UIView *_containerView;
    UIImageView *_iconView;
    UILabel *_titleLabel;
    UILabel *_subtitleLabel;
    UIButton *_showArchiveContentButton;
    NSError *_error;
    id <QLGenericViewDelegate> delegate;
}

@property id <QLGenericViewDelegate> delegate; // @synthesize delegate;
- (void)showArchiveContents:(id)arg1;
@property _Bool showArchiveButton;
@property(copy) NSAttributedString *attributedSubtitle;
@property(copy) NSString *subtitle;
@property(copy) NSString *title;
- (void)layoutSubviews;
- (void)_updateContainerFrameForOrientation:(long long)arg1;
- (id)initWithFrame:(struct CGRect)arg1;

@end


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
exports.configure = configure;

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

var _utilsTableValidationViewStrategy = require('./utils/table-validation-view-strategy');

Object.defineProperty(exports, 'TableValidationViewStrategy', {
  enumerable: true,
  get: function get() {
    return _utilsTableValidationViewStrategy.TableValidationViewStrategy;
  }
});

var _utilsTimespan = require('./utils/timespan');

Object.defineProperty(exports, 'Timespan', {
  enumerable: true,
  get: function get() {
    return _utilsTimespan.Timespan;
  }
});

var _utilsBaseModel = require('./utils/base-model');

Object.defineProperty(exports, 'BaseModel', {
  enumerable: true,
  get: function get() {
    return _utilsBaseModel.BaseModel;
  }
});

function configure(aurelia, configCallback) {
  var config = new _config.Config();

  aurelia.globalResources('./custom-elements/timepicker/timepicker');
  aurelia.globalResources('./custom-elements/datepicker/datepicker');
  aurelia.globalResources('./custom-elements/datetimepicker/datetimepicker');
  aurelia.globalResources('./custom-attributes/enable');

  aurelia.globalResources('./value-converters/date-format');
  aurelia.globalResources('./value-converters/short-date-format');

  if (configCallback !== undefined && typeof configCallback === 'function') {
    configCallback(config);
  }

  return config.locale();
}


text:
import { Observable } from 'rxjs/Observable';

export class IonKeyboardMock {
    public static instance(): any {
        let instance = jasmine.createSpyObj('Keyboard', [
            'close',
            'didHide',
            'didShow',
            'eventsAvailable',
            'hasFocusedTextInput',
            'isOpen',
            'onClose',
            'willHide',
            'willShow'
        ]);

        instance.isOpen.and.returnValue(false);

        return instance;
    }
}


text:
    <ion-header-bar>

Event

            <button class="button button-clear" ng-click="closeModal()">Close</button>

    </ion-header-bar>
    <ion-content class="has-header">

                Name
                <input type="text" ng-model="event.name">

                Start Date
                <input type="date" ng-model="event.date_start">

                End Date
                <input type="date" ng-model="event.date_end">

                Variation (%)
                <input type="number" ng-model="event.variation">

                Category
                <select ng-model="event.category">
                    <option value="fds">Weekend</option>
                    <option value="occasional_event">Occasional Event</option>
                    <option value="birthday">Birthday</option>
                    <option value="trip">Trip</option>
                    <option value="party">Party</option>
                </select>

        <button class="button button-block button-positive" ng-click="add_event()">
            Done
        </button>
    </ion-content>


text:
using FluentAssertions;
using NUnit.Framework;
using System.Threading.Tasks;

namespace NSpec.Tests.WhenRunningSpecs.BeforeAndAfter
{
    [TestFixture]
    [Category("RunningSpecs")]
    [Category("Async")]
    public class async_middle_abstract : when_running_specs
    {
        class Base : sequence_spec
        {
            async Task before_all()
            {
                await Task.Run(() => sequence += "A");
            }
            async Task after_all()
            {
                await Task.Run(() => sequence += "F");
            }
        }

        abstract class Abstract : Base
        {
            async Task before_all()
            {
                await Task.Run(() => sequence += "B");
            }
            async Task before_each()
            {
                await Task.Run(() => sequence += "C");
            }
            async Task after_each()
            {
                await Task.Run(() => sequence += "D");
            }
            async Task after_all()
            {
                await Task.Run(() => sequence += "E");
            }
        }

        class Concrete : Abstract
        {
            async Task it_one_is_one()
            {
                await Task.Delay(0);

                Assert.That(true, Is.True);
            }
        }

        [SetUp]
        public void setup()
        {
            Concrete.sequence = "";
        }

        [Test]
        public void befores_are_run_from_middle_abstract_classes()
        {
            Run(typeof(Concrete));

            Concrete.sequence.Should().StartWith("ABC");
        }

        [Test]
        public void afters_are_run_from_middle_abstract_classes()
        {
            Run(typeof(Concrete));

            Concrete.sequence.Should().EndWith("DEF");
        }
    }
}


text:
import settings
import controllers
import util

PM_PARSERS = {}

# --------------- STANDARD ECONOMY FUNCTIONS ---------------

def standard_economy_permissions(user):
    return user.name in settings.ALPHATESTERS

def send_by_username(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 3:
        raise ValueError("Invalid number of parameters supplied to SNDU. Help: " + send_by_username.help)

    str_amount = tokens[2]
    amount = util.parse_amount(str_amount)

    username = tokens[1]
    destination_account = controllers.get_account_from_username(session, username)
    source_account = controllers.force_get_account_from_username(session, author.name)

    controllers.transfer_account_money(session, source_account, destination_account, amount)
    tax_paid = controllers.get_transfer_tax_for_amount(amount)

    redditor = reddit.redditor(username)
    if redditor is not None:
        redditor.message("You have received funds!", "You have received Y%.2f from account %08d: %s" % (
            amount, source_account.number,
            source_account.name if source_account.name is not None else source_account.description))

    return "Transaction completed successfully. You transferred Y%.2f and paid Y%.2f in transaction tax. You have Y%.2f remaining in your account." % (
        amount, tax_paid, controllers.get_account_balance(source_account))

send_by_username.help = "Sends money to the account owned by the provided user. Format: SNDU [username] [amount]"
send_by_username.hasPermission = standard_economy_permissions
PM_PARSERS['SNDU'] = send_by_username

def send_by_account_number(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 3:
        raise ValueError("Invalid number of parameters supplied to SNDA. Help: " + send_by_account_number.help)

    str_amount = tokens[2]
    amount = util.parse_amount(str_amount)

    str_account_number = tokens[1]
    try:
        account_number = int(str_account_number)
    except:
        raise ValueError("Invalid account number: account numbers need to be integers.")

    destination_account = controllers.get_account_from_number(session, account_number)
    source_account = controllers.force_get_account_from_username(session, author.name)

    controllers.transfer_account_money(session, source_account, destination_account, amount)
    tax_paid = controllers.get_transfer_tax_for_amount(amount)

    try:
        username = destination_account.name
        if username is not None:
            redditor = reddit.redditor(username)
            if redditor is not None:
                redditor.message("You have received funds!", "You have received Y%.2f from account %08d: %s" % (
                    amount, source_account.number,
                    source_account.name if source_account.name is not None else source_account.description))
    except:
        pass

    return "Transaction completed successfully. You transferred Y%.2f and paid Y%.2f in transaction tax. You have Y%.2f remaining in your account." % (
        amount, tax_paid, controllers.get_account_balance(source_account))

send_by_account_number.help = "Sends money to the account marked with the provided account number. Format: SNDA [account number] [amount]"
send_by_account_number.hasPermission = standard_economy_permissions
PM_PARSERS['SNDA'] = send_by_account_number

def show_balance(reddit, session, author, body):
    account = controllers.force_get_account_from_username(session, author.name)
    return "You have Y%.2f remaining in your account with number %08d." % (
        controllers.get_account_balance(account), account.number)

show_balance.help = "Shows your bank balance and account number. Format: BALN"
show_balance.hasPermission = standard_economy_permissions
PM_PARSERS['BALN'] = show_balance

def show_federal_reserve_balance(reddit, session, author, body):
    return "The Federal Reserve has a balance of Y%.2f." % controllers.get_account_balance(
        controllers.get_treasury_account(session))

show_federal_reserve_balance.help = "Shows the balance of the Federal Reserve. Format: FBAL"
show_federal_reserve_balance.hasPermission = standard_economy_permissions
PM_PARSERS['FBAL'] = show_federal_reserve_balance

def yamecon_help(reddit, session, author, body):
    output = "YamTellerBot Help\n\nTo run any command, send it to u/YamTellerBot in a message. The title does not matter.\n\nHere is a list of commands:\n\n"
    for key, handler in sorted(PM_PARSERS.iteritems()):
        perms = handler.hasPermission
        if perms is None or perms(author):
            output += "* %s %s\n" % (key, handler.help)

    return output

yamecon_help.help = "Shows economy command help. Format: HELP"
yamecon_help.hasPermission = standard_economy_permissions
PM_PARSERS['HELP'] = yamecon_help

# --------------- ADMIN FUNCTIONS ---------------
def has_admin_transfer_perms(user):
    return settings.FEDERAL_RESERVE_TRANSFERS_ENABLED and (user.name in settings.FRTRANSFERPERMS)

def admin_payment_to_user(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 4:
        raise ValueError("Invalid number of parameters supplied to FEDU. Help: " + admin_payment_to_user.help)

    str_amount = tokens[3]
    amount = util.parse_amount(str_amount)

    # From Acct
    str_source_account_number = tokens[1]
    try:
        source_account_number = int(str_source_account_number)
    except:
        raise ValueError("Invalid source account number: account numbers need to be integers.")

    source_account = controllers.get_account_from_number(session, source_account_number)

    if source_account is None:
        raise ValueError("Source account with this number not found.")

    if source_account.name is not None:
        raise ValueError("FEDU can only be used to transfer from non-user accounts.")

    # To Acct
    destination_username = tokens[2]
    destination_account = controllers.get_account_from_username(session, destination_username)

    controllers.transfer_account_money(session, source_account, destination_account, amount)
    tax_paid = controllers.get_transfer_tax_for_amount(amount)

    redditor = reddit.redditor(destination_username)
    if redditor is not None:
        redditor.message("You have received funds!", "You have received Y%.2f from account %08d: %s" % (
            amount, source_account.number,
            source_account.name if source_account.name is not None else source_account.description))

    return "Transaction completed successfully. You transferred Y%.2f and Y%.2f was paid in transaction tax. There is Y%.2f remaining in the source account." % (
        amount, tax_paid, controllers.get_account_balance(source_account))

admin_payment_to_user.help = "Transfers money to a given user's bank account from a provided non-user bank account. Format: FEDU [from account number] [to username] [amount]"
admin_payment_to_user.hasPermission = has_admin_transfer_perms
PM_PARSERS['FEDU'] = admin_payment_to_user

def admin_payment_to_account(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 4:
        raise ValueError("Invalid number of parameters supplied to FEDA. Help: " + admin_payment_to_account.help)

    str_amount = tokens[3]
    amount = util.parse_amount(str_amount)

    # From Acct
    str_source_account_number = tokens[1]
    try:
        source_account_number = int(str_source_account_number)
    except:
        raise ValueError("Invalid source account number: account numbers need to be integers.")

    try:
        source_account = controllers.get_account_from_number(session, source_account_number)
    except:
        raise ValueError("Source account with this number not found.")

    if source_account.name is not None:
        raise ValueError("FEDA can only be used to transfer from non-user accounts.")

    # To Acct
    str_destination_account_number = tokens[2]
    try:
        destination_account_number = int(str_destination_account_number)
    except:
        raise ValueError("Invalid destination account number: account numbers need to be integers.")

    try:
        destination_account = controllers.get_account_from_number(session, destination_account_number)
    except:
        raise ValueError("Destination account with this number not found.")

    controllers.transfer_account_money(session, source_account, destination_account, amount)
    tax_paid = controllers.get_transfer_tax_for_amount(amount)

    username = destination_account.name
    try:
        if username is not None:
            redditor = reddit.redditor(username)
            if redditor is not None:
                redditor.message("You have received funds!", "You have received Y%.2f from account %08d: %s" % (
                    amount, source_account.number,
                    source_account.name if source_account.name is not None else source_account.description))
    except:
        pass

    return "Transaction completed successfully. You transferred Y%.2f and Y%.2f was paid in transaction tax. There is Y%.2f remaining in the source account." % (
        amount, tax_paid, controllers.get_account_balance(source_account))

admin_payment_to_account.help = "Transfers money to a given bank account from a provided non-user bank account. Format: FEDU [from account number] [to account number] [amount]"
admin_payment_to_account.hasPermission = has_admin_transfer_perms
PM_PARSERS['FEDA'] = admin_payment_to_account

def admin_show_account_balance(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to FEDB. Help: " + admin_show_account_balance.help)

    str_account_number = tokens[1]
    try:
        account_number = int(str_account_number)
    except:
        raise ValueError("Invalid source account number: account numbers need to be integers.")

    try:
        account = controllers.get_account_from_number(session, account_number)
    except:
        raise ValueError("Source account with this number not found.")

    if account.name is not None:
        raise ValueError("FEDB can only be used to look up the balance of non-user accounts.")

    balance = controllers.get_account_balance(account)

    return "The balance of account %08d (%s) is Y%.2f." % (account_number, account.description, balance)

admin_show_account_balance.help = "Shows the balance of a non-user bank account. Format: FEDB [account number]"
admin_show_account_balance.hasPermission = has_admin_transfer_perms
PM_PARSERS['FEDB'] = admin_show_account_balance

def admin_create_non_user_account(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to CRTA. Help: " + admin_create_non_user_account.help)

    description = tokens[1]
    account = controllers.create_non_user_account(session, description)

    return "New account created. Account number: %08d, description: %s" % (account.number, account.description)

admin_create_non_user_account.help = "Creates a non-user bank account for use by parties and enterprises. The account description should not contain spaces. Format: CRTA [account description]"
admin_create_non_user_account.hasPermission = has_admin_transfer_perms
PM_PARSERS['CRTA'] = admin_create_non_user_account

def admin_create_user_account(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to CRTU. Help: " + admin_create_user_account.help)

    username = tokens[1]

    try:
        redditor = reddit.redditor(username)
        if redditor is None:
            raise ValueError("No such Redditor found.")
    except:
        raise ValueError("No such Redditor found.")

    try:
        existing_account = controllers.get_account_from_username(session, username)
    except:
        pass
    else:
        raise ValueError("This user already has a bank account. Account number: %08d" % existing_account.number)

    account = controllers.force_get_account_from_username(session, username)

    return "New user account created. Account number: %08d, username: %s" % (account.number, account.name)

admin_create_user_account.help = "Creates an account for a user other than the author of the message. Format: CRTU [Reddit username without u/]"
admin_create_user_account.hasPermission = has_admin_transfer_perms
PM_PARSERS['CRTU'] = admin_create_user_account

def admin_create_government_account(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to CRTG. Help: " + admin_create_government_account.help)

    description = tokens[1]
    account = controllers.create_government_account(session, description)

    return "New government account created. Account number: %08d, description: %s" % (
        account.number, account.description)

admin_create_government_account.help = "Creates a non-user bank account for use by Government Institutions. These accounts have 10000000-level numbers. The account description should not contain spaces. Format: CRTG [account description]"
admin_create_government_account.hasPermission = has_admin_transfer_perms
PM_PARSERS['CRTG'] = admin_create_government_account

# --------------- POST EVALUATION & FLAIR SYSTEM FUNCTIONS ---------------
def has_post_evaluation_permissions(user):
    return settings.POST_EVALUATION_ENABLED

def deposit_post(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to FDPT. Help: " + deposit_post.help)

    url = tokens[1]
    try:
        submission = reddit.submission(url=url)
        if submission is None:
            raise ValueError(
                "No submission found at this URL. If the post is a link post, be sure to post the URL of the Reddit post (get the comments URL) and not the URL of the link.")
    except:
        raise ValueError(
            "No submission found at this URL. If the post is a link post, be sure to post the URL of the Reddit post (get the comments URL) and not the URL of the link.")

    subreddit = submission.subreddit
    if subreddit.display_name.lower() not in settings.SUBREDDITMULTIPLIERS:
        raise ValueError("Submission in subreddit %s are not accepted by the Yam Treasury." % subreddit.display_name)

    if submission.author != author:
        raise ValueError("You can only deposit submissions you submitted.")

    account = controllers.force_get_account_from_username(session, author.name)
    controllers.register_post_to_user(session, account, submission.id)

    score = submission.score
    multiplier = settings.SUBREDDITMULTIPLIERS[subreddit.display_name.lower()]
    amount = score * multiplier

    post_deposit_tax = controllers.get_post_registration_tax_for_amount(amount)
    amount_after_tax = amount - post_deposit_tax

    controllers.transfer_account_money(session, controllers.get_treasury_account(session), account, amount_after_tax)

    return "You have deposited the submission with the ID %s (%s). At Y%.2f per upvote in the subreddit /r/%s, you received Y%.2f for the %d upvotes on your submission after paying Y%.2f in deposit tax." \
           % (submission.id, submission.title, multiplier, subreddit.display_name, amount_after_tax, score, post_deposit_tax)

deposit_post.help = "Deposits a Reddit post's upvote values into the user's bank account. Format: FDPT [post url]"
deposit_post.hasPermission = has_post_evaluation_permissions
PM_PARSERS['FDPT'] = deposit_post

def purchase_flair(reddit, session, author, body):
    tokens = body.split()
    if len(tokens) != 2:
        raise ValueError("Invalid number of parameters supplied to FPRS. Help: " + purchase_flair.help)

    try:
        flair_id = int(tokens[1])
    except:
        raise ValueError("The second parameter needs to be the number representing the flair you want to purchase.")

    if flair_id not in settings.FLAIRS:
        raise ValueError("A flair with this ID does not exist.")

    text, css, price = settings.FLAIRS[flair_id]

    account = controllers.force_get_account_from_username(session, author.name)
    balance = controllers.get_account_balance(account)
    if balance < price:
        raise ValueError("You cannot afford this flair: it costs Y%.2f but you only have Y%.2f" % (price, balance))

    controllers.add_flair(reddit, session, account, text, css)
    controllers.transfer_account_money(session, account, controllers.get_treasury_account(session), price)
    tax_paid = controllers.get_transfer_tax_for_amount(price)

    expiration = account.owner_flair_expiration.strftime("%A, %d %B %Y")
    return "You have purchased the %s flair for Y%.2f and paid Y%.2f in transaction tax. It will expire on %s. You have Y%.2f remaining in your account." % (
        text, price, tax_paid, expiration, controllers.get_account_balance(account))

purchase_flair.help = "Purchases a /r/YamRepublic flair using funds from the user's bank account. Format: FPRS [flair number]"
purchase_flair.hasPermission = has_post_evaluation_permissions
PM_PARSERS['FPRS'] = purchase_flair

def show_current_flair(reddit, session, author, body):
    account = controllers.force_get_account_from_username(session, author.name)
    text = account.owner_flair_text

    if text is None:
        return "You currently do not own a flair."

    expiration = account.owner_flair_expiration.strftime("%A, %d %B %Y")

    return "You currently own the %s flair. It will expire on %s." % (text, expiration)

show_current_flair.help = "Shows information about the user's current flair. Format: FQRY"
show_current_flair.hasPermission = has_post_evaluation_permissions
PM_PARSERS['FQRY'] = show_current_flair

def list_available_flairs(reddit, session, author, body):
    flairs = ["#%d: %s for Y%.2f weekly" % (flair_id, name, price) for flair_id, (name, css, price) in
              settings.FLAIRS.iteritems()]

    return "Here is a list of purchasable flairs: \n" + "\n".join(flairs)

list_available_flairs.help = "Lists purchasable flairs. Format: FLST"
list_available_flairs.hasPermission = has_post_evaluation_permissions
PM_PARSERS['FLST'] = list_available_flairs

def delete_flair(reddit, session, author, body):
    acct = controllers.force_get_account_from_username(session, author.name)
    controllers.remove_flair(reddit, session, acct)

    return "Your current flair has been successfully deleted."

delete_flair.help = "Deletes the user's current flair without a refund so that he can purchase a new one. Format: FDEL"
delete_flair.hasPermission = has_post_evaluation_permissions
PM_PARSERS['FDEL'] = delete_flair

# --------------- AUXILLIARY FUNCTIONS ---------------

def default_pm_parser(_, a, b, c):
    return "This command does not exist. Please send a message starting with the word HELP to see the commands."

default_pm_parser.help = ""
default_pm_parser.hasPermission = lambda x: True

def get_pm_parser(command):
    return PM_PARSERS.get(command.upper(), default_pm_parser)


text:
class ElemSequence implements Iterable<MyElem> {
  private MyElem[] data;

  public Iterator<MyElem> iterator() {
    return new Iterator<MyElem>() {
      private idx = 0;
      public boolean hasNext() {
        return idx < data.length;
      }
      public MyElem next() {
        return data[idx++];
      }
    };
  }
  // ...
}


text:
package true_.oop.web;

import org.javamoney.moneta.FastMoney;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.facets.fork.RqRegex;
import org.takes.rs.RsJson;
import true_.oop.api.Base;
import true_.oop.api.Product;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.IOException;
import java.math.BigDecimal;

/**
 * Update product.
 */
final class TkProductUpdate implements Take {

    private final Base base;

    TkProductUpdate(Base base) {
        this.base = base;
    }

    @Override
    public Response act(Request req) throws IOException {
        try {
            long number = Long.parseLong(((RqRegex) req).matcher().group("number"));
            Product product = base.products().product(number);

            JsonReader reader = Json.createReader(req.body());
            JsonObject json = reader.readObject();
            String name = json.getString("name");
            String desc = json.getString("desc");
            FastMoney price = FastMoney.of(new BigDecimal(json.getString("price")), "CZK");

            Product result = product.update(name, desc, price);
            return new RsJson(result);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}


text:
package resultdb

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"net/http"

	"go.chromium.org/luci/common/errors"
	"go.chromium.org/luci/common/logging"
	"go.chromium.org/luci/common/sync/parallel"
	"go.chromium.org/luci/gae/service/info"
	"go.chromium.org/luci/grpc/prpc"
	rdbPb "go.chromium.org/luci/resultdb/proto/v1"
	"go.chromium.org/luci/server/auth"
	"google.golang.org/grpc"
	"google.golang.org/grpc/metadata"

	"go.chromium.org/luci/buildbucket/appengine/model"
	pb "go.chromium.org/luci/buildbucket/proto"
	"go.chromium.org/luci/buildbucket/protoutil"
)

var mockRecorderClientKey = "used in tests only for setting the mock recorder client"

// SetMockRecorder set the mock resultDB recorder client for testing purpose.
func SetMockRecorder(ctx context.Context, mock rdbPb.RecorderClient) context.Context {
	return context.WithValue(ctx, &mockRecorderClientKey, mock)
}

// CreateInvocations creates resultdb invocations for each build.
// build.Proto.Infra.Resultdb must not be nil.
//
// cfgs is the builder config map with the struct of Bucket ID -> Builder name -> *pb.BuilderConfig.
//
// Note: it will mutate the value of build.Proto.Infra.Resultdb.Invocation and build.ResultDBUpdateToken.
func CreateInvocations(ctx context.Context, builds []*model.Build, cfgs map[string]map[string]*pb.BuilderConfig, host string) errors.MultiError {
	bbHost := info.AppID(ctx) + ".appspot.com"
	merr := make(errors.MultiError, len(builds))

	_ = parallel.WorkPool(64, func(ch chan<- func() error) {
		for i, b := range builds {
			i := i
			b := b
			proj := b.Proto.Builder.Project
			cfg := cfgs[protoutil.FormatBucketID(proj, b.Proto.Builder.Bucket)][b.Proto.Builder.Builder]
			if !cfg.GetResultdb().GetEnable() {
				continue
			}
			realm := b.Realm()
			if realm == "" {
				logging.Warningf(ctx, fmt.Sprintf("the builder %q has resultDB enabled while the build %d doesn't have realm", b.Proto.Builder.Builder, b.Proto.Id))
				continue
			}
			ch <- func() error {
				// TODO(crbug/1042991): After build scheduling flow also dedups number not just the id,
				// we can combine build id invocation and number invocation into a Batch.

				// Use per-project credential to create invocation.
				recorderClient, err := newRecorderClient(ctx, host, proj)
				if err != nil {
					merr[i] = errors.Annotate(err, "failed to create resultDB recorder client for project: %s", proj).Err()
					return nil
				}

				// Make a call to create build id invocation.
				invID := fmt.Sprintf("build-%d", b.Proto.Id)
				reqForBldID := &rdbPb.CreateInvocationRequest{
					InvocationId: invID,
					Invocation: &rdbPb.Invocation{
						BigqueryExports:  cfg.Resultdb.BqExports,
						ProducerResource: fmt.Sprintf("//%s/builds/%d", bbHost, b.Proto.Id),
						Realm:            realm,
						HistoryOptions: &rdbPb.HistoryOptions{
							UseInvocationTimestamp: cfg.Resultdb.HistoryOptions.GetUseInvocationTimestamp(),
						},
					},
					RequestId: invID,
				}
				header := metadata.MD{}
				if _, err = recorderClient.CreateInvocation(ctx, reqForBldID, grpc.Header(&header)); err != nil {
					merr[i] = errors.Annotate(err, "failed to create the invocation for build id: %d", b.Proto.Id).Err()
					return nil
				}
				token, ok := header["update-token"]
				if !ok {
					merr[i] = errors.Reason("CreateInvocation response doesn't have update-token header for build id: %d", b.Proto.Id).Err()
					return nil
				}
				b.ResultDBUpdateToken = token[0]
				b.Proto.Infra.Resultdb.Invocation = fmt.Sprintf("invocations/%s", reqForBldID.InvocationId)

				// Create another invocation for the build number in which it includes the invocation for build id,
				// If the build has the Number field populated.
				if b.Proto.Number > 0 {
					sha256Builder := sha256.Sum256([]byte(protoutil.FormatBuilderID(b.Proto.Builder)))
					_, err = recorderClient.CreateInvocation(ctx, &rdbPb.CreateInvocationRequest{
						InvocationId: fmt.Sprintf("build-%s-%d", hex.EncodeToString(sha256Builder[:]), b.Proto.Number),
						Invocation: &rdbPb.Invocation{
							State:               rdbPb.Invocation_FINALIZING,
							ProducerResource:    reqForBldID.Invocation.ProducerResource,
							Realm:               realm,
							IncludedInvocations: []string{fmt.Sprintf("invocations/%s", reqForBldID.InvocationId)},
						},
						RequestId: fmt.Sprintf("build-%d-%d", b.Proto.Id, b.Proto.Number),
					})
					if err != nil {
						merr[i] = errors.Annotate(err, "failed to create the invocation for build number: %d (build id: %d)", b.Proto.Number, b.Proto.Id).Err()
						return nil
					}
				}
				return nil
			}
		}
	})

	if merr.First() != nil {
		return merr
	}
	return nil
}

func newRecorderClient(ctx context.Context, host string, project string) (rdbPb.RecorderClient, error) {
	if mockClient, ok := ctx.Value(&mockRecorderClientKey).(*rdbPb.MockRecorderClient); ok {
		return mockClient, nil
	}

	t, err := auth.GetRPCTransport(ctx, auth.AsProject, auth.WithProject(project))
	if err != nil {
		return nil, err
	}
	return rdbPb.NewRecorderPRPCClient(
		&prpc.Client{
			C:    &http.Client{Transport: t},
			Host: host,
		}), nil
}


text:
package csum.confluence.permissionmgmt;

import bucket.core.actions.PagerPaginationSupport;
import com.atlassian.confluence.spaces.actions.AbstractSpaceAction;
import com.atlassian.confluence.spaces.actions.SpaceAdministrative;
import com.opensymphony.xwork.ActionContext;
import csum.confluence.permissionmgmt.service.vo.AdvancedUserQuery;
import csum.confluence.permissionmgmt.util.SessionUtil;
import csum.confluence.permissionmgmt.util.logging.LogUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Gary S. Weaver
 */
public abstract class AbstractPagerPaginationSupportCachingSpaceAction extends AbstractSpaceAction implements SpaceAdministrative, CacheConstants {

    private Log log = LogFactory.getLog(this.getClass());
    private static final Log staticlog = LogFactory.getLog(AbstractPagerPaginationSupportCachingSpaceAction.class);

    private String id(Object o) {
        if (o != null) {
            return "" + o.hashCode();
        }

        return "null";
    }

    // GROUP LIST AND GROUP LIST INDEX CACHING

    public PagerPaginationSupport getGroupsPps(String spaceKey) {
        PagerPaginationSupport result = null;
        try {
            result = (PagerPaginationSupport) SessionUtil.getSessionProperty(getGroupsPpsKey(spaceKey));
            log.debug("Got groups instance " + id(result) + " for spaceKey '" + spaceKey + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setGroupsPps(String spaceKey, PagerPaginationSupport groupsPps) {
        SessionUtil.setSessionProperty(getGroupsPpsKey(spaceKey), groupsPps);
        log.debug("Set groups instance " + id(groupsPps) + " for spaceKey '" + spaceKey + "'");
    }

    private String getGroupsPpsKey(String spaceKey) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + GROUPS_SESSION_KEY_SUFFIX;
    }

    public Integer getGroupsIndex(String spaceKey) {
        Integer result = null;
        try {
            result = (Integer) SessionUtil.getSessionProperty(getGroupsIndexKey(spaceKey));
            log.debug("Got groups index instance " + id(result) + " for spaceKey '" + spaceKey + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setGroupsIndex(String spaceKey, Integer index) {
        SessionUtil.setSessionProperty(getGroupsIndexKey(spaceKey), index);
        log.debug("Set groups index instance " + id(index) + " for spaceKey '" + spaceKey + "'");
    }

    private String getGroupsIndexKey(String spaceKey) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + GROUPS_INDEX_SESSION_KEY_SUFFIX;
    }

    // USERS LIST AND GROUP LIST INDEX CACHING

    public PagerPaginationSupport getUsersPps(String spaceKey, String groupName) {
        PagerPaginationSupport result = null;
        try {
            result = (PagerPaginationSupport) SessionUtil.getSessionProperty(getUsersPpsKey(spaceKey, groupName));
            log.debug("Got users instance " + id(result) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setUsersPps(String spaceKey, String groupName, PagerPaginationSupport usersPps) {
        SessionUtil.setSessionProperty(getUsersPpsKey(spaceKey, groupName), usersPps);
        log.debug("Set users instance " + id(usersPps) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
    }

    private String getUsersPpsKey(String spaceKey, String groupName) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + groupName + DELIMITER + USERS_SESSION_KEY_SUFFIX;
    }

    public Integer getUsersIndex(String spaceKey, String groupName) {
        Integer result = null;
        try {
            result = (Integer) SessionUtil.getSessionProperty(getUsersIndexKey(spaceKey, groupName));
            log.debug("Got users index instance " + id(result) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setUsersIndex(String spaceKey, String groupName, Integer index) {
        SessionUtil.setSessionProperty(getUsersIndexKey(spaceKey, groupName), index);
        log.debug("Set users index instance " + id(index) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
    }

    private String getUsersIndexKey(String spaceKey, String groupName) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + groupName + DELIMITER + USERS_INDEX_SESSION_KEY_SUFFIX;
    }

    // USER SEARCH-RELATED CACHING

    public PagerPaginationSupport getSearchResultUsersPps(String spaceKey, String groupName) {
        PagerPaginationSupport result = null;
        try {
            result = (PagerPaginationSupport) SessionUtil.getSessionProperty(getSearchResultUsersPpsKey(spaceKey, groupName));
            log.debug("Got search result users instance " + id(result) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setSearchResultUsersPps(String spaceKey, String groupName, PagerPaginationSupport searchResultUsersPps) {
        SessionUtil.setSessionProperty(getSearchResultUsersPpsKey(spaceKey, groupName), searchResultUsersPps);
        log.debug("Set search result users instance " + id(searchResultUsersPps) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
    }

    private String getSearchResultUsersPpsKey(String spaceKey, String groupName) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + groupName + DELIMITER + SEARCH_RESULT_USERS_SESSION_KEY_SUFFIX;
    }

    public Integer getSearchResultUsersIndex(String spaceKey, String groupName) {
        Integer result = null;
        try {
            result = (Integer) SessionUtil.getSessionProperty(getSearchResultUsersIndexKey(spaceKey, groupName));
            log.debug("Got search result users index instance " + id(result) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setSearchResultUsersIndex(String spaceKey, String groupName, Integer index) {
        SessionUtil.setSessionProperty(getSearchResultUsersIndexKey(spaceKey, groupName), index);
        log.debug("Set search result users index instance " + id(index) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
    }

    private String getSearchResultUsersIndexKey(String spaceKey, String groupName) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + groupName + DELIMITER + SEARCH_RESULT_USERS_INDEX_SESSION_KEY_SUFFIX;
    }

    public AdvancedUserQuery getAdvancedUserQuery(String spaceKey, String groupName) {
        AdvancedUserQuery result = null;
        try {
            result = (AdvancedUserQuery) SessionUtil.getSessionProperty(getAdvancedUserQueryKey(spaceKey, groupName));
            log.debug("Got advanced user query instance " + id(result) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
        }
        catch (java.lang.ClassCastException e) {
            LogUtil.errorWithRemoteUserInfo(log, "Invalid type stored in cache. Returning null", e);
        }
        return result;
    }

    public void setAdvancedUserQuery(String spaceKey, String groupName, AdvancedUserQuery advancedUserQuery) {
        SessionUtil.setSessionProperty(getAdvancedUserQueryKey(spaceKey, groupName), advancedUserQuery);
        log.debug("Set advanced user query instance " + id(advancedUserQuery) + " for spaceKey '" + spaceKey + "' and groupName '" + groupName + "'");
    }

    private String getAdvancedUserQueryKey(String spaceKey, String groupName) {
        return PLUGIN_SESSION_KEY_PREFIX + DELIMITER + spaceKey + DELIMITER + groupName + DELIMITER + ADVANCED_USER_QUERY_SESSION_KEY_SUFFIX;
    }

    // MISCELLANEOUS

    public void storeInPluginCache(String key, Object o) {
        SessionUtil.setSessionProperty(PLUGIN_SESSION_KEY_PREFIX + DELIMITER + key, o);
    }

    public Object getFromPluginCache(String key) {
        Map session = (Map) ActionContext.getContext().get("session");
        return session.get(PLUGIN_SESSION_KEY_PREFIX + DELIMITER + key);
    }

    public void removeFromPluginCache(String key) {
        Map session = (Map) ActionContext.getContext().get("session");
        session.remove(PLUGIN_SESSION_KEY_PREFIX + DELIMITER + key);
    }

    // CACHE-CLEARING METHODS

    // Note: this is a little dangerous as it makes an assumption that we want to cache every index for every pps

    private void cachePpsIndexIfSupported(String key) {
        Object o = SessionUtil.getSessionProperty(key);
        if (o instanceof PagerPaginationSupport) {
            PagerPaginationSupport pps = (PagerPaginationSupport) o;
            SessionUtil.setSessionProperty(key + INDEX_SUFFIX, new Integer(pps.getStartIndex()));
        }
    }

    // called by config
    public static void clearCacheIncludingIndexes() {
        staticlog.debug("Clearing all cache (removing all session data with keys that start with '" + PLUGIN_SESSION_KEY_PREFIX + DELIMITER + "')");
        Map session = (Map) ActionContext.getContext().get("session");
        Iterator iter = session.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            // intentionally not removing index here
            if (key.startsWith(PLUGIN_SESSION_KEY_PREFIX + DELIMITER)) {
                session.remove(key);
            }
        }
    }

    // Note: intentionally not clearing index cache. That is used to find out where you were in result set.
    public void clearCache() {
        log.debug("Clearing all cache (removing all session data with keys that start with '" + PLUGIN_SESSION_KEY_PREFIX + "' and not ending with '" + INDEX_SUFFIX + "')");
        Map session = (Map) ActionContext.getContext().get("session");
        Iterator iter = session.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            // intentionally not removing index here
            if (key.startsWith(PLUGIN_SESSION_KEY_PREFIX + DELIMITER) && !key.endsWith(INDEX_SUFFIX)) {
                cachePpsIndexIfSupported(key);
                session.remove(key);
            }
        }
    }

    // Note: intentionally not clearing index cache. That is used to find out where you were in result set.
    public void clearGroupCache(String spaceKey) {
        String sessionKey = getGroupsPpsKey(spaceKey);
        log.debug("Clearing all groups cache for spacekey '" + spaceKey + "' (removing session data for '" + sessionKey + ")");
        cachePpsIndexIfSupported(sessionKey);
        SessionUtil.removeSessionProperty(sessionKey);
    }

    // Note: intentionally not clearing index cache. That is used to find out where you were in result set.
    public void clearUserCache(String spaceKey, List groupNames) {
        Map session = SessionUtil.getSession();
        for (int i = 0; i < groupNames.size(); i++) {
            String groupName = (String) groupNames.get(i);
            String sessionKey = getUsersPpsKey(spaceKey, groupName);
            log.debug("Clearing all users cache for spacekey '" + spaceKey + "' and groupName '" + groupName + "' (removing all session data for key '" + sessionKey + "')");
            cachePpsIndexIfSupported(sessionKey);
            session.remove(sessionKey);
        }
    }

    // Note: intentionally not clearing index cache. That is used to find out where you were in result set.
    public void clearSearchResultUserCache(String spaceKey, List groupNames) {
        Map session = SessionUtil.getSession();
        for (int i = 0; i < groupNames.size(); i++) {
            String groupName = (String) groupNames.get(i);
            String sessionKey = getSearchResultUsersPpsKey(spaceKey, groupName);
            log.debug("Clearing all search result users cache for spacekey '" + spaceKey + "' and groupName '" + groupName + "' (removing all session data for key '" + sessionKey + "')");
            cachePpsIndexIfSupported(sessionKey);
            session.remove(sessionKey);
        }
    }

    public String getCacheAsHtml() {
        StringBuffer sb = new StringBuffer();
        sb.append("

Key	Data
");
        try {
            TreeMap session = new TreeMap(SessionUtil.getSession());
            Iterator iter = session.keySet().iterator();
            boolean flag = false;
            while (iter.hasNext()) {

                String key = (String) iter.next();

                // intentionally not removing index here
                if (key.startsWith(PLUGIN_SESSION_KEY_PREFIX + DELIMITER)) {
                    if (flag) {
                        sb.append("
");
                    } else {
                        sb.append("
");
                    }
                    sb.append("" + key + "	");
                    Object val = session.get(key);
                    if (val instanceof PagerPaginationSupport) {
                        sb.append("total size: " + ((PagerPaginationSupport) val).getTotal() + "	");
                    } else if (val instanceof Integer) {
                        sb.append("" + ((Integer) val).intValue() + "	");
                    } else {
                        sb.append("" + val + "	");
                    }
                    sb.append("
");

                    flag = !flag;
                }

            }
        }
        catch (Throwable t) {
            LogUtil.errorWithRemoteUserInfo(log, "Problem debugging action", t);
        }
        sb.append("

");
        return sb.toString();
    }
}


text:
#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include "stats.h"

#include <ucs/debug/log.h>
#include <ucs/time/time.h>
#include <ucs/config/global_opts.h>
#include <ucs/config/parser.h>
#include <ucs/type/status.h>

#include <sys/ioctl.h>
#include <linux/futex.h>

#if ENABLE_STATS

enum {
    UCS_STATS_FLAG_ON_EXIT        = UCS_BIT(0),
    UCS_STATS_FLAG_ON_TIMER       = UCS_BIT(1),
    UCS_STATS_FLAG_ON_SIGNAL      = UCS_BIT(2),

    UCS_STATS_FLAG_SOCKET         = UCS_BIT(8),
    UCS_STATS_FLAG_STREAM         = UCS_BIT(9),
    UCS_STATS_FLAG_STREAM_CLOSE   = UCS_BIT(10),
    UCS_STATS_FLAG_STREAM_BINARY  = UCS_BIT(11),
};

enum {
    UCS_ROOT_STATS_RUNTIME,
    UCS_ROOT_STATS_LAST
};

typedef struct {
    volatile unsigned    flags;

    ucs_time_t           start_time;
    ucs_stats_node_t     root_node;
    ucs_stats_counter_t  root_counters[UCS_ROOT_STATS_LAST];

    union {
        FILE             *stream;         /* Output stream */
        ucs_stats_client_h client;       /* UDP client */
    };

    union {
        int              signo;
        double           interval;
    };

    pthread_mutex_t      lock;
    pthread_t            thread;
} ucs_stats_context_t;

static ucs_stats_context_t ucs_stats_context = {
    .flags            = 0,
    .root_node        = {},
    .lock             = PTHREAD_MUTEX_INITIALIZER,
    .thread           = 0xfffffffful
};

static ucs_stats_class_t ucs_stats_root_node_class = {
    .name          = "",
    .num_counters  = UCS_ROOT_STATS_LAST,
    .counter_names = {
        [UCS_ROOT_STATS_RUNTIME] = "runtime"
    }
};

static inline int
ucs_sys_futex(volatile void *addr1, int op, int val1, struct timespec *timeout,
              void *uaddr2, int val3)
{
    return syscall(SYS_futex, addr1, op, val1, timeout, uaddr2, val3);
}

static void ucs_stats_node_add(ucs_stats_node_t *node, ucs_stats_node_t *parent)
{
    ucs_assert(node != &ucs_stats_context.root_node);

    /* Append node to existing tree */
    pthread_mutex_lock(&ucs_stats_context.lock);
    if (parent == NULL) {
        parent = &ucs_stats_context.root_node;
    }
    ucs_list_add_tail(&parent->children[UCS_STATS_ACTIVE_CHILDREN], &node->list);
    node->parent = parent;

    pthread_mutex_unlock(&ucs_stats_context.lock);
}

static void ucs_stats_node_remove(ucs_stats_node_t *node, int make_inactive)
{
    ucs_assert(node != &ucs_stats_context.root_node);

    if (!ucs_list_is_empty(&node->children[UCS_STATS_ACTIVE_CHILDREN])) {
        ucs_warn("stats node "UCS_STATS_NODE_FMT" still has active children",
                 UCS_STATS_NODE_ARG(node));
    }

    pthread_mutex_lock(&ucs_stats_context.lock);
    ucs_list_del(&node->list);
    if (make_inactive) {
        ucs_list_add_tail(&node->parent->children[UCS_STATS_INACTIVE_CHILDREN], &node->list);
    }
    pthread_mutex_unlock(&ucs_stats_context.lock);
}

static void ucs_stats_node_init_root(const char *name, ...)
{
    ucs_status_t status;
    va_list ap;

    if (!ucs_stats_is_active()) {
        return;
    }

    va_start(ap, name);
    status = ucs_stats_node_initv(&ucs_stats_context.root_node,
                                 &ucs_stats_root_node_class, name, ap);
    ucs_assert_always(status == UCS_OK);
    va_end(ap);

    ucs_stats_context.root_node.parent = NULL;
}

static ucs_status_t ucs_stats_node_new(ucs_stats_class_t *cls, ucs_stats_node_t **p_node)
{
    ucs_stats_node_t *node;

    node = ucs_malloc(sizeof(ucs_stats_node_t) +
                      sizeof(ucs_stats_counter_t) * cls->num_counters,
                      "stats node");
    if (node == NULL) {
        ucs_error("Failed to allocate stats node for %s", cls->name);
        return UCS_ERR_NO_MEMORY;
    }

    *p_node = node;
    return UCS_OK;
}

ucs_status_t ucs_stats_node_alloc(ucs_stats_node_t** p_node, ucs_stats_class_t *cls,
                                 ucs_stats_node_t *parent, const char *name, ...)
{
    ucs_stats_node_t *node;
    ucs_status_t status;
    va_list ap;

    if (!ucs_stats_is_active()) {
        *p_node = NULL;
        return UCS_OK;
    }

    status = ucs_stats_node_new(cls, &node);
    if (status != UCS_OK) {
        return status;
    }

    va_start(ap, name);
    status = ucs_stats_node_initv(node, cls, name, ap);
    va_end(ap);

    if (status != UCS_OK) {
        ucs_free(node);
        return status;
    }

    ucs_trace("allocated stats node '"UCS_STATS_NODE_FMT"'", UCS_STATS_NODE_ARG(node));

    ucs_stats_node_add(node, parent);
    *p_node = node;
    return UCS_OK;
}

void ucs_stats_node_free(ucs_stats_node_t *node)
{
    if (node == NULL) {
        return;
    }

    ucs_trace("releasing stats node '"UCS_STATS_NODE_FMT"'", UCS_STATS_NODE_ARG(node));

    /* If we would dump stats in exit, keep this data instead of releasing it */
    if (ucs_stats_context.flags & UCS_STATS_FLAG_ON_EXIT) {
        ucs_stats_node_remove(node, 1);
    } else {
        ucs_stats_node_remove(node, 0);
        ucs_free(node);
    }
}

static void __ucs_stats_dump(int inactive)
{
    ucs_status_t status = UCS_OK;
    int options;

    /* Assume locked */

    UCS_STATS_SET_TIME(&ucs_stats_context.root_node, UCS_ROOT_STATS_RUNTIME,
                       ucs_stats_context.start_time);

    if (ucs_stats_context.flags & UCS_STATS_FLAG_SOCKET) {
        status = ucs_stats_client_send(ucs_stats_context.client,
                                      &ucs_stats_context.root_node,
                                      ucs_get_time());
    }

    if (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM) {
        options = 0;
        if (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM_BINARY) {
            options |= UCS_STATS_SERIALIZE_BINARY;
        }
        if (inactive) {
            options |= UCS_STATS_SERIALIZE_INACTVIVE;
        }

        status = ucs_stats_serialize(ucs_stats_context.stream,
                                    &ucs_stats_context.root_node, options);
        fflush(ucs_stats_context.stream);
    }

    if (status != UCS_OK) {
        ucs_warn("Failed to dump statistics: %s", ucs_status_string(status));
    }
}

static void* ucs_stats_thread_func(void *arg)
{
    struct timespec timeout, *ptime;
    unsigned flags;
    long nsec;

    if (ucs_stats_context.interval > 0) {
        nsec = (long)(ucs_stats_context.interval * UCS_NSEC_PER_SEC + 0.5);
        timeout.tv_sec  = nsec / UCS_NSEC_PER_SEC;
        timeout.tv_nsec = nsec % UCS_NSEC_PER_SEC;
        ptime = &timeout;
    }
    else {
        ptime = NULL;
    }

    flags = ucs_stats_context.flags;
    while (flags & UCS_STATS_FLAG_ON_TIMER) {
        /* Wait for timeout/wakeup */
        ucs_sys_futex(&ucs_stats_context.flags, FUTEX_WAIT, flags, ptime, NULL, 0);
        ucs_stats_dump();
        flags = ucs_stats_context.flags;
    }

    return NULL;
}

static void ucs_stats_open_dest()
{
    ucs_status_t status;
    char *copy_str, *saveptr;
    const char *hostname, *port_str;
    const char *next_token;
    int need_close;

    if (!strncmp(ucs_global_opts.stats_dest, "udp:", 4)) {

        copy_str = strdupa(&ucs_global_opts.stats_dest[4]);
        saveptr  = NULL;
        hostname = strtok_r(copy_str, ":", &saveptr);
        port_str = strtok_r(NULL,     ":", &saveptr);

        if (hostname == NULL) {
           ucs_error("Invalid statistics destination format (%s)", ucs_global_opts.stats_dest);
           return;
        }

        status = ucs_stats_client_init(hostname,
                                      port_str ? atoi(port_str) : UCS_STATS_DEFAULT_UDP_PORT,
                                      &ucs_stats_context.client);
        if (status != UCS_OK) {
            return;
        }

        ucs_stats_context.flags |= UCS_STATS_FLAG_SOCKET;
    } else if (strcmp(ucs_global_opts.stats_dest, "") != 0) {
        status = ucs_open_output_stream(ucs_global_opts.stats_dest,
                                       &ucs_stats_context.stream,
                                       &need_close, &next_token);
        if (status != UCS_OK) {
            return;
        }

        /* File flags */
        ucs_stats_context.flags |= UCS_STATS_FLAG_STREAM;
        if (need_close) {
            ucs_stats_context.flags |= UCS_STATS_FLAG_STREAM_CLOSE;
        }

        /* Optional: Binary mode */
        if (!strcmp(next_token, ":bin")) {
            ucs_stats_context.flags |= UCS_STATS_FLAG_STREAM_BINARY;
        }
    }
}

static void ucs_stats_close_dest()
{
    if (ucs_stats_context.flags & UCS_STATS_FLAG_SOCKET) {
        ucs_stats_context.flags &= ~UCS_STATS_FLAG_SOCKET;
        ucs_stats_client_cleanup(ucs_stats_context.client);
    }
    if (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM) {
        fflush(ucs_stats_context.stream);
        if (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM_CLOSE) {
            fclose(ucs_stats_context.stream);
        }
        ucs_stats_context.flags &= ~(UCS_STATS_FLAG_STREAM|
                                     UCS_STATS_FLAG_STREAM_BINARY|
                                     UCS_STATS_FLAG_STREAM_CLOSE);
    }
}

static void ucs_stats_dump_sighandler(int signo)
{
    ucs_stats_dump();
}

static void ucs_stats_set_trigger()
{
    char *p;

    if (!strcmp(ucs_global_opts.stats_trigger, "exit")) {
        ucs_stats_context.flags |= UCS_STATS_FLAG_ON_EXIT;
    } else if (!strncmp(ucs_global_opts.stats_trigger, "timer:", 6)) {
        p = ucs_global_opts.stats_trigger + 6;
        if (!ucs_config_sscanf_time(p, &ucs_stats_context.interval, NULL)) {
            ucs_error("Invalid statistics interval time format: %s", p);
            return;
        }

        ucs_stats_context.flags |= UCS_STATS_FLAG_ON_TIMER;
        pthread_create(&ucs_stats_context.thread, NULL, ucs_stats_thread_func, NULL);
   } else if (!strncmp(ucs_global_opts.stats_trigger, "signal:", 7)) {
        p = ucs_global_opts.stats_trigger + 7;
        if (!ucs_config_sscanf_signo(p, &ucs_stats_context.signo, NULL)) {
            ucs_error("Invalid statistics signal specification: %s", p);
            return;
        }

        signal(ucs_stats_context.signo, ucs_stats_dump_sighandler);
        ucs_stats_context.flags |= UCS_STATS_FLAG_ON_SIGNAL;
    } else if (!strcmp(ucs_global_opts.stats_trigger, "")) {
        /* No external trigger */
    } else {
        ucs_error("Invalid statistics trigger: %s", ucs_global_opts.stats_trigger);
    }
}

static void ucs_stats_unset_trigger()
{
    void *result;

    if (ucs_stats_context.flags & UCS_STATS_FLAG_ON_TIMER) {
        ucs_stats_context.flags &= ~UCS_STATS_FLAG_ON_TIMER;
        ucs_sys_futex(&ucs_stats_context.flags, FUTEX_WAKE, 1, NULL, NULL, 0);
        pthread_join(ucs_stats_context.thread, &result);
    }

    if (ucs_stats_context.flags & UCS_STATS_FLAG_ON_EXIT) {
        ucs_debug("dumping stats");
        __ucs_stats_dump(1);
        ucs_stats_context.flags &= ~UCS_STATS_FLAG_ON_EXIT;
    }

    if (ucs_stats_context.flags & UCS_STATS_FLAG_ON_SIGNAL) {
        ucs_stats_context.flags &= ~UCS_STATS_FLAG_ON_SIGNAL;
        signal(ucs_stats_context.signo, SIG_DFL);
    }
}

static void ucs_stats_clean_node_recurs(ucs_stats_node_t *node)
{
    ucs_stats_node_t *child, *tmp;

    if (!ucs_list_is_empty(&node->children[UCS_STATS_ACTIVE_CHILDREN])) {
        ucs_warn("stats node "UCS_STATS_NODE_FMT" still has active children",
                 UCS_STATS_NODE_ARG(node));
    }

    ucs_list_for_each_safe(child, tmp, &node->children[UCS_STATS_INACTIVE_CHILDREN], list) {
        ucs_stats_clean_node_recurs(child);
        ucs_stats_node_remove(child, 0);
        ucs_free(child);
    }
}

void ucs_stats_init()
{
    ucs_assert(ucs_stats_context.flags == 0);
    ucs_stats_open_dest();

    if (!ucs_stats_is_active()) {
        ucs_trace("statistics disabled");
        return;
    }

    UCS_STATS_START_TIME(ucs_stats_context.start_time);
    ucs_stats_node_init_root("%s:%d", ucs_get_host_name(), getpid());
    ucs_stats_set_trigger();

    ucs_debug("statistics enabled, flags: %c%c%c%c%c%c%c",
              (ucs_stats_context.flags & UCS_STATS_FLAG_ON_TIMER)      ? 't' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_ON_EXIT)       ? 'e' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_ON_SIGNAL)     ? 's' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_SOCKET)        ? 'u' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM)        ? 'f' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM_BINARY) ? 'b' : '-',
              (ucs_stats_context.flags & UCS_STATS_FLAG_STREAM_CLOSE)  ? 'c' : '-');
}

void ucs_stats_cleanup()
{
    if (!ucs_stats_is_active()) {
        return;
    }

    ucs_stats_unset_trigger();
    ucs_stats_clean_node_recurs(&ucs_stats_context.root_node);
    ucs_stats_close_dest();
    ucs_assert(ucs_stats_context.flags == 0);
}

void ucs_stats_dump()
{
    pthread_mutex_lock(&ucs_stats_context.lock);
    __ucs_stats_dump(0);
    pthread_mutex_unlock(&ucs_stats_context.lock);
}

int ucs_stats_is_active()
{
    return ucs_stats_context.flags & (UCS_STATS_FLAG_SOCKET|UCS_STATS_FLAG_STREAM);
}

#else

void ucs_stats_init()
{
}

void ucs_stats_cleanup()
{
}

void ucs_stats_dump()
{
}

int ucs_stats_is_active()
{
    return 0;
}

#endif


text:
<?php
namespace UNL\UCBCN\Calendar;

use UNL\UCBCN\ActiveRecord\Record;
use UNL\UCBCN\Calendar;
use UNL\UCBCN\Calendars;
use UNL\UCBCN\Events;
use UNL\UCBCN\Manager\Controller as ManagerController;
use UNL\UCBCN\Manager\Auth;

/**
 * ORM for a record within the database.
 *
 * @category  Events
 * @package   UNL_UCBCN
 * @author    Brett Bieber <brett.bieber@gmail.com>
 * @copyright 2009 Regents of the University of Nebraska
 * @license   http://www1.unl.edu/wdn/wiki/Software_License BSD License
 * @link      http://code.google.com/p/unl-event-publisher/
 */
class Subscription extends Record
{

    public $id;                              // int(10)  not_null primary_key unsigned auto_increment
    public $calendar_id;                     // int(10)  not_null multiple_key unsigned
    public $name;                            // string(100)
    public $automaticapproval;               // int(1)  not_null
    public $timeperiod;                      // date(10)  binary
    public $expirationdate;                  // date(10)  binary
    public $datecreated;                     // datetime(19)  binary
    public $uidcreated;                      // string(100)
    public $datelastupdated;                 // datetime(19)  binary
    public $uidlastupdated;                  // string(100)

    public static function getTable()
    {
        return 'subscription';
    }

    function keys()
    {
        return array(
            'id',
        );
    }

    public function getNewURL($calendar) {
        return ManagerController::$url . $calendar->shortname . '/subscriptions/new/';
    }

    public function getEditURL() {
        $calendar = $this->getCalendar();
        return ManagerController::$url . $calendar->shortname . '/subscriptions/' . $this->id . '/edit/';
    }

    public function getDeleteURL() {
        $calendar = $this->getCalendar();
        return ManagerController::$url . $calendar->shortname . '/subscriptions/' . $this->id . '/delete/';
    }

    public function getCalendar() {
        return Calendar::getByID($this->calendar_id);
    }

    public function getSubscribedCalendars()
    {
        $options = array(
            'subscription_id' => $this->id
        );
        return new Calendars($options);
    }

    /**
     * Inserts a record into the subscription table, and processes the subscription
     * for matching events.
     *
     * @return int ID of inserted record on success.
     */
    public function insert()
    {
        $this->datecreated = date('Y-m-d H:i:s');
        $this->uidcreated = Auth::getCurrentUser()->uid;
        $this->datelastupdated = date('Y-m-d H:i:s');
        $this->uidlastupdated = Auth::getCurrentUser()->uid;
        $result = parent::insert();

        return $result;
    }

    /**
     * Performs an update on this subscription. This will re-evaluate all the events
     * to see if they match the subscription and add them in.
     *
     * Calls self::process() if update was successful.
     *
     * @return bool true on success
     */
    public function update()
    {
        $this->datelastupdated = date('Y-m-d H:i:s');
        $this->uidlastupdated = Auth::getCurrentUser()->uid;
        $result = parent::update();

        return $result;
    }

    /**
     * Processes this subscription and adds events not currently
     * added to the calendar this subscription is for.
     *
     * @param int $event_id Optionally only add the event with the mathcing id.
     *
     * @return int number of events added to the calendar
     */
    public function process($event_id = null)
    {
        $status = $this->getApprovalStatus();
        foreach ($this->matchingEvents() as $event) {
            $this->getCalendar()->addEvent($event, $status, Auth::getCurrentUser(), 'subscription');
        }
    }

    /**
     * returns the string equivalent of the automatic approval status, for
     * inserting into the calendar_has_event database.
     * It will return 'posted' if automatic approval is true.
     * 'pending' otherwise.
     *
     * @return string the Status.
     */
    public function getApprovalStatus()
    {
        if ($this->automaticapproval==1) {
            return 'posted';
        }

        return 'pending';
    }

    /**
     * Finds the events matching this subscription.
     */
    public function matchingEvents()
    {
        $calendars = $this->getSubscribedCalendars();
        $calendar_ids = array();
        foreach ($calendars as $calendar) {
            $calendar_ids[] = $calendar->id;
        }

        $options = array(
            'subscription_calendars' => $calendar_ids,
            'subscription_calendar' => $this->calendar_id
        );
        return new Events($options);
    }

}


text: define("dojox/widget/nls/sl/Wizard",{next:"Naprej",previous:"Prej\u0161nji",done:"Opravljeno"});


text:
module Azure::Compute::Mgmt::V2017_12_01
  module Models
    #
    # The instance view of a virtual machine.
    #
    class VirtualMachineInstanceView

      include MsRestAzure

      # @return [Integer] Specifies the update domain of the virtual machine.
      attr_accessor :platform_update_domain

      # @return [Integer] Specifies the fault domain of the virtual machine.
      attr_accessor :platform_fault_domain

      # @return [String] The computer name assigned to the virtual machine.
      attr_accessor :computer_name

      # @return [String] The Operating System running on the virtual machine.
      attr_accessor :os_name

      # @return [String] The version of Operating System running on the virtual
      # machine.
      attr_accessor :os_version

      # @return [String] The Remote desktop certificate thumbprint.
      attr_accessor :rdp_thumb_print

      # @return [VirtualMachineAgentInstanceView] The VM Agent running on the
      # virtual machine.
      attr_accessor :vm_agent

      # @return [MaintenanceRedeployStatus] The Maintenance Operation status on
      # the virtual machine.
      attr_accessor :maintenance_redeploy_status

      # @return [Array<DiskInstanceView>] The virtual machine disk information.
      attr_accessor :disks

      # @return [Array<VirtualMachineExtensionInstanceView>] The extensions
      # information.
      attr_accessor :extensions

      # @return [BootDiagnosticsInstanceView] Boot Diagnostics is a debugging
      # feature which allows you to view Console Output and Screenshot to
      # diagnose VM status.

 You can easily view the output of your
      # console log.

 Azure also enables you to see a screenshot of the
      # VM from the hypervisor.
      attr_accessor :boot_diagnostics

      # @return [Array<InstanceViewStatus>] The resource status information.
      attr_accessor :statuses

      #
      # Mapper for VirtualMachineInstanceView class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'VirtualMachineInstanceView',
          type: {
            name: 'Composite',
            class_name: 'VirtualMachineInstanceView',
            model_properties: {
              platform_update_domain: {
                client_side_validation: true,
                required: false,
                serialized_name: 'platformUpdateDomain',
                type: {
                  name: 'Number'
                }
              },
              platform_fault_domain: {
                client_side_validation: true,
                required: false,
                serialized_name: 'platformFaultDomain',
                type: {
                  name: 'Number'
                }
              },
              computer_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'computerName',
                type: {
                  name: 'String'
                }
              },
              os_name: {
                client_side_validation: true,
                required: false,
                serialized_name: 'osName',
                type: {
                  name: 'String'
                }
              },
              os_version: {
                client_side_validation: true,
                required: false,
                serialized_name: 'osVersion',
                type: {
                  name: 'String'
                }
              },
              rdp_thumb_print: {
                client_side_validation: true,
                required: false,
                serialized_name: 'rdpThumbPrint',
                type: {
                  name: 'String'
                }
              },
              vm_agent: {
                client_side_validation: true,
                required: false,
                serialized_name: 'vmAgent',
                type: {
                  name: 'Composite',
                  class_name: 'VirtualMachineAgentInstanceView'
                }
              },
              maintenance_redeploy_status: {
                client_side_validation: true,
                required: false,
                serialized_name: 'maintenanceRedeployStatus',
                type: {
                  name: 'Composite',
                  class_name: 'MaintenanceRedeployStatus'
                }
              },
              disks: {
                client_side_validation: true,
                required: false,
                serialized_name: 'disks',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'DiskInstanceViewElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'DiskInstanceView'
                      }
                  }
                }
              },
              extensions: {
                client_side_validation: true,
                required: false,
                serialized_name: 'extensions',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'VirtualMachineExtensionInstanceViewElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'VirtualMachineExtensionInstanceView'
                      }
                  }
                }
              },
              boot_diagnostics: {
                client_side_validation: true,
                required: false,
                serialized_name: 'bootDiagnostics',
                type: {
                  name: 'Composite',
                  class_name: 'BootDiagnosticsInstanceView'
                }
              },
              statuses: {
                client_side_validation: true,
                required: false,
                serialized_name: 'statuses',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'InstanceViewStatusElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'InstanceViewStatus'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
layout: default
permalink: docs/error-reporting.html
---

# Error Reporting

 Stylus has fantastic error reporting built-in for syntax, parse, and evaluation errors—complete with stack traces, line numbers, and filenames.

## Parse Error

Parse error example:

     body
       form input
         == padding 5px

Yielding:

      ParseError: test.styl:3:16
        1| body
        2|    form input
        3|      == padding 5px
     ---------------------^
        4|

      illegal unary "==", missing left-hand operand

## Evaluation Error

 This "runtime" or evaluation error is caused by passing a string to `border-radius()`, instead of the expected `Unit` (by using our helper `ensure(n, 'unit')`).

      ensure(val, type)
        unless val is a type
          error('expected a ' + type + ', but got ' + typeof(val))

      border-radius(n)
        ensure(n, 'unit')
        -webkit-border-radius n
        -moz-border-radius n
        border-radius n

      body
        border-radius '5px'

Yielding:

      Error: test.styl:3:62
        1| ensure(val, type)
        2|     unless val is a type
        3|       error('expected a ' + type + ', but got ' + typeof(val))
     -------------------------------------------------------------------^
        4|
        5| border-radius(n)
        6|   ensure(n, 'unit')

      expected a unit, but got string
          at ensure() (test.styl:2:17)
          at border-radius() (test.styl:6:16)
          at "body" (test.styl:10:18)