text:
<bill session="110" type="hr" number="678" updated="2009-01-09T09:16:26-05:00">
	<status><vote date="1190816940" datetime="2007-09-26T11:29:00-04:00" where="h" result="pass" how="by voice vote" roll=""/></status>

	<introduced date="1190692800" datetime="2007-09-25"/>
	<titles>
		<title type="official" as="introduced">Providing for consideration of the bill (H.R. 2693) to direct the Occupational Safety and Health Administration to issue a standard regulating worker exposure to diacetyl.</title>
	</titles>
	<sponsor id="412228"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1190755080" datetime="2007-09-25T18:18:00-04:00"><text>The House Committee on Rules reported an original measure, H. Rept. 110-349, by Ms. Sutton.</text></action>
		<action date="1190755080" datetime="2007-09-25T18:18:00-04:00"><text>Rule provides for consideration of H.R. 2693 with 1 hour of general debate. Previous question shall be considered as ordered without intervening motions except motion to recommit with or without instructions. Measure will be considered read. Specified amendments are in order.</text></action>
		<calendar date="1190755080" datetime="2007-09-25T18:18:00-04:00" ><text>Placed on the House Calendar, Calendar No. 123.</text></calendar>
		<action date="1190813100" datetime="2007-09-26T10:25:00-04:00"><text>Considered as privileged matter.</text><reference label="consideration" ref="CR H10908-10910"/></action>
		<action date="1190813280" datetime="2007-09-26T10:28:00-04:00"><text>DEBATE - The House proceeded with one hour of debate on H. Res. 678.</text></action>
		<action date="1190814600" datetime="2007-09-26T10:50:00-04:00"><text>POSTPONED PROCEEDINGS - At the conclusion of debate on H. Res. 678, Ms. Sutton moved the previous question and by voice vote, the Chair announced that the ayes had prevailed. Mr. Lincoln Diaz-Balart demanded the yeas and nays which were ordered and the Chair postponed further proceedings on the question of ordering the previous question until later in the legislative day.</text></action>
		<action date="1190816580" datetime="2007-09-26T11:23:00-04:00"><text>Considered as unfinished business.</text><reference label="consideration" ref="CR H10912-10913"/></action>
		<action date="1190816940" datetime="2007-09-26T11:29:00-04:00"><text>On ordering the previous question Agreed to by the Yeas and Nays: 221 - 193 (Roll no. 909).</text><reference label="consideration" ref="CR H10910, H10912-10913"/></action>
		<vote date="1190816940" how="by voice vote" datetime="2007-09-26T11:29:00-04:00" where="h" type="vote" result="pass" ><text>On agreeing to the resolution Agreed to by voice vote.</text><reference label="text" ref="CR H10908"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	9/26/2007--Passed House without amendment. Sets forth the rule for consideration of H.R. 2693 (Popcorn Workers Lung Disease Prevention Act).<br/>
	</summary>
</bill>


text:
namespace llvm {
  class LLVMContext;
  class DiagnosticInfo;
  class GlobalValue;
  class Mangler;
  class MemoryBuffer;
  class TargetLibraryInfo;
  class TargetMachine;
  class raw_ostream;
  class raw_pwrite_stream;

//===----------------------------------------------------------------------===//
/// C++ class which implements the opaque lto_code_gen_t type.
///
struct LTOCodeGenerator {
  static const char *getVersionString();

  LTOCodeGenerator();
  LTOCodeGenerator(std::unique_ptr<LLVMContext> Context);
  ~LTOCodeGenerator();

  /// Merge given module.  Return true on success.
  bool addModule(struct LTOModule *);

  /// Set the destination module.
  void setModule(std::unique_ptr<LTOModule> M);

  void setTargetOptions(TargetOptions Options);
  void setDebugInfo(lto_debug_model);
  void setCodePICModel(Reloc::Model Model) { RelocModel = Model; }

  void setCpu(const char *MCpu) { this->MCpu = MCpu; }
  void setAttr(const char *MAttr) { this->MAttr = MAttr; }
  void setOptLevel(unsigned OptLevel);

  void setShouldInternalize(bool Value) { ShouldInternalize = Value; }
  void setShouldEmbedUselists(bool Value) { ShouldEmbedUselists = Value; }

  void addMustPreserveSymbol(StringRef Sym) { MustPreserveSymbols[Sym] = 1; }

  /// Pass options to the driver and optimization passes.
  ///
  /// These options are not necessarily for debugging purpose (the function
  /// name is misleading).  This function should be called before
  /// LTOCodeGenerator::compilexxx(), and
  /// LTOCodeGenerator::writeMergedModules().
  void setCodeGenDebugOptions(const char *Opts);

  /// Parse the options set in setCodeGenDebugOptions.
  ///
  /// Like \a setCodeGenDebugOptions(), this must be called before
  /// LTOCodeGenerator::compilexxx() and
  /// LTOCodeGenerator::writeMergedModules().
  void parseCodeGenDebugOptions();

  /// Write the merged module to the file specified by the given path.  Return
  /// true on success.
  bool writeMergedModules(const char *Path, std::string &ErrMsg);

  /// Compile the merged module into a *single* object file; the path to object
  /// file is returned to the caller via argument "name". Return true on
  /// success.
  ///
  /// \note It is up to the linker to remove the intermediate object file.  Do
  /// not try to remove the object file in LTOCodeGenerator's destructor as we
  /// don't who (LTOCodeGenerator or the obj file) will last longer.
  bool compile_to_file(const char **Name, bool DisableVerify,
                       bool DisableInline, bool DisableGVNLoadPRE,
                       bool DisableVectorization, std::string &ErrMsg);

  /// As with compile_to_file(), this function compiles the merged module into
  /// single object file. Instead of returning the object-file-path to the
  /// caller (linker), it brings the object to a buffer, and return the buffer
  /// to the caller. This function should delete intermediate object file once
  /// its content is brought to memory. Return NULL if the compilation was not
  /// successful.
  std::unique_ptr<MemoryBuffer> compile(bool DisableVerify, bool DisableInline,
                                        bool DisableGVNLoadPRE,
                                        bool DisableVectorization,
                                        std::string &errMsg);

  /// Optimizes the merged module.  Returns true on success.
  bool optimize(bool DisableVerify, bool DisableInline, bool DisableGVNLoadPRE,
                bool DisableVectorization, std::string &ErrMsg);

  /// Compiles the merged optimized module into a single object file. It brings
  /// the object to a buffer, and returns the buffer to the caller. Return NULL
  /// if the compilation was not successful.
  std::unique_ptr<MemoryBuffer> compileOptimized(std::string &ErrMsg);

  /// Compile the merged optimized module into out.size() object files each
  /// representing a linkable partition of the module. If out contains more
  /// than one element, code generation is done in parallel with out.size()
  /// threads.  Object files will be written to members of out. Returns true on
  /// success.
  bool compileOptimized(ArrayRef<raw_pwrite_stream *> Out, std::string &ErrMsg);

  void setDiagnosticHandler(lto_diagnostic_handler_t, void *);

  LLVMContext &getContext() { return Context; }

private:
  void initializeLTOPasses();

  bool compileOptimizedToFile(const char **Name, std::string &ErrMsg);
  void applyScopeRestrictions();
  void applyRestriction(GlobalValue &GV, ArrayRef<StringRef> Libcalls,
                        std::vector<const char *> &MustPreserveList,
                        SmallPtrSetImpl<GlobalValue *> &AsmUsed,
                        Mangler &Mangler);
  bool determineTarget(std::string &ErrMsg);

  static void DiagnosticHandler(const DiagnosticInfo &DI, void *Context);

  void DiagnosticHandler2(const DiagnosticInfo &DI);

  typedef StringMap<uint8_t> StringSet;

  std::unique_ptr<LLVMContext> OwnedContext;
  LLVMContext &Context;
  std::unique_ptr<Module> MergedModule;
  Linker IRLinker;
  std::unique_ptr<TargetMachine> TargetMach;
  bool EmitDwarfDebugInfo = false;
  bool ScopeRestrictionsDone = false;
  Reloc::Model RelocModel = Reloc::Default;
  StringSet MustPreserveSymbols;
  StringSet AsmUndefinedRefs;
  std::vector<std::string> CodegenOptions;
  std::string FeatureStr;
  std::string MCpu;
  std::string MAttr;
  std::string NativeObjectPath;
  TargetOptions Options;
  CodeGenOpt::Level CGOptLevel = CodeGenOpt::Default;
  unsigned OptLevel = 2;
  lto_diagnostic_handler_t DiagHandler = nullptr;
  void *DiagContext = nullptr;
  bool ShouldInternalize = true;
  bool ShouldEmbedUselists = false;
};
}
#endif

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"fmt"
	"log"

	"github.com/milosgajdos83/tenus"
)

func main() {
	// Create a new network bridge
	br, err := tenus.NewBridgeWithName("mybridge")
	if err != nil {
		log.Fatal(err)
	}

	// Bring the bridge up
	if err = br.SetLinkUp(); err != nil {
		fmt.Println(err)
	}

	// Create a dummy link
	dl, err := tenus.NewLink("mydummylink")
	if err != nil {
		log.Fatal(err)
	}

	// Add the dummy link into bridge
	if err = br.AddSlaveIfc(dl.NetInterface()); err != nil {
		log.Fatal(err)
	}

	// Bring the dummy link up
	if err = dl.SetLinkUp(); err != nil {
		fmt.Println(err)
	}
}


text:
var csv = require('ya-csv');
var fs=require('fs');

function Reader(){
    this.databaseR = csv.createCsvFileReader('./database/data.csv', {
        'separator': ',',
        'quote': '"',
        'escape': '"',
        'comment': '#'
    });

}

module.exports=Reader;


text:
<?php

use Symfony\Component\Config\Resource\ClassExistenceResource;
use Symfony\Component\Console\Application;

$handlers = [
    'main' => [
        'type' => 'stream',
        'path' => '%kernel.logs_dir%/%kernel.environment%.log',
        'level' => 'debug',
        'channels' => ['!event', '!doctrine'],
    ],
    'doctrine' => [
        'type' => 'stream',
        'path' => '%kernel.logs_dir%/doctrine_%kernel.environment%.log',
        'level' => 'debug',
        'channels' => ['doctrine'],
    ],
];

$container->addResource(new ClassExistenceResource(Application::class));
if (class_exists(Application::class)) {
    $handlers['console'] = [
        'type' => 'console',
        'process_psr_3_messages' => false,
        'channels' => ['!event', '!doctrine', '!console'],
    ];
}

$container->loadFromExtension(
    'monolog',
    [
        'handlers' => $handlers,
    ]
);


text:
module load openblas
module load lapack
module load openmpi-1.8.6

source ./helper.sh $*
stage_dl_cmake sundials-2.6.1.tar.gz -DCMAKE_INSTALL_PREFIX=$PREFIX/$DIRNAME


text:
import header
import footer

def renderHeader(data):
    return header.render(data)

def renderFooter():
    return footer.render()


text:
layout: default
title:  'Part 4: Coverage plotting, chimera detection and inspection'
---

# Part 4: Coverage plotting, chimera detection and inspection

## 4.3 Detection and inspection of chimeric reads
---

The MDA reaction will produce chimeric DNA in several ways.
If you want to get a more detailed picture of how this is happening, a very good starting point is the Lasken et al. paper from 2007.
See http://www.biomedcentral.com/1472-6750/7/19
One issue with single-cell data is that chimeric DNA will be formed and sequenced just like any other DNA.
This will be assembled into chimeric contigs which can be quite hard to distinguish from correct contigs.
One way of getting around this is by using multiple SAGs from the same organism.
If they have been amplified independently, chimeras will form, but there will be different chimeras in each SAG.
By co-assembling n-1 SAGs together, and mapping the reads from the excluded SAG against this co-assembly,
chimeric reads can be identified since they will be split and mapped to different contigs, or parts of contigs.
However, in most cases, like the one we are examining today, there is only 1 SAG.
Identifying chimeras in a single SAG is quite difficult since the chimeric mapped reads will map perfect against the assembled chimeric contigs.
We can look for traces of this though. If the chimeric reads were amplified late, resulting in very few reads actually being chimeric,
one might still catch these. To find chimeric reads, we return to our SAM file. The sixth field in the SAM file holds the mapped reads CIGAR value.
This value shows you how a read has been mapped in terms of matches and mismatches.
The most common value you would see if you open your SAM file would be "100M". This means that 100 bases of our 100 bp read was mapped against the contig.
We can also find a few that have a partial mapping. This usually looks something like "40S60M", meaning that the first 40 bases were masked off,
then the following 60 bases mapped against our contig.
If the masked of part of our read is mapped against another coordinate we can tell by the twelfth field in the SAM file.
It is prefixed with "SA:Z". To find these kinds of reads we can use 'grep'.

```sh
java -jar /sw/apps/bioinfo/picard/1.92/milou/ViewSam.jar I=G5_vs_contigs_sorted.bam | grep "SA:Z:"
```

If we also want to count the number of such reads we can use greps '-c' flag.

```sh
java -jar /sw/apps/bioinfo/picard/1.92/milou/ViewSam.jar I=G5_vs_contigs_sorted.bam | grep -c "SA:Z:"
# Or we could also use 'wc' (word count)
java -jar /sw/apps/bioinfo/picard/1.92/milou/ViewSam.jar I=G5_vs_contigs_sorted.bam | grep "SA:Z:" | wc -l
```

One thing to keep in mind is that some reads will be at the very ends of contigs, and that could be the reason why they are not mapped in full-length.
To correct for this we modify our command with some awk-magic.

```sh
java -jar /sw/apps/bioinfo/picard/1.92/milou/ViewSam.jar I=G5_vs_contigs_sorted.bam | grep "SA:Z:" | awk '{split($3,array,"_"); if($4 > 200 && $4 < (array[4]-300)) print $0}' | wc -l
```

For those of you unfamiliar with awk, the command gets the length of each contig by looking in the contig name which looks something like
NODE_24_length_2520_cov_2.03245_ID_101896
Awk then splits this into parts separated by "_" and stores them in a data-structure called an array.
We then tell awk to only print the line ($0) if the first position of our reads (fourth field in the SAM file, $4)
is more than 200 bases from the start, or more than than 300 bases from the end.
Keep in mind that all reads with an alternative alignment isn't necessarily chimeric in origin.
Some reads might be split due to assembly-errors or sequencing errors. If we want to do a better job at finding chimeras we would need more clonal SAGs.

  Previous page
  Next page


text:
title: 'New York Times Ten Best Books '
date: 2020-01-23T00:00:00-05:00
attribution: New York Times Ten Best Books - Editors of The New York Times Book Review.
book: book/pachinko.md
description: ''
featured: false
weight:

---
Lee's stunning novel, her second, chronicles four generations of an ethnic Korean family, first in Japanese-occupied Korea in the early 20th century, then in Japan itself from the years before World War II to the late 1980s. Exploring central concerns of identity, homeland and belonging, the book announces its ambitions right from the opening sentence: "History has failed us, but no matter." Lee suggests that behind the facades of wildly different people lie countless private desires, hopes and miseries, if we have the patience and compassion to look and listen.


text:
<license>
The MIT License (MIT)
Copyright (c) 2016 CNES
</license>


text:
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.Assertions;

/// <summary>
/// Represents a projectile explosion.  Damages enemy entities with an area effect.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class ShellExplosion : MonoBehaviour, IProjectile
{
    /// <summary>
    /// Triggered when the projectile is destroyed.
    /// </summary>
    public UnityEvent DestroyedEvent { get { return _destroyedEvent; } }

    [SerializeField] private UnityEvent _destroyedEvent;

    /// <summary>
    /// The time in seconds before the shell is removed.
    /// </summary>
    [SerializeField] private float _maxLifeTime = 10f;

    /// <summary>
    /// The maximum distance away from the explosion tanks can be and are still affected.
    /// </summary>
    [SerializeField] private float _explosionRadius = 5f;

    // Optional.
    [SerializeField] private ParticleSystem _explosionParticlePrefab;
    [SerializeField] private AudioSource _explosionAudio;

    private PlayerModel _owner;
    private Rigidbody _rigidbody;
    private int _areaDamage;

    public void Init(Entity creator)
    {
        // EARLY OUT ! //
        if(creator == null) return;

        _owner = creator.Owner;
        _areaDamage = creator.AreaAttackDamage;
    }

    private void Start ()
    {
        _rigidbody = GetComponent<Rigidbody>();
        Assert.IsNotNull(_rigidbody);

        // If it isn't destroyed by then, destroy the shell after it's lifetime.
        Destroy (gameObject, _maxLifeTime);
    }

    private void Update()
    {
        // Point the projectile to its direction of movement.
        if(_rigidbody != null && !Mathf.Approximately(_rigidbody.velocity.sqrMagnitude, 0f))
        {
            transform.forward = _rigidbody.velocity;
        }
    }

    private void OnTriggerEnter (Collider other)
    {
        // EARLY OUT! //
        // If the trigger isn't on an impact layer, ignore it.
        if(!CombatUtils.IsProjectileCollider(other.gameObject.layer)) return;

        // EARLY OUT! //
        // If the collider is a friendly entity, early out.
        if(CombatUtils.IsEntity(other.gameObject.layer) && !CombatUtils.IsEnemy(_owner, other)) return;

        // Collect all the colliders in a sphere from the shell's current position to a radius of the explosion radius.
        Collider[] colliders = Physics.OverlapSphere (transform.position, _explosionRadius, CombatUtils.EntityMask);

        for (int i = 0; i < colliders.Length; i++)
        {
            Entity targetEntity = colliders[i].GetComponent<Entity> ();

            // If it's an enemy unit, do damage to it.
            if(CombatUtils.IsEnemy(_owner, targetEntity))
            {
                targetEntity.TakeDamage(_areaDamage);
            }
        }

        if(_explosionParticlePrefab != null)
        {
            var explosion = Utils.Instantiate(_explosionParticlePrefab, transform.position, transform.rotation);

            // Play the particle system.
            explosion.Play();

            // Once the particles have finished, destroy the gameobject they are on.
            Destroy (explosion.gameObject, explosion.main.duration);
        }

        if(_explosionAudio != null)
        {
            // Play the explosion sound effect.
            _explosionAudio.Play();
        }

        // Destroy the shell.
        Destroy (gameObject);
    }

    private void OnDestroy()
    {
        _destroyedEvent.Invoke();
        _destroyedEvent.RemoveAllListeners();
    }
}


text:
package gocql

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"strings"
	"sync"
	"time"
	"unicode"

	"github.com/gocql/gocql/lru"
)

// Session is the interface used by users to interact with the database.
//
// It's safe for concurrent use by multiple goroutines and a typical usage
// scenario is to have one global session object to interact with the
// whole Cassandra cluster.
//
// This type extends the Node interface by adding a convinient query builder
// and automatically sets a default consinstency level on all operations
// that do not have a consistency level set.
type Session struct {
	Pool                ConnectionPool
	cons                Consistency
	pageSize            int
	prefetch            float64
	routingKeyInfoCache routingKeyInfoLRU
	schemaDescriber     *schemaDescriber
	trace               Tracer
	hostSource          *ringDescriber
	mu                  sync.RWMutex

	cfg ClusterConfig

	closeMu  sync.RWMutex
	isClosed bool
}

// NewSession wraps an existing Node.
func NewSession(cfg ClusterConfig) (*Session, error) {
	//Check that hosts in the ClusterConfig is not empty
	if len(cfg.Hosts) < 1 {
		return nil, ErrNoHosts
	}

	maxStreams := 128
	if cfg.ProtoVersion > protoVersion2 {
		maxStreams = 32768
	}

	if cfg.NumStreams <= 0 || cfg.NumStreams > maxStreams {
		cfg.NumStreams = maxStreams
	}

	pool, err := cfg.ConnPoolType(&cfg)
	if err != nil {
		return nil, err
	}

	//Adjust the size of the prepared statements cache to match the latest configuration
	stmtsLRU.Lock()
	initStmtsLRU(cfg.MaxPreparedStmts)
	stmtsLRU.Unlock()

	s := &Session{
		Pool:     pool,
		cons:     cfg.Consistency,
		prefetch: 0.25,
		cfg:      cfg,
	}

	//See if there are any connections in the pool
	if pool.Size() > 0 {
		s.routingKeyInfoCache.lru = lru.New(cfg.MaxRoutingKeyInfo)

		s.SetConsistency(cfg.Consistency)
		s.SetPageSize(cfg.PageSize)

		if cfg.DiscoverHosts {
			s.hostSource = &ringDescriber{
				session:    s,
				dcFilter:   cfg.Discovery.DcFilter,
				rackFilter: cfg.Discovery.RackFilter,
				closeChan:  make(chan bool),
			}

			go s.hostSource.run(cfg.Discovery.Sleep)
		}

		return s, nil
	}

	s.Close()

	return nil, ErrNoConnectionsStarted
}

// SetConsistency sets the default consistency level for this session. This
// setting can also be changed on a per-query basis and the default value
// is Quorum.
func (s *Session) SetConsistency(cons Consistency) {
	s.mu.Lock()
	s.cons = cons
	s.mu.Unlock()
}

// SetPageSize sets the default page size for this session. A value <= 0 will
// disable paging. This setting can also be changed on a per-query basis.
func (s *Session) SetPageSize(n int) {
	s.mu.Lock()
	s.pageSize = n
	s.mu.Unlock()
}

// SetPrefetch sets the default threshold for pre-fetching new pages. If
// there are only p*pageSize rows remaining, the next page will be requested
// automatically. This value can also be changed on a per-query basis and
// the default value is 0.25.
func (s *Session) SetPrefetch(p float64) {
	s.mu.Lock()
	s.prefetch = p
	s.mu.Unlock()
}

// SetTrace sets the default tracer for this session. This setting can also
// be changed on a per-query basis.
func (s *Session) SetTrace(trace Tracer) {
	s.mu.Lock()
	s.trace = trace
	s.mu.Unlock()
}

// Query generates a new query object for interacting with the database.
// Further details of the query may be tweaked using the resulting query
// value before the query is executed. Query is automatically prepared
// if it has not previously been executed.
func (s *Session) Query(stmt string, values ...interface{}) *Query {
	s.mu.RLock()
	qry := &Query{stmt: stmt, values: values, cons: s.cons,
		session: s, pageSize: s.pageSize, trace: s.trace,
		prefetch: s.prefetch, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
		defaultTimestamp: s.cfg.DefaultTimestamp,
	}
	s.mu.RUnlock()
	return qry
}

type QueryInfo struct {
	Id   []byte
	Args []ColumnInfo
	Rval []ColumnInfo
}

// Bind generates a new query object based on the query statement passed in.
// The query is automatically prepared if it has not previously been executed.
// The binding callback allows the application to define which query argument
// values will be marshalled as part of the query execution.
// During execution, the meta data of the prepared query will be routed to the
// binding callback, which is responsible for producing the query argument values.
func (s *Session) Bind(stmt string, b func(q *QueryInfo) ([]interface{}, error)) *Query {
	s.mu.RLock()
	qry := &Query{stmt: stmt, binding: b, cons: s.cons,
		session: s, pageSize: s.pageSize, trace: s.trace,
		prefetch: s.prefetch, rt: s.cfg.RetryPolicy}
	s.mu.RUnlock()
	return qry
}

// Close closes all connections. The session is unusable after this
// operation.
func (s *Session) Close() {

	s.closeMu.Lock()
	defer s.closeMu.Unlock()
	if s.isClosed {
		return
	}
	s.isClosed = true

	s.Pool.Close()

	if s.hostSource != nil {
		close(s.hostSource.closeChan)
	}
}

func (s *Session) Closed() bool {
	s.closeMu.RLock()
	closed := s.isClosed
	s.closeMu.RUnlock()
	return closed
}

func (s *Session) executeQuery(qry *Query) *Iter {

	// fail fast
	if s.Closed() {
		return &Iter{err: ErrSessionClosed}
	}

	var iter *Iter
	qry.attempts = 0
	qry.totalLatency = 0
	for {
		conn := s.Pool.Pick(qry)

		//Assign the error unavailable to the iterator
		if conn == nil {
			iter = &Iter{err: ErrNoConnections}
			break
		}

		t := time.Now()
		iter = conn.executeQuery(qry)
		qry.totalLatency += time.Now().Sub(t).Nanoseconds()
		qry.attempts++

		//Exit for loop if the query was successful
		if iter.err == nil {
			break
		}

		if qry.rt == nil || !qry.rt.Attempt(qry) {
			break
		}
	}

	return iter
}

// KeyspaceMetadata returns the schema metadata for the keyspace specified.
func (s *Session) KeyspaceMetadata(keyspace string) (*KeyspaceMetadata, error) {
	// fail fast
	if s.Closed() {
		return nil, ErrSessionClosed
	}

	if keyspace == "" {
		return nil, ErrNoKeyspace
	}

	s.mu.Lock()
	// lazy-init schemaDescriber
	if s.schemaDescriber == nil {
		s.schemaDescriber = newSchemaDescriber(s)
	}
	s.mu.Unlock()

	return s.schemaDescriber.getSchema(keyspace)
}

// returns routing key indexes and type info
func (s *Session) routingKeyInfo(stmt string) (*routingKeyInfo, error) {
	s.routingKeyInfoCache.mu.Lock()

	entry, cached := s.routingKeyInfoCache.lru.Get(stmt)
	if cached {
		// done accessing the cache
		s.routingKeyInfoCache.mu.Unlock()
		// the entry is an inflight struct similiar to that used by
		// Conn to prepare statements
		inflight := entry.(*inflightCachedEntry)

		// wait for any inflight work
		inflight.wg.Wait()

		if inflight.err != nil {
			return nil, inflight.err
		}

		key, _ := inflight.value.(*routingKeyInfo)

		return key, nil
	}

	// create a new inflight entry while the data is created
	inflight := new(inflightCachedEntry)
	inflight.wg.Add(1)
	defer inflight.wg.Done()
	s.routingKeyInfoCache.lru.Add(stmt, inflight)
	s.routingKeyInfoCache.mu.Unlock()

	var (
		prepared     *resultPreparedFrame
		partitionKey []*ColumnMetadata
	)

	// get the query info for the statement
	conn := s.Pool.Pick(nil)
	if conn == nil {
		// no connections
		inflight.err = ErrNoConnections
		// don't cache this error
		s.routingKeyInfoCache.Remove(stmt)
		return nil, inflight.err
	}

	prepared, inflight.err = conn.prepareStatement(stmt, nil)
	if inflight.err != nil {
		// don't cache this error
		s.routingKeyInfoCache.Remove(stmt)
		return nil, inflight.err
	}

	if len(prepared.reqMeta.columns) == 0 {
		// no arguments, no routing key, and no error
		return nil, nil
	}

	// get the table metadata
	table := prepared.reqMeta.columns[0].Table

	var keyspaceMetadata *KeyspaceMetadata
	keyspaceMetadata, inflight.err = s.KeyspaceMetadata(s.cfg.Keyspace)
	if inflight.err != nil {
		// don't cache this error
		s.routingKeyInfoCache.Remove(stmt)
		return nil, inflight.err
	}

	tableMetadata, found := keyspaceMetadata.Tables[table]
	if !found {
		// unlikely that the statement could be prepared and the metadata for
		// the table couldn't be found, but this may indicate either a bug
		// in the metadata code, or that the table was just dropped.
		inflight.err = ErrNoMetadata
		// don't cache this error
		s.routingKeyInfoCache.Remove(stmt)
		return nil, inflight.err
	}

	partitionKey = tableMetadata.PartitionKey

	size := len(partitionKey)
	routingKeyInfo := &routingKeyInfo{
		indexes: make([]int, size),
		types:   make([]TypeInfo, size),
	}
	for keyIndex, keyColumn := range partitionKey {
		// set an indicator for checking if the mapping is missing
		routingKeyInfo.indexes[keyIndex] = -1

		// find the column in the query info
		for argIndex, boundColumn := range prepared.reqMeta.columns {
			if keyColumn.Name == boundColumn.Name {
				// there may be many such bound columns, pick the first
				routingKeyInfo.indexes[keyIndex] = argIndex
				routingKeyInfo.types[keyIndex] = boundColumn.TypeInfo
				break
			}
		}

		if routingKeyInfo.indexes[keyIndex] == -1 {
			// missing a routing key column mapping
			// no routing key, and no error
			return nil, nil
		}
	}

	// cache this result
	inflight.value = routingKeyInfo

	return routingKeyInfo, nil
}

// ExecuteBatch executes a batch operation and returns nil if successful
// otherwise an error is returned describing the failure.
func (s *Session) ExecuteBatch(batch *Batch) error {
	// fail fast
	if s.Closed() {
		return ErrSessionClosed
	}

	// Prevent the execution of the batch if greater than the limit
	// Currently batches have a limit of 65536 queries.
	// https://datastax-oss.atlassian.net/browse/JAVA-229
	if batch.Size() > BatchSizeMaximum {
		return ErrTooManyStmts
	}

	var err error
	batch.attempts = 0
	batch.totalLatency = 0
	for {
		conn := s.Pool.Pick(nil)

		//Assign the error unavailable and break loop
		if conn == nil {
			err = ErrNoConnections
			break
		}
		t := time.Now()
		err = conn.executeBatch(batch)
		batch.totalLatency += time.Now().Sub(t).Nanoseconds()
		batch.attempts++
		//Exit loop if operation executed correctly
		if err == nil {
			return nil
		}

		if batch.rt == nil || !batch.rt.Attempt(batch) {
			break
		}
	}

	return err
}

// Query represents a CQL statement that can be executed.
type Query struct {
	stmt             string
	values           []interface{}
	cons             Consistency
	pageSize         int
	routingKey       []byte
	routingKeyBuffer []byte
	pageState        []byte
	prefetch         float64
	trace            Tracer
	session          *Session
	rt               RetryPolicy
	binding          func(q *QueryInfo) ([]interface{}, error)
	attempts         int
	totalLatency     int64
	serialCons       SerialConsistency
	defaultTimestamp bool

	disableAutoPage bool
}

// String implements the stringer interface.
func (q Query) String() string {
	return fmt.Sprintf("[query statement=%q values=%+v consistency=%s]", q.stmt, q.values, q.cons)
}

//Attempts returns the number of times the query was executed.
func (q *Query) Attempts() int {
	return q.attempts
}

//Latency returns the average amount of nanoseconds per attempt of the query.
func (q *Query) Latency() int64 {
	if q.attempts > 0 {
		return q.totalLatency / int64(q.attempts)
	}
	return 0
}

// Consistency sets the consistency level for this query. If no consistency
// level have been set, the default consistency level of the cluster
// is used.
func (q *Query) Consistency(c Consistency) *Query {
	q.cons = c
	return q
}

// GetConsistency returns the currently configured consistency level for
// the query.
func (q *Query) GetConsistency() Consistency {
	return q.cons
}

// Trace enables tracing of this query. Look at the documentation of the
// Tracer interface to learn more about tracing.
func (q *Query) Trace(trace Tracer) *Query {
	q.trace = trace
	return q
}

// PageSize will tell the iterator to fetch the result in pages of size n.
// This is useful for iterating over large result sets, but setting the
// page size to low might decrease the performance. This feature is only
// available in Cassandra 2 and onwards.
func (q *Query) PageSize(n int) *Query {
	q.pageSize = n
	return q
}

// DefaultTimestamp will enable the with default timestamp flag on the query.
// If enable, this will replace the server side assigned
// timestamp as default timestamp. Note that a timestamp in the query itself
// will still override this timestamp. This is entirely optional.
//
// Only available on protocol >= 3
func (q *Query) DefaultTimestamp(enable bool) *Query {
	q.defaultTimestamp = enable
	return q
}

// RoutingKey sets the routing key to use when a token aware connection
// pool is used to optimize the routing of this query.
func (q *Query) RoutingKey(routingKey []byte) *Query {
	q.routingKey = routingKey
	return q
}

// GetRoutingKey gets the routing key to use for routing this query. If
// a routing key has not been explicitly set, then the routing key will
// be constructed if possible using the keyspace's schema and the query
// info for this query statement. If the routing key cannot be determined
// then nil will be returned with no error. On any error condition,
// an error description will be returned.
func (q *Query) GetRoutingKey() ([]byte, error) {
	if q.routingKey != nil {
		return q.routingKey, nil
	}

	// try to determine the routing key
	routingKeyInfo, err := q.session.routingKeyInfo(q.stmt)
	if err != nil {
		return nil, err
	}
	if routingKeyInfo == nil {
		return nil, nil
	}

	if len(routingKeyInfo.indexes) == 1 {
		// single column routing key
		routingKey, err := Marshal(
			routingKeyInfo.types[0],
			q.values[routingKeyInfo.indexes[0]],
		)
		if err != nil {
			return nil, err
		}
		return routingKey, nil
	}

	// We allocate that buffer only once, so that further re-bind/exec of the
	// same query don't allocate more memory.
	if q.routingKeyBuffer == nil {
		q.routingKeyBuffer = make([]byte, 0, 256)
	}

	// composite routing key
	buf := bytes.NewBuffer(q.routingKeyBuffer)
	for i := range routingKeyInfo.indexes {
		encoded, err := Marshal(
			routingKeyInfo.types[i],
			q.values[routingKeyInfo.indexes[i]],
		)
		if err != nil {
			return nil, err
		}
		lenBuf := []byte{0x00, 0x00}
		binary.BigEndian.PutUint16(lenBuf, uint16(len(encoded)))
		buf.Write(lenBuf)
		buf.Write(encoded)
		buf.WriteByte(0x00)
	}
	routingKey := buf.Bytes()
	return routingKey, nil
}

func (q *Query) shouldPrepare() bool {

	stmt := strings.TrimLeftFunc(strings.TrimRightFunc(q.stmt, func(r rune) bool {
		return unicode.IsSpace(r) || r == ';'
	}), unicode.IsSpace)

	var stmtType string
	if n := strings.IndexFunc(stmt, unicode.IsSpace); n >= 0 {
		stmtType = strings.ToLower(stmt[:n])
	}
	if stmtType == "begin" {
		if n := strings.LastIndexFunc(stmt, unicode.IsSpace); n >= 0 {
			stmtType = strings.ToLower(stmt[n+1:])
		}
	}
	switch stmtType {
	case "select", "insert", "update", "delete", "batch":
		return true
	}
	return false
}

// SetPrefetch sets the default threshold for pre-fetching new pages. If
// there are only p*pageSize rows remaining, the next page will be requested
// automatically.
func (q *Query) Prefetch(p float64) *Query {
	q.prefetch = p
	return q
}

// RetryPolicy sets the policy to use when retrying the query.
func (q *Query) RetryPolicy(r RetryPolicy) *Query {
	q.rt = r
	return q
}

// Bind sets query arguments of query. This can also be used to rebind new query arguments
// to an existing query instance.
func (q *Query) Bind(v ...interface{}) *Query {
	q.values = v
	return q
}

// SerialConsistency sets the consistencyc level for the
// serial phase of conditional updates. That consitency can only be
// either SERIAL or LOCAL_SERIAL and if not present, it defaults to
// SERIAL. This option will be ignored for anything else that a
// conditional update/insert.
func (q *Query) SerialConsistency(cons SerialConsistency) *Query {
	q.serialCons = cons
	return q
}

// PageState sets the paging state for the query to resume paging from a specific
// point in time. Setting this will disable to query paging for this query, and
// must be used for all subsequent pages.
func (q *Query) PageState(state []byte) *Query {
	q.pageState = state
	q.disableAutoPage = true
	return q
}

// Exec executes the query without returning any rows.
func (q *Query) Exec() error {
	iter := q.Iter()
	return iter.err
}

func isUseStatement(stmt string) bool {
	if len(stmt) < 3 {
		return false
	}

	return strings.ToLower(stmt[0:3]) == "use"
}

// Iter executes the query and returns an iterator capable of iterating
// over all results.
func (q *Query) Iter() *Iter {
	if isUseStatement(q.stmt) {
		return &Iter{err: ErrUseStmt}
	}
	return q.session.executeQuery(q)
}

// MapScan executes the query, copies the columns of the first selected
// row into the map pointed at by m and discards the rest. If no rows
// were selected, ErrNotFound is returned.
func (q *Query) MapScan(m map[string]interface{}) error {
	iter := q.Iter()
	if err := iter.checkErrAndNotFound(); err != nil {
		return err
	}
	iter.MapScan(m)
	return iter.Close()
}

// Scan executes the query, copies the columns of the first selected
// row into the values pointed at by dest and discards the rest. If no rows
// were selected, ErrNotFound is returned.
func (q *Query) Scan(dest ...interface{}) error {
	iter := q.Iter()
	if err := iter.checkErrAndNotFound(); err != nil {
		return err
	}
	iter.Scan(dest...)
	return iter.Close()
}

// ScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
// statement containing an IF clause). If the transaction fails because
// the existing values did not match, the previous values will be stored
// in dest.
func (q *Query) ScanCAS(dest ...interface{}) (applied bool, err error) {
	iter := q.Iter()
	if err := iter.checkErrAndNotFound(); err != nil {
		return false, err
	}
	if len(iter.Columns()) > 1 {
		dest = append([]interface{}{&applied}, dest...)
		iter.Scan(dest...)
	} else {
		iter.Scan(&applied)
	}
	return applied, iter.Close()
}

// MapScanCAS executes a lightweight transaction (i.e. an UPDATE or INSERT
// statement containing an IF clause). If the transaction fails because
// the existing values did not match, the previous values will be stored
// in dest map.
//
// As for INSERT .. IF NOT EXISTS, previous values will be returned as if
// SELECT * FROM. So using ScanCAS with INSERT is inherently prone to
// column mismatching. MapScanCAS is added to capture them safely.
func (q *Query) MapScanCAS(dest map[string]interface{}) (applied bool, err error) {
	iter := q.Iter()
	if err := iter.checkErrAndNotFound(); err != nil {
		return false, err
	}
	iter.MapScan(dest)
	applied = dest["[applied]"].(bool)
	delete(dest, "[applied]")

	return applied, iter.Close()
}

// Iter represents an iterator that can be used to iterate over all rows that
// were returned by a query. The iterator might send additional queries to the
// database during the iteration if paging was enabled.
type Iter struct {
	err  error
	pos  int
	rows [][][]byte
	meta resultMetadata
	next *nextIter
}

// Columns returns the name and type of the selected columns.
func (iter *Iter) Columns() []ColumnInfo {
	return iter.meta.columns
}

// Scan consumes the next row of the iterator and copies the columns of the
// current row into the values pointed at by dest. Use nil as a dest value
// to skip the corresponding column. Scan might send additional queries
// to the database to retrieve the next set of rows if paging was enabled.
//
// Scan returns true if the row was successfully unmarshaled or false if the
// end of the result set was reached or if an error occurred. Close should
// be called afterwards to retrieve any potential errors.
func (iter *Iter) Scan(dest ...interface{}) bool {
	if iter.err != nil {
		return false
	}
	if iter.pos >= len(iter.rows) {
		if iter.next != nil {
			*iter = *iter.next.fetch()
			return iter.Scan(dest...)
		}
		return false
	}
	if iter.next != nil && iter.pos == iter.next.pos {
		go iter.next.fetch()
	}

	// currently only support scanning into an expand tuple, such that its the same
	// as scanning in more values from a single column
	if len(dest) != iter.meta.actualColCount {
		iter.err = errors.New("count mismatch")
		return false
	}

	// i is the current position in dest, could posible replace it and just use
	// slices of dest
	i := 0
	for c, col := range iter.meta.columns {
		if dest[i] == nil {
			i++
			continue
		}

		switch col.TypeInfo.Type() {
		case TypeTuple:
			// this will panic, actually a bug, please report
			tuple := col.TypeInfo.(TupleTypeInfo)

			count := len(tuple.Elems)
			// here we pass in a slice of the struct which has the number number of
			// values as elements in the tuple
			iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i:i+count])
			i += count
		default:
			iter.err = Unmarshal(col.TypeInfo, iter.rows[iter.pos][c], dest[i])
			i++
		}

		if iter.err != nil {
			return false
		}
	}

	iter.pos++
	return true
}

// Close closes the iterator and returns any errors that happened during
// the query or the iteration.
func (iter *Iter) Close() error {
	return iter.err
}

// checkErrAndNotFound handle error and NotFound in one method.
func (iter *Iter) checkErrAndNotFound() error {
	if iter.err != nil {
		return iter.err
	} else if len(iter.rows) == 0 {
		return ErrNotFound
	}
	return nil
}

// PageState return the current paging state for a query which can be used for
// subsequent quries to resume paging this point.
func (iter *Iter) PageState() []byte {
	return iter.meta.pagingState
}

type nextIter struct {
	qry  Query
	pos  int
	once sync.Once
	next *Iter
}

func (n *nextIter) fetch() *Iter {
	n.once.Do(func() {
		n.next = n.qry.session.executeQuery(&n.qry)
	})
	return n.next
}

type Batch struct {
	Type             BatchType
	Entries          []BatchEntry
	Cons             Consistency
	rt               RetryPolicy
	attempts         int
	totalLatency     int64
	serialCons       SerialConsistency
	defaultTimestamp bool
}

// NewBatch creates a new batch operation without defaults from the cluster
func NewBatch(typ BatchType) *Batch {
	return &Batch{Type: typ}
}

// NewBatch creates a new batch operation using defaults defined in the cluster
func (s *Session) NewBatch(typ BatchType) *Batch {
	s.mu.RLock()
	batch := &Batch{Type: typ, rt: s.cfg.RetryPolicy, serialCons: s.cfg.SerialConsistency,
		Cons: s.cons, defaultTimestamp: s.cfg.DefaultTimestamp}
	s.mu.RUnlock()
	return batch
}

// Attempts returns the number of attempts made to execute the batch.
func (b *Batch) Attempts() int {
	return b.attempts
}

//Latency returns the average number of nanoseconds to execute a single attempt of the batch.
func (b *Batch) Latency() int64 {
	if b.attempts > 0 {
		return b.totalLatency / int64(b.attempts)
	}
	return 0
}

// GetConsistency returns the currently configured consistency level for the batch
// operation.
func (b *Batch) GetConsistency() Consistency {
	return b.Cons
}

// Query adds the query to the batch operation
func (b *Batch) Query(stmt string, args ...interface{}) {
	b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, Args: args})
}

// Bind adds the query to the batch operation and correlates it with a binding callback
// that will be invoked when the batch is executed. The binding callback allows the application
// to define which query argument values will be marshalled as part of the batch execution.
func (b *Batch) Bind(stmt string, bind func(q *QueryInfo) ([]interface{}, error)) {
	b.Entries = append(b.Entries, BatchEntry{Stmt: stmt, binding: bind})
}

// RetryPolicy sets the retry policy to use when executing the batch operation
func (b *Batch) RetryPolicy(r RetryPolicy) *Batch {
	b.rt = r
	return b
}

// Size returns the number of batch statements to be executed by the batch operation.
func (b *Batch) Size() int {
	return len(b.Entries)
}

// SerialConsistency sets the consistencyc level for the
// serial phase of conditional updates. That consitency can only be
// either SERIAL or LOCAL_SERIAL and if not present, it defaults to
// SERIAL. This option will be ignored for anything else that a
// conditional update/insert.
//
// Only available for protocol 3 and above
func (b *Batch) SerialConsistency(cons SerialConsistency) *Batch {
	b.serialCons = cons
	return b
}

// DefaultTimestamp will enable the with default timestamp flag on the query.
// If enable, this will replace the server side assigned
// timestamp as default timestamp. Note that a timestamp in the query itself
// will still override this timestamp. This is entirely optional.
//
// Only available on protocol >= 3
func (b *Batch) DefaultTimestamp(enable bool) *Batch {
	b.defaultTimestamp = enable
	return b
}

type BatchType byte

const (
	LoggedBatch   BatchType = 0
	UnloggedBatch           = 1
	CounterBatch            = 2
)

type BatchEntry struct {
	Stmt    string
	Args    []interface{}
	binding func(q *QueryInfo) ([]interface{}, error)
}

type ColumnInfo struct {
	Keyspace string
	Table    string
	Name     string
	TypeInfo TypeInfo
}

func (c ColumnInfo) String() string {
	return fmt.Sprintf("[column keyspace=%s table=%s name=%s type=%v]", c.Keyspace, c.Table, c.Name, c.TypeInfo)
}

// routing key indexes LRU cache
type routingKeyInfoLRU struct {
	lru *lru.Cache
	mu  sync.Mutex
}

type routingKeyInfo struct {
	indexes []int
	types   []TypeInfo
}

func (r *routingKeyInfoLRU) Remove(key string) {
	r.mu.Lock()
	r.lru.Remove(key)
	r.mu.Unlock()
}

//Max adjusts the maximum size of the cache and cleans up the oldest records if
//the new max is lower than the previous value. Not concurrency safe.
func (r *routingKeyInfoLRU) Max(max int) {
	r.mu.Lock()
	for r.lru.Len() > max {
		r.lru.RemoveOldest()
	}
	r.lru.MaxEntries = max
	r.mu.Unlock()
}

type inflightCachedEntry struct {
	wg    sync.WaitGroup
	err   error
	value interface{}
}

// Tracer is the interface implemented by query tracers. Tracers have the
// ability to obtain a detailed event log of all events that happened during
// the execution of a query from Cassandra. Gathering this information might
// be essential for debugging and optimizing queries, but this feature should
// not be used on production systems with very high load.
type Tracer interface {
	Trace(traceId []byte)
}

type traceWriter struct {
	session *Session
	w       io.Writer
	mu      sync.Mutex
}

// NewTraceWriter returns a simple Tracer implementation that outputs
// the event log in a textual format.
func NewTraceWriter(session *Session, w io.Writer) Tracer {
	return &traceWriter{session: session, w: w}
}

func (t *traceWriter) Trace(traceId []byte) {
	var (
		coordinator string
		duration    int
	)
	t.session.Query(`SELECT coordinator, duration
			FROM system_traces.sessions
			WHERE session_id = ?`, traceId).
		Consistency(One).Scan(&coordinator, &duration)

	iter := t.session.Query(`SELECT event_id, activity, source, source_elapsed
			FROM system_traces.events
			WHERE session_id = ?`, traceId).
		Consistency(One).Iter()
	var (
		timestamp time.Time
		activity  string
		source    string
		elapsed   int
	)
	t.mu.Lock()
	defer t.mu.Unlock()
	fmt.Fprintf(t.w, "Tracing session %016x (coordinator: %s, duration: %v):\n",
		traceId, coordinator, time.Duration(duration)*time.Microsecond)
	for iter.Scan(&timestamp, &activity, &source, &elapsed) {
		fmt.Fprintf(t.w, "%s: %s (source: %s, elapsed: %d)\n",
			timestamp.Format("2006/01/02 15:04:05.999999"), activity, source, elapsed)
	}
	if err := iter.Close(); err != nil {
		fmt.Fprintln(t.w, "Error:", err)
	}
}

type Error struct {
	Code    int
	Message string
}

func (e Error) Error() string {
	return e.Message
}

var (
	ErrNotFound      = errors.New("not found")
	ErrUnavailable   = errors.New("unavailable")
	ErrUnsupported   = errors.New("feature not supported")
	ErrTooManyStmts  = errors.New("too many statements")
	ErrUseStmt       = errors.New("use statements aren't supported. Please see https://github.com/gocql/gocql for explaination.")
	ErrSessionClosed = errors.New("session has been closed")
	ErrNoConnections = errors.New("no connections available")
	ErrNoKeyspace    = errors.New("no keyspace provided")
	ErrNoMetadata    = errors.New("no metadata available")
)

type ErrProtocol struct{ error }

func NewErrProtocol(format string, args ...interface{}) error {
	return ErrProtocol{fmt.Errorf(format, args...)}
}

// BatchSizeMaximum is the maximum number of statements a batch operation can have.
// This limit is set by cassandra and could change in the future.
const BatchSizeMaximum = 65535


text:
module Chateau
  class Room
    attr_reader :name, :api, :configuration

    def initialize(name, api, configuration)
      @name = name
      @api = api
      @configuration= configuration
    end

    def message(text, from = nil, options = {})
      from = from || configuration.default_sender
      room_id = find_room_id
      api.send_message(room_id, from, text, options) if room_id
    end

    private

    def find_room_id
      api.room_id_for(name)
    end
  end
end


text:
title: Reflect Apply
localeTitle: تعكس تطبيق
---
## تعكس تطبيق

هذا هو كعب. [ساعد مجتمعنا على توسيعه](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/reflect/reflect-apply/index.md) .

[سيساعدك دليل النمط السريع هذا على ضمان قبول طلب السحب](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### معلومات اكثر:


text:
from pySDC.core.Hooks import hooks

class error_output(hooks):
    """
    Hook class to add output of error
    """

    def post_iteration(self, step, level_number):
        """
        Default routine called after each iteration
        Args:
            step: the current step
            level_number: the current level number
        """

        super(error_output, self).post_iteration(step, level_number)

        # some abbreviations
        L = step.levels[level_number]
        P = L.prob

        L.sweep.compute_end_point()

        uex = P.u_exact(step.time + step.dt)
        err = abs(uex - L.uend)

        print(
            '--- Current error (vs. exact solution) at iteration %2i and time %4.2f: %6.4e'
            % (step.status.iter, step.time, err)
        )


text:
/**
 *
 */
package gov.hhs.fha.nhinc.docretrieve.util;

import ihe.iti.xds_b._2007.RetrieveDocumentSetResponseType;

import gov.hhs.fha.nhinc.gateway.aggregator.document.DocumentConstants;

/**
 * @author achidamb
 *
 */
public class DocRetrieveStatusUtil {

    /**
     * Sets the response status (Success, Partial, Failure) of the to ResponseType based on the from ResponseType.
     *
     * @param from the ResponseType to based the status from
     * @param to the ResponseType whose status is to be modified
     * @return a String containing the response set on the from ResponseType
     */
    public static String setResponseStatus(RetrieveDocumentSetResponseType from, RetrieveDocumentSetResponseType to) {

        String status = null;

        if (to.getRegistryResponse().getStatus() == null) {
            status = from.getRegistryResponse().getStatus();
        } else if (from.getRegistryResponse().getStatus().equalsIgnoreCase(to.getRegistryResponse().getStatus())) {
            status = from.getRegistryResponse().getStatus();
        } else if (!from.getRegistryResponse().getStatus().equals(to.getRegistryResponse().getStatus())) {
            status = DocumentConstants.XDS_RETRIEVE_RESPONSE_STATUS_PARTIALSUCCESS;
        }
        return status;

    }

    /**
     * Returns true if the passed in status string has a success value.
     *
     * @param status String that contains the value to be checked
     * @return true if status string represents a success
     */
    public static boolean isStatusSuccess(String status) {
        return DocumentConstants.XDS_RETRIEVE_RESPONSE_STATUS_SUCCESS.equalsIgnoreCase(status);
    }

    /**
     * Returns true if the passed in status string has a failure value.
     *
     * @param status String that contains the value to be checked
     * @return true if status string represents a failure or partial failure
     */
    public static boolean isStatusFailureOrPartialFailure(String status) {
        return !isStatusSuccess(status);
    }

}


text:
<<<<<<< HEAD
<<<<<<< HEAD
var test = require("tap").test
  , fs = require("fs")
  , path = require("path")
  , existsSync = fs.existsSync || path.existsSync
  , npm = require("../../")
  , rimraf = require("rimraf")
  , mr = require("npm-registry-mock")
  , common = require('../common-tap.js')

test("dedupe finds the common module and moves it up one level", function (t) {
  setup(function (s) {
    npm.install(".", function (err) {
      if (err) return t.fail(err)
      npm.dedupe(function(err) {
        if (err) return t.fail(err)
        t.ok(existsSync(path.join(__dirname, "dedupe", "node_modules", "minimist")))
        t.ok(!existsSync(path.join(__dirname, "dedupe", "node_modules", "checker")))
        s.close() // shutdown mock registry.
        t.end()
      })
    })
  })
})

function setup (cb) {
  process.chdir(path.join(__dirname, "dedupe"))
  mr(common.port, function (s) { // create mock registry.
    npm.load({registry: common.registry}, function() {
      rimraf.sync(path.join(__dirname, "dedupe", "node_modules"))
      fs.mkdirSync(path.join(__dirname, "dedupe", "node_modules"))
      cb(s)
    })
  })
}
=======
var test = require("tap").test
  , fs = require("fs")
  , path = require("path")
  , existsSync = fs.existsSync || path.existsSync
  , npm = require("../../")
  , rimraf = require("rimraf")
  , mr = require("npm-registry-mock")
  , common = require('../common-tap.js')

test("dedupe finds the common module and moves it up one level", function (t) {
  setup(function (s) {
    npm.install(".", function (err) {
      if (err) return t.fail(err)
      npm.dedupe(function(err) {
        if (err) return t.fail(err)
        t.ok(existsSync(path.join(__dirname, "dedupe", "node_modules", "minimist")))
        t.ok(!existsSync(path.join(__dirname, "dedupe", "node_modules", "checker")))
        s.close() // shutdown mock registry.
        t.end()
      })
    })
  })
})

function setup (cb) {
  process.chdir(path.join(__dirname, "dedupe"))
  mr(common.port, function (s) { // create mock registry.
    npm.load({registry: common.registry}, function() {
      rimraf.sync(path.join(__dirname, "dedupe", "node_modules"))
      fs.mkdirSync(path.join(__dirname, "dedupe", "node_modules"))
      cb(s)
    })
  })
}
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
var test = require("tap").test
  , fs = require("fs")
  , path = require("path")
  , existsSync = fs.existsSync || path.existsSync
  , npm = require("../../")
  , rimraf = require("rimraf")
  , mr = require("npm-registry-mock")
  , common = require('../common-tap.js')

test("dedupe finds the common module and moves it up one level", function (t) {
  setup(function (s) {
    npm.install(".", function (err) {
      if (err) return t.fail(err)
      npm.dedupe(function(err) {
        if (err) return t.fail(err)
        t.ok(existsSync(path.join(__dirname, "dedupe", "node_modules", "minimist")))
        t.ok(!existsSync(path.join(__dirname, "dedupe", "node_modules", "checker")))
        s.close() // shutdown mock registry.
        t.end()
      })
    })
  })
})

function setup (cb) {
  process.chdir(path.join(__dirname, "dedupe"))
  mr(common.port, function (s) { // create mock registry.
    npm.load({registry: common.registry}, function() {
      rimraf.sync(path.join(__dirname, "dedupe", "node_modules"))
      fs.mkdirSync(path.join(__dirname, "dedupe", "node_modules"))
      cb(s)
    })
  })
}
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453


text:
CREATE DATABASE trip_builder;

-- Table city
CREATE TABLE city (
    id INT AUTO_INCREMENT NOT NULL,
    name VARCHAR(64) NOT NULL,
    country VARCHAR(64) NOT NULL,
    PRIMARY KEY(id)
)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

-- Table airport
CREATE TABLE airport (
    id INT AUTO_INCREMENT NOT NULL,
    city_id INT DEFAULT NULL,
    iata_code VARCHAR(3) NOT NULL,
    name VARCHAR(128) NOT NULL,
    INDEX IDX_B12CCE5E8BAC62AF (city_id),
    PRIMARY KEY(id)
)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

ALTER TABLE airport ADD CONSTRAINT FK_B12CCE5E8BAC62AF FOREIGN KEY (city_id) REFERENCES city (id);

-- Table trip
CREATE TABLE trip (
    id INT AUTO_INCREMENT NOT NULL,
    name VARCHAR(128) NOT NULL,
    PRIMARY KEY(id)
)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

-- Table trip_has_flight
CREATE TABLE trip_has_flight (
    trip_id INT NOT NULL,
    flight_id INT NOT NULL,
    INDEX IDX_1B672A83A5BC2E0E (trip_id),
    INDEX IDX_1B672A8391F478C5 (flight_id),
    PRIMARY KEY(trip_id, flight_id)
)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

-- Table flight
CREATE TABLE flight (
    id INT AUTO_INCREMENT NOT NULL,
    departure_airport_id INT DEFAULT NULL,
    arrival_airport_id INT DEFAULT NULL,
    INDEX IDX_C257E60EF631AB5C (departure_airport_id),
    INDEX IDX_C257E60E7F43E343 (arrival_airport_id),
    PRIMARY KEY(id)
)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;

ALTER TABLE flight ADD CONSTRAINT FK_C257E60EF631AB5C FOREIGN KEY (departure_airport_id) REFERENCES airport (id);
ALTER TABLE flight ADD CONSTRAINT FK_C257E60E7F43E343 FOREIGN KEY (arrival_airport_id) REFERENCES airport (id);

-- Constraints linking tables trip and flight.
ALTER TABLE trip_has_flight ADD CONSTRAINT FK_1B672A83A5BC2E0E FOREIGN KEY (trip_id) REFERENCES trip (id);
ALTER TABLE trip_has_flight ADD CONSTRAINT FK_1B672A8391F478C5 FOREIGN KEY (flight_id) REFERENCES flight (id);


text:
<?php

namespace AppBundle\Service\Hero;

use AppBundle\Service\Interfaces\IHeroMagician;

class Magician extends AbstractHeroFighter
{
    protected static $initialMana = 10;

    protected static $initialHealth = 20;

    protected $damage = 5;

    protected $mana;

    protected $magicDamageMultiply = 3;

    protected $manaCostPerSpell = 5;

    public function __construct(IHeroMagician $hero)
    {
        parent::__construct($hero);

        $this->mana = $hero->getMana();
    }

    /**
     * @param IHeroMagician $hero
     */
    public static function setInitialState(IHeroMagician $hero)
    {
        parent::setBaseInitialState($hero);

        $hero->setMana(self::$initialMana);
    }

    /**
     * @return string
     */
    public function getType(): string
    {
        return 'Magician';
    }

    /**
     * @return float
     */
    public function getDamage(): float
    {
        $damage = parent::getDamage();
        if ($this->mana - $this->manaCostPerSpell > 0) {
            $damage *= $this->magicDamageMultiply;

            $this->mana -= $this->manaCostPerSpell;
            $this->mana = $this->mana >= 0 ? $this->mana : 0;
        }

        return $damage;
    }

    /**
     * @param IHeroMagician $hero
     */
    public function exportStates(IHeroMagician $hero)
    {
        parent::exportBaseStates($hero);

        $hero->setMana($this->mana);
    }
}


text:
"""
    the main entry point of utils

    Parameters
    ----------

    Attributes
    ----------

    Methods
    -------

    See Also
    --------

    Notes
    -----

    Examples
    --------

    """
from .mfreadnam import parsenamefile
from .util_array import Util3d, Util2d, Transient2d, Transient3d, read1d
from .util_list import MfList
from .binaryfile import BinaryHeader, HeadFile, UcnFile, CellBudgetFile
from .formattedfile import FormattedHeadFile
from .modpathfile import PathlineFile, EndpointFile
from .swroutputfile import SwrStage, SwrBudget, SwrFlow, SwrExchange, \
    SwrStructure
from .observationfile import HydmodObs, SwrObs
from .reference import SpatialReference  # , TemporalReference
from .mflistfile import MfListBudget, MfusgListBudget, SwtListBudget, \
    SwrListBudget
from .check import check, get_neighbors
from .utils_def import FlopyBinaryData, totim_to_datetime
from .flopy_io import read_fixed_var, write_fixed_var
from .zonbud_utils import write_zonfile, run_zonbud


text:
<?php
include_once "../Class/Config.php";
session_start();
$db = new PDO("mysql:host=" . config::SERVERNAME . ";dbname=" . config::DBNAME, config::USER, config::PASSWORD);
$req = $db -> prepare("Select AdresseMail , MotDePasse ,Id from Client ");
$req -> execute();
$res = $req -> fetchAll();
var_dump($res);
$i=1;
foreach($res as $personne){
    if($personne ['AdresseMail']==$_POST['mail']){
        if($personne['MotDePasse']==$_POST['motDePasse']){
            $_SESSION['idClient'] = $personne['Id'];
            header('location:../Index.php');
        }else{
            header('location:../Connexion.php?error=mdp');
        }
    }else{
        $i+=1;
        if($i > count($res)){
           header('location:../Connexion.php?error=mail');
        }
    }
}

?>


text:
'use strict';

/* Controllers */

var declashControllers = angular.module('declashControllers', [])

declashControllers.controller('AppController', ['$scope', '$rootScope', '$location', 'GlobalService',
    function($scope, $rootScope, $location, GlobalService) {
        var failureCb = function (status) {
            console.log(status);
        };
        $rootScope.globals = GlobalService;

        $scope.initialize = function (is_authenticated) {
            if(is_authenticated == 'False') {
                $rootScope.globals.is_authenticated = false;
            }
            else {
                $rootScope.globals.is_authenticated = true;
            }
        };
    }
]);

declashControllers.controller('SessionListCtrl', ['$scope', '$interval','Restangular', '$modal',
    function($scope, $interval, Restangular, $modal) {

        var getSessions = function() {
            Restangular.all('sessions').getList().then(function (sessions) {
                $scope.sessions = sessions;
                if(!$scope.$$phase) {
                    $scope.$apply();
                }
            })
        }
        getSessions();

        // $interval(getSessions, 30000);

        $scope.openForm = function(session) {
            var modalInstance = $modal.open({
                templateUrl: "sessionreg2.html",
                controller: 'DebaterRegCtrl',
                resolve: {
                    sessionObj: function() {
                        return session;
                    }
                }
            });

            modalInstance.result.then(function() {
                getSessions();
            })
        };

}]);

declashControllers.controller('DebaterRegCtrl', ['$scope', '$modalInstance', 'Restangular','sessionObj',
    function($scope, $modalInstance, Restangular, sessionObj) {
        $scope.session = sessionObj;
        $scope.errorMessage = "";
        $scope.debatername = "";
        $scope.teammate = {};
        $scope.teammate2 = {};
        $scope.viableTeammates = [];
        $scope.novpro = 'NOV';
        $scope.djs = 'DEBATE';
        $scope.positionpref = 'OP';
        $scope.customrequest = "";

        for(var i=0; i<sessionObj.debaters.length; i++) {
            if (sessionObj.debaters[i].teammates.length < 1 && sessionObj.debaters[i].team == null) {
                $scope.viableTeammates.push(sessionObj.debaters[i]);
            }
        }

        // $scope.viableTeammates = viableTeammates();

        $scope.Submit = function() {
            var teammatesArray = function() {
                if($scope.teammate.id) {
                    if($scope.teammate2.id) {
                        return [$scope.teammate.id, $scope.teammate2.id]
                    }
                    return [$scope.teammate.id];
                }
                return [];
            }

            var master = {
                'name': this.debatername,
                'teammates': teammatesArray(),
                'team': null,
                'nov_pro': this.novpro,
                'debate_judge_spectate': this.djs,
                'session': $scope.session.id,
                'position': this.positionpref,
                'custom_requests': this.customrequest
            };

            Restangular.all('debaters/').post(master).then(function() {
                $modalInstance.close();
            }, function(response) {
                $scope.errorMessage = response.data;
                // console.log(response.data)
            });
        };

        $scope.Cancel = function() {
            $modalInstance.dismiss('cancel');
        };

        $scope.addTeammate = function(debaterTeammate, index) {
            if(index == 0) {
                $scope.teammate = debaterTeammate;
            }
            else {
                $scope.teammate2 = debaterTeammate;
            }

        }

        $scope.teammateFilter = function(debater) {
            return debater != $scope.teammate;
        }

}]);

declashControllers.controller('ManagementCtrl', ['$scope', '$route','Restangular', '$modal',
    function($scope, $route, Restangular, $modal) {
        $scope.isCollapsed = false;

        var pushAlerts = function(response) {
            if (response.data instanceof Array){
                for(var i=0, len=response.data.length; i<len; i++) {
                    $scope.alerts.push(response.data[i]);
                }
            }
            else {
                $scope.alerts.push(response.data)
            }
        }

        var getRooms = function () {
            Restangular.all('rooms').getList().then(function(rooms) {
            $scope.rooms = rooms;
            if(!$scope.$$phase) {
                    $scope.$apply();
                }
            });
        };

        var getSession = function () {
            Restangular.all('sessions').getList().then(function(sessions) {
                //This is assuming logged in user can only view his/her own session AND
                //a user can only have one session unfinalized at a time.
                $scope.alerts = [];
                $scope.session = sessions[0];
                $scope.tableDebaters = getTableDebaters(sessions[0]);
                $scope.tableTeams = getTableTeams(sessions[0], sessions[0].debaters)

            }, function(response) {
                pushAlerts(response);
            });
        };

        var getTableDebaters = function(session) {
            var debaters = [];
            var sessionDebaters = JSON.parse(JSON.stringify(session.debaters));
            for(var i=0; i<sessionDebaters.length; i++) {
                var mateLength = sessionDebaters[i].teammates.length;
                if(mateLength < 1) {
                    debaters.push(sessionDebaters[i]);
                }
                else {
                    var pluckedMates = _.remove(sessionDebaters,
                        function(d) {
                            for(var j=0; j<mateLength; j++) {
                                if(d.id === sessionDebaters[i].teammates[j]) {
                                    return true;
                                }
                            }
                            return false;
                        });

                    sessionDebaters[i].teammates = pluckedMates;
                    debaters.push(sessionDebaters[i]);
                }
            }
            return debaters;
        };

        var getTableTeams = function(session, debaters) {
            var sessionTeams = session.teams;
            var sessionDebaters = debaters;
            for(var i=0, len=sessionTeams.length; i<len; i++) {
                for(var j=0, len2=sessionTeams[i].team_members.length; j<len2; j++) {
                    sessionTeams[i].team_members[j] = _.find(
                        sessionDebaters, function(d) {return d.id == sessionTeams[i].team_members[j]});
                }
                sessionTeams[i].room = _.find($scope.rooms, function(r) {return r.id == sessionTeams[i].room});
            }
            return sessionTeams;
        };

        getRooms();
        getSession();

        $scope.createSession = function() {
            var modalInstance = $modal.open({
                templateUrl: "sessioncreate.html",
                controller: 'SessionCreateCtrl',
            });

            modalInstance.result.then(function(session) {
                $scope.session = session;
            });
        };

        $scope.toggleReg = function(open) {
            var putSession = Restangular.copy($scope.session)
            // putSession.openForReg = open;
            putSession.patch({'openForReg': open}).then(function (session) {
                $scope.session.openForReg = session.openForReg;
            }, function(response) {
                pushAlerts(response);
            });
        };

        $scope.deClashify = function() {
            console.log('boom');
            Restangular.one('sessions', $scope.session.id).get({'declashify': true}).then(function(session) {
                getSession();
                getRooms();
            }, function(response) {
                pushAlerts(response);
                console.log(response);
            });
        };

        $scope.togglePublish = function(publish) {
            var putSession = Restangular.copy($scope.session)

            putSession.patch({'published': publish}).then(function(session) {
                $scope.session.published = session.published;
            }, function(response) {
                pushAlerts(response);
                console.log('response data' + response.data);
            });
        };

        $scope.teamNullDebaters = function(debater) {
            return debater.team == null;
        };

        $scope.addRoom = function(room) {
            if(room.location.length<1) {
                return;
            }

            if (!room.group) {
                room.group = 0;
            }

            Restangular.all('rooms/').post(room).then(function(room) {
                $scope.rooms.push(room);
            }, function(response) {
                pushAlerts(response);
                console.log(response.data);
            });
        };

        $scope.deleteRoom = function(room) {
            Restangular.one('rooms', room.id).remove().then(function() {
                $scope.rooms = _.reject($scope.rooms, function(rm) {return rm == room});
                getSession();
            }, function(response) {
                pushAlerts(response);
                console.log(reponse.data);
            });
        };

        $scope.createTeam = function() {
            var modalInstance = $modal.open({
                templateUrl: "teamcreate.html",
                controller: 'TeamCreateCtrl',
                resolve: {
                    session: function() {
                        getSession()
                        return $scope.session
                    },
                    rooms: function() {
                        return $scope.rooms
                    }
                }

            });
            modalInstance.result.then(function(team) {
                getSession();
            });
        };

        $scope.deleteDebater = function(debater) {
            Restangular.one('debaters', debater.id).remove().then(function(deletedDebater) {
                getSession();
            }, function(response) {
                pushAlerts(response);
            })
        }

        $scope.patchDebater = function(debater, elem, data) {
            var patchObj = {};
            patchObj[elem] = data;
            Restangular.one('debaters', debater.id).patch(patchObj).then(function(debater) {
                getSession();
            }, function(response) {
                pushAlerts(response);
                console.log(response);
            })
        }

        $scope.deleteTeam = function(team) {
            Restangular.one('teams', team.id).remove().then(function(deletedTeam) {
                getSession();
            });
        };

        $scope.finalize = function() {
            var modalInstance = $modal.open({
                templateUrl: "finalize.html",
                controller: 'FinalizeCtrl',
                resolve: {
                    sessionID: function() {
                        getSession()
                        return $scope.session.id
                    }
                }

            });
            modalInstance.result.then(function() {
                getSession();
            });

        }

        $scope.createDiffStyleForMessage = function(debater) {
            if(debater && debater.custom_requests) {
                return {color: "red"};
            }
            else {
                return {color: "black"};
            }
        }
  }]);

declashControllers.controller('SessionCreateCtrl', ['$scope', '$modalInstance', 'Restangular',
    function($scope, $modalInstance, Restangular) {
        $scope.master = {};

        $scope.submit = function(session) {
            $scope.master = angular.copy(session);
            $scope.master.openForReg = true;

            // console.log($scope.master)

            Restangular.all('sessions/').post($scope.master).then(function(addedSession) {
                Restangular.one('sessions', addedSession.id).get().then(function(session) {
                    $modalInstance.close(session);
                });
            }, function(response) {
            });
        };
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };

}]);

declashControllers.controller('TeamCreateCtrl', ['$scope', '$modalInstance', 'Restangular', 'session', 'rooms',
    function($scope, $modalInstance, Restangular, session, rooms) {
        $scope.errorMessage = "";
        $scope.session = session;
        $scope.rooms = rooms;
        $scope.teamDebaters = [];

        $scope.team = {};
        $scope.team.position = 'GV';
        $scope.team.room = null;

        $scope.nullTeamFilter = function(debater) {
            var cond1 = debater.team == null && !(_.contains($scope.teamDebaters, debater));
            var cond2 = debater.debate_judge_spectate != 'JUDGE' && debater.debate_judge_spectate != 'SPEC';

            return cond1 && cond2;
        };

        $scope.notInUsedRoom = function(room) {
            // for(var i=0;i<session.teams.length;i++) {
            //     if(room.id == session.teams[i].room.id) {
            //         return false;
            //     }
            // }

            var teamCount = _.reduce(
                session.teams,
                function(sum, team) {
                    if(team.room.id == room.id) {
                        sum++;
                    }
                    return sum;
                },
                0
            );

            if(session.format == 'BP') {
                return ((teamCount < 4)? true : false);
            }
            else {
                return ((teamCount < 2)? true : false);
            }
        };

        $scope.addDebater = function(debater, index) {
            $scope.teamDebaters[index] = debater
        };

        $scope.submit = function(team) {
            $scope.master = {};
            $scope.master.session = $scope.session.id;
            $scope.master.team_members = _.map($scope.teamDebaters, function(d) {return d.id});
            $scope.master.room = team.room.id;
            $scope.master.position = team.position;

            Restangular.all('teams/').post($scope.master).then(function(addedTeam) {
                $modalInstance.close(addedTeam);
            }, function(response) {
                $scope.errorMessage = response.data;
                console.log($scope.master);
            });

        };

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
}]);

declashControllers.controller('TeamsCtrl', ['$scope', '$routeParams','Restangular',
    function($scope, $routeParams, Restangular, $modal) {
        Restangular.all('teams').getList({'sessionID': $routeParams.sessionID}).then(function(teams) {

            $scope.teams = teams.filter(function(leTeam) {
                return leTeam.session == $routeParams.sessionID;
            });
        });

}]);

declashControllers.controller('FinalizeCtrl', ['$scope', '$modalInstance', 'Restangular', 'sessionID',
    function($scope, $modalInstance, Restangular, sessionID) {

        $scope.confirm = function() {
            Restangular.one('sessions', sessionID).patch({'finalized': true}).then(function () {
                $modalInstance.close();
            });
        };

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        }

}]);


text:
@class DVTTextCompletionSession;

@interface FATextCompletionListHeaderView : NSTableHeaderView

- (void) updateWithDataFromSession: (DVTTextCompletionSession *) session;

@end

@interface FATextCompletionListCornerView : NSView

@end


text:
<?php
/**
 * Created by Antoine Jackson
 * User: Antoine Jackson
 * Date: 11/10/13
 * Time: 1:45 PM
 */

namespace BusinessManagement;

class BlockConfigNotFoundException extends \Exception {

}


text:
#ifndef SkStroke_DEFINED
#define SkStroke_DEFINED

#include "SkPoint.h"
#include "SkPaint.h"

struct SkRect;
class SkPath;

/** \class SkStroke
    SkStroke is the utility class that constructs paths by stroking
    geometries (lines, rects, ovals, roundrects, paths). This is
    invoked when a geometry or text is drawn in a canvas with the
    kStroke_Mask bit set in the paint.
*/
class SkStroke {
public:
    SkStroke();
    SkStroke(const SkPaint&);
    SkStroke(const SkPaint&, SkScalar width);   // width overrides paint.getStrokeWidth()

    SkPaint::Cap    getCap() const { return (SkPaint::Cap)fCap; }
    void        setCap(SkPaint::Cap);

    SkPaint::Join   getJoin() const { return (SkPaint::Join)fJoin; }
    void        setJoin(SkPaint::Join);

    void    setMiterLimit(SkScalar);
    void    setWidth(SkScalar);

    bool    getDoFill() const { return SkToBool(fDoFill); }
    void    setDoFill(bool doFill) { fDoFill = SkToU8(doFill); }

    void    strokeLine(const SkPoint& start, const SkPoint& end, SkPath*) const;
    void    strokeRect(const SkRect& rect, SkPath*) const;
    void    strokeOval(const SkRect& oval, SkPath*) const;
    void    strokeRRect(const SkRect& rect, SkScalar rx, SkScalar ry, SkPath*) const;
    void    strokePath(const SkPath& path, SkPath*) const;

    ////////////////////////////////////////////////////////////////

private:
    SkScalar    fWidth, fMiterLimit;
    uint8_t     fCap, fJoin;
    SkBool8     fDoFill;

    friend class SkPaint;
};

#endif


text:
#ifndef Fennel_DT_Test_CorrelationJoinExecStreamTestSuite_Included
#define Fennel_DT_Test_CorrelationJoinExecStreamTestSuite_Included

#include "fennel/common/CommonPreamble.h"
#include "fennel/test/ExecStreamUnitTestBase.h"
#include <boost/test/test_tools.hpp>
using namespace fennel;

class CorrelationJoinExecStreamTestSuite : public ExecStreamUnitTestBase
{
    TupleAttributeDescriptor descAttrInt64;
    TupleDescriptor descInt64;
    TupleAttributeDescriptor descAttrVarbinary16;
    TupleDescriptor descVarbinary16;

public:
    explicit CorrelationJoinExecStreamTestSuite(bool addAllTests = true);
    void testCorrelationJoin();
};

#endif

// End CorrelationJoinExecStreamTestSuite.h


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SlashTodo.Core
{
    public class TodoContext
    {
        public string TeamId { get; set; }
        public string UserId { get; set; }
    }
}


text:
package javax.measure.unit;

import javax.measure.converter.UnitConverter;
import javax.measure.quantity.Quantity;

/**
 *
 This class represents the units used in expressions to distinguish
 *     between quantities of a different nature but of the same dimensions.

 *
 *
 Instances of this class are created through the
 *     {@link Unit#alternate(String)} method.

 *
 * @author  Jean-Marie Dautelle
 * @version 4.2, August 26, 2007
 */
public final class AlternateUnit<Q extends Quantity> extends DerivedUnit<Q> {

    /**
     * Holds the symbol.
     */
    private final String _symbol;

    /**
     * Holds the parent unit (a system unit).
     */
    private final Unit<?> _parent;

    /**
     * Creates an alternate unit for the specified unit identified by the
     * specified symbol.
     *
     * @param symbol the symbol for this alternate unit.
     * @param parent the system unit from which this alternate unit is
     *        derived.
     * @throws UnsupportedOperationException if the source is not
     *         a standard unit.
     * @throws IllegalArgumentException if the specified symbol is
     *         associated to a different unit.
     */
    AlternateUnit(String symbol, Unit<?> parent) {
        if (!parent.isStandardUnit())
            throw new UnsupportedOperationException(this
                    + " is not a standard unit");
        _symbol = symbol;
        _parent = parent;
        // Checks if the symbol is associated to a different unit.
        synchronized (Unit.SYMBOL_TO_UNIT) {
            Unit<?> unit = Unit.SYMBOL_TO_UNIT.get(symbol);
            if (unit == null) {
                Unit.SYMBOL_TO_UNIT.put(symbol, this);
                return;
            }
            if (unit instanceof AlternateUnit) {
                AlternateUnit<?> existingUnit = (AlternateUnit<?>) unit;
                if (symbol.equals(existingUnit._symbol)
                        && _parent.equals(existingUnit._parent))
                    return; // OK, same unit.
            }
            throw new IllegalArgumentException("Symbol " + symbol
                    + " is associated to a different unit");
        }
    }

    /**
     * Returns the symbol for this alternate unit.
     *
     * @return this alternate unit symbol.
     */
    public final String getSymbol() {
        return _symbol;
    }

    /**
     * Returns the parent unit from which this alternate unit is derived
     * (a system unit itself).
     *
     * @return the parent of the alternate unit.
     */
    @SuppressWarnings("unchecked")
    public final Unit<? super Q> getParent() {
        return (Unit<? super Q>) _parent;
    }

    @Override
    public final Unit<? super Q> getStandardUnit() {
        return this;
    }

    @Override
    public final UnitConverter toStandardUnit() {
        return UnitConverter.IDENTITY;
    }

    /**
     * Indicates if this alternate unit is considered equals to the specified
     * object (both are alternate units with equal symbol, equal base units
     * and equal converter to base units).
     *
     * @param  that the object to compare for equality.
     * @return true if this and that
     *         are considered equals; falseotherwise.
     */
    public boolean equals(Object that) {
        if (this == that)
            return true;
        if (!(that instanceof AlternateUnit))
            return false;
        AlternateUnit<?> thatUnit = (AlternateUnit<?>) that;
        return this._symbol.equals(thatUnit._symbol); // Symbols are unique.
    }

    // Implements abstract method.
    public int hashCode() {
        return _symbol.hashCode();
    }

    private static final long serialVersionUID = 1L;
}


text:
package com.cyphercove.lwptools.android.prefs;

import java.util.ArrayList;
import java.util.List;
import android.annotation.TargetApi;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.widget.ListAdapter;

public abstract class ProgramaticPreferencesActivity extends PreferenceActivity{

	private List<UniversalHeader> mUniversalHeaders;
	private List<Header> mHeaders;

	private OnRebuildPrefScreenListener rebuildPrefScreenOnResumeListener = null;

	@Override
	public void onCreate(Bundle savedInstanceState){
		mUniversalHeaders = onCreateUniversalHeaders(); //Need the list before super.onCreate, because that calls onBuildHeaders, where the list is used.

		super.onCreate(savedInstanceState);

		//Load legacy headers, or the appropriate preferences screen if not on Honeycomb or later.
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			String action = getIntent().getAction();
			if (action != null){
				constructLegacyFragmentAlternativeFromActionName(action);
			} else { //Is showing a headers view
				constructLegacyHeadersScreen();
			}
		}

	}

	@Override
	public void onResume(){
		super.onResume();
		if (rebuildPrefScreenOnResumeListener!=null){
			rebuildPrefScreenOnResumeListener.onRebuildPrefScreen();
		}
	}

	@Override
	public boolean isValidFragment(String fragmentName){
		return true;
	}

	public void enableRebuildPrefScreenOnResume(OnRebuildPrefScreenListener onRebuildPrefScreenListener){
		rebuildPrefScreenOnResumeListener = onRebuildPrefScreenListener;
	}

	public void disableRebuildPrefScreenOnResume(){
		rebuildPrefScreenOnResumeListener = null;
	}

	protected abstract void constructLegacyFragmentAlternativeFromActionName(String actionName);

	protected OnRebuildPrefScreenListener getLegacyOnRebuildPrefScreenListener(final String actionName){
		return new OnRebuildPrefScreenListener(){
			@Override
			public void onRebuildPrefScreen() {
				constructLegacyFragmentAlternativeFromActionName(actionName);
			}

		};
	}

	/**
	 *
	 * @return whether any headers were used.
	 */
	@SuppressWarnings("deprecation")
	private final void constructLegacyHeadersScreen(){
		PrefRoot root = new PrefRoot(getPreferenceManager(), this, getSharedPreferences(), getIndentLayoutResource(),
				getChooseColorStringResource(), getAdvancedColorPickerStringResources(), null);

		for (UniversalHeader hf : mUniversalHeaders){
			hf.addLegacyHeader(this, getHeaderLayoutResource(), root);
		}

		setPreferenceScreen(root.root);
	}

	@Override
	public final void onBuildHeaders(List<Header> target) {
		for (UniversalHeader hf : mUniversalHeaders){
			Header h = hf.createHeader(this);
			if (h!=null)
				target.add( h );
		}
		mHeaders = target;
	}

	@Override
	public void setListAdapter(ListAdapter adapter) {
		if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
			int i, count;

			if (mHeaders == null) {
				mHeaders = new ArrayList<Header>();
				// When the saved state provides the list of headers,
				// onBuildHeaders is not called
				// so we build it from the adapter given, then use our own adapter

				count = adapter.getCount();
				for (i = 0; i < count; ++i)
					mHeaders.add((Header) adapter.getItem(i));
			}

			super.setListAdapter(new UniversalHeaderAdapter(this, mHeaders, getHeaderLayoutResource()));
		} else {
			super.setListAdapter(adapter);
		}

	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onHeaderClick(Header header, int position){
		if (header.extras!=null && header.extras.getInt(UniversalHeader.HEADER_TYPE_KEY)== UniversalHeader.TYPE_ABOUT_DIALOG){
			int versionStringResource = header.extras.getInt(UniversalHeader.ABOUT_DIALOG_VERSION_RESOURCE);
			int bodyResource = header.extras.getInt(UniversalHeader.ABOUT_DIALOG_HTML_MESSAGE_RESOURCE);
			int iconResource = header.extras.getInt(UniversalHeader.ABOUT_DIALOG_ICON_RESOURCE);
			UniversalHeader.showAboutDialog(this, versionStringResource, bodyResource,
					iconResource);
		}
		if (header.extras!=null && header.extras.getInt(UniversalHeader.HEADER_TYPE_KEY)== UniversalHeader.TYPE_ONE_TIME_INTENT){
			String prefNamePressed = header.extras.getString(UniversalHeader.ONE_TIME_INTENT_PREF_NAME_PRESSED);
			PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(prefNamePressed, true).commit();
		}
		super.onHeaderClick(header, position);
	}

	protected abstract SharedPreferences getSharedPreferences();
	/**
	 * Override and create a list of header prefs here.
	 * @return Provide a List of HeaderPrefs to populate in Headers list.
	 */
	protected abstract List<UniversalHeader> onCreateUniversalHeaders();
	protected abstract int getIndentLayoutResource();
	protected abstract int getChooseColorStringResource();
	protected abstract AdvancedColorPickerDialog.TextResources getAdvancedColorPickerStringResources();

	/**
	 * @return A layout XML resource that must have a TextViews with IDs @+android:id/title and @+android:id/summary,
	 * and an ImageView with ID @+android:id/icon.
	 */
	protected abstract int getHeaderLayoutResource();

}