text:
> Transform cmd and get cmd dependences
>
> [![NPM Version][npm-image]][npm-url]
> [![Download Status][download-image]][npm-url]
> [![Linux Status][travis-image]][travis-url]
> [![Windows Status][appveyor-image]][appveyor-url]
> [![Test Coverage][coveralls-image]][coveralls-url]
> [![Dependencies][david-image]][david-url]

### Installation

```
npm install cmd-deps
```

### Api

* parseDependencies(code:String|Buffer, options:Object):Object
* parseDependencies(code:String|Buffer, replace:Function, options:Object):Object
  * options { acorn:Object, word:String, flags:Array }
    * acorn: acorn options
    * word: dependencies function name
    * flags: dependencies function method name

### Example

source:

```js
require('a');
//require('b');
/require('c')/;
('require("d")');
if (true) /require('e')/;
do /require('f')/.test(s);
while (false);
require.async('g');
require.async(['h']);
```

js:

```js
const parseDependencies = require('cmd-deps');
const dependencies = parseDependencies(source, { flags: ['async'] }).dependencies;

// print dependencies
console.log(dependencies);
```

parser output:

```js
[
  {
    flag: null,
    path: 'a'
  },
  {
    flag: 'async',
    path: 'g'
  },
  {
    flag: 'async',
    path: 'h'
  }
];
```

## License

[MIT](LICENSE)

[travis-image]: http://img.shields.io/travis/nuintun/cmd-deps.svg?style=flat-square&label=linux
[travis-url]: https://travis-ci.org/nuintun/cmd-deps
[appveyor-image]: https://img.shields.io/appveyor/ci/nuintun/cmd-deps.svg?style=flat-square&label=windows
[appveyor-url]: https://ci.appveyor.com/project/nuintun/cmd-deps
[coveralls-image]: http://img.shields.io/coveralls/nuintun/cmd-deps/master.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/nuintun/cmd-deps?branch=master
[david-image]: http://img.shields.io/david/nuintun/cmd-deps.svg?style=flat-square
[david-url]: https://david-dm.org/nuintun/cmd-deps
[npm-image]: http://img.shields.io/npm/v/cmd-deps.svg?style=flat-square
[npm-url]: https://www.npmjs.org/package/cmd-deps
[download-image]: http://img.shields.io/npm/dm/cmd-deps.svg?style=flat-square


text:
//===- llvm/LLVMContext.h - Class for managing "global" state ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file declares LLVMContext, a container of "global" state in LLVM, such
// as the global type and constant uniquing tables.
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_IR_LLVMCONTEXT_H
#define LLVM_IR_LLVMCONTEXT_H

#include "llvm-c/Types.h"
#include "llvm/IR/DiagnosticHandler.h"
#include "llvm/Support/CBindingWrapping.h"
#include <cstdint>
#include <memory>
#include <string>

namespace llvm {

class DiagnosticInfo;
enum DiagnosticSeverity : char;
class Function;
class Instruction;
class LLVMContextImpl;
class Module;
class OptPassGate;
template <typename T> class SmallVectorImpl;
class SMDiagnostic;
class StringRef;
class Twine;
class RemarkStreamer;
class raw_ostream;

namespace SyncScope {

typedef uint8_t ID;

/// Known synchronization scope IDs, which always have the same value.  All
/// synchronization scope IDs that LLVM has special knowledge of are listed
/// here.  Additionally, this scheme allows LLVM to efficiently check for
/// specific synchronization scope ID without comparing strings.
enum {
  /// Synchronized with respect to signal handlers executing in the same thread.
  SingleThread = 0,

  /// Synchronized with respect to all concurrently executing threads.
  System = 1
};

} // end namespace SyncScope

/// This is an important class for using LLVM in a threaded context.  It
/// (opaquely) owns and manages the core "global" data of LLVM's core
/// infrastructure, including the type and constant uniquing tables.
/// LLVMContext itself provides no locking guarantees, so you should be careful
/// to have one context per thread.
class LLVMContext {
public:
  LLVMContextImpl *const pImpl;
  LLVMContext();
  LLVMContext(LLVMContext &) = delete;
  LLVMContext &operator=(const LLVMContext &) = delete;
  ~LLVMContext();

  // Pinned metadata names, which always have the same value.  This is a
  // compile-time performance optimization, not a correctness optimization.
  enum : unsigned {
#define LLVM_FIXED_MD_KIND(EnumID, Name, Value) EnumID = Value,
#include "llvm/IR/FixedMetadataKinds.def"
#undef LLVM_FIXED_MD_KIND
  };

  /// Known operand bundle tag IDs, which always have the same value.  All
  /// operand bundle tags that LLVM has special knowledge of are listed here.
  /// Additionally, this scheme allows LLVM to efficiently check for specific
  /// operand bundle tags without comparing strings.
  enum : unsigned {
    OB_deopt = 0,         // "deopt"
    OB_funclet = 1,       // "funclet"
    OB_gc_transition = 2, // "gc-transition"
    OB_cfguardtarget = 3, // "cfguardtarget"
  };

  /// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
  /// This ID is uniqued across modules in the current LLVMContext.
  unsigned getMDKindID(StringRef Name) const;

  /// getMDKindNames - Populate client supplied SmallVector with the name for
  /// custom metadata IDs registered in this LLVMContext.
  void getMDKindNames(SmallVectorImpl<StringRef> &Result) const;

  /// getOperandBundleTags - Populate client supplied SmallVector with the
  /// bundle tags registered in this LLVMContext.  The bundle tags are ordered
  /// by increasing bundle IDs.
  /// \see LLVMContext::getOperandBundleTagID
  void getOperandBundleTags(SmallVectorImpl<StringRef> &Result) const;

  /// getOperandBundleTagID - Maps a bundle tag to an integer ID.  Every bundle
  /// tag registered with an LLVMContext has an unique ID.
  uint32_t getOperandBundleTagID(StringRef Tag) const;

  /// getOrInsertSyncScopeID - Maps synchronization scope name to
  /// synchronization scope ID.  Every synchronization scope registered with
  /// LLVMContext has unique ID except pre-defined ones.
  SyncScope::ID getOrInsertSyncScopeID(StringRef SSN);

  /// getSyncScopeNames - Populates client supplied SmallVector with
  /// synchronization scope names registered with LLVMContext.  Synchronization
  /// scope names are ordered by increasing synchronization scope IDs.
  void getSyncScopeNames(SmallVectorImpl<StringRef> &SSNs) const;

  /// Define the GC for a function
  void setGC(const Function &Fn, std::string GCName);

  /// Return the GC for a function
  const std::string &getGC(const Function &Fn);

  /// Remove the GC for a function
  void deleteGC(const Function &Fn);

  /// Return true if the Context runtime configuration is set to discard all
  /// value names. When true, only GlobalValue names will be available in the
  /// IR.
  bool shouldDiscardValueNames() const;

  /// Set the Context runtime configuration to discard all value name (but
  /// GlobalValue). Clients can use this flag to save memory and runtime,
  /// especially in release mode.
  void setDiscardValueNames(bool Discard);

  /// Whether there is a string map for uniquing debug info
  /// identifiers across the context.  Off by default.
  bool isODRUniquingDebugTypes() const;
  void enableDebugTypeODRUniquing();
  void disableDebugTypeODRUniquing();

  using InlineAsmDiagHandlerTy = void (*)(const SMDiagnostic&, void *Context,
                                          unsigned LocCookie);

  /// Defines the type of a yield callback.
  /// \see LLVMContext::setYieldCallback.
  using YieldCallbackTy = void (*)(LLVMContext *Context, void *OpaqueHandle);

  /// setInlineAsmDiagnosticHandler - This method sets a handler that is invoked
  /// when problems with inline asm are detected by the backend.  The first
  /// argument is a function pointer and the second is a context pointer that
  /// gets passed into the DiagHandler.
  ///
  /// LLVMContext doesn't take ownership or interpret either of these
  /// pointers.
  void setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
                                     void *DiagContext = nullptr);

  /// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
  /// setInlineAsmDiagnosticHandler.
  InlineAsmDiagHandlerTy getInlineAsmDiagnosticHandler() const;

  /// getInlineAsmDiagnosticContext - Return the diagnostic context set by
  /// setInlineAsmDiagnosticHandler.
  void *getInlineAsmDiagnosticContext() const;

  /// setDiagnosticHandlerCallBack - This method sets a handler call back
  /// that is invoked when the backend needs to report anything to the user.
  /// The first argument is a function pointer and the second is a context pointer
  /// that gets passed into the DiagHandler.  The third argument should be set to
  /// true if the handler only expects enabled diagnostics.
  ///
  /// LLVMContext doesn't take ownership or interpret either of these
  /// pointers.
  void setDiagnosticHandlerCallBack(
      DiagnosticHandler::DiagnosticHandlerTy DiagHandler,
      void *DiagContext = nullptr, bool RespectFilters = false);

  /// setDiagnosticHandler - This method sets unique_ptr to object of DiagnosticHandler
  /// to provide custom diagnostic handling. The first argument is unique_ptr of object
  /// of type DiagnosticHandler or a derived of that.   The third argument should be
  /// set to true if the handler only expects enabled diagnostics.
  ///
  /// Ownership of this pointer is moved to LLVMContextImpl.
  void setDiagnosticHandler(std::unique_ptr<DiagnosticHandler> &&DH,
                            bool RespectFilters = false);

  /// getDiagnosticHandlerCallBack - Return the diagnostic handler call back set by
  /// setDiagnosticHandlerCallBack.
  DiagnosticHandler::DiagnosticHandlerTy getDiagnosticHandlerCallBack() const;

  /// getDiagnosticContext - Return the diagnostic context set by
  /// setDiagnosticContext.
  void *getDiagnosticContext() const;

  /// getDiagHandlerPtr - Returns const raw pointer of DiagnosticHandler set by
  /// setDiagnosticHandler.
  const DiagnosticHandler *getDiagHandlerPtr() const;

  /// getDiagnosticHandler - transfers owenership of DiagnosticHandler unique_ptr
  /// to caller.
  std::unique_ptr<DiagnosticHandler> getDiagnosticHandler();

  /// Return if a code hotness metric should be included in optimization
  /// diagnostics.
  bool getDiagnosticsHotnessRequested() const;
  /// Set if a code hotness metric should be included in optimization
  /// diagnostics.
  void setDiagnosticsHotnessRequested(bool Requested);

  /// Return the minimum hotness value a diagnostic would need in order
  /// to be included in optimization diagnostics. If there is no minimum, this
  /// returns None.
  uint64_t getDiagnosticsHotnessThreshold() const;

  /// Set the minimum hotness value a diagnostic needs in order to be
  /// included in optimization diagnostics.
  void setDiagnosticsHotnessThreshold(uint64_t Threshold);

  /// Return the streamer used by the backend to save remark diagnostics. If it
  /// does not exist, diagnostics are not saved in a file but only emitted via
  /// the diagnostic handler.
  RemarkStreamer *getRemarkStreamer();
  const RemarkStreamer *getRemarkStreamer() const;

  /// Set the diagnostics output used for optimization diagnostics.
  /// This filename may be embedded in a section for tools to find the
  /// diagnostics whenever they're needed.
  ///
  /// If a remark streamer is already set, it will be replaced with
  /// \p RemarkStreamer.
  ///
  /// By default, diagnostics are not saved in a file but only emitted via the
  /// diagnostic handler.  Even if an output file is set, the handler is invoked
  /// for each diagnostic message.
  void setRemarkStreamer(std::unique_ptr<RemarkStreamer> RemarkStreamer);

  /// Get the prefix that should be printed in front of a diagnostic of
  ///        the given \p Severity
  static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity);

  /// Report a message to the currently installed diagnostic handler.
  ///
  /// This function returns, in particular in the case of error reporting
  /// (DI.Severity == \a DS_Error), so the caller should leave the compilation
  /// process in a self-consistent state, even though the generated code
  /// need not be correct.
  ///
  /// The diagnostic message will be implicitly prefixed with a severity keyword
  /// according to \p DI.getSeverity(), i.e., "error: " for \a DS_Error,
  /// "warning: " for \a DS_Warning, and "note: " for \a DS_Note.
  void diagnose(const DiagnosticInfo &DI);

  /// Registers a yield callback with the given context.
  ///
  /// The yield callback function may be called by LLVM to transfer control back
  /// to the client that invoked the LLVM compilation. This can be used to yield
  /// control of the thread, or perform periodic work needed by the client.
  /// There is no guaranteed frequency at which callbacks must occur; in fact,
  /// the client is not guaranteed to ever receive this callback. It is at the
  /// sole discretion of LLVM to do so and only if it can guarantee that
  /// suspending the thread won't block any forward progress in other LLVM
  /// contexts in the same process.
  ///
  /// At a suspend point, the state of the current LLVM context is intentionally
  /// undefined. No assumptions about it can or should be made. Only LLVM
  /// context API calls that explicitly state that they can be used during a
  /// yield callback are allowed to be used. Any other API calls into the
  /// context are not supported until the yield callback function returns
  /// control to LLVM. Other LLVM contexts are unaffected by this restriction.
  void setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle);

  /// Calls the yield callback (if applicable).
  ///
  /// This transfers control of the current thread back to the client, which may
  /// suspend the current thread. Only call this method when LLVM doesn't hold
  /// any global mutex or cannot block the execution in another LLVM context.
  void yield();

  /// emitError - Emit an error message to the currently installed error handler
  /// with optional location information.  This function returns, so code should
  /// be prepared to drop the erroneous construct on the floor and "not crash".
  /// The generated code need not be correct.  The error message will be
  /// implicitly prefixed with "error: " and should not end with a ".".
  void emitError(unsigned LocCookie, const Twine &ErrorStr);
  void emitError(const Instruction *I, const Twine &ErrorStr);
  void emitError(const Twine &ErrorStr);

  /// Access the object which can disable optional passes and individual
  /// optimizations at compile time.
  OptPassGate &getOptPassGate() const;

  /// Set the object which can disable optional passes and individual
  /// optimizations at compile time.
  ///
  /// The lifetime of the object must be guaranteed to extend as long as the
  /// LLVMContext is used by compilation.
  void setOptPassGate(OptPassGate&);

private:
  // Module needs access to the add/removeModule methods.
  friend class Module;

  /// addModule - Register a module as being instantiated in this context.  If
  /// the context is deleted, the module will be deleted as well.
  void addModule(Module*);

  /// removeModule - Unregister a module from this context.
  void removeModule(Module*);
};

// Create wrappers for C Binding types (see CBindingWrapping.h).
DEFINE_SIMPLE_CONVERSION_FUNCTIONS(LLVMContext, LLVMContextRef)

/* Specialized opaque context conversions.
 */
inline LLVMContext **unwrap(LLVMContextRef* Tys) {
  return reinterpret_cast<LLVMContext**>(Tys);
}

inline LLVMContextRef *wrap(const LLVMContext **Tys) {
  return reinterpret_cast<LLVMContextRef*>(const_cast<LLVMContext**>(Tys));
}

} // end namespace llvm

#endif // LLVM_IR_LLVMCONTEXT_H

redpajama_set_name: RedPajamaGithub


text:
import { VectorKeyframeTrack } from './tracks/VectorKeyframeTrack';
import { QuaternionKeyframeTrack } from './tracks/QuaternionKeyframeTrack';
import { NumberKeyframeTrack } from './tracks/NumberKeyframeTrack';
import { AnimationUtils } from './AnimationUtils';
import { KeyframeTrack } from './KeyframeTrack';
import { _Math } from '../math/Math';

/**
 *
 * Reusable set of Tracks that represent an animation.
 *
 * @author Ben Houston / http://clara.io/
 * @author David Sarno / http://lighthaus.us/
 */

function AnimationClip( name, duration, tracks ) {

	this.name = name;
	this.tracks = tracks;
	this.duration = ( duration !== undefined ) ? duration : - 1;

	this.uuid = _Math.generateUUID();

	// this means it should figure out its duration by scanning the tracks
	if ( this.duration < 0 ) {

		this.resetDuration();

	}

	this.optimize();

}

Object.assign( AnimationClip, {

	parse: function ( json ) {

		var tracks = [],
			jsonTracks = json.tracks,
			frameTime = 1.0 / ( json.fps || 1.0 );

		for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {

			tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );

		}

		return new AnimationClip( json.name, json.duration, tracks );

	},

	toJSON: function ( clip ) {

		var tracks = [],
			clipTracks = clip.tracks;

		var json = {

			'name': clip.name,
			'duration': clip.duration,
			'tracks': tracks

		};

		for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {

			tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );

		}

		return json;

	},

	CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {

		var numMorphTargets = morphTargetSequence.length;
		var tracks = [];

		for ( var i = 0; i < numMorphTargets; i ++ ) {

			var times = [];
			var values = [];

			times.push(
					( i + numMorphTargets - 1 ) % numMorphTargets,
					i,
					( i + 1 ) % numMorphTargets );

			values.push( 0, 1, 0 );

			var order = AnimationUtils.getKeyframeOrder( times );
			times = AnimationUtils.sortedArray( times, 1, order );
			values = AnimationUtils.sortedArray( values, 1, order );

			// if there is a key at the first frame, duplicate it as the
			// last frame as well for perfect loop.
			if ( ! noLoop && times[ 0 ] === 0 ) {

				times.push( numMorphTargets );
				values.push( values[ 0 ] );

			}

			tracks.push(
					new NumberKeyframeTrack(
						'.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
						times, values
					).scale( 1.0 / fps ) );

		}

		return new AnimationClip( name, - 1, tracks );

	},

	findByName: function ( objectOrClipArray, name ) {

		var clipArray = objectOrClipArray;

		if ( ! Array.isArray( objectOrClipArray ) ) {

			var o = objectOrClipArray;
			clipArray = o.geometry && o.geometry.animations || o.animations;

		}

		for ( var i = 0; i < clipArray.length; i ++ ) {

			if ( clipArray[ i ].name === name ) {

				return clipArray[ i ];

			}

		}

		return null;

	},

	CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {

		var animationToMorphTargets = {};

		// tested with https://regex101.com/ on trick sequences
		// such flamingo_flyA_003, flamingo_run1_003, crdeath0059
		var pattern = /^([\w-]*?)([\d]+)$/;

		// sort morph target names into animation groups based
		// patterns like Walk_001, Walk_002, Run_001, Run_002
		for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {

			var morphTarget = morphTargets[ i ];
			var parts = morphTarget.name.match( pattern );

			if ( parts && parts.length > 1 ) {

				var name = parts[ 1 ];

				var animationMorphTargets = animationToMorphTargets[ name ];
				if ( ! animationMorphTargets ) {

					animationToMorphTargets[ name ] = animationMorphTargets = [];

				}

				animationMorphTargets.push( morphTarget );

			}

		}

		var clips = [];

		for ( var name in animationToMorphTargets ) {

			clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );

		}

		return clips;

	},

	// parse the animation.hierarchy format
	parseAnimation: function ( animation, bones ) {

		if ( ! animation ) {

			console.error( 'B3D.AnimationClip: No animation in JSONLoader data.' );
			return null;

		}

		var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {

			// only return track if there are actually keys.
			if ( animationKeys.length !== 0 ) {

				var times = [];
				var values = [];

				AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );

				// empty keys are filtered out, so check again
				if ( times.length !== 0 ) {

					destTracks.push( new trackType( trackName, times, values ) );

				}

			}

		};

		var tracks = [];

		var clipName = animation.name || 'default';
		// automatic length determination in AnimationClip.
		var duration = animation.length || - 1;
		var fps = animation.fps || 30;

		var hierarchyTracks = animation.hierarchy || [];

		for ( var h = 0; h < hierarchyTracks.length; h ++ ) {

			var animationKeys = hierarchyTracks[ h ].keys;

			// skip empty tracks
			if ( ! animationKeys || animationKeys.length === 0 ) continue;

			// process morph targets
			if ( animationKeys[ 0 ].morphTargets ) {

				// figure out all morph targets used in this track
				var morphTargetNames = {};

				for ( var k = 0; k < animationKeys.length; k ++ ) {

					if ( animationKeys[ k ].morphTargets ) {

						for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {

							morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;

						}

					}

				}

				// create a track for each morph target with all zero
				// morphTargetInfluences except for the keys in which
				// the morphTarget is named.
				for ( var morphTargetName in morphTargetNames ) {

					var times = [];
					var values = [];

					for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {

						var animationKey = animationKeys[ k ];

						times.push( animationKey.time );
						values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );

					}

					tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );

				}

				duration = morphTargetNames.length * ( fps || 1.0 );

			} else {

				// ...assume skeletal animation

				var boneName = '.bones[' + bones[ h ].name + ']';

				addNonemptyTrack(
						VectorKeyframeTrack, boneName + '.position',
						animationKeys, 'pos', tracks );

				addNonemptyTrack(
						QuaternionKeyframeTrack, boneName + '.quaternion',
						animationKeys, 'rot', tracks );

				addNonemptyTrack(
						VectorKeyframeTrack, boneName + '.scale',
						animationKeys, 'scl', tracks );

			}

		}

		if ( tracks.length === 0 ) {

			return null;

		}

		var clip = new AnimationClip( clipName, duration, tracks );

		return clip;

	}

} );

Object.assign( AnimationClip.prototype, {

	resetDuration: function () {

		var tracks = this.tracks, duration = 0;

		for ( var i = 0, n = tracks.length; i !== n; ++ i ) {

			var track = this.tracks[ i ];

			duration = Math.max( duration, track.times[ track.times.length - 1 ] );

		}

		this.duration = duration;

	},

	trim: function () {

		for ( var i = 0; i < this.tracks.length; i ++ ) {

			this.tracks[ i ].trim( 0, this.duration );

		}

		return this;

	},

	optimize: function () {

		for ( var i = 0; i < this.tracks.length; i ++ ) {

			this.tracks[ i ].optimize();

		}

		return this;

	}

} );

export { AnimationClip };


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');

class MY_Config extends CI_Config
{
    private $ci;

    function __construct()
    {
        parent::__construct();
        $this->ci = &get_instance();
    }

    public function set_item_section($section, $item, $value)
    {
        $this->config[$section][$item] = $value;
    }

    function save($file_name)
    {
        $this->ci->load->helper('file');
        $str = "<?php if (!defined('BASEPATH')) exit('No direct script access allowed.');\n";
        foreach ($this->config[$file_name] as $k => $item) {
            $str .= "\$config['$k'] = '" . addslashes($item) . "';\n";
        }

        $path = APPPATH . 'config' . DIRECTORY_SEPARATOR . $file_name . '.php';

        if (file_exists($path)) {
            write_file($path, $str);
        } else {
            show_error('Config file not exists.');
        }

        return TRUE;
    }
}


text:
namespace device {

struct CtapAuthenticatorSelectionRequest {};

std::pair<CtapRequestCommand, absl::optional<cbor::Value>>
AsCTAPRequestValuePair(const CtapAuthenticatorSelectionRequest&);

}  // namespace device

#endif  // DEVICE_FIDO_CTAP_AUTHENTICATOR_SELECTION_REQUEST_H_


text:
using System;
using Lucene.Net.Support;

namespace Lucene.Net.Store
{

    ///  A memory-resident <see cref="Directory"/> implementation.  Locking
    /// implementation is by default the <see cref="SingleInstanceLockFactory"/>
    /// but can be changed with <see cref="Directory.SetLockFactory"/>.
    ///
    [Serializable]
    public class RAMDirectory:Directory
    {

        private const long serialVersionUID = 1L;

        internal protected HashMap<string, RAMFile> fileMap = new HashMap<string, RAMFile>();
        internal protected long internalSizeInBytes = 0;

        // *****
        // Lock acquisition sequence:  RAMDirectory, then RAMFile
        // *****

        /// Constructs an empty <see cref="Directory"/>.
        public RAMDirectory()
        {
            SetLockFactory(new SingleInstanceLockFactory());
        }

        ///  Creates a new <c>RAMDirectory</c> instance from a different
        /// <c>Directory</c> implementation.  This can be used to load
        /// a disk-based index into memory.
        ///

        /// This should be used only with indices that can fit into memory.
        ///

        /// Note that the resulting <c>RAMDirectory</c> instance is fully
        /// independent from the original <c>Directory</c> (it is a
        /// complete copy).  Any subsequent changes to the
        /// original <c>Directory</c> will not be visible in the
        /// <c>RAMDirectory</c> instance.
        ///
        ///
        /// <param name="dir">a <c>Directory</c> value
        /// </param>
        /// <exception cref="System.IO.IOException">if an error occurs
        /// </exception>
        public RAMDirectory(Directory dir):this(dir, false)
        {
        }

        private RAMDirectory(Directory dir, bool closeDir):this()
        {
            Directory.Copy(dir, this, closeDir);
        }

         //https://issues.apache.org/jira/browse/LUCENENET-174
        [System.Runtime.Serialization.OnDeserialized]
        void OnDeserialized(System.Runtime.Serialization.StreamingContext context)
        {
            if (interalLockFactory == null)
            {
                SetLockFactory(new SingleInstanceLockFactory());
            }
        }

        public override System.String[] ListAll()
        {
            lock (this)
            {
                EnsureOpen();
                // TODO: may have better performance if our HashMap implmented KeySet() instead of generating one via HashSet
                System.Collections.Generic.ISet<string> fileNames = Support.Compatibility.SetFactory.CreateHashSet(fileMap.Keys);
                System.String[] result = new System.String[fileNames.Count];
                int i = 0;
                foreach(string filename in fileNames)
                {
                    result[i++] = filename;
                }
                return result;
            }
        }

        /// Returns true iff the named file exists in this directory.
        public override bool FileExists(System.String name)
        {
            EnsureOpen();
            RAMFile file;
            lock (this)
            {
                file = fileMap[name];
            }
            return file != null;
        }

        /// Returns the time the named file was last modified.
        /// <throws>  IOException if the file does not exist </throws>
        public override long FileModified(System.String name)
        {
            EnsureOpen();
            RAMFile file;
            lock (this)
            {
                file = fileMap[name];
            }
            if (file == null)
                throw new System.IO.FileNotFoundException(name);

            // RAMOutputStream.Flush() was changed to use DateTime.UtcNow.
            // Convert it back to local time before returning (previous behavior)
            return new DateTime(file.LastModified*TimeSpan.TicksPerMillisecond, DateTimeKind.Utc).ToLocalTime().Ticks/
                   TimeSpan.TicksPerMillisecond;
        }

        /// Set the modified time of an existing file to now.
        /// <throws>  IOException if the file does not exist </throws>
        public override void  TouchFile(System.String name)
        {
            EnsureOpen();
            RAMFile file;
            lock (this)
            {
                file = fileMap[name];
            }
            if (file == null)
                throw new System.IO.FileNotFoundException(name);

            long ts2, ts1 = System.DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
            do
            {
                try
                {
                    System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 0 + 100 * 1));
                }
                catch (System.Threading.ThreadInterruptedException ie)
                {
                    // In 3.0 we will change this to throw
                    // InterruptedException instead
                    ThreadClass.Current().Interrupt();
                    throw new System.SystemException(ie.Message, ie);
                }
                ts2 = System.DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond;
            }
            while (ts1 == ts2);

            file.LastModified = ts2;
        }

        /// Returns the length in bytes of a file in the directory.
        /// <throws>  IOException if the file does not exist </throws>
        public override long FileLength(System.String name)
        {
            EnsureOpen();
            RAMFile file;
            lock (this)
            {
                file = fileMap[name];
            }
            if (file == null)
                throw new System.IO.FileNotFoundException(name);
            return file.Length;
        }

        /// Return total size in bytes of all files in this
        /// directory.  This is currently quantized to
        /// RAMOutputStream.BUFFER_SIZE.
        ///
        public long SizeInBytes()
        {
            lock (this)
            {
                EnsureOpen();
                return internalSizeInBytes;
            }
        }

        /// Removes an existing file in the directory.
        /// <throws>  IOException if the file does not exist </throws>
        public override void  DeleteFile(System.String name)
        {
            lock (this)
            {
                EnsureOpen();
                RAMFile file = fileMap[name];
                if (file != null)
                {
                    fileMap.Remove(name);
                    file.directory = null;
                    internalSizeInBytes -= file.sizeInBytes;
                }
                else
                    throw new System.IO.FileNotFoundException(name);
            }
        }

        /// Creates a new, empty file in the directory with the given name. Returns a stream writing this file.
        public override IndexOutput CreateOutput(System.String name)
        {
            EnsureOpen();
            RAMFile file = new RAMFile(this);
            lock (this)
            {
                RAMFile existing = fileMap[name];
                if (existing != null)
                {
                    internalSizeInBytes -= existing.sizeInBytes;
                    existing.directory = null;
                }
                fileMap[name] = file;
            }
            return new RAMOutputStream(file);
        }

        /// Returns a stream reading an existing file.
        public override IndexInput OpenInput(System.String name)
        {
            EnsureOpen();
            RAMFile file;
            lock (this)
            {
                file = fileMap[name];
            }
            if (file == null)
                throw new System.IO.FileNotFoundException(name);
            return new RAMInputStream(file);
        }

        /// Closes the store to future operations, releasing associated memory.
        protected override void Dispose(bool disposing)
        {
            isOpen = false;
            fileMap = null;
        }

        //public HashMap<string, RAMFile> fileMap_ForNUnit
        //{
        //    get { return fileMap; }
        //}

        //public long sizeInBytes_ForNUnitTest
        //{
        //    get { return sizeInBytes; }
        //    set { sizeInBytes = value; }
        //}
    }
}


text:
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"

# Add diff-highlight from Git contrib
export PATH="$PATH:/usr/local/opt/git/share/git-core/contrib/diff-highlight"

export PATH="$PATH:./node_modules/.bin"
export PATH="$PATH:/usr/local/sbin"

export PATH="$PATH:$HOME/.local/bin"

# ----- From Stripe IT department ---------------------------------------------

export PATH="/Users/jzimmerman/stripe/henson/bin:$PATH"
source /Users/jzimmerman/.rbenvrc
rbenv rehash
source ~/.stripe-repos.sh

# ----- aliases ---------------------------------------------------------------

# Double double letters are hard
which coffee &> /dev/null && alias coffe="coffee"

# Use neovim for the lulz
alias vim="nvim -p"
alias vimdiff="nvim -d"

# Override BSD grep with GNU equivalent
which ggrep &> /dev/null && alias grep="ggrep --color=auto";

alias cdsc="cd ~/stripe/checkout-js"
alias cds="cd ~/stripe"

# ----- Haskell ---------------------------------------------------------------

# Have Haskell Stack use XDG Base Directory spec
export STACK_ROOT="$XDG_DATA_HOME/stack"

# ----- Prompt  ---------------------------------------------------------------

export PROMPT_PURE_DIR_COLOR="%{$ccyan%}"
export PROMPT_PURE_SUCCESS_COLOR="%{$cmagentab%}"

# ----- Miscellaneous ---------------------------------------------------------

# update-host
# Usage:
#     update-host
#
# You should never have to call this. It's called when you call `update`
update-host () {
  echo "$cblueb==>$cwhiteb Updating Homebrew...$cnone"
  brew update

  echo "$cblueb==>$cwhiteb Checking Homebrew...$cnone"
  brew doctor

  echo "$cblueb==>$cwhiteb Checking for outdated brew packages...$cnone"
  brew outdated --verbose

}


text:
<?php
if(!empty($_POST['tekst'])){
	fx('czatuj');
	czatuj($gracz['login'],$_POST['tekst']);
}
?>

Czat

		w wersji demo mocno spowolniono odświeżanie się czatu (tylko co minutę)

			<form action='?akcja=czat' method='post'>
			<textarea name="tekst" cols=80 rows=2></textarea>

			<input type='submit' class='submit' value='powiedz'/>
			</form>

			<?php
				require_once('czat.php');
			?>


text:
( function(){
    'use strict';

    var config = require('pony-config');

    exports.localize = function( req, res, next ){

        if( req.flash !== undefined ){
            var flashErrors = req.flash('error');
            var flashInfos = req.flash('info');
            var flashSuccesses = req.flash('success');

            res.locals.flashMessagesPresent = function(){
                return (flashErrors && flashErrors.length > 0) || (flashInfos && flashInfos.length > 0) || (flashSuccesses && flashSuccesses.length > 0);
            };

            // Just moving the flash messages to the response locals so we can reference them in the views
            res.locals.flashErrors = flashErrors;
            res.locals.flashInfos = flashInfos;
            res.locals.flashSuccesses = flashSuccesses;
        }

        if( req.user ) res.locals.user = req.user;
        res.locals.currentUrl = req.originalUrl;
        res.locals.scriptsToMinify = config.get("scriptsToMinify");
        res.locals.useMinifiedJs = config.get("useMinifiedJs");

        next();
    };

    exports.fourOhFour = function( req, res, next ){
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    };

    exports.unhandledError = function( err, req, res, next ){
        console.log( "Unhandled error: ", err );

        var error = ( config.get("renderStackTraces") === true ) ? err : {};

        res.status( err.status || 500 );

        res.render( 'error', {
            message: err.message,
            error: error
        });
    };

})();


text:
var awsIot = require("aws-iot-device-sdk");
var config = require("./device.json");
const commandLineArgs = require('command-line-args');

const optionDefinitions = [
  { name: 'verbose', alias: 'v', type: Boolean, defaultValue: false },
  { name: 'region', alias: 'r', type: String, defaultValue: config.region },
  { name: 'unitid', alias: 'u', type: String, defaultValue: config.deviceId }
];
const options = commandLineArgs(optionDefinitions);

var data = [];
try {
  var device = awsIot.device({
    keyPath: "cert/private.pem.key",
    certPath: "cert/certificate.pem.crt",
    caPath: "cert/root.pem.crt",
    clientId: options.unitid,
    region: options.region
  });

  var topic = "test/"+options.unitid;

  var messages = [
    {"line1":"I :heart: beer!","line2":"How about you?"},
    {"line1":"Step right up...","line2":"and grab a beer!"},
    {"line1":"What a beautiful","line2":"day for a beer!"},
    {"line1":"HEY! YOU!","line2":"Want a beer?"}
  ]

  var temp = Math.floor((Math.random() * 8)+14);
  var humidity = Math.floor((Math.random() * 20)+40);
  var sound = Math.floor((Math.random() * 100)+100);

  // Creates the JSON Payload to send to AWS IoT
  function generatePayload() {
    var payload = {
      "version": "5",
      "deviceId": options.unitid,
      "data": data
    }
    data = [];
    //console.log("Payload: ", payload);
    return JSON.stringify(payload);
  }

  // Generates a random flow count every 10 iterations.
  var delay = 0;
  function getRandomFlowCount() {
    delay++;
    if (delay<20 && delay>10) {
      return 10 + Math.floor(Math.random() * 30);
    } else if (delay>20) {
      delay = 0;
    }
    return 0;
  }

  /** Generates a random new value.
   * @param val The previous value.
   * @param low The lower bound (if below, always increment)
   * @param high The upper bound (if above, always decrement)
   * @param delta The highest amount of change.
   */
  function getRandomValue(val, low, high, delta) {
    var rand = Math.random()*1;
    if (val>high|| rand>1 && !(val<low)) {
      val -= Math.random() * delta;
    } else if (val<low||rand<1) {
      val += Math.random() * delta;
    }
    return Math.floor(val);
  }

  // Push to the data array.
  function populateData(sensor, value) {
    data.push({
      "timestamp":new Date().getTime(),
      "value":value,
      "type":sensor
    })
  }

  // Runs the simulator. Gets a random value for each sensor and Generates
  // a random flow count.
  function run(callback) {
    temp = getRandomValue(temp, 14, 24, 2);
    humidity = getRandomValue(humidity, 40, 70, 5);
    sound = getRandomValue(sound, 50, 250, 80);
    populateData('Flow', getRandomFlowCount());
    populateData('Temperature', temp);
    populateData('Humidity', humidity);
    populateData('Sound', sound);
    device.publish(topic, generatePayload());
  }

  // Sets only a random value for the Sound sensor.
  function consistent(callback) {
    sound = getRandomValue(sound, 20, 160, 150);
    populateData('Flow', 0);
    populateData('Temperature', 14);
    populateData('Humidity', 55);
    populateData('Sound', sound);
    device.publish(topic, generatePayload());
  }

  // Connect to AWS IoT and setup Intervals
  console.log("Connecting to AWS IoT...");
  device.on("connect", function() {
    console.log("Connected to AWS IoT.");
    setInterval(consistent, 1000);
    setInterval(function() {
      console.log("Message: ",messages[Math.floor(Math.random()*4)]);
    },10000);
  });

} catch (e) {
  console.log(e);
  process.exit();
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>Qt 4.8: QML XmlListModel Element</title>
  <link rel="stylesheet" type="text/css" href="style/style.css" />

  <link rel="stylesheet" type="text/css" href="style/superfish.css" />
  <link rel="stylesheet" type="text/css" href="style/narrow.css" />

      Home

    Qt Reference Documentation

Qt HOME

DEV

          DOC

BLOG

Qt 4.8

ALL VERSIONS

API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

Examples

Examples

Tutorials

Demos

QML Examples

          Search index:

          <form id="qtdocsearch" action="" onsubmit="return false;">
            <fieldset>
              <input type="text" name="searchstring" id="pageType" value="" />

 Close

All | API | Articles | Examples

 results:

            </fieldset>
          </form>

            API Lookup

Class index

Function index

Modules

Namespaces

Global Declarations

QML elements

            Qt Topics

Programming with Qt

Device UIs & Qt Quick

UI Design with Qt

Supported Platforms

Qt and Key Technologies

How-To's and Best Practices

            Examples

Examples

Tutorials

Demos

QML Examples

Home

QML Elements

QML XmlListModel Element

A

A

A

                Print

Contents

Properties

Methods

Detailed Description

Using key XML roles

QML XmlListModel Element

The XmlListModel element is used to specify a read-only model using XPath expressions. More...

This element was introduced in Qt 4.7.

List of all members, including inherited members

Properties

count : int

namespaceDeclarations : string

progress : real

query : string

roles : list<XmlRole>

source : url

status : enumeration

xml : string

Methods

errorString

get

reload

Detailed Description

XmlListModel is used to create a read-only model from XML data. It can be used as a data source for view elements (such as ListView, PathView, GridView) and other elements that interact with model data (such as Repeater).

For example, if there is a XML document at http://www.mysite.com/feed.xml like this:

 <?xml version="1.0" encoding="utf-8"?>
 <rss version="2.0">
     ...
     <channel>
         <item>
             <title>A blog post</title>
             <pubDate>Sat, 07 Sep 2010 10:00:01 GMT</pubDate>
         </item>
         <item>
             <title>Another blog post</title>
             <pubDate>Sat, 07 Sep 2010 15:35:01 GMT</pubDate>
         </item>
     </channel>
 </rss>

A XmlListModel could create a model from this data, like this:

 import QtQuick 1.0

 XmlListModel {
     id: xmlModel
     source: "http://www.mysite.com/feed.xml"
     query: "/rss/channel/item"

     XmlRole { name: "title"; query: "title/string()" }
     XmlRole { name: "pubDate"; query: "pubDate/string()" }
 }

The query value of "/rss/channel/item" specifies that the XmlListModel should generate a model item for each <tt><item></tt> in the XML document.

The XmlRole objects define the model item attributes. Here, each model item will have <tt>title</tt> and <tt>pubDate</tt> attributes that match the <tt>title</tt> and <tt>pubDate</tt> values of its corresponding <tt><item></tt>. (See XmlRole::query for more examples of valid XPath expressions for XmlRole.)

The model could be used in a ListView, like this:

 ListView {
     width: 180; height: 300
     model: xmlModel
     delegate: Text { text: title + ": " + pubDate }
 }

The XmlListModel data is loaded asynchronously, and status is set to <tt>XmlListModel.Ready</tt> when loading is complete. Note this means when XmlListModel is used for a view, the view is not populated until the model is loaded.

Using key XML roles

You can define certain roles as "keys" so that when reload() is called, the model will only add and refresh data that contains new values for these keys.

For example, if above role for "pubDate" was defined like this instead:

     XmlRole { name: "pubDate"; query: "pubDate/string()"; isKey: true }

Then when reload() is called, the model will only add and reload items with a "pubDate" value that is not already present in the model.

This is useful when displaying the contents of XML documents that are incrementally updated (such as RSS feeds) to avoid repainting the entire contents of a model in a view.

If multiple key roles are specified, the model only adds and reload items with a combined value of all key roles that is not already present in the model.

See also RSS News.

Property Documentation

read-onlycount : int

The number of data entries in the model.

namespaceDeclarations : string

The namespace declarations to be used in the XPath queries.

The namespaces should be declared as in XQuery. For example, if a requested document at http://mysite.com/feed.xml uses the namespace "http://www.w3.org/2005/Atom", this can be declared as the default namespace:

 XmlListModel {
     source: "http://mysite.com/feed.xml"
     query: "/feed/entry"
     namespaceDeclarations: "declare default element namespace 'http://www.w3.org/2005/Atom';"

     XmlRole { name: "title"; query: "title/string()" }
 }

read-onlyprogress : real

This indicates the current progress of the downloading of the XML data source. This value ranges from 0.0 (no data downloaded) to 1.0 (all data downloaded). If the XML data is not from a remote source, the progress becomes 1.0 as soon as the data is read.

Note that when the progress is 1.0, the XML data has been downloaded, but it is yet to be loaded into the model at this point. Use the status property to find out when the XML data has been read and loaded into the model.

See also status and source.

query : string

An absolute XPath query representing the base query for creating model items from this model's XmlRole objects. The query should start with '/' or '//'.

read-onlyroles : list<XmlRole>

The roles to make available for this model.

source : url

The location of the XML data source.

If both <tt>source</tt> and xml are set, xml is used.

read-onlystatus : enumeration

Specifies the model loading status, which can be one of the following:

XmlListModel.Null - No XML data has been set for this model.

XmlListModel.Ready - The XML data has been loaded into the model.

XmlListModel.Loading - The model is in the process of reading and loading XML data.

XmlListModel.Error - An error occurred while the model was loading. See errorString() for details about the error.

See also progress.

xml : string

This property holds the XML data for this model, if set.

The text is assumed to be UTF-8 encoded.

If both source and <tt>xml</tt> are set, <tt>xml</tt> is used.

Method Documentation

void XmlListModel::errorString ()

Returns a string description of the last error that occurred if status is XmlListModel::Error.

object XmlListModel::get ( int index )

Returns the item at index in the model.

For example, for a model like this:

 XmlListModel {
     id: model
     source: "http://mysite.com/feed.xml"
     query: "/feed/entry"
     XmlRole { name: "title"; query: "title/string()" }
 }

This will access the <tt>title</tt> value for the first item in the model:

 var title = model.get(0).title;

XmlListModel::reload ()

Reloads the model.

If no key roles have been specified, all existing model data is removed, and the model is rebuilt from scratch.

Otherwise, items are only added if the model does not already contain items with matching key role values.

See also Using key XML roles and XmlRole::isKey.

      <acronym title="Copyright">©</acronym> 2013 Digia Plc and/or its
      subsidiaries. Documentation contributions included herein are the copyrights of
      their respective owners.

      The documentation provided herein is licensed under the terms of the
      GNU Free Documentation
      License version 1.3 as published by the Free Software Foundation.

      Documentation sources may be obtained from
      www.qt-project.org.

      Digia, Qt and their respective logos are trademarks of Digia Plc
      in Finland and/or other countries worldwide. All other trademarks are property
      of their respective owners. Privacy Policy


text:
require "monitor"
require "pathname"
require "set"
require "tempfile"

require "bundler"

require_relative "shared_helpers"
require_relative "version"

module Vagrant
  # This class manages Vagrant's interaction with Bundler. Vagrant uses
  # Bundler as a way to properly resolve all dependencies of Vagrant and
  # all Vagrant-installed plugins.
  class Bundler
    def self.instance
      @bundler ||= self.new
    end

    def initialize
      @enabled = true if ENV["VAGRANT_INSTALLER_ENV"] ||
        ENV["VAGRANT_FORCE_BUNDLER"]
      @enabled  = !::Bundler::SharedHelpers.in_bundle? if !@enabled
      @monitor  = Monitor.new

      @gem_home = ENV["GEM_HOME"]
      @gem_path = ENV["GEM_PATH"]
    end

    # Initializes Bundler and the various gem paths so that we can begin
    # loading gems. This must only be called once.
    def init!(plugins)
      # If we're not enabled, then we don't do anything.
      return if !@enabled

      # Set the Bundler UI to be a silent UI. We have to add the
      # `silence` method to it because Bundler UI doesn't have it.
      ::Bundler.ui =
        if ::Bundler::UI.const_defined? :Silent
          # bundler >= 1.6.0
          ::Bundler::UI::Silent.new
        else
          # bundler < 1.6.0
          ::Bundler::UI.new
        end
      if !::Bundler.ui.respond_to?(:silence)
        ui = ::Bundler.ui
        def ui.silence(*args)
          yield
        end
      end

      bundle_path = Vagrant.user_data_path.join("gems")

      # Setup the "local" Bundler configuration. We need to set BUNDLE_PATH
      # because the existence of this actually suppresses `sudo`.
      @appconfigpath = Dir.mktmpdir
      File.open(File.join(@appconfigpath, "config"), "w+") do |f|
        f.write("BUNDLE_PATH: \"#{bundle_path}\"")
      end

      # Setup the Bundler configuration
      @configfile = File.open(Tempfile.new("vagrant").path + "1", "w+")
      @configfile.close

      # Build up the Gemfile for our Bundler context. We make sure to
      # lock Vagrant to our current Vagrant version. In addition to that,
      # we add all our plugin dependencies.
      @gemfile = build_gemfile(plugins)

      # Set the environmental variables for Bundler
      ENV["BUNDLE_APP_CONFIG"] = @appconfigpath
      ENV["BUNDLE_CONFIG"]  = @configfile.path
      ENV["BUNDLE_GEMFILE"] = @gemfile.path
      ENV["GEM_PATH"] =
        "#{bundle_path}#{::File::PATH_SEPARATOR}#{@gem_path}"
      Gem.clear_paths
    end

    # Installs the list of plugins.
    #
    # @param [Hash] plugins
    # @return [Array<Gem::Specification>]
    def install(plugins, local=false)
      internal_install(plugins, nil, local: local)
    end

    # Installs a local '*.gem' file so that Bundler can find it.
    #
    # @param [String] path Path to a local gem file.
    # @return [Gem::Specification]
    def install_local(path)
      # We have to do this load here because this file can be loaded
      # before RubyGems is actually loaded.
      require "rubygems/dependency_installer"
      begin
        require "rubygems/format"
      rescue LoadError
        # rubygems 2.x
      end

      # If we're installing from a gem file, determine the name
      # based on the spec in the file.
      pkg = if defined?(Gem::Format)
              # RubyGems 1.x
              Gem::Format.from_file_by_path(path)
            else
              # RubyGems 2.x
              Gem::Package.new(path)
            end

      # Install the gem manually. If the gem exists locally, then
      # Bundler shouldn't attempt to get it remotely.
      with_isolated_gem do
        installer = Gem::DependencyInstaller.new(
          document: [], prerelease: false)
        installer.install(path, "= #{pkg.spec.version}")
      end

      pkg.spec
    end

    # Update updates the given plugins, or every plugin if none is given.
    #
    # @param [Hash] plugins
    # @param [Array<String>] specific Specific plugin names to update. If
    #   empty or nil, all plugins will be updated.
    def update(plugins, specific)
      specific ||= []
      update = true
      update = { gems: specific } if !specific.empty?
      internal_install(plugins, update)
    end

    # Clean removes any unused gems.
    def clean(plugins)
      gemfile    = build_gemfile(plugins)
      lockfile   = "#{gemfile.path}.lock"
      definition = ::Bundler::Definition.build(gemfile, lockfile, nil)
      root       = File.dirname(gemfile.path)

      with_isolated_gem do
        runtime = ::Bundler::Runtime.new(root, definition)
        runtime.clean
      end
    end

    # During the duration of the yielded block, Bundler loud output
    # is enabled.
    def verbose
      @monitor.synchronize do
        begin
          old_ui = ::Bundler.ui
          require 'bundler/vendored_thor'
          ::Bundler.ui = ::Bundler::UI::Shell.new
          yield
        ensure
          ::Bundler.ui = old_ui
        end
      end
    end

    protected

    # Builds a valid Gemfile for use with Bundler given the list of
    # plugins.
    #
    # @return [Tempfile]
    def build_gemfile(plugins)
      sources = plugins.values.map { |p| p["sources"] }.flatten.compact.uniq

      f = File.open(Tempfile.new("vagrant").path + "2", "w+")
      f.tap do |gemfile|
        if !sources.include?("http://rubygems.org")
          gemfile.puts(%Q[source "https://rubygems.org"])
        end

        gemfile.puts(%Q[source "http://gems.hashicorp.com"])
        sources.each do |source|
          next if source == ""
          gemfile.puts(%Q[source "#{source}"])
        end

        gemfile.puts(%Q[gem "vagrant", "= #{VERSION}"])

        gemfile.puts("group :plugins do")
        plugins.each do |name, plugin|
          version = plugin["gem_version"]
          version = nil if version == ""

          opts = {}
          if plugin["require"] && plugin["require"] != ""
            opts[:require] = plugin["require"]
          end

          gemfile.puts(%Q[gem "#{name}", #{version.inspect}, #{opts.inspect}])
        end
        gemfile.puts("end")

        gemfile.close
      end
    end

    # This installs a set of plugins and optionally updates those gems.
    #
    # @param [Hash] plugins
    # @param [Hash, Boolean] update If true, updates all plugins, otherwise
    #   can be a hash of options. See Bundler.definition.
    # @return [Array<Gem::Specification>]
    def internal_install(plugins, update, **extra)
      gemfile    = build_gemfile(plugins)
      lockfile   = "#{gemfile.path}.lock"
      definition = ::Bundler::Definition.build(gemfile, lockfile, update)
      root       = File.dirname(gemfile.path)
      opts       = {}
      opts["local"] = true if extra[:local]

      with_isolated_gem do
        ::Bundler::Installer.install(root, definition, opts)
      end

      # TODO(mitchellh): clean gems here... for some reason when I put
      # it in on install, we get a GemNotFound exception. Gotta investigate.

      definition.specs
    rescue ::Bundler::VersionConflict => e
      raise Errors::PluginInstallVersionConflict,
        conflicts: e.to_s.gsub("Bundler", "Vagrant")
    end

    def with_isolated_gem
      raise Errors::BundlerDisabled if !@enabled

      # Remove bundler settings so that Bundler isn't loaded when building
      # native extensions because it causes all sorts of problems.
      old_rubyopt = ENV["RUBYOPT"]
      old_gemfile = ENV["BUNDLE_GEMFILE"]
      ENV["BUNDLE_GEMFILE"] = Tempfile.new("vagrant-gemfile").path
      ENV["RUBYOPT"] = (ENV["RUBYOPT"] || "").gsub(/-rbundler\/setup\s*/, "")

      # Set the GEM_HOME so gems are installed only to our local gem dir
      ENV["GEM_HOME"] = Vagrant.user_data_path.join("gems").to_s

      # Clear paths so that it reads the new GEM_HOME setting
      Gem.paths = ENV

      # Reset the all specs override that Bundler does
      old_all = Gem::Specification._all
      Gem::Specification.all = nil

      # /etc/gemrc and so on.
      old_config = nil
      begin
        old_config = Gem.configuration
      rescue Psych::SyntaxError
        # Just ignore this. This means that the ".gemrc" file has
        # an invalid syntax and can't be loaded. We don't care, because
        # when we set Gem.configuration to nil later, it'll force a reload
        # if it is needed.
      end
      Gem.configuration = NilGemConfig.new

      # Use a silent UI so that we have no output
      Gem::DefaultUserInteraction.use_ui(Gem::SilentUI.new) do
        return yield
      end
    ensure
      ENV["BUNDLE_GEMFILE"] = old_gemfile
      ENV["GEM_HOME"] = @gem_home
      ENV["RUBYOPT"]  = old_rubyopt

      Gem.configuration = old_config
      Gem.paths = ENV
      Gem::Specification.all = old_all
    end

    # This is pretty hacky but it is a custom implementation of
    # Gem::ConfigFile so that we don't load any gemrc files.
    class NilGemConfig < Gem::ConfigFile
      def initialize
        # We _can not_ `super` here because that can really mess up
        # some other configuration state. We need to just set everything
        # directly.

        @api_keys       = {}
        @args           = []
        @backtrace      = false
        @bulk_threshold = 1000
        @hash           = {}
        @update_sources = true
        @verbose        = true
      end
    end
  end
end


text:
<?php
/* @var $this yii\web\View */

use frontend\widgets\EventsWidget;
use backend\models\structure\StructureRecord;
use frontend\widgets\LastnewsWidget;

$this->title = 'myoption.ru - Главная страница';
$this->registerMetaTag([
    'name' => 'description',
    'content' => 'Описание'
]);
$this->registerMetaTag([
    'name' => 'keywords',
    'content' => 'Ключевые'
]);
?>

События для заработка на бинарных опционах

                    Календарь событий
                    Бинарные опционы

                        <?=EventsWidget::widget(['mode'=>'all'])?>

                        Как заработать на событии
                        Открыть счет

                        <?php
                        $binpage = StructureRecord::find()->where(['code'=>'content_bin'])->one();
                        if($binpage){
                            echo $binpage->content;
                        }
                        ?>

            <?php
            /*

Торговая стратегия бинарных опционов 60 секунд (h1)

                    Главная /
                    Стратегии /
                    Торговая стратегия бинарных опционов 60 секунд

Стратегия, о которой пойдет речь ниже, является моей собственной разработкой. Ранее правила работы по данной методике
                    неоднократно публиковались на сторонних сайтах, посвященных Forex или бинарным опционам. Теперь полное описание стратегии 60 секунд
                    доступно читателям моего блога.

Считаю необходимым для начала рассказать, на чем именно основан метод торговли, что бы было полное понимание всего метода, а не
                    бессмысленное заучивание правил. Потом Вы найдете примеры и объяснения, как следует действовать на рынке

Торговая стратегия бинарных опционов 60 секунд (h2)

Торговая стратегия бинарных опционов 60 секунд (h3)

Торговая стратегия бинарных опционов 60 секунд (h4)

Торговая стратегия бинарных опционов 60 секунд (h5-h6)

На рынке спокойное движение цены (пусть и не боковое, но относительно плавное);

Рыночная цена резко принимает значение, удаленное от общей тенденции на несколько пунктов;

Отсутствие новостей в данный момент (период).

                    « Считаю необходимым для начала рассказать, на чем именно
                    основан метод торговли, что бы было полное понимание
                    всего метода, а не бессмысленное
                    заучивание правил »

Комментарии

Наталья

                            Надеюсь, Вам понравятся результаты от торговли по моей стратегии бинарных опционов 60 секунд.
                            Потребуется некоторое время, что бы приноровиться ловить моменты отскока рыночной цены

Наталья

                            Надеюсь, Вам понравятся результаты от торговли по моей стратегии бинарных опционов 60 секунд.
                            Потребуется некоторое время, что бы приноровиться ловить моменты отскока рыночной цены

                    <form method="post" id="add_comment">

Оставить сообщение

                        <input type="text" name="name" placeholder="имя">

                        <textarea>сообщение</textarea>

                        <input type="submit" value="Отправить">
                    </form>

            */
            ?>

            <?=LastnewsWidget::widget([
                    'count' => 6,
                    'captionClass' => 'caption blue',
                    'parentCode' => 'on_events',
                    'caption'=>'Обзоры событий на бинарных опционах'
            ])?>

            <?=LastnewsWidget::widget([
                    'count' => 3,
                    'captionClass' => 'caption red',
                    'parentCode' => 'pamm',
                    'caption'=>'Заработок на инвестициях'
            ])?>


text:
<?php

namespace Sylius\Component\Resource\Metadata;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
interface MetadataInterface
{
    /**
     * @return string
     */
    public function getAlias();

    /**
     * @return string
     */
    public function getApplicationName();

    /**
     * @return string
     */
    public function getName();

    /**
     * @return string
     */
    public function getHumanizedName();

    /**
     * @return string
     */
    public function getPluralName();

    /**
     * @return string
     */
    public function getDriver();

    /**
     * @return string
     */
    public function getTemplatesNamespace();

    /**
     * @param string $name
     *
     * @throws \InvalidArgumentException
     *
     * @return string|array
     */
    public function getParameter($name);

    /**
     * Return all the metadata parameters.
     *
     * @return array
     */
    public function getParameters();

    /**
     * @param $name
     *
     * @return bool
     */
    public function hasParameter($name);

    /**
     * @param string $name
     *
     * @throws \InvalidArgumentException
     *
     * @return string|array
     */
    public function getClass($name);

    /**
     * @param $name
     *
     * @return bool
     */
    public function hasClass($name);

    /**
     * @param string $serviceName
     *
     * @return string
     */
    public function getServiceId($serviceName);

    /**
     * @param string $permissionName
     *
     * @return string
     */
    public function getPermissionCode($permissionName);
}


text:
use glium::{BackfaceCullingMode, Depth, DepthTest, DrawParameters, Program};
use glium::backend::{Facade};

pub struct ShadowProgram {
	pub program:    Program,
	pub parameters: DrawParameters<'static>,
}

impl ShadowProgram {
	pub fn new<F: Facade>(facade: &F) -> ShadowProgram {
		let program = {
			let vertex_source = r#"
				#version 140

				in vec3 position;

				uniform mat4 shadow;

				void main() {
					gl_Position = shadow * vec4(position, 1.0);
				}
			"#;
			let fragment_source = r#"
				#version 140
				void main() { }
			"#;
			Program::from_source(facade, vertex_source, fragment_source, None).expect("Unable to compile shadow shader")
		};

		ShadowProgram {
			program: program,
			parameters: DrawParameters {
				depth: Depth {
					test: DepthTest::IfLess,
					write: true,
					.. Default::default()
				},
				color_mask: (false, false, false, false),
				backface_culling: BackfaceCullingMode::CullClockwise,
				.. Default::default()
			},
		}
	}
}


text:
<?php
/**
 * Standard Change Password Form
 * @package sapphire
 * @subpackage security
 */
class ChangePasswordForm extends Form {

	/**
	 * Constructor
	 *
	 * @param Controller $controller The parent controller, necessary to
	 *                               create the appropriate form action tag.
	 * @param string $name The method on the controller that will return this
	 *                     form object.
	 * @param FieldSet|FormField $fields All of the fields in the form - a
	 *                                   {@link FieldSet} of {@link FormField}
	 *                                   objects.
	 * @param FieldSet|FormAction $actions All of the action buttons in the
	 *                                     form - a {@link FieldSet} of
	 */
	function __construct($controller, $name, $fields = null, $actions = null) {
		if(isset($_REQUEST['BackURL'])) {
			$backURL = $_REQUEST['BackURL'];
		} else {
			$backURL = Session::get('BackURL');
		}

		if(!$fields) {
			$fields = new FieldSet();
			if(Member::currentUser() && (!isset($_REQUEST['h']) || !Member::member_from_autologinhash($_REQUEST['h']))) {
				$fields->push(new PasswordField("OldPassword",_t('Member.YOUROLDPASSWORD', "Your old password")));
			}

			$fields->push(new PasswordField("NewPassword1", _t('Member.NEWPASSWORD', "New Password")));
			$fields->push(new PasswordField("NewPassword2", _t('Member.CONFIRMNEWPASSWORD', "Confirm New Password")));
		}
		if(!$actions) {
			$actions = new FieldSet(
				new FormAction("doChangePassword", _t('Member.BUTTONCHANGEPASSWORD', "Change Password"))
			);
		}

		if(isset($backURL)) {
			$fields->push(new HiddenField('BackURL', 'BackURL', $backURL));
		}

		parent::__construct($controller, $name, $fields, $actions);
	}

	/**
	 * Change the password
	 *
	 * @param array $data The user submitted data
	 */
	function doChangePassword(array $data) {
		if($member = Member::currentUser()) {
			// The user was logged in, check the current password
			if(empty($data['OldPassword']) || !$member->checkPassword($data['OldPassword'])->valid()) {
				$this->clearMessage();
				$this->sessionMessage(
					_t('Member.ERRORPASSWORDNOTMATCH', "Your current password does not match, please try again"),
					"bad"
				);
				Director::redirectBack();
				return;
			}
		}

		if(!$member) {
			if(Session::get('AutoLoginHash')) {
				$member = Member::member_from_autologinhash(Session::get('AutoLoginHash'));
			}

			// The user is not logged in and no valid auto login hash is available
			if(!$member) {
				Session::clear('AutoLoginHash');
				Director::redirect('loginpage');
				return;
			}
		}

		// Check the new password
		if(empty($data['NewPassword1'])) {
			$this->clearMessage();
			$this->sessionMessage(
				_t('Member.EMPTYNEWPASSWORD', "The new password can't be empty, please try again"),
				"bad");
			Director::redirectBack();
			return;
		}
		else if($data['NewPassword1'] == $data['NewPassword2']) {
			$isValid = $member->changePassword($data['NewPassword1']);
			if($isValid->valid()) {
				$this->clearMessage();
				$this->sessionMessage(
					_t('Member.PASSWORDCHANGED', "Your password has been changed, and a copy emailed to you."),
					"good");
				Session::clear('AutoLoginHash');

				if (isset($_REQUEST['BackURL'])
					&& $_REQUEST['BackURL']
					// absolute redirection URLs may cause spoofing
					&& Director::is_site_url($_REQUEST['BackURL'])
				) {
					Director::redirect($_REQUEST['BackURL']);
				}
				else {
					// Redirect to default location - the login form saying "You are logged in as..."
					$redirectURL = HTTP::setGetVar('BackURL', Director::absoluteBaseURL(), Security::Link('login'));
					Director::redirect($redirectURL);
				}
			} else {
				$this->clearMessage();
				$this->sessionMessage(
					sprintf(_t('Member.INVALIDNEWPASSWORD', "We couldn't accept that password: %s"), nl2br("\n".$isValid->starredList())),
					"bad"
				);
				Director::redirectBack();
			}

		} else {
			$this->clearMessage();
			$this->sessionMessage(
				_t('Member.ERRORNEWPASSWORD', "You have entered your new password differently, try again"),
				"bad");
			Director::redirectBack();
		}
	}

}

?>


text:
<?php

namespace Avro\CaseBundle\Twig\Extension;

use Avro\CaseBundle\Util\CaseConverter;

/**
 * Twig extension for case conversion
 *
 * @author Joris de Wit <joris.w.dewit@gmail.com>
 */
class CaseExtension extends \Twig_Extension
{
    protected $caseConverter;

    /**
     * @param CaseConverter $caseConverter
     */
    public function __construct(CaseConverter $caseConverter)
    {
        $this->caseConverter = $caseConverter;
    }

    /**
     * Get twig filters
     *
     * @return array filters
     */
    public function getFilters()
    {
        return array(
            'camel'   => new \Twig_Filter_Method($this, 'toCamelCase'),
            'pascal'   => new \Twig_Filter_Method($this, 'toPascalCase'),
            'underscore'   => new \Twig_Filter_Method($this, 'toUnderscoreCase'),
            'title'   => new \Twig_Filter_Method($this, 'toTitleCase')
        );
    }

    /**
     * Convert string to camel case format
     *
     * @param string $input
     *
     * @return string In camel case
     */
    public function toCamelCase($input)
    {
        return $this->caseConverter->toCamelCase($input);
    }

    /**
     * Convert string to pascal case format
     *
     * @param string $input
     *
     * @return string In pascal case
     */
    public function toPascalCase($input)
    {
        return $this->caseConverter->toPascalCase($input);
    }

    /**
     * Convert string to underscore case format
     *
     * @param string $input
     *
     * @return string In underscore case
     */
    public function toUnderscoreCase($input)
    {
        return $this->caseConverter->toUnderscoreCase($input);
    }

    /**
     * Convert string to title case format
     *
     * @param string $input
     *
     * @return string In title case
     */
    public function toTitleCase($input)
    {
        return $this->caseConverter->toTitleCase($input);
    }

    /**
     * Get twig extension name
     *
     * @return string
     */
    public function getName()
    {
        return 'CaseExtension';
    }
}


text:
package ru.job4j.tracker;
/**
 * Input.
 * @author Aleksandr Shigin
 * @version $Id$
 * @since 0.1
 */
public interface Input {
    /**
     * Ask.
     * @param question - question
     * @return scanner
     */
    String ask(String question);
    /**
     * Ask with range.
     * @param question - question
     * @param range - range
     * @return - scanner
     */
    int ask(String question, int[] range);
}


text:
class AddColumnSegundoCursoToMonitoria < ActiveRecord::Migration[5.0]
  def change
    add_column :monitorias, :segundo_curso, :string
  end
end


text:
#include "session_fixture.h"

#include <libssh2.h>

#include <stdio.h>

const char *USERNAME = "libssh2"; /* set in Dockerfile */
const char *KEY_FILE_PRIVATE = "key_rsa";
const char *KEY_FILE_PUBLIC = "key_rsa.pub"; /* set in Dockerfile */

int test(LIBSSH2_SESSION *session)
{
    int rc;
    LIBSSH2_CHANNEL *channel;

    const char *userauth_list =
        libssh2_userauth_list(session, USERNAME, strlen(USERNAME));
    if(userauth_list == NULL) {
        print_last_session_error("libssh2_userauth_list");
        return 1;
    }

    if(strstr(userauth_list, "publickey") == NULL) {
        fprintf(stderr, "'publickey' was expected in userauth list: %s\n",
                userauth_list);
        return 1;
    }

    rc = libssh2_userauth_publickey_fromfile_ex(
        session, USERNAME, strlen(USERNAME), KEY_FILE_PUBLIC, KEY_FILE_PRIVATE,
        NULL);
    if(rc != 0) {
        print_last_session_error("libssh2_userauth_publickey_fromfile_ex");
        return 1;
    }

    channel = libssh2_channel_open_session(session);
    /* if(channel == NULL) { */
    /*     printf("Error opening channel\n"); */
    /*     return 1; */
    /* } */

    rc = libssh2_channel_request_auth_agent(channel);
    if(rc != 0) {
        fprintf(stderr, "Auth agent request for agent forwarding failed, "
            "error code %d\n", rc);
        return 1;
    }

    return 0;
}


text:
require 'test_helper'

class RemoteNabTransactTest < Test::Unit::TestCase

  def setup
    @gateway = NabTransactGateway.new(fixtures(:nab_transact))
    @card_acceptor_gateway = NabTransactGateway.new(fixtures(:nab_transact_card_acceptor))

    @amount = 200
    @credit_card = credit_card('4444333322221111')

    @declined_card = credit_card('4111111111111234')

    @options = {
      :order_id => '1',
      :billing_address => address,
      :description => 'NAB Transact Purchase'
    }
  end

  # Order totals to simulate approved transactions:
  #   $1.00 $1.08 $105.00 $105.08 (or any total ending in 00, 08, 11 or 16)

  # Order totals to simulate declined transactions:
  #   $1.51 $1.05 $105.51 $105.05 (or any total not ending in 00, 08, 11 or 16)

  def test_successful_purchase
    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    assert_equal 'Approved', response.message
  end

  def test_unsuccessful_purchase_insufficient_funds
    #Any total not ending in 00/08/11/16
    failing_amount = 151 #Specifically tests 'Insufficient Funds'
    assert response = @gateway.purchase(failing_amount, @credit_card, @options)
    assert_failure response
    assert_equal 'Insufficient Funds', response.message
  end

  def test_unsuccessful_purchase_do_not_honour
    #Any total not ending in 00/08/11/16
    failing_amount = 105 #Specifically tests 'do not honour'
    assert response = @gateway.purchase(failing_amount, @credit_card, @options)
    assert_failure response
    assert_equal 'Do Not Honour', response.message
  end

  def test_unsuccessful_purchase_bad_credit_card
    assert response = @gateway.purchase(@amount, @declined_card, @options)
    assert_failure response
    assert_equal 'Invalid Credit Card Number', response.message
  end

  # Unfortunately there is no "real" way to test the dynamic card acceptor,
  # however the "Integration Guide - XML API for Payments" documentation states:
  #   If enabled on your NAB Transact account, the Dynamic Card Acceptor details
  #   will be accepted via metadata tags added to your XML request. Note that
  #   permission for this feature must be enabled on your account or you will
  #   receive a response of "555 – Permission denied".
  #
  # I couldn't find any other reference to this error code, so we can set the
  # fields on an account with the dynamic card acceptor feature disabled and
  # ensure we get the error.
  def test_successful_purchase_with_card_acceptor
    card_acceptor_options = {
      :merchant_name => 'ActiveMerchant',
      :merchant_location => 'Melbourne'
    }
    card_acceptor_options.each do |key, value|
      options = @options.merge({key => value})
      assert response = @gateway.purchase(@amount, @credit_card, options)
      assert_failure response
      assert_equal 'Permission denied', response.message

      assert response = @card_acceptor_gateway.purchase(@amount, @credit_card, options)
      assert_success response
      assert_equal 'Approved', response.message
    end
  end

  def test_successful_authorize
    assert response = @gateway.authorize(@amount, @credit_card, @options)
    assert_success response
    assert_equal 'Approved', response.message
  end

  def test_successful_capture
    assert auth = @gateway.authorize(@amount, @credit_card, @options)
    assert_success auth
    assert_equal 'Approved', auth.message

    authorization = auth.authorization

    assert capture = @gateway.capture(@amount, authorization)
    assert_success capture
    assert_equal 'Approved', capture.message
  end

  def test_unsuccessful_authorize_insufficient_funds
    # amount of 151 is the test amount for "Insufficient Funds"
    failing_amount = 151

    assert response = @gateway.authorize(failing_amount, @credit_card, @options)
    assert_failure response
    assert_equal 'Insufficient Funds', response.message
  end

  def test_unsuccessful_authorize_do_not_honour
    # amount of 105 for "Do Not Honour"
    failing_amount = 105

    assert response = @gateway.authorize(failing_amount, @credit_card, @options)
    assert_failure response
    assert_equal 'Do Not Honour', response.message
  end

  def test_unsuccessful_capture_amount_greater_than_authorized
    assert auth = @gateway.authorize(@amount, @credit_card, @options)
    assert_success auth
    assert_equal 'Approved', auth.message

    authorization = auth.authorization

    assert capture = @gateway.capture(@amount+100, authorization)
    assert_failure capture
    assert_equal 'Preauth was done for smaller amount', capture.message
  end

  def test_authorize_and_capture_with_card_acceptor
    card_acceptor_options = {
      :merchant_name => 'ActiveMerchant',
      :merchant_location => 'Melbourne'
    }
    card_acceptor_options.each do |key, value|
      options = @options.merge({key => value})
      assert response = @gateway.authorize(@amount, @credit_card, options)
      assert_failure response
      assert_equal 'Permission denied', response.message

      assert response = @card_acceptor_gateway.authorize(@amount, @credit_card, options)
      assert_success response
      assert_equal 'Approved', response.message

      authorization = response.authorization

      assert response = @card_acceptor_gateway.capture(@amount, authorization)
      assert_success response
      assert_equal 'Approved', response.message
    end
  end

  def test_successful_refund
    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    authorization = response.authorization
    assert response = @gateway.refund(@amount, authorization)
    assert_success response
    assert_equal 'Approved', response.message
  end

  def test_failed_refund
    assert response = @gateway.purchase(@amount, @credit_card, @options)
    assert_success response
    authorization = response.authorization
    assert response = @gateway.refund(@amount+1, authorization)
    assert_failure response
    assert_equal 'Only $2.0 available for refund', response.message
  end

  def test_invalid_login
    gateway = NabTransactGateway.new(
                :login => 'ABCFAKE',
                :password => 'changeit'
              )
    assert response = gateway.purchase(@amount, @credit_card, @options)
    assert_failure response
    assert_equal 'Invalid merchant ID', response.message
  end

  def test_successful_store
    @gateway.unstore(1234)

    assert response = @gateway.store(@credit_card, {:billing_id => 1234, :amount => 150})
    assert_success response
    assert_equal 'Successful', response.message
  end

  def test_unsuccessful_store
    @gateway.unstore(1235)

    assert response = @gateway.store(@declined_card, {:billing_id => 1235, :amount => 150})
    assert_failure response
    assert_equal 'Invalid Credit Card Number', response.message
  end

  def test_duplicate_store
    @gateway.unstore(1236)

    assert response = @gateway.store(@credit_card, {:billing_id => 1236, :amount => 150})
    assert_success response
    assert_equal 'Successful', response.message

    assert response = @gateway.store(@credit_card, {:billing_id => 1236, :amount => 150})
    assert_failure response
    assert_equal 'Duplicate CRN Found', response.message
  end

  def test_unstore
    gateway_id = '1234'
    @gateway.unstore(gateway_id)

    assert response = @gateway.store(@credit_card, {:billing_id => gateway_id, :amount => 150})
    assert_success response
    assert_equal 'Successful', response.message

    assert gateway_id = response.params["crn"]
    assert unstore_response = @gateway.unstore(gateway_id)
    assert_success unstore_response
  end

  def test_successful_trigger_purchase
    gateway_id = '1234'
    trigger_amount = 12000
    @gateway.unstore(gateway_id)

    assert response = @gateway.store(@credit_card, {:billing_id => gateway_id, :amount => 150})
    assert_success response
    assert_equal 'Successful', response.message

    purchase_response = @gateway.purchase(trigger_amount, gateway_id)

    assert gateway_id = purchase_response.params["crn"]
    assert trigger_amount = purchase_response.params["amount"]
    assert_success purchase_response
    assert_equal 'Approved', purchase_response.message
  end

  def test_failure_trigger_purchase
    gateway_id = '1234'
    trigger_amount = 0
    @gateway.unstore(gateway_id)

    assert response = @gateway.store(@credit_card, {:billing_id => gateway_id, :amount => 150})
    assert_success response
    assert_equal 'Successful', response.message

    purchase_response = @gateway.purchase(trigger_amount, gateway_id)

    assert gateway_id = purchase_response.params["crn"]
    assert_failure purchase_response
    assert_equal 'Invalid Amount', purchase_response.message
  end

end


text:
NS_ASSUME_NONNULL_BEGIN

typedef void (^CDRSpecBlock)(void);

@protocol CDRExampleParent

- (BOOL)shouldRun;

- (void)setUp;
- (nullable CDRSpecBlock)subjectActionBlock;
- (void)tearDown;

@optional
- (BOOL)hasFullText;
- (NSString *)fullText;
- (NSMutableArray *)fullTextInPieces;

- (NSUInteger)stackAddress;
@end

NS_ASSUME_NONNULL_END


text:
module.exports = ObjectMapBase;

// Abstract. Common methods between our map implementations
function ObjectMapBase() { }

ObjectMapBase.prototype['delete'] = function (key) {
    var has = this.has(key);
    delete this._obj[key];
    return has;
};

ObjectMapBase.prototype.get = function (key) {
    throw new Error('Method not implemented.');
};

ObjectMapBase.prototype.has = function (key) {
    throw new Error('Method not implemented.');
};

ObjectMapBase.prototype.set = function (key, value) {
    this._obj[key] = value;
    return this;
};


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _react = _interopRequireDefault(require("react"));

var _styledComponents = require("styled-components");

var _react2 = require("@testing-library/react");

var _VisWrapper = require("./VisWrapper");

describe('VisWrapper', function () {
  it('wraps itself in ComponentsProvider if rendered outside of theme context', function () {
    var CustomVis = function CustomVis() {
      var theme = (0, _styledComponents.useTheme)();
      return _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement("p", null, "Rendered Without Error!"), _react["default"].createElement("dl", null, _react["default"].createElement("dt", null, "Background Color:"), _react["default"].createElement("dd", null, theme.colors.background)));
    };

    (0, _react2.render)(_react["default"].createElement(_VisWrapper.VisWrapper, null, _react["default"].createElement(CustomVis, null)));
    expect(_react2.screen.getByText('Rendered Without Error!')).toBeInTheDocument();
  });
});
//# sourceMappingURL=VisWrapper.spec.js.map


text:
import EventEmitter from "wolfy87-eventemitter";

export default class Socket extends EventEmitter {

    emit () {
        var args = arguments;
        setTimeout(() => {
            super.emit.apply(this, args);
        }, 0);
    }

    constructor (SocketConstructor, endpoint) {
        super();
        this.SocketConstructor = SocketConstructor;
        this.endpoint = endpoint;
    }

    send (object) {
        var message = JSON.stringify(object);
        this.rawSocket.send(message);
        // Emit a copy of the object, as the listener might mutate it.
        this.emit("message:out", JSON.parse(message));
    }

    connect () {

        this.rawSocket = new this.SocketConstructor(this.endpoint);

        /*
        *   The `open`, `error` and `close` events are simply proxy-ed to `_socket`.
        *   The `message` event is instead parsed into a js object (if possible) and
        *   then passed as a parameter of the `message:in` event
        */

        this.rawSocket.onopen = () => this.emit("open");
        this.rawSocket.onerror = (error) => this.emit("error", error);
        this.rawSocket.onclose = () => this.emit("close");
        this.rawSocket.onmessage = (message) => {
            var object;
            try {
                object = JSON.parse(message.data);
            } catch (ignore) {
                // Simply ignore the malformed message and return
                return;
            }
            // Outside the try-catch block as it must only catch JSON parsing
            // errors, not errors that may occur inside a "message:in" event handler
            this.emit("message:in", object);
        };
    }

    close () {
        this.rawSocket.close();
    }

}