text
stringlengths 2
1.04M
| meta
dict |
---|---|
/* doc in vfprintf.c */
/* This code created by modifying vsprintf.c so copyright inherited. */
/*
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "%W% (Berkeley) %G%";
#endif /* LIBC_SCCS and not lint */
#include <_ansi.h>
#include <reent.h>
#include <stdio.h>
#include <limits.h>
#ifdef _HAVE_STDC
#include <stdarg.h>
#else
#include <varargs.h>
#endif
int
vsnprintf (str, size, fmt, ap)
char *str;
size_t size;
char _CONST *fmt;
va_list ap;
{
int ret;
FILE f;
f._flags = __SWR | __SSTR;
f._bf._base = f._p = (unsigned char *) str;
f._bf._size = f._w = (size > 0 ? size - 1 : 0);
f._data = _REENT;
ret = vfprintf (&f, fmt, ap);
if (size > 0)
*f._p = 0;
return ret;
}
int
vsnprintf_r (ptr, str, size, fmt, ap)
struct _reent *ptr;
char *str;
size_t size;
char _CONST *fmt;
va_list ap;
{
int ret;
FILE f;
f._flags = __SWR | __SSTR;
f._bf._base = f._p = (unsigned char *) str;
f._bf._size = f._w = (size > 0 ? size - 1 : 0);
f._data = ptr;
ret = vfprintf (&f, fmt, ap);
if (size > 0)
*f._p = 0;
return ret;
}
| {
"content_hash": "c5a5ab2c4ffdcf6e77273bb5710a9ecb",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 71,
"avg_line_length": 25.88,
"alnum_prop": 0.6470891293147862,
"repo_name": "shaotuanchen/sunflower_exp",
"id": "5ca0ff27b5d2a5e23c892427157652e5a50e7908",
"size": "1941",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/source/newlib-1.9.0/newlib/libc/stdio/vsnprintf.c",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "459993"
},
{
"name": "Awk",
"bytes": "6562"
},
{
"name": "Batchfile",
"bytes": "9028"
},
{
"name": "C",
"bytes": "50326113"
},
{
"name": "C++",
"bytes": "2040239"
},
{
"name": "CSS",
"bytes": "2355"
},
{
"name": "Clarion",
"bytes": "2484"
},
{
"name": "Coq",
"bytes": "61440"
},
{
"name": "DIGITAL Command Language",
"bytes": "69150"
},
{
"name": "Emacs Lisp",
"bytes": "186910"
},
{
"name": "Fortran",
"bytes": "5364"
},
{
"name": "HTML",
"bytes": "2171356"
},
{
"name": "JavaScript",
"bytes": "27164"
},
{
"name": "Logos",
"bytes": "159114"
},
{
"name": "M",
"bytes": "109006"
},
{
"name": "M4",
"bytes": "100614"
},
{
"name": "Makefile",
"bytes": "5409865"
},
{
"name": "Mercury",
"bytes": "702"
},
{
"name": "Module Management System",
"bytes": "56956"
},
{
"name": "OCaml",
"bytes": "253115"
},
{
"name": "Objective-C",
"bytes": "57800"
},
{
"name": "Papyrus",
"bytes": "3298"
},
{
"name": "Perl",
"bytes": "70992"
},
{
"name": "Perl 6",
"bytes": "693"
},
{
"name": "PostScript",
"bytes": "3440120"
},
{
"name": "Python",
"bytes": "40729"
},
{
"name": "Redcode",
"bytes": "1140"
},
{
"name": "Roff",
"bytes": "3794721"
},
{
"name": "SAS",
"bytes": "56770"
},
{
"name": "SRecode Template",
"bytes": "540157"
},
{
"name": "Shell",
"bytes": "1560436"
},
{
"name": "Smalltalk",
"bytes": "10124"
},
{
"name": "Standard ML",
"bytes": "1212"
},
{
"name": "TeX",
"bytes": "385584"
},
{
"name": "WebAssembly",
"bytes": "52904"
},
{
"name": "Yacc",
"bytes": "510934"
}
],
"symlink_target": ""
} |
<?php
namespace PhpBinaryReader;
use PhpBinaryReader\Exception\InvalidDataException;
use PhpBinaryReader\Type\Bit;
use PhpBinaryReader\Type\Byte;
use PhpBinaryReader\Type\Int8;
use PhpBinaryReader\Type\Int16;
use PhpBinaryReader\Type\Int32;
use PhpBinaryReader\Type\String;
class BinaryReader
{
/**
* @var int
*/
private $machineByteOrder = Endian::ENDIAN_LITTLE;
/**
* @var resource
*/
private $inputHandle;
/**
* @var int
*/
private $currentBit;
/**
* @var mixed
*/
private $nextByte;
/**
* @var int
*/
private $position;
/**
* @var int
*/
private $eofPosition;
/**
* @var string
*/
private $endian;
/**
* @var \PhpBinaryReader\Type\Byte
*/
private $byteReader;
/**
* @var \PhpBinaryReader\Type\Bit
*/
private $bitReader;
/**
* @var \PhpBinaryReader\Type\String
*/
private $stringReader;
/**
* @var \PhpBinaryReader\Type\Int8
*/
private $int8Reader;
/**
* @var \PhpBinaryReader\Type\Int16
*/
private $int16Reader;
/**
* @var \PhpBinaryReader\Type\Int32
*/
private $int32Reader;
/**
* @param string|resource $input
* @param int|string $endian
* @throws \InvalidArgumentException
*/
public function __construct($input, $endian = Endian::ENDIAN_LITTLE)
{
if (!is_resource($input)) {
$this->setInputString($input);
} else {
$this->setInputHandle($input);
}
$this->eofPosition = fstat($this->getInputHandle())['size'];
$this->setEndian($endian);
$this->setNextByte(false);
$this->setCurrentBit(0);
$this->setPosition(0);
$this->bitReader = new Bit();
$this->stringReader = new String();
$this->byteReader = new Byte();
$this->int8Reader = new Int8();
$this->int16Reader = new Int16();
$this->int32Reader = new Int32();
}
/**
* @return bool
*/
public function isEof()
{
return $this->position >= $this->eofPosition;
}
/**
* @param int $length
* @return bool
*/
public function canReadBytes($length = 0)
{
return $this->position + $length <= $this->eofPosition;
}
/**
* @return void
*/
public function align()
{
$this->setCurrentBit(0);
$this->setNextByte(false);
}
/**
* @param int $count
* @return int
*/
public function readBits($count)
{
return $this->bitReader->readSigned($this, $count);
}
/**
* @param int $count
* @return int
*/
public function readUBits($count)
{
return $this->bitReader->read($this, $count);
}
/**
* @param int $count
* @return int
*/
public function readBytes($count)
{
return $this->byteReader->read($this, $count);
}
/**
* @return int
*/
public function readInt8()
{
return $this->int8Reader->readSigned($this);
}
/**
* @return int
*/
public function readUInt8()
{
return $this->int8Reader->read($this);
}
/**
* @return int
*/
public function readInt16()
{
return $this->int16Reader->readSigned($this);
}
/**
* @return string
*/
public function readUInt16()
{
return $this->int16Reader->read($this);
}
/**
* @return int
*/
public function readInt32()
{
return $this->int32Reader->readSigned($this);
}
/**
* @return int
*/
public function readUInt32()
{
return $this->int32Reader->read($this);
}
/**
* @param int $length
* @return string
*/
public function readString($length)
{
return $this->stringReader->read($this, $length);
}
/**
* @param int $length
* @return string
*/
public function readAlignedString($length)
{
return $this->stringReader->readAligned($this, $length);
}
/**
* @param int $machineByteOrder
* @return $this
*/
public function setMachineByteOrder($machineByteOrder)
{
$this->machineByteOrder = $machineByteOrder;
return $this;
}
/**
* @return int
*/
public function getMachineByteOrder()
{
return $this->machineByteOrder;
}
/**
* @param resource $inputHandle
* @return $this
*/
public function setInputHandle($inputHandle)
{
$this->inputHandle = $inputHandle;
return $this;
}
/**
* @return resource
*/
public function getInputHandle()
{
return $this->inputHandle;
}
/**
* @param string $inputString
* @return $this
*/
public function setInputString($inputString)
{
$handle = fopen('php://memory', 'br+');
fwrite($handle, $inputString);
rewind($handle);
$this->inputHandle = $handle;
return $this;
}
/**
* @return string
*/
public function getInputString()
{
$handle = $this->getInputHandle();
$str = stream_get_contents($handle);
rewind($handle);
return $str;
}
/**
* @param mixed $nextByte
* @return $this
*/
public function setNextByte($nextByte)
{
$this->nextByte = $nextByte;
return $this;
}
/**
* @return mixed
*/
public function getNextByte()
{
return $this->nextByte;
}
/**
* @param int $position
* @return $this
*/
public function setPosition($position)
{
$this->position = $position;
fseek($this->getInputHandle(), $position);
return $this;
}
/**
* @return int
*/
public function getPosition()
{
return $this->position;
}
/**
* @return int
*/
public function getEofPosition()
{
return $this->eofPosition;
}
/**
* @param string $endian
* @return $this
* @throws InvalidDataException
*/
public function setEndian($endian)
{
if ($endian == 'big' || $endian == Endian::ENDIAN_BIG) {
$this->endian = Endian::ENDIAN_BIG;
} elseif ($endian == 'little' || $endian == Endian::ENDIAN_LITTLE) {
$this->endian = Endian::ENDIAN_LITTLE;
} else {
throw new InvalidDataException('Endian must be set as big or little');
}
return $this;
}
/**
* @return string
*/
public function getEndian()
{
return $this->endian;
}
/**
* @param int $currentBit
* @return $this
*/
public function setCurrentBit($currentBit)
{
$this->currentBit = $currentBit;
return $this;
}
/**
* @return int
*/
public function getCurrentBit()
{
return $this->currentBit;
}
/**
* @return \PhpBinaryReader\Type\Bit
*/
public function getBitReader()
{
return $this->bitReader;
}
/**
* @return \PhpBinaryReader\Type\Byte
*/
public function getByteReader()
{
return $this->byteReader;
}
/**
* @return \PhpBinaryReader\Type\Int8
*/
public function getInt8Reader()
{
return $this->int8Reader;
}
/**
* @return \PhpBinaryReader\Type\Int16
*/
public function getInt16Reader()
{
return $this->int16Reader;
}
/**
* @return \PhpBinaryReader\Type\Int32
*/
public function getInt32Reader()
{
return $this->int32Reader;
}
/**
* @return \PhpBinaryReader\Type\String
*/
public function getStringReader()
{
return $this->stringReader;
}
/**
* Read a length of characters from the input handle, updating the
* internal position marker.
*
* @return string
*/
public function readFromHandle($length)
{
$this->position += $length;
return fread($this->inputHandle, $length);
}
}
| {
"content_hash": "e604cd47b1293cf54cb6e112cca96d43",
"timestamp": "",
"source": "github",
"line_count": 442,
"max_line_length": 82,
"avg_line_length": 18.78054298642534,
"alnum_prop": 0.5225876400433682,
"repo_name": "JanTvrdik/php-binary-reader",
"id": "8045b25c00d9ff42a76bbb434e92458dfdbe203e",
"size": "8301",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/BinaryReader.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "55521"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>posix::basic_stream_descriptor::native</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../posix__basic_stream_descriptor.html" title="posix::basic_stream_descriptor">
<link rel="prev" href="lowest_layer_type.html" title="posix::basic_stream_descriptor::lowest_layer_type">
<link rel="next" href="native_handle.html" title="posix::basic_stream_descriptor::native_handle">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="lowest_layer_type.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../posix__basic_stream_descriptor.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="native_handle.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.posix__basic_stream_descriptor.native"></a><a class="link" href="native.html" title="posix::basic_stream_descriptor::native">posix::basic_stream_descriptor::native</a>
</h4></div></div></div>
<p>
<span class="emphasis"><em>Inherited from posix::basic_descriptor.</em></span>
</p>
<p>
<a class="indexterm" name="idp164739712"></a>
(Deprecated: Use <code class="computeroutput"><span class="identifier">native_handle</span><span class="special">()</span></code>.) Get the native descriptor representation.
</p>
<pre class="programlisting"><span class="identifier">native_type</span> <span class="identifier">native</span><span class="special">();</span>
</pre>
<p>
This function may be used to obtain the underlying representation of the
descriptor. This is intended to allow access to native descriptor functionality
that is not otherwise provided.
</p>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="lowest_layer_type.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../posix__basic_stream_descriptor.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="native_handle.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "ee8ed04616a64172667771fbff35c555",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 369,
"avg_line_length": 63.372549019607845,
"alnum_prop": 0.6531559405940595,
"repo_name": "otgaard/zap",
"id": "d25398a3ec9d72d63184fdfab1e412ee7b222b32",
"size": "3232",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "third_party/asio/doc/asio/reference/posix__basic_stream_descriptor/native.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "98227"
},
{
"name": "C++",
"bytes": "908094"
},
{
"name": "CMake",
"bytes": "86343"
}
],
"symlink_target": ""
} |
#ifndef AliAnalysisTaskEmcalJetHMEC_H
#define AliAnalysisTaskEmcalJetHMEC_H
/**
* @class AliAnalysisTaskEmcalJetHMEC
* @brief Jet-hadron correlations analysis task for central Pb-Pb and pp
*
* %Analysis task for jet-hadron correlations in central Pb-Pb and pp.
* Includes the ability to weight entries by the efficiency, as well
* as utilize a jet energy scale correction in the form of a histogram.
*
* This code has been cross checked against the code used for the event
* plane dependent analysis (AliAnalysisTaskEmcalJetHadEPpid).
*
* @author Raymond Ehlers <[email protected]>, Yale University
* @author Megan Connors, Georgia State
* @date 1 Jan 2017
*/
class TH1;
class TH2;
class TH3;
class THnSparse;
class AliEmcalJet;
class AliEventPoolManager;
class AliTLorentzVector;
#include "AliAnalysisTaskEmcalJet.h"
class AliAnalysisTaskEmcalJetHMEC : public AliAnalysisTaskEmcalJet {
public:
/**
* @enum jetBias_t
* @brief Default value used to disable constituent bias
*/
enum jetBias_t {
kDisableBias = 10000 //!<! Arbitrarily large value which can be used to disable the constituent bias. Can be used for either tracks or clusters.
};
AliAnalysisTaskEmcalJetHMEC();
AliAnalysisTaskEmcalJetHMEC(const char *name);
virtual ~AliAnalysisTaskEmcalJetHMEC() {}
Double_t GetTrackBias() const { return fTrackBias; }
Double_t GetClusterBias() const { return fClusterBias; }
// Jet bias - setters
/// Require a track with pt > b in jet
virtual void SetTrackBias(Double_t b) { fTrackBias = b; }
/// Require a cluster with pt > b in jet
virtual void SetClusterBias(Double_t b) { fClusterBias = b; }
// Event trigger/mixed selection - setters
/// Set the trigger event trigger selection
virtual void SetTriggerType(UInt_t te) { fTriggerType = te; }
/// Set the mixed event trigger selection
virtual void SetMixedEventTriggerType(UInt_t me) { fMixingEventType = me; }
/// True if the task should be disabled for the fast parititon
void SetDisableFastPartition(Bool_t b = kTRUE) { fDisableFastPartition = b; }
Bool_t GetDisableFastPartition() const { return fDisableFastPartition; }
// Mixed events
virtual void SetEventMixing(Bool_t enable) { fDoEventMixing = enable;}
virtual void SetNumberOfMixingTracks(Int_t tracks) { fNMixingTracks = tracks; }
virtual void SetMinNTracksForMixedEvents(Int_t nmt) { fMinNTracksMixedEvents = nmt; }
virtual void SetMinNEventsForMixedEvents(Int_t nme) { fMinNEventsMixedEvents = nme; }
virtual void SetNCentBinsMixedEvent(Bool_t centbins) { fNCentBinsMixedEvent = centbins; }
// Switch to cut out some unneeded sparse axis
void SetDoLessSparseAxes(Bool_t dlsa) { fDoLessSparseAxes = dlsa; }
void SetDoWiderTrackBin(Bool_t wtrbin) { fDoWiderTrackBin = wtrbin; }
// set efficiency correction
void SetDoEffCorr(Int_t effcorr) { fDoEffCorrection = effcorr; }
// Setup JES correction
void SetJESCorrectionHist(TH2D * hist) { fJESCorrectionHist = hist; }
void SetNoMixedEventJESCorrection(Bool_t b) { fNoMixedEventJESCorrection = b; }
Bool_t RetrieveAndInitializeJESCorrectionHist(TString filename, TString histName, Double_t trackBias = AliAnalysisTaskEmcalJetHMEC::kDisableBias, Double_t clusterBias = AliAnalysisTaskEmcalJetHMEC::kDisableBias);
// Corrections
// Public so that it can be tested externally
Double_t EffCorrection(Double_t trkETA, Double_t trkPT, AliAnalysisTaskEmcal::BeamType beamType) const;
virtual void UserCreateOutputObjects();
virtual void Terminate(Option_t *);
// AddTask
static AliAnalysisTaskEmcalJetHMEC * AddTaskEmcalJetHMEC(
const char *nTracks = "usedefault",
const char *nCaloClusters = "usedefault",
// Jet options
const Double_t trackBias = 5,
const Double_t clusterBias = 5,
const Double_t minJetArea = 0.4,
// Mixed event options
const Int_t nTracksMixedEvent = 0, // Additionally acts as a switch for enabling mixed events
const Int_t minNTracksMixedEvent = 5000,
const Int_t minNEventsMixedEvent = 5,
const UInt_t nCentBinsMixedEvent = 10,
// Triggers
UInt_t trigEvent = AliVEvent::kAny,
UInt_t mixEvent = AliVEvent::kAny,
// Options
const Double_t trackEta = 0.9,
const Bool_t lessSparseAxes = 0,
const Bool_t widerTrackBin = 0,
// Corrections
const Int_t doEffCorrSW = 0,
const Bool_t JESCorrection = kFALSE,
const char * JESCorrectionFilename = "alien:///alice/cern.ch/user/r/rehlersi/JESCorrection.root",
const char * JESCorrectionHistName = "JESCorrection",
const char *suffix = "biased"
);
protected:
// NOTE: This is not an ideal way to resolve the size of histogram initialization.
// Will be resolved when we move fully to the THnSparse
/**
* @enum binArrayLimits_t
* @brief Define the number of elements in various arrays
*/
enum binArrayLimits_t {
kMaxJetPtBins = 5, //!<! Number of elements in jet pt binned arrays
kMaxTrackPtBins = 7, //!<! Number of elements in track pt binned arrays
kMaxCentralityBins = 5, //!<! Number of elements in centrality binned arrays
kMixedEventMulitplictyBins = 8, //!<! Number of elements in mixed event multiplicity binned arrays
kMaxEtaBins = 3 //!<! Number of elements in eta binned arrays
};
// EMCal framework functions
void ExecOnce();
Bool_t Run();
// Reduce event mixing memory usage
TObjArray* CloneAndReduceTrackList();
// Histogram helper functions
virtual THnSparse* NewTHnSparseF(const char* name, UInt_t entries);
virtual void GetDimParams(Int_t iEntry,TString &label, Int_t &nbins, Double_t &xmin, Double_t &xmax);
// Binning helper functions
Int_t GetEtaBin(Double_t eta) const;
Int_t GetTrackPtBin(Double_t pt) const;
Int_t GetJetPtBin(Double_t pt) const;
// Helper functions
void InitializeArraysToZero();
void GetDeltaEtaDeltaPhiDeltaR(AliTLorentzVector & particleOne, AliVParticle * particleTwo, Double_t & deltaEta, Double_t & deltaPhi, Double_t & deltaR);
// Test for biased jet
Bool_t BiasedJet(AliEmcalJet * jet);
// Corrections
Double_t EffCorrection(Double_t trkETA, Double_t trkPT) const;
// Fill methods which allow for the JES correction
void FillHist(TH1 * hist, Double_t fillValue, Double_t weight = 1.0, Bool_t noCorrection = kFALSE);
void FillHist(THnSparse * hist, Double_t *fillValue, Double_t weight = 1.0, Bool_t noCorrection = kFALSE);
void AccessSetOfYBinValues(TH2D * hist, Int_t xBin, std::vector <Double_t> & yBinsContent, Double_t scaleFactor = -1.0);
// Jet bias
Double_t fTrackBias; ///< Jet track bias
Double_t fClusterBias; ///< Jet cluster bias
// Event Mixing
Bool_t fDoEventMixing; ///< flag to do evt mixing
Int_t fNMixingTracks; ///< size of track buffer for event mixing
Int_t fMinNTracksMixedEvents; ///< threshold to use event pool # tracks
Int_t fMinNEventsMixedEvents; ///< threshold to use event pool # events
UInt_t fNCentBinsMixedEvent; ///< N cent bins for the event mixing pool
AliEventPoolManager *fPoolMgr; //!<! Event pool manager
// Event selection types
UInt_t fTriggerType; ///< Event selection for jets (ie triggered events).
UInt_t fMixingEventType; ///< Event selection for mixed events
Bool_t fDisableFastPartition; ///< True if task should be disabled for the fast partition, where the EMCal is not included.
// Efficiency correction
Int_t fDoEffCorrection; ///< Control the efficiency correction. See EffCorrection() for meaning of values.
// JES correction
Bool_t fNoMixedEventJESCorrection; ///< True if the jet energy scale correction should be applied to mixed event histograms
TH2D *fJESCorrectionHist; ///< Histogram containing the jet energy scale correction
// Histogram binning variables
Bool_t fDoLessSparseAxes; ///< True if there should be fewer THnSparse axes
Bool_t fDoWiderTrackBin; ///< True if the track pt bins in the THnSparse should be wider
// TODO: Consider moving to THistManager
TH1 *fHistTrackPt; //!<! Track pt spectrum
TH2 *fHistJetEtaPhi; //!<! Jet eta-phi distribution
TH2 *fHistTrackEtaPhi[7]; //!<! Track eta-phi distribution (the array corresponds to track pt)
TH2 *fHistJetHEtaPhi; //!<! Eta-phi distribution of jets which are in jet-hadron correlations
TH1 *fHistJetPt[6]; //!<! Jet pt spectrum (the array corresponds to centrality bins)
TH1 *fHistJetPtBias[6]; //!<! Jet pt spectrum of jets which meet the constituent bias criteria (the array corresponds to centrality bins)
TH2 *fHistJetH[6][5][3]; //!<! Jet-hadron correlations (the arrays correspond to centrality, jet pt bins, and eta bins)
TH2 *fHistJetHBias[6][5][3]; //!<! Jet-hadron correlations of jets which meet the constituent bias criteria (the arrays correspond to centrality, jet pt bins, and eta bins)
TH3 *fHistJHPsi; //!<! Psi angle distribution
THnSparse *fhnMixedEvents; //!<! Mixed events THnSparse
THnSparse *fhnJH; //!<! JetH THnSparse
// Pb-Pb Efficiency correction coefficients
static Double_t p0_10SG[17]; ///< 0-10% centrality semi-good runs
static Double_t p10_30SG[17]; ///< 10-30% centrality semi-good runs
static Double_t p30_50SG[17]; ///< 30-50% centrality semi-good runs
static Double_t p50_90SG[17]; ///< 50-90% centrality semi-good runs
// Good Runs
static Double_t p0_10G[17]; ///< 0-10% centrality good runs
static Double_t p10_30G[17]; ///< 10-30% centrality good runs
static Double_t p30_50G[17]; ///< 30-50% centrality good runs
static Double_t p50_90G[17]; ///< 50-90% centrality good runs
private:
AliAnalysisTaskEmcalJetHMEC(const AliAnalysisTaskEmcalJetHMEC&); // not implemented
AliAnalysisTaskEmcalJetHMEC& operator=(const AliAnalysisTaskEmcalJetHMEC&); // not implemented
/// \cond CLASSIMP
ClassDef(AliAnalysisTaskEmcalJetHMEC, 12);
/// \endcond
};
#endif
| {
"content_hash": "34ca5ec1cb325368d163943a2a6a690b",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 231,
"avg_line_length": 54.424528301886795,
"alnum_prop": 0.6244583116658,
"repo_name": "aaniin/AliPhysics",
"id": "2e7bce316f7f6ba78b0d70194c09697b25b69379",
"size": "11538",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskEmcalJetHMEC.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Awk",
"bytes": "752"
},
{
"name": "C",
"bytes": "51817802"
},
{
"name": "C++",
"bytes": "91964271"
},
{
"name": "CMake",
"bytes": "521890"
},
{
"name": "CSS",
"bytes": "5189"
},
{
"name": "Fortran",
"bytes": "134275"
},
{
"name": "HTML",
"bytes": "7245"
},
{
"name": "JavaScript",
"bytes": "3536"
},
{
"name": "Makefile",
"bytes": "25080"
},
{
"name": "Objective-C",
"bytes": "223534"
},
{
"name": "Perl",
"bytes": "16782"
},
{
"name": "Python",
"bytes": "674955"
},
{
"name": "Shell",
"bytes": "940388"
},
{
"name": "TeX",
"bytes": "384325"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_02) on Tue Apr 29 11:29:41 CEST 2014 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>ResolutionResult (Gradle API 1.12)</title>
<meta name="date" content="2014-04-29">
<link rel="stylesheet" type="text/css" href="../../../../../javadoc.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="ResolutionResult (Gradle API 1.12)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ResolutionResult.html" target="_top">Frames</a></li>
<li><a href="ResolutionResult.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.gradle.api.artifacts.result</div>
<h2 title="Interface ResolutionResult" class="title">Interface ResolutionResult</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre><a href="../../../../../org/gradle/api/Incubating.html" title="annotation in org.gradle.api">@Incubating</a>
public interface <span class="strong">ResolutionResult</span></pre>
<div class="block">Contains the information about the result of dependency resolution. You can use this type to determine all the component instances that are included
in the resolved dependency graph, and the dependencies between them.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#allComponents(org.gradle.api.Action)">allComponents</a></strong>(<a href="../../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a><? super <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a>> action)</code>
<div class="block">Applies given action for each component.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#allComponents(groovy.lang.Closure)">allComponents</a></strong>(<a href="http://groovy.codehaus.org/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a> closure)</code>
<div class="block">Applies given closure for each component.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#allDependencies(org.gradle.api.Action)">allDependencies</a></strong>(<a href="../../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a><? super <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result">DependencyResult</a>> action)</code>
<div class="block">Applies given action for each dependency.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#allDependencies(groovy.lang.Closure)">allDependencies</a></strong>(<a href="http://groovy.codehaus.org/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a> closure)</code>
<div class="block">Applies given closure for each dependency.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#getAllComponents()">getAllComponents</a></strong>()</code>
<div class="block">Retrieves all instances of <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><code>ResolvedComponentResult</code></a> from the graph,
e.g.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><? extends <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result">DependencyResult</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#getAllDependencies()">getAllDependencies</a></strong>()</code>
<div class="block">Retrieves all dependencies, including unresolved dependencies.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a></code></td>
<td class="colLast"><code><strong><a href="../../../../../org/gradle/api/artifacts/result/ResolutionResult.html#getRoot()">getRoot</a></strong>()</code>
<div class="block">Gives access to the root of resolved dependency graph.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getRoot()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getRoot</h4>
<pre><a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a> getRoot()</pre>
<div class="block">Gives access to the root of resolved dependency graph.
You can walk the graph recursively from the root to obtain information about resolved dependencies.
For example, Gradle's built-in 'dependencies' task uses this to render the dependency tree.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>the root node of the resolved dependency graph</dd></dl>
</li>
</ul>
<a name="getAllDependencies()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getAllDependencies</h4>
<pre><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><? extends <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result">DependencyResult</a>> getAllDependencies()</pre>
<div class="block">Retrieves all dependencies, including unresolved dependencies.
Resolved dependencies are represented by instances of <a href="../../../../../org/gradle/api/artifacts/result/ResolvedDependencyResult.html" title="interface in org.gradle.api.artifacts.result"><code>ResolvedDependencyResult</code></a>,
unresolved dependencies by <a href="../../../../../org/gradle/api/artifacts/result/UnresolvedDependencyResult.html" title="interface in org.gradle.api.artifacts.result"><code>UnresolvedDependencyResult</code></a>.
In dependency graph terminology, this method returns the edges of the graph.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>all dependencies, including unresolved dependencies.</dd></dl>
</li>
</ul>
<a name="allDependencies(org.gradle.api.Action)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>allDependencies</h4>
<pre>void allDependencies(<a href="../../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a><? super <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result">DependencyResult</a>> action)</pre>
<div class="block">Applies given action for each dependency.
An instance of <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result"><code>DependencyResult</code></a> is passed as parameter to the action.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>action</code> - - action that is applied for each dependency</dd></dl>
</li>
</ul>
<a name="allDependencies(groovy.lang.Closure)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>allDependencies</h4>
<pre>void allDependencies(<a href="http://groovy.codehaus.org/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a> closure)</pre>
<div class="block">Applies given closure for each dependency.
An instance of <a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result"><code>DependencyResult</code></a> is passed as parameter to the closure.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>closure</code> - - closure that is applied for each dependency</dd></dl>
</li>
</ul>
<a name="getAllComponents()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getAllComponents</h4>
<pre><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a>> getAllComponents()</pre>
<div class="block">Retrieves all instances of <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><code>ResolvedComponentResult</code></a> from the graph,
e.g. all nodes of the dependency graph.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>all nodes of the dependency graph.</dd></dl>
</li>
</ul>
<a name="allComponents(org.gradle.api.Action)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>allComponents</h4>
<pre>void allComponents(<a href="../../../../../org/gradle/api/Action.html" title="interface in org.gradle.api">Action</a><? super <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result">ResolvedComponentResult</a>> action)</pre>
<div class="block">Applies given action for each component.
An instance of <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><code>ResolvedComponentResult</code></a> is passed as parameter to the action.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>action</code> - - action that is applied for each component</dd></dl>
</li>
</ul>
<a name="allComponents(groovy.lang.Closure)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>allComponents</h4>
<pre>void allComponents(<a href="http://groovy.codehaus.org/gapi/groovy/lang/Closure.html?is-external=true" title="class or interface in groovy.lang">Closure</a> closure)</pre>
<div class="block">Applies given closure for each component.
An instance of <a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><code>ResolvedComponentResult</code></a> is passed as parameter to the closure.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>closure</code> - - closure that is applied for each component</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../org/gradle/api/artifacts/result/DependencyResult.html" title="interface in org.gradle.api.artifacts.result"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/gradle/api/artifacts/result/ResolvedComponentResult.html" title="interface in org.gradle.api.artifacts.result"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/gradle/api/artifacts/result/ResolutionResult.html" target="_top">Frames</a></li>
<li><a href="ResolutionResult.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "96e3b705becf6641a186acdf7599f2fb",
"timestamp": "",
"source": "github",
"line_count": 326,
"max_line_length": 477,
"avg_line_length": 52.06748466257669,
"alnum_prop": 0.6802757158006363,
"repo_name": "Pushjet/Pushjet-Android",
"id": "ed3bcffb16417e3dbce32bf7ef9c1a11c8019fc6",
"size": "16974",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/wrapper/dists/gradle-1.12-all/4ff8jj5a73a7zgj5nnzv1ubq0/gradle-1.12/docs/javadoc/org/gradle/api/artifacts/result/ResolutionResult.html",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "92331"
}
],
"symlink_target": ""
} |
var _callBack;
function locate(pCallBack) {
_callBack = pCallBack;
var geolocator = navigator.geolocation;
if (geolocator) {
var geoOptions = {
maximumAge: 600000
};
// Request a position whose age is not greater than 10 minutes old.
geolocator.getCurrentPosition(_success, _error, geoOptions);
} else {
var message = {
message: 'Geolocation is not supported.'
};
_callBack.error(message);
}
}
// Location successfully found.
function _success(position) {
_callBack.success(position);
}
// Error retrieving location.
function _error(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
error.message = 'User denied the request for Geolocation.';
break;
case error.POSITION_UNAVAILABLE:
error.message = 'Location information is unavailable.';
break;
case error.TIMEOUT:
error.message = 'The request to get user location timed out.';
break;
case error.UNKNOWN_ERROR:
error.message = 'An unknown error occurred.';
break;
}
_callBack.error(error);
}
export default {
locate:locate
};
| {
"content_hash": "98c8122fe07e6bfbb6b33cdb359db3cc",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 71,
"avg_line_length": 22.770833333333332,
"alnum_prop": 0.6806953339432754,
"repo_name": "smcgov/SMC-Connect",
"id": "74c9716931e122a6384a1033ee5855e15740a005",
"size": "1180",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/javascript/app/util/geolocation/geolocator.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "793"
},
{
"name": "HTML",
"bytes": "9160"
},
{
"name": "Haml",
"bytes": "45947"
},
{
"name": "JavaScript",
"bytes": "74667"
},
{
"name": "Procfile",
"bytes": "39"
},
{
"name": "Ruby",
"bytes": "127113"
},
{
"name": "SCSS",
"bytes": "176699"
},
{
"name": "Shell",
"bytes": "1763"
}
],
"symlink_target": ""
} |
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.permissions;
import org.chromium.components.omnibox.AutocompleteSchemeClassifier;
/**
* Provides embedder-level information to {@link BluetoothScanningPermissionDialog}.
*/
public interface BluetoothScanningPromptAndroidDelegate {
/**
* Creates a new {@link AutoCompleteSchemeClassifier}. After use
* {@link AutoCompleteSchemeClassifier#destroy()} must be called to delete the native object.
*/
AutocompleteSchemeClassifier createAutocompleteSchemeClassifier();
}
| {
"content_hash": "05005856e1c337b1d98b3765c4021350",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 97,
"avg_line_length": 38.333333333333336,
"alnum_prop": 0.7782608695652173,
"repo_name": "ric2b/Vivaldi-browser",
"id": "3e7397f1642cfa987425f4c450499e0f5692acb7",
"size": "690",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chromium/components/permissions/android/java/src/org/chromium/components/permissions/BluetoothScanningPromptAndroidDelegate.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------------
// <copyright file="IKeyInfoHelperProvider.cs" company="NMemory Team">
// Copyright (C) 2012-2014 NMemory Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// </copyright>
// ----------------------------------------------------------------------------------
namespace NMemory.Indexes
{
public interface IKeyInfoHelperProvider
{
IKeyInfoHelper KeyInfoHelper { get; }
}
}
| {
"content_hash": "43ef39b264305a9c7fc8760c4ec615b6",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 86,
"avg_line_length": 51.70967741935484,
"alnum_prop": 0.6294447910168434,
"repo_name": "wertzui/nmemory",
"id": "84539d596bce4cbd980043845a9f7817da21333e",
"size": "1605",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Main/Source/NMemory/Indexes/IKeyInfoHelperProvider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "508"
},
{
"name": "C#",
"bytes": "1024126"
}
],
"symlink_target": ""
} |
Orwell::Application.config.session_store :cookie_store, key: '_orwell_session'
| {
"content_hash": "63868ce717d09a33877d8a11ebbee120",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 78,
"avg_line_length": 79,
"alnum_prop": 0.7848101265822784,
"repo_name": "dchilot/server-proxy-web",
"id": "2e0c34fdcc70963c79e5dfadcc4c53e25d4501c2",
"size": "140",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "config/initializers/session_store.rb",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "724"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "JavaScript",
"bytes": "2096"
},
{
"name": "Ruby",
"bytes": "19447"
}
],
"symlink_target": ""
} |
const gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename'),
webpackStream = require('webpack-stream'),
webpack = require('webpack')
gulp.task('sass', () =>
gulp.src('./src/styles/global.scss')
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('./app'))
)
gulp.task('webpack', () =>
gulp.src('./src/js/app.jsx')
.pipe(webpackStream(require('./webpack.config.js'), webpack))
.on('error', function handleError() {
this.emit('end'); // Recover from errors
})
.pipe(gulp.dest('./app'))
)
gulp.task('watch', () => {
gulp.watch('./src/js/**/*.js*', ['webpack'])
gulp.watch('./src/styles/**.scss', ['sass'])
})
gulp.task('dev',['sass','webpack','watch'])
| {
"content_hash": "9b677aa675a739fe31e26f378ada82f7",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 73,
"avg_line_length": 29.678571428571427,
"alnum_prop": 0.5691937424789411,
"repo_name": "cesargdm/bcrud",
"id": "762a6eff7701225fc6cb62171c7370ab9f6ecd71",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gulpfile.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9329"
},
{
"name": "HTML",
"bytes": "237"
},
{
"name": "JavaScript",
"bytes": "20309"
}
],
"symlink_target": ""
} |
namespace NQuery.Tests
{
public class ConversionTests
{
private static Conversion ClassifyConversion(Type sourceType, Type targetType)
{
var semanticModel = Compilation.Empty.GetSemanticModel();
var conversion = semanticModel.ClassifyConversion(sourceType, targetType);
return conversion;
}
private static void HasConversion(Type sourceType, Type targetType, bool isImplicit, bool viaMethod)
{
var conversion = ClassifyConversion(sourceType, targetType);
var isExplicit = !isImplicit;
var expectedMethodCount = viaMethod ? 1 : 0;
Assert.True(conversion.Exists);
Assert.Equal(isImplicit, conversion.IsImplicit);
Assert.Equal(isExplicit, conversion.IsExplicit);
Assert.False(conversion.IsIdentity);
Assert.False(conversion.IsBoxing);
Assert.False(conversion.IsUnboxing);
Assert.False(conversion.IsReference);
Assert.Equal(expectedMethodCount, conversion.ConversionMethods.Length);
}
private static void AssertIdentityConversion(Type type)
{
var conversion = ClassifyConversion(type, type);
Assert.True(conversion.Exists);
Assert.True(conversion.IsIdentity);
Assert.True(conversion.IsImplicit);
Assert.False(conversion.IsExplicit);
Assert.False(conversion.IsBoxing);
Assert.False(conversion.IsUnboxing);
Assert.False(conversion.IsReference);
Assert.Empty(conversion.ConversionMethods);
}
private static void AssertHasImplicitIntrinsicConversion(Type sourceType, Type targetType)
{
HasConversion(sourceType, targetType, true, false);
}
private static void AssertHasExplicitIntrinsicConversion(Type sourceType, Type targetType)
{
HasConversion(sourceType, targetType, false, false);
}
private static void AssertHasImplicitConversionViaMethod(Type sourceType, Type targetType)
{
HasConversion(sourceType, targetType, true, true);
}
private static void AssertHasExplicitConversionViaMethod(Type sourceType, Type targetType)
{
HasConversion(sourceType, targetType, false, true);
}
[Fact]
public void Conversion_ClassifiesIdentityConversionsCorrectly()
{
// Known types
AssertIdentityConversion(typeof(sbyte));
AssertIdentityConversion(typeof(byte));
AssertIdentityConversion(typeof(short));
AssertIdentityConversion(typeof(ushort));
AssertIdentityConversion(typeof(int));
AssertIdentityConversion(typeof(uint));
AssertIdentityConversion(typeof(long));
AssertIdentityConversion(typeof(ulong));
AssertIdentityConversion(typeof(char));
AssertIdentityConversion(typeof(float));
AssertIdentityConversion(typeof(double));
AssertIdentityConversion(typeof(bool));
AssertIdentityConversion(typeof(string));
AssertIdentityConversion(typeof(object));
// Other
AssertIdentityConversion(typeof(decimal));
}
[Fact]
public void Conversion_ClassifiesImplicitIntrinsicConversionsCorrectly()
{
AssertHasImplicitIntrinsicConversion(typeof(sbyte), typeof(short));
AssertHasImplicitIntrinsicConversion(typeof(sbyte), typeof(int));
AssertHasImplicitIntrinsicConversion(typeof(sbyte), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(sbyte), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(sbyte), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(short));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(ushort));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(int));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(uint));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(ulong));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(byte), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(short), typeof(int));
AssertHasImplicitIntrinsicConversion(typeof(short), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(short), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(short), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(int));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(uint));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(ulong));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(ushort), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(int), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(int), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(int), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(uint), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(uint), typeof(ulong));
AssertHasImplicitIntrinsicConversion(typeof(uint), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(uint), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(long), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(long), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(ulong), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(ulong), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(ushort));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(int));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(uint));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(long));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(ulong));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(float));
AssertHasImplicitIntrinsicConversion(typeof(char), typeof(double));
AssertHasImplicitIntrinsicConversion(typeof(float), typeof(double));
}
[Fact]
public void Conversion_ClassifiesExplicitIntrinsicConversionsCorrectly()
{
AssertHasExplicitIntrinsicConversion(typeof(sbyte), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(sbyte), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(sbyte), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(sbyte), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(sbyte), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(byte), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(byte), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(short), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(ushort), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(ushort), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(ushort), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(ushort), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(int), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(int));
AssertHasExplicitIntrinsicConversion(typeof(uint), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(int));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(long), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(int));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(long));
AssertHasExplicitIntrinsicConversion(typeof(ulong), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(char), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(char), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(char), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(int));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(long));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(float), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(sbyte));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(byte));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(short));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(ushort));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(int));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(uint));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(long));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(ulong));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(char));
AssertHasExplicitIntrinsicConversion(typeof(double), typeof(float));
}
[Fact]
public void Conversion_ClassifiesImplicitDecimalConversionsCorrectly()
{
AssertHasImplicitConversionViaMethod(typeof(sbyte), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(byte), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(short), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(ushort), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(int), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(uint), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(long), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(ulong), typeof(decimal));
AssertHasImplicitConversionViaMethod(typeof(char), typeof(decimal));
}
[Fact]
public void Conversion_ClassifiesExplicitDecimalConversionsCorrectly()
{
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(sbyte));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(byte));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(short));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(ushort));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(int));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(uint));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(long));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(ulong));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(char));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(float));
AssertHasExplicitConversionViaMethod(typeof(decimal), typeof(double));
AssertHasExplicitConversionViaMethod(typeof(float), typeof(decimal));
AssertHasExplicitConversionViaMethod(typeof(double), typeof(decimal));
}
[Fact]
public void Conversion_ClassifiesImplicitConversionViaMethodCorrectly()
{
AssertHasImplicitConversionViaMethod(typeof(DateTime), typeof(DateTimeOffset));
}
[Fact]
public void Conversion_ClassifiesExplicitConversionViaMethodCorrectly()
{
AssertHasExplicitConversionViaMethod(typeof(int), typeof(IntPtr));
}
[Fact]
public void Conversion_ClassifiesBoxingCorrectly()
{
var conversion = ClassifyConversion(typeof(int), typeof(object));
Assert.True(conversion.Exists);
Assert.True(conversion.IsImplicit);
Assert.False(conversion.IsExplicit);
Assert.False(conversion.IsIdentity);
Assert.True(conversion.IsBoxing);
Assert.False(conversion.IsUnboxing);
Assert.False(conversion.IsReference);
Assert.Empty(conversion.ConversionMethods);
}
[Fact]
public void Conversion_ClassifiesUnboxingCorrectly()
{
var conversion = ClassifyConversion(typeof(object), typeof(int));
Assert.True(conversion.Exists);
Assert.False(conversion.IsImplicit);
Assert.True(conversion.IsExplicit);
Assert.False(conversion.IsIdentity);
Assert.False(conversion.IsBoxing);
Assert.True(conversion.IsUnboxing);
Assert.False(conversion.IsReference);
Assert.Empty(conversion.ConversionMethods);
}
[Fact]
public void Conversion_ClassifiesUpCastCorrectly()
{
var conversion = ClassifyConversion(typeof(string), typeof(object));
Assert.True(conversion.Exists);
Assert.True(conversion.IsImplicit);
Assert.False(conversion.IsExplicit);
Assert.False(conversion.IsIdentity);
Assert.False(conversion.IsBoxing);
Assert.False(conversion.IsUnboxing);
Assert.True(conversion.IsReference);
Assert.Empty(conversion.ConversionMethods);
}
[Fact]
public void Conversion_ClassifiesDownCastCorrectly()
{
var conversion = ClassifyConversion(typeof(object), typeof(string));
Assert.True(conversion.Exists);
Assert.False(conversion.IsImplicit);
Assert.True(conversion.IsExplicit);
Assert.False(conversion.IsIdentity);
Assert.False(conversion.IsBoxing);
Assert.False(conversion.IsUnboxing);
Assert.True(conversion.IsReference);
Assert.Empty(conversion.ConversionMethods);
}
}
} | {
"content_hash": "d87b3b6aa8b1851a458ce6c81a63c054",
"timestamp": "",
"source": "github",
"line_count": 329,
"max_line_length": 108,
"avg_line_length": 51.7112462006079,
"alnum_prop": 0.6887674131546464,
"repo_name": "terrajobst/nquery-vnext",
"id": "98bfcdc3ed4ccff8292d3a3b37d1019e1fd34bcd",
"size": "17015",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/NQuery.Tests/ConversionTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "375"
},
{
"name": "C#",
"bytes": "2487099"
}
],
"symlink_target": ""
} |
using System.Linq;
using System.Runtime.Remoting.Channels;
using Capsicum.Exceptions;
using NUnit.Framework;
namespace Capsicum.Test {
[TestFixture]
public class EntityTests {
/* Initial State Tests */
[TestFixture]
public class InitialState {
private Entity e;
[SetUp]
public void Setup() => e = new Entity();
[Test]
public void ThrowsWhenAttemptingToRetrieveUnregisteredComponent() {
Assert.Throws<ComponentNotRegisteredException>(() => e.GetComponent<FakeComponent>());
}
[Test]
public void NoComponentsWhenNoComponentsRegistered()
{
Assert.That(!e.GetComponents().Any());
}
}
[TestFixture]
public class Events {
private Entity e;
[SetUp]
public void Setup() => e = new Entity();
[Test]
public void DispatchesOnComponentAdded() {
var dispatched = 0;
e.OnComponentAdded += (sender, value) => {
dispatched++;
Assert.That(value.Component is FakeComponent);
Assert.That(value.Entity == e);
};
e.OnComponentRemoved += (o, _) => Assert.Fail();
e.OnComponentReplaced += (o, _) => Assert.Fail();
e.AddComponent(new FakeComponent());
Assert.AreEqual(1, dispatched);
}
[Test]
public void DispatchesOnComponentRemoved() {
var dispatched = 0;
e.AddComponent(new FakeComponent());
e.OnComponentRemoved += (sender, value) => {
dispatched++;
Assert.That(value.Component is FakeComponent);
Assert.That(value.Entity == e);
};
e.OnComponentAdded += (o, _) => Assert.Fail();
e.OnComponentReplaced += (o, _) => Assert.Fail();
e.RemoveComponent<FakeComponent>();
Assert.AreEqual(1, dispatched);
}
[Test]
public void DispatchesOnComponentReplaced() {
var dispatched = 0;
var component = new FakeComponent();
e.AddComponent(component);
e.OnComponentReplaced += (sender, value) => {
dispatched++;
Assert.That(value.NewComponent == component);
Assert.That(value.PreviousComponent == component);
};
e.OnComponentAdded += (o, _) => Assert.Fail();
e.OnComponentRemoved += (o, _) => Assert.Fail();
e.ReplaceComponent(component);
Assert.AreEqual(1, dispatched);
}
[Test]
public void DispatchesOnComponentReplaced_PrevAndNewValues()
{
var dispatched = 0;
var component = new FakeComponent();
var componentNew = new FakeComponent();
e.AddComponent(component);
e.OnComponentReplaced += (sender, value) => {
dispatched++;
Assert.That(value.NewComponent == componentNew);
Assert.That(value.PreviousComponent == component);
};
e.OnComponentAdded += (o, _) => Assert.Fail();
e.OnComponentRemoved += (o, _) => Assert.Fail();
e.ReplaceComponent(componentNew);
Assert.AreEqual(1, dispatched);
}
[Test]
public void ThrowsExceptionWhenReplacingUnaddedComponent() {
Assert.Throws<ComponentNotRegisteredException>(() => e.ReplaceComponent(new FakeComponent()));
}
}
}
} | {
"content_hash": "85f7db2f1c61dbd14a040cff3f7055f9",
"timestamp": "",
"source": "github",
"line_count": 118,
"max_line_length": 110,
"avg_line_length": 33.059322033898304,
"alnum_prop": 0.4991027941553448,
"repo_name": "LambdaSix/Capsicum",
"id": "60d4414aa10040b0269ea7a9ae02d8d57ebd719b",
"size": "3903",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Capsicum.Test/EntityTests.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "45890"
}
],
"symlink_target": ""
} |
/**
* My solution to problem 9 of Project Euler.
*
* @author Joe Carnahan ([email protected])
*/
object _009 {
/**
* Tests if the given triple of numbers is a
* Pythagorean triple.
*
* @param a
* first number to test
* @param b
* second number to test
* @param c
* third number to test
* @return <code>true</code> if and only if (a*a) + (b*b) = (c*c)
*/
def isTriple(a: Int, b: Int, c: Int): Boolean =
((a * a) + (b * b)) == (c * c)
/**
* Searches for a Pythagorean triplet that sums to the given value.
* <p>
* Starts with <code>a = 1</code>, <code>b = 2</code>, and
* <code>c = value - (a + b)</code>. Then, and it increments
* <code>a</code> until it reaches <code>b</code>. At that point, it
* increments <code>b</code> and starts over again with <code>a = 1</code>.
*
* @param value
* the number to which the three numbers in the Pythagorean
* triple should sum
* @return a list of three integers consisting of a Pythagorean
* triple that sums to <code>value</code>, or an empty list if
* no Pythagorean triple sums to <code>value</code>
*/
def getPythagoreanTriplet(value: Long): List[Int] = {
def sum = value.toInt
def search(a: Int, b: Int, c: Int): List[Int] =
if (isTriple(a, b, c))
List(a, b, c)
else if ((a >= (b - 1)) || (a >= c)) {
val newB = b + 1
if (newB > (sum / 2))
List[Int]() // No Pythagorean triple exists
else {
val newA = 1
search(newA, newB, sum - (newA + newB))
}
}
else {
val newA = a + 1
search(newA, b, sum - (newA + b))
}
search(1, 2, sum - (1 + 2))
}
/**
* Searches for a Pythagorean triplet that sums to the given value.
*
* @param value
* the number to which the three numbers in the Pythagorean
* triple should sum
* @return a list of three integers consisting of a Pythagorean
* triple that sums to <code>value</code>
* @throws RuntimeException
* if no Pythagorean triple exists that sums to
* <code>value</code>
*/
def getPythagoreanTripletOrError(value: Long): List[Int] = {
val result = getPythagoreanTriplet(value)
if (result.isEmpty)
sys.error("No Pythagorean triplet sums to " + value)
else
result
}
/**
* Brute-force method for finding Pythagorean triplets. Used for
* debugging this algorithm.
*
* @param n
* the number of triplets to get
*/
def getNTriplets(n: Int): List[List[Int]] = {
def increment(a: Int, b: Int, c: Int): (Int, Int, Int) =
if (a == (b - 1))
if (b == (c - 1))
(1, 2, c + 1)
else
(1, b + 1, c)
else
(a + 1, b, c)
def search(a: Int, b: Int, c: Int, result: List[List[Int]]): List[List[Int]] =
if (result.size == n)
result
else {
val (newA, newB, newC) = increment(a, b, c)
if (isTriple(a, b, c))
search(newA, newB, newC, List(a, b, c) :: result)
else
search(newA, newB, newC, result)
}
search(1, 2, 3, List[List[Int]]())
}
val defaultValue = 1000L
def main(args: Array[String]) =
Runner.run[Long](args, java.lang.Long.parseLong _, defaultValue,
getPythagoreanTripletOrError(_).product.toString,
"Solution to problem 9")
}
| {
"content_hash": "e871fda31819ef5dab31cfda98c5cfc7",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 82,
"avg_line_length": 28.910569105691057,
"alnum_prop": 0.5359955005624297,
"repo_name": "joecarnahan/projecteuler",
"id": "6d7e7adf2722db50a357d2437b31ff942f379727",
"size": "3556",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/main/scala/009.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "27663"
},
{
"name": "Go",
"bytes": "74"
},
{
"name": "Scala",
"bytes": "93552"
},
{
"name": "Shell",
"bytes": "676"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.config.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DeleteDeliveryChannelResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteDeliveryChannelResultJsonUnmarshaller implements Unmarshaller<DeleteDeliveryChannelResult, JsonUnmarshallerContext> {
public DeleteDeliveryChannelResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DeleteDeliveryChannelResult deleteDeliveryChannelResult = new DeleteDeliveryChannelResult();
return deleteDeliveryChannelResult;
}
private static DeleteDeliveryChannelResultJsonUnmarshaller instance;
public static DeleteDeliveryChannelResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DeleteDeliveryChannelResultJsonUnmarshaller();
return instance;
}
}
| {
"content_hash": "0051eb0bbd3614eb34ae6e9f5a594b48",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 136,
"avg_line_length": 33.54545454545455,
"alnum_prop": 0.7976513098464318,
"repo_name": "jentfoo/aws-sdk-java",
"id": "fed04e939345cc6e3236bd4c184f6432206b9a6f",
"size": "1687",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/DeleteDeliveryChannelResultJsonUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
require_relative '../../spec_helper'
describe 'git::server' do
platform 'ubuntu'
step_into :git_service
it do
is_expected.to create_git_service('default').with(
service_base_path: '/srv/git'
)
end
it do
expect(chef_run).to create_directory('/srv/git').with(
owner: 'root',
group: 'root',
mode: '0755'
)
end
it do
expect(chef_run).to create_template('/etc/xinetd.d/git').with(
backup: false,
source: 'git-xinetd.d.erb',
owner: 'root',
group: 'root',
mode: '0644'
)
end
it { expect(chef_run).to enable_service('xinetd') }
it { expect(chef_run).to start_service('xinetd') }
end
| {
"content_hash": "06ba8e74cc2f77282bfbdac6c30df607",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 66,
"avg_line_length": 19.970588235294116,
"alnum_prop": 0.5876288659793815,
"repo_name": "chef-cookbooks/git",
"id": "aaa8a06dd154005f560275da8ae646be7ed991bc",
"size": "679",
"binary": false,
"copies": "2",
"ref": "refs/heads/automated/standardfiles",
"path": "spec/unit/recipes/server_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "399"
},
{
"name": "Ruby",
"bytes": "20955"
}
],
"symlink_target": ""
} |
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'dreamhost'))
require 'fog/dns'
module Fog
module DNS
class Dreamhost < Fog::Service
requires :dreamhost_api_key
model_path 'fog/dreamhost/models/dns'
model :record
model :zone
collection :records
collection :zones
request_path 'fog/dreamhost/requests/dns'
request :create_record
request :list_records
request :delete_record
class Mock
def self.data
@data ||= Hash.new do |hash, key|
hash[key] = {}
end
end
def self.reset
@data = nil
end
def initialize(options={})
@dreamhost_api_key = options[:dreamhost_api_key]
end
def data
self.class.data
end
def reset_data
self.class.data.delete
end
end
class Real
def initialize(options={})
require 'multi_json'
@dreamhost_api_key = options[:dreamhost_api_key]
if options[:dreamhost_url]
uri = URI.parse(options[:dreamhost_url])
options[:host] = uri.host
options[:port] = uri.port
options[:scheme] = uri.scheme
end
@host = options[:host] || "api.dreamhost.com"
@persistent = options[:persistent] || false
@port = options[:port] || 443
@scheme = options[:scheme] || 'https'
@connection = Fog::Connection.new("#{@scheme}://#{@host}:#{@port}", @persistent)
end
def reload
@connection.reset
end
def request(params)
params[:query].merge!( { :key => @dreamhost_api_key,
:format => 'json' } )
response = @connection.request(params)
unless response.body.empty?
response.body = MultiJson.decode(response.body)
end
if response.body['result'] != 'success'
raise response.body['data']
end
response
end
end
end
end
end
| {
"content_hash": "86ad2cf6a70e7f6753c72a6868837070",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 90,
"avg_line_length": 25.127906976744185,
"alnum_prop": 0.5118000925497455,
"repo_name": "remotesyssupport/stupidexample",
"id": "2dc8b4f07e4726e3439a61af9ae4c3422e639a1a",
"size": "2161",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "vendor/ruby/1.9.1/gems/fog-1.15.0/lib/fog/dreamhost/dns.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "8674"
}
],
"symlink_target": ""
} |
package io.hawtjms.jms;
import static org.junit.Assert.assertNotNull;
import io.hawtjms.test.support.AmqpTestSupport;
import javax.jms.JMSException;
import javax.jms.JMSSecurityException;
import javax.jms.TopicConnection;
import org.junit.Test;
/**
*
*/
public class JmsTopicConnectionTest extends AmqpTestSupport {
@Test
public void testCreateQueueConnection() throws JMSException {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
TopicConnection connection = factory.createTopicConnection();
assertNotNull(connection);
connection.close();
}
@Test(timeout=30000)
public void testCreateConnectionAsSystemAdmin() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
factory.setUsername("system");
factory.setPassword("manager");
TopicConnection connection = factory.createTopicConnection();
assertNotNull(connection);
connection.start();
connection.close();
}
@Test(timeout=30000)
public void testCreateConnectionCallSystemAdmin() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
TopicConnection connection = factory.createTopicConnection("system", "manager");
assertNotNull(connection);
connection.start();
connection.close();
}
@Test(timeout=30000, expected = JMSSecurityException.class)
public void testCreateConnectionAsUnknwonUser() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
factory.setUsername("unknown");
factory.setPassword("unknown");
TopicConnection connection = factory.createTopicConnection();
assertNotNull(connection);
connection.start();
connection.close();
}
@Test(timeout=30000, expected = JMSSecurityException.class)
public void testCreateConnectionCallUnknownUser() throws Exception {
JmsConnectionFactory factory = new JmsConnectionFactory(getBrokerAmqpConnectionURI());
TopicConnection connection = factory.createTopicConnection("unknown", "unknown");
assertNotNull(connection);
connection.start();
connection.close();
}
}
| {
"content_hash": "5e7a1f2a38e343cc7e005738c7189ee1",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 94,
"avg_line_length": 36.184615384615384,
"alnum_prop": 0.7249149659863946,
"repo_name": "fusesource/hawtjms",
"id": "ac1beea5bf56d16568da2ebb3258bd954746270e",
"size": "3155",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hawtjms-amqp/src/test/java/io/hawtjms/jms/JmsTopicConnectionTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1495002"
}
],
"symlink_target": ""
} |
from windmill.authoring import WindmillTestClient
def test_foreign_open():
client = WindmillTestClient(__name__)
client.open(url=u'http://www.asdf.com')
client.waits.forPageLoad(timeout=u'2000')
client.asserts.assertJS(js=u"windmill.testWin().document.title == 'asdf'")
| {
"content_hash": "844f1c5f5a71899a1defa7325818c6af",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 78,
"avg_line_length": 32.44444444444444,
"alnum_prop": 0.7157534246575342,
"repo_name": "ept/windmill",
"id": "d6798cdf6821457c027a6757ec43559e0c59dd17",
"size": "341",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/internet_tests/test_open_foreign_domain.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "653334"
},
{
"name": "Python",
"bytes": "337875"
},
{
"name": "Shell",
"bytes": "49"
}
],
"symlink_target": ""
} |
const StepBase = require( "../../src/step-definitions/step-base" );
const fs = require( "fs" );
const js = fs.readFileSync( __dirname + "/scripts/login-as-needed.js" ).toString();
const loginToFakeLoginPage = fs.readFileSync( __dirname + "/scripts/remote/login-to-fake-login-page.js" ).toString();
const detectFakeLoginPage = fs.readFileSync( __dirname + "/scripts/remote/detect-fake-login-page.js" ).toString();
class LoginAsNeeded extends StepBase {
static get stepName() { return "Login as needed"; }
static get shape() { return [
{ label: "Username", name: "username", type: "text" },
{ label: "Password", name: "password", type: "password" }
]; }
constructor() {
super( js, { detectFakeLoginPage, loginToFakeLoginPage } );
}
consume( variables ) {
this.args.username = variables.username;
this.args.password = variables.password;
}
}
module.exports = LoginAsNeeded;
| {
"content_hash": "832d6c60424aeb46f747dae23a99e32d",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 117,
"avg_line_length": 28.029411764705884,
"alnum_prop": 0.6505771248688352,
"repo_name": "goofballLogic/formicido",
"id": "305ed55f9ac966f7cebc354e85f7159fb8885495",
"size": "953",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "feature-data-pristine/step--login-as-needed.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6026"
},
{
"name": "Gherkin",
"bytes": "9853"
},
{
"name": "HTML",
"bytes": "8750"
},
{
"name": "JavaScript",
"bytes": "150234"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"strings"
"github.com/spf13/cobra"
)
func printDNSSuffixList(cmd *cobra.Command, args []string) {
dnsSuffixList := getDNSSuffixList()
fmt.Println(strings.Join(dnsSuffixList, ","))
}
| {
"content_hash": "a5f71c8b461c5aeaeab475eaab930fbd",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 60,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.7090909090909091,
"repo_name": "juju-solutions/kubernetes",
"id": "e0df5e7a018b2ee47a2edd4eeeda0531eadc0cac",
"size": "789",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/images/agnhost/common.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2840"
},
{
"name": "Dockerfile",
"bytes": "62626"
},
{
"name": "Go",
"bytes": "46248521"
},
{
"name": "HTML",
"bytes": "38"
},
{
"name": "Lua",
"bytes": "17200"
},
{
"name": "Makefile",
"bytes": "77710"
},
{
"name": "PowerShell",
"bytes": "93410"
},
{
"name": "Python",
"bytes": "3371110"
},
{
"name": "Ruby",
"bytes": "430"
},
{
"name": "Shell",
"bytes": "1618145"
},
{
"name": "sed",
"bytes": "11973"
}
],
"symlink_target": ""
} |
<?php
require_once dirname(__FILE__).'/../Client.php';
require_once dirname(__FILE__).'/../Cluster.php';
require_once dirname(__FILE__).'/../Sentinel.php';
class CredisSentinelTest extends PHPUnit_Framework_TestCase
{
/** @var Credis_Sentinel */
protected $sentinel;
protected $sentinelConfig;
protected $redisConfig;
protected $useStandalone = FALSE;
protected function setUp()
{
if($this->sentinelConfig === NULL) {
$configFile = dirname(__FILE__).'/sentinel_config.json';
if( ! file_exists($configFile) || ! ($config = file_get_contents($configFile))) {
$this->markTestSkipped('Could not load '.$configFile);
return;
}
$this->sentinelConfig = json_decode($config);
}
if($this->redisConfig === NULL) {
$configFile = dirname(__FILE__).'/redis_config.json';
if( ! file_exists($configFile) || ! ($config = file_get_contents($configFile))) {
$this->markTestSkipped('Could not load '.$configFile);
return;
}
$this->redisConfig = json_decode($config);
$arrayConfig = array();
foreach($this->redisConfig as $config) {
$arrayConfig[] = (array)$config;
}
$this->redisConfig = $arrayConfig;
}
$sentinelClient = new Credis_Client($this->sentinelConfig->host, $this->sentinelConfig->port);
$this->sentinel = new Credis_Sentinel($sentinelClient);
if($this->useStandalone) {
$this->sentinel->forceStandalone();
} else if ( ! extension_loaded('redis')) {
$this->fail('The Redis extension is not loaded.');
}
}
protected function tearDown()
{
if($this->sentinel) {
$this->sentinel = NULL;
}
}
public function testMasterClient()
{
$master = $this->sentinel->getMasterClient($this->sentinelConfig->clustername);
$this->assertInstanceOf('Credis_Client',$master);
$this->assertEquals($this->redisConfig[0]['port'],$master->getPort());
$this->setExpectedException('CredisException','Master not found');
$this->sentinel->getMasterClient('non-existing-cluster');
}
public function testMasters()
{
$masters = $this->sentinel->masters();
$this->assertInternalType('array',$masters);
$this->assertCount(2,$masters);
$this->assertArrayHasKey(0,$masters);
$this->assertArrayHasKey(1,$masters);
$this->assertArrayHasKey(1,$masters[0]);
$this->assertArrayHasKey(1,$masters[1]);
$this->assertArrayHasKey(5,$masters[1]);
if($masters[0][1] == 'masterdown'){
$this->assertEquals($this->sentinelConfig->clustername,$masters[1][1]);
$this->assertEquals($this->redisConfig[0]['port'],$masters[1][5]);
} else {
$this->assertEquals('masterdown',$masters[1][1]);
$this->assertEquals($this->sentinelConfig->clustername,$masters[0][1]);
$this->assertEquals($this->redisConfig[0]['port'],$masters[0][5]);
}
}
public function testMaster()
{
$master = $this->sentinel->master($this->sentinelConfig->clustername);
$this->assertInternalType('array',$master);
$this->assertArrayHasKey(1,$master);
$this->assertArrayHasKey(5,$master);
$this->assertEquals($this->sentinelConfig->clustername,$master[1]);
$this->assertEquals($this->redisConfig[0]['port'],$master[5]);
$this->setExpectedException('CredisException','No such master with that name');
$this->sentinel->master('non-existing-cluster');
}
public function testSlaveClient()
{
$slaves = $this->sentinel->getSlaveClients($this->sentinelConfig->clustername);
$this->assertInternalType('array',$slaves);
$this->assertCount(1,$slaves);
foreach($slaves as $slave){
$this->assertInstanceOf('Credis_Client',$slave);
}
$this->setExpectedException('CredisException','No such master with that name');
$this->sentinel->getSlaveClients('non-existing-cluster');
}
public function testSlaves()
{
$slaves = $this->sentinel->slaves($this->sentinelConfig->clustername);
$this->assertInternalType('array',$slaves);
$this->assertCount(1,$slaves);
$this->assertArrayHasKey(0,$slaves);
$this->assertArrayHasKey(5,$slaves[0]);
$this->assertEquals(6385,$slaves[0][5]);
$slaves = $this->sentinel->slaves('masterdown');
$this->assertInternalType('array',$slaves);
$this->assertCount(0,$slaves);
$this->setExpectedException('CredisException','No such master with that name');
$this->sentinel->slaves('non-existing-cluster');
}
public function testNonExistingClusterNameWhenCreatingSlaves()
{
$this->setExpectedException('CredisException','No such master with that name');
$this->sentinel->createSlaveClients('non-existing-cluster');
}
public function testCreateCluster()
{
$cluster = $this->sentinel->createCluster($this->sentinelConfig->clustername);
$this->assertInstanceOf('Credis_Cluster',$cluster);
$this->assertCount(2,$cluster->clients());
$cluster = $this->sentinel->createCluster($this->sentinelConfig->clustername,0,1,false);
$this->assertInstanceOf('Credis_Cluster',$cluster);
$this->assertCount(2,$cluster->clients());
$this->setExpectedException('CredisException','The master is down');
$this->sentinel->createCluster($this->sentinelConfig->downclustername);
}
public function testGetCluster()
{
$cluster = $this->sentinel->getCluster($this->sentinelConfig->clustername);
$this->assertInstanceOf('Credis_Cluster',$cluster);
$this->assertCount(2,$cluster->clients());
}
public function testGetClusterOnDbNumber2()
{
$cluster = $this->sentinel->getCluster($this->sentinelConfig->clustername,2);
$this->assertInstanceOf('Credis_Cluster',$cluster);
$this->assertCount(2,$cluster->clients());
$clients = $cluster->clients();
$this->assertEquals(2,$clients[0]->getSelectedDb());
$this->assertEquals(2,$clients[1]->getSelectedDb());
}
public function testGetMasterAddressByName()
{
$address = $this->sentinel->getMasterAddressByName($this->sentinelConfig->clustername);
$this->assertInternalType('array',$address);
$this->assertCount(2,$address);
$this->assertArrayHasKey(0,$address);
$this->assertArrayHasKey(1,$address);
$this->assertEquals($this->redisConfig[0]['host'],$address[0]);
$this->assertEquals($this->redisConfig[0]['port'],$address[1]);
}
public function testPing()
{
$pong = $this->sentinel->ping();
$this->assertEquals("PONG",$pong);
}
public function testGetHostAndPort()
{
$host = 'localhost';
$port = '123456';
$client = $this->getMock('\Credis_Client');
$sentinel = new Credis_Sentinel($client);
$client->expects($this->once())->method('getHost')->willReturn($host);
$client->expects($this->once())->method('getPort')->willReturn($port);
$this->assertEquals($host, $sentinel->getHost());
$this->assertEquals($port, $sentinel->getPort());
}
public function testNonExistingMethod()
{
$this->setExpectedException('CredisException','Unknown sentinel subcommand \'bla\'');
$this->sentinel->bla();
}
}
| {
"content_hash": "514867cd4a897dce91029f7fa8219b01",
"timestamp": "",
"source": "github",
"line_count": 188,
"max_line_length": 98,
"avg_line_length": 38.62234042553192,
"alnum_prop": 0.6449524858834871,
"repo_name": "MrGekko/credis",
"id": "d7e8d832eea38b463847c1c4e4c4039122a1108f",
"size": "7261",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tests/CredisSentinelTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "103246"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a8a7abca36c4ed2d03b15d58c4d811a9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a3b9d5b4aeaaf0fea5976a1e8305867340c9b574",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Helichroa/Helichroa fuscata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
if (!defined('_PS_VERSION_'))
exit;
class StatsRegistrations extends ModuleGraph
{
private $_html = '';
private $_query = '';
function __construct()
{
$this->name = 'statsregistrations';
$this->tab = 'analytics_stats';
$this->version = 1.0;
$this->author = 'PrestaShop';
$this->need_instance = 0;
parent::__construct();
$this->displayName = $this->l('Customer accounts');
$this->description = $this->l('Display registration progress.');
}
/**
* Called during module installation
*/
public function install()
{
return (parent::install() AND $this->registerHook('AdminStatsModules'));
}
/**
* @return int Get total of registration in date range
*/
public function getTotalRegistrations()
{
$sql = 'SELECT COUNT(`id_customer`) as total
FROM `'._DB_PREFIX_.'customer`
WHERE `date_add` BETWEEN '.ModuleGraph::getDateBetween().'
'.Shop::addSqlRestriction(Shop::SHARE_ORDER);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return isset($result['total']) ? $result['total'] : 0;
}
/**
* @return int Get total of blocked visitors during registration process
*/
public function getBlockedVisitors()
{
$sql = 'SELECT COUNT(DISTINCT c.`id_guest`) as blocked
FROM `'._DB_PREFIX_.'page_type` pt
LEFT JOIN `'._DB_PREFIX_.'page` p ON p.id_page_type = pt.id_page_type
LEFT JOIN `'._DB_PREFIX_.'connections_page` cp ON p.id_page = cp.id_page
LEFT JOIN `'._DB_PREFIX_.'connections` c ON c.id_connections = cp.id_connections
LEFT JOIN `'._DB_PREFIX_.'guest` g ON c.id_guest = g.id_guest
WHERE pt.name = "authentication"
'.Shop::addSqlRestriction(false, 'c').'
AND (g.id_customer IS NULL OR g.id_customer = 0)
AND c.`date_add` BETWEEN '.ModuleGraph::getDateBetween();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return $result['blocked'];
}
public function getFirstBuyers()
{
$sql = 'SELECT COUNT(DISTINCT o.`id_customer`) as buyers
FROM `'._DB_PREFIX_.'orders` o
LEFT JOIN `'._DB_PREFIX_.'guest` g ON o.id_customer = g.id_customer
LEFT JOIN `'._DB_PREFIX_.'connections` c ON c.id_guest = g.id_guest
WHERE o.`date_add` BETWEEN '.ModuleGraph::getDateBetween().'
'.Shop::addSqlRestriction(Shop::SHARE_ORDER, 'o').'
AND o.valid = 1
AND ABS(TIMEDIFF(o.date_add, c.date_add)+0) < 120000';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return $result['buyers'];
}
public function hookAdminStatsModules($params)
{
$totalRegistrations = $this->getTotalRegistrations();
$totalBlocked = $this->getBlockedVisitors();
$totalBuyers = $this->getFirstBuyers();
if (Tools::getValue('export'))
$this->csvExport(array('layers' => 0, 'type' => 'line'));
$this->_html = '
<div class="blocStats"><h2 class="icon-'.$this->name.'"><span></span>'.$this->displayName.'</h2>
<ul>
<li>
'.$this->l('Number of visitors who stopped at the registering step:').' <span class="totalStats">'.(int)($totalBlocked).($totalRegistrations ? ' ('.number_format(100*$totalBlocked/($totalRegistrations+$totalBlocked), 2).'%)' : '').'</span><li/>
'.$this->l('Number of visitors who placed an order directly after registration:').' <span class="totalStats">'.(int)($totalBuyers).($totalRegistrations ? ' ('.number_format(100*$totalBuyers/($totalRegistrations), 2).'%)' : '').'</span>
<li>'.$this->l('Total customer accounts:').' <span class="totalStats">'.$totalRegistrations.'</span></li>
</ul>
<div>'.$this->engine(array('type' => 'line')).'</div>
<p><a class="button export-csv" href="'.Tools::safeOutput($_SERVER['REQUEST_URI']).'&export=1"><span>'.$this->l('CSV Export').'</span></a></p>
</div><br />
<div class="blocStats"><h2 class="icon-guide"><span></span>'.$this->l('Guide').'</legend>
<h2>'.$this->l('Number of customer accounts created').'</h2>
<p>'.$this->l('The total number of accounts created is not in itself important information. However, it is beneficial to analyze the number created over time. This will indicate whether or not things are on the right track. You feel me?').'</p>
<br /><h3>'.$this->l('How to act on the registrations\' evolution?').'</h3>
<p>
'.$this->l('If you let your shop run without changing anything, the number of customer registrations should stay stable or slightly decline.').'
'.$this->l('A significant increase or decrease in customer registration shows that there has probably been a change to your shop.With that in mind, we suggest that you identify the cause, correct the issue and get back in the business of making money!').'<br />
'.$this->l('Here is a summary of what may affect the creation of customer accounts:').'
<ul>
<li>'.$this->l('An advertising campaign can attract an increased number of visitors to your online store. This will likely be followed by an increase in customer accounts, and profit margins, which will depend on customer "quality." Well-targeted advertising is typically more effective than large-scale advertising... and it\'s cheaper too!').'</li>
<li>'.$this->l('Specials, sales, promotions and/or contests typically demand a shoppers\' attentions. Offering such things will not only keep your business lively, it will also increase traffic, build customer loyalty and genuine change your current e-commerce philosophy.').'</li>
<li>'.$this->l('Design and user-friendliness are more important than ever in the world of online sales. An ill-chosen or hard-to-follow graphical theme can keep shoppers at bay. This means that you should aspire to find the right balance between beauty and functionality for your online store.').'</li>
</ul>
</p><br />
</div>';
return $this->_html;
}
protected function getData($layers)
{
$this->_query = '
SELECT `date_add`
FROM `'._DB_PREFIX_.'customer`
WHERE 1
'.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).'
AND `date_add` BETWEEN';
$this->_titles['main'] = $this->l('Number of customer accounts created');
$this->setDateGraph($layers, true);
}
protected function setAllTimeValues($layers)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->_query.$this->getDate());
foreach ($result AS $row)
$this->_values[(int)(substr($row['date_add'], 0, 4))]++;
}
protected function setYearValues($layers)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->_query.$this->getDate());
foreach ($result AS $row)
{
$mounth = (int)substr($row['date_add'], 5, 2);
if (!isset($this->_values[$mounth]))
$this->_values[$mounth] = 0;
$this->_values[$mounth]++;
}
}
protected function setMonthValues($layers)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->_query.$this->getDate());
foreach ($result AS $row)
$this->_values[(int)(substr($row['date_add'], 8, 2))]++;
}
protected function setDayValues($layers)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($this->_query.$this->getDate());
foreach ($result AS $row)
$this->_values[(int)(substr($row['date_add'], 11, 2))]++;
}
}
| {
"content_hash": "6068c7c0a8fd12cb16d70db248ceda3f",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 355,
"avg_line_length": 44.70987654320987,
"alnum_prop": 0.6484881954991025,
"repo_name": "rafaeljuzo/makeuptown",
"id": "70dbbe19b401f24de1a6839d166037e2bc086af4",
"size": "8234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/modules/statsregistrations/statsregistrations.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1284076"
},
{
"name": "PHP",
"bytes": "14546161"
}
],
"symlink_target": ""
} |
"""
Created on Fri Apr 17 10:16:21 2015
@author: anderson
"""
# importing modules
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as sig
from . import adjust_spines
import math
def plot_eeg(Data,start_sec = 0, window_size = 10, amp = 200, figure_size = (15,8),
dpi=600, detrend = True, envelope=False, plot_bad = False, exclude = [], grid=True,
xtickspace = 1,saveplot = None, subplot = None ,spines = ['left', 'bottom'],time_out = False, common_ref=False, **kwargs):
"""
Function to plot EEG signal
Parameters
----------
Data: DataObj
Data object to plot
start_sec: int, optional
0 (defaut) - The start second from begining of file to plot (n+time_vev[1] to start at second n)
window_size: int, optional
10 (default) - Size of window in second
amp: int
200 (default) - Amplitude between channels in plot
figure_size: tuple
(15,8) (default) - Size of figure, tuple of integers with width, height in inches
dpi: int
600 - DPI resolution
detrend: boolean
False (default) - detrend each line before filter
envelop: boolean
False (default) - plot the amplitude envelope by hilbert transform
plot_bad: boolean
False (default) - exclude bad channels from plot
exclude: list
Channels to exclude from plot
gride: boolean
True (default) - plot grid
xtickspace: int
1 (default) - distance of tick in seconds
saveplot: str
None (default) - Don't save
String with the name to save (ex: 'Figura.png')
subplot: matplotlib axes
None (default) - create a new figure
ax - axes of figure where figure should plot
spines: str
['left', 'bottom'] (default) - plot figure with left and bottom spines only
**kwargs: matplotlib arguments
"""
#geting data from Data_dict
data = Data.data
time_vec = Data.time_vec
sample_rate = Data.sample_rate
ch_labels = Data.ch_labels
if plot_bad:
badch = np.array([],dtype=int) # a empty array
else:
badch = Data.bad_channels
if type(exclude) == list:
for item in exclude:
if type(item) == str:
idx = [i for i,x in enumerate(ch_labels) if x == item]
badch = sorted(set(np.append(badch,idx)))
elif type(item) == int:
idx = item
badch = sorted(set(np.append(badch,idx)))
elif type(exclude) == str:
idx = [i for i,x in enumerate(ch_labels) if x == exclude]
badch = sorted(set(np.append(badch,idx)))
elif type(exclude) == int:
idx = exclude
badch = sorted(set(np.append(badch,idx)))
# Transforming the start_sec in points
start_sec *= sample_rate
start_sec = int(start_sec)
# Transforming the window_size in points
window_size *= sample_rate
window_size = int(window_size)
if subplot == None:
# Creating the figure
f = plt.figure(figsize=figure_size,dpi=dpi)
# creating the axes
sp = f.add_subplot(111)
else:
sp = subplot
# creating a vector with the desired index
time_window = np.arange(start_sec, start_sec + window_size)
# declaring tick variables
yticklocs = []
yticklabel = []
ch_l = 1
if len(data.shape) == 1:
# in the axes, plot the raw signal for each channel with a amp diference
if detrend:
sp.plot(time_vec[time_window],(ch_l)*amp + sig.detrend(data[time_window]),**kwargs)
else:
sp.plot(time_vec[time_window],(ch_l)*amp + data[time_window],**kwargs)
if envelope:
sp.plot(time_vec[time_window],(ch_l)*amp + np.abs(sig.hilbert(data[time_window])),**kwargs)
# appeng the channel label and the tick location
if ch_labels is None:
yticklabel.append(ch_l)
else:
yticklabel.append(ch_labels[0])
yticklocs.append((ch_l)*amp)
else:
# Loop to plot each channel
for ch in [x for x in range(data.shape[1]) if x not in badch]:
# in the axes, plot the raw signal for each channel with a amp diference
if detrend:
sp.plot(time_vec[time_window],(ch_l)*amp + sig.detrend(data[time_window,ch]),**kwargs)
else:
sp.plot(time_vec[time_window],(ch_l)*amp + data[time_window,ch],**kwargs)
if envelope:
sp.plot(time_vec[time_window],(ch_l)*amp + np.abs(sig.hilbert(data[time_window,ch])),**kwargs)
# appeng the channel label and the tick location
if ch_labels is None:
yticklabel.append(ch_l)
else:
yticklabel.append(ch_labels[ch])
yticklocs.append((ch_l)*amp)
ch_l += 1
if common_ref:
sp.plot(time_vec[time_window],(ch_l)*amp + Data.common_ref[time_window],**kwargs)
yticklocs.append((ch_l)*amp)
yticklabel.append('common_ref')
adjust_spines(sp, spines)
if len(spines) > 0:
# changing the x-axis (label, limit and ticks)
plt .xlabel('time (s)', size = 16)
#xtickslocs = np.linspace(int(time_vec[time_window[0]]),int(time_vec[time_window[-1]]),int(window_size/(sample_rate*xtickspace)),endpoint=True)
xtickslocs = np.arange(math.ceil(time_vec[time_window[0]]),math.ceil(time_vec[time_window[-1]]+xtickspace),xtickspace)
xtickslabels = ['']*len(xtickslocs)
for x in np.arange(0,len(xtickslocs),10):
xtickslabels[x] = xtickslocs[x]
plt.xticks(xtickslocs,xtickslabels,size = 16)
# changing the y-axis
plt.yticks(yticklocs, yticklabel, size=16)
if grid:
ax = plt.gca()
ax.xaxis.grid(True)
sp.set_xlim(time_vec[time_window[0]],time_vec[time_window[-1]]+np.diff(time_vec[time_window[0:2]]))
#sp.set_ylim(0,(ch_l)*amp)
if time_out:
return time_vec[time_window[0]], time_vec[time_window[-1]]+np.diff(time_vec[time_window[0:2]]), sp
if saveplot != None:
if type(saveplot) == str:
plt.savefig(saveplot, bbox_inches='tight')
else:
raise Exception('saveplot should be a string')
| {
"content_hash": "aba6dfd66fe5d88496bb63de1d846a01",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 151,
"avg_line_length": 38.449101796407184,
"alnum_prop": 0.5882261330010902,
"repo_name": "britodasilva/pyhfo",
"id": "0016e813117640efb6e607a013c761a9285878ad",
"size": "6445",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyhfo/ui/plot_eeg.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "194788"
}
],
"symlink_target": ""
} |
package org.sagebionetworks.bridge.sdk.integration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.sagebionetworks.bridge.rest.model.Role.ADMIN;
import static org.sagebionetworks.bridge.rest.model.Role.DEVELOPER;
import static org.sagebionetworks.bridge.rest.model.Role.RESEARCHER;
import static org.sagebionetworks.bridge.sdk.integration.Tests.ORG_ID_1;
import static org.sagebionetworks.bridge.sdk.integration.Tests.STUDY_ID_1;
import static org.sagebionetworks.bridge.util.IntegTestUtils.SAGE_ID;
import java.io.IOException;
import java.util.stream.Collectors;
import com.google.common.collect.ImmutableSet;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.sagebionetworks.bridge.rest.api.AccountsApi;
import org.sagebionetworks.bridge.rest.api.AssessmentsApi;
import org.sagebionetworks.bridge.rest.api.OrganizationsApi;
import org.sagebionetworks.bridge.rest.api.SharedAssessmentsApi;
import org.sagebionetworks.bridge.rest.exceptions.BadRequestException;
import org.sagebionetworks.bridge.rest.exceptions.ConstraintViolationException;
import org.sagebionetworks.bridge.rest.exceptions.EntityNotFoundException;
import org.sagebionetworks.bridge.rest.model.Account;
import org.sagebionetworks.bridge.rest.model.AccountSummary;
import org.sagebionetworks.bridge.rest.model.AccountSummaryList;
import org.sagebionetworks.bridge.rest.model.AccountSummarySearch;
import org.sagebionetworks.bridge.rest.model.Assessment;
import org.sagebionetworks.bridge.rest.model.Message;
import org.sagebionetworks.bridge.rest.model.Organization;
import org.sagebionetworks.bridge.rest.model.OrganizationList;
import org.sagebionetworks.bridge.rest.model.StudyList;
import org.sagebionetworks.bridge.user.TestUser;
import org.sagebionetworks.bridge.user.TestUserHelper;
public class OrganizationTest {
private TestUser admin;
private TestUser orgAdmin;
private TestUser user;
private String orgId1;
private Organization org1;
private String orgId2;
private Organization org2;
private String orgId3;
private Organization org3;
private Assessment assessment;
@Before
public void before() throws Exception {
admin = TestUserHelper.getSignedInAdmin();
}
@After
public void deleteUser() throws Exception {
if (user != null) {
user.signOutAndDeleteUser();
}
}
@After
public void deleteOrgAdmin() throws Exception {
if (orgAdmin != null) {
orgAdmin.signOutAndDeleteUser();
}
}
@After
public void after() throws Exception {
OrganizationsApi orgApi = admin.getClient(OrganizationsApi.class);
if (org1 != null && orgId1 != null) {
orgApi.deleteOrganization(orgId1).execute();
}
if (org2 != null && orgId2 != null) {
orgApi.deleteOrganization(orgId2).execute();
}
if (org3 != null && orgId3 != null) {
orgApi.deleteOrganization(orgId3).execute();
}
AssessmentsApi assessmentsApi = admin.getClient(AssessmentsApi.class);
SharedAssessmentsApi sharedAssessmentsApi = admin.getClient(SharedAssessmentsApi.class);
if (assessment != null) {
try {
assessmentsApi.deleteAssessment(assessment.getGuid(), true);
} catch (Exception ignored) {
}
try {
sharedAssessmentsApi.deleteSharedAssessment(assessment.getGuid(), true);
} catch (Exception ignored) {
}
}
}
@Test
public void test() throws Exception {
OrganizationsApi orgApi = admin.getClient(OrganizationsApi.class);
orgId1 = Tests.randomIdentifier(getClass());
Organization newOrg = new Organization();
newOrg.setIdentifier(orgId1);
newOrg.setName("Test Name");
newOrg.setDescription("A description");
org1 = orgApi.createOrganization(newOrg).execute().body();
assertNotNull(org1.getVersion());
assertNotNull(org1.getCreatedOn());
assertNotNull(org1.getModifiedOn());
org1.setDescription("Description updated");
org1.setIdentifier("not-the-identifier"); // this has no effect.
Organization updated = orgApi.updateOrganization(orgId1, org1).execute().body();
assertEquals(orgId1, updated.getIdentifier());
assertEquals("Description updated", updated.getDescription());
assertTrue(updated.getVersion() > org1.getVersion());
OrganizationList list = orgApi.getOrganizations(0, 50).execute().body();
assertEquals(Integer.valueOf(0), list.getRequestParams().getOffsetBy());
assertEquals(Integer.valueOf(50), list.getRequestParams().getPageSize());
Organization found = findOrganization(list, orgId1);
assertNull(found.getCreatedOn());
assertNull(found.getModifiedOn());
assertEquals("Test Name", found.getName());
assertEquals(orgId1, found.getIdentifier());
assertEquals("Description updated", found.getDescription());
found = orgApi.getOrganization(orgId1).execute().body();
assertNotNull(found.getCreatedOn());
assertNotNull(found.getModifiedOn());
assertNotNull(found.getVersion());
assertEquals("Organization", found.getType());
assertEquals("Test Name", found.getName());
assertEquals(orgId1, found.getIdentifier());
assertEquals("Description updated", found.getDescription());
Message message = orgApi.deleteOrganization(orgId1).execute().body();
org1 = null;
assertEquals("Organization deleted.", message.getMessage());
try {
orgApi.getOrganization(orgId1).execute().body();
fail("Should have thrown exception");
} catch(EntityNotFoundException e) {
}
list = orgApi.getOrganizations(null, null).execute().body();
found = findOrganization(list, orgId1);
assertNull(found);
}
@Test
public void testMembership() throws Exception {
// Create an organization
OrganizationsApi superadminOrgApi = admin.getClient(OrganizationsApi.class);
orgId1 = Tests.randomIdentifier(getClass());
Organization newOrg1 = new Organization();
newOrg1.setIdentifier(orgId1);
newOrg1.setName("Test Org 1");
org1 = superadminOrgApi.createOrganization(newOrg1).execute().body();
orgId2 = Tests.randomIdentifier(getClass());
Organization newOrg2 = new Organization();
newOrg2.setIdentifier(orgId2);
newOrg2.setName("Test Org 2");
org2 = superadminOrgApi.createOrganization(newOrg2).execute().body();
// Create an admin in organization 1, with researcher permissions to access the participant APIs
orgAdmin = TestUserHelper.createAndSignInUser(OrganizationTest.class, false, ADMIN, RESEARCHER);
superadminOrgApi.addMember(orgId1, orgAdmin.getUserId()).execute();
OrganizationsApi appAdminOrgApi = orgAdmin.getClient(OrganizationsApi.class);
// session should show organizational membership
orgAdmin.signInAgain();
assertEquals(orgId1, orgAdmin.getSession().getOrgMembership());
// create a user. TestUserHelper puts admins in the Sage Bionetworks organization, so for this
// test, remove the user first.
user = TestUserHelper.createAndSignInUser(OrganizationTest.class, false, DEVELOPER);
admin.getClient(OrganizationsApi.class).removeMember(SAGE_ID, user.getUserId()).execute();
// the user is unassigned and should appear in the unassigned API
AccountSummarySearch search = new AccountSummarySearch();
AccountSummaryList list = orgAdmin.getClient(OrganizationsApi.class)
.getUnassignedAdminAccounts(search).execute().body();
assertTrue(list.getItems().stream().anyMatch((summary) -> summary.getId().equals(user.getUserId())));
// cannot change organizational affiliation on an update. We need an admin to retrieve the account because
// it's moving between organizations
AccountsApi adminAccountsApi = admin.getClient(AccountsApi.class);
Account account = adminAccountsApi.getAccount(user.getUserId()).execute().body();
account.setOrgMembership(orgId2);
adminAccountsApi.updateAccount(user.getUserId(), account).execute();
// Membership was not assigned. It didn't throw an error, it did nothing.
account = adminAccountsApi.getAccount(user.getUserId()).execute().body();
assertNull(account.getOrgMembership());
// Still in the unassigned list
list = orgAdmin.getClient(OrganizationsApi.class)
.getUnassignedAdminAccounts(search).execute().body();
assertTrue(list.getItems().stream().anyMatch((summary) -> summary.getId().equals(user.getUserId())));
for (AccountSummary summary : list.getItems()) {
assertNull(summary.getOrgMembership());
}
// add the person to another organization
appAdminOrgApi.addMember(orgId1, user.getUserId()).execute();
account = adminAccountsApi.getAccount(user.getUserId()).execute().body();
assertEquals(orgId1, account.getOrgMembership());
// The account should now be listed as a member
list = appAdminOrgApi.getMembers(orgId1, new AccountSummarySearch()).execute().body();
assertEquals(ImmutableSet.of(user.getEmail(), orgAdmin.getEmail()),
list.getItems().stream().map(AccountSummary::getEmail).collect(Collectors.toSet()));
assertEquals(Integer.valueOf(2), list.getTotal()); // the admin and the user
for (AccountSummary summary : list.getItems()) {
assertEquals(orgId1, summary.getOrgMembership());
}
// The user is no longer in the unassigned users list
list = orgAdmin.getClient(OrganizationsApi.class)
.getUnassignedAdminAccounts(search).execute().body();
assertFalse(list.getItems().stream().anyMatch((summary) -> summary.getId().equals(user.getUserId())));
// can remove someone from the organization
appAdminOrgApi.removeMember(orgId1, user.getUserId()).execute();
// account is no longer listed as a member
list = appAdminOrgApi.getMembers(orgId1, new AccountSummarySearch()).execute().body();
assertEquals(ImmutableSet.of(orgAdmin.getEmail()),
list.getItems().stream().map(AccountSummary::getEmail).collect(Collectors.toSet()));
assertEquals(Integer.valueOf(1), list.getTotal());
list = orgAdmin.getClient(OrganizationsApi.class)
.getUnassignedAdminAccounts(search).execute().body();
assertTrue(list.getItems().stream().anyMatch((summary) -> summary.getId().equals(user.getUserId())));
}
@Test
public void testSponsorship() throws Exception {
OrganizationsApi adminOrgApi = admin.getClient(OrganizationsApi.class);
try {
// In essence, let's clean this up before we test. It throws an exception if
// not associated.
try {
adminOrgApi.removeStudySponsorship(ORG_ID_1, STUDY_ID_1).execute();
} catch(BadRequestException e) {
}
adminOrgApi.addStudySponsorship(ORG_ID_1, STUDY_ID_1).execute();
StudyList list = adminOrgApi.getSponsoredStudies(ORG_ID_1, null, null).execute().body();
assertTrue(list.getItems().stream().anyMatch((study) -> study.getIdentifier().equals(STUDY_ID_1)));
adminOrgApi.removeStudySponsorship(ORG_ID_1, STUDY_ID_1).execute();
list = adminOrgApi.getSponsoredStudies(ORG_ID_1, null, null).execute().body();
assertFalse(list.getItems().stream().anyMatch((study) -> study.getIdentifier().equals(STUDY_ID_1)));
} finally {
// This must be added back after the test.
adminOrgApi.addStudySponsorship(ORG_ID_1, STUDY_ID_1).execute();
}
}
@Test
public void testDeleteWithAssessment() throws IOException {
// Create an organization
OrganizationsApi orgApi = admin.getClient(OrganizationsApi.class);
orgId3 = Tests.randomIdentifier(getClass());
org3 = new Organization();
org3.setIdentifier(orgId3);
org3.setName("Test Name");
org3.setDescription("A description");
org3 = orgApi.createOrganization(org3).execute().body();
AssessmentsApi assessmentApi = admin.getClient(AssessmentsApi.class);
Assessment unsavedAssessment = new Assessment()
.identifier(Tests.randomIdentifier(Assessment.class))
.title("Title")
.summary("Summary")
.validationStatus("Not validated")
.normingStatus("Not normed")
.osName("Both")
.ownerId(orgId3);
assessment = assessmentApi.createAssessment(unsavedAssessment).execute().body();
assertNotNull(assessment);
try {
orgApi.deleteOrganization(orgId3).execute();
fail("Should have thrown an exception");
} catch (ConstraintViolationException ignored) {
}
assessmentApi.publishAssessment(assessment.getGuid(), null).execute().body();
assessmentApi.deleteAssessment(assessment.getGuid(), true).execute();
try {
orgApi.deleteOrganization(orgId3).execute();
fail("Should have thrown an exception");
} catch (ConstraintViolationException ignored) {
}
SharedAssessmentsApi sharedAssessmentsApi = admin.getClient(SharedAssessmentsApi.class);
Assessment shared = sharedAssessmentsApi.getLatestSharedAssessmentRevision(assessment.getIdentifier()).execute().body();
sharedAssessmentsApi.deleteSharedAssessment(shared.getGuid(), true).execute();
orgApi.deleteOrganization(orgId3).execute();
orgId3 = null;
org3 = null;
}
private Organization findOrganization(OrganizationList list, String id) {
for (Organization org : list.getItems()) {
if (org.getIdentifier().equals(id)) {
return org;
}
}
return null;
}
}
| {
"content_hash": "8850630a00fb2a2edefdb08469ae142d",
"timestamp": "",
"source": "github",
"line_count": 335,
"max_line_length": 128,
"avg_line_length": 44.17313432835821,
"alnum_prop": 0.6684687119881065,
"repo_name": "alxdarksage/BridgeIntegrationTests",
"id": "a51bdb904ae6556bae8375d7880ba96518ebf398",
"size": "14798",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "src/test/java/org/sagebionetworks/bridge/sdk/integration/OrganizationTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1355170"
}
],
"symlink_target": ""
} |
package io.gatling.http.client.impl;
import io.netty.handler.codec.http.HttpContent;
public class Http2Content {
private final HttpContent httpContent;
private final int streamId;
public Http2Content(HttpContent httpContent, int streamId) {
this.httpContent = httpContent;
this.streamId = streamId;
}
public HttpContent getHttpContent() {
return httpContent;
}
public int getStreamId() {
return streamId;
}
}
| {
"content_hash": "4f4c1eb1e0056f06fce741562eb1fb94",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 62,
"avg_line_length": 19.47826086956522,
"alnum_prop": 0.734375,
"repo_name": "gatling/gatling",
"id": "4abc0e83c87be1aa782036301cdcb6d3f9b0acaa",
"size": "1065",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "gatling-http-client/src/main/java/io/gatling/http/client/impl/Http2Content.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4107"
},
{
"name": "CSS",
"bytes": "18867"
},
{
"name": "HTML",
"bytes": "41444"
},
{
"name": "Java",
"bytes": "1341839"
},
{
"name": "JavaScript",
"bytes": "7567"
},
{
"name": "Kotlin",
"bytes": "104724"
},
{
"name": "Scala",
"bytes": "2616285"
},
{
"name": "Shell",
"bytes": "2074"
}
],
"symlink_target": ""
} |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "init.h"
#include "util.h"
#include "sync.h"
#include "ui_interface.h"
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include <boost/asio.hpp>
#include <boost/asio/ip/v6_only.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/shared_ptr.hpp>
#include <list>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
static std::string strRPCUserColonPass;
// These are created by StartRPCThreads, destroyed in StopRPCThreads
static asio::io_service* rpc_io_service = NULL;
static ssl::context* rpc_ssl_context = NULL;
static boost::thread_group* rpc_worker_group = NULL;
static inline unsigned short GetDefaultRPCPort()
{
return GetBoolArg("-testnet", false) ? 19332 : 9332;
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
void RPCTypeCheck(const Array& params,
const list<Value_type>& typesExpected,
bool fAllowNull)
{
unsigned int i = 0;
BOOST_FOREACH(Value_type t, typesExpected)
{
if (params.size() <= i)
break;
const Value& v = params[i];
if (!((v.type() == t) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s, got %s",
Value_type_name[t], Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
i++;
}
}
void RPCTypeCheck(const Object& o,
const map<string, Value_type>& typesExpected,
bool fAllowNull)
{
BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected)
{
const Value& v = find_value(o, t.first);
if (!fAllowNull && v.type() == null_type)
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first.c_str()));
if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type))))
{
string err = strprintf("Expected type %s for %s, got %s",
Value_type_name[t.second], t.first.c_str(), Value_type_name[v.type()]);
throw JSONRPCError(RPC_TYPE_ERROR, err);
}
}
}
int64 AmountFromValue(const Value& value)
{
double dAmount = value.get_real();
if (dAmount <= 0.0 || dAmount > 84000000.0)
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
int64 nAmount = roundint64(dAmount * COIN);
if (!MoneyRange(nAmount))
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount");
return nAmount;
}
Value ValueFromAmount(int64 amount)
{
return (double)amount / (double)COIN;
}
std::string HexBits(unsigned int nBits)
{
union {
int32_t nBits;
char cBits[4];
} uBits;
uBits.nBits = htonl((int32_t)nBits);
return HexStr(BEGIN(uBits.cBits), END(uBits.cBits));
}
///
/// Note: This interface may still be subject to change.
///
string CRPCTable::help(string strCommand) const
{
string strRet;
set<rpcfn_type> setDone;
for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi)
{
const CRPCCommand *pcmd = mi->second;
string strMethod = mi->first;
// We already filter duplicates, but these deprecated screw up the sort order
if (strMethod.find("label") != string::npos)
continue;
if (strCommand != "" && strMethod != strCommand)
continue;
if (pcmd->reqWallet && !pwalletMain)
continue;
try
{
Array params;
rpcfn_type pfn = pcmd->actor;
if (setDone.insert(pfn).second)
(*pfn)(params, true);
}
catch (std::exception& e)
{
// Help text is returned in an exception
string strHelp = string(e.what());
if (strCommand == "")
if (strHelp.find('\n') != string::npos)
strHelp = strHelp.substr(0, strHelp.find('\n'));
strRet += strHelp + "\n";
}
}
if (strRet == "")
strRet = strprintf("help: unknown command: %s\n", strCommand.c_str());
strRet = strRet.substr(0,strRet.size()-1);
return strRet;
}
Value help(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"help [command]\n"
"List commands, or get help for a command.");
string strCommand;
if (params.size() > 0)
strCommand = params[0].get_str();
return tableRPC.help(strCommand);
}
Value stop(const Array& params, bool fHelp)
{
// Accept the deprecated and ignored 'detach' boolean argument
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop Testcoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return "Testcoin server stopping";
}
//
// Call Table
//
static const CRPCCommand vRPCCommands[] =
{ // name actor (function) okSafeMode threadSafe reqWallet
// ------------------------ ----------------------- ---------- ---------- ---------
{ "help", &help, true, true, false },
{ "stop", &stop, true, true, false },
{ "getblockcount", &getblockcount, true, false, false },
{ "getbestblockhash", &getbestblockhash, true, false, false },
{ "getconnectioncount", &getconnectioncount, true, false, false },
{ "getpeerinfo", &getpeerinfo, true, false, false },
{ "addnode", &addnode, true, true, false },
{ "getaddednodeinfo", &getaddednodeinfo, true, true, false },
{ "getdifficulty", &getdifficulty, true, false, false },
{ "getnetworkhashps", &getnetworkhashps, true, false, false },
{ "getgenerate", &getgenerate, true, false, false },
{ "setgenerate", &setgenerate, true, false, true },
{ "gethashespersec", &gethashespersec, true, false, false },
{ "getinfo", &getinfo, true, false, false },
{ "getmininginfo", &getmininginfo, true, false, false },
{ "getnewaddress", &getnewaddress, true, false, true },
{ "getaccountaddress", &getaccountaddress, true, false, true },
{ "setaccount", &setaccount, true, false, true },
{ "getaccount", &getaccount, false, false, true },
{ "getaddressesbyaccount", &getaddressesbyaccount, true, false, true },
{ "sendtoaddress", &sendtoaddress, false, false, true },
{ "getreceivedbyaddress", &getreceivedbyaddress, false, false, true },
{ "getreceivedbyaccount", &getreceivedbyaccount, false, false, true },
{ "listreceivedbyaddress", &listreceivedbyaddress, false, false, true },
{ "listreceivedbyaccount", &listreceivedbyaccount, false, false, true },
{ "backupwallet", &backupwallet, true, false, true },
{ "keypoolrefill", &keypoolrefill, true, false, true },
{ "walletpassphrase", &walletpassphrase, true, false, true },
{ "walletpassphrasechange", &walletpassphrasechange, false, false, true },
{ "walletlock", &walletlock, true, false, true },
{ "encryptwallet", &encryptwallet, false, false, true },
{ "validateaddress", &validateaddress, true, false, false },
{ "getbalance", &getbalance, false, false, true },
{ "move", &movecmd, false, false, true },
{ "sendfrom", &sendfrom, false, false, true },
{ "sendmany", &sendmany, false, false, true },
{ "addmultisigaddress", &addmultisigaddress, false, false, true },
{ "createmultisig", &createmultisig, true, true , false },
{ "getrawmempool", &getrawmempool, true, false, false },
{ "getblock", &getblock, false, false, false },
{ "getblockhash", &getblockhash, false, false, false },
{ "gettransaction", &gettransaction, false, false, true },
{ "listtransactions", &listtransactions, false, false, true },
{ "listaddressgroupings", &listaddressgroupings, false, false, true },
{ "signmessage", &signmessage, false, false, true },
{ "verifymessage", &verifymessage, false, false, false },
{ "getwork", &getwork, true, false, true },
{ "getworkex", &getworkex, true, false, true },
{ "listaccounts", &listaccounts, false, false, true },
{ "settxfee", &settxfee, false, false, true },
{ "getblocktemplate", &getblocktemplate, true, false, false },
{ "submitblock", &submitblock, false, false, false },
{ "setmininput", &setmininput, false, false, false },
{ "listsinceblock", &listsinceblock, false, false, true },
{ "dumpprivkey", &dumpprivkey, true, false, true },
{ "importprivkey", &importprivkey, false, false, true },
{ "listunspent", &listunspent, false, false, true },
{ "getrawtransaction", &getrawtransaction, false, false, false },
{ "createrawtransaction", &createrawtransaction, false, false, false },
{ "decoderawtransaction", &decoderawtransaction, false, false, false },
{ "signrawtransaction", &signrawtransaction, false, false, false },
{ "sendrawtransaction", &sendrawtransaction, false, false, false },
{ "gettxoutsetinfo", &gettxoutsetinfo, true, false, false },
{ "gettxout", &gettxout, true, false, false },
{ "lockunspent", &lockunspent, false, false, true },
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
};
CRPCTable::CRPCTable()
{
unsigned int vcidx;
for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++)
{
const CRPCCommand *pcmd;
pcmd = &vRPCCommands[vcidx];
mapCommands[pcmd->name] = pcmd;
}
}
const CRPCCommand *CRPCTable::operator[](string name) const
{
map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name);
if (it == mapCommands.end())
return NULL;
return (*it).second;
}
//
// HTTP protocol
//
// This ain't Apache. We're just using HTTP header for the length field
// and to be compatible with other JSON-RPC implementations.
//
string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: testcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH(const PAIRTYPE(string, string)& item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n" << strMsg;
return s.str();
}
string rfc1123Time()
{
char buffer[64];
time_t now;
time(&now);
struct tm* now_gmt = gmtime(&now);
string locale(setlocale(LC_TIME, NULL));
setlocale(LC_TIME, "C"); // we want POSIX (aka "C") weekday/month strings
strftime(buffer, sizeof(buffer), "%a, %d %b %Y %H:%M:%S +0000", now_gmt);
setlocale(LC_TIME, locale.c_str());
return string(buffer);
}
static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: testcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n", rfc1123Time().c_str(), FormatFullVersion().c_str());
const char *cStatus;
if (nStatus == HTTP_OK) cStatus = "OK";
else if (nStatus == HTTP_BAD_REQUEST) cStatus = "Bad Request";
else if (nStatus == HTTP_FORBIDDEN) cStatus = "Forbidden";
else if (nStatus == HTTP_NOT_FOUND) cStatus = "Not Found";
else if (nStatus == HTTP_INTERNAL_SERVER_ERROR) cStatus = "Internal Server Error";
else cStatus = "";
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: testcoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
cStatus,
rfc1123Time().c_str(),
keepalive ? "keep-alive" : "close",
strMsg.size(),
FormatFullVersion().c_str(),
strMsg.c_str());
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int &proto,
string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char *ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int &proto)
{
string str;
getline(stream, str);
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char *ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver+7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
loop
{
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos)
{
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon+1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string,
string>& mapHeadersRet, string& strMessageRet,
int nProto)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || nLen > (int)MAX_SIZE)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0)
{
vector<char> vch(nLen);
stream.read(&vch[0], nLen);
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive"))
{
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
bool HTTPAuthorized(map<string, string>& mapHeaders)
{
string strAuth = mapHeaders["authorization"];
if (strAuth.substr(0,6) != "Basic ")
return false;
string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64);
string strUserPass = DecodeBase64(strUserPass64);
return TimingResistantEqual(strUserPass, strRPCUserColonPass);
}
//
// JSON-RPC protocol. Bitcoin speaks version 1.0 for maximum compatibility,
// but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
// unspecified (HTTP errors and contents of 'error').
//
// 1.0 spec: http://json-rpc.org/wiki/specification
// 1.2 spec: http://groups.google.com/group/json-rpc/web/json-rpc-over-http
// http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
//
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
void ErrorReply(std::ostream& stream, const Object& objError, const Value& id)
{
// Send error reply from json-rpc error object
int nStatus = HTTP_INTERNAL_SERVER_ERROR;
int code = find_value(objError, "code").get_int();
if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST;
else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND;
string strReply = JSONRPCReply(Value::null, objError, id);
stream << HTTPReply(nStatus, strReply, false) << std::flush;
}
bool ClientAllowed(const boost::asio::ip::address& address)
{
// Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses
if (address.is_v6()
&& (address.to_v6().is_v4_compatible()
|| address.to_v6().is_v4_mapped()))
return ClientAllowed(address.to_v6().to_v4());
if (address == asio::ip::address_v4::loopback()
|| address == asio::ip::address_v6::loopback()
|| (address.is_v4()
// Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet)
&& (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000))
return true;
const string strAddress = address.to_string();
const vector<string>& vAllow = mapMultiArgs["-rpcallowip"];
BOOST_FOREACH(string strAllow, vAllow)
if (WildcardMatch(strAddress, strAllow))
return true;
return false;
}
//
// IOStream device that speaks SSL but can also speak non-SSL
//
template <typename Protocol>
class SSLIOStreamDevice : public iostreams::device<iostreams::bidirectional> {
public:
SSLIOStreamDevice(asio::ssl::stream<typename Protocol::socket> &streamIn, bool fUseSSLIn) : stream(streamIn)
{
fUseSSL = fUseSSLIn;
fNeedHandshake = fUseSSLIn;
}
void handshake(ssl::stream_base::handshake_type role)
{
if (!fNeedHandshake) return;
fNeedHandshake = false;
stream.handshake(role);
}
std::streamsize read(char* s, std::streamsize n)
{
handshake(ssl::stream_base::server); // HTTPS servers read first
if (fUseSSL) return stream.read_some(asio::buffer(s, n));
return stream.next_layer().read_some(asio::buffer(s, n));
}
std::streamsize write(const char* s, std::streamsize n)
{
handshake(ssl::stream_base::client); // HTTPS clients write first
if (fUseSSL) return asio::write(stream, asio::buffer(s, n));
return asio::write(stream.next_layer(), asio::buffer(s, n));
}
bool connect(const std::string& server, const std::string& port)
{
ip::tcp::resolver resolver(stream.get_io_service());
ip::tcp::resolver::query query(server.c_str(), port.c_str());
ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
ip::tcp::resolver::iterator end;
boost::system::error_code error = asio::error::host_not_found;
while (error && endpoint_iterator != end)
{
stream.lowest_layer().close();
stream.lowest_layer().connect(*endpoint_iterator++, error);
}
if (error)
return false;
return true;
}
private:
bool fNeedHandshake;
bool fUseSSL;
asio::ssl::stream<typename Protocol::socket>& stream;
};
class AcceptedConnection
{
public:
virtual ~AcceptedConnection() {}
virtual std::iostream& stream() = 0;
virtual std::string peer_address_to_string() const = 0;
virtual void close() = 0;
};
template <typename Protocol>
class AcceptedConnectionImpl : public AcceptedConnection
{
public:
AcceptedConnectionImpl(
asio::io_service& io_service,
ssl::context &context,
bool fUseSSL) :
sslStream(io_service, context),
_d(sslStream, fUseSSL),
_stream(_d)
{
}
virtual std::iostream& stream()
{
return _stream;
}
virtual std::string peer_address_to_string() const
{
return peer.address().to_string();
}
virtual void close()
{
_stream.close();
}
typename Protocol::endpoint peer;
asio::ssl::stream<typename Protocol::socket> sslStream;
private:
SSLIOStreamDevice<Protocol> _d;
iostreams::stream< SSLIOStreamDevice<Protocol> > _stream;
};
void ServiceConnection(AcceptedConnection *conn);
// Forward declaration required for RPCListen
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error);
/**
* Sets up I/O resources to accept and handle a new connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL)
{
// Accept connection
AcceptedConnectionImpl<Protocol>* conn = new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL);
acceptor->async_accept(
conn->sslStream.lowest_layer(),
conn->peer,
boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>,
acceptor,
boost::ref(context),
fUseSSL,
conn,
boost::asio::placeholders::error));
}
/**
* Accept and handle incoming connection.
*/
template <typename Protocol, typename SocketAcceptorService>
static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor,
ssl::context& context,
const bool fUseSSL,
AcceptedConnection* conn,
const boost::system::error_code& error)
{
// Immediately start accepting new connections, except when we're cancelled or our socket is closed.
if (error != asio::error::operation_aborted && acceptor->is_open())
RPCListen(acceptor, context, fUseSSL);
AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn);
// TODO: Actually handle errors
if (error)
{
delete conn;
}
// Restrict callers by IP. It is important to
// do this before starting client thread, to filter out
// certain DoS and misbehaving clients.
else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address()))
{
// Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake.
if (!fUseSSL)
conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush;
delete conn;
}
else {
ServiceConnection(conn);
conn->close();
delete conn;
}
}
void StartRPCThreads()
{
strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"];
if ((mapArgs["-rpcpassword"] == "") ||
(mapArgs["-rpcuser"] == mapArgs["-rpcpassword"]))
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use testcoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\"");
uiInterface.ThreadSafeMessageBox(strprintf(
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=testcoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"Testcoin Alert\" [email protected]\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
assert(rpc_io_service == NULL);
rpc_io_service = new asio::io_service();
rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23);
const bool fUseSSL = GetBoolArg("-rpcssl");
if (fUseSSL)
{
rpc_ssl_context->set_options(ssl::context::no_sslv2);
filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert"));
if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile;
if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string());
else printf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string().c_str());
filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem"));
if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile;
if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem);
else printf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string().c_str());
string strCiphers = GetArg("-rpcsslciphers", "TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH");
SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str());
}
// Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets
const bool loopback = !mapArgs.count("-rpcallowip");
asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any();
ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", GetDefaultRPCPort()));
boost::system::error_code v6_only_error;
boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service));
bool fListening = false;
std::string strerr;
try
{
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
// Try making the socket dual IPv6/IPv4 (if listening on the "any" address)
acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error);
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what());
}
try {
// If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately
if (!fListening || loopback || v6_only_error)
{
bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any();
endpoint.address(bindAddress);
acceptor.reset(new ip::tcp::acceptor(*rpc_io_service));
acceptor->open(endpoint.protocol());
acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
acceptor->bind(endpoint);
acceptor->listen(socket_base::max_connections);
RPCListen(acceptor, *rpc_ssl_context, fUseSSL);
fListening = true;
}
}
catch(boost::system::system_error &e)
{
strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what());
}
if (!fListening) {
uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR);
StartShutdown();
return;
}
rpc_worker_group = new boost::thread_group();
for (int i = 0; i < GetArg("-rpcthreads", 4); i++)
rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service));
}
void StopRPCThreads()
{
if (rpc_io_service == NULL) return;
rpc_io_service->stop();
rpc_worker_group->join_all();
delete rpc_worker_group; rpc_worker_group = NULL;
delete rpc_ssl_context; rpc_ssl_context = NULL;
delete rpc_io_service; rpc_io_service = NULL;
}
class JSONRequest
{
public:
Value id;
string strMethod;
Array params;
JSONRequest() { id = Value::null; }
void parse(const Value& valRequest);
};
void JSONRequest::parse(const Value& valRequest)
{
// Parse request
if (valRequest.type() != obj_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object");
const Object& request = valRequest.get_obj();
// Parse id now so errors from here on will have the id
id = find_value(request, "id");
// Parse method
Value valMethod = find_value(request, "method");
if (valMethod.type() == null_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method");
if (valMethod.type() != str_type)
throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string");
strMethod = valMethod.get_str();
if (strMethod != "getwork" && strMethod != "getworkex" && strMethod != "getblocktemplate")
printf("ThreadRPCServer method=%s\n", strMethod.c_str());
// Parse params
Value valParams = find_value(request, "params");
if (valParams.type() == array_type)
params = valParams.get_array();
else if (valParams.type() == null_type)
params = Array();
else
throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array");
}
static Object JSONRPCExecOne(const Value& req)
{
Object rpc_result;
JSONRequest jreq;
try {
jreq.parse(req);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id);
}
catch (Object& objError)
{
rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id);
}
catch (std::exception& e)
{
rpc_result = JSONRPCReplyObj(Value::null,
JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
}
return rpc_result;
}
static string JSONRPCExecBatch(const Array& vReq)
{
Array ret;
for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++)
ret.push_back(JSONRPCExecOne(vReq[reqIdx]));
return write_string(Value(ret), false) + "\n";
}
void ServiceConnection(AcceptedConnection *conn)
{
bool fRun = true;
while (fRun)
{
int nProto = 0;
map<string, string> mapHeaders;
string strRequest, strMethod, strURI;
// Read HTTP request line
if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI))
break;
// Read HTTP message headers and body
ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto);
if (strURI != "/") {
conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush;
break;
}
// Check authorization
if (mapHeaders.count("authorization") == 0)
{
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (!HTTPAuthorized(mapHeaders))
{
printf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string().c_str());
/* Deter brute-forcing short passwords.
If this results in a DOS the user really
shouldn't have their RPC port exposed.*/
if (mapArgs["-rpcpassword"].size() < 20)
MilliSleep(250);
conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush;
break;
}
if (mapHeaders["connection"] == "close")
fRun = false;
JSONRequest jreq;
try
{
// Parse request
Value valRequest;
if (!read_string(strRequest, valRequest))
throw JSONRPCError(RPC_PARSE_ERROR, "Parse error");
string strReply;
// singleton request
if (valRequest.type() == obj_type) {
jreq.parse(valRequest);
Value result = tableRPC.execute(jreq.strMethod, jreq.params);
// Send reply
strReply = JSONRPCReply(result, Value::null, jreq.id);
// array of requests
} else if (valRequest.type() == array_type)
strReply = JSONRPCExecBatch(valRequest.get_array());
else
throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error");
conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush;
}
catch (Object& objError)
{
ErrorReply(conn->stream(), objError, jreq.id);
break;
}
catch (std::exception& e)
{
ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id);
break;
}
}
}
json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array ¶ms) const
{
// Find method
const CRPCCommand *pcmd = tableRPC[strMethod];
if (!pcmd)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found");
if (pcmd->reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode") &&
!pcmd->okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
try
{
// Execute
Value result;
{
if (pcmd->threadSafe)
result = pcmd->actor(params, false);
else if (!pwalletMain) {
LOCK(cs_main);
result = pcmd->actor(params, false);
} else {
LOCK2(cs_main, pwalletMain->cs_wallet);
result = pcmd->actor(params, false);
}
}
return result;
}
catch (std::exception& e)
{
throw JSONRPCError(RPC_MISC_ERROR, e.what());
}
}
Object CallRPC(const string& strMethod, const Array& params)
{
if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "")
throw runtime_error(strprintf(
_("You must set rpcpassword=<password> in the configuration file:\n%s\n"
"If the file does not exist, create it with owner-readable-only file permissions."),
GetConfigFile().string().c_str()));
// Connect to localhost
bool fUseSSL = GetBoolArg("-rpcssl");
asio::io_service io_service;
ssl::context context(io_service, ssl::context::sslv23);
context.set_options(ssl::context::no_sslv2);
asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context);
SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL);
iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d);
if (!d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(GetDefaultRPCPort()))))
throw runtime_error("couldn't connect to server");
// HTTP basic authentication
string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]);
map<string, string> mapRequestHeaders;
mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64;
// Send request
string strRequest = JSONRPCRequest(strMethod, params, 1);
string strPost = HTTPPost(strRequest, mapRequestHeaders);
stream << strPost << std::flush;
// Receive HTTP reply status
int nProto = 0;
int nStatus = ReadHTTPStatus(stream, nProto);
// Receive HTTP reply message headers and body
map<string, string> mapHeaders;
string strReply;
ReadHTTPMessage(stream, mapHeaders, strReply, nProto);
if (nStatus == HTTP_UNAUTHORIZED)
throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)");
else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR)
throw runtime_error(strprintf("server returned HTTP error %d", nStatus));
else if (strReply.empty())
throw runtime_error("no response from server");
// Parse reply
Value valReply;
if (!read_string(strReply, valReply))
throw runtime_error("couldn't parse reply from server");
const Object& reply = valReply.get_obj();
if (reply.empty())
throw runtime_error("expected reply to have result, error and id properties");
return reply;
}
template<typename T>
void ConvertTo(Value& value, bool fAllowNull=false)
{
if (fAllowNull && value.type() == null_type)
return;
if (value.type() == str_type)
{
// reinterpret string as unquoted json value
Value value2;
string strJSON = value.get_str();
if (!read_string(strJSON, value2))
throw runtime_error(string("Error parsing JSON:")+strJSON);
ConvertTo<T>(value2, fAllowNull);
value = value2;
}
else
{
value = value.get_value<T>();
}
}
// Convert strings to command-specific RPC representation
Array RPCConvertValues(const std::string &strMethod, const std::vector<std::string> &strParams)
{
Array params;
BOOST_FOREACH(const std::string ¶m, strParams)
params.push_back(param);
int n = params.size();
//
// Special case non-string parameter types
//
if (strMethod == "stop" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "getaddednodeinfo" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "setgenerate" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getnetworkhashps" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "getnetworkhashps" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendtoaddress" && n > 1) ConvertTo<double>(params[1]);
if (strMethod == "settxfee" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "setmininput" && n > 0) ConvertTo<double>(params[0]);
if (strMethod == "getreceivedbyaddress" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getreceivedbyaccount" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listreceivedbyaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaddress" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "listreceivedbyaccount" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listreceivedbyaccount" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getbalance" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblockhash" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "move" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "move" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "sendfrom" && n > 2) ConvertTo<double>(params[2]);
if (strMethod == "sendfrom" && n > 3) ConvertTo<boost::int64_t>(params[3]);
if (strMethod == "listtransactions" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listtransactions" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "listaccounts" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "walletpassphrase" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "getblocktemplate" && n > 0) ConvertTo<Object>(params[0]);
if (strMethod == "listsinceblock" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "sendmany" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "sendmany" && n > 2) ConvertTo<boost::int64_t>(params[2]);
if (strMethod == "addmultisigaddress" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "addmultisigaddress" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "createmultisig" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "createmultisig" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "listunspent" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "listunspent" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "listunspent" && n > 2) ConvertTo<Array>(params[2]);
if (strMethod == "getblock" && n > 1) ConvertTo<bool>(params[1]);
if (strMethod == "getrawtransaction" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "createrawtransaction" && n > 0) ConvertTo<Array>(params[0]);
if (strMethod == "createrawtransaction" && n > 1) ConvertTo<Object>(params[1]);
if (strMethod == "signrawtransaction" && n > 1) ConvertTo<Array>(params[1], true);
if (strMethod == "signrawtransaction" && n > 2) ConvertTo<Array>(params[2], true);
if (strMethod == "gettxout" && n > 1) ConvertTo<boost::int64_t>(params[1]);
if (strMethod == "gettxout" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "lockunspent" && n > 0) ConvertTo<bool>(params[0]);
if (strMethod == "lockunspent" && n > 1) ConvertTo<Array>(params[1]);
if (strMethod == "importprivkey" && n > 2) ConvertTo<bool>(params[2]);
if (strMethod == "verifychain" && n > 0) ConvertTo<boost::int64_t>(params[0]);
if (strMethod == "verifychain" && n > 1) ConvertTo<boost::int64_t>(params[1]);
return params;
}
int CommandLineRPC(int argc, char *argv[])
{
string strPrint;
int nRet = 0;
try
{
// Skip switches
while (argc > 1 && IsSwitchChar(argv[1][0]))
{
argc--;
argv++;
}
// Method
if (argc < 2)
throw runtime_error("too few parameters");
string strMethod = argv[1];
// Parameters default to strings
std::vector<std::string> strParams(&argv[2], &argv[argc]);
Array params = RPCConvertValues(strMethod, strParams);
// Execute
Object reply = CallRPC(strMethod, params);
// Parse reply
const Value& result = find_value(reply, "result");
const Value& error = find_value(reply, "error");
if (error.type() != null_type)
{
// Error
strPrint = "error: " + write_string(error, false);
int code = find_value(error.get_obj(), "code").get_int();
nRet = abs(code);
}
else
{
// Result
if (result.type() == null_type)
strPrint = "";
else if (result.type() == str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
strPrint = string("error: ") + e.what();
nRet = 87;
}
catch (...) {
PrintException(NULL, "CommandLineRPC()");
}
if (strPrint != "")
{
fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str());
}
return nRet;
}
#ifdef TEST
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFile("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
setbuf(stdin, NULL);
setbuf(stdout, NULL);
setbuf(stderr, NULL);
try
{
if (argc >= 2 && string(argv[1]) == "-server")
{
printf("server ready\n");
ThreadRPCServer(NULL);
}
else
{
return CommandLineRPC(argc, argv);
}
}
catch (boost::thread_interrupted) {
throw;
}
catch (std::exception& e) {
PrintException(&e, "main()");
} catch (...) {
PrintException(NULL, "main()");
}
return 0;
}
#endif
const CRPCTable tableRPC;
| {
"content_hash": "79bbe2cc5aeeee948dc45b93a97a9a83",
"timestamp": "",
"source": "github",
"line_count": 1305,
"max_line_length": 159,
"avg_line_length": 37.216858237547896,
"alnum_prop": 0.5770054356778126,
"repo_name": "ottolevin/testcoin",
"id": "7e1975bde8af815e35959202b86c3009691cb55d",
"size": "48568",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/bitcoinrpc.cpp",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import './slidePanel.less';
import React, { Component, PropTypes } from 'react';
import LeftNav from 'material-ui/lib/left-nav';
import SelectField from 'material-ui/lib/select-field';
import MenuItem from 'material-ui/lib/menus/menu-item';
import Checkbox from 'material-ui/lib/checkbox';
import TextField from 'material-ui/lib/text-field';
import { T__ } from '../../reducers/language.js';
import { DropDown, SlidePanelSocial } from '../';
class SlidePanel extends Component {
render() {
const {
isMapClickEnabled = true,
clickRadius = 250,
selectedLanguage,
languages,
onChange
} = this.props;
const sizeStyle = {
maxWidth: '226px'
};
const textStyle = {
color: '#eee'
};
const floatingLabelStyle = {
...textStyle,
opacity: 0.5
};
return (
<LeftNav open={this.props.visible} className="tgv-slidePanel">
<h3>{this.props.header}</h3>
<SlidePanelSocial />
<h4>{T__('mapPage.slidePanel.header')}</h4>
<ul>
<li>
<SelectField
value={selectedLanguage.code}
floatingLabelText={T__('mapPage.slidePanel.languageSelector.label')}
style={sizeStyle}
floatingLabelStyle={floatingLabelStyle}
labelStyle={textStyle}
onChange={(event, index, value) =>
onChange('selectedLanguageCode', value)
}
>
{
languages.map(language => <MenuItem
value={language.code}
key={language.code}
primaryText={language.name}
/>)
}
</SelectField>
</li>
<li>
<Checkbox
label={T__('mapPage.slidePanel.mapClick.label')}
labelPosition="left"
className="tgv-slidePanel-control-width"
labelStyle={textStyle}
checked={isMapClickEnabled}
onCheck={(event, value) => onChange('isMapClickEnabled', value)}
/>
</li>
<li>
<Checkbox
label={T__('mapPage.slidePanel.showFilter.label')}
labelPosition="left"
className="tgv-slidePanel-control-width"
labelStyle={textStyle}
checked={this.props.showFilter}
onCheck={(event, value) => onChange('showFilter', value)}
/>
</li>
<li>
<Checkbox
label={T__('mapPage.slidePanel.showTimeStamps.label')}
labelPosition="left"
className="tgv-slidePanel-control-width"
labelStyle={textStyle}
checked={this.props.showTimeStamps}
onCheck={(event, value) => onChange('showTimeStamps', value)}
/>
</li>
<li>
<TextField
floatingLabelText={T__('mapPage.slidePanel.clickRadius.label')}
value={clickRadius}
className="tgv-slidePanel-control-width"
inputStyle={textStyle}
floatingLabelStyle={floatingLabelStyle}
onChange={event => {
let { value } = event.target;
value = value.replace(/\D/g, '');
value = value.length ? parseInt(value, 10) : 1;
if (value === clickRadius) {
return;
}
onChange('clickRadius', value);
}}
/>
</li>
<li>
<SelectField
value={this.props.selectedLayer}
floatingLabelText={T__('mapPage.slidePanel.layerSelector.label')}
style={sizeStyle}
floatingLabelStyle={floatingLabelStyle}
labelStyle={textStyle}
onChange={(event, index, value) =>
onChange('selectedLayer', value)
}
>
{
this.props.layers.map(layer => <MenuItem
value={layer.value}
key={layer.value}
primaryText={layer.label}
/>)
}
</SelectField>
</li>
</ul>
<div>
<p>{T__('mapPage.slidePanel.footer1')}</p>
<p>{T__('mapPage.slidePanel.footer2')}</p>
<p>
<span className="label label-primary">v{this.props.version}</span>
</p>
</div>
</LeftNav>
);
}
}
SlidePanel.propTypes = {
visible: PropTypes.bool,
selectedLanguage: PropTypes.object.isRequired,
clickRadius: PropTypes.number,
isMapClickEnabled: PropTypes.bool,
contentSelector: PropTypes.string,
languages: PropTypes.array,
version: PropTypes.string,
header: PropTypes.string,
onChange: PropTypes.func
};
export default SlidePanel;
| {
"content_hash": "654c530ff0a2918350b29010a4a79da1",
"timestamp": "",
"source": "github",
"line_count": 157,
"max_line_length": 82,
"avg_line_length": 31.159235668789808,
"alnum_prop": 0.5204415372035978,
"repo_name": "JaredHawkins/TweetGeoViz",
"id": "2e999930c4a2766365fa94da27115c55ebeb9ef7",
"size": "4950",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "client/src/components/SlidePanel/SlidePanel.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1868"
},
{
"name": "HTML",
"bytes": "465"
},
{
"name": "JavaScript",
"bytes": "50516"
}
],
"symlink_target": ""
} |
/*
OpenGL loader generated by glad 0.1.33 on Thu Feb 13 13:20:31 2020.
Language/Generator: C/C++
Specification: gl
APIs: gl=3.3
Profile: core
Extensions:
Loader: True
Local files: True
Omit khrplatform: False
Reproducible: False
Commandline:
--profile="core" --api="gl=3.3" --generator="c" --spec="gl" --local-files --extensions=""
Online:
https://glad.dav1d.de/#profile=core&language=c&specification=gl&loader=on&api=gl%3D3.3
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "glad.h"
static void* get_proc(const char *namez);
#if defined(_WIN32) || defined(__CYGWIN__)
#ifndef _WINDOWS_
#undef APIENTRY
#endif
#include <windows.h>
static HMODULE libGL;
typedef void* (APIENTRYP PFNWGLGETPROCADDRESSPROC_PRIVATE)(const char*);
static PFNWGLGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr;
#ifdef _MSC_VER
#ifdef __has_include
#if __has_include(<winapifamily.h>)
#define HAVE_WINAPIFAMILY 1
#endif
#elif _MSC_VER >= 1700 && !_USING_V110_SDK71_
#define HAVE_WINAPIFAMILY 1
#endif
#endif
#ifdef HAVE_WINAPIFAMILY
#include <winapifamily.h>
#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP)
#define IS_UWP 1
#endif
#endif
static
int open_gl(void) {
#ifndef IS_UWP
libGL = LoadLibraryW(L"opengl32.dll");
if(libGL != NULL) {
void (* tmp)(void);
tmp = (void(*)(void)) GetProcAddress(libGL, "wglGetProcAddress");
gladGetProcAddressPtr = (PFNWGLGETPROCADDRESSPROC_PRIVATE) tmp;
return gladGetProcAddressPtr != NULL;
}
#endif
return 0;
}
static
void close_gl(void) {
if(libGL != NULL) {
FreeLibrary((HMODULE) libGL);
libGL = NULL;
}
}
#else
#include <dlfcn.h>
static void* libGL;
#if !defined(__APPLE__) && !defined(__HAIKU__)
typedef void* (APIENTRYP PFNGLXGETPROCADDRESSPROC_PRIVATE)(const char*);
static PFNGLXGETPROCADDRESSPROC_PRIVATE gladGetProcAddressPtr;
#endif
static
int open_gl(void) {
#ifdef __APPLE__
static const char *NAMES[] = {
"../Frameworks/OpenGL.framework/OpenGL",
"/Library/Frameworks/OpenGL.framework/OpenGL",
"/System/Library/Frameworks/OpenGL.framework/OpenGL",
"/System/Library/Frameworks/OpenGL.framework/Versions/Current/OpenGL"
};
#else
static const char *NAMES[] = {"libGL.so.1", "libGL.so"};
#endif
unsigned int index = 0;
for(index = 0; index < (sizeof(NAMES) / sizeof(NAMES[0])); index++) {
libGL = dlopen(NAMES[index], RTLD_NOW | RTLD_GLOBAL);
if(libGL != NULL) {
#if defined(__APPLE__) || defined(__HAIKU__)
return 1;
#else
gladGetProcAddressPtr = (PFNGLXGETPROCADDRESSPROC_PRIVATE)dlsym(libGL,
"glXGetProcAddressARB");
return gladGetProcAddressPtr != NULL;
#endif
}
}
return 0;
}
static
void close_gl(void) {
if(libGL != NULL) {
dlclose(libGL);
libGL = NULL;
}
}
#endif
static
void* get_proc(const char *namez) {
void* result = NULL;
if(libGL == NULL) return NULL;
#if !defined(__APPLE__) && !defined(__HAIKU__)
if(gladGetProcAddressPtr != NULL) {
result = gladGetProcAddressPtr(namez);
}
#endif
if(result == NULL) {
#if defined(_WIN32) || defined(__CYGWIN__)
result = (void*)GetProcAddress((HMODULE) libGL, namez);
#else
result = dlsym(libGL, namez);
#endif
}
return result;
}
int gladLoadGL(void) {
int status = 0;
if(open_gl()) {
status = gladLoadGLLoader(&get_proc);
close_gl();
}
return status;
}
struct gladGLversionStruct GLVersion = { 0, 0 };
#if defined(GL_ES_VERSION_3_0) || defined(GL_VERSION_3_0)
#define _GLAD_IS_SOME_NEW_VERSION 1
#endif
static int max_loaded_major;
static int max_loaded_minor;
static const char *exts = NULL;
static int num_exts_i = 0;
static char **exts_i = NULL;
static int get_exts(void) {
#ifdef _GLAD_IS_SOME_NEW_VERSION
if(max_loaded_major < 3) {
#endif
exts = (const char *)glGetString(GL_EXTENSIONS);
#ifdef _GLAD_IS_SOME_NEW_VERSION
} else {
unsigned int index;
num_exts_i = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_exts_i);
if (num_exts_i > 0) {
exts_i = (char **)malloc((size_t)num_exts_i * (sizeof *exts_i));
}
if (exts_i == NULL) {
return 0;
}
for(index = 0; index < (unsigned)num_exts_i; index++) {
const char *gl_str_tmp = (const char*)glGetStringi(GL_EXTENSIONS, index);
size_t len = strlen(gl_str_tmp);
char *local_str = (char*)malloc((len+1) * sizeof(char));
if(local_str != NULL) {
memcpy(local_str, gl_str_tmp, (len+1) * sizeof(char));
}
exts_i[index] = local_str;
}
}
#endif
return 1;
}
static void free_exts(void) {
if (exts_i != NULL) {
int index;
for(index = 0; index < num_exts_i; index++) {
free((char *)exts_i[index]);
}
free((void *)exts_i);
exts_i = NULL;
}
}
static int has_ext(const char *ext) {
#ifdef _GLAD_IS_SOME_NEW_VERSION
if(max_loaded_major < 3) {
#endif
const char *extensions;
const char *loc;
const char *terminator;
extensions = exts;
if(extensions == NULL || ext == NULL) {
return 0;
}
while(1) {
loc = strstr(extensions, ext);
if(loc == NULL) {
return 0;
}
terminator = loc + strlen(ext);
if((loc == extensions || *(loc - 1) == ' ') &&
(*terminator == ' ' || *terminator == '\0')) {
return 1;
}
extensions = terminator;
}
#ifdef _GLAD_IS_SOME_NEW_VERSION
} else {
int index;
if(exts_i == NULL) return 0;
for(index = 0; index < num_exts_i; index++) {
const char *e = exts_i[index];
if(exts_i[index] != NULL && strcmp(e, ext) == 0) {
return 1;
}
}
}
#endif
return 0;
}
int GLAD_GL_VERSION_1_0 = 0;
int GLAD_GL_VERSION_1_1 = 0;
int GLAD_GL_VERSION_1_2 = 0;
int GLAD_GL_VERSION_1_3 = 0;
int GLAD_GL_VERSION_1_4 = 0;
int GLAD_GL_VERSION_1_5 = 0;
int GLAD_GL_VERSION_2_0 = 0;
int GLAD_GL_VERSION_2_1 = 0;
int GLAD_GL_VERSION_3_0 = 0;
int GLAD_GL_VERSION_3_1 = 0;
int GLAD_GL_VERSION_3_2 = 0;
int GLAD_GL_VERSION_3_3 = 0;
PFNGLACTIVETEXTUREPROC glad_glActiveTexture = NULL;
PFNGLATTACHSHADERPROC glad_glAttachShader = NULL;
PFNGLBEGINCONDITIONALRENDERPROC glad_glBeginConditionalRender = NULL;
PFNGLBEGINQUERYPROC glad_glBeginQuery = NULL;
PFNGLBEGINTRANSFORMFEEDBACKPROC glad_glBeginTransformFeedback = NULL;
PFNGLBINDATTRIBLOCATIONPROC glad_glBindAttribLocation = NULL;
PFNGLBINDBUFFERPROC glad_glBindBuffer = NULL;
PFNGLBINDBUFFERBASEPROC glad_glBindBufferBase = NULL;
PFNGLBINDBUFFERRANGEPROC glad_glBindBufferRange = NULL;
PFNGLBINDFRAGDATALOCATIONPROC glad_glBindFragDataLocation = NULL;
PFNGLBINDFRAGDATALOCATIONINDEXEDPROC glad_glBindFragDataLocationIndexed = NULL;
PFNGLBINDFRAMEBUFFERPROC glad_glBindFramebuffer = NULL;
PFNGLBINDRENDERBUFFERPROC glad_glBindRenderbuffer = NULL;
PFNGLBINDSAMPLERPROC glad_glBindSampler = NULL;
PFNGLBINDTEXTUREPROC glad_glBindTexture = NULL;
PFNGLBINDVERTEXARRAYPROC glad_glBindVertexArray = NULL;
PFNGLBLENDCOLORPROC glad_glBlendColor = NULL;
PFNGLBLENDEQUATIONPROC glad_glBlendEquation = NULL;
PFNGLBLENDEQUATIONSEPARATEPROC glad_glBlendEquationSeparate = NULL;
PFNGLBLENDFUNCPROC glad_glBlendFunc = NULL;
PFNGLBLENDFUNCSEPARATEPROC glad_glBlendFuncSeparate = NULL;
PFNGLBLITFRAMEBUFFERPROC glad_glBlitFramebuffer = NULL;
PFNGLBUFFERDATAPROC glad_glBufferData = NULL;
PFNGLBUFFERSUBDATAPROC glad_glBufferSubData = NULL;
PFNGLCHECKFRAMEBUFFERSTATUSPROC glad_glCheckFramebufferStatus = NULL;
PFNGLCLAMPCOLORPROC glad_glClampColor = NULL;
PFNGLCLEARPROC glad_glClear = NULL;
PFNGLCLEARBUFFERFIPROC glad_glClearBufferfi = NULL;
PFNGLCLEARBUFFERFVPROC glad_glClearBufferfv = NULL;
PFNGLCLEARBUFFERIVPROC glad_glClearBufferiv = NULL;
PFNGLCLEARBUFFERUIVPROC glad_glClearBufferuiv = NULL;
PFNGLCLEARCOLORPROC glad_glClearColor = NULL;
PFNGLCLEARDEPTHPROC glad_glClearDepth = NULL;
PFNGLCLEARSTENCILPROC glad_glClearStencil = NULL;
PFNGLCLIENTWAITSYNCPROC glad_glClientWaitSync = NULL;
PFNGLCOLORMASKPROC glad_glColorMask = NULL;
PFNGLCOLORMASKIPROC glad_glColorMaski = NULL;
PFNGLCOLORP3UIPROC glad_glColorP3ui = NULL;
PFNGLCOLORP3UIVPROC glad_glColorP3uiv = NULL;
PFNGLCOLORP4UIPROC glad_glColorP4ui = NULL;
PFNGLCOLORP4UIVPROC glad_glColorP4uiv = NULL;
PFNGLCOMPILESHADERPROC glad_glCompileShader = NULL;
PFNGLCOMPRESSEDTEXIMAGE1DPROC glad_glCompressedTexImage1D = NULL;
PFNGLCOMPRESSEDTEXIMAGE2DPROC glad_glCompressedTexImage2D = NULL;
PFNGLCOMPRESSEDTEXIMAGE3DPROC glad_glCompressedTexImage3D = NULL;
PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC glad_glCompressedTexSubImage1D = NULL;
PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC glad_glCompressedTexSubImage2D = NULL;
PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC glad_glCompressedTexSubImage3D = NULL;
PFNGLCOPYBUFFERSUBDATAPROC glad_glCopyBufferSubData = NULL;
PFNGLCOPYTEXIMAGE1DPROC glad_glCopyTexImage1D = NULL;
PFNGLCOPYTEXIMAGE2DPROC glad_glCopyTexImage2D = NULL;
PFNGLCOPYTEXSUBIMAGE1DPROC glad_glCopyTexSubImage1D = NULL;
PFNGLCOPYTEXSUBIMAGE2DPROC glad_glCopyTexSubImage2D = NULL;
PFNGLCOPYTEXSUBIMAGE3DPROC glad_glCopyTexSubImage3D = NULL;
PFNGLCREATEPROGRAMPROC glad_glCreateProgram = NULL;
PFNGLCREATESHADERPROC glad_glCreateShader = NULL;
PFNGLCULLFACEPROC glad_glCullFace = NULL;
PFNGLDELETEBUFFERSPROC glad_glDeleteBuffers = NULL;
PFNGLDELETEFRAMEBUFFERSPROC glad_glDeleteFramebuffers = NULL;
PFNGLDELETEPROGRAMPROC glad_glDeleteProgram = NULL;
PFNGLDELETEQUERIESPROC glad_glDeleteQueries = NULL;
PFNGLDELETERENDERBUFFERSPROC glad_glDeleteRenderbuffers = NULL;
PFNGLDELETESAMPLERSPROC glad_glDeleteSamplers = NULL;
PFNGLDELETESHADERPROC glad_glDeleteShader = NULL;
PFNGLDELETESYNCPROC glad_glDeleteSync = NULL;
PFNGLDELETETEXTURESPROC glad_glDeleteTextures = NULL;
PFNGLDELETEVERTEXARRAYSPROC glad_glDeleteVertexArrays = NULL;
PFNGLDEPTHFUNCPROC glad_glDepthFunc = NULL;
PFNGLDEPTHMASKPROC glad_glDepthMask = NULL;
PFNGLDEPTHRANGEPROC glad_glDepthRange = NULL;
PFNGLDETACHSHADERPROC glad_glDetachShader = NULL;
PFNGLDISABLEPROC glad_glDisable = NULL;
PFNGLDISABLEVERTEXATTRIBARRAYPROC glad_glDisableVertexAttribArray = NULL;
PFNGLDISABLEIPROC glad_glDisablei = NULL;
PFNGLDRAWARRAYSPROC glad_glDrawArrays = NULL;
PFNGLDRAWARRAYSINSTANCEDPROC glad_glDrawArraysInstanced = NULL;
PFNGLDRAWBUFFERPROC glad_glDrawBuffer = NULL;
PFNGLDRAWBUFFERSPROC glad_glDrawBuffers = NULL;
PFNGLDRAWELEMENTSPROC glad_glDrawElements = NULL;
PFNGLDRAWELEMENTSBASEVERTEXPROC glad_glDrawElementsBaseVertex = NULL;
PFNGLDRAWELEMENTSINSTANCEDPROC glad_glDrawElementsInstanced = NULL;
PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC glad_glDrawElementsInstancedBaseVertex = NULL;
PFNGLDRAWRANGEELEMENTSPROC glad_glDrawRangeElements = NULL;
PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC glad_glDrawRangeElementsBaseVertex = NULL;
PFNGLENABLEPROC glad_glEnable = NULL;
PFNGLENABLEVERTEXATTRIBARRAYPROC glad_glEnableVertexAttribArray = NULL;
PFNGLENABLEIPROC glad_glEnablei = NULL;
PFNGLENDCONDITIONALRENDERPROC glad_glEndConditionalRender = NULL;
PFNGLENDQUERYPROC glad_glEndQuery = NULL;
PFNGLENDTRANSFORMFEEDBACKPROC glad_glEndTransformFeedback = NULL;
PFNGLFENCESYNCPROC glad_glFenceSync = NULL;
PFNGLFINISHPROC glad_glFinish = NULL;
PFNGLFLUSHPROC glad_glFlush = NULL;
PFNGLFLUSHMAPPEDBUFFERRANGEPROC glad_glFlushMappedBufferRange = NULL;
PFNGLFRAMEBUFFERRENDERBUFFERPROC glad_glFramebufferRenderbuffer = NULL;
PFNGLFRAMEBUFFERTEXTUREPROC glad_glFramebufferTexture = NULL;
PFNGLFRAMEBUFFERTEXTURE1DPROC glad_glFramebufferTexture1D = NULL;
PFNGLFRAMEBUFFERTEXTURE2DPROC glad_glFramebufferTexture2D = NULL;
PFNGLFRAMEBUFFERTEXTURE3DPROC glad_glFramebufferTexture3D = NULL;
PFNGLFRAMEBUFFERTEXTURELAYERPROC glad_glFramebufferTextureLayer = NULL;
PFNGLFRONTFACEPROC glad_glFrontFace = NULL;
PFNGLGENBUFFERSPROC glad_glGenBuffers = NULL;
PFNGLGENFRAMEBUFFERSPROC glad_glGenFramebuffers = NULL;
PFNGLGENQUERIESPROC glad_glGenQueries = NULL;
PFNGLGENRENDERBUFFERSPROC glad_glGenRenderbuffers = NULL;
PFNGLGENSAMPLERSPROC glad_glGenSamplers = NULL;
PFNGLGENTEXTURESPROC glad_glGenTextures = NULL;
PFNGLGENVERTEXARRAYSPROC glad_glGenVertexArrays = NULL;
PFNGLGENERATEMIPMAPPROC glad_glGenerateMipmap = NULL;
PFNGLGETACTIVEATTRIBPROC glad_glGetActiveAttrib = NULL;
PFNGLGETACTIVEUNIFORMPROC glad_glGetActiveUniform = NULL;
PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC glad_glGetActiveUniformBlockName = NULL;
PFNGLGETACTIVEUNIFORMBLOCKIVPROC glad_glGetActiveUniformBlockiv = NULL;
PFNGLGETACTIVEUNIFORMNAMEPROC glad_glGetActiveUniformName = NULL;
PFNGLGETACTIVEUNIFORMSIVPROC glad_glGetActiveUniformsiv = NULL;
PFNGLGETATTACHEDSHADERSPROC glad_glGetAttachedShaders = NULL;
PFNGLGETATTRIBLOCATIONPROC glad_glGetAttribLocation = NULL;
PFNGLGETBOOLEANI_VPROC glad_glGetBooleani_v = NULL;
PFNGLGETBOOLEANVPROC glad_glGetBooleanv = NULL;
PFNGLGETBUFFERPARAMETERI64VPROC glad_glGetBufferParameteri64v = NULL;
PFNGLGETBUFFERPARAMETERIVPROC glad_glGetBufferParameteriv = NULL;
PFNGLGETBUFFERPOINTERVPROC glad_glGetBufferPointerv = NULL;
PFNGLGETBUFFERSUBDATAPROC glad_glGetBufferSubData = NULL;
PFNGLGETCOMPRESSEDTEXIMAGEPROC glad_glGetCompressedTexImage = NULL;
PFNGLGETDOUBLEVPROC glad_glGetDoublev = NULL;
PFNGLGETERRORPROC glad_glGetError = NULL;
PFNGLGETFLOATVPROC glad_glGetFloatv = NULL;
PFNGLGETFRAGDATAINDEXPROC glad_glGetFragDataIndex = NULL;
PFNGLGETFRAGDATALOCATIONPROC glad_glGetFragDataLocation = NULL;
PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC glad_glGetFramebufferAttachmentParameteriv = NULL;
PFNGLGETINTEGER64I_VPROC glad_glGetInteger64i_v = NULL;
PFNGLGETINTEGER64VPROC glad_glGetInteger64v = NULL;
PFNGLGETINTEGERI_VPROC glad_glGetIntegeri_v = NULL;
PFNGLGETINTEGERVPROC glad_glGetIntegerv = NULL;
PFNGLGETMULTISAMPLEFVPROC glad_glGetMultisamplefv = NULL;
PFNGLGETPROGRAMINFOLOGPROC glad_glGetProgramInfoLog = NULL;
PFNGLGETPROGRAMIVPROC glad_glGetProgramiv = NULL;
PFNGLGETQUERYOBJECTI64VPROC glad_glGetQueryObjecti64v = NULL;
PFNGLGETQUERYOBJECTIVPROC glad_glGetQueryObjectiv = NULL;
PFNGLGETQUERYOBJECTUI64VPROC glad_glGetQueryObjectui64v = NULL;
PFNGLGETQUERYOBJECTUIVPROC glad_glGetQueryObjectuiv = NULL;
PFNGLGETQUERYIVPROC glad_glGetQueryiv = NULL;
PFNGLGETRENDERBUFFERPARAMETERIVPROC glad_glGetRenderbufferParameteriv = NULL;
PFNGLGETSAMPLERPARAMETERIIVPROC glad_glGetSamplerParameterIiv = NULL;
PFNGLGETSAMPLERPARAMETERIUIVPROC glad_glGetSamplerParameterIuiv = NULL;
PFNGLGETSAMPLERPARAMETERFVPROC glad_glGetSamplerParameterfv = NULL;
PFNGLGETSAMPLERPARAMETERIVPROC glad_glGetSamplerParameteriv = NULL;
PFNGLGETSHADERINFOLOGPROC glad_glGetShaderInfoLog = NULL;
PFNGLGETSHADERSOURCEPROC glad_glGetShaderSource = NULL;
PFNGLGETSHADERIVPROC glad_glGetShaderiv = NULL;
PFNGLGETSTRINGPROC glad_glGetString = NULL;
PFNGLGETSTRINGIPROC glad_glGetStringi = NULL;
PFNGLGETSYNCIVPROC glad_glGetSynciv = NULL;
PFNGLGETTEXIMAGEPROC glad_glGetTexImage = NULL;
PFNGLGETTEXLEVELPARAMETERFVPROC glad_glGetTexLevelParameterfv = NULL;
PFNGLGETTEXLEVELPARAMETERIVPROC glad_glGetTexLevelParameteriv = NULL;
PFNGLGETTEXPARAMETERIIVPROC glad_glGetTexParameterIiv = NULL;
PFNGLGETTEXPARAMETERIUIVPROC glad_glGetTexParameterIuiv = NULL;
PFNGLGETTEXPARAMETERFVPROC glad_glGetTexParameterfv = NULL;
PFNGLGETTEXPARAMETERIVPROC glad_glGetTexParameteriv = NULL;
PFNGLGETTRANSFORMFEEDBACKVARYINGPROC glad_glGetTransformFeedbackVarying = NULL;
PFNGLGETUNIFORMBLOCKINDEXPROC glad_glGetUniformBlockIndex = NULL;
PFNGLGETUNIFORMINDICESPROC glad_glGetUniformIndices = NULL;
PFNGLGETUNIFORMLOCATIONPROC glad_glGetUniformLocation = NULL;
PFNGLGETUNIFORMFVPROC glad_glGetUniformfv = NULL;
PFNGLGETUNIFORMIVPROC glad_glGetUniformiv = NULL;
PFNGLGETUNIFORMUIVPROC glad_glGetUniformuiv = NULL;
PFNGLGETVERTEXATTRIBIIVPROC glad_glGetVertexAttribIiv = NULL;
PFNGLGETVERTEXATTRIBIUIVPROC glad_glGetVertexAttribIuiv = NULL;
PFNGLGETVERTEXATTRIBPOINTERVPROC glad_glGetVertexAttribPointerv = NULL;
PFNGLGETVERTEXATTRIBDVPROC glad_glGetVertexAttribdv = NULL;
PFNGLGETVERTEXATTRIBFVPROC glad_glGetVertexAttribfv = NULL;
PFNGLGETVERTEXATTRIBIVPROC glad_glGetVertexAttribiv = NULL;
PFNGLHINTPROC glad_glHint = NULL;
PFNGLISBUFFERPROC glad_glIsBuffer = NULL;
PFNGLISENABLEDPROC glad_glIsEnabled = NULL;
PFNGLISENABLEDIPROC glad_glIsEnabledi = NULL;
PFNGLISFRAMEBUFFERPROC glad_glIsFramebuffer = NULL;
PFNGLISPROGRAMPROC glad_glIsProgram = NULL;
PFNGLISQUERYPROC glad_glIsQuery = NULL;
PFNGLISRENDERBUFFERPROC glad_glIsRenderbuffer = NULL;
PFNGLISSAMPLERPROC glad_glIsSampler = NULL;
PFNGLISSHADERPROC glad_glIsShader = NULL;
PFNGLISSYNCPROC glad_glIsSync = NULL;
PFNGLISTEXTUREPROC glad_glIsTexture = NULL;
PFNGLISVERTEXARRAYPROC glad_glIsVertexArray = NULL;
PFNGLLINEWIDTHPROC glad_glLineWidth = NULL;
PFNGLLINKPROGRAMPROC glad_glLinkProgram = NULL;
PFNGLLOGICOPPROC glad_glLogicOp = NULL;
PFNGLMAPBUFFERPROC glad_glMapBuffer = NULL;
PFNGLMAPBUFFERRANGEPROC glad_glMapBufferRange = NULL;
PFNGLMULTIDRAWARRAYSPROC glad_glMultiDrawArrays = NULL;
PFNGLMULTIDRAWELEMENTSPROC glad_glMultiDrawElements = NULL;
PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC glad_glMultiDrawElementsBaseVertex = NULL;
PFNGLMULTITEXCOORDP1UIPROC glad_glMultiTexCoordP1ui = NULL;
PFNGLMULTITEXCOORDP1UIVPROC glad_glMultiTexCoordP1uiv = NULL;
PFNGLMULTITEXCOORDP2UIPROC glad_glMultiTexCoordP2ui = NULL;
PFNGLMULTITEXCOORDP2UIVPROC glad_glMultiTexCoordP2uiv = NULL;
PFNGLMULTITEXCOORDP3UIPROC glad_glMultiTexCoordP3ui = NULL;
PFNGLMULTITEXCOORDP3UIVPROC glad_glMultiTexCoordP3uiv = NULL;
PFNGLMULTITEXCOORDP4UIPROC glad_glMultiTexCoordP4ui = NULL;
PFNGLMULTITEXCOORDP4UIVPROC glad_glMultiTexCoordP4uiv = NULL;
PFNGLNORMALP3UIPROC glad_glNormalP3ui = NULL;
PFNGLNORMALP3UIVPROC glad_glNormalP3uiv = NULL;
PFNGLPIXELSTOREFPROC glad_glPixelStoref = NULL;
PFNGLPIXELSTOREIPROC glad_glPixelStorei = NULL;
PFNGLPOINTPARAMETERFPROC glad_glPointParameterf = NULL;
PFNGLPOINTPARAMETERFVPROC glad_glPointParameterfv = NULL;
PFNGLPOINTPARAMETERIPROC glad_glPointParameteri = NULL;
PFNGLPOINTPARAMETERIVPROC glad_glPointParameteriv = NULL;
PFNGLPOINTSIZEPROC glad_glPointSize = NULL;
PFNGLPOLYGONMODEPROC glad_glPolygonMode = NULL;
PFNGLPOLYGONOFFSETPROC glad_glPolygonOffset = NULL;
PFNGLPRIMITIVERESTARTINDEXPROC glad_glPrimitiveRestartIndex = NULL;
PFNGLPROVOKINGVERTEXPROC glad_glProvokingVertex = NULL;
PFNGLQUERYCOUNTERPROC glad_glQueryCounter = NULL;
PFNGLREADBUFFERPROC glad_glReadBuffer = NULL;
PFNGLREADPIXELSPROC glad_glReadPixels = NULL;
PFNGLRENDERBUFFERSTORAGEPROC glad_glRenderbufferStorage = NULL;
PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC glad_glRenderbufferStorageMultisample = NULL;
PFNGLSAMPLECOVERAGEPROC glad_glSampleCoverage = NULL;
PFNGLSAMPLEMASKIPROC glad_glSampleMaski = NULL;
PFNGLSAMPLERPARAMETERIIVPROC glad_glSamplerParameterIiv = NULL;
PFNGLSAMPLERPARAMETERIUIVPROC glad_glSamplerParameterIuiv = NULL;
PFNGLSAMPLERPARAMETERFPROC glad_glSamplerParameterf = NULL;
PFNGLSAMPLERPARAMETERFVPROC glad_glSamplerParameterfv = NULL;
PFNGLSAMPLERPARAMETERIPROC glad_glSamplerParameteri = NULL;
PFNGLSAMPLERPARAMETERIVPROC glad_glSamplerParameteriv = NULL;
PFNGLSCISSORPROC glad_glScissor = NULL;
PFNGLSECONDARYCOLORP3UIPROC glad_glSecondaryColorP3ui = NULL;
PFNGLSECONDARYCOLORP3UIVPROC glad_glSecondaryColorP3uiv = NULL;
PFNGLSHADERSOURCEPROC glad_glShaderSource = NULL;
PFNGLSTENCILFUNCPROC glad_glStencilFunc = NULL;
PFNGLSTENCILFUNCSEPARATEPROC glad_glStencilFuncSeparate = NULL;
PFNGLSTENCILMASKPROC glad_glStencilMask = NULL;
PFNGLSTENCILMASKSEPARATEPROC glad_glStencilMaskSeparate = NULL;
PFNGLSTENCILOPPROC glad_glStencilOp = NULL;
PFNGLSTENCILOPSEPARATEPROC glad_glStencilOpSeparate = NULL;
PFNGLTEXBUFFERPROC glad_glTexBuffer = NULL;
PFNGLTEXCOORDP1UIPROC glad_glTexCoordP1ui = NULL;
PFNGLTEXCOORDP1UIVPROC glad_glTexCoordP1uiv = NULL;
PFNGLTEXCOORDP2UIPROC glad_glTexCoordP2ui = NULL;
PFNGLTEXCOORDP2UIVPROC glad_glTexCoordP2uiv = NULL;
PFNGLTEXCOORDP3UIPROC glad_glTexCoordP3ui = NULL;
PFNGLTEXCOORDP3UIVPROC glad_glTexCoordP3uiv = NULL;
PFNGLTEXCOORDP4UIPROC glad_glTexCoordP4ui = NULL;
PFNGLTEXCOORDP4UIVPROC glad_glTexCoordP4uiv = NULL;
PFNGLTEXIMAGE1DPROC glad_glTexImage1D = NULL;
PFNGLTEXIMAGE2DPROC glad_glTexImage2D = NULL;
PFNGLTEXIMAGE2DMULTISAMPLEPROC glad_glTexImage2DMultisample = NULL;
PFNGLTEXIMAGE3DPROC glad_glTexImage3D = NULL;
PFNGLTEXIMAGE3DMULTISAMPLEPROC glad_glTexImage3DMultisample = NULL;
PFNGLTEXPARAMETERIIVPROC glad_glTexParameterIiv = NULL;
PFNGLTEXPARAMETERIUIVPROC glad_glTexParameterIuiv = NULL;
PFNGLTEXPARAMETERFPROC glad_glTexParameterf = NULL;
PFNGLTEXPARAMETERFVPROC glad_glTexParameterfv = NULL;
PFNGLTEXPARAMETERIPROC glad_glTexParameteri = NULL;
PFNGLTEXPARAMETERIVPROC glad_glTexParameteriv = NULL;
PFNGLTEXSUBIMAGE1DPROC glad_glTexSubImage1D = NULL;
PFNGLTEXSUBIMAGE2DPROC glad_glTexSubImage2D = NULL;
PFNGLTEXSUBIMAGE3DPROC glad_glTexSubImage3D = NULL;
PFNGLTRANSFORMFEEDBACKVARYINGSPROC glad_glTransformFeedbackVaryings = NULL;
PFNGLUNIFORM1FPROC glad_glUniform1f = NULL;
PFNGLUNIFORM1FVPROC glad_glUniform1fv = NULL;
PFNGLUNIFORM1IPROC glad_glUniform1i = NULL;
PFNGLUNIFORM1IVPROC glad_glUniform1iv = NULL;
PFNGLUNIFORM1UIPROC glad_glUniform1ui = NULL;
PFNGLUNIFORM1UIVPROC glad_glUniform1uiv = NULL;
PFNGLUNIFORM2FPROC glad_glUniform2f = NULL;
PFNGLUNIFORM2FVPROC glad_glUniform2fv = NULL;
PFNGLUNIFORM2IPROC glad_glUniform2i = NULL;
PFNGLUNIFORM2IVPROC glad_glUniform2iv = NULL;
PFNGLUNIFORM2UIPROC glad_glUniform2ui = NULL;
PFNGLUNIFORM2UIVPROC glad_glUniform2uiv = NULL;
PFNGLUNIFORM3FPROC glad_glUniform3f = NULL;
PFNGLUNIFORM3FVPROC glad_glUniform3fv = NULL;
PFNGLUNIFORM3IPROC glad_glUniform3i = NULL;
PFNGLUNIFORM3IVPROC glad_glUniform3iv = NULL;
PFNGLUNIFORM3UIPROC glad_glUniform3ui = NULL;
PFNGLUNIFORM3UIVPROC glad_glUniform3uiv = NULL;
PFNGLUNIFORM4FPROC glad_glUniform4f = NULL;
PFNGLUNIFORM4FVPROC glad_glUniform4fv = NULL;
PFNGLUNIFORM4IPROC glad_glUniform4i = NULL;
PFNGLUNIFORM4IVPROC glad_glUniform4iv = NULL;
PFNGLUNIFORM4UIPROC glad_glUniform4ui = NULL;
PFNGLUNIFORM4UIVPROC glad_glUniform4uiv = NULL;
PFNGLUNIFORMBLOCKBINDINGPROC glad_glUniformBlockBinding = NULL;
PFNGLUNIFORMMATRIX2FVPROC glad_glUniformMatrix2fv = NULL;
PFNGLUNIFORMMATRIX2X3FVPROC glad_glUniformMatrix2x3fv = NULL;
PFNGLUNIFORMMATRIX2X4FVPROC glad_glUniformMatrix2x4fv = NULL;
PFNGLUNIFORMMATRIX3FVPROC glad_glUniformMatrix3fv = NULL;
PFNGLUNIFORMMATRIX3X2FVPROC glad_glUniformMatrix3x2fv = NULL;
PFNGLUNIFORMMATRIX3X4FVPROC glad_glUniformMatrix3x4fv = NULL;
PFNGLUNIFORMMATRIX4FVPROC glad_glUniformMatrix4fv = NULL;
PFNGLUNIFORMMATRIX4X2FVPROC glad_glUniformMatrix4x2fv = NULL;
PFNGLUNIFORMMATRIX4X3FVPROC glad_glUniformMatrix4x3fv = NULL;
PFNGLUNMAPBUFFERPROC glad_glUnmapBuffer = NULL;
PFNGLUSEPROGRAMPROC glad_glUseProgram = NULL;
PFNGLVALIDATEPROGRAMPROC glad_glValidateProgram = NULL;
PFNGLVERTEXATTRIB1DPROC glad_glVertexAttrib1d = NULL;
PFNGLVERTEXATTRIB1DVPROC glad_glVertexAttrib1dv = NULL;
PFNGLVERTEXATTRIB1FPROC glad_glVertexAttrib1f = NULL;
PFNGLVERTEXATTRIB1FVPROC glad_glVertexAttrib1fv = NULL;
PFNGLVERTEXATTRIB1SPROC glad_glVertexAttrib1s = NULL;
PFNGLVERTEXATTRIB1SVPROC glad_glVertexAttrib1sv = NULL;
PFNGLVERTEXATTRIB2DPROC glad_glVertexAttrib2d = NULL;
PFNGLVERTEXATTRIB2DVPROC glad_glVertexAttrib2dv = NULL;
PFNGLVERTEXATTRIB2FPROC glad_glVertexAttrib2f = NULL;
PFNGLVERTEXATTRIB2FVPROC glad_glVertexAttrib2fv = NULL;
PFNGLVERTEXATTRIB2SPROC glad_glVertexAttrib2s = NULL;
PFNGLVERTEXATTRIB2SVPROC glad_glVertexAttrib2sv = NULL;
PFNGLVERTEXATTRIB3DPROC glad_glVertexAttrib3d = NULL;
PFNGLVERTEXATTRIB3DVPROC glad_glVertexAttrib3dv = NULL;
PFNGLVERTEXATTRIB3FPROC glad_glVertexAttrib3f = NULL;
PFNGLVERTEXATTRIB3FVPROC glad_glVertexAttrib3fv = NULL;
PFNGLVERTEXATTRIB3SPROC glad_glVertexAttrib3s = NULL;
PFNGLVERTEXATTRIB3SVPROC glad_glVertexAttrib3sv = NULL;
PFNGLVERTEXATTRIB4NBVPROC glad_glVertexAttrib4Nbv = NULL;
PFNGLVERTEXATTRIB4NIVPROC glad_glVertexAttrib4Niv = NULL;
PFNGLVERTEXATTRIB4NSVPROC glad_glVertexAttrib4Nsv = NULL;
PFNGLVERTEXATTRIB4NUBPROC glad_glVertexAttrib4Nub = NULL;
PFNGLVERTEXATTRIB4NUBVPROC glad_glVertexAttrib4Nubv = NULL;
PFNGLVERTEXATTRIB4NUIVPROC glad_glVertexAttrib4Nuiv = NULL;
PFNGLVERTEXATTRIB4NUSVPROC glad_glVertexAttrib4Nusv = NULL;
PFNGLVERTEXATTRIB4BVPROC glad_glVertexAttrib4bv = NULL;
PFNGLVERTEXATTRIB4DPROC glad_glVertexAttrib4d = NULL;
PFNGLVERTEXATTRIB4DVPROC glad_glVertexAttrib4dv = NULL;
PFNGLVERTEXATTRIB4FPROC glad_glVertexAttrib4f = NULL;
PFNGLVERTEXATTRIB4FVPROC glad_glVertexAttrib4fv = NULL;
PFNGLVERTEXATTRIB4IVPROC glad_glVertexAttrib4iv = NULL;
PFNGLVERTEXATTRIB4SPROC glad_glVertexAttrib4s = NULL;
PFNGLVERTEXATTRIB4SVPROC glad_glVertexAttrib4sv = NULL;
PFNGLVERTEXATTRIB4UBVPROC glad_glVertexAttrib4ubv = NULL;
PFNGLVERTEXATTRIB4UIVPROC glad_glVertexAttrib4uiv = NULL;
PFNGLVERTEXATTRIB4USVPROC glad_glVertexAttrib4usv = NULL;
PFNGLVERTEXATTRIBDIVISORPROC glad_glVertexAttribDivisor = NULL;
PFNGLVERTEXATTRIBI1IPROC glad_glVertexAttribI1i = NULL;
PFNGLVERTEXATTRIBI1IVPROC glad_glVertexAttribI1iv = NULL;
PFNGLVERTEXATTRIBI1UIPROC glad_glVertexAttribI1ui = NULL;
PFNGLVERTEXATTRIBI1UIVPROC glad_glVertexAttribI1uiv = NULL;
PFNGLVERTEXATTRIBI2IPROC glad_glVertexAttribI2i = NULL;
PFNGLVERTEXATTRIBI2IVPROC glad_glVertexAttribI2iv = NULL;
PFNGLVERTEXATTRIBI2UIPROC glad_glVertexAttribI2ui = NULL;
PFNGLVERTEXATTRIBI2UIVPROC glad_glVertexAttribI2uiv = NULL;
PFNGLVERTEXATTRIBI3IPROC glad_glVertexAttribI3i = NULL;
PFNGLVERTEXATTRIBI3IVPROC glad_glVertexAttribI3iv = NULL;
PFNGLVERTEXATTRIBI3UIPROC glad_glVertexAttribI3ui = NULL;
PFNGLVERTEXATTRIBI3UIVPROC glad_glVertexAttribI3uiv = NULL;
PFNGLVERTEXATTRIBI4BVPROC glad_glVertexAttribI4bv = NULL;
PFNGLVERTEXATTRIBI4IPROC glad_glVertexAttribI4i = NULL;
PFNGLVERTEXATTRIBI4IVPROC glad_glVertexAttribI4iv = NULL;
PFNGLVERTEXATTRIBI4SVPROC glad_glVertexAttribI4sv = NULL;
PFNGLVERTEXATTRIBI4UBVPROC glad_glVertexAttribI4ubv = NULL;
PFNGLVERTEXATTRIBI4UIPROC glad_glVertexAttribI4ui = NULL;
PFNGLVERTEXATTRIBI4UIVPROC glad_glVertexAttribI4uiv = NULL;
PFNGLVERTEXATTRIBI4USVPROC glad_glVertexAttribI4usv = NULL;
PFNGLVERTEXATTRIBIPOINTERPROC glad_glVertexAttribIPointer = NULL;
PFNGLVERTEXATTRIBP1UIPROC glad_glVertexAttribP1ui = NULL;
PFNGLVERTEXATTRIBP1UIVPROC glad_glVertexAttribP1uiv = NULL;
PFNGLVERTEXATTRIBP2UIPROC glad_glVertexAttribP2ui = NULL;
PFNGLVERTEXATTRIBP2UIVPROC glad_glVertexAttribP2uiv = NULL;
PFNGLVERTEXATTRIBP3UIPROC glad_glVertexAttribP3ui = NULL;
PFNGLVERTEXATTRIBP3UIVPROC glad_glVertexAttribP3uiv = NULL;
PFNGLVERTEXATTRIBP4UIPROC glad_glVertexAttribP4ui = NULL;
PFNGLVERTEXATTRIBP4UIVPROC glad_glVertexAttribP4uiv = NULL;
PFNGLVERTEXATTRIBPOINTERPROC glad_glVertexAttribPointer = NULL;
PFNGLVERTEXP2UIPROC glad_glVertexP2ui = NULL;
PFNGLVERTEXP2UIVPROC glad_glVertexP2uiv = NULL;
PFNGLVERTEXP3UIPROC glad_glVertexP3ui = NULL;
PFNGLVERTEXP3UIVPROC glad_glVertexP3uiv = NULL;
PFNGLVERTEXP4UIPROC glad_glVertexP4ui = NULL;
PFNGLVERTEXP4UIVPROC glad_glVertexP4uiv = NULL;
PFNGLVIEWPORTPROC glad_glViewport = NULL;
PFNGLWAITSYNCPROC glad_glWaitSync = NULL;
static void load_GL_VERSION_1_0(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_0) return;
glad_glCullFace = (PFNGLCULLFACEPROC)load("glCullFace");
glad_glFrontFace = (PFNGLFRONTFACEPROC)load("glFrontFace");
glad_glHint = (PFNGLHINTPROC)load("glHint");
glad_glLineWidth = (PFNGLLINEWIDTHPROC)load("glLineWidth");
glad_glPointSize = (PFNGLPOINTSIZEPROC)load("glPointSize");
glad_glPolygonMode = (PFNGLPOLYGONMODEPROC)load("glPolygonMode");
glad_glScissor = (PFNGLSCISSORPROC)load("glScissor");
glad_glTexParameterf = (PFNGLTEXPARAMETERFPROC)load("glTexParameterf");
glad_glTexParameterfv = (PFNGLTEXPARAMETERFVPROC)load("glTexParameterfv");
glad_glTexParameteri = (PFNGLTEXPARAMETERIPROC)load("glTexParameteri");
glad_glTexParameteriv = (PFNGLTEXPARAMETERIVPROC)load("glTexParameteriv");
glad_glTexImage1D = (PFNGLTEXIMAGE1DPROC)load("glTexImage1D");
glad_glTexImage2D = (PFNGLTEXIMAGE2DPROC)load("glTexImage2D");
glad_glDrawBuffer = (PFNGLDRAWBUFFERPROC)load("glDrawBuffer");
glad_glClear = (PFNGLCLEARPROC)load("glClear");
glad_glClearColor = (PFNGLCLEARCOLORPROC)load("glClearColor");
glad_glClearStencil = (PFNGLCLEARSTENCILPROC)load("glClearStencil");
glad_glClearDepth = (PFNGLCLEARDEPTHPROC)load("glClearDepth");
glad_glStencilMask = (PFNGLSTENCILMASKPROC)load("glStencilMask");
glad_glColorMask = (PFNGLCOLORMASKPROC)load("glColorMask");
glad_glDepthMask = (PFNGLDEPTHMASKPROC)load("glDepthMask");
glad_glDisable = (PFNGLDISABLEPROC)load("glDisable");
glad_glEnable = (PFNGLENABLEPROC)load("glEnable");
glad_glFinish = (PFNGLFINISHPROC)load("glFinish");
glad_glFlush = (PFNGLFLUSHPROC)load("glFlush");
glad_glBlendFunc = (PFNGLBLENDFUNCPROC)load("glBlendFunc");
glad_glLogicOp = (PFNGLLOGICOPPROC)load("glLogicOp");
glad_glStencilFunc = (PFNGLSTENCILFUNCPROC)load("glStencilFunc");
glad_glStencilOp = (PFNGLSTENCILOPPROC)load("glStencilOp");
glad_glDepthFunc = (PFNGLDEPTHFUNCPROC)load("glDepthFunc");
glad_glPixelStoref = (PFNGLPIXELSTOREFPROC)load("glPixelStoref");
glad_glPixelStorei = (PFNGLPIXELSTOREIPROC)load("glPixelStorei");
glad_glReadBuffer = (PFNGLREADBUFFERPROC)load("glReadBuffer");
glad_glReadPixels = (PFNGLREADPIXELSPROC)load("glReadPixels");
glad_glGetBooleanv = (PFNGLGETBOOLEANVPROC)load("glGetBooleanv");
glad_glGetDoublev = (PFNGLGETDOUBLEVPROC)load("glGetDoublev");
glad_glGetError = (PFNGLGETERRORPROC)load("glGetError");
glad_glGetFloatv = (PFNGLGETFLOATVPROC)load("glGetFloatv");
glad_glGetIntegerv = (PFNGLGETINTEGERVPROC)load("glGetIntegerv");
glad_glGetString = (PFNGLGETSTRINGPROC)load("glGetString");
glad_glGetTexImage = (PFNGLGETTEXIMAGEPROC)load("glGetTexImage");
glad_glGetTexParameterfv = (PFNGLGETTEXPARAMETERFVPROC)load("glGetTexParameterfv");
glad_glGetTexParameteriv = (PFNGLGETTEXPARAMETERIVPROC)load("glGetTexParameteriv");
glad_glGetTexLevelParameterfv = (PFNGLGETTEXLEVELPARAMETERFVPROC)load("glGetTexLevelParameterfv");
glad_glGetTexLevelParameteriv = (PFNGLGETTEXLEVELPARAMETERIVPROC)load("glGetTexLevelParameteriv");
glad_glIsEnabled = (PFNGLISENABLEDPROC)load("glIsEnabled");
glad_glDepthRange = (PFNGLDEPTHRANGEPROC)load("glDepthRange");
glad_glViewport = (PFNGLVIEWPORTPROC)load("glViewport");
}
static void load_GL_VERSION_1_1(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_1) return;
glad_glDrawArrays = (PFNGLDRAWARRAYSPROC)load("glDrawArrays");
glad_glDrawElements = (PFNGLDRAWELEMENTSPROC)load("glDrawElements");
glad_glPolygonOffset = (PFNGLPOLYGONOFFSETPROC)load("glPolygonOffset");
glad_glCopyTexImage1D = (PFNGLCOPYTEXIMAGE1DPROC)load("glCopyTexImage1D");
glad_glCopyTexImage2D = (PFNGLCOPYTEXIMAGE2DPROC)load("glCopyTexImage2D");
glad_glCopyTexSubImage1D = (PFNGLCOPYTEXSUBIMAGE1DPROC)load("glCopyTexSubImage1D");
glad_glCopyTexSubImage2D = (PFNGLCOPYTEXSUBIMAGE2DPROC)load("glCopyTexSubImage2D");
glad_glTexSubImage1D = (PFNGLTEXSUBIMAGE1DPROC)load("glTexSubImage1D");
glad_glTexSubImage2D = (PFNGLTEXSUBIMAGE2DPROC)load("glTexSubImage2D");
glad_glBindTexture = (PFNGLBINDTEXTUREPROC)load("glBindTexture");
glad_glDeleteTextures = (PFNGLDELETETEXTURESPROC)load("glDeleteTextures");
glad_glGenTextures = (PFNGLGENTEXTURESPROC)load("glGenTextures");
glad_glIsTexture = (PFNGLISTEXTUREPROC)load("glIsTexture");
}
static void load_GL_VERSION_1_2(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_2) return;
glad_glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)load("glDrawRangeElements");
glad_glTexImage3D = (PFNGLTEXIMAGE3DPROC)load("glTexImage3D");
glad_glTexSubImage3D = (PFNGLTEXSUBIMAGE3DPROC)load("glTexSubImage3D");
glad_glCopyTexSubImage3D = (PFNGLCOPYTEXSUBIMAGE3DPROC)load("glCopyTexSubImage3D");
}
static void load_GL_VERSION_1_3(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_3) return;
glad_glActiveTexture = (PFNGLACTIVETEXTUREPROC)load("glActiveTexture");
glad_glSampleCoverage = (PFNGLSAMPLECOVERAGEPROC)load("glSampleCoverage");
glad_glCompressedTexImage3D = (PFNGLCOMPRESSEDTEXIMAGE3DPROC)load("glCompressedTexImage3D");
glad_glCompressedTexImage2D = (PFNGLCOMPRESSEDTEXIMAGE2DPROC)load("glCompressedTexImage2D");
glad_glCompressedTexImage1D = (PFNGLCOMPRESSEDTEXIMAGE1DPROC)load("glCompressedTexImage1D");
glad_glCompressedTexSubImage3D = (PFNGLCOMPRESSEDTEXSUBIMAGE3DPROC)load("glCompressedTexSubImage3D");
glad_glCompressedTexSubImage2D = (PFNGLCOMPRESSEDTEXSUBIMAGE2DPROC)load("glCompressedTexSubImage2D");
glad_glCompressedTexSubImage1D = (PFNGLCOMPRESSEDTEXSUBIMAGE1DPROC)load("glCompressedTexSubImage1D");
glad_glGetCompressedTexImage = (PFNGLGETCOMPRESSEDTEXIMAGEPROC)load("glGetCompressedTexImage");
}
static void load_GL_VERSION_1_4(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_4) return;
glad_glBlendFuncSeparate = (PFNGLBLENDFUNCSEPARATEPROC)load("glBlendFuncSeparate");
glad_glMultiDrawArrays = (PFNGLMULTIDRAWARRAYSPROC)load("glMultiDrawArrays");
glad_glMultiDrawElements = (PFNGLMULTIDRAWELEMENTSPROC)load("glMultiDrawElements");
glad_glPointParameterf = (PFNGLPOINTPARAMETERFPROC)load("glPointParameterf");
glad_glPointParameterfv = (PFNGLPOINTPARAMETERFVPROC)load("glPointParameterfv");
glad_glPointParameteri = (PFNGLPOINTPARAMETERIPROC)load("glPointParameteri");
glad_glPointParameteriv = (PFNGLPOINTPARAMETERIVPROC)load("glPointParameteriv");
glad_glBlendColor = (PFNGLBLENDCOLORPROC)load("glBlendColor");
glad_glBlendEquation = (PFNGLBLENDEQUATIONPROC)load("glBlendEquation");
}
static void load_GL_VERSION_1_5(GLADloadproc load) {
if(!GLAD_GL_VERSION_1_5) return;
glad_glGenQueries = (PFNGLGENQUERIESPROC)load("glGenQueries");
glad_glDeleteQueries = (PFNGLDELETEQUERIESPROC)load("glDeleteQueries");
glad_glIsQuery = (PFNGLISQUERYPROC)load("glIsQuery");
glad_glBeginQuery = (PFNGLBEGINQUERYPROC)load("glBeginQuery");
glad_glEndQuery = (PFNGLENDQUERYPROC)load("glEndQuery");
glad_glGetQueryiv = (PFNGLGETQUERYIVPROC)load("glGetQueryiv");
glad_glGetQueryObjectiv = (PFNGLGETQUERYOBJECTIVPROC)load("glGetQueryObjectiv");
glad_glGetQueryObjectuiv = (PFNGLGETQUERYOBJECTUIVPROC)load("glGetQueryObjectuiv");
glad_glBindBuffer = (PFNGLBINDBUFFERPROC)load("glBindBuffer");
glad_glDeleteBuffers = (PFNGLDELETEBUFFERSPROC)load("glDeleteBuffers");
glad_glGenBuffers = (PFNGLGENBUFFERSPROC)load("glGenBuffers");
glad_glIsBuffer = (PFNGLISBUFFERPROC)load("glIsBuffer");
glad_glBufferData = (PFNGLBUFFERDATAPROC)load("glBufferData");
glad_glBufferSubData = (PFNGLBUFFERSUBDATAPROC)load("glBufferSubData");
glad_glGetBufferSubData = (PFNGLGETBUFFERSUBDATAPROC)load("glGetBufferSubData");
glad_glMapBuffer = (PFNGLMAPBUFFERPROC)load("glMapBuffer");
glad_glUnmapBuffer = (PFNGLUNMAPBUFFERPROC)load("glUnmapBuffer");
glad_glGetBufferParameteriv = (PFNGLGETBUFFERPARAMETERIVPROC)load("glGetBufferParameteriv");
glad_glGetBufferPointerv = (PFNGLGETBUFFERPOINTERVPROC)load("glGetBufferPointerv");
}
static void load_GL_VERSION_2_0(GLADloadproc load) {
if(!GLAD_GL_VERSION_2_0) return;
glad_glBlendEquationSeparate = (PFNGLBLENDEQUATIONSEPARATEPROC)load("glBlendEquationSeparate");
glad_glDrawBuffers = (PFNGLDRAWBUFFERSPROC)load("glDrawBuffers");
glad_glStencilOpSeparate = (PFNGLSTENCILOPSEPARATEPROC)load("glStencilOpSeparate");
glad_glStencilFuncSeparate = (PFNGLSTENCILFUNCSEPARATEPROC)load("glStencilFuncSeparate");
glad_glStencilMaskSeparate = (PFNGLSTENCILMASKSEPARATEPROC)load("glStencilMaskSeparate");
glad_glAttachShader = (PFNGLATTACHSHADERPROC)load("glAttachShader");
glad_glBindAttribLocation = (PFNGLBINDATTRIBLOCATIONPROC)load("glBindAttribLocation");
glad_glCompileShader = (PFNGLCOMPILESHADERPROC)load("glCompileShader");
glad_glCreateProgram = (PFNGLCREATEPROGRAMPROC)load("glCreateProgram");
glad_glCreateShader = (PFNGLCREATESHADERPROC)load("glCreateShader");
glad_glDeleteProgram = (PFNGLDELETEPROGRAMPROC)load("glDeleteProgram");
glad_glDeleteShader = (PFNGLDELETESHADERPROC)load("glDeleteShader");
glad_glDetachShader = (PFNGLDETACHSHADERPROC)load("glDetachShader");
glad_glDisableVertexAttribArray = (PFNGLDISABLEVERTEXATTRIBARRAYPROC)load("glDisableVertexAttribArray");
glad_glEnableVertexAttribArray = (PFNGLENABLEVERTEXATTRIBARRAYPROC)load("glEnableVertexAttribArray");
glad_glGetActiveAttrib = (PFNGLGETACTIVEATTRIBPROC)load("glGetActiveAttrib");
glad_glGetActiveUniform = (PFNGLGETACTIVEUNIFORMPROC)load("glGetActiveUniform");
glad_glGetAttachedShaders = (PFNGLGETATTACHEDSHADERSPROC)load("glGetAttachedShaders");
glad_glGetAttribLocation = (PFNGLGETATTRIBLOCATIONPROC)load("glGetAttribLocation");
glad_glGetProgramiv = (PFNGLGETPROGRAMIVPROC)load("glGetProgramiv");
glad_glGetProgramInfoLog = (PFNGLGETPROGRAMINFOLOGPROC)load("glGetProgramInfoLog");
glad_glGetShaderiv = (PFNGLGETSHADERIVPROC)load("glGetShaderiv");
glad_glGetShaderInfoLog = (PFNGLGETSHADERINFOLOGPROC)load("glGetShaderInfoLog");
glad_glGetShaderSource = (PFNGLGETSHADERSOURCEPROC)load("glGetShaderSource");
glad_glGetUniformLocation = (PFNGLGETUNIFORMLOCATIONPROC)load("glGetUniformLocation");
glad_glGetUniformfv = (PFNGLGETUNIFORMFVPROC)load("glGetUniformfv");
glad_glGetUniformiv = (PFNGLGETUNIFORMIVPROC)load("glGetUniformiv");
glad_glGetVertexAttribdv = (PFNGLGETVERTEXATTRIBDVPROC)load("glGetVertexAttribdv");
glad_glGetVertexAttribfv = (PFNGLGETVERTEXATTRIBFVPROC)load("glGetVertexAttribfv");
glad_glGetVertexAttribiv = (PFNGLGETVERTEXATTRIBIVPROC)load("glGetVertexAttribiv");
glad_glGetVertexAttribPointerv = (PFNGLGETVERTEXATTRIBPOINTERVPROC)load("glGetVertexAttribPointerv");
glad_glIsProgram = (PFNGLISPROGRAMPROC)load("glIsProgram");
glad_glIsShader = (PFNGLISSHADERPROC)load("glIsShader");
glad_glLinkProgram = (PFNGLLINKPROGRAMPROC)load("glLinkProgram");
glad_glShaderSource = (PFNGLSHADERSOURCEPROC)load("glShaderSource");
glad_glUseProgram = (PFNGLUSEPROGRAMPROC)load("glUseProgram");
glad_glUniform1f = (PFNGLUNIFORM1FPROC)load("glUniform1f");
glad_glUniform2f = (PFNGLUNIFORM2FPROC)load("glUniform2f");
glad_glUniform3f = (PFNGLUNIFORM3FPROC)load("glUniform3f");
glad_glUniform4f = (PFNGLUNIFORM4FPROC)load("glUniform4f");
glad_glUniform1i = (PFNGLUNIFORM1IPROC)load("glUniform1i");
glad_glUniform2i = (PFNGLUNIFORM2IPROC)load("glUniform2i");
glad_glUniform3i = (PFNGLUNIFORM3IPROC)load("glUniform3i");
glad_glUniform4i = (PFNGLUNIFORM4IPROC)load("glUniform4i");
glad_glUniform1fv = (PFNGLUNIFORM1FVPROC)load("glUniform1fv");
glad_glUniform2fv = (PFNGLUNIFORM2FVPROC)load("glUniform2fv");
glad_glUniform3fv = (PFNGLUNIFORM3FVPROC)load("glUniform3fv");
glad_glUniform4fv = (PFNGLUNIFORM4FVPROC)load("glUniform4fv");
glad_glUniform1iv = (PFNGLUNIFORM1IVPROC)load("glUniform1iv");
glad_glUniform2iv = (PFNGLUNIFORM2IVPROC)load("glUniform2iv");
glad_glUniform3iv = (PFNGLUNIFORM3IVPROC)load("glUniform3iv");
glad_glUniform4iv = (PFNGLUNIFORM4IVPROC)load("glUniform4iv");
glad_glUniformMatrix2fv = (PFNGLUNIFORMMATRIX2FVPROC)load("glUniformMatrix2fv");
glad_glUniformMatrix3fv = (PFNGLUNIFORMMATRIX3FVPROC)load("glUniformMatrix3fv");
glad_glUniformMatrix4fv = (PFNGLUNIFORMMATRIX4FVPROC)load("glUniformMatrix4fv");
glad_glValidateProgram = (PFNGLVALIDATEPROGRAMPROC)load("glValidateProgram");
glad_glVertexAttrib1d = (PFNGLVERTEXATTRIB1DPROC)load("glVertexAttrib1d");
glad_glVertexAttrib1dv = (PFNGLVERTEXATTRIB1DVPROC)load("glVertexAttrib1dv");
glad_glVertexAttrib1f = (PFNGLVERTEXATTRIB1FPROC)load("glVertexAttrib1f");
glad_glVertexAttrib1fv = (PFNGLVERTEXATTRIB1FVPROC)load("glVertexAttrib1fv");
glad_glVertexAttrib1s = (PFNGLVERTEXATTRIB1SPROC)load("glVertexAttrib1s");
glad_glVertexAttrib1sv = (PFNGLVERTEXATTRIB1SVPROC)load("glVertexAttrib1sv");
glad_glVertexAttrib2d = (PFNGLVERTEXATTRIB2DPROC)load("glVertexAttrib2d");
glad_glVertexAttrib2dv = (PFNGLVERTEXATTRIB2DVPROC)load("glVertexAttrib2dv");
glad_glVertexAttrib2f = (PFNGLVERTEXATTRIB2FPROC)load("glVertexAttrib2f");
glad_glVertexAttrib2fv = (PFNGLVERTEXATTRIB2FVPROC)load("glVertexAttrib2fv");
glad_glVertexAttrib2s = (PFNGLVERTEXATTRIB2SPROC)load("glVertexAttrib2s");
glad_glVertexAttrib2sv = (PFNGLVERTEXATTRIB2SVPROC)load("glVertexAttrib2sv");
glad_glVertexAttrib3d = (PFNGLVERTEXATTRIB3DPROC)load("glVertexAttrib3d");
glad_glVertexAttrib3dv = (PFNGLVERTEXATTRIB3DVPROC)load("glVertexAttrib3dv");
glad_glVertexAttrib3f = (PFNGLVERTEXATTRIB3FPROC)load("glVertexAttrib3f");
glad_glVertexAttrib3fv = (PFNGLVERTEXATTRIB3FVPROC)load("glVertexAttrib3fv");
glad_glVertexAttrib3s = (PFNGLVERTEXATTRIB3SPROC)load("glVertexAttrib3s");
glad_glVertexAttrib3sv = (PFNGLVERTEXATTRIB3SVPROC)load("glVertexAttrib3sv");
glad_glVertexAttrib4Nbv = (PFNGLVERTEXATTRIB4NBVPROC)load("glVertexAttrib4Nbv");
glad_glVertexAttrib4Niv = (PFNGLVERTEXATTRIB4NIVPROC)load("glVertexAttrib4Niv");
glad_glVertexAttrib4Nsv = (PFNGLVERTEXATTRIB4NSVPROC)load("glVertexAttrib4Nsv");
glad_glVertexAttrib4Nub = (PFNGLVERTEXATTRIB4NUBPROC)load("glVertexAttrib4Nub");
glad_glVertexAttrib4Nubv = (PFNGLVERTEXATTRIB4NUBVPROC)load("glVertexAttrib4Nubv");
glad_glVertexAttrib4Nuiv = (PFNGLVERTEXATTRIB4NUIVPROC)load("glVertexAttrib4Nuiv");
glad_glVertexAttrib4Nusv = (PFNGLVERTEXATTRIB4NUSVPROC)load("glVertexAttrib4Nusv");
glad_glVertexAttrib4bv = (PFNGLVERTEXATTRIB4BVPROC)load("glVertexAttrib4bv");
glad_glVertexAttrib4d = (PFNGLVERTEXATTRIB4DPROC)load("glVertexAttrib4d");
glad_glVertexAttrib4dv = (PFNGLVERTEXATTRIB4DVPROC)load("glVertexAttrib4dv");
glad_glVertexAttrib4f = (PFNGLVERTEXATTRIB4FPROC)load("glVertexAttrib4f");
glad_glVertexAttrib4fv = (PFNGLVERTEXATTRIB4FVPROC)load("glVertexAttrib4fv");
glad_glVertexAttrib4iv = (PFNGLVERTEXATTRIB4IVPROC)load("glVertexAttrib4iv");
glad_glVertexAttrib4s = (PFNGLVERTEXATTRIB4SPROC)load("glVertexAttrib4s");
glad_glVertexAttrib4sv = (PFNGLVERTEXATTRIB4SVPROC)load("glVertexAttrib4sv");
glad_glVertexAttrib4ubv = (PFNGLVERTEXATTRIB4UBVPROC)load("glVertexAttrib4ubv");
glad_glVertexAttrib4uiv = (PFNGLVERTEXATTRIB4UIVPROC)load("glVertexAttrib4uiv");
glad_glVertexAttrib4usv = (PFNGLVERTEXATTRIB4USVPROC)load("glVertexAttrib4usv");
glad_glVertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)load("glVertexAttribPointer");
}
static void load_GL_VERSION_2_1(GLADloadproc load) {
if(!GLAD_GL_VERSION_2_1) return;
glad_glUniformMatrix2x3fv = (PFNGLUNIFORMMATRIX2X3FVPROC)load("glUniformMatrix2x3fv");
glad_glUniformMatrix3x2fv = (PFNGLUNIFORMMATRIX3X2FVPROC)load("glUniformMatrix3x2fv");
glad_glUniformMatrix2x4fv = (PFNGLUNIFORMMATRIX2X4FVPROC)load("glUniformMatrix2x4fv");
glad_glUniformMatrix4x2fv = (PFNGLUNIFORMMATRIX4X2FVPROC)load("glUniformMatrix4x2fv");
glad_glUniformMatrix3x4fv = (PFNGLUNIFORMMATRIX3X4FVPROC)load("glUniformMatrix3x4fv");
glad_glUniformMatrix4x3fv = (PFNGLUNIFORMMATRIX4X3FVPROC)load("glUniformMatrix4x3fv");
}
static void load_GL_VERSION_3_0(GLADloadproc load) {
if(!GLAD_GL_VERSION_3_0) return;
glad_glColorMaski = (PFNGLCOLORMASKIPROC)load("glColorMaski");
glad_glGetBooleani_v = (PFNGLGETBOOLEANI_VPROC)load("glGetBooleani_v");
glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v");
glad_glEnablei = (PFNGLENABLEIPROC)load("glEnablei");
glad_glDisablei = (PFNGLDISABLEIPROC)load("glDisablei");
glad_glIsEnabledi = (PFNGLISENABLEDIPROC)load("glIsEnabledi");
glad_glBeginTransformFeedback = (PFNGLBEGINTRANSFORMFEEDBACKPROC)load("glBeginTransformFeedback");
glad_glEndTransformFeedback = (PFNGLENDTRANSFORMFEEDBACKPROC)load("glEndTransformFeedback");
glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange");
glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase");
glad_glTransformFeedbackVaryings = (PFNGLTRANSFORMFEEDBACKVARYINGSPROC)load("glTransformFeedbackVaryings");
glad_glGetTransformFeedbackVarying = (PFNGLGETTRANSFORMFEEDBACKVARYINGPROC)load("glGetTransformFeedbackVarying");
glad_glClampColor = (PFNGLCLAMPCOLORPROC)load("glClampColor");
glad_glBeginConditionalRender = (PFNGLBEGINCONDITIONALRENDERPROC)load("glBeginConditionalRender");
glad_glEndConditionalRender = (PFNGLENDCONDITIONALRENDERPROC)load("glEndConditionalRender");
glad_glVertexAttribIPointer = (PFNGLVERTEXATTRIBIPOINTERPROC)load("glVertexAttribIPointer");
glad_glGetVertexAttribIiv = (PFNGLGETVERTEXATTRIBIIVPROC)load("glGetVertexAttribIiv");
glad_glGetVertexAttribIuiv = (PFNGLGETVERTEXATTRIBIUIVPROC)load("glGetVertexAttribIuiv");
glad_glVertexAttribI1i = (PFNGLVERTEXATTRIBI1IPROC)load("glVertexAttribI1i");
glad_glVertexAttribI2i = (PFNGLVERTEXATTRIBI2IPROC)load("glVertexAttribI2i");
glad_glVertexAttribI3i = (PFNGLVERTEXATTRIBI3IPROC)load("glVertexAttribI3i");
glad_glVertexAttribI4i = (PFNGLVERTEXATTRIBI4IPROC)load("glVertexAttribI4i");
glad_glVertexAttribI1ui = (PFNGLVERTEXATTRIBI1UIPROC)load("glVertexAttribI1ui");
glad_glVertexAttribI2ui = (PFNGLVERTEXATTRIBI2UIPROC)load("glVertexAttribI2ui");
glad_glVertexAttribI3ui = (PFNGLVERTEXATTRIBI3UIPROC)load("glVertexAttribI3ui");
glad_glVertexAttribI4ui = (PFNGLVERTEXATTRIBI4UIPROC)load("glVertexAttribI4ui");
glad_glVertexAttribI1iv = (PFNGLVERTEXATTRIBI1IVPROC)load("glVertexAttribI1iv");
glad_glVertexAttribI2iv = (PFNGLVERTEXATTRIBI2IVPROC)load("glVertexAttribI2iv");
glad_glVertexAttribI3iv = (PFNGLVERTEXATTRIBI3IVPROC)load("glVertexAttribI3iv");
glad_glVertexAttribI4iv = (PFNGLVERTEXATTRIBI4IVPROC)load("glVertexAttribI4iv");
glad_glVertexAttribI1uiv = (PFNGLVERTEXATTRIBI1UIVPROC)load("glVertexAttribI1uiv");
glad_glVertexAttribI2uiv = (PFNGLVERTEXATTRIBI2UIVPROC)load("glVertexAttribI2uiv");
glad_glVertexAttribI3uiv = (PFNGLVERTEXATTRIBI3UIVPROC)load("glVertexAttribI3uiv");
glad_glVertexAttribI4uiv = (PFNGLVERTEXATTRIBI4UIVPROC)load("glVertexAttribI4uiv");
glad_glVertexAttribI4bv = (PFNGLVERTEXATTRIBI4BVPROC)load("glVertexAttribI4bv");
glad_glVertexAttribI4sv = (PFNGLVERTEXATTRIBI4SVPROC)load("glVertexAttribI4sv");
glad_glVertexAttribI4ubv = (PFNGLVERTEXATTRIBI4UBVPROC)load("glVertexAttribI4ubv");
glad_glVertexAttribI4usv = (PFNGLVERTEXATTRIBI4USVPROC)load("glVertexAttribI4usv");
glad_glGetUniformuiv = (PFNGLGETUNIFORMUIVPROC)load("glGetUniformuiv");
glad_glBindFragDataLocation = (PFNGLBINDFRAGDATALOCATIONPROC)load("glBindFragDataLocation");
glad_glGetFragDataLocation = (PFNGLGETFRAGDATALOCATIONPROC)load("glGetFragDataLocation");
glad_glUniform1ui = (PFNGLUNIFORM1UIPROC)load("glUniform1ui");
glad_glUniform2ui = (PFNGLUNIFORM2UIPROC)load("glUniform2ui");
glad_glUniform3ui = (PFNGLUNIFORM3UIPROC)load("glUniform3ui");
glad_glUniform4ui = (PFNGLUNIFORM4UIPROC)load("glUniform4ui");
glad_glUniform1uiv = (PFNGLUNIFORM1UIVPROC)load("glUniform1uiv");
glad_glUniform2uiv = (PFNGLUNIFORM2UIVPROC)load("glUniform2uiv");
glad_glUniform3uiv = (PFNGLUNIFORM3UIVPROC)load("glUniform3uiv");
glad_glUniform4uiv = (PFNGLUNIFORM4UIVPROC)load("glUniform4uiv");
glad_glTexParameterIiv = (PFNGLTEXPARAMETERIIVPROC)load("glTexParameterIiv");
glad_glTexParameterIuiv = (PFNGLTEXPARAMETERIUIVPROC)load("glTexParameterIuiv");
glad_glGetTexParameterIiv = (PFNGLGETTEXPARAMETERIIVPROC)load("glGetTexParameterIiv");
glad_glGetTexParameterIuiv = (PFNGLGETTEXPARAMETERIUIVPROC)load("glGetTexParameterIuiv");
glad_glClearBufferiv = (PFNGLCLEARBUFFERIVPROC)load("glClearBufferiv");
glad_glClearBufferuiv = (PFNGLCLEARBUFFERUIVPROC)load("glClearBufferuiv");
glad_glClearBufferfv = (PFNGLCLEARBUFFERFVPROC)load("glClearBufferfv");
glad_glClearBufferfi = (PFNGLCLEARBUFFERFIPROC)load("glClearBufferfi");
glad_glGetStringi = (PFNGLGETSTRINGIPROC)load("glGetStringi");
glad_glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)load("glIsRenderbuffer");
glad_glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)load("glBindRenderbuffer");
glad_glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)load("glDeleteRenderbuffers");
glad_glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)load("glGenRenderbuffers");
glad_glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)load("glRenderbufferStorage");
glad_glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)load("glGetRenderbufferParameteriv");
glad_glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)load("glIsFramebuffer");
glad_glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)load("glBindFramebuffer");
glad_glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)load("glDeleteFramebuffers");
glad_glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)load("glGenFramebuffers");
glad_glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)load("glCheckFramebufferStatus");
glad_glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)load("glFramebufferTexture1D");
glad_glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)load("glFramebufferTexture2D");
glad_glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)load("glFramebufferTexture3D");
glad_glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)load("glFramebufferRenderbuffer");
glad_glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)load("glGetFramebufferAttachmentParameteriv");
glad_glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)load("glGenerateMipmap");
glad_glBlitFramebuffer = (PFNGLBLITFRAMEBUFFERPROC)load("glBlitFramebuffer");
glad_glRenderbufferStorageMultisample = (PFNGLRENDERBUFFERSTORAGEMULTISAMPLEPROC)load("glRenderbufferStorageMultisample");
glad_glFramebufferTextureLayer = (PFNGLFRAMEBUFFERTEXTURELAYERPROC)load("glFramebufferTextureLayer");
glad_glMapBufferRange = (PFNGLMAPBUFFERRANGEPROC)load("glMapBufferRange");
glad_glFlushMappedBufferRange = (PFNGLFLUSHMAPPEDBUFFERRANGEPROC)load("glFlushMappedBufferRange");
glad_glBindVertexArray = (PFNGLBINDVERTEXARRAYPROC)load("glBindVertexArray");
glad_glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSPROC)load("glDeleteVertexArrays");
glad_glGenVertexArrays = (PFNGLGENVERTEXARRAYSPROC)load("glGenVertexArrays");
glad_glIsVertexArray = (PFNGLISVERTEXARRAYPROC)load("glIsVertexArray");
}
static void load_GL_VERSION_3_1(GLADloadproc load) {
if(!GLAD_GL_VERSION_3_1) return;
glad_glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDPROC)load("glDrawArraysInstanced");
glad_glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDPROC)load("glDrawElementsInstanced");
glad_glTexBuffer = (PFNGLTEXBUFFERPROC)load("glTexBuffer");
glad_glPrimitiveRestartIndex = (PFNGLPRIMITIVERESTARTINDEXPROC)load("glPrimitiveRestartIndex");
glad_glCopyBufferSubData = (PFNGLCOPYBUFFERSUBDATAPROC)load("glCopyBufferSubData");
glad_glGetUniformIndices = (PFNGLGETUNIFORMINDICESPROC)load("glGetUniformIndices");
glad_glGetActiveUniformsiv = (PFNGLGETACTIVEUNIFORMSIVPROC)load("glGetActiveUniformsiv");
glad_glGetActiveUniformName = (PFNGLGETACTIVEUNIFORMNAMEPROC)load("glGetActiveUniformName");
glad_glGetUniformBlockIndex = (PFNGLGETUNIFORMBLOCKINDEXPROC)load("glGetUniformBlockIndex");
glad_glGetActiveUniformBlockiv = (PFNGLGETACTIVEUNIFORMBLOCKIVPROC)load("glGetActiveUniformBlockiv");
glad_glGetActiveUniformBlockName = (PFNGLGETACTIVEUNIFORMBLOCKNAMEPROC)load("glGetActiveUniformBlockName");
glad_glUniformBlockBinding = (PFNGLUNIFORMBLOCKBINDINGPROC)load("glUniformBlockBinding");
glad_glBindBufferRange = (PFNGLBINDBUFFERRANGEPROC)load("glBindBufferRange");
glad_glBindBufferBase = (PFNGLBINDBUFFERBASEPROC)load("glBindBufferBase");
glad_glGetIntegeri_v = (PFNGLGETINTEGERI_VPROC)load("glGetIntegeri_v");
}
static void load_GL_VERSION_3_2(GLADloadproc load) {
if(!GLAD_GL_VERSION_3_2) return;
glad_glDrawElementsBaseVertex = (PFNGLDRAWELEMENTSBASEVERTEXPROC)load("glDrawElementsBaseVertex");
glad_glDrawRangeElementsBaseVertex = (PFNGLDRAWRANGEELEMENTSBASEVERTEXPROC)load("glDrawRangeElementsBaseVertex");
glad_glDrawElementsInstancedBaseVertex = (PFNGLDRAWELEMENTSINSTANCEDBASEVERTEXPROC)load("glDrawElementsInstancedBaseVertex");
glad_glMultiDrawElementsBaseVertex = (PFNGLMULTIDRAWELEMENTSBASEVERTEXPROC)load("glMultiDrawElementsBaseVertex");
glad_glProvokingVertex = (PFNGLPROVOKINGVERTEXPROC)load("glProvokingVertex");
glad_glFenceSync = (PFNGLFENCESYNCPROC)load("glFenceSync");
glad_glIsSync = (PFNGLISSYNCPROC)load("glIsSync");
glad_glDeleteSync = (PFNGLDELETESYNCPROC)load("glDeleteSync");
glad_glClientWaitSync = (PFNGLCLIENTWAITSYNCPROC)load("glClientWaitSync");
glad_glWaitSync = (PFNGLWAITSYNCPROC)load("glWaitSync");
glad_glGetInteger64v = (PFNGLGETINTEGER64VPROC)load("glGetInteger64v");
glad_glGetSynciv = (PFNGLGETSYNCIVPROC)load("glGetSynciv");
glad_glGetInteger64i_v = (PFNGLGETINTEGER64I_VPROC)load("glGetInteger64i_v");
glad_glGetBufferParameteri64v = (PFNGLGETBUFFERPARAMETERI64VPROC)load("glGetBufferParameteri64v");
glad_glFramebufferTexture = (PFNGLFRAMEBUFFERTEXTUREPROC)load("glFramebufferTexture");
glad_glTexImage2DMultisample = (PFNGLTEXIMAGE2DMULTISAMPLEPROC)load("glTexImage2DMultisample");
glad_glTexImage3DMultisample = (PFNGLTEXIMAGE3DMULTISAMPLEPROC)load("glTexImage3DMultisample");
glad_glGetMultisamplefv = (PFNGLGETMULTISAMPLEFVPROC)load("glGetMultisamplefv");
glad_glSampleMaski = (PFNGLSAMPLEMASKIPROC)load("glSampleMaski");
}
static void load_GL_VERSION_3_3(GLADloadproc load) {
if(!GLAD_GL_VERSION_3_3) return;
glad_glBindFragDataLocationIndexed = (PFNGLBINDFRAGDATALOCATIONINDEXEDPROC)load("glBindFragDataLocationIndexed");
glad_glGetFragDataIndex = (PFNGLGETFRAGDATAINDEXPROC)load("glGetFragDataIndex");
glad_glGenSamplers = (PFNGLGENSAMPLERSPROC)load("glGenSamplers");
glad_glDeleteSamplers = (PFNGLDELETESAMPLERSPROC)load("glDeleteSamplers");
glad_glIsSampler = (PFNGLISSAMPLERPROC)load("glIsSampler");
glad_glBindSampler = (PFNGLBINDSAMPLERPROC)load("glBindSampler");
glad_glSamplerParameteri = (PFNGLSAMPLERPARAMETERIPROC)load("glSamplerParameteri");
glad_glSamplerParameteriv = (PFNGLSAMPLERPARAMETERIVPROC)load("glSamplerParameteriv");
glad_glSamplerParameterf = (PFNGLSAMPLERPARAMETERFPROC)load("glSamplerParameterf");
glad_glSamplerParameterfv = (PFNGLSAMPLERPARAMETERFVPROC)load("glSamplerParameterfv");
glad_glSamplerParameterIiv = (PFNGLSAMPLERPARAMETERIIVPROC)load("glSamplerParameterIiv");
glad_glSamplerParameterIuiv = (PFNGLSAMPLERPARAMETERIUIVPROC)load("glSamplerParameterIuiv");
glad_glGetSamplerParameteriv = (PFNGLGETSAMPLERPARAMETERIVPROC)load("glGetSamplerParameteriv");
glad_glGetSamplerParameterIiv = (PFNGLGETSAMPLERPARAMETERIIVPROC)load("glGetSamplerParameterIiv");
glad_glGetSamplerParameterfv = (PFNGLGETSAMPLERPARAMETERFVPROC)load("glGetSamplerParameterfv");
glad_glGetSamplerParameterIuiv = (PFNGLGETSAMPLERPARAMETERIUIVPROC)load("glGetSamplerParameterIuiv");
glad_glQueryCounter = (PFNGLQUERYCOUNTERPROC)load("glQueryCounter");
glad_glGetQueryObjecti64v = (PFNGLGETQUERYOBJECTI64VPROC)load("glGetQueryObjecti64v");
glad_glGetQueryObjectui64v = (PFNGLGETQUERYOBJECTUI64VPROC)load("glGetQueryObjectui64v");
glad_glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISORPROC)load("glVertexAttribDivisor");
glad_glVertexAttribP1ui = (PFNGLVERTEXATTRIBP1UIPROC)load("glVertexAttribP1ui");
glad_glVertexAttribP1uiv = (PFNGLVERTEXATTRIBP1UIVPROC)load("glVertexAttribP1uiv");
glad_glVertexAttribP2ui = (PFNGLVERTEXATTRIBP2UIPROC)load("glVertexAttribP2ui");
glad_glVertexAttribP2uiv = (PFNGLVERTEXATTRIBP2UIVPROC)load("glVertexAttribP2uiv");
glad_glVertexAttribP3ui = (PFNGLVERTEXATTRIBP3UIPROC)load("glVertexAttribP3ui");
glad_glVertexAttribP3uiv = (PFNGLVERTEXATTRIBP3UIVPROC)load("glVertexAttribP3uiv");
glad_glVertexAttribP4ui = (PFNGLVERTEXATTRIBP4UIPROC)load("glVertexAttribP4ui");
glad_glVertexAttribP4uiv = (PFNGLVERTEXATTRIBP4UIVPROC)load("glVertexAttribP4uiv");
glad_glVertexP2ui = (PFNGLVERTEXP2UIPROC)load("glVertexP2ui");
glad_glVertexP2uiv = (PFNGLVERTEXP2UIVPROC)load("glVertexP2uiv");
glad_glVertexP3ui = (PFNGLVERTEXP3UIPROC)load("glVertexP3ui");
glad_glVertexP3uiv = (PFNGLVERTEXP3UIVPROC)load("glVertexP3uiv");
glad_glVertexP4ui = (PFNGLVERTEXP4UIPROC)load("glVertexP4ui");
glad_glVertexP4uiv = (PFNGLVERTEXP4UIVPROC)load("glVertexP4uiv");
glad_glTexCoordP1ui = (PFNGLTEXCOORDP1UIPROC)load("glTexCoordP1ui");
glad_glTexCoordP1uiv = (PFNGLTEXCOORDP1UIVPROC)load("glTexCoordP1uiv");
glad_glTexCoordP2ui = (PFNGLTEXCOORDP2UIPROC)load("glTexCoordP2ui");
glad_glTexCoordP2uiv = (PFNGLTEXCOORDP2UIVPROC)load("glTexCoordP2uiv");
glad_glTexCoordP3ui = (PFNGLTEXCOORDP3UIPROC)load("glTexCoordP3ui");
glad_glTexCoordP3uiv = (PFNGLTEXCOORDP3UIVPROC)load("glTexCoordP3uiv");
glad_glTexCoordP4ui = (PFNGLTEXCOORDP4UIPROC)load("glTexCoordP4ui");
glad_glTexCoordP4uiv = (PFNGLTEXCOORDP4UIVPROC)load("glTexCoordP4uiv");
glad_glMultiTexCoordP1ui = (PFNGLMULTITEXCOORDP1UIPROC)load("glMultiTexCoordP1ui");
glad_glMultiTexCoordP1uiv = (PFNGLMULTITEXCOORDP1UIVPROC)load("glMultiTexCoordP1uiv");
glad_glMultiTexCoordP2ui = (PFNGLMULTITEXCOORDP2UIPROC)load("glMultiTexCoordP2ui");
glad_glMultiTexCoordP2uiv = (PFNGLMULTITEXCOORDP2UIVPROC)load("glMultiTexCoordP2uiv");
glad_glMultiTexCoordP3ui = (PFNGLMULTITEXCOORDP3UIPROC)load("glMultiTexCoordP3ui");
glad_glMultiTexCoordP3uiv = (PFNGLMULTITEXCOORDP3UIVPROC)load("glMultiTexCoordP3uiv");
glad_glMultiTexCoordP4ui = (PFNGLMULTITEXCOORDP4UIPROC)load("glMultiTexCoordP4ui");
glad_glMultiTexCoordP4uiv = (PFNGLMULTITEXCOORDP4UIVPROC)load("glMultiTexCoordP4uiv");
glad_glNormalP3ui = (PFNGLNORMALP3UIPROC)load("glNormalP3ui");
glad_glNormalP3uiv = (PFNGLNORMALP3UIVPROC)load("glNormalP3uiv");
glad_glColorP3ui = (PFNGLCOLORP3UIPROC)load("glColorP3ui");
glad_glColorP3uiv = (PFNGLCOLORP3UIVPROC)load("glColorP3uiv");
glad_glColorP4ui = (PFNGLCOLORP4UIPROC)load("glColorP4ui");
glad_glColorP4uiv = (PFNGLCOLORP4UIVPROC)load("glColorP4uiv");
glad_glSecondaryColorP3ui = (PFNGLSECONDARYCOLORP3UIPROC)load("glSecondaryColorP3ui");
glad_glSecondaryColorP3uiv = (PFNGLSECONDARYCOLORP3UIVPROC)load("glSecondaryColorP3uiv");
}
static int find_extensionsGL(void) {
if (!get_exts()) return 0;
(void)&has_ext;
free_exts();
return 1;
}
static void find_coreGL(void) {
/* Thank you @elmindreda
* https://github.com/elmindreda/greg/blob/master/templates/greg.c.in#L176
* https://github.com/glfw/glfw/blob/master/src/context.c#L36
*/
int i, major, minor;
const char* version;
const char* prefixes[] = {
"OpenGL ES-CM ",
"OpenGL ES-CL ",
"OpenGL ES ",
NULL
};
version = (const char*) glGetString(GL_VERSION);
if (!version) return;
for (i = 0; prefixes[i]; i++) {
const size_t length = strlen(prefixes[i]);
if (strncmp(version, prefixes[i], length) == 0) {
version += length;
break;
}
}
/* PR #18 */
#ifdef _MSC_VER
sscanf_s(version, "%d.%d", &major, &minor);
#else
sscanf(version, "%d.%d", &major, &minor);
#endif
GLVersion.major = major; GLVersion.minor = minor;
max_loaded_major = major; max_loaded_minor = minor;
GLAD_GL_VERSION_1_0 = (major == 1 && minor >= 0) || major > 1;
GLAD_GL_VERSION_1_1 = (major == 1 && minor >= 1) || major > 1;
GLAD_GL_VERSION_1_2 = (major == 1 && minor >= 2) || major > 1;
GLAD_GL_VERSION_1_3 = (major == 1 && minor >= 3) || major > 1;
GLAD_GL_VERSION_1_4 = (major == 1 && minor >= 4) || major > 1;
GLAD_GL_VERSION_1_5 = (major == 1 && minor >= 5) || major > 1;
GLAD_GL_VERSION_2_0 = (major == 2 && minor >= 0) || major > 2;
GLAD_GL_VERSION_2_1 = (major == 2 && minor >= 1) || major > 2;
GLAD_GL_VERSION_3_0 = (major == 3 && minor >= 0) || major > 3;
GLAD_GL_VERSION_3_1 = (major == 3 && minor >= 1) || major > 3;
GLAD_GL_VERSION_3_2 = (major == 3 && minor >= 2) || major > 3;
GLAD_GL_VERSION_3_3 = (major == 3 && minor >= 3) || major > 3;
if (GLVersion.major > 3 || (GLVersion.major >= 3 && GLVersion.minor >= 3)) {
max_loaded_major = 3;
max_loaded_minor = 3;
}
}
int gladLoadGLLoader(GLADloadproc load) {
GLVersion.major = 0; GLVersion.minor = 0;
glGetString = (PFNGLGETSTRINGPROC)load("glGetString");
if(glGetString == NULL) return 0;
if(glGetString(GL_VERSION) == NULL) return 0;
find_coreGL();
load_GL_VERSION_1_0(load);
load_GL_VERSION_1_1(load);
load_GL_VERSION_1_2(load);
load_GL_VERSION_1_3(load);
load_GL_VERSION_1_4(load);
load_GL_VERSION_1_5(load);
load_GL_VERSION_2_0(load);
load_GL_VERSION_2_1(load);
load_GL_VERSION_3_0(load);
load_GL_VERSION_3_1(load);
load_GL_VERSION_3_2(load);
load_GL_VERSION_3_3(load);
if (!find_extensionsGL()) return 0;
return GLVersion.major != 0 || GLVersion.minor != 0;
}
| {
"content_hash": "5182b3c91bc21dc182bc215af517e862",
"timestamp": "",
"source": "github",
"line_count": 1140,
"max_line_length": 138,
"avg_line_length": 52.86929824561403,
"alnum_prop": 0.8070548024754858,
"repo_name": "PearCoding/PearRay",
"id": "f21e13e650a027b2eef7c59f45046f17243cf60f",
"size": "60271",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ui/3d/glad.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "326"
},
{
"name": "C",
"bytes": "846604"
},
{
"name": "C++",
"bytes": "2299221"
},
{
"name": "CMake",
"bytes": "108162"
},
{
"name": "Python",
"bytes": "75267"
},
{
"name": "Shell",
"bytes": "3408"
}
],
"symlink_target": ""
} |
"""
Downloads Amazon AWS IP Address Ranges and converts them to CSV
Documentation: http://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html
"""
import cidr
import json
import subprocess
import sys
URL = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
def get_json(url):
p = subprocess.Popen(['curl', URL], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
return out
def extract_ip_blocks(txt):
cidrs = {}
aws_json = json.loads(txt)
aws_ip_ranges = aws_json['prefixes']
for ip_range in aws_ip_ranges:
cidr = ip_range['ip_prefix']
name = "AWS %s %s" % (ip_range['service'], ip_range['region'])
cidrs[cidr] = name
return cidrs
def emit_csv(cidrs):
csv = []
for key in cidrs:
(range_start, range_end) = cidr.cidr_to_range(key)
csv.append("%s,%s,%s" % (range_start, range_end, cidrs[key]))
return csv
def main():
xml = get_json(URL)
cidrs = extract_ip_blocks(xml)
csv = emit_csv(cidrs)
for line in csv:
print line
if __name__ == '__main__':
status = main()
sys.exit(status)
| {
"content_hash": "2331aaa34e9068cf164fbf3f2a0579f4",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 87,
"avg_line_length": 21.452830188679247,
"alnum_prop": 0.6182937554969217,
"repo_name": "rafeco/ip_range_tools",
"id": "736d10d9f7d6106122d132da9040fdbfc4ebf9cb",
"size": "1160",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws_ip_ranges.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "9938"
}
],
"symlink_target": ""
} |
{exp:channel:entries channel="articles" limit="1" entry_id="{embed:entry_id}" status="open"}
{exp:playa:parents channel="issues" status="open"}{exp:stash:set name="total-children"}{exp:playa:total_children}{/exp:stash:set}{/exp:playa:parents}
<aside id="related" class="sidebar var1">
<i class="widget-branding ala"></i>
{if article_follow_up != ""}
<!-- start first block--><!-- if a follow up has been selected show the follow up -->
<section class="follow-up">
<h1>Follow-up</h1>
{article_follow_up}
<article>
{entry}<h1><a href="{site_url}/{if channel_short_name=='blog'}{channel_short_name}/post/{url_title}{if:elseif channel_short_name=='articles'}article/{url_title}{if:elseif channel_short_name=='columns'}column/{url_title}{/if}" data-trackevent="Related sidebar: Follow up">{title}</a></h1>{/entry}
<p>{exp:ala_typography:inline}{exp:strip_html}
{if note}
{note}
{if:else}
{entry}
{if channel_short_name=='blog'}
{if blog_mini_deck}{blog_mini_deck}{if:elseif blog_intro}{exp:trunchtml chars="130" inline="..."}{blog_intro}{/exp:trunchtml}{/if}
{if:elseif channel_short_name=='columns'}
{if column_mini_deck}{column_mini_deck}{if:elseif column_intro}{exp:trunchtml chars="130" inline="..."}{column_intro}{/exp:trunchtml}{/if}
{if:elseif channel_short_name=='articles'}
{if article_mini_deck}{article_mini_deck}{if:elseif article_deck}{exp:trunchtml chars="130" inline="..."}{article_deck}{/exp:trunchtml}{/if}
{/if}
{/entry}
{/if}
{/exp:strip_html}{/exp:ala_typography:inline}</p>
</article>
{/article_follow_up}
</section>
{/if}
<!-- if a follow up has not been selected, and the issue has two articles show the other article -->
{if article_follow_up == ""}
{exp:playa:parents channel="issues" status="open"}
{if {exp:stash:get name="total-children"} > 1}
{exp:stash:set name="issue-number"}{issue_number}{/exp:stash:set}
{exp:playa:children child_id="not {embed:entry_id}" status="open"}
<section>
{if count == "1"}
{article_illustration}
<figure class="sidebar-hero {if width > height}wideone{/if}" data-picture data-alt="">
<div data-src="{exp:ce_img:pair src="{url}" width="322" crop="no" save_type="jpg" quality="61"}{made}{/exp:ce_img:pair}"></div>
<div data-src="{exp:ce_img:pair src="{url}" width="644" crop="no" save_type="jpg" quality="10"}{made}{/exp:ce_img:pair}" data-media="(min-width: 600px) and (min-device-pixel-ratio: 2.0)"></div>
<noscript><img src="{exp:ce_img:pair src="{url}" width="322" crop="no" save_type="jpg" quality="10"}{made}{/exp:ce_img:pair}" alt=""></noscript>
</figure>
{/article_illustration}
<h1>Also in Issue № {exp:stash:get name="issue-number"}</h1>
{/if}
<article>
<h1><a href="/article/{url_title}" data-trackevent="Related sidebar: Also in issue">{title}</a></h1>
<p>{exp:ala_typography:inline}{exp:strip_html}{if article_mini_deck}<p>{article_mini_deck}</p>{if:elseif article_deck}<p>{exp:trunchtml chars="130" inline="..."}{article_deck}{/exp:trunchtml}</p>{/if}{/exp:strip_html}{/exp:ala_typography:inline}</p>
</article>
</section>
{/exp:playa:children}
{/if}
{/exp:playa:parents}
{/if}<!-- end first block -->
{if "{article_related_content:count}" != ""}
<!-- start second block --><!-- show related articles if they exist -->
<section class="related-articles">
<h1>Further reading</h1>
{article_related_content status="open"}
<article>
<h2><a href="{site_url}/{if article_related_content:channel_short_name=='blog'}{article_related_content:channel_short_name}/post/{article_related_content:url_title}{if:elseif article_related_content:channel_short_name=='articles'}article/{article_related_content:url_title}{if:elseif article_related_content:channel_short_name=='columns'}column/{article_related_content:url_title}{/if}" data-trackevent="Related sidebar: Related by editor">{article_related_content:title}</a></h2>
<p>{exp:ala_typography:inline}{exp:strip_html}
{if article_related_content:channel_short_name=='columns'}
{if article_related_content:column_mini_deck}{article_related_content:column_mini_deck}{if:elseif article_related_content:column_intro}{exp:trunchtml chars="130" inline="..."}{article_related_content:column_intro}{/exp:trunchtml}{/if}
{if:elseif article_related_content:channel_short_name=='blog'}
{if article_related_content:blog_mini_deck}{article_related_content:blog_mini_deck}{if:elseif article_related_content:blog_intro}{exp:trunchtml chars="130" inline="..."}{article_related_content:blog_intro}{/exp:trunchtml}{/if}
{if:elseif article_related_content:channel_short_name=='articles'}
{if article_related_content:article_mini_deck}{article_related_content:article_mini_deck}{if:elseif article_related_content:article_deck}{exp:trunchtml chars="130" inline="..."}{article_related_content:article_deck}{/exp:trunchtml}{/if}
{/if}
{/exp:strip_html}{/exp:ala_typography:inline}</p>
</article>
{/article_related_content}
</section>
{if:else}<!-- if no related articles show categories -->
<section class="related-articles">
{embed="embeds/primary-category-logic" id="{entry_id}"}
</section>
{/if}
{if article_follow_up == ""}
{exp:playa:parents channel="issues" status="open"}
{if {exp:stash:get name="total-children"} == 1}
<section>
{embed="embeds/event-entries"}
</section>
{/if}
{/exp:playa:parents}
{/if}
</aside>
{/exp:channel:entries}
| {
"content_hash": "f22371119e337ee4eec6c9d58eab4c00",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 485,
"avg_line_length": 58.916666666666664,
"alnum_prop": 0.6603606789250354,
"repo_name": "alistapart/AListApart",
"id": "d321268160874c8148de4b0289d663bd4df8da34",
"size": "5658",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/default_site/embeds.group/related-sidebar.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "282450"
},
{
"name": "HTML",
"bytes": "579336"
},
{
"name": "JavaScript",
"bytes": "181897"
},
{
"name": "Python",
"bytes": "759"
},
{
"name": "Ruby",
"bytes": "3067"
}
],
"symlink_target": ""
} |
package umiker9.stardust2d.graphics.lwjgl2;
import org.lwjgl.opengl.*;
import umiker9.stardust2d.systems.error.Error;
import umiker9.stardust2d.systems.error.ErrorBuilder;
import umiker9.stardust2d.systems.error.ErrorStack;
import umiker9.stardust2d.systems.io.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.ByteBuffer;
import static org.lwjgl.opengl.EXTTextureFilterAnisotropic.GL_TEXTURE_MAX_ANISOTROPY_EXT;
import static org.lwjgl.opengl.GL11.*;
public class TextureLoader {
public static Texture2D loadTexture(Resource resource) {
return loadTexture(resource, TextureParameters.defaultParameters);
}
public static Texture2D loadTexture(Resource resource, TextureParameters parameters) {
Texture2D texture = new Texture2D();
loadTexture(texture, resource, parameters);
return texture;
}
public static void loadTexture(Texture2D texture, Resource resource) {
upload(texture, new TextureData(readImage(resource)), TextureParameters.defaultParameters);
}
public static void loadTexture(Texture2D texture, Resource resource, TextureParameters parameters) {
upload(texture, new TextureData(readImage(resource)), parameters);
}
public static void upload(Texture texture, TextureData textureData, TextureParameters parameters) {
if(textureData == null) {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setMessage("TextureData is null").finish());
return;
}
if(!corresponds(texture.getTarget(), textureData.getType())) {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setMessage("Incompatible TextureTarget:"
+ texture.getTarget() + " and TextureData: " + textureData.getType().name())
.setErrorSource(textureData).finish());
return;
}
if(!textureData.hasImageData()) {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setErrorSource(textureData)
.setMessage("TextureData does not contain any ImageData").finish());
return;
}
texture.bind();
setParameters(texture.getTarget(), parameters);
if(texture.getTarget() == GL_TEXTURE_2D) {
upload2d(texture, textureData, parameters);
} else {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setMessage("Unknown or unsupported TextureTarget: "
+ texture.getTarget()).setErrorSource(texture).finish());
return;
}
//todo add more textures
texture.setTextureData(textureData);
texture.setInitialized(true);
}
protected static void upload2d(Texture texture, TextureData textureData, TextureParameters parameters) {
ImageData image = textureData.getImageData();
glTexImage2D(texture.getTarget(), 0, parameters.INTERNAL_FORMAT, image.getWidth(), image.getHeight(),
parameters.BORDER, image.getFormat(), image.getDataType(), GLHelper.wrapDirectBuffer(image.getMipmap(0)));
if (parameters.GENERATE_MIPMAPS) {
GL30.glGenerateMipmap(texture.getTarget());
} else {
int width = image.getWidth();
int height = image.getHeight();
for (int i = 1; i < image.getMipmapCount(); i++) {
width = (width + 1)/2;
height = (height + 1)/2;
glTexImage2D(texture.getTarget(), i, parameters.INTERNAL_FORMAT, width, height, parameters.BORDER,
image.getFormat(), image.getDataType(), GLHelper.wrapDirectBuffer(image.getMipmap(i)));
}
}
}
public static ImageData readImage(Resource resource) {
BufferedImage image = null;
if(resource.getSize() == 0) {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setErrorSource(resource)
.setMessage("Resource [" + resource.getPath() + "] is empty(Missing or unavailable)").finish());
}
try {
image = ImageIO.read(resource.getInputStream());
} catch (IOException e) {
ErrorStack.addError(new ErrorBuilder().setLevel(Error.ERROR).setException(e).setErrorSource(resource)
.setMessage("Error reading image from resource [" + resource.getPath() + "]").finish());
}
return decodeImage(image);
}
public static ImageData decodeImage(BufferedImage image) {
if (image == null) {
return null;
}
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer buffer = ByteBuffer.allocate(image.getWidth() * image.getHeight() * 4);
for (int pixel : pixels) {
buffer.put((byte) (pixel >> 16 & 0xFF));
buffer.put((byte) (pixel >> 8 & 0xFF));
buffer.put((byte) (pixel & 0xFF));
buffer.put((byte) (pixel >> 24 & 0xFF));
}
buffer.flip();
return new ImageData(image.getWidth(), image.getHeight(), GL_RGBA, GL_UNSIGNED_BYTE, buffer.array());
}
protected static void setParameters(int target, TextureParameters parameters) {
glTexParameteri(target, GL_TEXTURE_MIN_FILTER, parameters.MIN_FILTER);
glTexParameteri(target, GL_TEXTURE_MAG_FILTER, parameters.MAG_FILTER);
glTexParameteri(target, GL_TEXTURE_WRAP_S, parameters.WRAP_S);
glTexParameteri(target, GL_TEXTURE_WRAP_T, parameters.WRAP_T);
glTexParameteri(target, GL12.GL_TEXTURE_WRAP_R, parameters.WRAP_R);
glTexParameter(target, GL_TEXTURE_BORDER_COLOR, GLHelper.wrapDirectBuffer(
parameters.BORDER_R, parameters.BORDER_G, parameters.BORDER_B, parameters.BORDER_A));
glTexParameteri(target, GL12.GL_TEXTURE_MAX_LEVEL, parameters.MIPMAP_MAX_LEVEL);
glTexParameteri(target, GL12.GL_TEXTURE_BASE_LEVEL, parameters.MIPMAP_BASE_LEVEL);
glTexParameterf(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, parameters.MAX_ANISOTROPY);
}
protected static boolean corresponds(int target, TextureDataType type) {
if (type == TextureDataType.SINGLE_IMAGE) {
return target == GL_TEXTURE_2D ||
target == GL_TEXTURE_1D ||
target == GL31.GL_TEXTURE_RECTANGLE;
} else if (type == TextureDataType.CUBEMAP) {
return target == GL13.GL_TEXTURE_CUBE_MAP;
} else if (type == TextureDataType.IMAGE_ARRAY) {
return target == GL30.GL_TEXTURE_2D_ARRAY ||
target == GL30.GL_TEXTURE_1D_ARRAY;
} else if (type == TextureDataType.CUBEMAP_ARRAY) {
return target == GL40.GL_TEXTURE_CUBE_MAP_ARRAY;
} else {
return false;
}
}
}
| {
"content_hash": "e35ff85968a96cdc7ab5d7ed38fb9cac",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 124,
"avg_line_length": 42.2060606060606,
"alnum_prop": 0.6434520390580126,
"repo_name": "slimon0/Stardust",
"id": "71ab5d6fc9d320c2eb115875fe53497006c2a911",
"size": "6964",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/umiker9/stardust2d/graphics/lwjgl2/TextureLoader.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "143225"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<style>
.ng-hide {
display: none !important;
}
</style>
<title ng-bind="title">Proverb</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<script>
if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement("style");
var mq = "@@-ms-viewport{width:auto!important}";
msViewportStyle.appendChild(document.createTextNode(mq));
document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
}
</script>
<link rel="icon" type="image/png" href="images/icon.png">
</head>
<body>
<div>
<div ng-include="'app/layout/shell.html'"></div>
<div id="splash-page" ng-show="false" class="dissolve-animation">
<div class="page-splash">
<div class="page-splash-message">
Proverb
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar" style="width: 20%;">
<span class="sr-only">loading...</span>
</div>
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="/build/jquery.min.js">\x3C/script>')</script>
<script>
(function () {
var appConfig = {}, scriptsToLoad;
/**
* Load JavaScript and CSS listed in manifest file
*/
function loadManifest(manifestFile) {
$.getJSON(manifestFile)
.done(function (manifest) {
if (!appConfig.inDebug) {
// If not in release mode then process the manifest straight away - we can assume it's all present and correct
addScriptsAndStylesToPage(manifest);
}
else if (manifest.scripts && manifest.styles) {
// If in debug mode and both scripts and styles are present and correct then process the manifest
addScriptsAndStylesToPage(manifest);
}
else {
// Reload if it looks like the manifest wasn't finished building
setTimeout(function () { loadManifest(manifestFile); }, 500);
}
})
.fail(function (jqXHR) {
console.error("Failed to load " + manifestFile);
// For 404's in debug mode then re-attempt - probably gulp hadn't finished running by the time the page was served
if (appConfig.inDebug && jqXHR.status === 404) {
setTimeout(function () { loadManifest(manifestFile); }, 500);
}
});
}
/**
* Handler which fires as each script loads
*/
function onScriptLoad(event) {
scriptsToLoad -= 1;
//console.log("Loaded " + this.src + ", scriptsToLoad: " + scriptsToLoad);
// Now all the scripts are present start the app
if (scriptsToLoad === 0) {
angularApp.start({
thirdPartyLibs: {
moment: window.moment,
toastr: window.toastr,
underscore: window._
},
appConfig: appConfig
});
}
}
/**
* Iterate through the manifest and build up scripts and style tags and add them to the page
*/
function addScriptsAndStylesToPage(manifest) {
manifest.styles.forEach(function (href) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.media = "all";
link.href = href;
document.head.appendChild(link);
});
scriptsToLoad = manifest.scripts.length;
manifest.scripts.forEach(function (src) {
var script = document.createElement("script");
script.onload = onScriptLoad;
script.src = src;
script.async = false;
document.head.appendChild(script);
});
}
// Load startup data from the server
$.getJSON("api/Startup")
.done(function (startUpData) {
appConfig = startUpData;
var manifestFile = appConfig.appRoot + "build/manifest-" +
(appConfig.inDebug ? "debug" : "release") + ".json";
loadManifest(manifestFile);
});
})();
</script>
</body>
</html> | {
"content_hash": "b9bd89c0173ecfd29d2730f8126a38a8",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 138,
"avg_line_length": 38.77142857142857,
"alnum_prop": 0.48231392778187177,
"repo_name": "johnnyreilly/proverb-node",
"id": "7a2b54c728643e6e4625ad34dc1102c569f69b86",
"size": "5430",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Proverb.Web/public/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "81284"
},
{
"name": "JavaScript",
"bytes": "86295"
},
{
"name": "TypeScript",
"bytes": "69782"
}
],
"symlink_target": ""
} |
<?php
require('require/class.Connection.php');
require('require/class.Spotter.php');
$spotter_array = Spotter::getSpotterDataByIdent($_GET['ident'],"0,1", $_GET['sort']);
if (!empty($spotter_array))
{
$title = 'Most Common Time of Day of '.$spotter_array[0]['ident'];
require('header.php');
date_default_timezone_set('America/Toronto');
print '<div class="info column">';
print '<h1>'.$spotter_array[0]['ident'].'</h1>';
print '<div><span class="label">Ident</span>'.$spotter_array[0]['ident'].'</div>';
print '<div><span class="label">Airline</span><a href="'.$globalURL.'/airline/'.$spotter_array[0]['airline_icao'].'">'.$spotter_array[0]['airline_name'].'</a></div>';
print '<div><span class="label">Flight History</span><a href="http://flightaware.com/live/flight/'.$spotter_array[0]['ident'].'" target="_blank">View the Flight History of this callsign</a></div>';
print '</div>';
include('ident-sub-menu.php');
print '<div class="column">';
print '<h2>Most Common Time of Day</h2>';
print '<p>The statistic below shows the most common time of day of flights with the ident/callsign <strong>'.$spotter_array[0]['ident'].'</strong>.</p>';
$hour_array = Spotter::countAllHoursByIdent($_GET['ident']);
print '<div id="chartHour" class="chart" width="100%"></div>
<script>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["Hour", "# of Flights"], ';
foreach($hour_array as $hour_item)
{
$hour_data .= '[ "'.date("ga", strtotime($hour_item['hour_name'].":00")).'",'.$hour_item['hour_count'].'],';
}
$hour_data = substr($hour_data, 0, -1);
print $hour_data;
print ']);
var options = {
legend: {position: "none"},
chartArea: {"width": "80%", "height": "60%"},
vAxis: {title: "# of Flights"},
hAxis: {showTextEvery: 2},
height:300,
colors: ["#1a3151"]
};
var chart = new google.visualization.AreaChart(document.getElementById("chartHour"));
chart.draw(data, options);
}
$(window).resize(function(){
drawChart();
});
</script>';
print '</div>';
} else {
$title = "Ident";
require('header.php');
print '<h1>Error</h1>';
print '<p>Sorry, this ident/callsign is not in the database. :(</p>';
}
?>
<?php
require('footer.php');
?> | {
"content_hash": "2574b4fdeab70d33ea38b0750efa9234",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 208,
"avg_line_length": 34.11538461538461,
"alnum_prop": 0.5580608793686584,
"repo_name": "Ysurac/Web_App",
"id": "7061124cdb447a35f0c8fd235e2dfcbbf43832ff",
"size": "2661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ident-statistics-time.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "31059"
},
{
"name": "JavaScript",
"bytes": "2676"
},
{
"name": "PHP",
"bytes": "1194490"
},
{
"name": "Shell",
"bytes": "3566"
}
],
"symlink_target": ""
} |
#include "ogrgeomediageometry.h"
#include "cpl_string.h"
CPL_CVSID("$Id: ogrgeomediageometry.cpp 27959 2014-11-14 18:29:21Z rouault $");
#define GEOMEDIA_POINT 0xC0
#define GEOMEDIA_ORIENTED_POINT 0xC8
#define GEOMEDIA_POLYLINE 0xC2
#define GEOMEDIA_POLYGON 0xC3
#define GEOMEDIA_BOUNDARY 0xC5
#define GEOMEDIA_COLLECTION 0xC6
#define GEOMEDIA_MULTILINE 0xCB
#define GEOMEDIA_MULTIPOLYGON 0xCC
/************************************************************************/
/* OGRCreateFromGeomedia() */
/************************************************************************/
OGRErr OGRCreateFromGeomedia( GByte *pabyGeom,
OGRGeometry **ppoGeom,
int nBytes )
{
*ppoGeom = NULL;
if( nBytes < 16 )
return OGRERR_FAILURE;
if( !(pabyGeom[1] == 0xFF && pabyGeom[2] == 0xD2 && pabyGeom[3] == 0x0F) )
return OGRERR_FAILURE;
int nGeomType = pabyGeom[0];
pabyGeom += 16;
nBytes -= 16;
if( nGeomType == GEOMEDIA_POINT ||
nGeomType == GEOMEDIA_ORIENTED_POINT )
{
if (nBytes < 3 * 8)
return OGRERR_FAILURE;
double dfX, dfY, dfZ;
memcpy(&dfX, pabyGeom, 8);
CPL_LSBPTR64(&dfX);
memcpy(&dfY, pabyGeom + 8, 8);
CPL_LSBPTR64(&dfY);
memcpy(&dfZ, pabyGeom + 16, 8);
CPL_LSBPTR64(&dfZ);
*ppoGeom = new OGRPoint( dfX, dfY, dfZ );
return OGRERR_NONE;
}
else if ( nGeomType == GEOMEDIA_POLYLINE )
{
if (nBytes < 4)
return OGRERR_FAILURE;
int nPoints;
memcpy(&nPoints, pabyGeom, 4);
CPL_LSBPTR32(&nPoints);
pabyGeom += 4;
nBytes -= 4;
if (nPoints < 0 || nPoints > INT_MAX / 24 || nBytes < nPoints * 24)
return OGRERR_FAILURE;
OGRLineString* poLS = new OGRLineString();
poLS->setNumPoints(nPoints);
int i;
for(i=0;i<nPoints;i++)
{
double dfX, dfY, dfZ;
memcpy(&dfX, pabyGeom, 8);
CPL_LSBPTR64(&dfX);
memcpy(&dfY, pabyGeom + 8, 8);
CPL_LSBPTR64(&dfY);
memcpy(&dfZ, pabyGeom + 16, 8);
CPL_LSBPTR64(&dfZ);
poLS->setPoint(i, dfX, dfY, dfZ);
pabyGeom += 24;
}
*ppoGeom = poLS;
return OGRERR_NONE;
}
else if ( nGeomType == GEOMEDIA_POLYGON )
{
if (nBytes < 4)
return OGRERR_FAILURE;
int nPoints;
memcpy(&nPoints, pabyGeom, 4);
CPL_LSBPTR32(&nPoints);
pabyGeom += 4;
nBytes -= 4;
if (nPoints < 0 || nPoints > INT_MAX / 24 || nBytes < nPoints * 24)
return OGRERR_FAILURE;
OGRLinearRing* poRing = new OGRLinearRing();
poRing->setNumPoints(nPoints);
int i;
for(i=0;i<nPoints;i++)
{
double dfX, dfY, dfZ;
memcpy(&dfX, pabyGeom, 8);
CPL_LSBPTR64(&dfX);
memcpy(&dfY, pabyGeom + 8, 8);
CPL_LSBPTR64(&dfY);
memcpy(&dfZ, pabyGeom + 16, 8);
CPL_LSBPTR64(&dfZ);
poRing->setPoint(i, dfX, dfY, dfZ);
pabyGeom += 24;
}
OGRPolygon* poPoly = new OGRPolygon();
poPoly->addRingDirectly(poRing);
*ppoGeom = poPoly;
return OGRERR_NONE;
}
else if ( nGeomType == GEOMEDIA_BOUNDARY )
{
if (nBytes < 4)
return OGRERR_FAILURE;
int nExteriorSize;
memcpy(&nExteriorSize, pabyGeom, 4);
CPL_LSBPTR32(&nExteriorSize);
pabyGeom += 4;
nBytes -= 4;
if (nBytes < nExteriorSize)
return OGRERR_FAILURE;
OGRGeometry* poExteriorGeom = NULL;
if (OGRCreateFromGeomedia( pabyGeom, &poExteriorGeom, nExteriorSize ) != OGRERR_NONE)
return OGRERR_FAILURE;
if ( wkbFlatten( poExteriorGeom->getGeometryType() ) != wkbPolygon )
{
delete poExteriorGeom;
return OGRERR_FAILURE;
}
pabyGeom += nExteriorSize;
nBytes -= nExteriorSize;
if (nBytes < 4)
{
delete poExteriorGeom;
return OGRERR_FAILURE;
}
int nInteriorSize;
memcpy(&nInteriorSize, pabyGeom, 4);
CPL_LSBPTR32(&nInteriorSize);
pabyGeom += 4;
nBytes -= 4;
if (nBytes < nInteriorSize)
{
delete poExteriorGeom;
return OGRERR_FAILURE;
}
OGRGeometry* poInteriorGeom = NULL;
if (OGRCreateFromGeomedia( pabyGeom, &poInteriorGeom, nInteriorSize ) != OGRERR_NONE)
{
delete poExteriorGeom;
return OGRERR_FAILURE;
}
OGRwkbGeometryType interiorGeomType = wkbFlatten( poInteriorGeom->getGeometryType() );
if ( interiorGeomType == wkbPolygon )
{
((OGRPolygon*)poExteriorGeom)->addRing(((OGRPolygon*)poInteriorGeom)->getExteriorRing());
}
else if ( interiorGeomType == wkbMultiPolygon )
{
int numGeom = ((OGRMultiPolygon*)poInteriorGeom)->getNumGeometries();
for ( int i = 0; i < numGeom; ++i )
{
OGRPolygon* poInteriorPolygon =
(OGRPolygon*)((OGRMultiPolygon*)poInteriorGeom)->getGeometryRef(i);
((OGRPolygon*)poExteriorGeom)->addRing( poInteriorPolygon->getExteriorRing() );
}
}
else
{
delete poExteriorGeom;
delete poInteriorGeom;
return OGRERR_FAILURE;
}
delete poInteriorGeom;
*ppoGeom = poExteriorGeom;
return OGRERR_NONE;
}
else if ( nGeomType == GEOMEDIA_COLLECTION ||
nGeomType == GEOMEDIA_MULTILINE ||
nGeomType == GEOMEDIA_MULTIPOLYGON )
{
if (nBytes < 4)
return OGRERR_FAILURE;
int i;
int nParts;
memcpy(&nParts, pabyGeom, 4);
CPL_LSBPTR32(&nParts);
pabyGeom += 4;
nBytes -= 4;
if (nParts < 0 || nParts > INT_MAX / (4 + 16) || nBytes < nParts * (4 + 16))
return OGRERR_FAILURE;
/* Can this collection be considered as a multipolyline or multipolygon ? */
if ( nGeomType == GEOMEDIA_COLLECTION )
{
GByte* pabyGeomBackup = pabyGeom;
int nBytesBackup = nBytes;
int bAllPolyline = TRUE;
int bAllPolygon = TRUE;
for(i=0;i<nParts;i++)
{
if (nBytes < 4)
return OGRERR_FAILURE;
int nSubBytes;
memcpy(&nSubBytes, pabyGeom, 4);
CPL_LSBPTR32(&nSubBytes);
if (nSubBytes < 0)
{
return OGRERR_FAILURE;
}
pabyGeom += 4;
nBytes -= 4;
if (nBytes < nSubBytes)
{
return OGRERR_FAILURE;
}
if( nSubBytes < 16 )
return OGRERR_FAILURE;
if( !(pabyGeom[1] == 0xFF && pabyGeom[2] == 0xD2 && pabyGeom[3] == 0x0F) )
return OGRERR_FAILURE;
int nSubGeomType = pabyGeom[0];
if ( nSubGeomType != GEOMEDIA_POLYLINE )
bAllPolyline = FALSE;
if ( nSubGeomType != GEOMEDIA_POLYGON )
bAllPolygon = FALSE;
pabyGeom += nSubBytes;
nBytes -= nSubBytes;
}
pabyGeom = pabyGeomBackup;
nBytes = nBytesBackup;
if (bAllPolyline)
nGeomType = GEOMEDIA_MULTILINE;
else if (bAllPolygon)
nGeomType = GEOMEDIA_MULTIPOLYGON;
}
OGRGeometryCollection* poColl = (nGeomType == GEOMEDIA_MULTILINE) ? new OGRMultiLineString() :
(nGeomType == GEOMEDIA_MULTIPOLYGON) ? new OGRMultiPolygon() :
new OGRGeometryCollection();
for(i=0;i<nParts;i++)
{
if (nBytes < 4)
return OGRERR_FAILURE;
int nSubBytes;
memcpy(&nSubBytes, pabyGeom, 4);
CPL_LSBPTR32(&nSubBytes);
if (nSubBytes < 0)
{
delete poColl;
return OGRERR_FAILURE;
}
pabyGeom += 4;
nBytes -= 4;
if (nBytes < nSubBytes)
{
delete poColl;
return OGRERR_FAILURE;
}
OGRGeometry* poSubGeom = NULL;
if (OGRCreateFromGeomedia( pabyGeom, &poSubGeom, nSubBytes ) == OGRERR_NONE)
{
if (wkbFlatten(poColl->getGeometryType()) == wkbMultiPolygon &&
wkbFlatten(poSubGeom->getGeometryType()) == wkbLineString)
{
OGRPolygon* poPoly = new OGRPolygon();
OGRLinearRing* poRing = new OGRLinearRing();
poRing->addSubLineString((OGRLineString*)poSubGeom);
poPoly->addRingDirectly(poRing);
delete poSubGeom;
poSubGeom = poPoly;
}
if (poColl->addGeometryDirectly(poSubGeom) != OGRERR_NONE)
{
delete poSubGeom;
}
}
pabyGeom += nSubBytes;
nBytes -= nSubBytes;
}
*ppoGeom = poColl;
return OGRERR_NONE;
}
else
{
CPLDebug("GEOMEDIA", "Unhandled type %d", nGeomType);
}
return OGRERR_FAILURE;
}
/************************************************************************/
/* OGRGetGeomediaSRS() */
/************************************************************************/
OGRSpatialReference* OGRGetGeomediaSRS(OGRFeature* poFeature)
{
if (poFeature == NULL)
return NULL;
int nGeodeticDatum = poFeature->GetFieldAsInteger("GeodeticDatum");
int nEllipsoid = poFeature->GetFieldAsInteger("Ellipsoid");
int nProjAlgorithm = poFeature->GetFieldAsInteger("ProjAlgorithm");
if (nGeodeticDatum == 17 && nEllipsoid == 22)
{
if (nProjAlgorithm == 12)
{
OGRSpatialReference* poSRS = new OGRSpatialReference();
const char* pszDescription = poFeature->GetFieldAsString("Description");
if (pszDescription && pszDescription[0] != 0)
poSRS->SetNode( "PROJCS", pszDescription );
poSRS->SetWellKnownGeogCS("WGS84");
double dfStdP1 = poFeature->GetFieldAsDouble("StandPar1");
double dfStdP2 = poFeature->GetFieldAsDouble("StandPar2");
double dfCenterLat = poFeature->GetFieldAsDouble("LatOfOrigin");
double dfCenterLong = poFeature->GetFieldAsDouble("LonOfOrigin");
double dfFalseEasting = poFeature->GetFieldAsDouble("FalseX");
double dfFalseNorthing = poFeature->GetFieldAsDouble("FalseY");
poSRS->SetACEA( dfStdP1, dfStdP2,
dfCenterLat, dfCenterLong,
dfFalseEasting, dfFalseNorthing );
return poSRS;
}
}
return NULL;
}
| {
"content_hash": "8354b122d57ad2077fe007c0b52b35e3",
"timestamp": "",
"source": "github",
"line_count": 388,
"max_line_length": 102,
"avg_line_length": 29.649484536082475,
"alnum_prop": 0.5000869262865091,
"repo_name": "Uli1/node-gdal",
"id": "6b6c962c42b076edeb1c6e5b0b008887f3eb9db9",
"size": "13165",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "deps/libgdal/gdal/ogr/ogrgeomediageometry.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "9324"
},
{
"name": "C++",
"bytes": "472162"
},
{
"name": "JavaScript",
"bytes": "210649"
},
{
"name": "Makefile",
"bytes": "2143"
},
{
"name": "PowerShell",
"bytes": "132"
},
{
"name": "Python",
"bytes": "3414"
},
{
"name": "Shell",
"bytes": "608"
}
],
"symlink_target": ""
} |
package org.jboss.hal.client.accesscontrol;
import org.jboss.hal.ballroom.Alert;
import org.jboss.hal.config.AccessControlProvider;
import org.jboss.hal.config.Environment;
import org.jboss.hal.core.finder.PreviewContent;
import org.jboss.hal.resources.Icons;
import org.jboss.hal.resources.Names;
import org.jboss.hal.resources.Previews;
import org.jboss.hal.resources.Resources;
import elemental2.dom.HTMLElement;
import static org.jboss.elemento.Elements.section;
import static org.jboss.elemento.Elements.setVisible;
class AccessControlPreview extends PreviewContent<Void> {
private final Environment environment;
private final Alert warning;
private final Alert warningSso;
AccessControlPreview(AccessControl accessControl, Environment environment, Resources resources) {
super(Names.ACCESS_CONTROL);
this.environment = environment;
this.warning = new Alert(Icons.WARNING, resources.messages().simpleProviderWarning(),
resources.constants().enableRbac(),
event -> accessControl.switchProvider());
this.warningSso = new Alert(Icons.WARNING, resources.messages().ssoAccessControlWarning());
HTMLElement content;
previewBuilder().add(warning);
previewBuilder().add(warningSso);
previewBuilder().add(content = section().element());
Previews.innerHtml(content, resources.previews().rbacOverview());
update(null);
}
@Override
public void update(Void item) {
setVisible(warning.element(),
environment.getAccessControlProvider() == AccessControlProvider.SIMPLE);
setVisible(warningSso.element(), environment.isSingleSignOn());
}
}
| {
"content_hash": "0c43b106245dce69005ca99a2ab05666",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 101,
"avg_line_length": 36.46808510638298,
"alnum_prop": 0.7287047841306884,
"repo_name": "michpetrov/hal.next",
"id": "ce06d074a6a4dd85b91c2058b45d3f93898bd135",
"size": "2315",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "app/src/main/java/org/jboss/hal/client/accesscontrol/AccessControlPreview.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "38443"
},
{
"name": "HTML",
"bytes": "218186"
},
{
"name": "Java",
"bytes": "6810395"
},
{
"name": "JavaScript",
"bytes": "45507"
},
{
"name": "Less",
"bytes": "72087"
},
{
"name": "Shell",
"bytes": "15270"
}
],
"symlink_target": ""
} |
import { ICustomNode } from '../../../interfaces/custom-nodes/ICustomNode';
import { StringArrayCustomNode } from '../../../enums/custom-nodes/StringArrayCustomNode';
export type TStringArrayCustomNodeFactory = <
TInitialData extends unknown[] = unknown[]
> (stringArrayCustomNodeName: StringArrayCustomNode) => ICustomNode <TInitialData>;
| {
"content_hash": "e5252577703d5bbfe3db3597d2997085",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 90,
"avg_line_length": 49.42857142857143,
"alnum_prop": 0.7572254335260116,
"repo_name": "javascript-obfuscator/javascript-obfuscator",
"id": "b118f2e3c6239ed607ceab2e74f756cdc725a804",
"size": "346",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/types/container/custom-nodes/TStringArrayCustomNodeFactory.ts",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "JavaScript",
"bytes": "121363"
},
{
"name": "Shell",
"bytes": "60"
},
{
"name": "TypeScript",
"bytes": "2608798"
}
],
"symlink_target": ""
} |
<?php
namespace spec\PSB\Core\Pipeline\Outgoing\StageContext;
use PhpSpec\ObjectBehavior;
use PSB\Core\Pipeline\Outgoing\StageContext\SubscribeContext;
use PSB\Core\Pipeline\PipelineStageContext;
use PSB\Core\SubscribeOptions;
/**
* @mixin SubscribeContext
*/
class SubscribeContextSpec extends ObjectBehavior
{
function it_is_initializable(SubscribeOptions $options, PipelineStageContext $parentContext)
{
$this->beConstructedWith($irrelevantEvent = 'class', $options, $parentContext);
$this->shouldHaveType('PSB\Core\Pipeline\Outgoing\StageContext\SubscribeContext');
}
function it_contains_the_event_set_at_construction(SubscribeOptions $options, PipelineStageContext $parentContext)
{
$this->beConstructedWith('event', $options, $parentContext);
$this->getEventFqcn()->shouldReturn('event');
}
function it_contains_the_options_set_at_construction(SubscribeOptions $options, PipelineStageContext $parentContext)
{
$this->beConstructedWith($irrelevantEvent = 'class', $options, $parentContext);
$this->getSubscribeOptions()->shouldReturn($options);
}
function it_throws_if_event_is_empty_during_construction(
SubscribeOptions $options,
PipelineStageContext $parentContext
) {
$this->beConstructedWith('', $options, $parentContext);
$this->shouldThrow('PSB\Core\Exception\InvalidArgumentException')->duringInstantiation();
}
}
| {
"content_hash": "cb6c3ddfd426a96ea5865da9f686ba93",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 120,
"avg_line_length": 33.36363636363637,
"alnum_prop": 0.7302452316076294,
"repo_name": "phpservicebus/core",
"id": "b04a35907d92c49348798b3fa19743e87b37b667",
"size": "1468",
"binary": false,
"copies": "1",
"ref": "refs/heads/devel",
"path": "tests/spec/Pipeline/Outgoing/StageContext/SubscribeContextSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "927722"
}
],
"symlink_target": ""
} |
cask "mirrorop" do
version "2.5.3.78"
sha256 "59279a53f344ec0b6edb36015164497107a3fea1d55d337d2bf7185ee3bb5b01"
url "https://www.barco.com/services/website/en/TdeFiles/Download?FileNumber=R33050100&TdeType=3&MajorVersion=#{version.major}&MinorVersion=#{version.minor}&PatchVersion=#{version.patch}&BuildVersion=#{version.split(".")[-1]}"
name "MirrorOp Sender"
desc "Mirroring software application for wePresent systems"
homepage "https://www.barco.com/en/product/mirrorop"
livecheck do
url "https://www.barco.com/en/support/software/R33050100"
strategy :page_match
regex(/MirrorOp\s*Mac\s*Sender\s*v?(\d+(?:\.\d+)*)/i)
end
app "MirrorOp.app"
end
| {
"content_hash": "b713432392ca55cdc766a72ba497deb9",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 227,
"avg_line_length": 40,
"alnum_prop": 0.7411764705882353,
"repo_name": "bric3/homebrew-cask",
"id": "6386a9133d19e707552e0ebebf3a58c3b32a6bfb",
"size": "680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Casks/mirrorop.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Dockerfile",
"bytes": "249"
},
{
"name": "Python",
"bytes": "3630"
},
{
"name": "Ruby",
"bytes": "2549392"
},
{
"name": "Shell",
"bytes": "32035"
}
],
"symlink_target": ""
} |
package com.newrelic.metrics.publish;
import com.doodle.spam.SpamAgent;
import com.newrelic.metrics.publish.configuration.ConfigurationException;
import java.util.Map;
public class SpamAgentFactory extends AgentFactory {
@Override
public Agent createConfiguredAgent(Map<String, Object> properties) throws ConfigurationException {
String name = (String) properties.get("name");
String logFile = (String) properties.get("logFile");
String dateFormat = (String) properties.get("dateFormat");
String patternMethod = (String) properties.get("patternMethod");
String patternEndpoint = (String) properties.get("patternEndpoint");
String patternIpv4 = (String) properties.get("patternIpv4");
String patternIpv6 = (String) properties.get("patternIpv6");
if (name == null || logFile == null || dateFormat == null || patternMethod == null || patternEndpoint == null || patternIpv4 == null || patternIpv6 == null) {
throw new ConfigurationException("Missing or null configuration parameters");
}
return new SpamAgent(name, logFile, dateFormat, patternMethod, patternEndpoint, patternIpv4, patternIpv6);
}
}
| {
"content_hash": "d1d8b604f9902ffbec147b10182ee4f2",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 166,
"avg_line_length": 50.125,
"alnum_prop": 0.7107231920199502,
"repo_name": "DoodleScheduling/newrelic-spam",
"id": "cf350aecb5bfad2f04b0eeaa626d5e048ad710c3",
"size": "1203",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/newrelic/metrics/publish/SpamAgentFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "78166"
}
],
"symlink_target": ""
} |
package br.com.anne;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import br.com.anne.Imposto;
import br.com.anne.Carro;
public class ImpostoTest {
@Test
public void testImposto() {
Carro carro = new Carro(100.0);
Imposto imposto = new Imposto();
assertEquals(10.0, imposto.calcula(carro), Double.MIN_VALUE);
}
}
| {
"content_hash": "4a0177a2c21e4b32ddd3d59ae85413bf",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 63,
"avg_line_length": 19.38888888888889,
"alnum_prop": 0.7306590257879656,
"repo_name": "annelorayne/jenkins-exemplo",
"id": "c530a3b8f40b1e1f8d6eda34f7c2ebb6b065d3c8",
"size": "349",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/br/com/anne/ImpostoTest.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "853"
}
],
"symlink_target": ""
} |
module("wrapper", package.seeall)
local json = require("cjson.safe")
-- by default, only call json lib for encoding and decoding
function encode(object)
return json.encode(object)
end
function decode(object)
return json.decode(object)
end
| {
"content_hash": "6d1add8d6dda455f84ea07da89b59215",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 59,
"avg_line_length": 20.333333333333332,
"alnum_prop": 0.7663934426229508,
"repo_name": "paintsnow/luainsight",
"id": "f86b6d3bf4614a4ab51e44ded69b59c88789d27c",
"size": "244",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run/lua/wrapper.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Common Lisp",
"bytes": "973"
},
{
"name": "Lua",
"bytes": "4774"
}
],
"symlink_target": ""
} |
package org.eclipse.jnosql.artemis.column;
import jakarta.nosql.mapping.Page;
import jakarta.nosql.mapping.Pagination;
import jakarta.nosql.mapping.column.ColumnQueryPagination;
import jakarta.nosql.mapping.column.ColumnTemplate;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* An implementation of {@link Page} to Column.
*
* @param <T> the entity type
*/
final class ColumnPage<T> implements Page<T> {
private final ColumnTemplate template;
private final Stream<T> entities;
private final ColumnQueryPagination query;
private List<T> entitiesCache;
ColumnPage(ColumnTemplate template, Stream<T> entities, ColumnQueryPagination query) {
this.template = template;
this.entities = entities;
this.query = query;
}
@Override
public Pagination getPagination() {
return query.getPagination();
}
@Override
public Page<T> next() {
return template.select(query.next());
}
@Override
public Stream<T> getContent() {
return getEntities();
}
@Override
public <C extends Collection<T>> C getContent(Supplier<C> collectionFactory) {
Objects.requireNonNull(collectionFactory, "collectionFactory is required");
return getEntities().collect(Collectors.toCollection(collectionFactory));
}
@Override
public Stream<T> get() {
return getEntities();
}
private Stream<T> getEntities() {
if (Objects.isNull(entitiesCache)) {
synchronized (this) {
this.entitiesCache = entities.collect(Collectors.toList());
}
}
return entitiesCache.stream();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ColumnPage<?> that = (ColumnPage<?>) o;
return Objects.equals(entities, that.entities) &&
Objects.equals(query, that.query);
}
@Override
public int hashCode() {
return Objects.hash(entities, query);
}
@Override
public String toString() {
return "ColumnPage{" +
"entities=" + entities +
", query=" + query +
'}';
}
}
| {
"content_hash": "e7ad9ec7819d2f5b49b4d923bc94468a",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 90,
"avg_line_length": 25.040816326530614,
"alnum_prop": 0.6234718826405868,
"repo_name": "JNOSQL/diana",
"id": "01e75573ddcfac7243f8315de4ec290ca6ed62cf",
"size": "3035",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "artemis/artemis-column/src/main/java/org/eclipse/jnosql/artemis/column/ColumnPage.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "375379"
}
],
"symlink_target": ""
} |
<?php
namespace Youshido\GraphQLBundle\Tests\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Compiler\ResolveDefinitionTemplatesPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Youshido\GraphQLBundle\DependencyInjection\GraphQLExtension;
class GraphQLExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testDefaultConfigIsUsed()
{
$container = $this->loadContainerFromFile('empty', 'yml');
$this->assertNull($container->getParameter('graphql.schema_class'));
$this->assertEquals(null, $container->getParameter('graphql.max_complexity'));
$this->assertEquals(null, $container->getParameter('graphql.logger'));
$this->assertEmpty($container->getParameter('graphql.security.white_list'));
$this->assertEmpty($container->getParameter('graphql.security.black_list'));
$this->assertEquals([
'field' => false,
'operation' => false,
],
$container->getParameter('graphql.security.guard_config')
);
$this->assertTrue($container->getParameter('graphql.response.json_pretty'));
$this->assertEquals([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'Content-Type',
],
$container->getParameter('graphql.response.headers')
);
}
public function testDefaultCanBeOverridden()
{
$container = $this->loadContainerFromFile('full', 'yml');
$this->assertEquals('AppBundle\GraphQL\Schema', $container->getParameter('graphql.schema_class'));
$this->assertEquals(10, $container->getParameter('graphql.max_complexity'));
$this->assertEquals('@logger', $container->getParameter('graphql.logger'));
$this->assertEquals(['hello'], $container->getParameter('graphql.security.black_list'));
$this->assertEquals(['world'], $container->getParameter('graphql.security.white_list'));
$this->assertEquals([
'field' => true,
'operation' => true,
],
$container->getParameter('graphql.security.guard_config')
);
$this->assertFalse($container->getParameter('graphql.response.json_pretty'));
$this->assertEquals([
'X-Powered-By' => 'GraphQL',
],
$container->getParameter('graphql.response.headers')
);
}
private function loadContainerFromFile($file, $type, array $services = array(), $skipEnvVars = false)
{
$container = new ContainerBuilder();
if ($skipEnvVars && !method_exists($container, 'resolveEnvPlaceholders')) {
$this->markTestSkipped('Runtime environment variables has been introduced in the Dependency Injection version 3.2.');
}
$container->setParameter('kernel.debug', false);
$container->setParameter('kernel.cache_dir', '/tmp');
foreach ($services as $id => $service) {
$container->set($id, $service);
}
$container->registerExtension(new GraphQLExtension());
$locator = new FileLocator(__DIR__.'/Fixtures/config/'.$type);
switch ($type) {
case 'xml':
$loader = new XmlFileLoader($container, $locator);
break;
case 'yml':
$loader = new YamlFileLoader($container, $locator);
break;
case 'php':
$loader = new PhpFileLoader($container, $locator);
break;
default:
throw new \InvalidArgumentException('Invalid file type');
}
$loader->load($file.'.'.$type);
$container->getCompilerPassConfig()->setOptimizationPasses(array(
new ResolveDefinitionTemplatesPass(),
));
$container->getCompilerPassConfig()->setRemovingPasses(array());
$container->compile();
return $container;
}
} | {
"content_hash": "7243881ce47b8816337a4ac0ebcd5c14",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 129,
"avg_line_length": 41.03921568627451,
"alnum_prop": 0.6311514572384138,
"repo_name": "Youshido/GraphQLBundle",
"id": "7f882f1ea94192b8df330cdc0e4f68650a9c130e",
"size": "4186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tests/DependencyInjection/GraphQLExtensionTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "36637"
},
{
"name": "HTML",
"bytes": "6502"
},
{
"name": "PHP",
"bytes": "44263"
}
],
"symlink_target": ""
} |
@interface CHFirstViewController : UIViewController
@end
| {
"content_hash": "2ea2981bbf9100bf6947bf0c69e5cdd0",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 51,
"avg_line_length": 19.333333333333332,
"alnum_prop": 0.8448275862068966,
"repo_name": "chetem/CHTransitionAnimationController",
"id": "37f091b2ffc2511e979f9835d82fe60437378879",
"size": "259",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHTransitionAnimationControllerExample/ViewControllers/CHFirstViewController.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "25075"
}
],
"symlink_target": ""
} |
//
// FMDatabasePool.h
// fmdb
//
// Created by August Mueller on 6/22/11.
// Copyright 2011 Flying Meat Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <sqlite3.h>
@class LCDatabase;
/** Pool of `<FMDatabase>` objects.
### See also
- `<FMDatabaseQueue>`
- `<FMDatabase>`
@warning Before using `FMDatabasePool`, please consider using `<FMDatabaseQueue>` instead.
If you really really really know what you're doing and `FMDatabasePool` is what
you really really need (ie, you're using a read only database), OK you can use
it. But just be careful not to deadlock!
For an example on deadlocking, search for:
`ONLY_USE_THE_POOL_IF_YOU_ARE_DOING_READS_OTHERWISE_YOULL_DEADLOCK_USE_FMDATABASEQUEUE_INSTEAD`
in the main.m file.
*/
@interface LCDatabasePool : NSObject {
NSString *_path;
dispatch_queue_t _lockQueue;
NSMutableArray *_databaseInPool;
NSMutableArray *_databaseOutPool;
__unsafe_unretained id _delegate;
NSUInteger _maximumNumberOfDatabasesToCreate;
int _openFlags;
}
/** Database path */
@property (atomic, retain) NSString *path;
/** Delegate object */
@property (atomic, assign) id delegate;
/** Maximum number of databases to create */
@property (atomic, assign) NSUInteger maximumNumberOfDatabasesToCreate;
/** Open flags */
@property (atomic, readonly) int openFlags;
///---------------------
/// @name Initialization
///---------------------
/** Create pool using path.
@param aPath The file path of the database.
@return The `FMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString*)aPath;
/** Create pool using path and specified flags
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabasePool` object. `nil` on error.
*/
+ (instancetype)databasePoolWithPath:(NSString*)aPath flags:(int)openFlags;
/** Create pool using path.
@param aPath The file path of the database.
@return The `FMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath;
/** Create pool using path and specified flags.
@param aPath The file path of the database.
@param openFlags Flags passed to the openWithFlags method of the database
@return The `FMDatabasePool` object. `nil` on error.
*/
- (instancetype)initWithPath:(NSString*)aPath flags:(int)openFlags;
///------------------------------------------------
/// @name Keeping track of checked in/out databases
///------------------------------------------------
/** Number of checked-in databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfCheckedInDatabases;
/** Number of checked-out databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfCheckedOutDatabases;
/** Total number of databases in pool
@returns Number of databases
*/
- (NSUInteger)countOfOpenDatabases;
/** Release all databases in pool */
- (void)releaseAllDatabases;
///------------------------------------------
/// @name Perform database operations in pool
///------------------------------------------
/** Synchronously perform database operations in pool.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inDatabase:(void (^)(LCDatabase *db))block;
/** Synchronously perform database operations in pool using transaction.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inTransaction:(void (^)(LCDatabase *db, BOOL *rollback))block;
/** Synchronously perform database operations in pool using deferred transaction.
@param block The code to be run on the `FMDatabasePool` pool.
*/
- (void)inDeferredTransaction:(void (^)(LCDatabase *db, BOOL *rollback))block;
#if SQLITE_VERSION_NUMBER >= 3007000
/** Synchronously perform database operations in pool using save point.
@param block The code to be run on the `FMDatabasePool` pool.
@return `NSError` object if error; `nil` if successful.
@warning You can not nest these, since calling it will pull another database out of the pool and you'll get a deadlock. If you need to nest, use `<[FMDatabase startSavePointWithName:error:]>` instead.
*/
- (NSError*)inSavePoint:(void (^)(LCDatabase *db, BOOL *rollback))block;
#endif
@end
/** FMDatabasePool delegate category
This is a category that defines the protocol for the FMDatabasePool delegate
*/
@interface NSObject (FMDatabasePoolDelegate)
/** Asks the delegate whether database should be added to the pool.
@param pool The `FMDatabasePool` object.
@param database The `FMDatabase` object.
@return `YES` if it should add database to pool; `NO` if not.
*/
- (BOOL)databasePool:(LCDatabasePool*)pool shouldAddDatabaseToPool:(LCDatabase*)database;
/** Tells the delegate that database was added to the pool.
@param pool The `FMDatabasePool` object.
@param database The `FMDatabase` object.
*/
- (void)databasePool:(LCDatabasePool*)pool didAddDatabase:(LCDatabase*)database;
@end
| {
"content_hash": "f784147d9ba5a8b605fe8ddea9a29acf",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 201,
"avg_line_length": 24.96078431372549,
"alnum_prop": 0.6883346425765907,
"repo_name": "leancloud/objc-sdk",
"id": "08dbabbec8abbd545d2c46219e709e85882bb444",
"size": "5092",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AVOS/Sources/Foundation/Vendor/LCDB/LCDatabasePool.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "93210"
},
{
"name": "Objective-C",
"bytes": "2514989"
},
{
"name": "Ruby",
"bytes": "65481"
},
{
"name": "Shell",
"bytes": "2037"
},
{
"name": "Swift",
"bytes": "355909"
}
],
"symlink_target": ""
} |
package com.adviser.hibernate.tryouts.helpers.models;
/**
* @author Hendrik Nunner
*/
public interface Bar {
public long getId();
public void setId(long id);
public String getName();
public void setName(String name);
}
| {
"content_hash": "e75923ac4dd3d0978421b681c1106dd8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 53,
"avg_line_length": 18.46153846153846,
"alnum_prop": 0.6875,
"repo_name": "hnunner/hibernate-tryouts",
"id": "346becb6c6e0a7322785a61376a83c3de62f44bf",
"size": "240",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "helpers/src/main/java/com/adviser/hibernate/tryouts/helpers/models/Bar.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4359"
}
],
"symlink_target": ""
} |
/*
*
* ToolsSortOptions
*
*/
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { injectIntl } from 'react-intl';
import { createStructuredSelector } from 'reselect';
import styled from 'styled-components';
import makeSelectToolsSortOptions from './selectors';
import { changeSortOption } from './actions';
import { SORT_NEWEST, SORT_ALPHABETICAL } from './constants';
import {TextButton} from 'components/CommonComponents';
import IconButton from 'components/IconButton';
import TranslatableStaticText from 'containers/TranslatableStaticText';
import staticText from './staticText';
const Container = styled.div`
display: inline-block;
width: auto;
`;
const SortButton = styled(IconButton)`
margin-${p=>p.isArabic?'right':'left'}: ${p=>p.last?'24px':'0'};
`
export class ToolsSortOptions extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const { locale } = this.props.intl;
return (
<Container>
<SortButton isArabic={locale==='ar'} width="auto" onClick={this.props.clickAlphabeticalSort}>
<TextButton ar={locale==='ar'} selected={this.props.ToolsSortOptions.chosen === SORT_ALPHABETICAL}>
<TranslatableStaticText {...staticText.alphabeticalButton} />
</TextButton>
</SortButton>
<SortButton isArabic={locale==='ar'} last={true} width="auto" onClick={this.props.clickNewestSort}>
<TextButton selected={this.props.ToolsSortOptions.chosen === SORT_NEWEST}>
<TranslatableStaticText {...staticText.newestButton} />
</TextButton>
</SortButton>
</Container>
);
}
}
ToolsSortOptions.propTypes = {
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = createStructuredSelector({
ToolsSortOptions: makeSelectToolsSortOptions(),
});
function mapDispatchToProps(dispatch) {
return {
dispatch,
clickAlphabeticalSort: (evt) => {
dispatch(changeSortOption(SORT_ALPHABETICAL))
},
clickNewestSort: (evt) => {
dispatch(changeSortOption(SORT_NEWEST))
}
};
}
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ToolsSortOptions));
| {
"content_hash": "5c7bfb23dc3249afabe3583daa18636a",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 114,
"avg_line_length": 31.098591549295776,
"alnum_prop": 0.6997282608695652,
"repo_name": "BeautifulTrouble/beautifulrising-client",
"id": "c1297c9d2fdcda34fecfe7cce328064cc3712c6c",
"size": "2208",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/containers/ToolsSortOptions/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "10233"
},
{
"name": "JavaScript",
"bytes": "745162"
}
],
"symlink_target": ""
} |
/* ###
* IP: GHIDRA
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package agent.gdb.manager.impl;
import java.io.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.apache.commons.lang3.exception.ExceptionUtils;
import agent.gdb.manager.*;
import agent.gdb.manager.GdbCause.Causes;
import agent.gdb.manager.breakpoint.GdbBreakpointInfo;
import agent.gdb.manager.breakpoint.GdbBreakpointType;
import agent.gdb.manager.evt.*;
import agent.gdb.manager.impl.cmd.*;
import agent.gdb.manager.impl.cmd.GdbConsoleExecCommand.CompletesWithRunning;
import agent.gdb.manager.parsing.GdbMiParser;
import agent.gdb.manager.parsing.GdbParsingUtils.GdbParseError;
import agent.gdb.pty.*;
import agent.gdb.pty.windows.AnsiBufferedInputStream;
import ghidra.GhidraApplicationLayout;
import ghidra.async.*;
import ghidra.async.AsyncLock.Hold;
import ghidra.dbg.error.DebuggerModelTerminatingException;
import ghidra.dbg.util.HandlerMap;
import ghidra.dbg.util.PrefixMap;
import ghidra.framework.OperatingSystem;
import ghidra.lifecycle.Internal;
import ghidra.util.Msg;
import ghidra.util.SystemUtilities;
import ghidra.util.datastruct.ListenerSet;
import sun.misc.Signal;
import sun.misc.SignalHandler;
/**
* Implementation of {@link GdbManager}
*
* <p>
* This is implemented using the asynchronous chaining library and executors. A single-threaded
* executor handles issuing GDB command and processing events. Another thread handles reading GDB's
* output and parsing events. Those events are then scheduled for processing on the executor. The
* executor guarantees that commands are executed serially while reducing the risk of deadlock since
* the asynchronous calls return futures immediately.
*
* <p>
* A {@link PrefixMap} aids in parsing GDB events. The event details are then parsed with the
* {@link GdbMiParser} and passed around for processing. If a command is currently executed, that
* command has the first option to claim or steal the event. If it is stolen, no further processing
* takes place in the manager. If no command is executing, or the command does not steal it, the
* event is processed using a {@link HandlerMap}.
*/
public class GdbManagerImpl implements GdbManager {
private static final int TIMEOUT_SEC = 10;
private static final String GDB_IS_TERMINATING = "GDB is terminating";
public static final int MAX_CMD_LEN = 4094; // Account for longest possible line end
private String maintInfoSectionsCmd = GdbModuleImpl.MAINT_INFO_SECTIONS_CMD_V11;
private Pattern fileLinePattern = GdbModuleImpl.OBJECT_FILE_LINE_PATTERN_V11;
private Pattern sectionLinePattern = GdbModuleImpl.OBJECT_SECTION_LINE_PATTERN_V10;
private static final String PTY_DIALOG_MESSAGE_PATTERN =
"<html><p>Please enter:</p>" +
"<pre>new-ui mi2 <b>{0}</b></pre>" + "" +
"<p>into an existing gdb session.</p><br/>" +
"<p>Alternatively, to launch a new session, cancel this dialog. " +
"Then, retry with <b>use existing session</b> disabled.</p></html>";
private static final String CANCEL = "Cancel";
@Internal
public enum Interpreter {
CLI, MI2;
}
private static final boolean LOG_IO =
Boolean.getBoolean("agent.gdb.manager.log") || SystemUtilities.isInDevelopmentMode();
private static PrintWriter DBG_LOG = null;
private static final String PROMPT_GDB = "(gdb)";
public static final int INTERRUPT_MAX_RETRIES = 3;
public static final int INTERRUPT_RETRY_PERIOD_MILLIS = 100;
class PtyThread extends Thread {
final Pty pty;
final BufferedReader reader;
final Channel channel;
Interpreter interpreter;
PrintWriter writer;
CompletableFuture<Void> hasWriter;
PtyThread(Pty pty, Channel channel, Interpreter interpreter) {
this.pty = pty;
this.channel = channel;
InputStream inputStream = pty.getParent().getInputStream();
// TODO: This should really only be applied to the MI2 console
// But, we don't know what we have until we read it....
if (OperatingSystem.CURRENT_OPERATING_SYSTEM == OperatingSystem.WINDOWS) {
inputStream = new AnsiBufferedInputStream(inputStream);
}
this.reader = new BufferedReader(new InputStreamReader(inputStream));
this.interpreter = interpreter;
hasWriter = new CompletableFuture<>();
}
@Override
public void run() {
if (LOG_IO && DBG_LOG == null) {
initLog();
}
try {
String line;
while (GdbManagerImpl.this.isAlive() && null != (line = reader.readLine())) {
String l = line;
if (interpreter == null) {
if (l.startsWith("=") || l.startsWith("~")) {
interpreter = Interpreter.MI2;
}
else {
interpreter = Interpreter.CLI;
}
}
if (writer == null) {
writer = new PrintWriter(pty.getParent().getOutputStream());
hasWriter.complete(null);
}
//Msg.debug(this, channel + ": " + line);
submit(() -> {
if (LOG_IO) {
DBG_LOG.println("<" + interpreter + ": " + l);
DBG_LOG.flush();
}
processLine(l, channel, interpreter);
});
}
}
catch (Throwable e) {
terminate();
Msg.debug(this, channel + "," + interpreter + " reader exiting because " + e);
//throw new AssertionError(e);
}
}
}
class PtyInfoDialogThread extends Thread {
private final JOptionPane pane;
private final JDialog dialog;
final CompletableFuture<Integer> result = new CompletableFuture<>();
public PtyInfoDialogThread(String ptyName) {
String message = MessageFormat.format(PTY_DIALOG_MESSAGE_PATTERN, ptyName);
pane = new JOptionPane(message, JOptionPane.PLAIN_MESSAGE, 0, null,
new Object[] { CANCEL });
dialog = pane.createDialog("Waiting for GDB/MI session");
}
@Override
public void run() {
dialog.setVisible(true);
Object sel = pane.getValue();
if (CANCEL.equals(sel)) {
result.complete(JOptionPane.CANCEL_OPTION);
}
else {
result.complete(JOptionPane.CLOSED_OPTION);
}
}
}
private final PtyFactory ptyFactory;
private final AsyncReference<GdbState, GdbCause> state =
new AsyncReference<>(GdbState.NOT_STARTED);
// A copy of state, which is updated on the eventThread.
private final AsyncReference<GdbState, GdbCause> asyncState = new AsyncReference<>(state.get());
private Interpreter runningInterpreter;
private final AsyncReference<Boolean, Void> mi2Prompt = new AsyncReference<>(false);
private final PrefixMap<GdbEvent<?>, GdbParseError> mi2PrefixMap = new PrefixMap<>();
private final HandlerMap<GdbEvent<?>, Void, Void> handlerMap = new HandlerMap<>();
private final AtomicBoolean exited = new AtomicBoolean(false);
private PtySession gdb;
private Thread gdbWaiter;
private PtyThread iniThread;
private PtyThread cliThread;
private PtyThread mi2Thread;
private String newLine = System.lineSeparator();
private final AsyncLock cmdLock = new AsyncLock();
private final AtomicReference<AsyncLock.Hold> cmdLockHold = new AtomicReference<>(null);
private ExecutorService executor;
private GdbPendingCommand<?> curCmd = null;
private int interruptCount = 0;
private final Map<Integer, GdbInferiorImpl> inferiors = new LinkedHashMap<>();
private GdbInferiorImpl curInferior = null;
private final Map<Integer, GdbInferior> unmodifiableInferiors =
Collections.unmodifiableMap(inferiors);
private final Map<Integer, GdbThreadImpl> threads = new LinkedHashMap<>();
private final Map<Integer, GdbThread> unmodifiableThreads =
Collections.unmodifiableMap(threads);
private final Map<Long, GdbBreakpointInfo> breakpoints = new LinkedHashMap<>();
private final Map<Long, GdbBreakpointInfo> unmodifiableBreakpoints =
Collections.unmodifiableMap(breakpoints);
protected final ListenerSet<GdbEventsListener> listenersEvent =
new ListenerSet<>(GdbEventsListener.class);
protected final ListenerSet<GdbTargetOutputListener> listenersTargetOutput =
new ListenerSet<>(GdbTargetOutputListener.class);
protected final ListenerSet<GdbConsoleOutputListener> listenersConsoleOutput =
new ListenerSet<>(GdbConsoleOutputListener.class);
protected final ExecutorService eventThread = Executors.newSingleThreadExecutor();
/**
* Instantiate a new manager
*
* @param ptyFactory a factory for creating Pty's for child GDBs
*/
public GdbManagerImpl(PtyFactory ptyFactory) {
this.ptyFactory = ptyFactory;
state.filter(this::stateFilter);
state.addChangeListener(this::trackRunningInterpreter);
state.addChangeListener((os, ns, c) -> event(() -> asyncState.set(ns, c), "managerState"));
defaultPrefixes();
defaultHandlers();
}
private void initLog() {
try {
GhidraApplicationLayout layout = new GhidraApplicationLayout();
File userSettings = layout.getUserSettingsDir();
File logFile = new File(userSettings, "GDB.log");
try {
logFile.getParentFile().mkdirs();
logFile.createNewFile();
}
catch (Exception e) {
throw new AssertionError(logFile.getPath() + " appears to be unwritable", e);
}
DBG_LOG = new PrintWriter(new FileOutputStream(logFile));
}
catch (IOException e) {
throw new AssertionError(e);
}
}
CompletableFuture<Void> event(Runnable r, String text) {
//Msg.debug(this, "Queueing event: " + text);
return CompletableFuture.runAsync(r, eventThread).exceptionally(ex -> {
Msg.error(this, "Error in event callback:", ex);
return ExceptionUtils.rethrow(ex);
});
}
private GdbState stateFilter(GdbState cur, GdbState set, GdbCause cause) {
if (set == null) {
return cur;
}
return set;
}
private void trackRunningInterpreter(GdbState oldSt, GdbState st, GdbCause cause) {
if (st == GdbState.RUNNING && cause instanceof GdbPendingCommand) {
GdbPendingCommand<?> pcmd = (GdbPendingCommand<?>) cause;
runningInterpreter = pcmd.getCommand().getInterpreter();
//Msg.debug(this, "Entered " + st + " with interpreter: " + runningInterpreter);
}
else {
runningInterpreter = null;
}
}
private void defaultPrefixes() {
mi2PrefixMap.put("-exec-interrupt", GdbCommandEchoInterruptEvent::new);
mi2PrefixMap.put("-", GdbCommandEchoEvent::new);
mi2PrefixMap.put("~", GdbConsoleOutputEvent::fromMi2);
mi2PrefixMap.put("@", GdbTargetOutputEvent::new);
mi2PrefixMap.put("&", GdbDebugOutputEvent::new);
mi2PrefixMap.put("^done", GdbCommandDoneEvent::new);
mi2PrefixMap.put("^running", GdbCommandRunningEvent::new);
mi2PrefixMap.put("^connected", GdbCommandConnectedEvent::new);
mi2PrefixMap.put("^exit", GdbCommandExitEvent::new);
mi2PrefixMap.put("^error", GdbCommandErrorEvent::fromMi2);
mi2PrefixMap.put("*running", GdbRunningEvent::new);
mi2PrefixMap.put("*stopped", GdbStoppedEvent::new);
mi2PrefixMap.put("=thread-group-added", GdbThreadGroupAddedEvent::new);
mi2PrefixMap.put("=thread-group-removed", GdbThreadGroupRemovedEvent::new);
mi2PrefixMap.put("=thread-group-started", GdbThreadGroupStartedEvent::new);
mi2PrefixMap.put("=thread-group-exited", GdbThreadGroupExitedEvent::new);
mi2PrefixMap.put("=thread-created", GdbThreadCreatedEvent::new);
mi2PrefixMap.put("=thread-exited", GdbThreadExitedEvent::new);
mi2PrefixMap.put("=thread-selected", GdbThreadSelectedEvent::new);
mi2PrefixMap.put("=library-loaded", GdbLibraryLoadedEvent::new);
mi2PrefixMap.put("=library-unloaded", GdbLibraryUnloadedEvent::new);
mi2PrefixMap.put("=breakpoint-created", t -> new GdbBreakpointCreatedEvent(t, this));
mi2PrefixMap.put("=breakpoint-modified", GdbBreakpointModifiedEvent::new);
mi2PrefixMap.put("=breakpoint-deleted", GdbBreakpointDeletedEvent::new);
mi2PrefixMap.put("=memory-changed", GdbMemoryChangedEvent::new);
mi2PrefixMap.put("=cmd-param-changed", GdbParamChangedEvent::new);
}
private void defaultHandlers() {
handlerMap.putVoid(GdbCommandEchoInterruptEvent.class, this::pushCmdInterrupt);
handlerMap.putVoid(GdbCommandEchoEvent.class, this::ignoreCmdEcho);
handlerMap.putVoid(GdbConsoleOutputEvent.class, this::processStdOut);
handlerMap.putVoid(GdbTargetOutputEvent.class, this::processTargetOut);
handlerMap.putVoid(GdbDebugOutputEvent.class, this::processStdErr);
handlerMap.putVoid(GdbCommandDoneEvent.class, this::processCommandDone);
handlerMap.putVoid(GdbCommandRunningEvent.class, this::processCommandRunning);
handlerMap.putVoid(GdbCommandConnectedEvent.class, this::processCommandConnected);
handlerMap.putVoid(GdbCommandExitEvent.class, this::processCommandExit);
handlerMap.putVoid(GdbCommandErrorEvent.class, this::processCommandError);
handlerMap.putVoid(GdbRunningEvent.class, this::processRunning);
handlerMap.putVoid(GdbStoppedEvent.class, this::processStopped);
handlerMap.putVoid(GdbThreadGroupAddedEvent.class, this::processThreadGroupAdded);
handlerMap.putVoid(GdbThreadGroupRemovedEvent.class, this::processThreadGroupRemoved);
handlerMap.putVoid(GdbThreadGroupStartedEvent.class, this::processThreadGroupStarted);
handlerMap.putVoid(GdbThreadGroupExitedEvent.class, this::processThreadGroupExited);
handlerMap.putVoid(GdbThreadCreatedEvent.class, this::processThreadCreated);
handlerMap.putVoid(GdbThreadExitedEvent.class, this::processThreadExited);
handlerMap.putVoid(GdbThreadSelectedEvent.class, this::processThreadSelected);
handlerMap.putVoid(GdbLibraryLoadedEvent.class, this::processLibraryLoaded);
handlerMap.putVoid(GdbLibraryUnloadedEvent.class, this::processLibraryUnloaded);
handlerMap.putVoid(GdbBreakpointCreatedEvent.class, this::processBreakpointCreated);
handlerMap.putVoid(GdbBreakpointModifiedEvent.class, this::processBreakpointModified);
handlerMap.putVoid(GdbBreakpointDeletedEvent.class, this::processBreakpointDeleted);
handlerMap.putVoid(GdbMemoryChangedEvent.class, this::processMemoryChanged);
handlerMap.putVoid(GdbParamChangedEvent.class, this::processParamChanged);
}
@Override
public boolean isAlive() {
return state.get().isAlive();
}
@Override
public void addStateListener(GdbStateListener listener) {
asyncState.addChangeListener(listener);
}
@Override
public void removeStateListener(GdbStateListener listener) {
asyncState.removeChangeListener(listener);
}
@Override
public void addEventsListener(GdbEventsListener listener) {
listenersEvent.add(listener);
}
@Override
public void removeEventsListener(GdbEventsListener listener) {
listenersEvent.remove(listener);
}
@Internal // for detach command
public void fireThreadExited(int tid, GdbInferiorImpl inferior, GdbCause cause) {
event(() -> listenersEvent.fire.threadExited(tid, inferior, cause), "threadExited");
}
@Override
public void addTargetOutputListener(GdbTargetOutputListener listener) {
listenersTargetOutput.add(listener);
}
@Override
public void removeTargetOutputListener(GdbTargetOutputListener listener) {
listenersTargetOutput.remove(listener);
}
@Override
public void addConsoleOutputListener(GdbConsoleOutputListener listener) {
listenersConsoleOutput.add(listener);
}
@Override
public void removeConsoleOutputListener(GdbConsoleOutputListener listener) {
listenersConsoleOutput.remove(listener);
}
/**
* Use {@link GdbThreadImpl#add()} instead
*
* @param thread the thread to add
*/
public void addThread(GdbThreadImpl thread) {
GdbThreadImpl exists = threads.get(thread.getId());
if (exists != null) {
throw new IllegalArgumentException("There is already thread " + exists);
}
threads.put(thread.getId(), thread);
}
@Override
public GdbThreadImpl getThread(int tid) {
GdbThreadImpl result = threads.get(tid);
if (result == null) {
throw new IllegalArgumentException("There is no thread with id " + tid);
}
return result;
}
public CompletableFuture<GdbThreadInfo> getThreadInfo(int threadId) {
return execute(new GdbGetThreadInfoCommand(this, threadId));
}
/**
* Use {@link GdbThreadImpl#remove()} instead
*
* @param tid the thread ID to remove
*/
public void removeThread(int tid) {
if (threads.remove(tid) == null) {
throw new IllegalArgumentException("There is no thread with id " + tid);
}
}
/**
* Use {@link GdbInferiorImpl#add(GdbCause)} instead
*
* @param inferior the inferior to add
* @param cause the cause of the new inferior
*/
@Internal
public void addInferior(GdbInferiorImpl inferior, GdbCause cause) {
GdbInferiorImpl exists = inferiors.get(inferior.getId());
if (exists != null) {
throw new IllegalArgumentException("There is already inferior " + exists);
}
inferiors.put(inferior.getId(), inferior);
event(() -> listenersEvent.fire.inferiorAdded(inferior, cause), "addInferior");
}
/**
* Use {@link GdbInferiorImpl#remove(GdbCause)} instead
*
* @param iid the inferior ID to remove
* @param cause the cause of removal
*/
@Internal
public void removeInferior(int iid, GdbCause cause) {
if (inferiors.remove(iid) == null) {
throw new IllegalArgumentException("There is no inferior with id " + iid);
}
event(() -> listenersEvent.fire.inferiorRemoved(iid, cause), "removeInferior");
}
/**
* Update the selected inferior
*
* @param inferior the inferior that now has focus
* @param cause the cause of the focus change
*/
protected boolean updateCurrentInferior(GdbInferiorImpl inferior, GdbCause cause,
boolean fire) {
// GDB will not permit removing all inferiors, so one is guaranteed to exist
// GDB may actually have already selected it, but without generating events
GdbInferiorImpl inf = inferior != null ? inferior : inferiors.values().iterator().next();
if (curInferior != inf) {
curInferior = inf;
if (fire) {
event(() -> listenersEvent.fire.inferiorSelected(inf, cause),
"updateCurrentInferior");
}
return true;
}
return false;
}
@Override
public GdbInferiorImpl getInferior(int iid) {
GdbInferiorImpl result = inferiors.get(iid);
if (result == null) {
throw new IllegalArgumentException("There is no inferior with id " + iid);
}
return result;
}
private void checkStarted() {
if (state.get() == GdbState.NOT_STARTED) {
throw new IllegalStateException(
"GDB has not been started or has not finished starting");
}
}
private void checkStartedNotExit() {
checkStarted();
if (state.get() == GdbState.EXIT) {
throw new DebuggerModelTerminatingException(GDB_IS_TERMINATING);
}
}
@Override
public GdbInferior currentInferior() {
checkStartedNotExit();
return curInferior;
}
@Override
public Map<Integer, GdbInferior> getKnownInferiors() {
return unmodifiableInferiors;
}
@Internal
public Map<Integer, GdbInferiorImpl> getKnownInferiorsInternal() {
return inferiors;
}
@Override
public Map<Integer, GdbThread> getKnownThreads() {
return unmodifiableThreads;
}
@Override
public Map<Long, GdbBreakpointInfo> getKnownBreakpoints() {
return unmodifiableBreakpoints;
}
@Internal
public Map<Long, GdbBreakpointInfo> getKnownBreakpointsInternal() {
return breakpoints;
}
public GdbBreakpointInfo addKnownBreakpoint(GdbBreakpointInfo bkpt, boolean expectExisting) {
GdbBreakpointInfo old = breakpoints.put(bkpt.getNumber(), bkpt);
if (expectExisting && old == null) {
Msg.warn(this, "Was missing breakpoint " + bkpt.getNumber());
}
else if (!expectExisting && old != null) {
Msg.warn(this, "Already had breakpoint " + bkpt.getNumber());
}
return old;
}
private GdbBreakpointInfo getKnownBreakpoint(long number) {
GdbBreakpointInfo info = breakpoints.get(number);
if (info == null) {
Msg.warn(this, "Breakpoint " + number + " is not known");
}
return info;
}
public GdbBreakpointInfo removeKnownBreakpoint(long number) {
GdbBreakpointInfo del = breakpoints.remove(number);
if (del == null) {
Msg.warn(this, "Deleted missing breakpoint " + number);
}
return del;
}
@Override
public CompletableFuture<GdbBreakpointInfo> insertBreakpoint(String loc,
GdbBreakpointType type) {
return execute(new GdbInsertBreakpointCommand(this, null, loc, type));
}
@Override
public CompletableFuture<Void> disableBreakpoints(long... numbers) {
return execute(new GdbDisableBreakpointsCommand(this, numbers));
}
@Override
public CompletableFuture<Void> enableBreakpoints(long... numbers) {
return execute(new GdbEnableBreakpointsCommand(this, numbers));
}
@Override
public CompletableFuture<Void> deleteBreakpoints(long... numbers) {
return execute(new GdbDeleteBreakpointsCommand(this, numbers));
}
@Override
public CompletableFuture<Map<Long, GdbBreakpointInfo>> listBreakpoints() {
return execute(new GdbListBreakpointsCommand(this, null));
}
private void submit(Runnable runnable) {
checkStartedNotExit();
executor.submit(() -> {
try {
runnable.run();
}
catch (Throwable e) {
e.printStackTrace();
}
});
}
@Override
public void setNewLine(String newLine) {
this.newLine = newLine;
}
protected void waitCheckExit(CompletableFuture<?> future)
throws InterruptedException, ExecutionException, TimeoutException, IOException {
CompletableFuture.anyOf(future, state.waitValue(GdbState.EXIT))
.get(TIMEOUT_SEC, TimeUnit.SECONDS);
if (state.get() == GdbState.EXIT) {
throw new IOException(
"GDB terminated early or could not be executed. Check your command line.");
}
}
@Override
public void start(String gdbCmd, String... args) throws IOException {
List<String> fullargs = new ArrayList<>();
fullargs.addAll(Arrays.asList(gdbCmd));
fullargs.addAll(Arrays.asList(args));
state.set(GdbState.STARTING, Causes.UNCLAIMED);
executor = Executors.newSingleThreadExecutor();
if (gdbCmd != null) {
iniThread = new PtyThread(ptyFactory.openpty(), Channel.STDOUT, null);
gdb = iniThread.pty.getChild().session(fullargs.toArray(new String[] {}), null);
gdbWaiter = new Thread(this::waitGdbExit, "GDB WaitExit");
gdbWaiter.start();
iniThread.start();
try {
waitCheckExit(iniThread.hasWriter);
}
catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new IOException(
"Could not detect GDB's interpreter mode. Try " + gdbCmd + " -i mi2");
}
switch (iniThread.interpreter) {
case CLI:
Pty mi2Pty = ptyFactory.openpty();
cliThread = iniThread;
cliThread.setName("GDB Read CLI");
// Looks terrible, but we're already in this world
cliThread.writer.print("set confirm off" + newLine);
cliThread.writer.print("set pagination off" + newLine);
String ptyName;
try {
ptyName = Objects.requireNonNull(mi2Pty.getChild().nullSession());
}
catch (UnsupportedOperationException e) {
throw new IOException(
"Pty implementation does not support null sessions. Try " + gdbCmd +
" i mi2",
e);
}
cliThread.writer.print("new-ui mi2 " + ptyName + newLine);
cliThread.writer.flush();
mi2Thread = new PtyThread(mi2Pty, Channel.STDOUT, Interpreter.MI2);
mi2Thread.setName("GDB Read MI2");
mi2Thread.start();
try {
waitCheckExit(mi2Thread.hasWriter);
}
catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new IOException(
"Could not obtain GDB/MI2 interpreter. Try " + gdbCmd + " -i mi2");
}
break;
case MI2:
mi2Thread = iniThread;
mi2Thread.setName("GDB Read MI2");
break;
}
}
else {
Pty mi2Pty = ptyFactory.openpty();
String mi2PtyName = mi2Pty.getChild().nullSession();
Msg.info(this, "Agent is waiting for GDB/MI v2 interpreter at " + mi2PtyName);
mi2Thread = new PtyThread(mi2Pty, Channel.STDOUT, Interpreter.MI2);
mi2Thread.setName("GDB Read MI2");
mi2Thread.start();
PtyInfoDialogThread dialog = new PtyInfoDialogThread(mi2PtyName);
dialog.start();
dialog.result.thenAccept(choice -> {
if (choice == JOptionPane.CANCEL_OPTION) {
mi2Thread.hasWriter.cancel(false);
// This will cause
}
});
// Yes, wait on the user indefinitely.
try {
mi2Thread.hasWriter.get();
}
catch (InterruptedException | ExecutionException e) {
Msg.info(this, "The user cancelled, or something else: " + e);
terminate();
}
dialog.dialog.setVisible(false);
}
// Do this whether or not joining existing. It's possible .gdbinit did stuff.
resync();
}
@Override
public CompletableFuture<Void> runRC() {
return waitForPrompt().thenCompose(__ -> rc());
}
/**
* Execute commands upon GDB startup
*
* @return a future which completes when the rc commands are complete
*/
protected CompletableFuture<Void> rc() {
if (cliThread != null) {
// NB. confirm and pagination are already disabled here
return AsyncUtils.NIL;
}
// NB. Don't disable pagination here. MI2 is not paginated.
return CompletableFuture.allOf(
console("set confirm off", CompletesWithRunning.CANNOT),
console("set new-console on", CompletesWithRunning.CANNOT).exceptionally(e -> {
// not Windows. So what?
return null;
}));
}
protected void resync() {
AsyncFence fence = new AsyncFence();
fence.include(listInferiors().thenCompose(infs -> {
AsyncFence inner = new AsyncFence();
for (GdbInferior inf : infs.values()) {
// NOTE: Mappings need not be constantly synced
// NOTE: Modules need not be constantly synced
inner.include(inf.listThreads());
}
return inner.ready();
}));
fence.include(listBreakpoints());
// NOTE: Available processes need not be constantly synced
fence.ready().exceptionally(ex -> {
Msg.error(this, "Could not resync the GDB session: " + ex);
return null;
});
}
private void waitGdbExit() {
try {
int exitcode = gdb.waitExited();
state.set(GdbState.EXIT, Causes.UNCLAIMED);
exited.set(true);
if (!executor.isShutdown()) {
processGdbExited(exitcode);
terminate();
}
}
catch (InterruptedException e) {
terminate();
}
}
@Override
public synchronized void terminate() {
Msg.debug(this, "Terminating " + this);
checkStarted();
exited.set(true);
executor.shutdownNow();
if (gdbWaiter != null) {
gdbWaiter.interrupt();
}
if (gdb != null) {
gdb.destroyForcibly();
}
try {
if (cliThread != null) {
cliThread.interrupt();
cliThread.pty.close();
}
if (mi2Thread != null) {
mi2Thread.interrupt();
mi2Thread.pty.close();
}
}
catch (IOException e) {
Msg.error(this, "Problem closing PTYs to GDB.");
}
DebuggerModelTerminatingException reason =
new DebuggerModelTerminatingException(GDB_IS_TERMINATING);
cmdLock.dispose(reason);
state.dispose(reason);
mi2Prompt.dispose(reason);
for (GdbThreadImpl thread : threads.values()) {
thread.dispose(reason);
}
GdbPendingCommand<?> cc = this.curCmd; // read volatile
if (cc != null && !cc.isDone()) {
cc.completeExceptionally(reason);
}
}
protected <T> CompletableFuture<T> execute(GdbCommand<? extends T> cmd) {
// NB. curCmd::finish is passed to eventThread already
return doExecute(cmd);//.thenApplyAsync(t -> t, eventThread);
}
/**
* Schedule a command for execution
*
* @param cmd the command to execute
* @return the pending command, which acts as a future for later completion
*/
protected <T> GdbPendingCommand<T> doExecute(GdbCommand<? extends T> cmd) {
assert cmd != null;
checkStartedNotExit();
GdbPendingCommand<T> pcmd = new GdbPendingCommand<>(cmd);
//Msg.debug(this, "WAITING cmdLock: " + pcmd);
cmdLock.acquire(null).thenAccept(hold -> {
cmdLockHold.set(hold);
//Msg.debug(this, "ACQUIRED cmdLock: " + pcmd);
synchronized (this) {
if (curCmd != null) {
throw new AssertionError("Cannot execute more than one command at a time");
}
if (gdb != null && !cmd.validInState(state.get())) {
throw new GdbCommandError(
"Command " + cmd + " is not valid while " + state.get());
}
cmd.preCheck(pcmd);
if (pcmd.isDone()) {
cmdLockHold.getAndSet(null).release();
return;
}
curCmd = pcmd;
//Msg.debug(this, "CURCMD = " + curCmd);
if (LOG_IO) {
DBG_LOG.println("*CMD: " + cmd.getClass());
DBG_LOG.flush();
}
String text = cmd.encode();
if (text != null) {
Interpreter interpreter = cmd.getInterpreter();
PrintWriter wr = getWriter(interpreter);
//Msg.debug(this, "STDIN: " + text);
wr.print(text + newLine);
wr.flush();
if (LOG_IO) {
DBG_LOG.println(">" + interpreter + ": " + text);
DBG_LOG.flush();
}
}
}
}).exceptionally((exc) -> {
pcmd.completeExceptionally(exc);
//Msg.debug(this, "ON_EXCEPTION: CURCMD = " + curCmd);
synchronized (this) {
curCmd = null;
}
//Msg.debug(this, "SET CURCMD = null");
//Msg.debug(this, "RELEASING cmdLock");
Hold hold = cmdLockHold.getAndSet(null);
if (hold != null) {
hold.release();
}
return null;
});
return pcmd;
}
@Override
public void cancelCurrentCommand() {
GdbPendingCommand<?> curCmd;
synchronized (this) {
curCmd = this.curCmd;
this.curCmd = null;
}
if (curCmd != null) {
Msg.info(this, "Cancelling current command: " + curCmd);
curCmd.cancel(false);
}
Hold hold = cmdLockHold.getAndSet(null);
if (hold != null) {
hold.release();
}
}
protected PrintWriter getWriter(Interpreter interpreter) {
switch (interpreter) {
case CLI:
return cliThread == null ? null : cliThread.writer;
case MI2:
return mi2Thread == null ? null : mi2Thread.writer;
default:
throw new AssertionError();
}
}
protected void checkImpliedFocusChange() {
Integer tid = curCmd.impliesCurrentThreadId();
GdbThreadImpl thread = null;
if (tid != null) {
thread = threads.get(tid);
if (thread == null) {
Msg.info(this, "Thread " + tid + " no longer exists");
return;
// Presumably, some event will have announced the new current thread
}
}
Integer level = curCmd.impliesCurrentFrameId();
GdbStackFrameImpl frame = null;
if (level != null) {
frame = new GdbStackFrameImpl(thread, level, null, null);
}
if (thread != null) {
doThreadSelected(thread, frame, curCmd);
}
}
protected synchronized void processEvent(GdbEvent<?> evt) {
if (evt instanceof AbstractGdbCompletedCommandEvent && interruptCount > 0) {
interruptCount--;
Msg.debug(this, "Ignoring " + evt +
" from -exec-interrupt. new count = " + interruptCount);
return;
}
/**
* NOTE: I've forgotten why, but the the state update needs to happen between handle and
* finish.
*/
boolean cmdFinished = false;
if (curCmd != null) {
cmdFinished = curCmd.handle(evt);
if (cmdFinished) {
checkImpliedFocusChange();
}
}
GdbState newState = evt.newState();
//Msg.debug(this, evt + " transitions state to " + newState);
state.set(newState, evt.getCause());
// NOTE: Do not check if claimed here.
// Downstream processing should check for cause
handlerMap.handle(evt, null);
if (cmdFinished) {
event(curCmd::finish, "curCmd::finish");
curCmd = null;
cmdLockHold.getAndSet(null).release();
}
}
/**
* Schedule a line of GDB output for processing
*
* <p>
* Before the implementation started using a PTY, the channel was used to distinguish whether
* the line was read from stdout or stderr. Now, all output is assumed to be from stdout.
*
* @param line the line
* @param channel the channel producing the line (stdout)
*/
protected synchronized void processLine(String line, Channel channel, Interpreter interpreter) {
if (interpreter == Interpreter.CLI) {
processEvent(GdbConsoleOutputEvent.fromCli(line));
return;
}
if ("".equals(line.trim())) {
return;
}
//Msg.debug(this, "processing: " + channel + ": " + line);
mi2Prompt.set(false, null); // Go ahead and fire on a second consecutive prompt
if (PROMPT_GDB.equals(line.trim())) {
if (state.get() == GdbState.STARTING) {
state.set(GdbState.STOPPED, Causes.UNCLAIMED);
}
//Msg.debug(this, "AT_PROMPT: CURCMD = " + curCmd);
/*if (curCmd != null) {
curCmd.finish();
curCmd = null;
//Msg.debug(this, "SET CURCMD = null");
//Msg.debug(this, "RELEASING cmdLock");
cmdLockHold.getAndSet(null).release();
}*/
mi2Prompt.set(true, null);
}
else {
GdbEvent<?> evt = null;
try {
while (line.startsWith("^C")) {
Msg.info(this, "Got ^C");
line = line.substring(2);
}
evt = mi2PrefixMap.construct(line);
if (evt == null) {
Msg.warn(this, "Unknown event: " + line);
return;
}
processEvent(evt);
}
catch (GdbParseError e) {
throw new RuntimeException("GDB gave an unrecognized response", e);
}
catch (IllegalArgumentException e) {
Msg.warn(this, "Error processing GDB output", e);
}
}
}
protected void processGdbExited(int exitcode) {
Msg.info(this, "GDB exited with code " + exitcode);
}
protected void pushCmdInterrupt(GdbCommandEchoInterruptEvent evt, Void v) {
interruptCount++;
}
/**
* Called for lines starting with "-", which are just commands echoed back by the PTY
*
* @param evt the "event"
* @param v nothing
*/
protected void ignoreCmdEcho(GdbCommandEchoEvent evt, Void v) {
// Do nothing
}
/**
* Called for lines starting with "~", which are lines GDB would like printed to stdout
*
* @param evt the event
* @param v nothing
*/
protected void processStdOut(GdbConsoleOutputEvent evt, Void v) {
String out = evt.getOutput();
//System.out.print(out);
if (!evt.isStolen()) {
listenersConsoleOutput.fire.output(Channel.STDOUT, out);
}
if (evt.getInterpreter() == Interpreter.MI2 &&
out.toLowerCase().contains("switching to inferior")) {
String[] parts = out.trim().split("\\s+");
int iid = Integer.parseInt(parts[3]);
updateCurrentInferior(getInferior(iid), evt.getCause(), true);
}
}
/**
* Called for lines starting with "@", which are lines printed by the target (limited support)
*
* @param evt the event
* @param v nothing
*/
protected void processTargetOut(GdbTargetOutputEvent evt, Void v) {
listenersTargetOutput.fire.output(evt.getOutput());
}
/**
* Called for lines starting with "&", which are lines GDB would like printed to stderr
*
* @param evt the event
* @param v nothing
*/
protected void processStdErr(GdbDebugOutputEvent evt, Void v) {
String out = evt.getOutput();
//System.err.print(out);
if (!evt.isStolen()) {
listenersConsoleOutput.fire.output(Channel.STDERR, out);
}
}
/**
* Handler for "=thread-group-added" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadGroupAdded(GdbThreadGroupAddedEvent evt, Void v) {
int iid = evt.getInferiorId();
GdbInferiorImpl inferior = new GdbInferiorImpl(this, iid);
/**
* Update currentInferior, but delay event. inferiorAdded callbacks may ask for
* currentInferior, so it must be up-to-date. However, inferiorSelected callbacks should not
* refer to an inferior that has not appeared in an inferiorAdded event.
*/
boolean fireSelected = false;
if (inferiors.isEmpty()) {
fireSelected = updateCurrentInferior(inferior, evt.getCause(), false);
}
inferior.add(evt.getCause());
if (fireSelected) {
event(() -> listenersEvent.fire.inferiorSelected(inferior, evt.getCause()),
"groupAdded-sel");
}
}
/**
* Handler for "=thread-group-removed" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadGroupRemoved(GdbThreadGroupRemovedEvent evt, Void v) {
int iid = evt.getInferiorId();
GdbInferiorImpl inferior = getInferior(iid);
GdbInferiorImpl cur;
boolean fireSelected = false;
if (curInferior == inferior) {
// Select a new current before removing, so no event is generated yet
cur = inferiors.values().stream().filter(i -> i != inferior).findFirst().get();
// Can't remove all, so this should always come out true
fireSelected = updateCurrentInferior(cur, evt.getCause(), false);
}
else {
cur = null;
}
inferior.remove(evt.getCause());
if (fireSelected) {
event(() -> listenersEvent.fire.inferiorSelected(cur, evt.getCause()),
"groupRemoved-sel");
// Also cause GDB to generate thread selection events, if applicable
setActiveInferior(cur, false);
}
}
/**
* Handler for "=thread-group-started" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadGroupStarted(GdbThreadGroupStartedEvent evt, Void v) {
int iid = evt.getInferiorId();
GdbInferiorImpl inf = getInferior(iid);
inf.setPid(evt.getPid());
fireInferiorStarted(inf, evt.getCause(), "inferiorStarted");
}
public void fireInferiorStarted(GdbInferiorImpl inf, GdbCause cause, String text) {
event(() -> listenersEvent.fire.inferiorStarted(inf, cause), text);
}
/**
* Handler for "=thread-group-exited" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadGroupExited(GdbThreadGroupExitedEvent evt, Void v) {
int iid = evt.getInferiorId();
GdbInferiorImpl inf = getInferior(iid);
inf.setExitCode(evt.getExitCode());
event(() -> listenersEvent.fire.inferiorExited(inf, evt.getCause()), "inferiorExited");
}
/**
* Handler for "=thread-created" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadCreated(GdbThreadCreatedEvent evt, Void v) {
int tid = evt.getThreadId();
int iid = evt.getInferiorId();
GdbInferiorImpl inf = getInferior(iid);
GdbThreadImpl thread = new GdbThreadImpl(this, inf, tid);
thread.add();
event(() -> listenersEvent.fire.threadCreated(thread, evt.getCause()), "threadCreated");
}
/**
* Handler for "=thread-exited" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadExited(GdbThreadExitedEvent evt, Void v) {
int tid = evt.getThreadId();
int iid = evt.getInferiorId();
GdbInferiorImpl inf = getInferior(iid);
GdbThreadImpl thread = inf.getThread(tid);
thread.remove();
event(() -> listenersEvent.fire.threadExited(tid, inf, evt.getCause()), "threadExited");
}
/**
* Handler for "=thread-selected" events
*
* @param evt the event
* @param v nothing
*/
protected void processThreadSelected(GdbThreadSelectedEvent evt, Void v) {
int tid = evt.getThreadId();
GdbThreadImpl thread = getThread(tid);
GdbStackFrameImpl frame = evt.getFrame(thread);
doThreadSelected(thread, frame, evt.getCause());
}
/**
* Fire thread (and frame) selection event
*
* @param thread the new thread
* @param frame the new frame
* @param cause the cause of the selection change
*/
public void doThreadSelected(GdbThreadImpl thread, GdbStackFrame frame, GdbCause cause) {
updateCurrentInferior(thread.getInferior(), cause, true);
event(() -> listenersEvent.fire.threadSelected(thread, frame, cause), "threadSelected");
}
/**
* Handler for "=library-loaded" events
*
* @param evt the event
* @param v nothing
*/
protected void processLibraryLoaded(GdbLibraryLoadedEvent evt, Void v) {
Integer iid = evt.getInferiorId();
String name = evt.getTargetName();
if (iid == null) { // Context of all inferiors
for (GdbInferiorImpl inf : inferiors.values()) {
inf.libraryLoaded(name);
event(() -> listenersEvent.fire.libraryLoaded(inf, name, evt.getCause()),
"libraryLoaded");
}
}
else {
GdbInferiorImpl inf = getInferior(iid);
inf.libraryLoaded(name);
event(() -> listenersEvent.fire.libraryLoaded(inf, name, evt.getCause()),
"libraryLoaded");
}
}
/**
* Handler for "=library-unloaded" events
*
* @param evt the event
* @param v nothing
*/
protected void processLibraryUnloaded(GdbLibraryUnloadedEvent evt, Void v) {
Integer iid = evt.getInferiorId();
String name = evt.getTargetName();
if (iid == null) { // Context of all inferiors
for (GdbInferiorImpl inf : inferiors.values()) {
inf.libraryUnloaded(name);
event(() -> listenersEvent.fire.libraryUnloaded(inf, name, evt.getCause()),
"libraryUnloaded");
}
}
else {
GdbInferiorImpl inf = getInferior(iid);
inf.libraryUnloaded(name);
event(() -> listenersEvent.fire.libraryUnloaded(inf, name, evt.getCause()),
"libraryUnloaded");
}
}
/**
* Fire breakpoint created event
*
* @param newInfo the new information
* @param cause the cause of the creation
*/
@Internal
public void doBreakpointCreated(GdbBreakpointInfo newInfo, GdbCause cause) {
addKnownBreakpoint(newInfo, false);
event(() -> listenersEvent.fire.breakpointCreated(newInfo, cause), "breakpointCreated");
}
/**
* Handler for "=breakpoint-created" events
*
* @param evt the event
* @param v nothing
*/
protected void processBreakpointCreated(GdbBreakpointCreatedEvent evt, Void v) {
doBreakpointCreated(evt.getBreakpointInfo(), evt.getCause());
}
/**
* Fire breakpoint modified event
*
* @param newInfo the new information
* @param cause the cause of the modification
*/
@Internal
public void doBreakpointModified(GdbBreakpointInfo newInfo, GdbCause cause) {
GdbBreakpointInfo oldInfo = addKnownBreakpoint(newInfo, true);
event(() -> listenersEvent.fire.breakpointModified(newInfo, oldInfo, cause),
"breakpointModified");
}
/**
* Handler for "=breakpoint-modified" events
*
* @param evt the event
* @param v nothing
*/
protected void processBreakpointModified(GdbBreakpointModifiedEvent evt, Void v) {
doBreakpointModified(evt.getBreakpointInfo(), evt.getCause());
}
/**
* Fire breakpoint deleted event
*
* @param number the deleted breakpoint number
* @param cause the cause of the deletion
*/
@Internal
public void doBreakpointDeleted(long number, GdbCause cause) {
GdbBreakpointInfo oldInfo = removeKnownBreakpoint(number);
if (oldInfo == null) {
return;
}
event(() -> listenersEvent.fire.breakpointDeleted(oldInfo, cause), "breakpointDeleted");
}
protected void doBreakpointModifiedSameLocations(GdbBreakpointInfo newInfo,
GdbBreakpointInfo oldInfo, GdbCause cause) {
if (Objects.equals(newInfo, oldInfo)) {
return;
}
addKnownBreakpoint(newInfo, true);
event(() -> listenersEvent.fire.breakpointModified(newInfo, oldInfo, cause),
"breakpointModified");
}
@Internal
public void doBreakpointDisabled(long number, GdbCause cause) {
GdbBreakpointInfo oldInfo = getKnownBreakpoint(number);
if (oldInfo == null) {
return;
}
GdbBreakpointInfo newInfo = oldInfo.withEnabled(false);
//oldInfo = oldInfo.withEnabled(true);
doBreakpointModifiedSameLocations(newInfo, oldInfo, cause);
}
@Internal
public void doBreakpointEnabled(long number, GdbCause cause) {
GdbBreakpointInfo oldInfo = getKnownBreakpoint(number);
if (oldInfo == null) {
return;
}
GdbBreakpointInfo newInfo = oldInfo.withEnabled(true);
//oldInfo = oldInfo.withEnabled(false);
doBreakpointModifiedSameLocations(newInfo, oldInfo, cause);
}
/**
* Handler for "=breakpoint-deleted" events
*
* @param evt the event
* @param v nothing
*/
protected void processBreakpointDeleted(GdbBreakpointDeletedEvent evt, Void v) {
doBreakpointDeleted(evt.getNumber(), evt.getCause());
}
/**
* Handler for "=memory-changed" events
*
* @param evt the event
* @param v nothing
*/
protected void processMemoryChanged(GdbMemoryChangedEvent evt, Void v) {
int iid = evt.getInferiorId();
GdbInferior inf = getInferior(iid);
event(() -> listenersEvent.fire.memoryChanged(inf, evt.getAddress(), evt.getLength(),
evt.getCause()), "memoryChanged");
}
/**
* Handler for "=cmd-param-changed" events
*
* @param evt the event
* @param v nothing
*/
protected void processParamChanged(GdbParamChangedEvent evt, Void v) {
event(() -> listenersEvent.fire.paramChanged(evt.getParam(), evt.getValue(),
evt.getCause()), "paramChanged");
}
/**
* Check that a command completion event was claimed
*
* <p>
* Except under certain error conditions, GDB should never issue a command completed event that
* is not associated with a command. A command implementation in the manager must claim the
* completion event. This is an assertion to ensure no implementation forgets to do that.
*
* @param evt the event
*/
protected void checkClaimed(GdbEvent<?> evt) {
if (evt.getCause() == Causes.UNCLAIMED) {
if (evt instanceof AbstractGdbCompletedCommandEvent) {
AbstractGdbCompletedCommandEvent completed = (AbstractGdbCompletedCommandEvent) evt;
String msg = completed.assumeMsg();
if (msg != null) {
if (evt instanceof GdbCommandErrorEvent) {
Msg.error(this, msg);
}
else {
Msg.info(this, msg);
throw new AssertionError("Command completion left unclaimed!");
}
}
}
}
}
/**
* Handler for "^done"
*
* @param evt the event
* @param v nothing
*/
protected void processCommandDone(GdbCommandDoneEvent evt, Void v) {
checkClaimed(evt);
}
/**
* Handler for "^running"
*
* @param evt the event
* @param v nothing
*/
protected void processCommandRunning(GdbCommandRunningEvent evt, Void v) {
checkClaimed(evt);
Msg.debug(this, "Target is running");
}
/**
* Handler for "^connected"
*
* @param evt the event
* @param v nothing
*/
protected void processCommandConnected(GdbCommandConnectedEvent evt, Void v) {
checkClaimed(evt);
Msg.debug(this, "Connected to target");
}
/**
* Handler for "^exit"
*
* @param evt the event
* @param v nothing
*/
protected void processCommandExit(GdbCommandExitEvent evt, Void v) {
checkClaimed(evt);
Msg.debug(this, "GDB is exiting....");
}
/**
* Handler for "^error"
*
* @param evt the event
* @param v nothing
*/
protected void processCommandError(GdbCommandErrorEvent evt, Void v) {
checkClaimed(evt);
}
/**
* Handler for "*running"
*
* @param evt the event
* @param v nothing
*/
protected void processRunning(GdbRunningEvent evt, Void v) {
String threadId = evt.assumeThreadId();
if (threadId == null) {
threadId = "all";
}
if ("all".equals(threadId)) {
GdbInferiorImpl cur = curInferior;
event(() -> {
listenersEvent.fire.inferiorStateChanged(cur, cur.getKnownThreads().values(),
evt.newState(), null, evt.getCause(), evt.getReason());
}, "inferiorState-running");
for (GdbThreadImpl thread : curInferior.getKnownThreadsImpl().values()) {
thread.setState(evt.newState(), evt.getCause(), evt.getReason());
}
}
else {
int id = Integer.parseUnsignedInt(threadId);
GdbThreadImpl thread = threads.get(id);
event(() -> {
listenersEvent.fire.inferiorStateChanged(thread.getInferior(),
List.of(thread), evt.newState(), null, evt.getCause(), evt.getReason());
}, "inferiorState-running");
thread.setState(evt.newState(), evt.getCause(), evt.getReason());
}
}
/**
* Handler for "*stopped"
*
* @param evt the event
* @param v nothing
*/
protected void processStopped(GdbStoppedEvent evt, Void v) {
String stoppedThreadsStr = evt.assumeStoppedThreads();
Collection<GdbThreadImpl> stoppedThreads;
if (null == stoppedThreadsStr || "all".equals(stoppedThreadsStr)) {
stoppedThreads = threads.values();
}
else {
stoppedThreads = new LinkedHashSet<>();
for (String stopped : stoppedThreadsStr.split(",")) {
stoppedThreads.add(threads.get(Integer.parseInt(stopped)));
}
}
Integer tid = evt.getThreadId();
GdbThreadImpl evtThread = tid == null ? null : threads.get(tid);
Map<GdbInferior, Set<GdbThread>> byInf = new LinkedHashMap<>();
for (GdbThreadImpl thread : stoppedThreads) {
thread.setState(evt.newState(), evt.getCause(), evt.getReason());
byInf.computeIfAbsent(thread.getInferior(), i -> new LinkedHashSet<>()).add(thread);
}
for (Map.Entry<GdbInferior, Set<GdbThread>> ent : byInf.entrySet()) {
event(() -> {
listenersEvent.fire.inferiorStateChanged(ent.getKey(), ent.getValue(),
evt.newState(), evtThread, evt.getCause(), evt.getReason());
}, "inferiorState-stopped");
}
if (evtThread != null) {
GdbStackFrameImpl frame = evt.getFrame(evtThread);
event(() -> listenersEvent.fire.threadSelected(evtThread, frame, evt),
"inferiorState-stopped");
}
}
/**
* An interface for taking lines of input
*/
public interface LineReader {
String readLine(String prompt) throws IOException;
}
/**
* An implementation of {@link LineReader} that does not use GPL code
*/
public static class BufferedReaderLineReader implements LineReader {
private BufferedReader reader;
BufferedReaderLineReader() {
this.reader = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public String readLine(String prompt) throws IOException {
System.out.print(prompt);
return reader.readLine();
}
}
@Override
public void consoleLoop() throws IOException {
checkStarted();
Signal sigInterrupt = new Signal("INT");
SignalHandler oldHandler = Signal.handle(sigInterrupt, (sig) -> {
try {
sendInterruptNow();
}
catch (IOException e) {
e.printStackTrace();
}
});
try {
/*
* prompt.addChangeListener((p, v) -> { if (p) { System.out.print(PROMPT_GDB + " "); }
* });
*/
LineReader reader = new BufferedReaderLineReader();
//LineReader reader = new GnuReadlineLineReader();
// System.out.print(PROMPT_GDB + " ");
while (isAlive()) {
String cmd = reader.readLine(PROMPT_GDB + " ");
if (cmd == null) {
System.out.println("quit");
return;
}
console(cmd).exceptionally((e) -> {
Throwable realExc = AsyncUtils.unwrapThrowable(e);
if (realExc instanceof GdbCommandError) {
return null; // Gdb will have already printed it
}
e.printStackTrace();
//System.out.print(PROMPT_GDB + " ");
return null;
});
}
}
finally {
Signal.handle(sigInterrupt, oldHandler);
}
}
public void sendInterruptNow(PtyThread thread, byte[] bytes) throws IOException {
Msg.info(this, "Interrupting by Ctrl-C on " + thread + "'s pty");
OutputStream os = thread.pty.getParent().getOutputStream();
os.write(bytes);
os.flush();
}
@Override
public void sendInterruptNow() throws IOException {
checkStarted();
/*Msg.info(this, "Interrupting while runningInterpreter = " + runningInterpreter);
if (runningInterpreter == Interpreter.MI2) {
if (cliThread != null) {
Msg.info(this, "Interrupting by 'interrupt' on CLI");
OutputStream os = cliThread.pty.getParent().getOutputStream();
os.write(("interrupt" + newLine).getBytes());
os.flush();
}
else {
sendInterruptNow(mi2Thread);
}
}
else*/
if (cliThread != null) {
sendInterruptNow(cliThread, (((char) 3) + "interrupt" + newLine).getBytes());
}
else if (mi2Thread != null) {
sendInterruptNow(mi2Thread, (((char) 3) + "-exec-interrupt" + newLine).getBytes());
}
}
@Internal
public void injectInput(Interpreter interpreter, String input) {
PrintWriter writer = getWriter(interpreter);
writer.print(input);
writer.flush();
}
@Internal
public void synthesizeConsoleOut(Channel channel, String line) {
listenersConsoleOutput.fire.output(channel, line);
}
@Override
public synchronized GdbState getState() {
return state.get();
}
@Override
public synchronized CompletableFuture<Void> waitForState(GdbState forState) {
checkStarted();
return state.waitValue(forState);
}
@Override
public CompletableFuture<Void> waitForPrompt() {
return mi2Prompt.waitValue(true);
}
@Override
@Deprecated
public CompletableFuture<Void> claimStopped() {
return execute(new GdbClaimStopped(this));
}
@Override
public CompletableFuture<GdbInferior> addInferior() {
return execute(new GdbAddInferiorCommand(this));
}
@Override
public CompletableFuture<GdbInferior> availableInferior() {
return listInferiors().thenCompose(map -> {
for (GdbInferior inf : map.values()) {
if (inf.getPid() == null) {
return CompletableFuture.completedFuture(inf);
}
}
return addInferior();
});
}
@Override
public CompletableFuture<Void> removeInferior(GdbInferior inferior) {
return execute(new GdbRemoveInferiorCommand(this, inferior.getId()));
}
/**
* Select the given inferior
*
* <p>
* This issues a command to GDB to change its focus. It is not just a manager concept.
*
* @param inferior the inferior to select
* @param internal true to prevent announcement of the change
* @return a future that completes when GDB has executed the command
*/
CompletableFuture<Void> setActiveInferior(GdbInferior inferior, boolean internal) {
return execute(new GdbInferiorSelectCommand(this, inferior.getId(), internal));
}
@Override
public CompletableFuture<Void> console(String command, CompletesWithRunning cwr) {
return execute(new GdbConsoleExecCommand(this, null, null, command,
GdbConsoleExecCommand.Output.CONSOLE, cwr)).thenApply(e -> null);
}
@Override
public CompletableFuture<String> consoleCapture(String command, CompletesWithRunning cwr) {
return execute(new GdbConsoleExecCommand(this, null, null, command,
GdbConsoleExecCommand.Output.CAPTURE, cwr));
}
@Override
public CompletableFuture<Map<Integer, GdbInferior>> listInferiors() {
return execute(new GdbListInferiorsCommand(this));
}
@Override
public CompletableFuture<List<GdbProcessThreadGroup>> listAvailableProcesses() {
return execute(new GdbListAvailableProcessesCommand(this));
}
@Override
public CompletableFuture<GdbTable> infoOs(String type) {
return execute(new GdbInfoOsCommand(this, type));
}
@Override
public String getMi2PtyName() throws IOException {
return mi2Thread.pty.getChild().nullSession();
}
@Override
public String getPtyDescription() {
return ptyFactory.getDescription();
}
public boolean hasCli() {
return cliThread != null && cliThread.pty != null;
}
public Interpreter getRunningInterpreter() {
return runningInterpreter;
}
private CompletableFuture<Map.Entry<String, String[]>> nextMaintInfoSections(
GdbInferiorImpl inferior, String cmds[], List<String[]> results) {
if (results.size() == cmds.length) {
int best = 0;
for (int i = 0; i < cmds.length; i++) {
if (results.get(i).length > results.get(best).length) {
best = i;
}
}
return CompletableFuture.completedFuture(Map.entry(cmds[best], results.get(best)));
}
String cmd = cmds[results.size()];
return inferior.consoleCapture(cmd, CompletesWithRunning.CANNOT).thenCompose(out -> {
String[] lines = out.split("\n");
if (lines.length >= 10) {
return CompletableFuture.completedFuture(Map.entry(cmd, lines));
}
results.add(lines);
return nextMaintInfoSections(inferior, cmds, results);
});
}
/**
* Execute "maintenance info sections" for all objects, starting with the syntax that last
* worked best
*
* <p>
* If any syntax yields at least 10 lines of output, then it is taken immediately, and the "last
* best" syntax is updated. In most cases, the first execution is the only time this will need
* to try more than once, since the underlying version should not change during the manager's
* lifetime. If none give more than 10, then the one which yielded the most lines is selected.
* This could happen in vacuous cases, e.g., if modules are requested without a target file.
*
* @param inferior the inferior for context when executing the command
* @return a future which completes with the list of lines
*/
protected CompletableFuture<String[]> execMaintInfoSectionsAllObjects(
GdbInferiorImpl inferior) {
// TODO: Would be nice to choose based on version
CompletableFuture<String> futureOut =
inferior.consoleCapture(maintInfoSectionsCmd, CompletesWithRunning.CANNOT);
return futureOut.thenCompose(out -> {
String[] lines = out.split("\n");
if (lines.length >= 10) {
return CompletableFuture.completedFuture(lines);
}
CompletableFuture<Entry<String, String[]>> futureBest = nextMaintInfoSections(inferior,
GdbModuleImpl.MAINT_INFO_SECTIONS_CMDS, new ArrayList<>());
return futureBest.thenApply(best -> {
maintInfoSectionsCmd = best.getKey();
return best.getValue();
});
});
}
/**
* Match a module file line, starting with the last working pattern
*
* <p>
* In most cases, only the first attempt to parse causes an update to the "last working"
* pattern, since the underlying GDB version should not change during the lifetime of the
* manager.
*
* @param line the line to parse
* @return the matcher or null
*/
protected Matcher matchFileLine(String line) {
Matcher matcher;
matcher = fileLinePattern.matcher(line);
if (matcher.matches()) {
return matcher;
}
for (Pattern pattern : GdbModuleImpl.OBJECT_FILE_LINE_PATTERNS) {
matcher = pattern.matcher(line);
if (matcher.matches()) {
fileLinePattern = pattern;
return matcher;
}
}
return null;
}
/**
* Match a module section line, starting with the last working pattern
*
* <p>
* In most cases, only the first attempt to parse causes an update to the "last working"
* pattern, since the underlying GDB version should not change during the lifetime of the
* manager.
*
* @param line the line to parse
* @return the matcher or null
*/
protected Matcher matchSectionLine(String line) {
Matcher matcher;
matcher = sectionLinePattern.matcher(line);
if (matcher.matches()) {
return matcher;
}
for (Pattern pattern : GdbModuleImpl.OBJECT_SECTION_LINE_PATTERNS) {
matcher = pattern.matcher(line);
if (matcher.matches()) {
sectionLinePattern = pattern;
return matcher;
}
}
return null;
}
}
| {
"content_hash": "2aaea1a61aa1f6e01d5694673987024f",
"timestamp": "",
"source": "github",
"line_count": 1892,
"max_line_length": 100,
"avg_line_length": 30.81183932346723,
"alnum_prop": 0.7065664882667765,
"repo_name": "NationalSecurityAgency/ghidra",
"id": "e98dcb79e9d87bda18c008e8a3ae5ef56d8618d6",
"size": "58296",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ghidra/Debug/Debugger-agent-gdb/src/main/java/agent/gdb/manager/impl/GdbManagerImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "77536"
},
{
"name": "Batchfile",
"bytes": "21610"
},
{
"name": "C",
"bytes": "1132868"
},
{
"name": "C++",
"bytes": "7334484"
},
{
"name": "CSS",
"bytes": "75788"
},
{
"name": "GAP",
"bytes": "102771"
},
{
"name": "GDB",
"bytes": "3094"
},
{
"name": "HTML",
"bytes": "4121163"
},
{
"name": "Hack",
"bytes": "31483"
},
{
"name": "Haskell",
"bytes": "453"
},
{
"name": "Java",
"bytes": "88669329"
},
{
"name": "JavaScript",
"bytes": "1109"
},
{
"name": "Lex",
"bytes": "22193"
},
{
"name": "Makefile",
"bytes": "15883"
},
{
"name": "Objective-C",
"bytes": "23937"
},
{
"name": "Pawn",
"bytes": "82"
},
{
"name": "Python",
"bytes": "587415"
},
{
"name": "Shell",
"bytes": "234945"
},
{
"name": "TeX",
"bytes": "54049"
},
{
"name": "XSLT",
"bytes": "15056"
},
{
"name": "Xtend",
"bytes": "115955"
},
{
"name": "Yacc",
"bytes": "127754"
}
],
"symlink_target": ""
} |
<?php
/**
* Off Amazon Payments Service Exception provides details of errors
* returned by Off Amazon Payments Service service
*
*/
class OffAmazonPaymentsService_Exception extends Exception
{
/** @var string */
private $_message = null;
/** @var int */
private $_statusCode = -1;
/** @var string */
private $_errorCode = null;
/** @var string */
private $_errorType = null;
/** @var string */
private $_requestId = null;
/** @var string */
private $_xml = null;
private $_responseHeaderMetadata = null;
/**
* Constructs OffAmazonPaymentsService_Exception
* @param array $errorInfo details of exception.
* Keys are:
* <ul>
* <li>Message - (string) text message for an exception</li>
* <li>StatusCode - (int) HTTP status code at the time of exception</li>
* <li>ErrorCode - (string) specific error code returned by the service</li>
* <li>ErrorType - (string) Possible types: Sender, Receiver or Unknown</li>
* <li>RequestId - (string) request id returned by the service</li>
* <li>XML - (string) compete xml response at the time of exception</li>
* <li>Exception - (Exception) inner exception if any</li>
* </ul>
*
*/
public function __construct(array $errorInfo = array())
{
$this->_message = array_key_exists("Message", $errorInfo) ? $errorInfo["Message"] : null;
parent::__construct($this->_message);
if (array_key_exists("Exception", $errorInfo)) {
$exception = array_key_exists("Exception", $errorInfo) ? $errorInfo["Exception"] : null;
if ($exception instanceof OffAmazonPaymentsService_Exception) {
$this->_statusCode = $exception->getStatusCode();
$this->_errorCode = $exception->getErrorCode();
$this->_errorType = $exception->getErrorType();
$this->_requestId = $exception->getRequestId();
$this->_xml= $exception->getXML();
$this->_responseHeaderMetadata = $exception->getResponseHeaderMetadata();
}
} else {
$this->_statusCode = array_key_exists("StatusCode", $errorInfo) ? $errorInfo["StatusCode"] : null;
$this->_errorCode = array_key_exists("ErrorCode", $errorInfo) ? $errorInfo["ErrorCode"] : null;
$this->_errorType = array_key_exists("ErrorType", $errorInfo) ? $errorInfo["ErrorType"] : null;
$this->_requestId = array_key_exists("RequestId", $errorInfo) ? $errorInfo["RequestId"] : null;
$this->_xml= array_key_exists("XML", $errorInfo) ? $errorInfo["XML"] : null;
$this->_responseHeaderMetadata = array_key_exists("ResponseHeaderMetadata", $errorInfo) ? $errorInfo["ResponseHeaderMetadata"] : null;
}
}
/**
* Gets error type returned by the service if available.
*
* @return string Error Code returned by the service
*/
public function getErrorCode(){
return $this->_errorCode;
}
/**
* Gets error type returned by the service.
*
* @return string Error Type returned by the service.
* Possible types: Sender, Receiver or Unknown
*/
public function getErrorType(){
return $this->_errorType;
}
/**
* Gets error message
*
* @return string Error message
*/
public function getErrorMessage() {
return $this->_message;
}
/**
* Gets status code returned by the service if available. If status
* code is set to -1, it means that status code was unavailable at the
* time exception was thrown
*
* @return int status code returned by the service
*/
public function getStatusCode() {
return $this->_statusCode;
}
/**
* Gets XML returned by the service if available.
*
* @return string XML returned by the service
*/
public function getXML() {
return $this->_xml;
}
/**
* Gets Request ID returned by the service if available.
*
* @return string Request ID returned by the service
*/
public function getRequestId() {
return $this->_requestId;
}
public function getResponseHeaderMetadata() {
return $this->_responseHeaderMetadata;
}
} | {
"content_hash": "eee23053020a397cf082a28f41001284",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 146,
"avg_line_length": 33.213740458015266,
"alnum_prop": 0.5984831073316479,
"repo_name": "yaelduckwen/libriastore",
"id": "c4dfe04a653f34513458f2fc3f3209929f152818",
"size": "5051",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "joomla/plugins/vmpayment/amazon/library/OffAmazonPaymentsService/Exception.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "44"
},
{
"name": "CSS",
"bytes": "2779463"
},
{
"name": "HTML",
"bytes": "26380"
},
{
"name": "JavaScript",
"bytes": "2813038"
},
{
"name": "PHP",
"bytes": "24821947"
},
{
"name": "PLpgSQL",
"bytes": "2393"
},
{
"name": "SQLPL",
"bytes": "17688"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Service_Yahoo_ResultSet
*/
// require_once 'Zend/Service/Yahoo/ResultSet.php';
/**
* @see Zend_Service_Yahoo_WebResult
*/
// require_once 'Zend/Service/Yahoo/WebResult.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage Yahoo
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_Yahoo_WebResultSet extends Zend_Service_Yahoo_ResultSet
{
/**
* Web result set namespace
*
* @var string
*/
protected $_namespace = 'urn:yahoo:srch';
/**
* Overrides Zend_Service_Yahoo_ResultSet::current()
*
* @return Zend_Service_Yahoo_WebResult
*/
public function current()
{
return new Zend_Service_Yahoo_WebResult($this->_results->item($this->_currentIndex));
}
}
| {
"content_hash": "93798921d1009f1b054cb0891e874886",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 93,
"avg_line_length": 20.704545454545453,
"alnum_prop": 0.6377607025246982,
"repo_name": "vastpromedia/zf1",
"id": "d7a6a6668d65437e87e06688758e6fce59c74c90",
"size": "1679",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "library/Zend/Service/Yahoo/WebResultSet.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "15906365"
},
{
"name": "PowerShell",
"bytes": "1028"
},
{
"name": "Shell",
"bytes": "1409"
}
],
"symlink_target": ""
} |
namespace first_party_sets {
// Add Profile prefs below.
extern const char kFirstPartySetsOverrides[];
} // namespace first_party_sets
#endif // CHROME_BROWSER_FIRST_PARTY_SETS_FIRST_PARTY_SETS_PREF_NAMES_H_
| {
"content_hash": "392626aa2119169b142bc07234b2051d",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 73,
"avg_line_length": 26.625,
"alnum_prop": 0.755868544600939,
"repo_name": "chromium/chromium",
"id": "cfaea87b845840e310e19754bae690eee5a9fc07",
"size": "500",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "chrome/browser/first_party_sets/first_party_sets_pref_names.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "3897ba368801a7020c9d276cee7e4dd4",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "b08b77ac4a569aed01d5b63069428b6944bbcaf0",
"size": "187",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Orchidaceae/Stanhopea/Stanhopea quadricornis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
title: "AzureAD Authentication with AWS API Gateway v2 JWT Authorizers"
tags: [aws, azuread]
---
AWS' API Gateway v2 (aka HTTP APIs) launched in December 2019, and came with a built-in ability to add JWT authorizers to endpoints. We use AzureAD as our Auth vendor, so I've been waiting for a chance to try this out. Finally got an opportunity.
I'm assuming you have a functional AzureAD application - I have an existing React app - so I'm just going to cover the pieces I needed to add/modify to get the AzureAD integration working.
### AzureAD Configuration
This ended up being one of the most difficult parts.
#### Create an App Registration for your API
1. Create a new application in the Application Registrations section of AzureAD
2. Add any permissions your API might need in the API Permissions tab
3. Go to the Expose an API tab, and click Add a Scope
* Give your scope a name, admin consent name and description, and click Add Scope.
4. Once your app registration has been configured - take note of the Application/Client ID and Scope name you created above - you'll need these for the API Gateway configuration
#### Modify your Application Registration to Grant Access to the API
1. Location your application in the Application Registrations section of AzureAD
2. Under API Permissions, click Add a Permission
3. Under either My APIs or APIs My Organization Uses, find the App Registration created for the API in the above section, check the box to add the scope, and click Add Permissions. If you marked Admin Consent as required, click the Grant admin consent button or get a Global Admin to perform the consent process to grant the necessary permissions.
At this point, your application should be able to request a token to call the AzureAD API.
### AWS Configuration
#### Build your Lambda Function
I had an existing Lambda function that I used for this, but if necessary, build a Lambda function and ensure it works and returns something to the caller so you're able to test things out.
#### Build the API Gateway v2 Configuration
1. In API Gateway, click APIs on the left nav, and then Create API
2. Click the Build button under HTTP API
3. On the Create an API screen, click Add Integration, choose Lambda, and pick the correct Region, as well as your Lambda function. Enter a name for your API, then click Next to continue
4. I set my resource path to / for simplicity, but by default it appears to choose the Lambda function's name. Whatever you choose is fine, you'll just need to remember this to test things out with your client. Click Next to continue.
5. Leave the Configure Stages section alone (configured for Auto-deploy), and click Next to continue.
6. Click Create to create the API Gateway configuration
#### Build your JWT Authorizer
1. Once your API Gateway configuration has been created, click Authorization in the left nav
2. Click the VERB for your newly created route - by default it should be ANY - and then click the button for Create an attach an authorizer
3. Give your Authorizer a name, and configure your Authorizer for AzureAD, then click Create and Attach
* Identity Source: $request.header.Authorization
* Issuer: Even though the AWS documentation says this should be coming from the well-known metadata endpoint, which can be found at https://login.microsoftonline.com/<YOUR AZUREAD TENANT GUID>/v2.0/.well-known/openid-configuration, I found that the value here did not match what was in my issued tokens. I had to set the issuer to https://sts.windows.net/<YOUR AZUREAD TENANT GUID>/
* Audience: api://<API APP Registration Application ID>, for example api://00000000-0000-0000-0000-000000000000
#### Testing with Postman
At this point, you should be able to test your API with Postman. You'll have to obtain an access token good for your API.
I use <https://www.npmjs.com/package/react-aad-msal> in my React applications, but I ran into an issue where even when I specified the scope for my API Application in my authProvider.js file, the token I was getting was still only good for the MS Graph API. Decoding the Access Token with JWT.io showed an invalid signature - apparently access tokens for MS Graph API include a nonce value that makes the token not validate correctly against the public key (<https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/521>) - learn something new everyday. Big shout out to Eric Johnson@AWS for helping me track this down.
I ended up adding some code to my React project to dump an access token to the console, and used react-aad-msal's ability to call into the underlying msal library to make this happen:
```
var tokenRequest = {
scopes: ["api://<MY API's APP REGISRATION/CLIENTID>/<MY API's SCOPE>"]
};
//call in and get a token for our api
let token = await props.provider.acquireTokenSilent(tokenRequest)
console.log(token.accessToken);
```
Once you have an access token valid for your API (you can pretty easily decode and check this with jwt.io), you should be able to use Postman to access the API - just set the Authorization to Bearer token and paste your access token into the token section.
#### Adding CORS Support
To be able to use this in a browser-based app which was my goal, there's some additional configuration required.
1. In API Gateway, click CORS in the left-hand nav, configure the following settings, then click Save to save your settings.
* Access-Control-Allow-Origin: Enter any origins which will need access to the API
* Access-Control-Allow-Headers: Add the authorization header
* Access-Control-Allow-Methods: Add GET as an allowed method
This should allow you to access the API from the browser using CORS with something like:
```
let response = await fetch("https://YOURAPI.execute-api.us-west-2.amazonaws.com", {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token.accessToken
},
});
var data = await response.json();
```
HUZZAH!
This vastly simplified API Gateway v2 is really a gamechanger for us - the previous API Gateway worked well, but it was WAYYYY too complicated. And the ability to do JWT auth easily like this - beautiful. Well done AWS.
| {
"content_hash": "af2662c9c34f69c59b46ed4ef4518a6e",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 636,
"avg_line_length": 65.02105263157895,
"alnum_prop": 0.7720576331552533,
"repo_name": "rayterrill/rayterrill.github.io",
"id": "746224fa330b23a658841692960e912b2cb2a943",
"size": "6181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_posts/2020-4-8-AzureADAPIGatewayv2JWTAuthorizer.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "182"
},
{
"name": "HTML",
"bytes": "2832"
}
],
"symlink_target": ""
} |
package net.ernstsson.sqlbuilder;
import static net.ernstsson.sqlbuilder.ArrayStatement.array;
import static net.ernstsson.sqlbuilder.StringStatement.string;
import static org.apache.commons.lang3.builder.EqualsBuilder.reflectionEquals;
import static org.apache.commons.lang3.builder.HashCodeBuilder.reflectionHashCode;
import static org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString;
public final class Ascending implements OrderableStatement {
static final String ASC = "ASC";
private static final Statement ASC_STATEMENT = string(ASC);
private final Statement statement;
private final Column column;
private Ascending(final Column column) {
this.statement = array(column, ASC_STATEMENT);
this.column = column;
}
public static OrderableStatement ascending(final Column column) {
return new Ascending(column);
}
@Override
public String toSql() {
return statement.toSql();
}
@Override
public Object getOrderObject() {
return column;
}
@Override
public String toString() {
return reflectionToString(this);
}
@Override
public boolean equals(final Object object) {
return reflectionEquals(this, object);
}
@Override
public int hashCode() {
return reflectionHashCode(this);
}
}
| {
"content_hash": "6955ffad7f8962d3eca3834a72428ef4",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 82,
"avg_line_length": 28.270833333333332,
"alnum_prop": 0.7155490051584378,
"repo_name": "ernstsson/sqlbuilder",
"id": "5233095051d0783cd541ed31f4d86ba742c9ef0a",
"size": "1357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/ernstsson/sqlbuilder/Ascending.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "477"
},
{
"name": "Java",
"bytes": "116661"
}
],
"symlink_target": ""
} |
TEST(LaunchDriver, defaultConstructor)
{
LaunchDriver s;
std::string actual = (std::string)s.getTag();
std::string expected = "undefined";
ASSERT_EQ(expected, actual);
}
// Run all the tests that were declared with TEST()
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | {
"content_hash": "c07bfb4373ad0e46b0e8cdfe4ecae6dd",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 51,
"avg_line_length": 23.285714285714285,
"alnum_prop": 0.7116564417177914,
"repo_name": "thijser/robotica-minor-5",
"id": "7dca308cd81b958eee278c5aaa24f804b5844d1c",
"size": "582",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "turtleCode/src/glados/src/drivers/test/utest.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "19131"
},
{
"name": "C",
"bytes": "1087410"
},
{
"name": "C++",
"bytes": "3671938"
},
{
"name": "D",
"bytes": "28193"
},
{
"name": "Makefile",
"bytes": "10682"
},
{
"name": "Python",
"bytes": "203232"
},
{
"name": "Shell",
"bytes": "354040"
},
{
"name": "TeX",
"bytes": "103504"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>plouffe: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.8.1 / plouffe - 1.2.1</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
plouffe
<small>
1.2.1
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-07-03 12:42:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-03 12:42:49 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.8.1 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.03.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.03.0 Official 4.03.0 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/thery/Plouffe"
bug-reports: "https://github.com/thery/Plouffe/issues"
license: "MIT"
build: [
["./configure.sh"]
[make "-j%{jobs}%"]
]
install: [make "install"]
depends: [
"ocaml"
"coq" {>= "8.5"}
"coq-mathcomp-ssreflect"
"coq-coquelicot" {>= "2.1.0" & < "3.~"}
]
tags: [
"logpath:Plouffe"
]
synopsis: "A Coq formalization of Plouffe formula"
authors: "Laurent Thery"
url {
src:
"https://github.com/thery/Plouffe/archive/Submitted_article_version_nob.zip"
checksum: "md5=ff44f9f14fa6ebbe28b7d8c92f8a57a9"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-plouffe.1.2.1 coq.8.8.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1).
The following dependencies couldn't be met:
- coq-plouffe -> coq-coquelicot < 3.~ -> coq-ssreflect -> coq < 8.5~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
- coq-plouffe -> coq-coquelicot < 3.~ -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-plouffe.1.2.1</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "6ee5b044b73000b47403e0fb41269980",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 159,
"avg_line_length": 40.07017543859649,
"alnum_prop": 0.5303561004086398,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "0b13ab303aa51ceca7ea1327380e4978451597f4",
"size": "6877",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.1/plouffe/1.2.1.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.IO;
namespace uWebshop.Newtonsoft.Json.Utilities
{
internal class Base64Encoder
{
private const int Base64LineSize = 76;
private const int LineSizeInBytes = 57;
private readonly char[] _charsLine = new char[Base64LineSize];
private readonly TextWriter _writer;
private byte[] _leftOverBytes;
private int _leftOverBytesCount;
public Base64Encoder(TextWriter writer)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
}
public void Encode(byte[] buffer, int index, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException("index");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (count > (buffer.Length - index))
throw new ArgumentOutOfRangeException("count");
if (_leftOverBytesCount > 0)
{
int leftOverBytesCount = _leftOverBytesCount;
while (leftOverBytesCount < 3 && count > 0)
{
_leftOverBytes[leftOverBytesCount++] = buffer[index++];
count--;
}
if (count == 0 && leftOverBytesCount < 3)
{
_leftOverBytesCount = leftOverBytesCount;
return;
}
int num2 = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0);
WriteChars(_charsLine, 0, num2);
}
_leftOverBytesCount = count%3;
if (_leftOverBytesCount > 0)
{
count -= _leftOverBytesCount;
if (_leftOverBytes == null)
{
_leftOverBytes = new byte[3];
}
for (int i = 0; i < _leftOverBytesCount; i++)
{
_leftOverBytes[i] = buffer[(index + count) + i];
}
}
int num4 = index + count;
int length = LineSizeInBytes;
while (index < num4)
{
if ((index + length) > num4)
{
length = num4 - index;
}
int num6 = Convert.ToBase64CharArray(buffer, index, length, _charsLine, 0);
WriteChars(_charsLine, 0, num6);
index += length;
}
}
public void Flush()
{
if (_leftOverBytesCount > 0)
{
int count = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0);
WriteChars(_charsLine, 0, count);
_leftOverBytesCount = 0;
}
}
private void WriteChars(char[] chars, int index, int count)
{
_writer.Write(chars, index, count);
}
}
} | {
"content_hash": "b59399a646a9d32a50b284924aea1885",
"timestamp": "",
"source": "github",
"line_count": 122,
"max_line_length": 97,
"avg_line_length": 28.262295081967213,
"alnum_prop": 0.6841647331786543,
"repo_name": "uWebshop/uWebshop-Releases",
"id": "8c6bfb1823ed736f623866bcb049255403cfef8b",
"size": "3450",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Core/uWebshop.Domain/NewtonsoftJsonNet/Utilities/Base64Encoder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "6945"
},
{
"name": "C#",
"bytes": "3966875"
},
{
"name": "CSS",
"bytes": "3285"
},
{
"name": "HTML",
"bytes": "18439"
},
{
"name": "JavaScript",
"bytes": "50632"
},
{
"name": "XSLT",
"bytes": "16095"
}
],
"symlink_target": ""
} |
package wkbcommon
import (
"io"
"github.com/paulmach/orb"
)
func readCollection(r io.Reader, order byteOrder, buf []byte) (orb.Collection, error) {
num, err := readUint32(r, order, buf[:4])
if err != nil {
return nil, err
}
alloc := num
if alloc > MaxMultiAlloc {
// invalid data can come in here and allocate tons of memory.
alloc = MaxMultiAlloc
}
result := make(orb.Collection, 0, alloc)
d := NewDecoder(r)
for i := 0; i < int(num); i++ {
geom, _, err := d.Decode()
if err != nil {
return nil, err
}
result = append(result, geom)
}
return result, nil
}
func (e *Encoder) writeCollection(c orb.Collection, srid int) error {
err := e.writeTypePrefix(geometryCollectionType, len(c), srid)
if err != nil {
return err
}
for _, geom := range c {
err := e.Encode(geom, 0)
if err != nil {
return err
}
}
return nil
}
| {
"content_hash": "43aed310ab211ddf551768a688f660dd",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 87,
"avg_line_length": 17.73469387755102,
"alnum_prop": 0.6294591484464902,
"repo_name": "paulmach/orb",
"id": "d926a0b4e10041afb1b284ba39300c0478dc842b",
"size": "869",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "encoding/internal/wkbcommon/collection.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "578959"
}
],
"symlink_target": ""
} |
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
| {
"content_hash": "2e063ddfe3e6881e7829780640111d76",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 77,
"avg_line_length": 33.666666666666664,
"alnum_prop": 0.63996399639964,
"repo_name": "EloStef/RockPaperScisors",
"id": "e3da5ce8d43cd3d2a5536670f163c5befc8ffbf6",
"size": "1916",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "www/js/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3033"
},
{
"name": "CSS",
"bytes": "36765"
},
{
"name": "HTML",
"bytes": "21967"
},
{
"name": "Java",
"bytes": "6317"
},
{
"name": "JavaScript",
"bytes": "364866"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_25) on Sat Apr 05 17:39:10 EEST 2014 -->
<title>All Classes</title>
<meta name="date" content="2014-04-05">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
</head>
<body>
<h1 class="bar">All Classes</h1>
<div class="indexContainer">
<ul>
<li><a href="me/machadolucas/dataconverter/Converter.html" title="class in me.machadolucas.dataconverter" target="classFrame">Converter</a></li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "0c2c65c4ae688878087c033e27a86b81",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 144,
"avg_line_length": 34.72222222222222,
"alnum_prop": 0.6864,
"repo_name": "machadolucas/dataConverter",
"id": "55b4d6caeb4cdbd15970503816a37704f5819906",
"size": "625",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "doc/allclasses-frame.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "10512"
}
],
"symlink_target": ""
} |
// This is a generated file. Not intended for manual editing.
package org.intellij.xquery.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
public interface XQueryNamespaceNodeTest extends XQueryPsiElement {
}
| {
"content_hash": "52d585af54b66f229ddb06e46e0dbf0f",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 67,
"avg_line_length": 22.083333333333332,
"alnum_prop": 0.8,
"repo_name": "ligasgr/intellij-xquery",
"id": "2613db5a3d3c6588594defcd7756f5eb6b5cfd11",
"size": "938",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gen/org/intellij/xquery/psi/XQueryNamespaceNodeTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "18427"
},
{
"name": "Java",
"bytes": "3994896"
},
{
"name": "Lex",
"bytes": "51063"
},
{
"name": "XQuery",
"bytes": "126191"
}
],
"symlink_target": ""
} |
namespace bp = boost::python;
struct ConstValueVisitor_wrapper : osg::ConstValueVisitor, bp::wrapper< osg::ConstValueVisitor > {
ConstValueVisitor_wrapper(osg::ConstValueVisitor const & arg )
: osg::ConstValueVisitor( arg )
, bp::wrapper< osg::ConstValueVisitor >(){
// copy constructor
}
ConstValueVisitor_wrapper( )
: osg::ConstValueVisitor( )
, bp::wrapper< osg::ConstValueVisitor >(){
// null constructor
}
virtual void apply( ::GLbyte const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLbyte const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLshort const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLshort const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLint const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLint const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLushort const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLushort const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLubyte const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLubyte const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLuint const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLuint const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::GLfloat const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( ::GLfloat const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( double const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( arg0 );
else{
this->osg::ConstValueVisitor::apply( arg0 );
}
}
void default_apply( double const & arg0 ) {
osg::ConstValueVisitor::apply( arg0 );
}
virtual void apply( ::osg::Vec2b const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2b const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3b const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3b const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4b const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4b const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2s const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2s const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3s const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3s const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4s const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4s const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2i const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2i const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3i const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3i const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4i const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4i const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2ub const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2ub const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3ub const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3ub const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4ub const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4ub const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2us const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2us const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3us const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3us const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4us const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4us const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2ui const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2ui const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3ui const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3ui const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4ui const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4ui const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2 const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2 const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3 const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3 const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4 const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4 const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec2d const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec2d const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec3d const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec3d const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Vec4d const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Vec4d const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Matrixf const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Matrixf const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
virtual void apply( ::osg::Matrixd const & arg0 ) {
if( bp::override func_apply = this->get_override( "apply" ) )
func_apply( boost::ref(arg0) );
else{
this->osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
}
void default_apply( ::osg::Matrixd const & arg0 ) {
osg::ConstValueVisitor::apply( boost::ref(arg0) );
}
};
void register_ConstValueVisitor_class(){
bp::class_< ConstValueVisitor_wrapper >( "ConstValueVisitor", bp::init< >() )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLbyte const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLbyte const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLshort const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLshort const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLint const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLint const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLushort const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLushort const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLubyte const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLubyte const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLuint const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLuint const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::GLfloat const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::GLfloat const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( double const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( double const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2b const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2b const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3b const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3b const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4b const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4b const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2s const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2s const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3s const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3s const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4s const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4s const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2i const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2i const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3i const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3i const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4i const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4i const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2ub const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2ub const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3ub const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3ub const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4ub const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4ub const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2us const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2us const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3us const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3us const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4us const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4us const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2ui const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2ui const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3ui const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3ui const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4ui const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4ui const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2 const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2 const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3 const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3 const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4 const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4 const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec2d const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec2d const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec3d const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec3d const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Vec4d const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Vec4d const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Matrixf const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Matrixf const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) )
.def(
"apply"
, (void ( ::osg::ConstValueVisitor::* )( ::osg::Matrixd const & ))(&::osg::ConstValueVisitor::apply)
, (void ( ConstValueVisitor_wrapper::* )( ::osg::Matrixd const & ))(&ConstValueVisitor_wrapper::default_apply)
, ( bp::arg("arg0") ) );
}
| {
"content_hash": "5aa1b0c11c95c5f41c5b2ee5ac10fc8f",
"timestamp": "",
"source": "github",
"line_count": 603,
"max_line_length": 122,
"avg_line_length": 39.81923714759536,
"alnum_prop": 0.5264253883636667,
"repo_name": "JaneliaSciComp/osgpyplusplus",
"id": "9a9620a8d0b8b51b8b813f0f587f9406971521c3",
"size": "24142",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/modules/osg/generated_code/ConstValueVisitor.pypp.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5836"
},
{
"name": "C++",
"bytes": "15619800"
},
{
"name": "CMake",
"bytes": "40664"
},
{
"name": "Python",
"bytes": "181050"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<package>
<name>mobility_base_gazebo</name>
<version>0.0.1</version>
<description>
Example launch files for working with the Mobility Base Simulator
</description>
<license>BSD</license>
<author>Dataspeed Inc.</author>
<maintainer email="[email protected]">Dataspeed Inc.</maintainer>
<url type="website">http://dataspeedinc.com</url>
<url type="repository">https://bitbucket.org/dataspeedinc/mobility_base_simulator</url>
<url type="bugtracker">https://bitbucket.org/dataspeedinc/mobility_base_simulator/issues</url>
<buildtool_depend>catkin</buildtool_depend>
<build_depend>roslaunch</build_depend>
<run_depend>gazebo_ros</run_depend>
<run_depend>mobility_base_description</run_depend>
<run_depend>mobility_base_gazebo_plugins</run_depend>
</package>
| {
"content_hash": "fb69f24ba2a963fc4d9a8b7b7e3f8ac5",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 96,
"avg_line_length": 35.82608695652174,
"alnum_prop": 0.741504854368932,
"repo_name": "cmsc421/mobility_base_simulator",
"id": "c8f8cff3c2af207f5a7e6f39681fbf2245440c37",
"size": "824",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mobility_base_gazebo/package.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "25787"
},
{
"name": "CMake",
"bytes": "1346"
}
],
"symlink_target": ""
} |
<?php
namespace conquer\i18n\models;
/**
* This is the model class for table "{{%i18n_translator}}".
*
* @property integer $translator_id
* @property string $class_name
* @property integer $created_at
* @property integer $updated_at
*
* @property I18nTranslation[] $i18nTranslations
*
* @author Andrey Borodulin
*/
class I18nTranslator extends \yii\db\ActiveRecord
{
private static $_translators;
public static function tableName()
{
return '{{%i18n_translator}}';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['class_name'], 'required'],
[['created_at', 'updated_at'], 'integer'],
[['class_name'], 'string', 'max' => 255],
[['class_name'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'translator_id' => 'Translator ID',
'class_name' => 'Class Name',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
];
}
public function behaviors()
{
return [
\yii\behaviors\TimestampBehavior::className(),
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getI18nTranslations()
{
return $this->hasMany(I18nTranslation::className(), ['translator_id' => 'translator_id']);
}
/**
*
* @param string $className
* @return \conquer\i18n\models\I18nTranslator
*/
public static function getTranslator($className)
{
if(empty(self::$_translators))
self::$_translators = static::find()->indexBy('class_name')->all();
if(!isset(self::$_translators[$className])){
self::$_translators[$className] = new static([
'class_name' => $className,
]);
self::$_translators[$className]->save(false);
}
return self::$_translators[$className];
}
/**
*
* @param string $category
* @param string $message
* @param string $language
* @return \conquer\i18n\models\I18nTranslation
*/
public function createTranslation($category, $message, $language)
{
$i18nMessage = I18nMessage::findOne([
'category' => $category,
'message' => $message,
]);
if(empty($i18nMessage)){
$i18nMessage = new I18nMessage([
'category' => $category,
'message' => $message,
]);
$i18nMessage->save(false);
}
$i18nTranslation= I18nTranslation::findOne([
'message_id' => $i18nMessage->message_id,
'language' => $language,
]);
if(empty($i18nTranslation)){
$i18nTranslation = new I18nTranslation([
'message_id' => $i18nMessage->message_id,
'language' => $language,
'translator_id' => $this->translator_id,
]);
}else{
$i18nTranslation->translator_id = $this->translator_id;
}
$i18nTranslation->save(false);
return $i18nTranslation;
}
} | {
"content_hash": "4fbf855b20723da9bb0c016935ce5ea0",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 98,
"avg_line_length": 26.65625,
"alnum_prop": 0.49208675263774915,
"repo_name": "borodulin/yii2-i18n-google",
"id": "0bbe56735fa618184b2ec660b19ec34911896d76",
"size": "3606",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/I18nTranslator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "46212"
}
],
"symlink_target": ""
} |
package com.github.dozermapper.core.vo.deepindex;
public class C {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| {
"content_hash": "595d9f70bf4a366dbfe2c00494fba35a",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 49,
"avg_line_length": 13.6,
"alnum_prop": 0.5686274509803921,
"repo_name": "orange-buffalo/dozer",
"id": "9a0a78e9febc80ded8b6e0dd6e891f5006454d15",
"size": "806",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "core/src/test/java/com/github/dozermapper/core/vo/deepindex/C.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2283605"
},
{
"name": "Shell",
"bytes": "1705"
}
],
"symlink_target": ""
} |
import getpass
import sys
import shelve
import time
import logging
import os
from urlparse import urljoin
import json
import requests
import Tkinter as tk
import tkFileDialog as tfile
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from library import Library, get_or_create
from importer import Importer
from uploader import Uploader
from settings import *
# TODO: Figure out how to create database first time and migrations
engine = create_engine('sqlite:///tinsparrow.db', echo=False)
class TinWatch(object):
def __init__(self):
# TODO: Convert to PySide GUI Application
# Currently using tkinter because it's easy
self.session = self.create_db_session()
def create_db_session(self):
Session = sessionmaker()
Session.configure(bind=engine)
return Session()
def main(self):
root = tk.Tk()
app = LoginWindow(root)
root.mainloop()
#
# library = session.query(Library).filter_by(path=LIBRARY_PATH).first()
# if not library:
# library = Library()
# library.path = LIBRARY_PATH
# session.add(library)
#
# session.commit()
#
# importer = Importer()
# importer.find_media(session, library)
#
# session.commit()
#
# uploader = Uploader(token)
# uploader.sync(session)
#
# session.commit()
# logging.basicConfig(level=logging.INFO,
# format='%(asctime)s - %(message)s',
# datefmt='%Y-%m-%d $H:%M:%S')
# path = sys.argv[1] if len(sys.argv) > 1 else '.'
# event_handler = LoggingEventHandler()
# observer = Observer()
# observer.schedule(event_handler, path, recursive=True)
# observer.start()
# try:
# while True:
# time.sleep(1)
# except KeyboardInterrupt:
# observer.stop()
# observer.join()
class SettingsWindow(tk.Tk):
def __init__(self, root):
root.title('Settings')
root.geometry('600x320')
frame = tk.Frame(root, padx=10, pady=10)
frame.pack(fill=tk.BOTH, expand=True)
self.root = root
self.parent = frame
self.initialize()
def initialize(self):
self.file_label = tk.Label(self.parent, text="Set a directory to scan.")
self.file_label.pack()
self.file_button = tk.Button(self.parent, text="Add Music", command=self.ask)
self.file_button.pack()
self.listbox = tk.Listbox(self.parent)
self.listbox.pack()
self.save_button = tk.Button(self.parent, text="Save", command=self.save)
self.save_button.pack()
self.refresh_listbox()
def ask(self):
music_path = tfile.askdirectory(parent=self.parent)
self.add_music_directory(music_path)
def add_music_directory(self, music_path=None):
if not os.path.isdir(music_path):
return
library = get_or_create(self.session, Library, path=music_path)
self.session.commit()
self.refresh_listbox()
def refresh_listbox(self):
self.listbox.delete(0, tk.END)
self.libraries = tw.session.query(Library).all()
for library in self.libraries:
self.listbox.insert(tk.END, library.path)
def save(self):
self.parent.destroy()
MonitorWindow(self.root)
class MonitorWindow(tk.Tk):
def __init__(self, root):
root.title('Monitor')
root.geometry('600x320')
frame = tk.Frame(root, padx=10, pady=10)
frame.pack(fill=tk.BOTH, expand=True)
self.root = root
self.parent = frame
self.initialize()
def initialize(self):
self.settings_button = tk.Button(self.parent, text="Settings", command=self.open_settings)
self.settings_button.pack()
def open_settings(self):
self.parent.destroy()
SettingsWindow(self.root)
class LoginWindow(tk.Tk):
def __init__(self, root):
root.title('Login')
root.geometry('300x160')
frame = tk.Frame(root, padx=10, pady=10)
frame.pack(fill=tk.BOTH, expand=True)
self.parent = frame
self.root = root
self.user_string = tk.StringVar()
self.password_string = tk.StringVar()
self.app_config = shelve.open(CONFIG)
self.initialize()
def initialize(self):
if self.check_token(self.app_config.get('token', False)):
self.open_monitor()
else:
self.user_label = tk.Label(self.parent, text="Username: ")
self.user_label.pack()
self.user_entry = tk.Entry(self.parent, textvariable=self.user_string)
self.user_entry.pack()
self.password_label = tk.Label(self.parent, text="Password: ")
self.password_label.pack()
self.password_entry = tk.Entry(self.parent, show="*", textvariable=self.password_string)
self.password_entry.pack()
self.login_button = tk.Button(self.parent, borderwidth=4, text="Login", width=10, pady=8, command=self.act)
self.login_button.pack(side=tk.BOTTOM)
self.password_entry.bind('<Return>', self.enter)
self.user_entry.focus_set()
def act(self):
token = self.authenticate(self.user_string.get(), self.password_string.get())
if token:
self.app_config['token'] = token
self.open_settings()
else:
self.root.title('Login Failure: Try again...')
def open_settings(self):
self.app_config.close()
self.parent.destroy()
SettingsWindow(self.root)
def open_monitor(self):
self.app_config.close()
self.parent.destroy()
MonitorWindow(self.root)
def enter(self, event):
self.act()
def authenticate(self, username, password):
url = urljoin(API_URL, 'token-auth/')
auth_r = requests.post(url, data={'username': username, 'password': password})
if auth_r.status_code == 200:
token_json = json.loads(auth_r.content)
token = token_json.get('token', None)
if token:
return token
else:
return False
def check_token(self, token):
# TODO: This can be used to check internet connectivity?
url = API_URL
headers = {'Authorization': 'Token {}'.format(token)}
auth_r = requests.get(url, data={}, headers=headers)
if auth_r.status_code == 200:
return True
else:
return False
if __name__ == "__main__":
tw = TinWatch()
tw.main()
| {
"content_hash": "81445ff189d08ba7e8476f1057f647bf",
"timestamp": "",
"source": "github",
"line_count": 215,
"max_line_length": 119,
"avg_line_length": 31.813953488372093,
"alnum_prop": 0.5940058479532164,
"repo_name": "endthestart/tinsparrow",
"id": "5a5a19a0079f9c285ab00b2f5ce21aa1b4f751e3",
"size": "6840",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tinwatch/tinwatch.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4102"
},
{
"name": "HTML",
"bytes": "19849"
},
{
"name": "JavaScript",
"bytes": "17502"
},
{
"name": "Python",
"bytes": "70091"
}
],
"symlink_target": ""
} |
namespace Lekarite.Mvc.Models.Comments
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Lekarite.Models;
using Lekarite.Mvc.Infrastructure.Mapping;
using System.ComponentModel.DataAnnotations;
public class CommentViewModel : IMapFrom<Comment>
{
[Required]
public string Content { get; set; }
public DateTime CreatedOn { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public int DoctorId { get; set; }
public virtual Doctor Doctor { get; set; }
}
} | {
"content_hash": "6a1150ae371c4db3c9feec15ee38639b",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 53,
"avg_line_length": 23.37037037037037,
"alnum_prop": 0.6418383518225039,
"repo_name": "timenov/lekarite.bg",
"id": "8d74eee2ee9f3159a11c04d3731c1da23be82e01",
"size": "633",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lekarite/Lekarite.Mvc/Models/Comments/CommentViewModel.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "144738"
},
{
"name": "CSS",
"bytes": "4598"
},
{
"name": "JavaScript",
"bytes": "10918"
}
],
"symlink_target": ""
} |
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([PXAppDelegate class]));
}
}
| {
"content_hash": "0a2fec500c4c4246a87059d75ae298a3",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 92,
"avg_line_length": 26.666666666666668,
"alnum_prop": 0.6625,
"repo_name": "pixio/PXBlockAlertView",
"id": "0a9c3c37b14e7c16519de2917d028bb14e4ea21c",
"size": "363",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/PXBlockAlertView/main.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "21354"
},
{
"name": "Ruby",
"bytes": "1148"
},
{
"name": "Shell",
"bytes": "18108"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'input' do
before(:all) do
GetsSome::STRICT = nil if defined?(GetsSome::STRICT)
GetsSome::LOOSE = nil if defined?(GetsSome::LOOSE)
end
describe "gets_integer" do
it "should convert the input to an integer" do
stub_input("2\n")
expect(Kernel.gets_integer).to eql(2)
stub_input("2345\n")
expect(Kernel.gets_integer).to eql(2345)
end
it "should raise an error if not a valid integer" do
stub_input("abc\n", '2')
printed = capture_stdout do
Kernel.gets_integer
end
expect(printed).to eq("abc is not a valid integer. Try again\n")
stub_input("1bc\n", '2')
printed = capture_stdout do
Kernel.gets_integer
end
expect(printed).to eql("1bc is not a valid integer. Try again\n")
end
end
describe "gets_array" do
it "should convert a comma separated list to an array" do
stub_input("1,2,3")
expect(Kernel.gets_array).to eql(['1', '2', '3'])
stub_input("apple, banana, orange")
expect(Kernel.gets_array).to eql(%w(apple banana orange))
stub_input("Hello world, goodbye, I love dogecoin")
expect(Kernel.gets_array).to eql(["Hello world", "goodbye", "I love dogecoin"])
end
it "should convert a pipe seperated list to an array" do
stub_input("1|2|3")
expect(Kernel.gets_array).to eql(['1', '2', '3'])
end
it "should convert a white space seperated list to an array" do
stub_input("1 2 3")
expect(Kernel.gets_array).to eql(['1', '2', '3'])
stub_input("hello world goodbye")
expect(Kernel.gets_array).to eql(['hello', 'world', 'goodbye'])
end
end
describe "gets_float" do
it "should convert a decimal seperated number to a float" do
stub_input("1.1")
expect(Kernel.gets_float).to eql(1.1)
stub_input("1")
expect(Kernel.gets_float).to eql(1.0)
end
it "should raise an error if not a valid float" do
stub_input("1.3.2", '2.1')
printed = capture_stdout do
Kernel.gets_float
end
expect(printed).to eq("1.3.2 is not a valid float. Try again\n")
stub_input("abc", '2.1')
printed = capture_stdout do
Kernel.gets_float
end
expect(printed).to eq("abc is not a valid float. Try again\n")
end
end
describe "gets_math" do
it "should evaluate the math in the input" do
stub_input("1 + 1")
expect(Kernel.gets_math).to eql(2)
end
it "should not value invalid math" do
stub_input("puts 'hello'")
expect{Kernel.gets_math}.to raise_error
end
end
describe "gets_number" do
it "should return an integer if the input is an integer" do
stub_input("1")
expect(Kernel.gets_number).to eql(1)
end
it "should be a float if the input is a float" do
stub_input("1.1")
expect(Kernel.gets_number).to eql(1.1)
end
it "should return an error if neither a float or an integer is given" do
stub_input("abc", "1")
printed = capture_stdout do
Kernel.gets_number
end
expect(printed).to eq("abc is not a valid number. Try again\n")
end
end
describe "gets_multiple" do
it "should do multiple assignment" do
stub_input("1,2")
a, b = Kernel.gets_multiple
expect(a).to eql('1')
expect(b).to eql('2')
end
end
end
| {
"content_hash": "3047a2bd524c532f6dc75f0c4e2a52b9",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 85,
"avg_line_length": 31.03669724770642,
"alnum_prop": 0.6157256872598286,
"repo_name": "wannabefro/gets_some",
"id": "c7dd72cf63acaaa9e23bd166918263401cddfba9",
"size": "3383",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/input_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8832"
}
],
"symlink_target": ""
} |
require 'linguist/repository'
require 'linguist/lazy_blob'
require 'test/unit'
class TestRepository < Test::Unit::TestCase
def rugged_repository
@rugged ||= Rugged::Repository.new(File.expand_path("../../.git", __FILE__))
end
def master_oid
'd40b4a33deba710e2f494db357c654fbe5d4b419'
end
def linguist_repo(oid = master_oid)
Linguist::Repository.new(rugged_repository, oid)
end
def test_linguist_language
assert_equal 'Ruby', linguist_repo.language
end
def test_linguist_languages
assert linguist_repo.languages['Ruby'] > 10_000
end
def test_linguist_size
assert linguist_repo.size > 30_000
end
def test_linguist_breakdown
assert linguist_repo.breakdown_by_file.has_key?("Ruby")
assert linguist_repo.breakdown_by_file["Ruby"].include?("bin/linguist")
assert linguist_repo.breakdown_by_file["Ruby"].include?("lib/linguist/language.rb")
end
def test_incremental_stats
old_commit = '3d7364877d6794f6cc2a86b493e893968a597332'
old_repo = linguist_repo(old_commit)
assert old_repo.languages['Ruby'] > 10_000
assert old_repo.size > 30_000
new_repo = Linguist::Repository.incremental(rugged_repository, master_oid, old_commit, old_repo.cache)
assert new_repo.languages['Ruby'] > old_repo.languages['Ruby']
assert new_repo.size > old_repo.size
assert_equal linguist_repo.cache, new_repo.cache
end
def test_repo_git_attributes
# See https://github.com/github/linguist/blob/351c1cc8fd57340839bdb400d7812332af80e9bd/.gitattributes
#
# It looks like this:
# Gemfile linguist-vendored=true
# lib/linguist.rb linguist-language=Java
# test/*.rb linguist-language=Java
# Rakefile linguist-generated
# test/fixtures/* linguist-vendored=false
attr_commit = '351c1cc8fd57340839bdb400d7812332af80e9bd'
repo = linguist_repo(attr_commit)
assert repo.breakdown_by_file.has_key?("Java")
assert repo.breakdown_by_file["Java"].include?("lib/linguist.rb")
assert repo.breakdown_by_file.has_key?("Ruby")
assert !repo.breakdown_by_file["Ruby"].empty?
end
def test_commit_with_git_attributes_data
# Before we had any .gitattributes data
old_commit = '4a017d9033f91b2776eb85275463f9613cc371ef'
old_repo = linguist_repo(old_commit)
# With some .gitattributes data
attr_commit = '7ee006cbcb2d7261f9e648510a684ee9ac64126b'
# It's incremental but should bust the cache
new_repo = Linguist::Repository.incremental(rugged_repository, attr_commit, old_commit, old_repo.cache)
assert new_repo.breakdown_by_file["Java"].include?("lib/linguist.rb")
end
def test_linguist_override_vendored?
attr_commit = '351c1cc8fd57340839bdb400d7812332af80e9bd'
repo = linguist_repo(attr_commit).read_index
override_vendored = Linguist::LazyBlob.new(rugged_repository, attr_commit, 'Gemfile')
# overridden .gitattributes
assert override_vendored.vendored?
end
def test_linguist_override_unvendored?
attr_commit = '351c1cc8fd57340839bdb400d7812332af80e9bd'
repo = linguist_repo(attr_commit).read_index
# lib/linguist/vendor.yml defines this as vendored.
override_unvendored = Linguist::LazyBlob.new(rugged_repository, attr_commit, 'test/fixtures/foo.rb')
# overridden .gitattributes
assert !override_unvendored.vendored?
end
end
| {
"content_hash": "4ef4c00e0ecbd033f832bcaf19380825",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 107,
"avg_line_length": 32.14423076923077,
"alnum_prop": 0.7295842058031708,
"repo_name": "blakeembrey/linguist",
"id": "1fba9b5764db5be7d5d1bf3c185166113ae1c035",
"size": "3343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/test_repository.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "123893"
},
{
"name": "Shell",
"bytes": "334"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__char_file_open_67b.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-67b.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sinks: open
* BadSink : Open the file named in data using open()
* Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#define OPEN _open
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif
namespace CWE36_Absolute_Path_Traversal__char_file_open_67
{
typedef struct _structType
{
char * structFirst;
} structType;
#ifndef OMITBAD
void badSink(structType myStruct)
{
char * data = myStruct.structFirst;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(structType myStruct)
{
char * data = myStruct.structFirst;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
#endif /* OMITGOOD */
} /* close namespace */
| {
"content_hash": "0abe0f414d3e390b03ef4526bb6e8c97",
"timestamp": "",
"source": "github",
"line_count": 83,
"max_line_length": 109,
"avg_line_length": 22.89156626506024,
"alnum_prop": 0.6357894736842106,
"repo_name": "JianpingZeng/xcc",
"id": "f178c4232de1155be8d6758f2885bf52a9a52daa",
"size": "1900",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "xcc/test/juliet/testcases/CWE36_Absolute_Path_Traversal/s02/CWE36_Absolute_Path_Traversal__char_file_open_67b.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
#import "ccMacros.h"
#if __CC_PLATFORM_IOS
#import <UIKit/UIView.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#import "CCView.h"
//CLASSES:
@class CCGLView;
//CLASS INTERFACE:
/** CCGLView Class.
This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass.
The view content is basically an EAGL surface you render your OpenGL scene into.
This class is normally set up for you in the AppDelegate instance of the Cocos2D project template, but you may need to create it yourself
in mixed UIKit / Cocos2D apps or tweak some of its parameters, for instance to enable the framebuffer's alpha channel in order to see views
underneath the CCGLView.
@note Setting the view non-opaque will only work if the pixelFormat is also set to `kEAGLColorFormatRGBA8` upon initialization.
@note This documentation is for the iOS version of the class. OS X and Android use specific variants of CCGLView which
inherit from other base classes (ie NSOpenGLView on OS X).
Parameters:
- `viewWithFrame`: size of the OpenGL view. For full screen use `_window.bounds`.
- `pixelFormat`: Format of the render buffer. Use `kEAGLColorFormatRGBA8` for better color precision (eg: gradients) at the
expense of doubling memory usage and performance.
- Possible values: `kEAGLColorFormatRGBA8`, `kEAGLColorFormatRGB565`
- `depthFormat`: Use stencil if you plan to use CCClippingNode. Use depth if you plan to use 3D effects.
- Possible values: `0`, `GL_DEPTH_COMPONENT24_OES`, `GL_DEPTH24_STENCIL8_OES`
- `sharegroup`: OpenGL sharegroup. Useful if you want to share the same OpenGL context between different threads.
- `multiSampling`: Whether or not to enable multisampling.
- `numberOfSamples`: Only valid if multisampling is enabled
- Possible values: any integer in the range `0` (off) to `glGetIntegerv(GL_MAX_SAMPLES_APPLE)` where the latter is device-dependent.
*/
@interface CCViewiOSGL : UIView <CCView>
/** @name Creating a CCViewiOSGL */
/** creates an initializes an CCViewiOSGL with a frame and 0-bit depth buffer, and a RGB565 color buffer.
@param frame The frame of the view. */
+ (id) viewWithFrame:(CGRect)frame;
/** creates an initializes an CCViewiOSGL with a frame, a color buffer format, and 0-bit depth buffer.
@param frame The frame of the view.
@param format The pixel format of the render buffer, either: `kEAGLColorFormatRGBA8` (24-bit colors, 8-bit alpha) or `kEAGLColorFormatRGB565` (16-bit colors, no alpha). */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
/** creates an initializes an CCViewiOSGL with a frame, a color buffer format, and a depth buffer.
@param frame The frame of the view.
@param format The pixel format of the render buffer, either: `kEAGLColorFormatRGBA8` (24-bit colors, 8-bit alpha) or `kEAGLColorFormatRGB565` (16-bit colors, no alpha).
@param depth The size and format of the depth buffer, use 0 to disable depth buffer. Otherwise use `GL_DEPTH24_STENCIL8_OES` or `GL_DEPTH_COMPONENT24_OES`. */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth;
/** creates an initializes an CCViewiOSGL with a frame, a color buffer format, a depth buffer format, a sharegroup, and multisamping.
@param frame The frame of the view.
@param format The pixel format of the render buffer, either: `kEAGLColorFormatRGBA8` (24-bit colors, 8-bit alpha) or `kEAGLColorFormatRGB565` (16-bit colors, no alpha).
@param depth The size and format of the depth buffer, use 0 to disable depth buffer. Otherwise use `GL_DEPTH24_STENCIL8_OES` or `GL_DEPTH_COMPONENT24_OES`.
@param retained Whether to clear the backbuffer before drawing to it. YES = don't clear, NO = clear.
@param sharegroup An OpenGL sharegroup or nil.
@param multisampling Whether to enable multisampling (AA).
@param samples The number of samples used in multisampling, from 0 (no AA) to `glGetIntegerv(GL_MAX_SAMPLES_APPLE)`. Only takes effect if the preceding multisampling parameters is set to `YES`. */
+ (id) viewWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)multisampling numberOfSamples:(unsigned int)samples;
/** Initializes an CCViewiOSGL with a frame and 0-bit depth buffer, and a RGB565 color buffer
@param frame The frame of the view. */
- (id) initWithFrame:(CGRect)frame; //These also set the current context
/** Initializes an CCViewiOSGL with a frame, a color buffer format, and 0-bit depth buffer
@param frame The frame of the view.
@param format The pixel format of the render buffer, either: `kEAGLColorFormatRGBA8` (24-bit colors, 8-bit alpha) or `kEAGLColorFormatRGB565` (16-bit colors, no alpha). */
- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format;
/** Initializes an CCViewiOSGL with a frame, a color buffer format, a depth buffer format, a sharegroup and multisampling support
@param frame The frame of the view.
@param format The pixel format of the render buffer, either: `kEAGLColorFormatRGBA8` (24-bit colors, 8-bit alpha) or `kEAGLColorFormatRGB565` (16-bit colors, no alpha).
@param depth The size and format of the depth buffer, use 0 to disable depth buffer. Otherwise use `GL_DEPTH24_STENCIL8_OES` or `GL_DEPTH_COMPONENT24_OES`.
@param retained Whether to clear the backbuffer before drawing to it. YES = don't clear, NO = clear.
@param sharegroup An OpenGL sharegroup or nil.
@param sampling Whether to enable multisampling (AA).
@param nSamples The number of samples used in multisampling, from 0 (no AA) to `glGetIntegerv(GL_MAX_SAMPLES_APPLE)`. Only takes effect if the preceding multisampling parameters is set to `YES`. */
- (id) initWithFrame:(CGRect)frame pixelFormat:(NSString*)format depthFormat:(GLuint)depth preserveBackbuffer:(BOOL)retained sharegroup:(EAGLSharegroup*)sharegroup multiSampling:(BOOL)sampling numberOfSamples:(unsigned int)nSamples;
/** @name Framebuffer Information */
/** pixel format: it could be RGBA8 (32-bit) or RGB565 (16-bit) */
@property(nonatomic,readonly) NSString* pixelFormat;
/** depth format of the render buffer: 0, 16 or 24 bits*/
@property(nonatomic,readonly) GLuint depthFormat;
/** returns surface size in pixels */
@property(nonatomic,readonly) CGSize surfaceSize;
/** OpenGL context */
@property(nonatomic,readonly) EAGLContext *context;
/** Whether multisampling is enabled. */
@property(nonatomic,readwrite) BOOL multiSampling;
@property(nonatomic, readonly) GLuint fbo;
@end
#endif // __CC_PLATFORM_IOS
| {
"content_hash": "066761b2cc3ea8d51ce7f9797028bcc9",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 236,
"avg_line_length": 60.84403669724771,
"alnum_prop": 0.767490952955368,
"repo_name": "TukekeSoft/cocos2d-spritebuilder",
"id": "1c57d0b7d4da0d23a038c4379c25b6d89ec1bcae",
"size": "7821",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cocos2d/Platforms/iOS/CCViewiOSGL.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "244583"
},
{
"name": "C++",
"bytes": "14862"
},
{
"name": "Java",
"bytes": "2117"
},
{
"name": "Matlab",
"bytes": "2853"
},
{
"name": "Objective-C",
"bytes": "3420152"
}
],
"symlink_target": ""
} |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-- Type definitions to avoid circular imports.
module Language.K3.Codegen.CPP.Materialization.Hints where
import Control.DeepSeq
import Data.Typeable
import GHC.Generics (Generic)
data Method
= ConstReferenced
| Referenced
| Moved
| Copied
deriving (Eq, Ord, Read, Show, Typeable, Generic)
-- Decisions as pertaining to an identifier at a given expression specify how the binding is to be
-- populated (initialized), and how it is to be written back (finalized, if necessary).
data Decision = Decision { inD :: Method, outD :: Method }
deriving (Eq, Ord, Read, Show, Typeable, Generic)
-- The most conservative decision is to initialize a new binding by copying its initializer, and to
-- finalize it by copying it back. There might be a strictly better strategy, but this is the
-- easiest to write.
defaultDecision :: Decision
defaultDecision = Decision { inD = Copied, outD = Copied }
{- Typeclass Instances -}
instance NFData Method
instance NFData Decision
| {
"content_hash": "28a2a55359e8d0a718b9d30654c0337d",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 99,
"avg_line_length": 34.12903225806452,
"alnum_prop": 0.7457466918714556,
"repo_name": "yliu120/K3",
"id": "245d0b4c8f0996d88d24fed11de8d6807863872c",
"size": "1058",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Language/K3/Codegen/CPP/Materialization/Hints.hs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "383043"
},
{
"name": "CMake",
"bytes": "685"
},
{
"name": "Haskell",
"bytes": "1741268"
},
{
"name": "Makefile",
"bytes": "11287"
}
],
"symlink_target": ""
} |
import hashlib
import json
import os
import random
import re
from nova import exception
from nova import flags
from nova import log as logging
from nova import utils
from nova.openstack.common import cfg
from nova.virt import images
LOG = logging.getLogger(__name__)
util_opts = [
cfg.StrOpt('image_info_filename_pattern',
default='$instances_path/$base_dir_name/%(image)s.info',
help='Allows image information files to be stored in '
'non-standard locations')
]
flags.DECLARE('instances_path', 'nova.compute.manager')
flags.DECLARE('base_dir_name', 'nova.compute.manager')
FLAGS = flags.FLAGS
FLAGS.register_opts(util_opts)
def execute(*args, **kwargs):
return utils.execute(*args, **kwargs)
def get_iscsi_initiator():
"""Get iscsi initiator name for this machine"""
# NOTE(vish) openiscsi stores initiator name in a file that
# needs root permission to read.
contents = utils.read_file_as_root('/etc/iscsi/initiatorname.iscsi')
for l in contents.split('\n'):
if l.startswith('InitiatorName='):
return l[l.index('=') + 1:].strip()
def create_image(disk_format, path, size):
"""Create a disk image
:param disk_format: Disk image format (as known by qemu-img)
:param path: Desired location of the disk image
:param size: Desired size of disk image. May be given as an int or
a string. If given as an int, it will be interpreted
as bytes. If it's a string, it should consist of a number
with an optional suffix ('K' for Kibibytes,
M for Mebibytes, 'G' for Gibibytes, 'T' for Tebibytes).
If no suffix is given, it will be interpreted as bytes.
"""
execute('qemu-img', 'create', '-f', disk_format, path, size)
def create_cow_image(backing_file, path):
"""Create COW image
Creates a COW image with the given backing file
:param backing_file: Existing image on which to base the COW image
:param path: Desired location of the COW image
"""
execute('qemu-img', 'create', '-f', 'qcow2', '-o',
'backing_file=%s' % backing_file, path)
def get_disk_size(path):
"""Get the (virtual) size of a disk image
:param path: Path to the disk image
:returns: Size (in bytes) of the given disk image as it would be seen
by a virtual machine.
"""
out, err = execute('qemu-img', 'info', path)
size = [i.split('(')[1].split()[0] for i in out.split('\n')
if i.strip().find('virtual size') >= 0]
return int(size[0])
def get_disk_backing_file(path):
"""Get the backing file of a disk image
:param path: Path to the disk image
:returns: a path to the image's backing store
"""
out, err = execute('qemu-img', 'info', path)
backing_file = [i.split('actual path:')[1].strip()[:-1]
for i in out.split('\n') if 0 <= i.find('backing file')]
if backing_file:
backing_file = os.path.basename(backing_file[0])
return backing_file
def copy_image(src, dest):
"""Copy a disk image
:param src: Source image
:param dest: Destination path
"""
# We shell out to cp because that will intelligently copy
# sparse files. I.E. holes will not be written to DEST,
# rather recreated efficiently. In addition, since
# coreutils 8.11, holes can be read efficiently too.
execute('cp', src, dest)
def mkfs(fs, path, label=None):
"""Format a file or block device
:param fs: Filesystem type (examples include 'swap', 'ext3', 'ext4'
'btrfs', etc.)
:param path: Path to file or block device to format
:param label: Volume label to use
"""
if fs == 'swap':
execute('mkswap', path)
else:
args = ['mkfs', '-t', fs]
if label:
args.extend(['-n', label])
args.append(path)
execute(*args)
def ensure_tree(path):
"""Create a directory (and any ancestor directories required)
:param path: Directory to create
"""
execute('mkdir', '-p', path)
def write_to_file(path, contents, umask=None):
"""Write the given contents to a file
:param path: Destination file
:param contents: Desired contents of the file
:param umask: Umask to set when creating this file (will be reset)
"""
if umask:
saved_umask = os.umask(umask)
try:
with open(path, 'w') as f:
f.write(contents)
finally:
if umask:
os.umask(saved_umask)
def chown(path, owner):
"""Change ownership of file or directory
:param path: File or directory whose ownership to change
:param owner: Desired new owner (given as uid or username)
"""
execute('chown', owner, path, run_as_root=True)
def create_snapshot(disk_path, snapshot_name):
"""Create a snapshot in a disk image
:param disk_path: Path to disk image
:param snapshot_name: Name of snapshot in disk image
"""
qemu_img_cmd = ('qemu-img',
'snapshot',
'-c',
snapshot_name,
disk_path)
# NOTE(vish): libvirt changes ownership of images
execute(*qemu_img_cmd, run_as_root=True)
def delete_snapshot(disk_path, snapshot_name):
"""Create a snapshot in a disk image
:param disk_path: Path to disk image
:param snapshot_name: Name of snapshot in disk image
"""
qemu_img_cmd = ('qemu-img',
'snapshot',
'-d',
snapshot_name,
disk_path)
# NOTE(vish): libvirt changes ownership of images
execute(*qemu_img_cmd, run_as_root=True)
def extract_snapshot(disk_path, source_fmt, snapshot_name, out_path, dest_fmt):
"""Extract a named snapshot from a disk image
:param disk_path: Path to disk image
:param snapshot_name: Name of snapshot in disk image
:param out_path: Desired path of extracted snapshot
"""
qemu_img_cmd = ('qemu-img',
'convert',
'-f',
source_fmt,
'-O',
dest_fmt,
'-s',
snapshot_name,
disk_path,
out_path)
execute(*qemu_img_cmd)
def load_file(path):
"""Read contents of file
:param path: File to read
"""
with open(path, 'r+') as fp:
return fp.read()
def file_open(*args, **kwargs):
"""Open file
see built-in file() documentation for more details
Note: The reason this is kept in a separate module is to easily
be able to provide a stub module that doesn't alter system
state at all (for unit tests)
"""
return file(*args, **kwargs)
def file_delete(path):
"""Delete (unlink) file
Note: The reason this is kept in a separate module is to easily
be able to provide a stub module that doesn't alter system
state at all (for unit tests)
"""
return os.unlink(path)
def get_open_port(start_port, end_port):
"""Find an available port
:param start_port: Start of acceptable port range
:param end_port: End of acceptable port range
"""
for i in xrange(0, 100): # don't loop forever
port = random.randint(start_port, end_port)
# netcat will exit with 0 only if the port is in use,
# so a nonzero return value implies it is unused
cmd = 'netcat', '0.0.0.0', port, '-w', '1'
try:
stdout, stderr = execute(*cmd, process_input='')
except exception.ProcessExecutionError:
return port
raise Exception(_('Unable to find an open port'))
def get_fs_info(path):
"""Get free/used/total space info for a filesystem
:param path: Any dirent on the filesystem
:returns: A dict containing:
:free: How much space is free (in bytes)
:used: How much space is used (in bytes)
:total: How big the filesystem is (in bytes)
"""
hddinfo = os.statvfs(path)
total = hddinfo.f_frsize * hddinfo.f_blocks
free = hddinfo.f_frsize * hddinfo.f_bavail
used = hddinfo.f_frsize * (hddinfo.f_blocks - hddinfo.f_bfree)
return {'total': total,
'free': free,
'used': used}
def fetch_image(context, target, image_id, user_id, project_id):
"""Grab image"""
images.fetch_to_raw(context, image_id, target, user_id, project_id)
def get_info_filename(base_path):
"""Construct a filename for storing addtional information about a base
image.
Returns a filename.
"""
base_file = os.path.basename(base_path)
return (FLAGS.image_info_filename_pattern
% {'image': base_file})
def is_valid_info_file(path):
"""Test if a given path matches the pattern for info files."""
digest_size = hashlib.sha1().digestsize * 2
regexp = (FLAGS.image_info_filename_pattern
% {'image': ('([0-9a-f]{%(digest_size)d}|'
'[0-9a-f]{%(digest_size)d}_sm|'
'[0-9a-f]{%(digest_size)d}_[0-9]+)'
% {'digest_size': digest_size})})
m = re.match(regexp, path)
if m:
return True
return False
def read_stored_info(base_path, field=None):
"""Read information about an image.
Returns an empty dictionary if there is no info, just the field value if
a field is requested, or the entire dictionary otherwise.
"""
info_file = get_info_filename(base_path)
if not os.path.exists(info_file):
# Special case to handle essex checksums being converted
old_filename = base_path + '.sha1'
if field == 'sha1' and os.path.exists(old_filename):
hash_file = open(old_filename)
hash_value = hash_file.read()
hash_file.close()
write_stored_info(base_path, field=field, value=hash_value)
os.remove(old_filename)
d = {field: hash_value}
else:
d = {}
else:
LOG.info(_('Reading image info file: %s'), info_file)
f = open(info_file, 'r')
serialized = f.read().rstrip()
f.close()
LOG.info(_('Read: %s'), serialized)
try:
d = json.loads(serialized)
except ValueError, e:
LOG.error(_('Error reading image info file %(filename)s: '
'%(error)s'),
{'filename': info_file,
'error': e})
d = {}
if field:
return d.get(field, None)
return d
def write_stored_info(target, field=None, value=None):
"""Write information about an image."""
if not field:
return
info_file = get_info_filename(target)
ensure_tree(os.path.dirname(info_file))
d = read_stored_info(info_file)
d[field] = value
serialized = json.dumps(d)
LOG.info(_('Writing image info file: %s'), info_file)
LOG.info(_('Wrote: %s'), serialized)
f = open(info_file, 'w')
f.write(serialized)
f.close()
| {
"content_hash": "243f3a8fd2f5358a76c4e5bf2b71eb1e",
"timestamp": "",
"source": "github",
"line_count": 377,
"max_line_length": 79,
"avg_line_length": 29.514588859416445,
"alnum_prop": 0.592073335130763,
"repo_name": "psiwczak/openstack",
"id": "edde15e001f70631e1629c12a2e8047437d8de9c",
"size": "12048",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nova/virt/libvirt/utils.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "7403"
},
{
"name": "Python",
"bytes": "5755682"
},
{
"name": "Shell",
"bytes": "26160"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>cats-in-zfc: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.11.2 / cats-in-zfc - 8.8.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
cats-in-zfc
<small>
8.8.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-04-03 22:58:34 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-03 22:58:34 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.11.2 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/cats-in-zfc"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/CatsInZFC"]
depends: [
"ocaml"
"coq" {>= "8.8" & < "8.9~"}
]
tags: [
"keyword: set theory"
"keyword: ordinal numbers"
"keyword: cardinal numbers"
"keyword: category theory"
"keyword: functors"
"keyword: natural transformation"
"keyword: limit"
"keyword: colimit"
"category: Mathematics/Logic/Set theory"
"category: Mathematics/Category Theory"
"date: 2004-10-10"
]
authors: [ "Carlos Simpson <[email protected]> [http://math.unice.fr/~carlos/]" ]
bug-reports: "https://github.com/coq-contribs/cats-in-zfc/issues"
dev-repo: "git+https://github.com/coq-contribs/cats-in-zfc.git"
synopsis: "Category theory in ZFC"
description: """
In a ZFC-like environment augmented by reference to the
ambient type theory, we develop some basic set theory, ordinals, cardinals
and transfinite induction, and category theory including functors,
natural transformations, limits and colimits, functor categories,
and the theorem that functor_cat a b has (co)limits if b does."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/cats-in-zfc/archive/v8.8.0.tar.gz"
checksum: "md5=090072b5cbf45a36fc9da1c24f98ee56"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-cats-in-zfc.8.8.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2).
The following dependencies couldn't be met:
- coq-cats-in-zfc -> coq < 8.9~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-cats-in-zfc.8.8.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "fb96a8e23fe2e7c7bc5645126d4d87bd",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 159,
"avg_line_length": 41.14525139664804,
"alnum_prop": 0.5556008146639512,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "ce2f915972a3610ddd674e57dd683c44d388eb0b",
"size": "7390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.11.2/cats-in-zfc/8.8.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
VMan::Application.routes.draw do
devise_for :users, path: '/'
resources :users
resources :templates
root :to => 'home#index'
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end
| {
"content_hash": "abcbde6328899e175a78f6579a882510",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 91,
"avg_line_length": 29.076923076923077,
"alnum_prop": 0.6550264550264551,
"repo_name": "OpenVDI/V-Man",
"id": "ae173b29d5465691f036d4dbb3dc89d3d233622e",
"size": "1890",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/routes.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "788"
},
{
"name": "Ruby",
"bytes": "45066"
}
],
"symlink_target": ""
} |
package volume
import (
// loads the volume drivers
_ "github.com/emccode/rexray/drivers/volume/docker"
)
| {
"content_hash": "226f032f1dbf511ea247a5a274f03286",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 52,
"avg_line_length": 18.166666666666668,
"alnum_prop": 0.7431192660550459,
"repo_name": "ltouati/rexray",
"id": "1265c7ba70f0b4fc7f9e058a7a40bce064dda6c0",
"size": "109",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "drivers/volume/volume.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "29702"
},
{
"name": "Go",
"bytes": "463090"
},
{
"name": "HTML",
"bytes": "8872"
},
{
"name": "JavaScript",
"bytes": "360"
},
{
"name": "Makefile",
"bytes": "14740"
},
{
"name": "Shell",
"bytes": "9114"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/action_settings"
android:icon="@drawable/ic_action_settings"
android:title="@string/action_settings"
android:showAsAction="ifRoom" />
<!-- Settings, should always be in the overflow -->
<item android:id="@+id/action_more_info"
android:title="@string/more_info"
android:showAsAction="never" />
<item android:id="@+id/action_give_me_a_beer"
android:title="@string/give_me_a_beer"
android:showAsAction="never" />
</menu> | {
"content_hash": "d45c3ee70638891b1f219bb73766c5cd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 66,
"avg_line_length": 45.61538461538461,
"alnum_prop": 0.6306913996627319,
"repo_name": "benjaminthorent/ProxSensorReset",
"id": "b6bf0eb96a685a5058c2a2b391943f2ca2a50b46",
"size": "593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "res/menu/prox_sensor_reset.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "27212"
}
],
"symlink_target": ""
} |
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.SecurityInsights.Models
{
internal partial class Office365ProjectConnectorDataTypesLogs : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("state");
writer.WriteStringValue(State.ToString());
writer.WriteEndObject();
}
internal static Office365ProjectConnectorDataTypesLogs DeserializeOffice365ProjectConnectorDataTypesLogs(JsonElement element)
{
DataTypeState state = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("state"))
{
state = new DataTypeState(property.Value.GetString());
continue;
}
}
return new Office365ProjectConnectorDataTypesLogs(state);
}
}
}
| {
"content_hash": "2572ff7f02c3487c68723205c1a19e7e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 133,
"avg_line_length": 33.93333333333333,
"alnum_prop": 0.6208251473477406,
"repo_name": "Azure/azure-sdk-for-net",
"id": "0141dea4b5fb8457cb86612f4cd25a436284827d",
"size": "1156",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/securityinsights/Azure.ResourceManager.SecurityInsights/src/Generated/Models/Office365ProjectConnectorDataTypesLogs.Serialization.cs",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004, Richard Levitte <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <descrip.h>
#include <namdef.h>
#include <rmsdef.h>
#include <libfildef.h>
#include <lib$routines.h>
#include <strdef.h>
#include <str$routines.h>
#include <stsdef.h>
#ifndef LPDIR_H
# include "LPdir.h"
#endif
#include "vms_rms.h"
/* Some compiler options hide EVMSERR. */
#ifndef EVMSERR
# define EVMSERR 65535 /* error for non-translatable VMS errors */
#endif
struct LP_dir_context_st {
unsigned long VMS_context;
char filespec[NAMX_MAXRSS + 1];
char result[NAMX_MAXRSS + 1];
struct dsc$descriptor_d filespec_dsc;
struct dsc$descriptor_d result_dsc;
};
const char *LP_find_file(LP_DIR_CTX **ctx, const char *directory)
{
int status;
char *p, *r;
size_t l;
unsigned long flags = 0;
/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# pragma pointer_size save
# pragma pointer_size 32
char *ctx_filespec_32p;
# pragma pointer_size restore
char ctx_filespec_32[NAMX_MAXRSS + 1];
#endif /* __INITIAL_POINTER_SIZE == 64 */
#ifdef NAML$C_MAXRSS
flags |= LIB$M_FIL_LONG_NAMES;
#endif
if (ctx == NULL || directory == NULL) {
errno = EINVAL;
return 0;
}
errno = 0;
if (*ctx == NULL) {
size_t filespeclen = strlen(directory);
char *filespec = NULL;
if (filespeclen == 0) {
errno = ENOENT;
return 0;
}
/* MUST be a VMS directory specification! Let's estimate if it is. */
if (directory[filespeclen - 1] != ']'
&& directory[filespeclen - 1] != '>'
&& directory[filespeclen - 1] != ':') {
errno = EINVAL;
return 0;
}
filespeclen += 4; /* "*.*;" */
if (filespeclen > NAMX_MAXRSS) {
errno = ENAMETOOLONG;
return 0;
}
*ctx = malloc(sizeof(**ctx));
if (*ctx == NULL) {
errno = ENOMEM;
return 0;
}
memset(*ctx, 0, sizeof(**ctx));
strcpy((*ctx)->filespec, directory);
strcat((*ctx)->filespec, "*.*;");
/* Arrange 32-bit pointer to (copied) string storage, if needed. */
#if __INITIAL_POINTER_SIZE == 64
# define CTX_FILESPEC ctx_filespec_32p
/* Copy the file name to storage with a 32-bit pointer. */
ctx_filespec_32p = ctx_filespec_32;
strcpy(ctx_filespec_32p, (*ctx)->filespec);
#else /* __INITIAL_POINTER_SIZE == 64 */
# define CTX_FILESPEC (*ctx)->filespec
#endif /* __INITIAL_POINTER_SIZE == 64 [else] */
(*ctx)->filespec_dsc.dsc$w_length = filespeclen;
(*ctx)->filespec_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
(*ctx)->filespec_dsc.dsc$b_class = DSC$K_CLASS_S;
(*ctx)->filespec_dsc.dsc$a_pointer = CTX_FILESPEC;
}
(*ctx)->result_dsc.dsc$w_length = 0;
(*ctx)->result_dsc.dsc$b_dtype = DSC$K_DTYPE_T;
(*ctx)->result_dsc.dsc$b_class = DSC$K_CLASS_D;
(*ctx)->result_dsc.dsc$a_pointer = 0;
status = lib$find_file(&(*ctx)->filespec_dsc, &(*ctx)->result_dsc,
&(*ctx)->VMS_context, 0, 0, 0, &flags);
if (status == RMS$_NMF) {
errno = 0;
vaxc$errno = status;
return NULL;
}
if (!$VMS_STATUS_SUCCESS(status)) {
errno = EVMSERR;
vaxc$errno = status;
return NULL;
}
/*
* Quick, cheap and dirty way to discard any device and directory, since
* we only want file names
*/
l = (*ctx)->result_dsc.dsc$w_length;
p = (*ctx)->result_dsc.dsc$a_pointer;
r = p;
for (; *p; p++) {
if (*p == '^' && p[1] != '\0') { /* Take care of ODS-5 escapes */
p++;
} else if (*p == ':' || *p == '>' || *p == ']') {
l -= p + 1 - r;
r = p + 1;
} else if (*p == ';') {
l = p - r;
break;
}
}
strncpy((*ctx)->result, r, l);
(*ctx)->result[l] = '\0';
str$free1_dx(&(*ctx)->result_dsc);
return (*ctx)->result;
}
int LP_find_file_end(LP_DIR_CTX **ctx)
{
if (ctx != NULL && *ctx != NULL) {
int status = lib$find_file_end(&(*ctx)->VMS_context);
free(*ctx);
if (!$VMS_STATUS_SUCCESS(status)) {
errno = EVMSERR;
vaxc$errno = status;
return 0;
}
return 1;
}
errno = EINVAL;
return 0;
}
| {
"content_hash": "ded8e22c5681cf3412be297f05771a56",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 78,
"avg_line_length": 29.995,
"alnum_prop": 0.5819303217202867,
"repo_name": "kipid/blog",
"id": "51043263ae6708e64e6a77987d5e97b3e211750d",
"size": "6334",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "nodejs/openssl-master/crypto/LPdir_vms.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "199547"
},
{
"name": "C",
"bytes": "20941476"
},
{
"name": "C++",
"bytes": "48100"
},
{
"name": "CSS",
"bytes": "71918"
},
{
"name": "DIGITAL Command Language",
"bytes": "5687"
},
{
"name": "Emacs Lisp",
"bytes": "3734"
},
{
"name": "HTML",
"bytes": "2046077"
},
{
"name": "Java",
"bytes": "34016"
},
{
"name": "JavaScript",
"bytes": "63627"
},
{
"name": "M4",
"bytes": "46625"
},
{
"name": "Makefile",
"bytes": "3457"
},
{
"name": "Module Management System",
"bytes": "1304"
},
{
"name": "Pawn",
"bytes": "4674"
},
{
"name": "Perl",
"bytes": "6794663"
},
{
"name": "Pug",
"bytes": "275"
},
{
"name": "Python",
"bytes": "1366"
},
{
"name": "Raku",
"bytes": "23308"
},
{
"name": "Ruby",
"bytes": "957"
},
{
"name": "Shell",
"bytes": "60412"
},
{
"name": "SourcePawn",
"bytes": "2561"
},
{
"name": "eC",
"bytes": "7473"
},
{
"name": "sed",
"bytes": "502"
}
],
"symlink_target": ""
} |
/* Author: Ioan Sucan */
#include "ompl/base/goals/GoalStates.h"
#include "ompl/base/SpaceInformation.h"
#include "ompl/util/Exception.h"
#include <limits>
ompl::base::GoalStates::~GoalStates()
{
freeMemory();
}
void ompl::base::GoalStates::clear()
{
freeMemory();
states_.clear();
}
void ompl::base::GoalStates::freeMemory()
{
for (auto &state : states_)
si_->freeState(state);
}
double ompl::base::GoalStates::distanceGoal(const State *st) const
{
double dist = std::numeric_limits<double>::infinity();
for (auto state : states_)
{
double d = si_->distance(st, state);
if (d < dist)
dist = d;
}
return dist;
}
void ompl::base::GoalStates::print(std::ostream &out) const
{
out << states_.size() << " goal states, threshold = " << threshold_ << ", memory address = " << this << std::endl;
for (auto state : states_)
{
si_->printState(state, out);
out << std::endl;
}
}
void ompl::base::GoalStates::sampleGoal(base::State *st) const
{
if (states_.empty())
throw Exception("There are no goals to sample");
// Roll over the samplePosition_ if it points past the number of states.
samplePosition_ = samplePosition_ % states_.size();
// Get the next state.
si_->copyState(st, states_[samplePosition_]);
// Increment the counter. Do NOT roll over incase a new state is added before sampleGoal is called again.
samplePosition_++;
}
unsigned int ompl::base::GoalStates::maxSampleCount() const
{
return states_.size();
}
void ompl::base::GoalStates::addState(const State *st)
{
states_.push_back(si_->cloneState(st));
}
void ompl::base::GoalStates::addState(const ScopedState<> &st)
{
addState(st.get());
}
const ompl::base::State *ompl::base::GoalStates::getState(unsigned int index) const
{
if (index >= states_.size())
throw Exception("Index " + std::to_string(index) + " out of range. Only " + std::to_string(states_.size()) +
" states are available");
return states_[index];
}
std::size_t ompl::base::GoalStates::getStateCount() const
{
return states_.size();
}
bool ompl::base::GoalStates::hasStates() const
{
return !states_.empty();
}
| {
"content_hash": "e714579e4438c43ae7f73b1379fef148",
"timestamp": "",
"source": "github",
"line_count": 93,
"max_line_length": 118,
"avg_line_length": 24.193548387096776,
"alnum_prop": 0.6288888888888889,
"repo_name": "davetcoleman/ompl",
"id": "9cb4a3aecee908f390cfa9beeaae736af0658f50",
"size": "4017",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "src/ompl/base/goals/src/GoalStates.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "10965"
},
{
"name": "C++",
"bytes": "4162615"
},
{
"name": "CMake",
"bytes": "57948"
},
{
"name": "CSS",
"bytes": "2410"
},
{
"name": "JavaScript",
"bytes": "766"
},
{
"name": "Python",
"bytes": "260849"
},
{
"name": "R",
"bytes": "43530"
},
{
"name": "Shell",
"bytes": "8533"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>XLabs: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectlogo"><img alt="Logo" src="XLabs_logo.psd"/></td>
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">XLabs
</div>
<div id="projectbrief">Cross-platform reusable C# libraries</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Packages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">XLabs.Platform.Device.IAccelerometer Member List</div> </div>
</div><!--header-->
<div class="contents">
<p>This is the complete list of members for <a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html">XLabs.Platform.Device.IAccelerometer</a>, including all inherited members.</p>
<table class="directory">
<tr class="even"><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html#a8c728486a6f8b2c53fe53fdb64848263">Interval</a></td><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html">XLabs.Platform.Device.IAccelerometer</a></td><td class="entry"></td></tr>
<tr><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html#a401c34c213ef40a8fe4585688ccbeda4">LatestReading</a></td><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html">XLabs.Platform.Device.IAccelerometer</a></td><td class="entry"></td></tr>
<tr class="even"><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html#ab41b43824e0408212354a98bea7ada4e">ReadingAvailable</a></td><td class="entry"><a class="el" href="interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer.html">XLabs.Platform.Device.IAccelerometer</a></td><td class="entry"></td></tr>
</table></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.10 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "9c239459aa33ce60f2023eef4112839b",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 361,
"avg_line_length": 47.465648854961835,
"alnum_prop": 0.6629141202959151,
"repo_name": "XLabs/xlabs.github.io",
"id": "ff350d66d241b21da63379bcfaafe11d80348dea",
"size": "6218",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "html/interface_x_labs_1_1_platform_1_1_device_1_1_i_accelerometer-members.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "33201"
},
{
"name": "HTML",
"bytes": "25233456"
},
{
"name": "JavaScript",
"bytes": "1159419"
}
],
"symlink_target": ""
} |
# <p align="center"> Lists - Exercises <p>
## Array Manipulator
Write a program that r**eads an array of integers** from the console and **set of commands** and **executes them over the array**. The commands are as follows:
- **add <index> <element>** – adds element at the specified index (elements right from this position inclusively are shifted to the right).
- **addMany <index> <element 1> <element 2> … <element n>** – adds a set of elements at the specified index.
- **contains <element>** – prints the index of the first occurrence of the specified element (if exists) in the array or -1 if the element is not found.
- **remove <index>** – removes the element at the specified index.
- **shift <positions> – shifts every element** of the array the number of positions **to the left** (with rotation).
For example, [1, 2, 3, 4, 5] -> shift 2 -> [3, 4, 5, 1, 2]
- **sumPairs** – sums the elements in the array by pairs (first + second, third + fourth, …).
For example, [1, 2, 4, 5, 6, 7, 8] -> [3, 9, 13, 8].
- **print** – stop receiving more commands and print the last state of the array.
#### Examples
|**Input**|**Output**|
|---|---|
|1 2 4 5 6 7 <br/> add 1 8 <br/> contains 1 <br/> contains -3 <br/> print|0 <br/> -1 <br/> [1, 8, 2, 4, 5, 6, 7]|
|1 2 3 4 5 <br/> addMany 5 9 8 7 6 5 <br/> contains 15 <br/> remove 3 <br/> shift 1 <br/> print|-1 <br/> [2, 3, 5, 9, 8, 7, 6, 5, 1]|
|2 2 4 2 4 <br/> add 1 4 <br/> sumPairs <br/> print|[6, 6, 6]|
|1 2 1 2 1 2 1 2 1 2 1 2 <br/> sumPairs <br/> sumPairs <br/> addMany 0 -1 -2 -3 <br/> print|[-1, -2, -3, 6, 6, 6]|
## Bomb Numbers
Write a program that **reads sequence of numbers** and **special bomb number** with a certain **power**. Your task is to **detonate every occurrence of the special bomb number** and according to its power **his neighbors from left and right**. Detonations are performed from left to right and all detonated numbers disappear. Finally print the **sum of the remaining elements** in the sequence.
#### Examples
|**Input**|**Output**|**Comments**|
|---|---|---|
|1 2 2 4 2 2 2 9 <br/> 4 2 |12| Special number is 4 with power 2. After detontaion we left with the sequence [1, 2, 9] with sum 12.|
|1 4 4 2 8 9 1 <br/> 9 3 |5| Special number is 9 with power 3. After detontaion we left with the sequence [1, 4] with sum 5. Since the 9 has only 1 neighbour from the right we remove just it (one number instead of 3).
|1 7 7 1 2 3 <br/> 7 1 |6| Detonations are performed from left to right. We could not detonate the second occurance of 7 because its already destroyed by the first occurance. The numbers [1, 2, 3] survive. Their sum is 6.|
|1 1 2 1 1 1 2 1 1 1 <br/> 2 1 |4| The red and yellow numbers disappear in two sequential detonations. The result is the sequence [1, 1, 1, 1]. Sum = 4.|
integers from the console and set of commands and executes them over
// the array. The commands are as follows:
// add index element – adds element at the specified index (elements right from this position inclusively
// are shifted to the right).
// addMany index element1 element2 elementN – adds a set of elements at the specified index.
// contains element – prints the index of the first occurrence of the specified element (if exists) in the array
// or -1 if the element is not found.
// remove index – removes the element at the specified index.
// shift positions – shifts every element of the array the number of positions to the left (with rotation).
// sumPairs – sums the elements in the array by pairs (first + second, third + fourth, …).
// print – stop receiving more commands and print the last state of the array.
## Append Lists
Write a program to **append several lists** of numbers.
- Lists are separated by **‘|’**.
- Values are separated by **spaces** (‘ ’, **one or several**)
- Order the lists from the **last to the first**, and their values from **left to right**.
#### Examples
|**Input**|**Output**|
|---|---|
|1 2 3 \|4 5 6 \| 7 8 |7 8 4 5 6 1 2 3|
|7 \| 4 5\|1 0\| 2 5 \|3 |3 2 5 1 0 4 5 7|
|1\| 4 5 6 7 \| 8 9 |8 9 4 5 6 7 1|
> #### Hints
> - Create a new empty list for the results.
> - Split the input by ‘|’ into array of tokens.
> - Pass through each of the obtained tokens from tight to left.
> For each token, split it by space and append all non-empty tokens to the results.
> - Print the results.
## Sum Adjacent Equal Numbers
Write a program to **sum all adjacent equal numbers** in a list of decimal numbers, starting from **left to right**.
- After two numbers are summed, the obtained result could be equal to some of its neighbors and should be summed as well (see the examples below).
- Always sum the **leftmost** two equal neighbors (if several couples of equal neighbors are available).
#### Examples
|**Input**|**Output**|**Explanation**|
|---|---|---|
|3 3 6 1 |12 1| 3 3 6 1 -> 6 6 1 -> 12 1|
|8 2 2 4 8 16 |16 8 16| 8 2 2 4 8 16 -> 8 4 4 8 16 -> 8 8 8 16 -> 16 8 16|
|5 4 2 1 1 4 |5 8 4| 5 4 2 1 1 4 -> 5 4 2 2 4 -> 5 4 4 4 -> 5 8 4|
> #### Hints
> 1. Read the **input** and parse it to **list of numbers**.
> 2. Find the **leftmost** two **adjacent equal cells**.
> 3. **Replace** them with their **sum**.
> 4. **Repeat** (1) and (2) until no two equal adjacent cells survive.
> 5. *Print** the processed list of numbers.
## Split by Word Casing
Read a **text**, split it into words and distribute them into **3 lists**.
- **Lower-case** words like “programming”, “at” and “databases” – consist of lowercase letters only.
- **Upper-case** words like “PHP”, “JS” and “SQL” – consist of uppercase letters only.
- **Mixed-case** words like “C#”, “SoftUni” and “Java” – all others.
Use the following **separators** between the words: **, ; : . ! ( ) " ' \ / [ ] space**
#### Examples
|**Input**|**Output**|
|---|---|
|Learn programming at SoftUni: Java, PHP, JS, HTML 5, CSS, Web, C#, SQL, databases, AJAX, etc.| Lower-case: programming, at, databases, etc <br/> Mixed-case: Learn, SoftUni, Java, 5, Web, C# <br/> Upper-case: PHP, JS, HTML, CSS, SQL, AJAX|
> #### Hints
> - **Split** the input text using the above described **separators**.
> - **Process** the obtained **list of words** one by one.
> - Create 3 lists of words (initially empty): lowercase words, mixed-case words and uppercase words.
> - Check each word and append it to one of the above 3 lists:
> Count the **lowercase letters** and **uppercase letters**.
> If all letters are **lowercase**, append the word to the lowercase list.
> If all letters are **uppercase**, append the word to the uppercase list.
> Otherwise the word is considered mixed-case -> append it to the mixed-case list.
> - Print the obtained 3 lists as shown in the example above.
## 06.Square Numbers
Read a **list of integers** and **extract all square numbers** from it and print them in **descending order**. A **square number** is an integer which is the square of any integer. For example, 1, 4, 9, 16 are square numbers.
#### Examples
|**Input**|**Output**|
|---|---|
|3 16 4 5 6 8 9 |16 9 4|
|12 1 9 4 16 8 25 |49 16 49 25 16 16 9 4 1|
> #### Hints
> - To find out whether an integer is **“square number”**, check whether its square root is integer number (has no fractional part):
> **if (√num == (int)√num) …**
> - To order the results list in descending order use sorting by lambda function:
> **squareNums.Sort((a, b) => b.CompareTo(a));**
## Count Numbers
Read a **list of integers** in range [0…1000] and **print them in ascending order** along with their **number of occurrences**.
#### Examples
|**Input**|**Output**|
|---|---|
|8 2 2 8 2 2 3 7|2 -> 4 <br/> 3 -> 1 <br/> 7 -> 1 <br/> 8 -> 2|
|10 8 8 10 10|8 -> 2 <br/> 10 -> 3|
> #### Hints
> Several algorithms can solve this problem:
> - Use an **array count[0…1000]** to count in **counts[x]** the occurrences of each element **x**.
> - *Sort** the numbers and count occurrences of each number.
> - Use a dictionary **counts<int, int>** to count in **counts[x]** the occurrences of each element **x**.
### Counting Occurrences Using Array
1. Read the input elements in array of integers **nums[]**.
2. Assume **max** holds the largest element in **nums[]**.
- **max = nums.Max()**
3. Allocate an array **counts[0 … max+1]**.
- It will hold for each number x its number of occurrences **counts[x]**.
4. **Scan** the input elements and for each element x increase counts[x].
- For each value **v** in **[0…max]**, print **v -> count[v]**.
- Skip all values which do not occur in **nums[]**, i.e. **counts[v] == 0**.
This algorithm has a serious drawback:
- It depends on **mapping numbers to array indexes**.
- It will work well for input values in the range [0…1000].
- It will **not work** for very large and very small values, e.g. if the input holds -100 000 000 or 100 000 000.
- It will **not work** for real numbers, e.g. 3.14 or 2.5.
| {
"content_hash": "a210bef38c6e4f58c25df50da5202114",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 394,
"avg_line_length": 54.39506172839506,
"alnum_prop": 0.6603495233772129,
"repo_name": "BoykoNeov/SoftUni---Programming-fundamentals-May-2017",
"id": "6edf5c51ee5e0ca375d7c555dc5896b779ec53d7",
"size": "8922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lists/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "697736"
}
],
"symlink_target": ""
} |
namespace chrono
{
namespace fem
{
/// Basic geometry for a beam section in 3D, along with basic material
/// properties.
/// This material can be shared between multiple beams.
class ChApiFem ChBeamSection : public ChShared
{
public:
double Area;
double Iyy;
double Izz;
double J;
double G;
double E;
double density;
double rdamping;
double Ks_y;
double Ks_z;
double y_drawsize;
double z_drawsize;
ChBeamSection()
{
E = 0.01e9; // default E stiffness: (almost rubber)
SetGwithPoissonRatio(0.3); // default G (low poisson ratio)
SetAsRectangularSection(0.01, 0.01); // defaults Area, Ixx, Iyy, Ks_y, Ks_z, J
density = 1000; // default density: water
rdamping = 0.01; // default raleygh damping.
}
virtual ~ChBeamSection() {}
/// Set the cross sectional area A of the beam (m^2)
void SetArea(const double ma) { this->Area = ma; }
double GetArea() const {return this->Area;}
/// Set the Iyy moment of inertia of the beam (for flexion about y axis)
/// Note: some textbook calls this Iyy as Iz
void SetIyy(double ma) { this->Iyy = ma; }
double GetIyy() const {return this->Iyy;}
/// Set the Izz moment of inertia of the beam (for flexion about z axis)
/// Note: some textbook calls this Izz as Iy
void SetIzz(double ma) { this->Izz = ma; }
double GetIzz() const {return this->Izz;}
/// Set the J torsion constant of the beam (for torsion about x axis)
void SetJ(double ma) { this->J = ma; }
double GetJ() const {return this->J;}
/// Set the Timoshenko shear coefficient Ks for y shear, usually about 0.8,
/// (for elements that use this, ex. the Timoshenko beams, or Reddy's beams)
void SetKsy (double ma) { this->Ks_y = ma; }
double GetKsy() const {return this->Ks_y;}
/// Set the Timoshenko shear coefficient Ks for z shear, usually about 0.8,
/// (for elements that use this, ex. the Timoshenko beams, or Reddy's beams)
void SetKsz (double ma) { this->Ks_z = ma; }
double GetKsz() const {return this->Ks_z;}
/// Shortcut: set Area, Ixx, Iyy, Ksy, Ksz and J torsion constant
/// at once, given the y and z widths of the beam assumed
/// with rectangular shape.
void SetAsRectangularSection(double width_y, double width_z)
{
this->Area = width_y * width_z;
this->Izz = (1.0/12.0)*width_z*pow(width_y,3);
this->Iyy = (1.0/12.0)*width_y*pow(width_z,3);
// use Roark's formulas for torsion of rectangular sect:
double t = ChMin(width_y, width_z);
double b = ChMax(width_y, width_z);
this->J = b*pow(t,3)* ( (1.0/3.0) - 0.210 * (t/b)*( 1.0- (1.0/12.0)*pow( (t/b) ,4) ) );
// set Ks using Timoshenko-Gere formula for solid rect.shapes
double poisson = this->E /(2.0*this->G) - 1.0;
this->Ks_y = 10.0*(1.0+poisson) / (12.0+ 11.0*poisson);
this->Ks_z = this->Ks_y;
this->y_drawsize = width_y;
this->z_drawsize = width_z;
}
/// Shortcut: set Area, Ixx, Iyy, Ksy, Ksz and J torsion constant
/// at once, given the diameter of the beam assumed
/// with circular shape.
void SetAsCircularSection(double diameter)
{
this->Area = CH_C_PI * pow((0.5*diameter),2);
this->Izz = (CH_C_PI/4.0)* pow((0.5*diameter),4);
this->Iyy = Izz;
// exact expression for circular beam J = Ixx ,
// where for polar theorem Ixx = Izz+Iyy
this->J = Izz + Iyy;
// set Ks using Timoshenko-Gere formula for solid circular shape
double poisson = this->E /(2.0*this->G) - 1.0;
this->Ks_y = 6.0*(1.0+poisson) / (7.0+ 6.0*poisson);
this->Ks_z = this->Ks_y;
this->y_drawsize = diameter;
this->z_drawsize = diameter;
}
/// Set the density of the beam (kg/m^3)
void SetDensity(double md) { this->density = md; }
double GetDensity() const {return this->density;}
/// Set E, the Young elastic modulus (N/m^2)
void SetYoungModulus(double mE) { this->E = mE; }
double GetYoungModulus() const {return this->E;}
/// Set G, the shear modulus
void SetGshearModulus(double mG) { this->G = mG; }
double GetGshearModulus() const {return this->G;}
/// Set G, the shear modulus, given current E and the specified Poisson ratio
void SetGwithPoissonRatio(double mpoisson) { this->G = this->E/(2.0*(1.0+mpoisson)); }
/// Set the Raleygh damping ratio r (as in: R = r * K ), to do: also mass-proportional term
void SetBeamRaleyghDamping(double mr) { this->rdamping = mr; }
double GetBeamRaleyghDamping() {return this->rdamping;}
/// Sets the rectangular thickness of the beam on y and z directions,
/// only for drawing/rendering purposes (these thickenss values do NOT
/// have any meaning at a physical level, use SetAsRectangularSection() instead
/// if you want to affect also the inertias of the beam section).
void SetDrawThickness(double thickness_y, double thickness_z)
{
this->y_drawsize = thickness_y;
this->z_drawsize = thickness_z;
}
double GetDrawThicknessY() {return this->y_drawsize;}
double GetDrawThicknessZ() {return this->z_drawsize;}
};
/// Geometry for a beam section in 3D, along with basic material
/// properties. It also supports the advanced case of
/// Iyy and Izz axes rotated respect reference, centroid with offset
/// from reference, and shear center with offset from reference.
/// This material can be shared between multiple beams.
class ChApiFem ChBeamSectionAdvanced : public ChBeamSection
{
public:
double alpha; // Rotation of Izz Iyy respect to reference line x
double Cy; // Centroid (elastic center, tension center)
double Cz;
double Sy; // Shear center
double Sz;
ChBeamSectionAdvanced()
{
alpha = 0;
Cy = 0;
Cz = 0;
Sy = 0;
Sz = 0;
}
virtual ~ChBeamSectionAdvanced() {}
/// Set the rotation of the section for which the Iyy Izz are
/// defined.
void SetSectionRotation(double ma) { this->alpha = ma; }
double GetSectionRotation() {return this->alpha;}
/// Set the displacement of the centroid C (i.e. the elastic center,
/// or tension center) respect to the reference beam line.
void SetCentroid(double my, double mz) { this->Cy = my; this->Cz = mz;}
double GetCentroidY() {return this->Cy;}
double GetCentroidZ() {return this->Cz;}
/// Set the displacement of the shear center S
/// respect to the reference beam line. For shapes like rectangles,
/// rotated rectangles, etc., it corresponds to the centroid C, but
/// for "L" shaped or "U" shaped beams this is not always true, and
/// the shear center accounts for torsion effects when a shear force is applied.
void SetShearCenter(double my, double mz) { this->Sy = my; this->Sz = mz;}
double GetShearCenterY() {return this->Sy;}
double GetShearCenterZ() {return this->Sz;}
};
} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____
#endif
| {
"content_hash": "131fdc4b69ccd28f4f17a2e82d688615",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 95,
"avg_line_length": 32.004629629629626,
"alnum_prop": 0.6513814552292782,
"repo_name": "scpeters/chrono",
"id": "45f9d8b96b29aeb9d0344ed93162502acc0cda29",
"size": "7372",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/unit_FEM/ChBeamSection.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "533727"
},
{
"name": "C++",
"bytes": "7930713"
},
{
"name": "CSS",
"bytes": "20012"
},
{
"name": "MATLAB",
"bytes": "4917"
},
{
"name": "Objective-C",
"bytes": "104621"
},
{
"name": "Python",
"bytes": "99604"
},
{
"name": "Shell",
"bytes": "6701"
},
{
"name": "TeX",
"bytes": "220"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Timer : MonoBehaviour
{
public int secs = 10;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == "Player")
{
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<GameController>().AddTime(secs);
Destroy(gameObject);
}
}
}
| {
"content_hash": "9a3e57e882029ba2a0f7358aee25201a",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 104,
"avg_line_length": 22.944444444444443,
"alnum_prop": 0.6585956416464891,
"repo_name": "ArthurBOliveira/Supah-Towah",
"id": "175b4cd2241074246ab0bcbada209a35a0493827",
"size": "415",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Tower/Assets/Scripts/Timer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "28360"
},
{
"name": "CSS",
"bytes": "1669"
},
{
"name": "HTML",
"bytes": "923"
},
{
"name": "JavaScript",
"bytes": "1186"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using Google.Apis.Plus.v1;
using Core;
using Logger;
using System.Collections.Generic;
using Google.Apis.Plus.v1.Data;
using System.Text.RegularExpressions;
using System.IO;
namespace LoggenCSG {
internal class Generator : Core.Generator, IDisposable {
protected enum TypePattern {
post,
share,
checkin,
comment,
plus,
reshare
}
protected enum DateType {
TimeSpan,
Date,
Time,
DateTime
}
protected class PatternOption {
public TypePattern Type {
get;
set;
}
public Activity Post {
get;
set;
}
public Activity Share {
get;
set;
}
public Comment Comment {
get;
set;
}
public Person Person {
get;
set;
}
public string SharePath {
get;
set;
}
public string PostFileName {
get;
set;
}
public string Pattern {
get;
set;
}
public Visualizers.Types VisType {
get;
set;
}
}
protected class PatternItem {
public string Type {
get;
set;
}
public string Id {
get;
set;
}
public string Actor {
get;
set;
}
public string ActorName {
get;
set;
}
public string TimeSpan {
get;
set;
}
public string Date {
get;
set;
}
public string Time {
get;
set;
}
public string DateTime {
get;
set;
}
public string Title {
get;
set;
}
public string SharePath {
get;
set;
}
public string PostFileName {
get;
set;
}
}
private string ApiKey {
get;
set;
}
protected static string Logout = "outlog.log";
private Google.Apis.Authentication.IAuthenticator Auth {
get;
set;
}
private PlusService service = null;
protected PlusService Service {
get {
if (service == null)
service = Auth != null ? new PlusService(Auth) : new PlusService();
if (Auth == null)
service.Key = ApiKey;
return service;
}
}
protected IStater Stater {
get;
set;
}
protected bool haveStater;
public Generator(string apiKey, IStater stater = null) {
ApiKey = apiKey;
Auth = null;
Stater = stater;
haveStater = stater != null;
InitLogfile();
WriteLog("Ctor simple apikey", this);
}
public Generator(Google.Apis.Authentication.IAuthenticator auth, IStater stater = null) {
ApiKey = null;
Auth = auth;
Stater = stater;
haveStater = stater != null;
InitLogfile();
WriteLog("Ctor auth", this);
}
private static void InitLogfile() {
using (var wt = (new FileInfo(Logout)).OpenWrite())
wt.Write(new byte[] {}, 0, 0);
}
protected static void WriteLog(string message, object sender, bool error = false){
using (var wt = (new FileInfo(Logout)).AppendText())
wt.WriteLine("{0};{1};{2};{3}", DateTime.Now,
sender,
error ? "Error" : "",
message
);
}
protected static void WriteLog(Exception e, object sender) {
WriteLog(e.Message + "|" + (e.InnerException ?? new Exception("")).Message, sender, true);
}
protected static string DateString(string date, DateType type) {
var str = date;
var parseDate = DateTime.MinValue;
var currentCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
try {
System.Threading.Thread.CurrentThread.CurrentCulture =
System.Globalization.CultureInfo.CreateSpecificCulture("ja-JP");
if (DateTime.TryParse(date, out parseDate))
switch (type) {
case DateType.TimeSpan:
str = (parseDate - DateTime.Parse("1970/1/1")).TotalMilliseconds.ToString();
break;
case DateType.Date:
str = parseDate.ToShortDateString();
break;
case DateType.Time:
str = parseDate.ToShortTimeString();
break;
case DateType.DateTime:
str = parseDate.ToString();
break;
}
}
finally {
System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture;
}
return str;
}
static protected string GetActor(Google.Apis.Plus.v1.Data.Activity.ActorData actor, Visualizers.Types logType) {
return logType == Visualizers.Types.Code_swarm ? actor.Id : actor.DisplayName;
}
static protected string GetActor(Google.Apis.Plus.v1.Data.Comment.ActorData actor, Visualizers.Types logType) {
return logType == Visualizers.Types.Code_swarm ? actor.Id : actor.DisplayName;
}
static protected string GetActor(Google.Apis.Plus.v1.Data.Activity.ObjectData.ActorData actor, Visualizers.Types logType) {
return logType == Visualizers.Types.Code_swarm ? actor.Id : actor.DisplayName;
}
static protected string GetActor(Google.Apis.Plus.v1.Data.Person actor, Visualizers.Types logType) {
return logType == Visualizers.Types.Code_swarm ? actor.Id : actor.DisplayName;
}
static public void LogGen(Dictionary<Visualizers.Types, Appender> loggers,
Visualizers.Types typelog,
Dictionary<Rules, string> rules,
KeyValuePair<Activity, ActivityCont> dicitem) {
var item = dicitem.Key;
var action = "A";
var logEvent = Visualizers.TypeLogEvent[typelog]
.GetConstructor(Type.EmptyTypes)
.Invoke(Type.EmptyTypes) as LogEvent;
var po = new PatternOption();
var share = dicitem.Value.Share;
if (share != null) {
po.Post = item;
po.Share = share;
po.Pattern = rules[Rules.SharePath];
po.Type = TypePattern.share;
po.SharePath = ReplacePattern(po);
po.Pattern = rules[Rules.ShareName];
po.PostFileName = po.SharePath + ReplacePattern(po);
po.PostFileName = po.PostFileName.Replace("//", "/");
logEvent.User = GetActor(share.Actor, typelog);
logEvent.Date = DateTime.Parse(share.Published);
logEvent.Action = typelog == Visualizers.Types.Logstalgia ? "share" : action;
logEvent.FileName = po.PostFileName;
if (logEvent is LogstalgiaEvent)
(logEvent as LogstalgiaEvent).Size =
!string.IsNullOrWhiteSpace(share.Title) ?
share.Title.Length.ToString() :
string.IsNullOrWhiteSpace(item.Title) ?
item.Title.Length.ToString() : "200";
loggers[typelog].Append(logEvent);
action = "M";
}
else {
po.Post = item;
po.Type = TypePattern.post;
po.Pattern = rules[Rules.NotShare];
po.SharePath = ReplacePattern(po);
}
po.Type = (TypePattern)Enum.Parse(typeof(TypePattern), item.Verb, true);
if (po.Type == TypePattern.share && share == null)
po.Type = TypePattern.post;
po.Pattern = rules[Rules.Post];
var sharafile = po.PostFileName;
po.PostFileName = ReplacePattern(po);
logEvent.User = GetActor(item.Actor, typelog);
logEvent.Date = DateTime.Parse(item.Published);
logEvent.Action = typelog == Visualizers.Types.Logstalgia ? "post" : action;
logEvent.FileName = po.PostFileName;
if (logEvent is LogstalgiaEvent)
(logEvent as LogstalgiaEvent).Size = item.Object != null ? item.Object.Content.Length.ToString() : "100";
if (share != null && (logEvent is GephiLogEvent)) {
(logEvent as GephiLogEvent).From = sharafile;
}
loggers[typelog].Append(logEvent);
if (item.Object != null) {
if (item.Object.Replies.TotalItems > 0) {
try {
var listpl = dicitem.Value.Comments;
po.Pattern = rules[Rules.Comment];
po.Type = TypePattern.comment;
foreach (var pl in listpl) {
po.Comment = pl;
po.Type = TypePattern.comment;
var fnp = ReplacePattern(po);
logEvent.User = GetActor(pl.Actor, typelog);
logEvent.Date = DateTime.Parse(pl.Published);
logEvent.Action = typelog == Visualizers.Types.Logstalgia ? "comment" : "A";
logEvent.FileName = fnp;
if (logEvent is LogstalgiaEvent)
(logEvent as LogstalgiaEvent).Size = pl.Object != null ? pl.Object.Content.Length.ToString() : "1";
if (logEvent is GephiLogEvent)
(logEvent as GephiLogEvent).From = po.PostFileName;
loggers[typelog].Append(logEvent);
}
}
catch (Exception e) {
WriteLog(e, "Generator.LogGen");
}
}
long ticks = 0;
if (item.Object.Plusoners.TotalItems > 0) {
try {
var listpl = dicitem.Value.Plusers;
po.Pattern = rules[Rules.Plus];
foreach (var pl in listpl) {
po.Person = pl;
po.Type = TypePattern.plus;
var fnp = ReplacePattern(po);
logEvent.User = GetActor(pl, typelog);
logEvent.Date = DateTime.Parse(item.Published).AddMinutes(ticks);
logEvent.Action = typelog == Visualizers.Types.Logstalgia ? "plus" : "A";
logEvent.FileName = fnp;
if (logEvent is LogstalgiaEvent)
(logEvent as LogstalgiaEvent).Size = "5";
if (logEvent is GephiLogEvent)
(logEvent as GephiLogEvent).From = po.PostFileName;
loggers[typelog].Append(logEvent);
ticks += 5;
}
}
catch (Exception e) {
WriteLog(e, "Generator.LogGen");
}
}
ticks = 0;
if (item.Object.Resharers.TotalItems > 0) {
try {
var listpl = dicitem.Value.Sharers;
po.Pattern = rules[Rules.Plus];
foreach (var pl in listpl) {
po.Person = pl;
po.Type = TypePattern.reshare;
var fnp = ReplacePattern(po);
logEvent.User = GetActor(pl, typelog);
logEvent.Date = DateTime.Parse(item.Published).AddMinutes(ticks);
logEvent.Action = typelog == Visualizers.Types.Logstalgia ? "reshare" : "A";
logEvent.FileName = fnp;
if (logEvent is LogstalgiaEvent)
(logEvent as LogstalgiaEvent).Size = "5";
if (logEvent is GephiLogEvent)
(logEvent as GephiLogEvent).From = po.PostFileName;
loggers[typelog].Append(logEvent);
ticks += 5;
}
}
catch (Exception e) {
WriteLog(e, "Generator.LogGen");
}
}
}
}
protected static string ApplyPattern(string pattern, PatternItem item, string prefix = "", string[] prefixignore = null) {
var result = pattern;
if (string.IsNullOrWhiteSpace(result))
return string.Empty;
var arr = item.GetType().GetProperties().ToArray();
foreach (var prop in arr) {
result = Regex.Replace(result,
MakeRule(prop.Name, prefix, prefixignore),
string.Format("{0}", prop.GetValue(item, null)),
RegexOptions.IgnoreCase | RegexOptions.Multiline);
}
return result;
}
private static string MakeRule(string name, string prefix = "", string[] prefixignore = null) {
return "{" + (
prefixignore == null ||
prefixignore.Count(x =>
Regex.Match(x, name, RegexOptions.IgnoreCase).Success) == 0 ?
prefix : string.Empty
) + name + "}";
}
protected static string GetTypePatternName(TypePattern type) {
return Enum.GetName(typeof(TypePattern), type);
}
protected static string ForTitle(string input, int length = 20) {
return string.IsNullOrEmpty(input) ? input :
input.Substring(0, input.Length > length ? length : input.Length);
}
protected static string ReplacePattern(PatternOption option) {
if (option == null)
return string.Empty;
var result = option.Pattern;
var prefix = string.Empty;
var completed = false;
PatternItem item = null;
do {
switch (option.Type) {
case TypePattern.share:
case TypePattern.checkin:
case TypePattern.post:
var post = option.Type == TypePattern.share ? option.Share : option.Post;
item = null;
if (post != null)
item = new PatternItem() {
Type = string.IsNullOrWhiteSpace(prefix) ? GetTypePatternName(option.Type) : "{type}",
Id = post.Id,
TimeSpan = DateString(post.Published, DateType.TimeSpan),
Date = DateString(post.Published, DateType.Date),
Time = DateString(post.Published, DateType.Time),
DateTime = DateString(post.Published, DateType.DateTime),
ActorName = post.Actor.DisplayName,
Actor = post.Actor.Id,
SharePath = !string.IsNullOrWhiteSpace(option.SharePath) ? option.SharePath : "{sharepath}",
PostFileName = !string.IsNullOrWhiteSpace(option.PostFileName) ? option.PostFileName : "{postfilename}",
Title = !string.IsNullOrWhiteSpace(post.Title) ? ForTitle(post.Title, 100) :
(string.IsNullOrWhiteSpace(post.Object.Content) ? post.Id :
ForTitle(Regex.Replace(post.Object.Content, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Multiline), 100))
};
if (!(completed = option.Type != TypePattern.share)) {
option.Type = TypePattern.post;
}
break;
case TypePattern.comment:
var comment = option.Comment;
item = null;
if (comment != null)
item = new PatternItem() {
Type = string.IsNullOrWhiteSpace(prefix) ? GetTypePatternName(option.Type) : "{type}",
Id = comment.Id,
TimeSpan = DateString(comment.Published, DateType.TimeSpan),
Date = DateString(comment.Published, DateType.Date),
Time = DateString(comment.Published, DateType.Time),
DateTime = DateString(comment.Published, DateType.DateTime),
ActorName = comment.Actor.DisplayName,
Actor = comment.Actor.Id,
SharePath = !string.IsNullOrWhiteSpace(option.SharePath) ? option.SharePath : "{sharepath}",
PostFileName = !string.IsNullOrWhiteSpace(option.PostFileName) ? option.PostFileName : "{postfilename}",
Title = comment.Object == null || string.IsNullOrWhiteSpace(comment.Object.Content) ?
comment.Id : ForTitle(Regex.Replace(comment.Object.Content, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Multiline), 100)
};
option.Type = TypePattern.post;
break;
case TypePattern.plus:
case TypePattern.reshare:
var person = option.Person;
item = null;
if (person != null) {
item = new PatternItem() {
Type = string.IsNullOrWhiteSpace(prefix) ? GetTypePatternName(option.Type) : "{type}",
Id = person.Id,
TimeSpan = DateString(DateTime.Now.ToString(), DateType.TimeSpan),
Date = DateString(DateTime.Now.ToString(), DateType.Date),
Time = DateString(DateTime.Now.ToString(), DateType.Time),
DateTime = DateString(DateTime.Now.ToString(), DateType.DateTime),
ActorName = person.DisplayName,
Actor = person.Id,
SharePath = !string.IsNullOrWhiteSpace(option.SharePath) ? option.SharePath : "{sharepath}",
PostFileName = !string.IsNullOrWhiteSpace(option.PostFileName) ? option.PostFileName : "{postfilename}",
Title = "{posttitle}"
};
post = option.Post;
if (post != null) {
item.TimeSpan = DateString(post.Published, DateType.TimeSpan);
item.Date = DateString(post.Published, DateType.Date);
item.Time = DateString(post.Published, DateType.Time);
item.DateTime = DateString(post.Published, DateType.DateTime);
}
}
option.Type = TypePattern.post;
break;
}
if (item != null && !string.IsNullOrWhiteSpace(result))
result = ApplyPattern(result, item, prefix, new string[] { "type", "sharepath", "postfilename" });
if (!completed)
prefix = "post";
else
break;
} while (!completed);
if (result == "{type}:{title}")
result = "вот же хер";
return ReplaceForLog(result.Replace("//", "/"));
}
private static string ReplaceForLog(string p) {
return p.Replace("\n", "")
.Replace("\r", "")
.Replace("!", "")
.Replace("©", "")
.Replace("►", "");
}
protected virtual void GenerateLogs(Dictionary<Activity, ActivityCont> data,
GeneratorSetting setting, Dictionary<Visualizers.Types, Appender> loggers) {
if (haveStater)
Stater.StateLabel = "Generation ...";
if (haveStater) {
Stater.MaxPosition = data.Count * loggers.Count;
Stater.SetState("Generate logs ...", 0);
}
foreach (var log in loggers.Keys) {
var rules = setting.Rules[log];
foreach (var dicitem in data) {
setting.Methods[log](loggers, log, rules, dicitem);
//LogGen(loggers, log.Key, rules, dicitem);
if (haveStater)
Stater.Inc();
}
}
}
protected Dictionary<Visualizers.Types, Appender> loggers = null;
protected Dictionary<string, bool> users = null;
protected virtual void doGenerate(GeneratorSetting setting, string pid, int depth = 0) {
if (string.IsNullOrWhiteSpace(pid) || setting == null)
return;
var acts = Service.Activities.List(pid, setting.Collection);
if (setting.UseDateRange)
setting.MaxResults = 100;
var step = setting.MaxResults / (double)100;
string nextPage = string.Empty;
if(users == null)
users = new Dictionary<string, bool>();
users[pid] = true;
while (step != 0) {
var nextResults = 100;
if (step-- < 1) {
nextResults = (int)((step + 1) * 100);
step = 0;
}
step = step == 0 && setting.UseDateRange ? 1 : step;
acts.MaxResults = nextResults;
acts.PageToken = nextPage;
if (haveStater) {
Stater.MaxPosition = nextResults;
Stater.SetState("Load feeds ...");
}
Dictionary<Activity, ActivityCont> dicdate = null;
try {
var feed = acts.Fetch();
if (dicdate == null)
dicdate = new Dictionary<Activity, ActivityCont>();
dicdate.Clear();
nextPage = null;
if (feed.Error == null) {
nextPage = feed.NextPageToken;
if (string.IsNullOrWhiteSpace(nextPage)) {
step = 0;
Stater.Position = Stater.MaxPosition;
}
if (haveStater) {
Stater.MaxPosition = feed.Items.Count;
Stater.SetState("Parsing ...");
}
foreach (var item in feed.Items) {
if (setting.UseDateRange && !InRange(setting.DateFrom, setting.DateTo, item.Published)) {
if (IsOutLeft(setting.DateFrom, item.Published)) {
step = 0;
break;
}
continue;
}
var ditem = dicdate[item] = new ActivityCont();
if (item.Object != null) {
if (item.Verb == "share" &&
!string.IsNullOrWhiteSpace(item.Object.Id)) {
try {
ditem.Share = Service.Activities.Get(item.Object.Id).Fetch();
}
catch (Exception e) {
WriteLog(e, this);
}
}
if (item.Object.Replies.TotalItems > 0) {
var plser = Service.Comments.List(item.Id);
plser.MaxResults = setting.MaxComments;
try {
var listpl = plser.Fetch();
ditem.Comments = listpl.Items;
}
catch (Exception e) {
WriteLog(e, this);
}
}
if (item.Object.Plusoners.TotalItems > 0) {
var plser = Service.People.ListByActivity(item.Id, PeopleResource.Collection.Plusoners);
plser.MaxResults = setting.MaxPluses;
try {
var listpl = plser.Fetch();
ditem.Plusers = listpl.Items;
}
catch (Exception e) {
WriteLog(e, this);
}
}
if (item.Object.Resharers.TotalItems > 0) {
var plser = Service.People.ListByActivity(item.Id, PeopleResource.Collection.Resharers);
plser.MaxResults = setting.MaxReshares;
try {
var listpl = plser.Fetch();
ditem.Sharers = listpl.Items;
}
catch (Exception e) {
WriteLog(e, this);
}
}
}
if (haveStater)
Stater.Inc();
}
GenerateLogs(dicdate, setting, loggers);
if (depth > 0) {
foreach (var ditem in dicdate) {
try {
var share = ditem.Value.Share;
if (share != null) {
if (share.Actor != null &&
!string.IsNullOrWhiteSpace(share.Actor.Id) &&
!users.ContainsKey(share.Actor.Id)) {
users[share.Actor.Id] = true;
doGenerate(setting, share.Actor.Id, depth - 1);
}
}
}
catch (Exception e) {
WriteLog(e, this);
}
try {
var coms = ditem.Value.Comments;
if (coms != null) {
foreach (var sitem in coms) {
if (!users.ContainsKey(sitem.Actor.Id)) {
users[sitem.Actor.Id] = true;
doGenerate(setting, sitem.Actor.Id, depth - 1);
}
if (haveStater)
Stater.Inc();
}
}
}
catch (Exception e) {
WriteLog(e, this);
}
try {
var pluses = ditem.Value.Plusers;
if (pluses != null) {
foreach (var sitem in pluses) {
if (!users.ContainsKey(sitem.Id)) {
users[sitem.Id] = true;
doGenerate(setting, sitem.Id, depth - 1);
}
if (haveStater)
Stater.Inc();
}
}
}
catch (Exception e) {
WriteLog(e, this);
}
try {
var shares = ditem.Value.Sharers;
if (shares != null) {
foreach (var sitem in shares) {
if (!users.ContainsKey(sitem.Id)) {
users[sitem.Id] = true;
doGenerate(setting, sitem.Id, depth - 1);
}
if (haveStater)
Stater.Inc();
}
}
}
catch (Exception e) {
WriteLog(e, this);
}
}
if (haveStater)
Stater.Inc();
}
}
else {
WriteLog(feed.Error.ToString(), this);
}
}
catch (Exception e) {
WriteLog(e, this);
e.ShowError();
step = 0;
}
}
}
protected override object GenerateLog(Core.GeneratorSetting insetting = null) {
var setting = insetting as GeneratorSetting;
var ids = setting.ProfileID.Split(new char[] { ';', ',', '|' });
loggers = new Dictionary<Visualizers.Types, Appender>();
foreach (var log in setting.LogFiles)
if (setting.VisLogs.HasFlag(log.Key) && (!loggers.ContainsKey(log.Key) || loggers[log.Key] == null))
loggers[log.Key] = Visualizers.Loggers[log.Key]
.GetConstructor(new Type[] { typeof(string) })
.Invoke(new object[] { log.Value }) as Appender;
foreach (var pid in ids) {
doGenerate(setting, pid, setting.Deep);
}
return true;
}
protected bool InRange(DateTime from, DateTime to, string current) {
var date = DateTime.MinValue;
return DateTime.TryParse(current, out date) && (from <= date && date <= to);
}
protected bool IsOutLeft(DateTime from, string current) {
var date = DateTime.MinValue;
return DateTime.TryParse(current, out date) && (from > date);
}
protected bool IsOutRight(DateTime to, string current) {
var date = DateTime.MinValue;
return DateTime.TryParse(current, out date) && (to < date);
}
public void Dispose() {
if (loggers != null)
foreach (var log in loggers.Keys)
loggers[log].Dispose();
loggers = null;
}
}
internal sealed class ActivityCont {
public IList<Person> Plusers {
get;
set;
}
public IList<Person> Sharers {
get;
set;
}
public IList<Comment> Comments {
get;
set;
}
public Activity Share {
get;
set;
}
}
delegate void GeneratorLogsMeth(Dictionary<Visualizers.Types, Appender> loggers, Visualizers.Types typelog, Dictionary<Rules, string> rules, KeyValuePair<Activity, ActivityCont> dicitem);
}
| {
"content_hash": "6842020971c5bd48d6ffe9fb32bd136a",
"timestamp": "",
"source": "github",
"line_count": 876,
"max_line_length": 188,
"avg_line_length": 27.628995433789953,
"alnum_prop": 0.59058794364335,
"repo_name": "artzub/LoggenCSG",
"id": "3e9ba67e3ddeea09500628869417fcacfa1791f7",
"size": "24216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gapi_plus/Generator.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "1978161"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "22bf8fd7de7e526e2c3b8d23e1182bb9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.23076923076923,
"alnum_prop": 0.6917293233082706,
"repo_name": "mdoering/backbone",
"id": "297c30a955c4be09e0130e71e169f311b274a7d8",
"size": "199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Iridaceae/Sisyrinchium/Sisyrinchium angustissimum/ Syn. Sisyrinchium polycladum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
// Start a session feed
session_start();
// Kick us out if we don't have a Tag Code given.
if (!isset($_POST["TagCode"]))
{
header("Location: tagpage.php");
die();
}
// Set Database Connection
include 'dbconnector.php';
// Get User's Name and ID
$MyId = $_SESSION["userId"];
// Current Date
$date = date('Y-m-d H:i:s');
// Which mission this is associated with?
$RelevantMissionID = $_POST["MissionAssoc"];
// Get the given tag.
$RecievedTag = mysqli_real_escape_string($DBCon, $_POST["TagCode"]);
// Get OUR info.
$GetBasicInfoQuery = "SELECT `userteam`,`usergame` FROM `hvzuserstate` WHERE `userid` = '$MyId'";
$UserInfoResult = mysqli_query($DBCon, $GetBasicInfoQuery);
// Get results.
$UserInfo = mysqli_fetch_row($UserInfoResult);
// Get Our Team and our Game
$UserTeam = $UserInfo[0];
$UserGame = $UserInfo[1];
// Check if our game is not on pause:
$CheckForPause = "SELECT `gameState` FROM `hvzgame` WHERE `gameId` = $UserGame";
$GameState = mysqli_fetch_row(mysqli_query($DBCon, $CheckForPause))[0];
// If game is not immediately running.
if ($GameState != 2)
{
echo "<html>";
echo "<body onload=\"document.frm1.submit()\">";
echo "<form action=\"tagpage.php\" method=\"post\" name=\"frm1\">";
echo "<input type=\"hidden\" name=\"LoadError\" value=\"1\"/>";
echo "</form>";
echo "</body>";
echo "</html>";
die();
}
// It's an NPC?
if (strpos($RecievedTag, 'NPC') == 0)
{
$FindVictimQuery = "SELECT `tagid`,`userId` FROM `hvztagnums` WHERE `tagcode` = '$RecievedTag'";
$VictimFound = mysqli_query($DBCon, $FindVictimQuery);
}
// Nope, human
else
{
// Try to see if we can find an appropriate tag
$FindVictimQuery = "SELECT `tagid`,`userId` FROM `hvztagnums` WHERE `tagcode` = '$RecievedTag' AND `gameId` = $UserGame";
$VictimFound = mysqli_query($DBCon, $FindVictimQuery);
}
// If there were no rows found,
// Kick us back and tell us that given code is wrong.
if ($VictimFound->num_rows==0)
{
echo "<html>";
echo "<body onload=\"document.frm1.submit()\">";
echo "<form action=\"tagpage.php\" method=\"post\" name=\"frm1\">";
echo "<input type=\"hidden\" name=\"LoadError\" value=\"2\"/>";
echo "</form>";
echo "</body>";
echo "</html>";
die();
}
// Get Which tag to remove and which user to tag.
$TagRow = mysqli_fetch_array($VictimFound);
$TagToRemoveId = $TagRow[0];
$UserTaggedId = $TagRow[1];
// Creates a new tag entry.
$CreateTagQuery = "INSERT INTO `hvztags`(`tagerid`, `taggedid`, `tagdate`, `taggameid`) VALUES ($MyId, $UserTaggedId, '$date', $UserGame)";
mysqli_query($DBCon, $CreateTagQuery);
// Find the last query we just made
$FindLastTagQuery = "SELECT `tagid` FROM `hvztags` WHERE `tagerid` = $MyId AND `taggedid` = $UserTaggedId AND `taggameid` = $UserGame ORDER BY `tagid` DESC LIMIT 1";
$LastTagResult = mysqli_query($DBCon, $FindLastTagQuery);
$LastTagID = mysqli_fetch_array($LastTagResult)[0];
// Start setting the Zombie Feeding Query
$FeedZmabiesQuery = "UPDATE `hvzuserstate` SET `userlastfed`= '$date' WHERE `userid` = $MyId";
// If extra feds are set:
if (isset($_POST["Zomb1"]))
{
// Save value into variables
$Extra = $_POST["Zomb1"];
// If not zero, add to the query.
if ($Extra != 0)
{
$FeedZmabiesQuery = $FeedZmabiesQuery . " OR `userid` = $Extra";
}
}
if (isset($_POST["Zomb2"]))
{
// Save value into variables
$Extra = $_POST["Zomb2"];
// If not zero, add to the query.
if ($Extra != 0)
{
$FeedZmabiesQuery = $FeedZmabiesQuery . " OR `userid` = $Extra";
}
}
if (isset($_POST["Zomb3"]))
{
// Save value into variables
$Extra = $_POST["Zomb3"];
// If not zero, add to the query.
if ($Extra != 0)
{
$FeedZmabiesQuery = $FeedZmabiesQuery . " OR `userid` = $Extra";
}
}
// Runs the Query to feed the zombies
mysqli_query($DBCon, $FeedZmabiesQuery);
// As long as it's not an NPC
if ($UserTaggedId != 0)
{
// Get the victim's team.
$GetVictimTeamQuery = "SELECT `userteam` FROM `hvzuserstate` WHERE `userid` = $UserTaggedId";
$VictimTeam = mysqli_fetch_array(mysqli_query($DBCon, $GetVictimTeamQuery))[0];
$NextTeam = 0;
if ($VictimTeam == 2 || $VictimTeam == 3)
{
$NextTeam = 0;
}
else if ($VictimTeam == 4)
{
$NextTeam = 1;
}
// Turn victim into a Zmabie
$ConvertVictimToZambyQuery = "UPDATE `hvzuserstate` SET `userteam`=$NextTeam,`userlastfed`='$date' WHERE `userid` = $UserTaggedId";
mysqli_query($DBCon, $ConvertVictimToZambyQuery);
// We are regular zombie tag
if ($UserTeam < 2)
{
$SmallTagType = 2;
}
// We are an OZ
else if ($UserTeam == 5)
{
$SmallTagType = 4;
}
// Create a new small event for tagger.
$CreateMiniEventQuery = "INSERT INTO `hvzsmallevents`(`evntType`, `evtDate`, `usrSubjctId`, `relevantId`) VALUES ($SmallTagType, '$date', $MyId, $LastTagID)";
mysqli_query($DBCon, $CreateMiniEventQuery);
// We are regular zombie tag
if ($UserTeam < 2)
{
$SmallTagType = 3;
}
// We are an OZ
else if ($UserTeam == 5)
{
$SmallTagType = 5;
}
// Create a new small event for tagged user.
$CreateMiniEventQuery = "INSERT INTO `hvzsmallevents`(`evntType`, `evtDate`, `usrSubjctId`, `relevantId`) VALUES ($SmallTagType, '$date', $UserTaggedId, $LastTagID)";
mysqli_query($DBCon, $CreateMiniEventQuery);
// If we want to associate a tag with a mission:
if ($RelevantMissionID != 0)
{
$CreateNewTagAssocQuery = "INSERT INTO `hvzmissionstagassoc`(`tagid`, `missionid`) VALUES ($LastTagID,$RelevantMissionID)";
mysqli_query($DBCon, $CreateNewTagAssocQuery);
}
// Change all active Arsenal Entries for the tagged player to state 2 (Zombiefied, Must Return)
$RequestArsenalReturn = "UPDATE `hvzarsenalclaims` SET `claimstate`= 2,`claimdate`='$date' WHERE `claimerid` = $UserTaggedId AND `claimstate` = 1";
mysqli_query($DBCon, $RequestArsenalReturn);
// Kill all non-active Queries: Zombies need no guns
$RemoveNonReturnQueries = "DELETE FROM `hvzarsenalclaims` WHERE `claimerid` = $UserTaggedId AND NOT `claimstate` = 2";
mysqli_query($DBCon, $RemoveNonReturnQueries);
}
// Oh, we tagged an NPC. Good on you.
else if ($UserTaggedId == 0)
{
// Create a new small event for tagger.
$CreateMiniEventQuery = "INSERT INTO `hvzsmallevents`(`evntType`, `evtDate`, `usrSubjctId`, `relevantId`) VALUES (7, '$date', $MyId, $UserGame)";
mysqli_query($DBCon, $CreateMiniEventQuery);
}
// Remove the victim's tag, so it can't be reused.
$DeleteVictimTag = "DELETE FROM `hvztagnums` WHERE `tagid` = $TagToRemoveId";
mysqli_query($DBCon, $DeleteVictimTag);
// Go back to game stats to see the fruit of our labor
header("Location: gamestats.php");
die();
?> | {
"content_hash": "d3ac689cd3cecd464da46841ba61011e",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 167,
"avg_line_length": 30.4147465437788,
"alnum_prop": 0.6683333333333333,
"repo_name": "dmitbor/althvz",
"id": "61b37d5c5592377699d5fd0e8ab3beb286102730",
"size": "6600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Server-Side/tagregistrar.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "59032"
},
{
"name": "JavaScript",
"bytes": "19478"
},
{
"name": "PHP",
"bytes": "282526"
}
],
"symlink_target": ""
} |
using System.Data.Entity.ModelConfiguration;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace NOF2.Demo.Model
{
public static partial class Mapper
{
public static void Map(this EntityTypeBuilder<SalesReason> builder)
{
builder.HasKey(t => t.SalesReasonID);
// Properties
builder.Property(t => t.mappedName)
.IsRequired()
.HasMaxLength(50);
builder.Property(t => t.mappedReasonType)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
builder.ToTable("SalesReason", "Sales");
builder.Property(t => t.SalesReasonID).HasColumnName("SalesReasonID");
builder.Property(t => t.mappedName).HasColumnName("Name");
builder.Property(t => t.mappedReasonType).HasColumnName("ReasonType");
builder.Property(t => t.mappedModifiedDate).HasColumnName("ModifiedDate").IsConcurrencyToken(false);
}
}
}
| {
"content_hash": "e87b2a8f2d9b1a66183645327c2814e2",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 112,
"avg_line_length": 36,
"alnum_prop": 0.6157407407407407,
"repo_name": "NakedObjectsGroup/NakedObjectsFramework",
"id": "fb30675d550d6f4539a2f07cc4a6f10c2650f6a2",
"size": "1080",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Test/NOF2.Demo.Database/Mapping/SalesReasonMap.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3010"
},
{
"name": "C#",
"bytes": "17252161"
},
{
"name": "CSS",
"bytes": "87105"
},
{
"name": "F#",
"bytes": "2080309"
},
{
"name": "HTML",
"bytes": "77491"
},
{
"name": "JavaScript",
"bytes": "7967"
},
{
"name": "TSQL",
"bytes": "5089"
},
{
"name": "TypeScript",
"bytes": "683807"
},
{
"name": "Vim Snippet",
"bytes": "41860"
},
{
"name": "Visual Basic .NET",
"bytes": "288499"
}
],
"symlink_target": ""
} |
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author Matthew Saltz
* @version 1.3
* @date Thu Jul 25 11:28:31 EDT 2013
* @see LICENSE (MIT style license file).
*/
package scalation.graphalytics
import scala.collection.immutable.{Set => SET}
import scala.collection.mutable.Queue
import scala.math.pow
import scala.util.Random
import LabelType.{TLabel, toTLabel}
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphGen` object is used to build random graph with various
* characteristics.
*/
object GraphGen
{
/** Random number generator
*/
private val rand = new Random
//------------------------------------------------------------------------
// Methods generating random graphs where the number of outgoing edges (the degree)
// for a vertex is uniformly distributed.
//------------------------------------------------------------------------
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Generate a random graph with the specified size (number of vertices),
* average degree and labels evenly distributed across vertices from 0 to
* 'nLabels - 1'. Not necessarily a connected graph.
* @param size the number of vertices to generate
* @param nLabels the number of labels (distributed uniformly)
* @param avDegree the average degree
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genRandomGraph (size: Int, nLabels: Int, avDegree: Int, inverse: Boolean = false,
name: String = "g"): Graph =
{
val ch = (0 until size).map { node =>
val degree = rand.nextInt (avDegree * 2 + 1)
(0 until degree).map ( _ => rand.nextInt (size) ).toSet.filter (_ != node)
}.toArray
val label = randDistLabels (size, nLabels)
new Graph (ch, label, inverse, name)
} // genRandomGraph
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Generate a random connected graph by using 'genRandomGraph' and
* checking whether it is connected.
* @param size the number of vertices to generate
* @param nLabels the number of labels (distributed uniformly)
* @param avDegree the average degree
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genRandomConnectedGraph (size: Int, nLabels: Int, avDegree: Int, inverse: Boolean = false,
name: String = "g"): Graph =
{
var g: Graph = null
do g = genRandomGraph (size, nLabels, avDegree, inverse, name) while (! g.isConnected)
g
} // genRandomConnectedGraph
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Generate a random graph with labels distributed based on a power law
* distribution (currently with the magic number 2.1 for the power law exponent).
* @param size the number of vertices to generate
* @param nLabels the number of labels (distributed according to power law)
* @param avDegree the average degree
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genRandomGraph_PowLabels (size: Int, nLabels: Int, avDegree: Int, inverse: Boolean = false,
name: String = "g"): Graph =
{
val ch = Array.ofDim [SET [Int]] (size).map ( node => {
val degree = rand.nextInt (avDegree * 2 + 1)
(0 until degree).map ( _ => rand.nextInt (size) ).toSet
})
// 2.1 is used in WWW graph pg 72 of m&m graph data
val label = powDistLabels (size, nLabels, 2.1)
new Graph (ch, label, inverse, name)
} // genRandomGraph_PowLabels
//------------------------------------------------------------------------
// Methods generating random graphs where the number of outgoing edges (the degree)
// for a vertex follows a power law distribution.
//------------------------------------------------------------------------
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Generate a graph with power law degree distribution with exponent 'distPow'
* and uniformly distributed labels.
* @param size the number of vertices
* @param nLabels the number of labels (distributed uniformly)
* @param maxDegree the maximum allowed degree for any vertex
* @param distPow the power/exponent
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genPowerLawGraph (size: Int, nLabels: Int, maxDegree: Int, distPow: Double,
inverse: Boolean = false, name: String = "g"): Graph =
{
val ch = (0 until size).map { node =>
val degree = powInt (0, maxDegree, distPow)
(0 until degree).map ( _ => rand.nextInt (size)).toSet.filter (_ != node)
}.toArray
val label = randDistLabels (size, nLabels)
new Graph (ch, label, inverse, name)
} // genPowerLawGraph
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Generate a graph with power law degree distribution with exponent 'distPow'
* and power law distributed labels.
* @param size the number of vertices
* @param nLabels the number of labels (distributed according to power law)
* @param maxDegree the maximum allowed degree for any vertex
* @param distPow the power/exponent
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genPowerLawGraph_PowLabels (size: Int, nLabels: Int, maxDegree: Int, distPow: Double,
inverse: Boolean = false, name: String = "g"): Graph =
{
val ch = Array.ofDim [SET [Int]] (size).map ( node => {
val degree = powInt (0, maxDegree, distPow)
(0 until degree).map ( _ => rand.nextInt(size) ).toSet
})
val label = powDistLabels (size, nLabels, distPow)
new Graph (ch, label, inverse, name)
} // genPowerLawGraph_PowLabels
//------------------------------------------------------------------------
// Methods for generating/extracting query graphs from data graphs.
// Ensures that matches will exist.
//------------------------------------------------------------------------
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Given a graph 'g', perform a breadth first search starting at a random vertex
* until the breadth first tree contains 'size' vertices. At each junction,
* it chooses a random number of children to traverse, with that random
* number averaging to 'avDegree'.
* @param size the number of vertices to extract
* @param avDegree the average out degree
* @param g the data graph to extract from
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def genBFSQuery (size: Int, avDegree: Int, g: Graph, inverse: Boolean = false,
name: String = "g"): Graph =
{
val maxRestarts = 5000
var nRestarts = 0
var cycle = false
var nodes = Set [Int] ()
var adjMap: Map [Int, SET [Int]] = null
while (nodes.size < size && nRestarts < maxRestarts) {
if (nRestarts % 100 == 0) println ("restarting " + nRestarts)
adjMap = Map [Int, SET [Int]] ()
nodes = Set [Int] ()
val q = Queue [Int] ()
val start = rand.nextInt (g.size) // randomly pick a start node in ch
q.enqueue (start)
nodes += start
while (! q.isEmpty && nodes.size < size) {
var adjs = Set [Int] ()
val newNode = q.dequeue
val newNodeChildren = g.ch (newNode)
if (! newNodeChildren.isEmpty) {
val nncArr = newNodeChildren.toArray
for (i <- 0 until rand.nextInt (avDegree * 2 + 1) if nodes.size < size) {
val newChild = nncArr (rand.nextInt (newNodeChildren.size))
if (!nodes.contains(newChild)) { nodes += newChild; q.enqueue (newChild) }
else cycle = true
if (newChild != newNode) adjs += newChild
} // for
adjMap += (newNode -> (adjMap.getOrElse (newNode, Set [Int] ()) ++ adjs))
} // if
} // while
if(nodes.size < size) nRestarts += 1
} // while
if (nRestarts == maxRestarts) { println ("genBFSQuery: could not find a good query"); return null }
// gives the nodes new ids
var newLabelMap = Map [Int, Int] ()
var c = 0
for (x <- nodes) { newLabelMap += (x -> c); c += 1 }
val newToOldLabels = Array.ofDim [Int] (size)
newLabelMap.foreach { case (oldL, newL) => newToOldLabels (newL) = oldL }
val ch = Array.ofDim [SET [Int]] (size).map (x => Set [Int] ())
for ((node, children) <- adjMap) ch (newLabelMap (node)) = children.map (x => newLabelMap (x))
val label = newToOldLabels.map (x => g.label(x)).toArray
if (cycle) println ("query has a cycle")
new Graph (ch, label, inverse, name)
} // genBFSQuery
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Extract a subgraph of 'size' vertices from graph 'g' by performing a
* breadth-first search from a random vertex.
* @param size the number of vertices to extract
* @param g the data graph to extract from
* @param inverse whether to create inverse adjacency (parents)
* @param name the name of the graph
*/
def extractSubgraph (size: Int, g: Graph, inverse: Boolean = false, name: String = "g"): Graph =
{
val maxRestarts = 5000
var nRestarts = 0
var adjMap: Map [Int, SET [Int]] = null
var nodes: SET [Int] = null
while (nodes.size < size && nRestarts < maxRestarts) {
if (nRestarts % 100 == 0) println ("restarting " + nRestarts)
adjMap = Map [Int, SET [Int]] ()
nodes = Set [Int] ()
val q = Queue [Int] ()
val start = rand.nextInt (g.size) // randomly pick a start node in ch
println ("start node: " + start)
q.enqueue (start)
nodes += start
while (! q.isEmpty && nodes.size < size) {
var adjs = Set [Int] ()
val newNode = q.dequeue
val newNodeChildren = g.ch (newNode)
if (! newNodeChildren.isEmpty) {
for (newChild <- newNodeChildren if nodes.size < size) {
if (! nodes.contains (newChild)) { nodes += newChild; q.enqueue (newChild) }
} // for
} // if
} // while
for (n <- nodes) { val adjs = g.ch(n) & nodes; adjMap += (n -> adjs ) }
if (nodes.size < size) {
nRestarts += 1
println ("nodes.size only " + nodes.size)
} // if
} // while
if (nRestarts == maxRestarts) { println ("extractSubgraph: could not find a good query"); return null }
// gives the nodes new ids
var newLabelMap = Map[Int, Int]()
var c = 0
for (x <- nodes) { newLabelMap += (x -> c); c += 1 }
val newToOldLabels = Array.ofDim [Int] (size)
newLabelMap.foreach { case (oldL, newL) => newToOldLabels (newL) = oldL }
val ch = Array.ofDim [SET [Int]] (size).map (x => Set [Int] ())
for ((node, children) <- adjMap) ch (newLabelMap(node)) = children.map (x => newLabelMap (x))
val label = newToOldLabels.map (x => g.label(x)).toArray
new Graph (ch, label, inverse, name)
} // extractSubgraph
//------------------------------------------------------------------------
// Private helper methods.
//------------------------------------------------------------------------
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Return an array with labels distributed between 0 and 'nLabels - 1'
* based on a uniform distribution.
* @param size the number of vertices
* @param nLabels the number of labels
*/
private def randDistLabels (size: Int, nLabels: Int): Array [TLabel] =
{
Array.ofDim [TLabel] (size).map ( x => toTLabel (rand.nextInt (nLabels).toString))
} // randDistLabels
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Return an array with labels distributed between 0 and 'nLabels - 1'
* based on a power law distribution.
* @param size the number of vertices
* @param nLabels the number of labels
* @param pow the power/exponent
*/
private def powDistLabels (size: Int, nLabels: Int, pow: Double): Array [TLabel] =
{
Array.ofDim [TLabel] (size).map ( x => toTLabel (powInt (0, nLabels, pow).toString))
} // powDistLabels
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Return an array with labels distributed between 0 and 'nLabels - 1'
* based on a Gaussian/Normal distribution.
* @param size the number of vertices
* @param nLabels the number of labels
*/
private def gaussianDistLabels (size: Int, nLabels: Int): Array [Int] =
{
Array.ofDim [Int] (size).map ( x => gaussInt (nLabels / 2.0) )
} // gaussianDistLabels
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Return a random integer between min and max with a frequency determined
* by a power law distribution.
* @param min the minimum value
* @param max the maximum value
* @param distPow the power distribution
*/
private def powInt (min: Int, max: Int, distPow: Double): Int =
{
val exp = distPow + 1.0
max - 1 - pow (( (pow (max, exp) - pow (min, exp)) * rand.nextDouble + pow (min, exp) ),
(1.0 / exp)).toInt
} // powInt
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Return an integer with a probability based on a Gaussian distribution
* FIX: may need to truncate with
* 'math.min(math.max((rand.nextGaussian()*d+d).toInt, 0), d*2).toInt
* @param d the distance/rescaling parameter
*/
private def gaussInt (d: Double) = (rand.nextGaussian () * 2.0 * d).toInt
} // GraphGen class
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphGenTest` object is used to test the `GraphGen` class for building
* random graphs where a vertex's degree is uniformly distributed.
*/
object GraphGenTest extends App
{
import GraphGen._
println ("GraphGenTest: test genRandomGraph")
(0 until 10).foreach { _ =>
val g = genRandomGraph (4, 100, 1)
g.printG ()
println ("CONNECTED? " + g.isConnected)
} // foreach
println ("GraphGenTest: test genRandomConnectedGraph")
(0 until 10).foreach { _ =>
val g = genRandomConnectedGraph (4, 100, 1)
g.printG ()
} // foreach
println ("GraphGenTest: test genRandomGraph_PowLabels")
val g1 = genRandomGraph_PowLabels (200, 50, 2)
g1.printG ()
println (s"g1.labelMap = ${g1.labelMap}")
} // GraphGenTest
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphGenTest2` object is used to test the `GraphGen` class for building
* power law graphs.
*/
object GraphGenTest2 extends App
{
import GraphGen._
println ("GraphGenTest2: test genPowerLawGraph")
val g2 = genPowerLawGraph (50, 10, 10, 2.1)
g2.printG ()
g2.ch.sortBy (_.size).foreach { println(_) }
println ("GraphGenTest2: test genPowerLawGraph_PowLabels")
val g3 = genPowerLawGraph_PowLabels (50, 10, 10, 2.1)
g3.printG ()
g3.ch.sortBy (_.size).foreach { println(_) }
println (s"g3.labelMap = ${g3.labelMap}")
} // GraphGenTest2
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphGenTest3` object is used to test the `GraphGen` class for
* extracting query graphs from data graphs.
*/
object GraphGenTest3 extends App
{
import GraphGen._
var g = genRandomGraph (1000000, 10, 16)
println ("done generating data graph")
println ("g.size: " + g.size)
println ("g.nEdges: " + g.nEdges)
println ("GraphGenTest3: test genBFSQuery")
(2 until 10).foreach { i =>
var q = genBFSQuery (25, 3, g)
q.printG ()
println (q.size)
println (q.nEdges)
println (q.nEdges / q.size.toDouble)
} // foreach
println ("done")
} // GraphGenTest3
| {
"content_hash": "d54388ce5149e99408caf145749301f5",
"timestamp": "",
"source": "github",
"line_count": 400,
"max_line_length": 111,
"avg_line_length": 43.6175,
"alnum_prop": 0.5195162492118989,
"repo_name": "scalation/fda",
"id": "d4d2531032809323050066eb2c20b6c281dc658c",
"size": "17447",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "scalation_1.3/scalation_modeling/src/main/scala/scalation/graphalytics/GraphGen.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "129"
},
{
"name": "CSS",
"bytes": "438"
},
{
"name": "HTML",
"bytes": "140526"
},
{
"name": "JavaScript",
"bytes": "40"
},
{
"name": "Scala",
"bytes": "19048105"
},
{
"name": "Shell",
"bytes": "64873"
}
],
"symlink_target": ""
} |
package com.cyc.webservice.client;
//// Internal Imports
//// External Imports
/**
* <P>WSRequestParams is designed to...
*
* <P>Copyright (c) 2010 Cycorp, Inc. All rights reserved.
* <BR>This software is the proprietary information of Cycorp, Inc.
* <P>Use is subject to license terms.
*
* Created on : Apr 1, 2010, 8:03:55 PM
* Author : tbrussea
* @version $Id: WSRequestParams.java 130517 2010-04-02 01:42:40Z tbrussea $
*/
public class WSRequestParams {
//// Constructors
/** Creates a new instance of WSRequestParams. */
public WSRequestParams(Object extraData, String requestType, Object... params) {
if ((requestType == null) || (params == null)) {
throw new IllegalArgumentException();
}
this.requestType = requestType;
this.params = params;
this.extraData = extraData;
}
//// Public Area
public String getRequestType() {
return requestType;
}
public Object[] getParams() {
return params;
}
public Object getExtraData() {
return extraData;
}
@Override
public String toString() {
return "";
}
@Override
public int hashCode() {
int code = (extraData == null) ? 0 : 0xFFFFFFFF;
code |= requestType.hashCode();
for (Object param : params) {
code |= (param == null) ? 0 : param.hashCode();
}
return code;
}
@Override
public boolean equals(Object o) {
if (o == null) { // fast fail
return false;
}
if (o == this) { // fast success
return true;
}
if (!(o instanceof WSRequestParams)) {
return false;
}
WSRequestParams req = (WSRequestParams) o;
if (extraData != req.extraData) {
if ((extraData == null) || (!extraData.equals(req.extraData))) {
return false;
}
}
if (!requestType.equals(req.requestType)) {
return false;
}
int i = 0;
for (Object param : params) {
Object otherParam = req.params[i++];
if (param != otherParam) {
if ((param == null) || (!param.equals(otherParam))) {
return false;
}
}
}
return true;
}
//// Protected Area
//// Private Area
//// Internal Rep
private String requestType;
private Object[] params;
private Object extraData;
//// Main
}
| {
"content_hash": "ced6f98c7cb6715b2430a6f6eaba1cce",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 82,
"avg_line_length": 21.798076923076923,
"alnum_prop": 0.6021173356859285,
"repo_name": "cycorp/common-libraries",
"id": "083bf717ab8762b61183fbf21c35826a3273201f",
"size": "2498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "restful-ws-client/src/main/java/com/cyc/webservice/client/WSRequestParams.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "41152"
}
],
"symlink_target": ""
} |
class VerificateDecorator < Draper::Decorator
delegate_all
def posting_date
return l(object.posting_date, format: "%Y-%m-%d") if object.posting_date
""
end
def parent
return object.vat_period.name if object.vat_period
return object.wage_period_wage.name if object.wage_period_wage
return object.wage_period_report.name if object.wage_period_report
""
end
def total_debit
number_with_precision(object.total_debit, precision: 2)
end
def total_credit
number_with_precision(object.total_credit, precision: 2)
end
def pretty_state
l = 'default'
case object.state
when 'preliminary'
l = 'info'
str = h.t(:preliminary)
when 'final'
l = 'success'
str = h.t(:final)
end
h.labelify(str, l)
end
end
| {
"content_hash": "6a5fce1f4db0870c5bf0f870a40f4417",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 76,
"avg_line_length": 25.125,
"alnum_prop": 0.6554726368159204,
"repo_name": "dulvie/kinna",
"id": "f26f649c011a8779a3ff41286b6b93789758cbd3",
"size": "804",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/decorators/verificate_decorator.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5798"
},
{
"name": "JavaScript",
"bytes": "15115"
},
{
"name": "Ruby",
"bytes": "301120"
},
{
"name": "Shell",
"bytes": "365"
}
],
"symlink_target": ""
} |
namespace sf { class RenderTarget; }
namespace Game
{
class Statistics : public Kunlaboro::Component
{
public:
Statistics();
void addedToEntity();
void newFrame(const Util::Timespan& dt);
void drawUI(sf::RenderTarget& target);
private:
std::list<int> mFramerates;
Util::Timespan mCurTime;
int mCurFrames;
};
}
| {
"content_hash": "b900156bbb39e0c3b200fafdb16ae7a9",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 47,
"avg_line_length": 14.695652173913043,
"alnum_prop": 0.6952662721893491,
"repo_name": "ace13/LD32",
"id": "eb4a0360df0aa67f574767e4fd7b164f573564a3",
"size": "434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Sources/Game/Statistics.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "5032"
},
{
"name": "C",
"bytes": "712"
},
{
"name": "C++",
"bytes": "438701"
},
{
"name": "CMake",
"bytes": "24994"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using RefactorThis.GraphDiff;
using DertInfo.WEB.Models.Contexts;
using System.ComponentModel.DataAnnotations.Schema;
using DertInfo.WEB.Models.Base;
namespace DertInfo.WEB.Models
{
public class MemberAttendance : DertObjectBase_Trackable_Accessible
{
private DertInfoContext db = new DertInfoContext();
//Primary Key
[Key]
public int Id { get; set; }
//Foreign Keys
public int RegistrationId { get; set; }
public int GroupMemberId { get; set; }
public int AttendanceClassificationId { get; set; }
//Objects
public virtual Registration Registration { get; set; }
public virtual GroupMember GroupMember { get; set; }
public virtual AttendanceClassification AttendanceClassification { get; set; }
//Properties
//Status
//public string AccessToken { get; set; }
//public DateTime DateCreated { get; set; }
//public DateTime DateModified { get; set; }
//public string CreatedBy { get; set; }
//public string ModifiedBy { get; set; }
//public bool IsDeleted { get; set; }
}
} | {
"content_hash": "6e5f1540c0a46ed6ff1ef40998ef1f2f",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 86,
"avg_line_length": 29.790697674418606,
"alnum_prop": 0.663544106167057,
"repo_name": "dertinfo-david/dertinfo-web",
"id": "528e925e0509b7391d8e2443239b395f8a376c7e",
"size": "1283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Models/MemberAttendance.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "103"
},
{
"name": "C#",
"bytes": "2371440"
},
{
"name": "CSS",
"bytes": "335396"
},
{
"name": "HTML",
"bytes": "26375"
},
{
"name": "JavaScript",
"bytes": "1406026"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<?dlps id="AndRuss"?>
<?dlps page-images="none" figure-images="no"?>
<?dlps transcription="other"?>
<!DOCTYPE TEI.2 SYSTEM "http://text.lib.virginia.edu/dtd/tei/tei-p4/tei2.dtd" [
<!ENTITY % POSTKB "INCLUDE">
<!ENTITY % TEI.extensions.ent SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.ent">
<!ENTITY % TEI.extensions.dtd SYSTEM "http://text.lib.virginia.edu/dtd/tei/uva-dl-tei/uva-dl-tei.dtd">
<!ENTITY % ISOnum SYSTEM "http://text.lib.virginia.edu/charent/iso-num.ent"> %ISOnum;
<!ENTITY % ISOlat1 SYSTEM "http://text.lib.virginia.edu/charent/iso-lat1.ent"> %ISOlat1;
<!ENTITY % ISOpub SYSTEM "http://text.lib.virginia.edu/charent/iso-pub.ent"> %ISOpub;
]>
<TEI.2 id="AndRuss">
<teiHeader type="migrated" creator="Etext">
<fileDesc>
<titleStmt>
<title type="main">To the Russian Soldier</title>
<title type="sort">to the russian soldier</title>
<author>Andreyev, Leonid</author>
<respStmt>
<resp>Creation of machine-readable version:</resp>
<name>Judy Boss</name>
<resp>Creation of digital images:</resp>
<name/>
<resp>Conversion to TEI.2-conformant markup:</resp>
<name>University of Virginia Library Electronic Text Center.</name>
</respStmt>
</titleStmt>
<extent>ca. <num type="kilobytes">10</num> kilobytes</extent>
<publicationStmt>
<publisher>University of Virginia Library</publisher>
<pubPlace>Charlottesville, Virginia</pubPlace>
<idno type="ETC">AndRuss</idno>
<date value="1998">1998</date>
<availability status="public">
<p n="copyright">Copyright © 1998 by the Rector and Visitors of the University of Virginia</p>
<p n="access">Publicly accessible</p>
</availability>
<idno type="uva-pid">uva-lib:475673</idno>
</publicationStmt>
<seriesStmt>
<title>University of Virginia Library, Text collection</title>
<idno type="uva-set">UVA-LIB-Text</idno>
</seriesStmt>
<sourceDesc>
<biblFull>
<titleStmt>
<title type="main">To the Russian Soldier</title>
<title level="j">The Yale Review, Vol. VII, No. 2 (Jan. 1918)</title>
<title type="sort">to the russian soldier</title>
<author>Leonid Andreyev</author>
<respStmt>
<resp>Editor</resp>
<name>Wilbur L. Cross</name>
</respStmt>
</titleStmt>
<extent>pp. 225-228</extent>
<publicationStmt>
<publisher>Yale Publishing Association, Inc.</publisher>
<pubPlace>New Haven, Connecticut</pubPlace>
<date value="1918">1918</date>
<idno type="callNo">Print copy consulted: UVA Library call number AP2 .Y2 v.7 1917-18</idno>
</publicationStmt>
</biblFull>
</sourceDesc>
</fileDesc>
<encodingDesc>
<projectDesc>
<p>Prepared for the University of Virginia Library Electronic Text Center.</p>
</projectDesc>
<editorialDecl>
<p>All unambiguous end-of-line hyphens have been removed, and the trailing part of a word has been joined to the preceding line.</p>
<p>The images exist as archived TIFF images, one or more JPEG versions for general use, and thumbnail GIFs.</p>
<p>Some keywords in the header are a local Electronic Text Center scheme to aid in establishing analytical groupings.</p>
</editorialDecl>
</encodingDesc>
<profileDesc>
<creation>
<date value="1918">1918</date>
</creation>
<langUsage>
<language id="eng" usage="main">English</language>
</langUsage>
<textClass>
<keywords>
<term>nonfiction</term>
<term>prose</term>
<term>masculine</term>
</keywords>
</textClass>
</profileDesc>
<revisionDesc>
<change>
<date value="1998-05">May, 1998</date>
<respStmt>
<resp>corrector</resp>
<name>Carol Osborne, Electronic Text Center</name>
</respStmt>
<item>Added TEI tags and header</item>
</change>
<change>
<date value="2005-06">June 2005</date>
<respStmt>
<resp>corrector</resp>
<name>John Ivor Carlson</name>
</respStmt>
<item>Converted sgml to xml.</item>
</change>
<change>
<date value="2007-09">September 2007</date>
<respStmt>
<resp>Migration</resp>
<name>Ethan Gruber, University of Virginia Library</name>
</respStmt>
<item>Converted XML markup from TEI Lite to uva-dl-tei (TEI P4 with local customizations).</item>
</change>
<change>
<date value="2008-01">January 2008</date>
<respStmt>
<resp>Migration</resp>
<name>Greg Murray, University of Virginia Library</name>
</respStmt>
<item>Programmatically updated TEI header markup (but not header content) for minimal compliance with current QA requirements.</item>
</change>
</revisionDesc>
</teiHeader>
<text id="d1">
<body id="d2">
<div1 type="article" id="d3">
<pb n="225"/>
<head>TO THE RUSSIAN SOLDIER<lb/>
By LEONID ANDRÉEV</head>
<p>SOLDIER, what hast thou been under Nicholas the Secone?
Thou hast been a slave of the autocrat. Conscience,
honor, love for the people, were beaten out of thee in
merciless training by whip and stick.
</p><p>"Kill thy father and thy mother if they raise their hands
against me," commanded the autocrat, — and thou becamest
a parricide.
</p><p>"Kill thy brother and thy sister, thy dearest friend and
everyone who raises a hand against me," commanded the
autocrat, — and thou didst kill thy brother and thy dearest
friend, and becamest like Cain, shedding the blood of
thy kin.
</p><p>When the gray coats appeared in the streets and the rifles
and bayonets glittered — we knew what that meant: it was
death stalking! It meant death to those innocent and
hungry ones who thirsted for brighter life and raised their
voices bravely against the tyrant. It meant death, destruction,
peril, tears, and horror. Thou wast terrible, Soldier!
</p><p>But thou wast brave in the field, Russian Soldier. . . .
Thou wast a martyr, but thou wast never a traitor, nor a
coward, Soldier!
</p><p>The Russian people loved thee secretly for this and waited
for thy awakening. . . . They called to thee: "Come to us,
<pb n="226"/>
beloved brother! Come to thy people. The people are
waiting for thee!"
</p><p>Soldier, what hast thou been in the days of the Revolution?
</p><p>Thou hast been our love, our happiness, our pride. We
did not know as yet who thou wast. We were still in dread
of the gray coats, we still mistrusted the dashing cossacks.
And dost thou remember, Soldier, how the heart of the
people leaped when the first blow of the cossack's sabre fell
not on the head of his brother but on that of the
policeman-executioner? Dost thou remember it?
</p><p>But still we were not able to believe. Already our hearts
were overcome with joy, happiness took our breath away,
but still we did not believe. How is it possible to believe all
at once in freedom?
</p><p>Yet the soldiers are bringing it with them! They are
coming, stalwart, brave, beautiful, in their armed power.
They are coming to give their life for freedom. As yet they
themselves do not know whether they are all awakened. The
Tsar's hirelings shoot at them from the roofs and from
behind street corners. The soldiers expect only death, yet
they are coming, stalwart, brave, beautiful!
</p><p>Then we believed them. The throne of the Romanovs
cracked with a noise heard throughout the world. For the
first time in our life soldiers' bullets sang a new song — not
the song of death, of shame, and of degradation, but the
wonderful song of freedom and of joy. . . .
</p><p>And what hast thou become now, Soldier?
</p><p>When cursing, drunken, thou didst come tearing down
peaceful streets in thy automobiles, threatening women and
children with guns, bragging, debauching, swearing the
basest of oaths — didst thou hear the answer of the people?
"Be accursed! Be accursed!" Thou didst shoot in mad
frenzy, and the people yelled fearlessly to thee: "Be
accursed!"
<pb n="227"/>
</p><p>Scoundrel! With quick-firing guns didst thou threaten;
yet invalids, old men, and women grabbed at thy rifle with
their bare hands and tore it away from thee. And thou
didst give it away, overcome with shame, helpless, sweating,
ugly.
</p><p>Soldier! How many didst thou kill in those days? How
many orphans hast thou made? How many bereaved
mothers hast thou left inconsolable? Dost thou hear the
words that their lips whisper? The lips from which thou
hast banished forever the smile of happiness? — "Murderer,
Murderer!"
</p><p>But what of mothers? What of orphans? A moment
came unforeseen and still more terrible. Thou hast betrayed
Russia. Thou hast thrown thy native land that nourished
thee under the feet of the enemy, thou Soldier, our sole
defense!
</p><p>Everything is entrusted to thee: the life and welfare of
Russia; our fields and forests; our peaceful rivers; our
villages and cities; our temples and those who are praying
in them.
</p><p>And all this thou hast betrayed, Soldier! — the quiet fields,
and the young, buoyant liberty. Behind thy back grain
was ripening in the fields — Russia's sacred treasury; now
the Germans will reap it. Under thy protection the people
were working in their villages; now they are running along
all the highways, leaving dead in their wake. Children and
old men are weeping — they have no roof over their heads,
no home, only death staring into their faces.
</p><p>Ah! how thou didst run from the enemy, Russian Soldier!
Never before has the world seen such a rout, such a mob of
traitors. It knew the one Judas, while here were tens of
thousands of Judases running past each other, galloping,
throwing down rifles, quarrelling, and still boasting of their
"meetings." What are they hurrying for? They hurry to
betray their native land. They do not even wait for the
<pb n="228"/>
Germans to shoot, so great is their haste to betray Russia,
so ready are they to deliver her almost by force into the hands
of the astounded enemy.
</p><p>And what hast thou done to thy officers, Soldier? See,
what piles of them lie in the fields appealing to the all-merciful
and all-forgiving God with their still, sightless eyes!
They called thee — thou didst not obey. They went alone to
their death — and they died. They died, Soldier!
</p><p>And what hast thou done to thy comrades? Traitor!
Dost thou see their bodies? Dost thou see the ditches where
careless German hands have thrown them? It is thou who
didst kill them!
</p><p>But look ahead of thee, Soldier! Dost thou see that terrible
structure that is being erected in Russia?
</p><p>It is the scaffold.
</p><p>And for whom is it? For thee, Soldier! For thee, traitor
and coward, who hast betrayed Russia and her liberty. Thou
seest, but thou dost not understand as yet. Thou dost not
understand our sorrow.
</p><p>Was Russia not happy in having destroyed the scaffold
as it seemed forever, and in giving its accursed memory to
oblivion. But now it grows again, unwelcome, sinister, evil,
like the shadows of night.
</p><p>Thou hast torn the body of Russia. Now thou desirest
to tear her heart and soul — thou, Soldier.
</p><p>Thou, Soldier, whom we loved and whom we still love.
</p><p>Arise! — Look at thy country which is calling in distress.
</p><p>Awake! — If cruel fate has no laurels of victory in store
for thee, put the crown of thorns on thy head. Through it
thou shalt find expiation, through it thou shalt regain our
love.
</p><p>Russia is dying, Russia is calling to thee:
</p><p>"Arise, dear Soldier!"</p>
</div1>
</body>
</text>
</TEI.2>
| {
"content_hash": "59ebae0cf5ee6a7ec6b026c2a912d1e3",
"timestamp": "",
"source": "github",
"line_count": 279,
"max_line_length": 133,
"avg_line_length": 39.96774193548387,
"alnum_prop": 0.7488117657609183,
"repo_name": "JohannGillium/modern_english_ed",
"id": "9212ed39e9fd708d7dd014fdd388b6782c8cc013",
"size": "11151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XML/AndRuss.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "19931"
},
{
"name": "HTML",
"bytes": "8251"
},
{
"name": "JavaScript",
"bytes": "1711"
},
{
"name": "Python",
"bytes": "3438"
},
{
"name": "Ruby",
"bytes": "75"
},
{
"name": "XSLT",
"bytes": "6581"
}
],
"symlink_target": ""
} |
package org.webrtc;
import android.support.annotation.Nullable;
import org.webrtc.MediaStreamTrack;
/** Java wrapper for a C++ RtpReceiverInterface. */
public class RtpReceiver {
/** Java wrapper for a C++ RtpReceiverObserverInterface*/
public static interface Observer {
// Called when the first audio or video packet is received.
@CalledByNative("Observer")
public void onFirstPacketReceived(MediaStreamTrack.MediaType media_type);
}
private long nativeRtpReceiver;
private long nativeObserver;
@Nullable private MediaStreamTrack cachedTrack;
@CalledByNative
public RtpReceiver(long nativeRtpReceiver) {
this.nativeRtpReceiver = nativeRtpReceiver;
long nativeTrack = nativeGetTrack(nativeRtpReceiver);
cachedTrack = MediaStreamTrack.createMediaStreamTrack(nativeTrack);
}
@Nullable
public MediaStreamTrack track() {
return cachedTrack;
}
public RtpParameters getParameters() {
checkRtpReceiverExists();
return nativeGetParameters(nativeRtpReceiver);
}
public String id() {
checkRtpReceiverExists();
return nativeGetId(nativeRtpReceiver);
}
@CalledByNative
public void dispose() {
checkRtpReceiverExists();
cachedTrack.dispose();
if (nativeObserver != 0) {
nativeUnsetObserver(nativeRtpReceiver, nativeObserver);
nativeObserver = 0;
}
JniCommon.nativeReleaseRef(nativeRtpReceiver);
nativeRtpReceiver = 0;
}
public void SetObserver(Observer observer) {
checkRtpReceiverExists();
// Unset the existing one before setting a new one.
if (nativeObserver != 0) {
nativeUnsetObserver(nativeRtpReceiver, nativeObserver);
}
nativeObserver = nativeSetObserver(nativeRtpReceiver, observer);
}
public void setFrameDecryptor(FrameDecryptor frameDecryptor) {
checkRtpReceiverExists();
nativeSetFrameDecryptor(nativeRtpReceiver, frameDecryptor.getNativeFrameDecryptor());
}
private void checkRtpReceiverExists() {
if (nativeRtpReceiver == 0) {
throw new IllegalStateException("RtpReceiver has been disposed.");
}
}
// This should increment the reference count of the track.
// Will be released in dispose().
private static native long nativeGetTrack(long rtpReceiver);
private static native RtpParameters nativeGetParameters(long rtpReceiver);
private static native String nativeGetId(long rtpReceiver);
private static native long nativeSetObserver(long rtpReceiver, Observer observer);
private static native void nativeUnsetObserver(long rtpReceiver, long nativeObserver);
private static native void nativeSetFrameDecryptor(long rtpReceiver, long nativeFrameDecryptor);
};
| {
"content_hash": "929b44d566e1dd918f25515d67c8e093",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 98,
"avg_line_length": 31.773809523809526,
"alnum_prop": 0.7579617834394905,
"repo_name": "endlessm/chromium-browser",
"id": "015d35a6a0e6f7ef621ccf309ed15fa2a54c3479",
"size": "3077",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "third_party/webrtc/sdk/android/api/org/webrtc/RtpReceiver.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
//
// ZKJAddTagToolbar.m
// 百思不得姐
//
// Created by ZKJ on 2017/4/12.
// Copyright © 2017年 ZKJ. All rights reserved.
//
#import "ZKJAddTagToolbar.h"
#import "ZKJAddTagViewController.h"
@interface ZKJAddTagToolbar ()
/** 顶部的view */
@property (weak, nonatomic) IBOutlet UIView *topView;
/** 添加按钮 */
@property (nonatomic, strong) UIButton *button;
/** 存放所有标签label的数组 */
@property (nonatomic, strong) NSMutableArray *tagLabels;
@end
@implementation ZKJAddTagToolbar
- (NSMutableArray *)tagLabels
{
if (!_tagLabels) {
_tagLabels = [NSMutableArray array];
}
return _tagLabels;
}
- (void)awakeFromNib
{
[super awakeFromNib];
// 添加一个加号按钮
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setImage:[UIImage imageNamed:@"tag_add_icon"] forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
// btn.size = [UIImage imageNamed:@"tag_add_icon"].size;
// btn.size = [btn imageForState:UIControlStateNormal].size;
btn.size = btn.currentImage.size;
btn.x = ZKJTagMargin;
[self addSubview:btn];
self.button = btn;
// 默认就拥有2个标签
[self createTagLabel:@[@"吐槽", @"糗事"]];
}
- (void)btnClick
{
ZKJAddTagViewController *tagVC = [[ZKJAddTagViewController alloc] init];
__weak typeof(self) weakSelf = self;
[tagVC setTagBlock:^(NSArray *tags){
[weakSelf createTagLabel:tags];
}];
tagVC.tags = [self.tagLabels valueForKeyPath:@"text"];
UIViewController *root = [UIApplication sharedApplication].keyWindow.rootViewController;
UINavigationController *nav = (UINavigationController *)root.presentedViewController;
[nav pushViewController:tagVC animated:YES];
}
- (void)layoutSubviews
{
[super layoutSubviews];
for (int i = 0; i < self.tagLabels.count; i++) {
UILabel *label = self.tagLabels[i];
// 设置位置
if (i == 0) {
// 最前面的标签按钮
label.x = 0;
label.y = 0;
} else {
// 其他标签按钮
UILabel *lastLabel = self.tagLabels[i-1];
// 计算当前行左边的宽度
CGFloat leftWidth = CGRectGetMaxX(lastLabel.frame) + ZKJTagMargin;
// 计算当前行右边的宽度
CGFloat rightWidth = self.topView.width - leftWidth;
if (rightWidth >= label.width) {
// 按钮显示在当前行
label.x = leftWidth;
label.y = lastLabel.y;
} else {
// 按钮显示在下一行
label.x = 0;
label.y = CGRectGetMaxY(lastLabel.frame) + ZKJTagMargin;
}
}
// 最后一个标签按钮
UILabel *lastLabel = [self.tagLabels lastObject];
CGFloat leftWidth = CGRectGetMaxX(lastLabel.frame) + ZKJTopicCellMargin;
CGFloat rightWidth = self.topView.width - leftWidth;
// 更新textField的frame
if (rightWidth >= self.button.width) {
self.button.x = leftWidth;
self.button.y = lastLabel.y;
} else {
self.button.x = 0;
self.button.y = CGRectGetMaxY(lastLabel.frame) + ZKJTagMargin;
}
}
// 整体的高度
CGFloat oldH = self.height;
self.height = CGRectGetMaxY(self.button.frame) + 45;
// ZKJLog(@"oldH:%f self.height:%f", oldH, self.height);
self.y -= self.height - oldH;
}
/**
* 创建标签
*/
- (void)createTagLabel:(NSArray *)array
{
[self.tagLabels makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self.tagLabels removeAllObjects];
for (int i = 0; i < array.count; i++) {
UILabel *label = [[UILabel alloc] init];
[self.tagLabels addObject:label];
label.backgroundColor = ZKJTagButtonBGColor;
label.textAlignment = NSTextAlignmentCenter;
label.text = array[i];
label.font = ZKJTagFont;
// 应该要先设置文字和字体后,再进行计算
[label sizeToFit];
label.width += 2 * ZKJTagMargin;
label.height = ZKJTagH;
label.textColor = [UIColor whiteColor];
[self.topView addSubview:label];
}
// 重新布局子控件
[self setNeedsLayout];
}
// a modal 出 b
// [a presentViewController:b animated:YES completion:nil];
// a.presentedViewController -> b
// b.presentingViewController -> a
@end
| {
"content_hash": "e471fa49414e7963e49dff81d416e9da",
"timestamp": "",
"source": "github",
"line_count": 149,
"max_line_length": 97,
"avg_line_length": 28.798657718120804,
"alnum_prop": 0.6122116056863202,
"repo_name": "jungeios111/BaiSiBuDeJie",
"id": "5b2d995d090601c69b3f047981277df1159e63af",
"size": "4576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "百思不得姐/百思不得姐/Classes/Publish-发布/View/ZKJAddTagToolbar.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "54687"
},
{
"name": "Objective-C",
"bytes": "1233065"
},
{
"name": "Objective-C++",
"bytes": "124423"
},
{
"name": "Ruby",
"bytes": "238"
},
{
"name": "Shell",
"bytes": "8735"
}
],
"symlink_target": ""
} |
<?php
namespace Predis\Configuration;
/**
* Manages Predis options with filtering, conversion and lazy initialization of
* values using a mini-DI container approach.
*
* @author Daniele Alessandri <[email protected]>
*/
class Options implements OptionsInterface
{
protected $input;
protected $options;
protected $handlers;
/**
* @param array $options Array of options with their values
*/
public function __construct(array $options = array())
{
$this->input = $options;
$this->options = array();
$this->handlers = $this->getHandlers();
}
/**
* Ensures that the default options are initialized.
*
* @return array
*/
protected function getHandlers()
{
return array(
'cluster' => 'Predis\Configuration\ClusterOption',
'connections' => 'Predis\Configuration\ConnectionFactoryOption',
'exceptions' => 'Predis\Configuration\ExceptionsOption',
'prefix' => 'Predis\Configuration\PrefixOption',
'profile' => 'Predis\Configuration\ProfileOption',
'replication' => 'Predis\Configuration\ReplicationOption',
);
}
/**
* {@inheritdoc}
*/
public function getDefault($option)
{
if (isset($this->handlers[$option])) {
$handler = $this->handlers[$option];
$handler = new $handler();
return $handler->getDefault($this);
}
}
/**
* {@inheritdoc}
*/
public function defined($option)
{
return (
array_key_exists($option, $this->options) ||
array_key_exists($option, $this->input)
);
}
/**
* {@inheritdoc}
*/
public function __isset($option)
{
return (
array_key_exists($option, $this->options) ||
array_key_exists($option, $this->input)
) && $this->__get($option) !== null;
}
/**
* {@inheritdoc}
*/
public function __get($option)
{
if (isset($this->options[$option]) || array_key_exists($option, $this->options)) {
return $this->options[$option];
}
if (isset($this->input[$option]) || array_key_exists($option, $this->input)) {
$value = $this->input[$option];
unset($this->input[$option]);
if (method_exists($value, '__invoke')) {
$value = $value($this, $option);
}
if (isset($this->handlers[$option])) {
$handler = $this->handlers[$option];
$handler = new $handler();
$value = $handler->filter($this, $value);
}
return $this->options[$option] = $value;
}
if (isset($this->handlers[$option])) {
return $this->options[$option] = $this->getDefault($option);
}
}
}
| {
"content_hash": "8e3bd640dc24c98db19f51879f0a1ff9",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 90,
"avg_line_length": 26.2972972972973,
"alnum_prop": 0.5299760191846523,
"repo_name": "cola1129/devtool",
"id": "ba527cf0ac41ccfc63a4ba0049f0952132639d7f",
"size": "3151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "phpra/vendor/lib/Predis/Configuration/Options.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "49343"
},
{
"name": "JavaScript",
"bytes": "2080156"
},
{
"name": "PHP",
"bytes": "6755602"
},
{
"name": "Python",
"bytes": "16042"
},
{
"name": "Shell",
"bytes": "7396"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>qarith: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.1+1 / qarith - 8.6.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
qarith
<small>
8.6.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-20 02:00:26 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-20 02:00:26 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.1+1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/qarith"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/QArith"]
depends: [
"ocaml"
"coq" {>= "8.6" & < "8.7~"}
]
tags: [
"keyword: Q"
"keyword: arithmetic"
"keyword: rational numbers"
"keyword: setoid"
"keyword: ring"
"category: Mathematics/Arithmetic and Number Theory/Rational numbers"
"category: Miscellaneous/Extracted Programs/Arithmetic"
]
authors: [ "Pierre Letouzey" ]
bug-reports: "https://github.com/coq-contribs/qarith/issues"
dev-repo: "git+https://github.com/coq-contribs/qarith.git"
synopsis: "A Library for Rational Numbers (QArith)"
description: """
This contribution is a proposition of a library formalizing
rational number in Coq."""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/qarith/archive/v8.6.0.tar.gz"
checksum: "md5=d4d97ba1445e77321a2b70f254e52a44"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-qarith.8.6.0 coq.8.7.1+1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.1+1).
The following dependencies couldn't be met:
- coq-qarith -> coq < 8.7~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-qarith.8.6.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "099cd9254260fcb63572668211c15021",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 159,
"avg_line_length": 40.395348837209305,
"alnum_prop": 0.540587219343696,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "70f98b0eb77d50dc4a564756da71faf2cf3f9fbc",
"size": "6973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.7.1+1/qarith/8.6.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.