text:
namespace ZXing.Common.ReedSolomon
{
   ///
Implements Reed-Solomon decoding, as the name implies.

   ///
   ///
The algorithm will not be explained here, but the following references were helpful
   /// in creating this implementation:

   ///
   ///

   ///
Bruce Maggs.
   ///
   /// "Decoding Reed-Solomon Codes" (see discussion of Forney's Formula)

   ///
J.I. Hall.
   /// "Chapter 5. Generalized Reed-Solomon Codes"
   /// (see discussion of Euclidean algorithm)

   ///

   ///
   ///
Much credit is due to William Rucklidge since portions of this code are an indirect
   /// port of his C++ Reed-Solomon implementation.

   ///
   ///
   /// <author>  Sean Owen
   /// </author>
   /// <author>  William Rucklidge
   /// </author>
   /// <author>  sanfordsquires
   /// </author>
   /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source
   /// </author>
   public sealed class ReedSolomonDecoder
   {
      private readonly GenericGF field;

      public ReedSolomonDecoder(GenericGF field)
      {
         this.field = field;
      }

      ///
Decodes given set of received codewords, which include both data and error-correction
      /// codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,
      /// in the input.

      ///
      ///
      /// <param name="received">data and error-correction codewords
      /// </param>
      /// <param name="twoS">number of error-correction codewords available
      /// </param>
      /// <throws>  ReedSolomonException if decoding fails for any reason </throws>
      public bool decode(int[] received, int twoS)
      {
         GenericGFPoly poly = new GenericGFPoly(field, received);
         int[] syndromeCoefficients = new int[twoS];
         bool dataMatrix = field.Equals(GenericGF.DATA_MATRIX_FIELD_256);
         bool noError = true;
         for (int i = 0; i < twoS; i++)
         {
            // Thanks to sanfordsquires for this fix:
            int eval = poly.evaluateAt(field.exp(dataMatrix ? i + 1 : i));
            syndromeCoefficients[syndromeCoefficients.Length - 1 - i] = eval;
            if (eval != 0)
            {
               noError = false;
            }
         }
         if (noError)
         {
            return true;
         }
         GenericGFPoly syndrome = new GenericGFPoly(field, syndromeCoefficients);

         GenericGFPoly[] sigmaOmega = runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);
         if (sigmaOmega == null)
            return false;

         GenericGFPoly sigma = sigmaOmega[0];
         int[] errorLocations = findErrorLocations(sigma);
         if (errorLocations == null)
            return false;

         GenericGFPoly omega = sigmaOmega[1];
         int[] errorMagnitudes = findErrorMagnitudes(omega, errorLocations, dataMatrix);
         for (int i = 0; i < errorLocations.Length; i++)
         {
            int position = received.Length - 1 - field.log(errorLocations[i]);
            if (position < 0)
            {
               // throw new ReedSolomonException("Bad error location");
               return false;
            }
            received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);
         }

         return true;
      }

      private GenericGFPoly[] runEuclideanAlgorithm(GenericGFPoly a, GenericGFPoly b, int R)
      {
         // Assume a's degree is >= b's
         if (a.Degree = R / 2)
         {
            GenericGFPoly rLastLast = rLast;
            GenericGFPoly tLastLast = tLast;
            rLast = r;
            tLast = t;

            // Divide rLastLast by rLast, with quotient in q and remainder in r
            if (rLast.isZero)
            {
               // Oops, Euclidean algorithm already terminated?
               // throw new ReedSolomonException("r_{i-1} was zero");
               return null;
            }
            r = rLastLast;
            GenericGFPoly q = field.Zero;
            int denominatorLeadingTerm = rLast.getCoefficient(rLast.Degree);
            int dltInverse = field.inverse(denominatorLeadingTerm);
            while (r.Degree >= rLast.Degree && !r.isZero)
            {
               int degreeDiff = r.Degree - rLast.Degree;
               int scale = field.multiply(r.getCoefficient(r.Degree), dltInverse);
               q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));
               r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));
            }

            t = q.multiply(tLast).addOrSubtract(tLastLast);
         }

         int sigmaTildeAtZero = t.getCoefficient(0);
         if (sigmaTildeAtZero == 0)
         {
            // throw new ReedSolomonException("sigmaTilde(0) was zero");
            return null;
         }

         int inverse = field.inverse(sigmaTildeAtZero);
         GenericGFPoly sigma = t.multiply(inverse);
         GenericGFPoly omega = r.multiply(inverse);
         return new GenericGFPoly[] { sigma, omega };
      }

      private int[] findErrorLocations(GenericGFPoly errorLocator)
      {
         // This is a direct application of Chien's search
         int numErrors = errorLocator.Degree;
         if (numErrors == 1)
         {
            // shortcut
            return new int[] { errorLocator.getCoefficient(1) };
         }
         int[] result = new int[numErrors];
         int e = 0;
         for (int i = 1; i < field.Size && e < numErrors; i++)
         {
            if (errorLocator.evaluateAt(i) == 0)
            {
               result[e] = field.inverse(i);
               e++;
            }
         }
         if (e != numErrors)
         {
            // throw new ReedSolomonException("Error locator degree does not match number of roots");
            return null;
         }
         return result;
      }

      private int[] findErrorMagnitudes(GenericGFPoly errorEvaluator, int[] errorLocations, bool dataMatrix)
      {
         // This is directly applying Forney's Formula
         int s = errorLocations.Length;
         int[] result = new int[s];
         for (int i = 0; i < s; i++)
         {
            int xiInverse = field.inverse(errorLocations[i]);
            int denominator = 1;
            for (int j = 0; j < s; j++)
            {
               if (i != j)
               {
                  //denominator = field.multiply(denominator,
                  //    GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
                  // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.
                  // Below is a funny-looking workaround from Steven Parkes
                  int term = field.multiply(errorLocations[j], xiInverse);
                  int termPlus1 = (term & 0x1) == 0 ? term | 1 : term & ~1;
                  denominator = field.multiply(denominator, termPlus1);

                  // removed in java version, not sure if this is right
                  // denominator = field.multiply(denominator, GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)));
               }
            }
            result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator));
            // Thanks to sanfordsquires for this fix:
            if (dataMatrix)
            {
               result[i] = field.multiply(result[i], xiInverse);
            }
         }
         return result;
      }
   }
}


text:
pycodestyle (formerly called pep8) - Python style guide checker
===============================================================

.. image:: https://github.com/PyCQA/pycodestyle/actions/workflows/main.yml/badge.svg
   :target: https://github.com/PyCQA/pycodestyle/actions/workflows/main.yml
   :alt: Build status

.. image:: https://readthedocs.org/projects/pycodestyle/badge/?version=latest
    :target: https://pycodestyle.pycqa.org
    :alt: Documentation Status

.. image:: https://img.shields.io/pypi/wheel/pycodestyle.svg
   :target: https://pypi.org/project/pycodestyle/
   :alt: Wheel Status

.. image:: https://badges.gitter.im/PyCQA/pycodestyle.svg
   :alt: Join the chat at https://gitter.im/PyCQA/pycodestyle
   :target: https://gitter.im/PyCQA/pycodestyle?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge

pycodestyle is a tool to check your Python code against some of the style
conventions in `PEP 8`_.

.. _PEP 8: http://www.python.org/dev/peps/pep-0008/

.. note::

    This package used to be called ``pep8`` but was renamed to ``pycodestyle``
    to reduce confusion. Further discussion can be found `in the issue where
    Guido requested this
    change <https://github.com/PyCQA/pycodestyle/issues/466>`_, or in the
    lightning talk at PyCon 2016 by @IanLee1521:
    `slides <https://speakerdeck.com/ianlee1521/pep8-vs-pep-8>`_
    `video <https://youtu.be/PulzIT8KYLk?t=36m>`_.

Features
--------

* Plugin architecture: Adding new checks is easy.

* Parseable output: Jump to error location in your editor.

* Small: Just one Python file, requires only stdlib. You can use just
  the ``pycodestyle.py`` file for this purpose.

* Comes with a comprehensive test suite.

Installation
------------

You can install, upgrade, and uninstall ``pycodestyle.py`` with these commands::

  $ pip install pycodestyle
  $ pip install --upgrade pycodestyle
  $ pip uninstall pycodestyle

There's also a package for Debian/Ubuntu, but it's not always the
latest version.

Example usage and output
------------------------

::

  $ pycodestyle --first optparse.py
  optparse.py:69:11: E401 multiple imports on one line
  optparse.py:77:1: E302 expected 2 blank lines, found 1
  optparse.py:88:5: E301 expected 1 blank line, found 0
  optparse.py:222:34: W602 deprecated form of raising exception
  optparse.py:347:31: E211 whitespace before '('
  optparse.py:357:17: E201 whitespace after '{'
  optparse.py:472:29: E221 multiple spaces before operator
  optparse.py:544:21: W601 .has_key() is deprecated, use 'in'

You can also make ``pycodestyle.py`` show the source code for each error, and
even the relevant text from PEP 8::

  $ pycodestyle --show-source --show-pep8 testsuite/E40.py
  testsuite/E40.py:2:10: E401 multiple imports on one line
  import os, sys
           ^
      Imports should usually be on separate lines.

      Okay: import os\nimport sys
      E401: import sys, os

Or you can display how often each error was found::

  $ pycodestyle --statistics -qq Python-2.5/Lib
  232     E201 whitespace after '['
  599     E202 whitespace before ')'
  631     E203 whitespace before ','
  842     E211 whitespace before '('
  2531    E221 multiple spaces before operator
  4473    E301 expected 1 blank line, found 0
  4006    E302 expected 2 blank lines, found 1
  165     E303 too many blank lines (4)
  325     E401 multiple imports on one line
  3615    E501 line too long (82 characters)
  612     W601 .has_key() is deprecated, use 'in'
  1188    W602 deprecated form of raising exception

Links
-----

* `Read the documentation <https://pycodestyle.pycqa.org/>`_

* `Fork me on GitHub <http://github.com/PyCQA/pycodestyle>`_

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.CompilerServices;
using Floobits.Common;
using Floobits.Common.Protocol;
using Floobits.Common.Protocol.Handlers;
using Floobits.Common.Interfaces;
using Floobits.Utilities;

namespace Floobits.Common.Protocol.Buf
{
    public class BinaryBuf : BufTempl<byte[]>
    {

        public BinaryBuf(string path, int? id, byte[] buf, string md5, IContext context, OutboundRequestHandler outbound) :
            base(path, id, buf, md5, context, outbound)
        {
            this.encoding = Encoding.BASE64;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public override void read()
        {
            IFile virtualFile = getVirtualFile();
            if (virtualFile == null)
            {
                Flog.warn("Couldn't get virtual file in readFromDisk {0}", this);
                return;
            }

            byte[] bytes = virtualFile.getBytes();
            if (bytes == null)
            {
                Flog.warn("Could not get byte array contents for file {0}", this);
                return;
            }
            buf = bytes;
            md5 = DigestUtils.md5Hex(bytes);
        }

        public override void write()
        {
            context.writeThread(delegate
            {
                if (!isPopulated())
                {
                    Flog.warn("Unable to write {0} because it's not populated yet.", path);
                    return;
                }
                IFile virtualFile = getOrCreateFile();
                if (virtualFile == null)
                {
                    context.errorMessage("Unable to write file. virtualFile is null.");
                    return;
                }
                FlooHandler flooHandler = context.getFlooHandler();
                if (flooHandler == null)
                {
                    return;
                }
                lock (context)
                {
                    try
                    {
                        context.setListener(false);
                        if (!virtualFile.setBytes(buf))
                        {
                            Flog.warn("Writing binary content to disk failed. {0}", path);
                        }
                    }
                    finally
                    {
                        context.setListener(true);
                    }
                }
            });
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public override void set(string s, string md5)
        {
            if (s == null)
            {
                buf = new byte[] { };
            }
            else
            {
                buf = Convert.FromBase64String(s);
            }
            this.md5 = md5;
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void set(byte[] s, string md5)
        {
            buf = s;
            this.md5 = md5;
        }

        public override string serialize()
        {
            return Convert.ToBase64String(buf);
        }

        public override void patch(FlooPatch res)
        {
            FlooHandler flooHandler = context.getFlooHandler();
            if (flooHandler == null)
            {
                return;
            }
            flooHandler.outbound.getBuf(this.id.Value);
            set((byte[])null, null);
        }

        public override void send_patch(IFile virtualFile)
        {
            FlooHandler flooHandler = context.getFlooHandler();
            if (flooHandler == null)
            {
                return;
            }
            byte[] contents = virtualFile.getBytes();
            if (contents == null)
            {
                Flog.warn("Couldn't read contents of binary file. {0}", virtualFile);
                return;
            }
            string after_md5 = DigestUtils.md5Hex(contents);
            if (md5.Equals(after_md5))
            {
                Flog.debug("Binary file change event but no change in md5 {0}", virtualFile);
                return;
            }
            set(contents, after_md5);
            flooHandler.outbound.setBuf(this);
        }
    }
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.concurrency;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

public abstract class AsyncValueLoader<T> {
  private final AtomicReference<Promise<T>> ref = new AtomicReference<>();

  private volatile long modificationCount;
  private volatile long loadedModificationCount;

  private final Consumer<T> doneHandler = new Consumer<T>() {
    @Override
    public void accept(T o) {
      loadedModificationCount = modificationCount;
    }
  };

  @NotNull
  public final Promise<T> get() {
    return get(true);
  }

  public final T getResultIfFullFilled() {
    Promise<T> result = ref.get();
    try {
      return (result != null && result.isSucceeded()) ? result.blockingGet(0) : null;
    }
    catch (TimeoutException | ExecutionException e) {
      return null;
    }
  }

  public final void reset() {
    Promise<T> oldValue = ref.getAndSet(null);
    if (oldValue instanceof AsyncPromise) {
      rejectAndDispose((AsyncPromise<T>)oldValue);
    }
  }

  private void rejectAndDispose(@NotNull AsyncPromise<T> asyncResult) {
    if (asyncResult.setError("rejected")) {
      return;
    }

    T result;
    try {
      result = asyncResult.blockingGet(0);
    }
    catch (TimeoutException e) {
      throw new RuntimeException(e);
    }
    catch (ExecutionException e) {
      throw new RuntimeException(e.getCause());
    }

    if (result != null) {
      disposeResult(result);
    }
  }

  protected void disposeResult(@NotNull T result) {
    if (result instanceof Disposable) {
      Disposer.dispose((Disposable)result, false);
    }
  }

  @NotNull
  public final Promise<T> get(boolean checkFreshness) {
    Promise<T> promise = ref.get();
    if (promise == null) {
      if (!ref.compareAndSet(null, promise = new AsyncPromise<>())) {
        return ref.get();
      }
    }
    else {
      Promise.State state = promise.getState();
      if (state == Promise.State.PENDING) {
        // if current promise is not processed, so, we don't need to check cache state
        return promise;
      }
      else if (state == Promise.State.SUCCEEDED) {
        //noinspection unchecked
        if (!checkFreshness || isUpToDate()) {
          return promise;
        }

        if (!ref.compareAndSet(promise, promise = new AsyncPromise<>())) {
          Promise<T> valueFromAnotherThread = ref.get();
          while (valueFromAnotherThread == null) {
            if (ref.compareAndSet(null, promise)) {
              return getPromise((AsyncPromise<T>)promise);
            }
            else {
              valueFromAnotherThread = ref.get();
            }
          }
          return valueFromAnotherThread;
        }
      }
    }

    return getPromise((AsyncPromise<T>)promise);
  }

  /**
   * if result was rejected, by default this result will not be canceled - call get() will return rejected result instead of attempt to load again,
   * but you can change this behavior - return true if you want to cancel result on reject
   */
  protected boolean isCancelOnReject() {
    return false;
  }

  @NotNull
  private Promise<T> getPromise(@NotNull AsyncPromise<T> promise) {
    final Promise<T> effectivePromise;
    try {
      effectivePromise = load(promise);
      if (effectivePromise != promise) {
        ref.compareAndSet(promise, effectivePromise);
      }
    }
    catch (Throwable e) {
      ref.compareAndSet(promise, null);
      rejectAndDispose(promise);
      //noinspection InstanceofCatchParameter
      throw e instanceof RuntimeException ? ((RuntimeException)e) : new RuntimeException(e);
    }

    effectivePromise.onSuccess(doneHandler);
    if (isCancelOnReject()) {
      effectivePromise.onError(throwable -> ref.compareAndSet(effectivePromise, null));
    }

    if (effectivePromise != promise) {
      effectivePromise.processed(promise);
    }
    return effectivePromise;
  }

  @NotNull
  protected abstract Promise<T> load(@NotNull AsyncPromise<T> result) throws IOException;

  private boolean isUpToDate() {
    return loadedModificationCount == modificationCount;
  }

  public final void set(@NotNull T result) {
    Promise<T> oldValue = ref.getAndSet(Promise.resolve(result));
    if (oldValue instanceof AsyncPromise) {
      rejectAndDispose((AsyncPromise<T>)oldValue);
    }
  }

  public final void markDirty() {
    modificationCount++;
  }
}


text:
/**
 * app
 * @author lifuqiang
 */
import React, { Component } from 'react';
import {
    StyleSheet,
    Navigator
} from 'react-native';

import AV from 'leancloud-storage';
import {
    Router,
    Scene,
    ActionConst
} from 'react-native-router-flux';
import { connect } from 'react-redux';
import Splash from '../pages/Splash';
import CategoryContainer from '../containers/CategoryContainer';
import MainContainer from '../containers/MainContainer';
import Feedback from '../pages/Feedback';
import About from '../pages/About';
import WebViewPage from '../pages/WebViewPage';
import TabIcon from '../components/TabIcon';

const RouterWithRedux = connect()(Router);
const backButton = require('../img/arrow_left.png');

const getSceneStyle = (props, computeProps) => {
    const style = {
        flex: 1,
        backgroundColor: '#fff',
        shadowColor: null,
        shadowOffset: null,
        shadowOpacity: null,
        shadowRadius: null,
    };

    if (computeProps.isActive) {
        style.marginTop = computeProps.hideNavBar ?
            0 : Navigator.NavigationBar.Styles.General.TotalNavHeight;
        style.marginBottom = computeProps.hideTabBar ? 0 : 50;
    }

    //console.log(style.marginTop);
    //console.log(style.marginBottom);

    return style;
}

class App extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {

    }

    render() {
        return (
            <RouterWithRedux
                getSceneStyle={getSceneStyle}
                navigationBarStyle={styles.navBar}
                titleStyle={styles.navBarTitle}
                backButtonImage={backButton}
            >
                <Scene key="root">
                    <Scene key="splash" component={Splash} hideNavBar hideTabBar initial />
                    <Scene
                        key="initCategory"
                        component={CategoryContainer}
                        hideNavBar
                        hideTabBar
                        type={ActionConst.REPLACE}
                    />
                    <Scene key="tabbar" tabs pressOpacity={0.8} type={ActionConst.REPLACE} tabBarStyle={styles.tabBarStyle}>
                        <Scene
                            key="main"
                            component={MainContainer}
                            hideNavBar
                            title="阅读"
                            icon={TabIcon}
                            iconName="md-home"
                        />
                        <Scene
                            key="category"
                            component={CategoryContainer}
                            title="分类"
                            icon={TabIcon}
                            iconName="md-pricetags"
                        />
                        <Scene
                            key="feedback"
                            component={Feedback}
                            title="建议"
                            icon={TabIcon}
                            iconName="md-thumbs-up"
                        />
                        <Scene
                            key="about"
                            component={About}
                            title="关于"
                            icon={TabIcon}
                            iconName="md-information-circle"
                        />
                    </Scene>
                </Scene>
                <Scene key="web" hideTabBar component={WebViewPage} />
            </RouterWithRedux>
        );
    }
}

const styles = StyleSheet.create({
    navBar: {
        backgroundColor: '#3e9ce9'
    },
    navBarTitle: {
        color: '#ffffff',
        fontSize: 20,
    },
    tabBarStyle: {
        backgroundColor: '#a2c4c9',
    },

});

export default App;


text:
"""Functions for interacting with yaml configuration files."""

import re
from typing import Any
from glazier.lib import file_util
import yaml

from glazier.lib import download
from glazier.lib import errors

class Error(errors.GlazierError):
  pass

class FileMoveError(Error):

  def __init__(self, src: str, dest: str):
    super().__init__(
        error_code=errors.ErrorCode.FILE_MOVE_ERROR,
        message=f'Failed to move file from {src} to {dest}')

class FileRemoveError(Error):

  def __init__(self, path: str):
    super().__init__(
        error_code=errors.ErrorCode.FILE_REMOVE_ERROR,
        message=f'Failed to remove file: {path}')

class FileWriteError(Error):

  def __init__(self, path: str):
    super().__init__(
        error_code=errors.ErrorCode.FILE_WRITE_ERROR,
        message=f'Failed to write file: {path}')

class FileReadError(Error):

  def __init__(self, path: str):
    super().__init__(
        error_code=errors.ErrorCode.FILE_READ_ERROR,
        message=f'Failed to read file: {path}')

class FileDownloadError(Error):

  def __init__(self, url: str):
    super().__init__(
        error_code=errors.ErrorCode.FILE_DOWNLOAD_ERROR,
        message=f'Could not download file: {url}')

def Remove(path: str, backup: bool = True):
  """Remove a config file.

  Args:
    path: The filesystem path to the file.
    backup: Whether to make a backup of the file being removed.

  Raises:
    Error: Failure performing the filesystem operation.
  """
  if backup:
    try:
      file_util.Move(path, path + '.bak')
    except file_util.Error as e:
      raise FileMoveError(path, path + '.bak') from e
  else:
    try:
      file_util.Remove(path)
    except file_util.Error as e:
      raise FileRemoveError(path) from e

def Dump(path: str, data: Any, mode: str = 'w'):
  """Write a config file containing some data.

  Args:
    path: The filesystem path to the destination file.
    data: Data to be written to the file as yaml.
    mode: Mode to use for writing the file (default: w)
  """
  file_util.CreateDirectories(path)
  tmp_f = path + '.tmp'

  # Write to a .tmp file to avoid corrupting the original if aborted mid-way.
  try:
    with open(tmp_f, mode) as handle:
      handle.write(yaml.dump(data))
  except IOError as e:
    raise FileWriteError(path) from e

  # Replace the original with the tmp.
  try:
    file_util.Move(tmp_f, path)
  except file_util.Error as e:
    raise FileMoveError(tmp_f, path) from e

def Read(path: str):
  """Read a config file at path and return any data it contains.

  Will attempt to download files from remote repositories prior to reading.

  Args:
    path: The path (either local or remote) to read from.

  Returns:
    The parsed YAML content from the file.

  Raises:
    Error: Failure retrieving a remote file or parsing file content.
  """
  if re.match('^http(s)?://', path):
    downloader = download.Download()
    try:
      path = downloader.DownloadFileTemp(path)
    except download.Error as e:
      raise FileDownloadError(path) from e
  return _YamlReader(path)

def _YamlReader(path: str) -> str:
  """Read a configuration file and return the contents.

  Can be overloaded to read configs from different sources.

  Args:
    path: The config file name (eg build.yaml).

  Returns:
    The parsed content of the yaml file.
  """
  try:
    with open(path, 'r') as yaml_file:
      yaml_config = yaml.safe_load(yaml_file)
  except IOError as e:
    raise FileReadError(path) from e
  return yaml_config


text:
// manages rendering (NOT FINISHED YET)

#pragma once

#include <functional>
#include <CL/cl.hpp>
#include <cstddef>
#include <vector>
#include <map>

#include "render/frame.hpp"

class Engine
{
    public:
        enum Module
        {
            SUBSAMPLER,
            PROJECTION,
            INTEGRATOR,
        };

        /** Creates a new Engine with an initial set of parameters.
          *
          * @param subsampler  Initial subsampler module.
          * @param projection  Initial projection module.
          * @param integrator  Initial integrator module.
          * @param image       OpenGL/OpenCL image to draw into.
        **/
        Engine(const cl::Program &subsampler,
               const cl::Program &projection,
               const cl::Program &integrator,
               const cl::ImageGL &image);

        /** Resizes the frame to new dimensions.
          *
          * @param image   New image.
        **/
        void resize_frame(const cl::ImageGL &image);

        /** Sets up a new module for rendering, replacing the previous one.
          *
          * @param type    The module type.
          * @param module  The loaded module program.
        **/
        void set_module(Module type, const cl::Program &module);

        /** Clears the frame completely.
        **/
        void clear_frame(void);

        /** Adds another sample to the frame.
        **/
        void sample(void);

        void draw(void); // this is where the post-processing goes

        /** Convenience function which attaches an arbitrary object, as long as
          * it has an accessible \c notify_cb callback member function with the
          * right parameters.
        **/
        template <typename T>
        void attach(T &obj)
        {
            attach(std::bind(&T::notify_cb, &obj, std::placeholders::_1));
        }

    private:
        /** Registers a callback function to be called whenever the kernels are
          * regenerated (e.g. after linking) for the caller to rebind itself.
          *
          * @param callback  Callback function to be called.
          *
          * @remarks The argument to this callback function will be a const map
          *          mapping kernel names to kernel objects - the object should
          *          bind its OpenCL resources to the appropriate kernel.
        **/
        void attach(const std::function
                    <void(std::map<std::string, cl::Kernel>&)>
                    &callback);

        /** Notifies all registered callbacks kernels have been regenerated.
        **/
        void notify(void);

        /** The list of callbacks registered by \c attach().
        **/
        std::vector<std::function
                    <void(std::map<std::string, cl::Kernel>&)>> callbacks;

        /** Links all currently loaded programs and generates kernels.
        **/
        void link(void);

        std::map<std::string, cl::Kernel> kernels;
        std::map<Module, cl::Program> modules;
        std::vector<cl::Program> core;
        cl::Program program;
        Frame frame;
};


text:
Popped Kettlecorn

        Kettlecorn vendor for sale and events

        Upcoming events
        Manage events


text:
<?php
/**
 * GroupController.php
 * Created by @anonymoussc on 29/12/15 21:16.
 */

namespace Componeint\Seneschal\Controllers;

use Componeint\AppFoundation\Controller\Controller;
use Vinkla\Hashids\HashidsManager;
use Illuminate\Pagination\Paginator;
use Componeint\Seneschal\FormRequests\GroupCreateRequest;
use Componeint\Seneschal\FormRequests\GroupUpdateRequest;
use Componeint\Seneschal\Repositories\Group\GroupRepositoryInterface;
use Componeint\Seneschal\Traits\SeneschalRedirectionTrait;
use Componeint\Seneschal\Traits\SeneschalViewfinderTrait;
use View;
use Input;
use Redirect;

class GroupController extends Controller
{
    use SeneschalRedirectionTrait;
    use SeneschalViewfinderTrait;

    public function __construct(GroupRepositoryInterface $groupRepository, HashidsManager $hashids)
    {
        $this->groupRepository = $groupRepository;
        $this->hashids         = $hashids;

        // You must have admin access to proceed
        // $this->middleware('sentry.admin');
    }

    public function index()
    {
        // Paginate the existing users
        // $groups      = $this->groupRepository->all();
        // $perPage     = 15;
        // $currentPage = Input::get('page') - 1;
        // $pagedData   = array_slice($groups, $currentPage * $perPage, $perPage);
        // $groups      = new Paginator($pagedData, $perPage, $currentPage);

        // return $this->viewFinder('Seneschal::groups.index', ['groups' => $groups]);

        $groups = $this->groupRepository->all();

        // $result = ['count' => count($groups), 'lists' => $groups];

        return response()->json(['count' => count($groups), 'data' => $groups]);
    }

    public function create()
    {
        //
    }

    public function store(GroupCreateRequest $request)
    {
        $data   = $request->all();
        $result = $this->groupRepository->store($data);

        // return $this->redirectViaResponse('groups_store', $result);
        return response()->success([$result]);
    }

    public function show($id)
    {
        $group = $this->groupRepository->retrieveById($id);

        return response()->success([$group]);
    }

    public function edit($id)
    {
        $group  = $this->groupRepository->retrieveById($id);
        $result = [
            'group'       => $group,
            'permissions' => $group->getPermissions(),
        ];

        return response()->success([$result]);
    }

    public function update(GroupUpdateRequest $request)
    {
        $data   = $request->all();
        $result = $this->groupRepository->update($data);

        return response()->success([$result]);
    }

    public function destroy($id)
    {
        $result = $this->groupRepository->destroy($id);

        return response()->success([$result]);
    }
}


text:
using log4net;
using log4net.Config;
using System;

namespace Common
{
    public class LogManagerFacade : ILoggerFactory
    {
        public LogManagerFacade()
        {
            XmlConfigurator.Configure();
        }

        public ILog GetLogger(Type type)
        {
            return LogManager.GetLogger(type);
        }
    }
}


text:
package googlemanagedprometheusexporter // import "github.com/open-telemetry/opentelemetry-collector-contrib/exporter/googlemanagedprometheusexporter"

import (
	"fmt"

	"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector"
	"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector/googlemanagedprometheus"
	"go.opentelemetry.io/collector/config"
	"go.opentelemetry.io/collector/exporter/exporterhelper"
)

// Config defines configuration for Google Cloud Managed Service for Prometheus exporter.
type Config struct {
	config.ExporterSettings `mapstructure:",squash"`
	GMPConfig               `mapstructure:",squash"`

	// Timeout for all API calls. If not set, defaults to 12 seconds.
	exporterhelper.TimeoutSettings `mapstructure:",squash"` // squash ensures fields are correctly decoded in embedded struct.
	exporterhelper.QueueSettings   `mapstructure:"sending_queue"`
	exporterhelper.RetrySettings   `mapstructure:"retry_on_failure"`
}

// GMPConfig is a subset of the collector config applicable to the GMP exporter.
type GMPConfig struct {
	ProjectID    string       `mapstructure:"project"`
	UserAgent    string       `mapstructure:"user_agent"`
	MetricConfig MetricConfig `mapstructure:"metric"`
}

type MetricConfig struct {
	// Prefix configures the prefix of metrics sent to GoogleManagedPrometheus.  Defaults to prometheus.googleapis.com.
	// Changing this prefix is not recommended, as it may cause metrics to not be queryable with promql in the Cloud Monitoring UI.
	Prefix       string                 `mapstructure:"prefix"`
	ClientConfig collector.ClientConfig `mapstructure:",squash"`
}

func (c *GMPConfig) toCollectorConfig() collector.Config {
	// start with whatever the default collector config is.
	cfg := collector.DefaultConfig()
	cfg.MetricConfig.Prefix = c.MetricConfig.Prefix
	if c.MetricConfig.Prefix == "" {
		cfg.MetricConfig.Prefix = "prometheus.googleapis.com"
	}
	cfg.MetricConfig.SkipCreateMetricDescriptor = true
	cfg.MetricConfig.InstrumentationLibraryLabels = false
	cfg.MetricConfig.ServiceResourceLabels = false
	// Update metric naming to match GMP conventions
	cfg.MetricConfig.GetMetricName = googlemanagedprometheus.GetMetricName
	// Map to the prometheus_target monitored resource
	cfg.MetricConfig.MapMonitoredResource = googlemanagedprometheus.MapToPrometheusTarget
	cfg.MetricConfig.EnableSumOfSquaredDeviation = true
	// map the GMP config's fields to the collector config
	cfg.ProjectID = c.ProjectID
	cfg.UserAgent = c.UserAgent
	cfg.MetricConfig.ClientConfig = c.MetricConfig.ClientConfig
	return cfg
}

func (cfg *Config) Validate() error {
	if err := collector.ValidateConfig(cfg.toCollectorConfig()); err != nil {
		return fmt.Errorf("exporter settings are invalid :%w", err)
	}
	return nil
}


text:
const Cubbyhole = require('cubbyhole')

const Future = require('perhaps')

const { Staccato } = require('staccato')
const Conduit = require('conduit')

const { Queue } = require('avenue')

const Olio = require('./olio')

const Keyify = require('keyify')

const logger = require('prolific.logger').create('olio')

const { Recorder, Player } = require('transcript')

// TODO It makes more sense to wait for all the children to register before
// returning the Olio so that we at least know that that much is working and so
// that a failed startup doesn't report in user code if it doesn't have to.

class Dispatcher {
    constructor (destructible, transmitter) {
        this._destructible = destructible
        this.olio = new Future
        this.transmitter = transmitter
        this.destructible = destructible
        this.destroyed = false
        destructible.destruct(() => this.destroyed = true)
        this.ready = new Cubbyhole
        this.registered = new Cubbyhole
    }

    async fromSibling (message, socket) {
        const [ olio ] = await this.olio.promise
        olio.emit(message.name, message.body, socket)
        return null
    }

    // TODO Add PQueue.
    async fromParent (message, socket) {
        if (this.destroyed) {
            if (socket != null) {
                socket.destroy()
            }
            return
        }
        switch (message.method) {
        case 'initialize': {
                const destructible = this._destructible.durable('olio')
                this.olio.resolve([ new Olio(destructible, this, message), message.source, message.properties ])
            }
            break
        case 'registered': {
                this.registered.resolve(Keyify.stringify([ message.name, message.index ]), {
                    name: message.name,
                    index: message.index,
                    address: message.address,
                    count: message.count
                })
            }
            break
        case 'connect': {
                // TODO This is also swallowing errors somehow.
                const destructible = this.destructible.durable([
                    'receiver', message.from.name, message.from.index
                ].join('.'))
                socket.on('error', logger.stackTrace({ message: message }))
                socket.on('close', () => destructible.destroy())
                const inbox = new Queue, outbox = new Queue, staccato = new Staccato(socket)
                const recorder = Recorder.create(() => 0)
                destructible.durable('serialize', async () => {
                    for await (const buffers of outbox.shifter()) {
                        await staccato.writable.write([ recorder([ buffers ]) ])
                    }
                    staccato.writable.end()
                    destructible.destroy()
                })
                const player = new Player(() => 0)
                destructible.durable('deserialize', async () => {
                    for await (const buffer of staccato.readable) {
                        for await (const entry of player.split(buffer)) {
                            inbox.push(entry.parts)
                        }
                    }
                    destructible.destroy()
                    inbox.push(null)
                })
                const conduit = new Conduit(destructible.durable('conduit'), inbox.shifter(), outbox, this.receiver)
                socket.write(JSON.stringify({ module: 'olio', method: 'connect' }) + '\n')
            }
            break
        case 'created': {
                this.ready.resolve(message.name, {
                    name: message.name,
                    addresses: message.addresses,
                    count: message.count
                })
            }
            break
        }
    }
}

module.exports = Dispatcher


text:
from redis import Redis
from config.getconfig import getconfig

class rclient(object):
	def __init__(self):
		rec = getconfig()["redis"]
		self.conn =  Redis(host=rec["host"],port=int(rec["port"]),db=int(rec['db']))
	def set(self,key,value):
		self.conn.set(key,value)
	def get(self,key):
		return self.conn.get(key)


text:
package dk.lessismore.nojpa.reflection.attributeconverters;
/**
 * This class can convert a String or Object to an string and back again.
 *
 * @version 1.0 21-5-2
 * @author LESS-IS-MORE
 */
public class StringConverter extends AttributeConverter {

    public Object stringToObject(String str) {
        return str;
    }

    public String objectToString(Object object) {
        return object.toString();
    }
    protected Class getObjectClass() {
        return String.class;
    }
}


text:
//
//  TRNavigationController.m
//  TRHouse
//
//  Created by wgf on 16/9/19.
//  Copyright © 2016年 wgf. All rights reserved.
//

#import "TRNavigationController.h"

@interface TRNavigationController ()

@end

@implementation TRNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationBar.barTintColor = TRColor(0, 220, 255, 1.0);
    UINavigationBar *navBar = [UINavigationBar appearance];
    [navBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}];
    [navBar setTintColor:[UIColor whiteColor]];

}

//重写pushViewController拦截导航栏的一些东西
- (void) pushViewController:(UIViewController *)viewController animated:(BOOL)animated {

    if (self.childViewControllers.count > 0) {

        viewController.hidesBottomBarWhenPushed = YES;
    }

    [super pushViewController:viewController animated:animated];

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<title>reverse running animation</title>
<link rel="match" href="reverse-running-animation-ref.html">

    This test animates the box color from green to red and reverses the play
    direction shortly after the midpoint. If the box remains red, the test
    failed.


text:
<?php

namespace app\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Expression;
use yii\helpers\VarDumper;

/**
 * This is the model class for table "users".
 *
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $status
 * @property string $auth_key
 * @property string $token
 * @property integer $isAdmin
 * @property string $activation_token
 * @property string $activation_at
 * @property string $password_reset_token
 * @property string $password_reset_at
 * @property string $created_at
 * @property string $updated_at
 */
class User extends ActiveRecord implements \yii\web\IdentityInterface
{
    const STATUS_NEW = 'new';
    const STATUS_ACTIVATED = 'activated';
    const STATUS_BANNED = 'banned';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'email', 'auth_key'], 'required'],
            [['status'], 'string'],
            [['isAdmin'], 'integer'],
            [['activation_at', 'password_reset_at', 'created_at', 'updated_at'], 'safe'],
            [['username', 'password', 'email', 'token', 'activation_token', 'password_reset_token'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['email'], 'unique'],
            [['token'], 'unique'],
            [['activation_token'], 'unique'],
            [['password_reset_token'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
            'status' => 'Status',
            'auth_key' => 'Auth Key',
            'token' => 'Token',
            'isAdmin' => 'Is Admin',
            'activation_token' => 'Activation Token',
            'activation_at' => 'Activation At',
            'password_reset_token' => 'Password Reset Token',
            'password_reset_at' => 'Password Reset At',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

//  ---------------------------------------------  Поведения -------------------------------------------
    public function behaviors()
    {
        return [
            [
                // Генерит поля created_at и updated_at
                'class' => TimestampBehavior::className(),
                'value' => new Expression('NOW()'),   // for mysql
            ],
        ];
    }

//  ----------------------------------------------  Хелперы ---------------------------------------------
    public function generateActivationToken()
    {
        $this->activation_token = Yii::$app->security->generateRandomString();
        $this->activation_at = Yii::$app->formatter->asDatetime(time());
    }

    public function removeActivationToken()
    {
        $this->activation_token = null;
        $this->activation_at = null;
    }

    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString();
        $this->touch('password_reset_at'); // touch - TimestampBehavior assign the current timestamp to the specified attribute and save them to the database
    }

    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
        $this->password_reset_at = null;
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Генерирует случайную строку из 32 шестнадцатеричных символов и присваивает (при записи) полученное значение полю auth_key
     * таблицы user для нового пользователя.
     * Вызывается из модели SignupForm.
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Сравнивает полученный пароль с паролем в поле password_hash, для текущего пользователя, в таблице user.
     * Вызывается из модели LoginForm.
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVATED]);
    }

    /**
     * Finds user by password_reset_token
     *
     * @param string $key
     * @return static|null
     */
    public static function findByPasswordResetToken($key)
    {
        $user = static::findOne(['password_reset_token' => $key]);
        //VarDumper::dump($user, 10, true);die;       // for debug
        return static::isSecretKeyExpire($key, $user->password_reset_at) ? $user : null;
    }

    /**
     * Finds user by activation_token
     *
     * @param string $key
     * @return static|null
     */
    public static function findByActivationToken($key)
    {
        $user = static::findOne(['activation_token' => $key]);
        //VarDumper::dump($user, 10, true);die;       // for debug
        return static::isSecretKeyExpire($key, $user->activation_at) ? $user : null;
    }

    public static function isSecretKeyExpire($key, $password_reset_at)
    {
        if (empty($key)) {
            return false;
        }
        $expire = Yii::$app->params['secretKeyExpire'];
        $timestamp = Yii::$app->formatter->asTimestamp($password_reset_at);
        return ($timestamp + $expire) >= time();
    }

//  -----------------------------------------  IdentityInterface  -----------------------------------------
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVATED]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['token' => $token]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->auth_key === $authKey;
    }
}


text:
using System;
using Aspose.Email.Mail;
using Aspose.Email.Outlook;
using Aspose.Email.Outlook.Pst;
using System.IO;

/*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from http://www.aspose.com/downloads,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using http://www.aspose.com/community/forums/default.aspx
*/

namespace Aspose.Email.Examples.CSharp.Email.Outlook
{
    class SearchStringInPSTWithIgnoreCaseParameter
    {
        public static void Run()
        {
            // The path to the File directory.
            // ExStart:SearchStringInPSTWithIgnoreCaseParameter
            string dataDir = RunExamples.GetDataDir_Outlook();

            string path = dataDir + "SearchStringInPSTWithIgnoreCaseParameter_out.pst";

            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (PersonalStorage personalStorage = PersonalStorage.Create(dataDir + "SearchStringInPSTWithIgnoreCaseParameter_out.pst", FileFormatVersion.Unicode))
            {
                FolderInfo folderInfo = personalStorage.CreatePredefinedFolder("Inbox", StandardIpmFolder.Inbox);

                folderInfo.AddMessage(MapiMessage.FromMailMessage(MailMessage.Load(dataDir + "Message.eml")));

                PersonalStorageQueryBuilder builder = new PersonalStorageQueryBuilder();
                // IgnoreCase is True
                builder.From.Contains("automated", true);

                MailQuery query = builder.GetQuery();
                MessageInfoCollection coll = folderInfo.GetContents(query);
                Console.WriteLine(coll.Count);
            }
            // ExEnd:SearchStringInPSTWithIgnoreCaseParameter
        }
    }
}


text:
package models;

import com.avaje.ebean.Model;
import play.data.validation.Constraints;

import javax.persistence.*;

@Entity
public class UserPreferences extends Model {

    @Id
    @Column(unique = true)
    public Long preferenceId;

    @Column
    @Constraints.Required
    public String locationPref;

    @Column
    @Constraints.Required
    public String genderPref;

    @Column
    @Constraints.Required
    public String studentPref;

    @OneToOne
    @JoinColumn(name = "id")
    public User user;

    @Column(unique = true)
    public Long userId;

    public static Model.Finder<Long, UserPreferences> find = new Model.Finder<Long, UserPreferences>(Long.class, UserPreferences.class);

    public static UserPreferences findByUserId(Long id) {
        return find.where().eq("user_id", id).findUnique();
    }

    public void set(UserPreferences newPreferences) {
        locationPref = newPreferences.locationPref;
        genderPref = newPreferences.genderPref;
        studentPref = newPreferences.studentPref;
    }
}


text:
<extend name="param"/>
<block name="css">
<link href="{:ADDON_PUBLIC_PATH}/css/diy.css?v={:SITE_VERSION}" rel="stylesheet" type="text/css">
</block>

<block name="baseSetting">
<form id="baseSettingForm" class="edit_module_form form-horizontal">

    	显示模板:

			<select name="template" id="template">
					<option value="simple" <eq name="template" value="simple">selected</eq> >普通模板</option>

                    <option value="$widget_id" id="custom_template" <eq name="template" value="widget_id">selected</eq> >自定义模板</option>

			</select>

        编辑模板

    	通用表单ID:

			<input type="text" name="target_id" placeholder="仅支持单个ID" class="text input-large" value="{$target_id}">

           <button type="button" id="confirm" class="btn submit-btn ajax-post" target-form="form-horizontal">确 定</button>
           <button type="button" class="btn preview_btn">预 览</button>

</form>
</block>

<block name="script">

</block>


text:
from minio import Minio
from minio.error import ResponseError

client = Minio('s3.amazonaws.com',
               access_key='YOUR-ACCESSKEYID',
               secret_key='YOUR-SECRETACCESSKEY')

# Get a full object
try:
    data = client.get_object('my-bucketname', 'my-objectname')
    with open('my-testfile', 'wb') as file_data:
        for d in data:
            file_data.write(d)
except ResponseError as err:
    print(err)


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Plotting the full MNE solution — MNE 0.15 documentation</title>
    <link rel="stylesheet" href="../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/gallery.css" type="text/css" />

    <link rel="shortcut icon" href="../../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../../genindex.html" />
    <link rel="search" title="Search" href="../../search.html" />

    <link rel="stylesheet" href="../../_static/style.css " type="text/css" />
    <link rel="stylesheet" href="../../_static/font-awesome.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/flag-icon.css" type="text/css" />

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.15

Install

Documentation

API

Examples

Contribute

  Site

  <button type="button" class="btn btn-primary navbar-btn dropdown-toggle" id="dropdownMenu1" data-toggle="dropdown">
    v0.15

  </button>

Development

v0.15 (stable)

v0.14

v0.13

v0.12

v0.11

<form class="navbar-form navbar-right" action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Plotting the full MNE solution

<form action="../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Plotting the full MNE solution¶

The source space that is used for the inverse computation defines a set of
dipoles, distributed across the cortex. When visualizing a source estimate, it
is sometimes useful to show the dipole directions, as well as their estimated
magnitude.

Out:

Successfully extracted to: [u'/home/ubuntu/mne_data/MNE-sample-data']
Reading /home/ubuntu/mne_data/MNE-sample-data/MEG/sample/sample_audvis-ave.fif ...
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Found the data of interest:
        t =    -199.80 ...     499.49 ms (Left Auditory)
        0 CTF compensation matrices available
        nave = 55 - aspect type = 100
Projections have already been applied. Setting proj attribute to True.
Applying baseline correction (mode: mean)
Reading inverse operator decomposition from /home/ubuntu/mne_data/MNE-sample-data/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif...
    Reading inverse operator info...
    [done]
    Reading inverse operator decomposition...
    [done]
    305 x 305 full covariance (kind = 1) found.
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Noise covariance matrix read.
    22494 x 22494 diagonal covariance (kind = 2) found.
    Source covariance matrix read.
    22494 x 22494 diagonal covariance (kind = 6) found.
    Orientation priors read.
    22494 x 22494 diagonal covariance (kind = 5) found.
    Depth priors read.
    Did not find the desired covariance matrix (kind = 3)
    Reading a source space...
    Computing patch statistics...
    Patch information added...
    Distance information added...
    [done]
    Reading a source space...
    Computing patch statistics...
    Patch information added...
    Distance information added...
    [done]
    2 source spaces read
    Read a total of 4 projection items:
        PCA-v1 (1 x 102) active
        PCA-v2 (1 x 102) active
        PCA-v3 (1 x 102) active
        Average EEG reference (1 x 60) active
    Source spaces transformed to the inverse solution coordinate frame
Preparing the inverse operator for use...
    Scaled noise and source covariance from nave = 1 to nave = 55
    Created the regularized inverter
    Created an SSP operator (subspace dimension = 3)
    Created the whitener using a full noise covariance matrix (3 small eigenvalues omitted)
    Computing noise-normalization factors (dSPM)...
[done]
Picked 305 channels from the data
Computing inverse...
(eigenleads need to be weighted)...
(dSPM)...
[done]

# Author: Marijn van Vliet <w.m.vanvliet@gmail.com>
#
# License: BSD (3-clause)
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, apply_inverse

print(__doc__)

data_path = sample.data_path()
subjects_dir = data_path + '/subjects'

# Read evoked data
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))

# Read inverse solution
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
inv = read_inverse_operator(fname_inv)

# Apply inverse solution, set pick_ori='vector' to obtain a
# :class:`mne.VectorSourceEstimate` object
snr = 3.0
lambda2 = 1.0 / snr ** 2
stc = apply_inverse(evoked, inv, lambda2, 'dSPM', pick_ori='vector')

# Use peak getter to move vizualization to the time point of the peak magnitude
_, peak_time = stc.magnitude().get_peak(hemi='lh')

# Plot the source estimate
brain = stc.plot(initial_time=peak_time, hemi='lh', subjects_dir=subjects_dir)

Total running time of the script: ( 0 minutes  11.544 seconds)

Download Python source code: plot_vector_mne_solution.py

Download Jupyter notebook: plot_vector_mne_solution.ipynb

Gallery generated by Sphinx-Gallery

GitHub

·

Mailing list

·

Gitter

·

What's new

·

Cite MNE

Back to top

© Copyright 2012-2017, MNE Developers. Last updated on 2017-10-31.


text:
#ifndef CACHE_H
#define CACHE_H

#include <unistd.h>		/* for type off_t */
#include <stdbool.h>		/* for type bool */
#include <pthread.h>

#define CACHE_PAGE 1000
#define PAGE_SIZE  65536
struct page
{
	int fd;			/* file that this page lives at */
	off_t offset;		/* offset that this page lives at */
	unsigned short lru_count;	/* count for clock LRU approx or
					 * UCHAR_MAX if unremovable */
	bool dirty;			/* whether this page is dirty */
	pthread_mutex_t mutex;		/* protect this page */

	char *mem;
};

struct cache
{
	struct page cache[CACHE_PAGE];
	unsigned int used;	/* how many page used in the cache */
	int lastaccess;
	pthread_mutex_t mutex;
};

struct cache *cache_new();

void cache_free(struct cache *cache);

struct page* cache_newpage(struct cache *cache,int fd,off_t offset);
struct page* cache_pagein(struct cache *cache,int fd,off_t offset);
void cache_freepage(struct cache *cache,int fd,off_t offset); /* FIXME:implement it */

#endif


text:
package co.com.codesoftware.entity;

import java.math.BigDecimal;

public class RespuestaReteEntity {
	private String mensaje;
	private BigDecimal respuesta;

	public String getMensaje() {
		return mensaje;
	}

	public void setMensaje(String mensaje) {
		this.mensaje = mensaje;
	}

	public BigDecimal getRespuesta() {
		return respuesta;
	}

	public void setRespuesta(BigDecimal respuesta) {
		this.respuesta = respuesta;
	}

}


text:
<?php

/*
 * This file is part of the "EloGank League of Legends Replay Downloader" package.
 *
 * https://github.com/EloGank/lol-replay-downloader
 *
 * For the full license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Example\Utils;

use Buzz\Browser;
use EloGank\Replay\Output\OutputInterface;

/**
 * @author Sylvain Lorinet <sylvain.lorinet@gmail.com>
 */
class LoLNexusParser
{
    const REGION_NA   = 1;
    const REGION_EUW  = 2;
    const REGION_EUNE = 3;
    const REGION_BR   = 4;
    const REGION_TR   = 5;
    const REGION_RU   = 6;
    const REGION_LAN  = 7;
    const REGION_LAS  = 8;
    const REGION_OCE  = 9;

    /**
     * @var string
     */
    protected $region;

    /**
     * @var int
     */
    protected $gameId;

    /**
     * @var string
     */
    protected $encryptionKey;

    protected static $serverNames = [
        'NA', 'EUW', 'EUNE', 'BR', 'TR', 'RU', 'LAN', 'LAS', 'OCE'
    ];

    /**
     * Select the first player in the recent games list for a selected region
     *
     * @param int             $regionId
     * @param OutputInterface $output
     */
    public function parseRandom($regionId = self::REGION_EUW, OutputInterface $output = null)
    {
        $hasOutput = null != $output;
        if ($hasOutput) {
            $output->write("Parsing homepage...\t\t\t");
        }

        $buzz = new Browser();
        $response = $buzz->get('http://www.lolnexus.com/recent-games?filter-region=' . $regionId . '&filter-sort=1');

        if (!preg_match('/<a class="green-button scouter-button" href="\/' . self::$serverNames[$regionId - 1] . '\/search\?name=(.*)">Live Game<\/a>/', $response->getContent(), $matches)) {
            throw new \RuntimeException('Cannot parse LoL Nexus website, maybe down ?');
        }

        if ($hasOutput) {
            $output->writeln('<info>OK</info>');
        }

        $this->parsePlayer($regionId, $matches[1], $output, $buzz);
    }

    /**
     * @param int                  $regionId
     * @param string               $playerName
     * @param null|OutputInterface $output
     * @param null|Browser         $buzz
     */
    public function parsePlayer($regionId, $playerName, OutputInterface $output = null, $buzz = null)
    {
        if (null == $buzz) {
            $buzz = new Browser();
        }

        $hasOutput = null != $output;
        if ($hasOutput) {
            $output->write("Parsing game page...\t\t\t");
        }

        $response = $buzz->get('http://www.lolnexus.com/ajax/get-game-info/' . self::$serverNames[$regionId - 1] . '.json?name=' . urlencode($playerName));

        if (!preg_match('/lrf:\/\/spectator [0-9a-zA-Z.:]+ (.*) ([0-9]+) ([A-Z0-9]+) [0-9\.]+/', $response->getContent(), $matches)) {
            throw new \RuntimeException('Cannot parse LoL Nexus game page, the game may be ended (sometimes LoLNexus\'s cache is bad), please retry.');
        }

        if ($hasOutput) {
            $output->writeln('<info>OK</info>');
        }

        $this->encryptionKey    = $matches[1];
        $this->gameId           = $matches[2];
        $this->region           = $matches[3];
    }

    /**
     * @return string
     */
    public function getEncryptionKey()
    {
        return $this->encryptionKey;
    }

    /**
     * @return int
     */
    public function getGameId()
    {
        return $this->gameId;
    }

    /**
     * @return string
     */
    public function getRegion()
    {
        return $this->region;
    }
}


text:
using namespace cnn;
using namespace cnn::expr;
using namespace std;

struct NodeTest {
  NodeTest() {
    // set up some dummy arguments to cnn
    for (auto x : {"NodeTest", "--cnn-mem", "10"}) {
      av.push_back(strdup(x));
    }
    char **argv = &av[0];
    int argc = av.size();
    cnn::Initialize(argc, argv);
    ones3_vals = {1.f,1.f,1.f};
    first_one_vals = {1.f,0.f,0.f};
    ones2_vals = {1.f,1.f};
    batch_vals = {1.f,2.f,3.f,4.f,5.f,6.f};
    // Create parameters
    std::vector<float> param1_vals = {1.1f,-2.2f,3.3f};
    std::vector<float> param2_vals = {2.2f,3.4f,-1.2f};
    std::vector<float> param3_vals = {1.1f,2.2f,3.3f};
    std::vector<float> param_scalar1_vals = {2.2f};
    std::vector<float> param_scalar2_vals = {1.1f};
    param1 = mod.add_parameters({3});
    TensorTools::SetElements(param1->values,param1_vals);
    param2 = mod.add_parameters({3});
    TensorTools::SetElements(param2->values,param2_vals);
    param3 = mod.add_parameters({3});
    TensorTools::SetElements(param3->values,param3_vals);
    param_scalar1 = mod.add_parameters({1});
    TensorTools::SetElements(param_scalar1->values,param_scalar1_vals);
    param_scalar2 = mod.add_parameters({1});
    TensorTools::SetElements(param_scalar2->values,param_scalar2_vals);
  }
  ~NodeTest() {
    for (auto x : av) free(x);
  }

  template <class T>
  std::string print_vec(const std::vector<T> vec) {
    ostringstream oss;
    if(vec.size()) oss << vec[0];
    for(size_t i = 1; i < vec.size(); i++)
      oss << ' ' << vec[i];
    return oss.str();
  }

  std::vector<float> ones3_vals, ones2_vals, first_one_vals, batch_vals;
  std::vector<char*> av;
  cnn::Model mod;
  cnn::Parameters *param1, *param2, *param3, *param_scalar1, *param_scalar2;
};

// define the test suite
BOOST_FIXTURE_TEST_SUITE(node_test, NodeTest);

// Expression operator-(const Expression& x);
BOOST_AUTO_TEST_CASE( negate_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = -x1;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator+(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( add_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = x1+x2;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator+(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( addscalar_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = x1+2.0;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator+(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalaradd_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = 2.0+x1;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator-(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( subtract_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = x1+x2;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator-(real x, const Expression& y);
BOOST_AUTO_TEST_CASE( scalarsubtract_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = 2.0-x1;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator-(const Expression& x, real y);
BOOST_AUTO_TEST_CASE( subtractscalar_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = x1-2.0;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = x1*transpose(x2);
  Expression ones3 = input(cg, {1,3}, ones3_vals);
  ones3 * y * transpose(ones3);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( multiply_batch_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = input(cg, Dim({3},2), batch_vals);
  Expression y = x1*transpose(x2);
  Expression ones3 = input(cg, {1,3}, ones3_vals);
  sum_batches(ones3 * y * transpose(ones3));
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression scalar = parameter(cg, param_scalar1);
  Expression x2 = parameter(cg, param2);
  Expression y = affine_transform({x1, x2, scalar});
  Expression ones3 = input(cg, {1,3}, ones3_vals);
  ones3 * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression scalar = parameter(cg, param_scalar1);
  Expression x2 = input(cg, Dim({3},2), batch_vals);
  Expression y = affine_transform({x1, x2, scalar});
  Expression ones3 = input(cg, {1,3}, ones3_vals);
  sum_batches(ones3 * y);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( affine_batch2_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = input(cg, Dim({1,3},2), batch_vals);
  Expression scalar = parameter(cg, param_scalar1);
  Expression x2 = parameter(cg, param2);
  Expression y = affine_transform({x1, scalar, transpose(x2) });
  Expression ones3 = input(cg, {3,1}, ones3_vals);
  sum_batches(y * ones3);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression operator*(const Expression& x, float y);
BOOST_AUTO_TEST_CASE( multiplyscalar_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = x1*2.0;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// inline Expression operator*(float y, const Expression& x) { return x * y; }
BOOST_AUTO_TEST_CASE( scalarmultiply_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = 2.0*x1;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// inline Expression operator/(const Expression& x, float y) { return x * (1.f / y); }
BOOST_AUTO_TEST_CASE( dividescalar_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = x1/2.0;
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression cdiv(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cdiv_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = cdiv(x1, x2);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression colwise_add(const Expression& x, const Expression& bias);
BOOST_AUTO_TEST_CASE( colwise_add_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = colwise_add(x1 * transpose(x2), x2);
  Expression ones3 = input(cg, {1,3}, ones3_vals);
  ones3 * y * transpose(ones3);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression contract3d_1d(const Expression& x, const Expression& y);
// TODO

// Expression contract3d_1d(const Expression& x, const Expression& y, const Expression& b);
// TODO

// Expression sqrt(const Expression& x);
BOOST_AUTO_TEST_CASE( sqrt_gradient ) {
  cnn::ComputationGraph cg;
  Expression x3 = parameter(cg, param3);
  Expression y = sqrt(x3);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression erf(const Expression& x);
BOOST_AUTO_TEST_CASE( erf_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = erf(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression tanh(const Expression& x);
BOOST_AUTO_TEST_CASE( tanh_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = tanh(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression exp(const Expression& x);
BOOST_AUTO_TEST_CASE( exp_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = exp(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression square(const Expression& x);
BOOST_AUTO_TEST_CASE( square_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = square(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression cube(const Expression& x);
BOOST_AUTO_TEST_CASE( cube_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = cube(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression lgamma(const Expression& x);
BOOST_AUTO_TEST_CASE( lgamma_gradient ) {
  cnn::ComputationGraph cg;
  Expression x2 = parameter(cg, param2);
  Expression y = lgamma(x2);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression log(const Expression& x);
BOOST_AUTO_TEST_CASE( log_gradient ) {
  cnn::ComputationGraph cg;
  Expression x3 = parameter(cg, param3);
  Expression y = log(x3);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression logistic(const Expression& x);
BOOST_AUTO_TEST_CASE( logistic_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = logistic(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression rectify(const Expression& x);
BOOST_AUTO_TEST_CASE( rectify_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = rectify(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression hinge(const Expression& x, unsigned index, float m = 1.0);
BOOST_AUTO_TEST_CASE( hinge_gradient ) {
  unsigned index = 0;
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  hinge(x1, index, 0.5);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression hinge(const Expression& x, const unsigned* pindex, float m = 1.0);
BOOST_AUTO_TEST_CASE( hingeptr_gradient ) {
  unsigned index = 0;
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  hinge(x1, &index, 0.5);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression log_softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( log_softmax_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = log_softmax(x1);
  input(cg, {1,3}, first_one_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression log_softmax(const Expression& x, const std::vector<unsigned>& restriction);
BOOST_AUTO_TEST_CASE( restricted_log_softmax_gradient ) {
  vector<unsigned> restriction = {0,1};
  cnn::ComputationGraph cg;
  Expression x3 = parameter(cg, param3);
  Expression y = exp( log_softmax(x3, restriction) );
  input(cg, {1,3}, first_one_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression softmax(const Expression& x);
BOOST_AUTO_TEST_CASE( softmax_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = softmax(x1);
  input(cg, {1,3}, first_one_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression softsign(const Expression& x);
BOOST_AUTO_TEST_CASE( softsign_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = softsign(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pow(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( pow_gradient ) {
  cnn::ComputationGraph cg;
  Expression x3 = parameter(cg, param3);
  Expression x_scalar1 = parameter(cg, param_scalar1);
  Expression y = pow(x3, x_scalar1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression min(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( min_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = min(x1, x2);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression max(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( max_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = max(x1, x2);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// TODO: Noise is random, so it cannot be tested simply?
// // Expression noise(const Expression& x, real stddev);
// BOOST_AUTO_TEST_CASE( noise_gradient ) {
//   cnn::ComputationGraph cg;
//   Expression x1 = parameter(cg, param1);
//   Expression y = noise(x1, 0.5);
//   input(cg, {1,3}, ones3_vals) * y;
//   BOOST_CHECK(CheckGrad(mod, cg, 0));
// }

// TODO: Dropout scales the gradients at training time, so they don't match.
// // Expression dropout(const Expression& x, real p);
// BOOST_AUTO_TEST_CASE( dropout_gradient ) {
//   cnn::ComputationGraph cg;
//   Expression x1 = parameter(cg, param1);
//   Expression y = dropout(x1, 0.5);
//   input(cg, {1,3}, ones3_vals) * y;
//   BOOST_CHECK(CheckGrad(mod, cg, 0));
// }

// Expression block_dropout(const Expression& x, real p);
// TODO

// Expression reshape(const Expression& x, const Dim& d);
BOOST_AUTO_TEST_CASE( reshape_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = reshape(x1, {1,3});
  y * input(cg, {3}, ones3_vals);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression transpose(const Expression& x);
BOOST_AUTO_TEST_CASE( transpose_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = softsign(x1);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression trace_of_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( trace_of_product_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  trace_of_product(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression cwise_multiply(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( cwise_multiply_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  Expression y = cwise_multiply(x1, x2);
  input(cg, {1,3}, ones3_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression dot_product(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( dot_product_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  dot_product(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression squared_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( squared_distance_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  squared_distance(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression huber_distance(const Expression& x, const Expression& y, float c = 1.345f);
BOOST_AUTO_TEST_CASE( huber_distance_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  huber_distance(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression l1_distance(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( l1_distance_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = parameter(cg, param2);
  l1_distance(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression binary_log_loss(const Expression& x, const Expression& y);
BOOST_AUTO_TEST_CASE( binary_log_loss_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = logistic( parameter(cg, param1) );
  Expression x2 = input(cg, {3}, ones3_vals);
  binary_log_loss(x1, x2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pairwise_rank_loss(const Expression& x, const Expression& y, real m=1.0);
BOOST_AUTO_TEST_CASE( pairwise_rank_loss_gradient ) {
  cnn::ComputationGraph cg;
  Expression x_scalar1 = parameter(cg, param_scalar1);
  Expression x_scalar2 = parameter(cg, param_scalar2);
  pairwise_rank_loss(x_scalar1, x_scalar2);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// TODO: These are all unimplemented
// Expression poisson_loss(const Expression& x, unsigned y);
// Expression poisson_loss(const Expression& x, const unsigned* py);
//
// Expression conv1d_narrow(const Expression& x, const Expression& f);
// Expression conv1d_wide(const Expression& x, const Expression& f);
// Expression kmax_pooling(const Expression& x, unsigned k);
// Expression fold_rows(const Expression& x, unsigned nrows=2);
// Expression sum_cols(const Expression& x);
// Expression kmh_ngram(const Expression& x, unsigned n);
//
// Expression sum_batches(const Expression& x);

// Expression pick(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_gradient ) {
  unsigned idx = 1;
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  pick(x1, idx);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pick(const Expression& x, unsigned* pv);
BOOST_AUTO_TEST_CASE( pickptr_gradient ) {
  unsigned idx = 1;
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  pick(x1, &idx);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pick_batch_gradient ) {
  std::vector<unsigned> idx = {1,2};
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = input(cg, Dim({3},2), batch_vals);
  sum_batches(pick(x1+x2, idx));
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pickrange(const Expression& x, unsigned v, unsigned u);
BOOST_AUTO_TEST_CASE( pickrange_gradient ) {
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression y = pickrange(x1, 0, 2);
  input(cg, {1,2}, ones2_vals) * y;
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_gradient ) {
  unsigned idx = 1;
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  pickneglogsoftmax(x1, idx);
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

// Expression pickneglogsoftmax(const Expression& x, unsigned v);
BOOST_AUTO_TEST_CASE( pickneglogsoftmax_batch_gradient ) {
  std::vector<unsigned> idx = {1,2};
  cnn::ComputationGraph cg;
  Expression x1 = parameter(cg, param1);
  Expression x2 = input(cg, Dim({3},2), batch_vals);
  sum_batches(pickneglogsoftmax(x1+x2, idx));
  BOOST_CHECK(CheckGrad(mod, cg, 0));
}

BOOST_AUTO_TEST_SUITE_END()


text:
package org.apache.dubbo.rpc.proxy;

import org.apache.dubbo.rpc.Invoker;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.lang.reflect.Method;

import static org.mockito.Mockito.*;

public class InvokerInvocationHandlerTest {

    @Mock
    private Invoker<?> invoker;
    @InjectMocks
    private InvokerInvocationHandler invokerInvocationHandler;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testInvokeToString() throws Throwable {
        String methodName = "toString";

        when(invoker.toString()).thenReturn(methodName);
        Method method = invoker.getClass().getMethod(methodName);

        Object result = invokerInvocationHandler.invoke(null, method, new Object[]{});
        Assert.assertEquals(methodName, result);
    }

}


text:
package com.jasonrobison.emulator8080.emulator.opcodes;

import org.apache.log4j.Logger;

import com.jasonrobison.emulator8080.emulator.Cpu;

public class OpCodes {

	private static final Logger LOGGER = Logger.getLogger(OpCodes.class);

	public static OpCode notImplemented() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "Opcode not implemented: "
						+ Integer.toHexString(Byte.toUnsignedInt(cpu
								.getCurrentOpCode())));
				System.exit(1);

			}
		};
	}

	public static OpCode nop() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "NOP");
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	public static OpCode lxiBD16() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LXI B,D16 $"
						+ readWord(cpu));
				cpu.getRegisters().setBC(readWord(cpu));
				cpu.getRegisters().incrementProgramCounter(3);
			}
		};
	}

	public static OpCode jmpAddr() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "JMP ADDR $"
						+ getAsHexString(readWord(cpu)));
				cpu.getRegisters().setProgramCounter(readWord(cpu));
			}
		};
	}

	/**
	 * 0x31
	 *
	 * @return
	 */
	public static OpCode lxiSpD16() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LXI SP, D16 "
						+ getActualOrderWord(cpu));
				cpu.getRegisters().setStackPointer(readWord(cpu));
				cpu.getRegisters().incrementProgramCounter(3);
			}
		};
	}

	/**
	 * B <- byte 2
	 *
	 * @param byteToConvert
	 * @return
	 */
	public static OpCode mviBD8() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				byte argument1 = cpu.getMemory()[cpu.getRegisters()
						.getProgramCounter() + 1];

				LOGGER.debug(getCurrentAddressAsString(cpu) + "MVI B, D8 "
						+ getAsHexString(argument1));
				cpu.getRegisters().setB(argument1);
				cpu.getRegisters().incrementProgramCounter(2);
			}
		};
	}

	/**
	 * 0xcd Call Addr (SP-1)<-PC.hi;(SP-2)<-PC.lo;SP<-SP+2;PC=adr
	 *
	 * @return
	 */
	public static OpCode callAddr() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				short returnAddress = (short) (cpu.getRegisters()
						.getProgramCounter() + 3);
				cpu.getMemory()[cpu.getRegisters().getStackPointer() - 1] = (byte) ((returnAddress >> 8) & 0xff);
				cpu.getMemory()[cpu.getRegisters().getStackPointer() - 2] = (byte) ((returnAddress & 0xff));

				LOGGER.debug(getCurrentAddressAsString(cpu) + "CALL Addr "
						+ getActualOrderWord(cpu));
				cpu.getRegisters().setProgramCounter(readWord(cpu));
				cpu.getRegisters().setStackPointer(
						(short) (cpu.getRegisters().getStackPointer() - 2));

			}
		};
	}

	/**
	 * 0x11 D <- byte 3, E <- byte 2
	 *
	 * @return
	 */
	public static OpCode lxiDD16() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LXI D,D16 "
						+ getActualOrderWord(cpu));

				cpu.getRegisters().setDE(readWord(cpu));
				cpu.getRegisters().incrementProgramCounter(3);
			}
		};
	}

	/**
	 * 0x21 H <- byte 3, L <- byte 2
	 *
	 * @return
	 */
	public static OpCode lxiHD16() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LXI H,D16 "
						+ getActualOrderWord(cpu));

				cpu.getRegisters().setHL(readWord(cpu));
				cpu.getRegisters().incrementProgramCounter(3);
			}
		};
	}

	/**
	 * 0x1a LDAX D A <- (DE)
	 *
	 * @return
	 */
	public static OpCode ldaxD() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LDAX D ");

				cpu.getRegisters().setA(
						cpu.getMemory()[cpu.getRegisters().getDE()]);
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	public static OpCode movMA() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "MOV M A ");

				cpu.getMemory()[cpu.getRegisters().getHL()] = cpu
						.getRegisters().getA();
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x23 INX H HL <- HL + 1
	 */
	public static OpCode inxH() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "INX H ");

				cpu.getRegisters().setHL(
						(short) (cpu.getRegisters().getHL() + 1));
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x13 INX D DE <- DE + 1
	 */
	public static OpCode inxD() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "INX D ");

				cpu.getRegisters().setDE(
						(short) (cpu.getRegisters().getDE() + 1));
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x05 DCR B B <- B-1 Needs to check arithmetic flags
	 */
	public static OpCode dcrB() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "DCR B ");

				cpu.getRegisters().setB(
						decrementByte(cpu.getRegisters().getB(), cpu));
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0xc2 JNZ if NZ, PC <- adr
	 */
	public static OpCode jnz() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "JNZ "
						+ getActualOrderWord(cpu));

				if (cpu.getFlags().isZero()) {
					cpu.getRegisters().incrementProgramCounter(3);
				} else {
					cpu.getRegisters().setProgramCounter(readWord(cpu));
				}
			}
		};
	}

	/**
	 * 0xc9	RET
	 * PC.lo <- (sp); PC.hi<-(sp+1); SP <- SP+2
	 */
	public static OpCode ret() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "RET " + getAsHexString(readStackPointerWord(cpu)));

				cpu.getRegisters().setProgramCounter(readStackPointerWord(cpu));
				cpu.getRegisters().setStackPointer((short)(cpu.getRegisters().getStackPointer() + 2));
			}
		};
	}

	/**
	 * 0x36	MVI M,D8	2		(HL) <- byte 2
	 * LD HL
	 */
	public static OpCode mvHLm() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "MVI M,D8 " + getAsHexString(readByte(cpu)));

				cpu.getMemory()[cpu.getRegisters().getHL()] = readByte(cpu);
				cpu.getRegisters().incrementProgramCounter(2);
			}
		};
	}

	/**
	 * 0x7c
	 * MOV A,H
	 * A <- H
	 */
	public static OpCode movAH() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "MOV A,H ");

				cpu.getRegisters().setA(cpu.getRegisters().getH());
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0xfe
	 * CPI D8
	 * A - next byte
	 */
	public static OpCode subByteA() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "CPI D8 " + readByte(cpu));

				subtractByte(cpu.getRegisters().getA(), readByte(cpu), cpu);
				cpu.getRegisters().incrementProgramCounter(2);
			}
		};
	}

	/**
	 * 0x0e
	 * MVI C,D8
	 * C <- byte 2
	 */
	public static OpCode movC() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "MVI C,D8 " + readByte(cpu));

				cpu.getRegisters().setC(readByte(cpu));
				cpu.getRegisters().incrementProgramCounter(2);
			}
		};
	}

	/**
	 * 0xd5
	 * PUSH D
	 * (sp-2)<-E; (sp-1)<-D; sp <- sp - 2
	 */
	public static OpCode pushDE() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "PUSH DE ");

				pushWordToStack(cpu.getRegisters().getDE(), cpu);
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0xe5
	 * PUSH H
	 * (sp-2)<-L; (sp-1)<-H; sp <- sp - 2
	 */
	public static OpCode pushHL() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "PUSH HL ");

				pushWordToStack(cpu.getRegisters().getHL(), cpu);
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x26
	 * MVI H,D8
	 * H <- byte 2
	 */
	public static OpCode ldH() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "LD H " + getAsHexString(readByte(cpu)));

				cpu.getRegisters().setH(readByte(cpu));
				cpu.getRegisters().incrementProgramCounter(2);
			}
		};
	}

	/**
	 * 0x6f
	 * MOV L,A
	 * L <- A
	 */
	public static OpCode movLA() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "MOV L,A ");

				cpu.getRegisters().setL(cpu.getRegisters().getA());
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x29	DAD H
	 * CY
	 * HL = HL + HL
	 */
	public static OpCode addHlHl() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "ADD HL,HL ");

				cpu.getRegisters().setHL(addWords(cpu.getRegisters().getHL(), cpu.getRegisters().getHL(), cpu));
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0x19	DAD D
	 * CY
	 * HL = HL + DE
	 */
	public static OpCode addHlDe() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "ADD HL,DE ");

				cpu.getRegisters().setHL(addWords(cpu.getRegisters().getHL(), cpu.getRegisters().getDE(), cpu));
				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	/**
	 * 0xeb	XCHG
	 * H <-> D
	 * L <-> E
	 */
	public static OpCode xchgHLDE() {
		return new OpCode() {
			public void execute(Cpu cpu) {
				LOGGER.debug(getCurrentAddressAsString(cpu) + "XCHG HL,DE ");

				short dE = cpu.getRegisters().getDE();
				cpu.getRegisters().setDE(cpu.getRegisters().getHL());
				cpu.getRegisters().setHL(dE);

				cpu.getRegisters().incrementProgramCounter();
			}
		};
	}

	private static void pushWordToStack(short word, Cpu cpu) {
		cpu.getMemory()[cpu.getRegisters().getStackPointer() - 1] = (byte)((word >>> 8) & 0xff);
		cpu.getMemory()[cpu.getRegisters().getStackPointer() - 2] = (byte)(word  & 0x00ff);

		cpu.getRegisters().setStackPointer((short)(cpu.getRegisters().getStackPointer() - 2));
	}

	private static String getActualOrderWord(Cpu cpu) {
		byte argument1 = cpu.getMemory()[cpu.getRegisters().getProgramCounter() + 1];
		byte argument2 = cpu.getMemory()[cpu.getRegisters().getProgramCounter() + 2];

		return getAsHexString(argument1) + getAsHexString(argument2);
	}

	private static short readWord(Cpu cpu) {
		byte argument1 = cpu.getMemory()[cpu.getRegisters().getProgramCounter() + 1];
		byte argument2 = cpu.getMemory()[cpu.getRegisters().getProgramCounter() + 2];

		return (short) ((argument2 << 8) | (argument1 & 0xff));
	}

	private static byte readByte(Cpu cpu) {
		return cpu.getMemory()[cpu.getRegisters().getProgramCounter() + 1];
	}

	private static short readStackPointerWord(Cpu cpu) {
		byte argument1 = cpu.getMemory()[cpu.getRegisters().getStackPointer()];
		byte argument2 = cpu.getMemory()[cpu.getRegisters().getStackPointer() + 1];

		return (short) ((argument2 << 8) | (argument1 & 0xff));
	}

	private static byte decrementByte(byte byteToDecrement, Cpu cpu) {
		short answer = (short) (((short) byteToDecrement - 1));
		setFlags(answer, cpu);

		return (byte) (answer & 0xff);
	}

	private static byte subtractByte(byte original, byte subtractBy, Cpu cpu) {
		short answer = (short) (((short) original - subtractBy));
		setFlags(answer, cpu);

		return (byte) (answer & 0xff);
	}

	private static short addWords(short word1, short word2, Cpu cpu) {
		int answer = Short.toUnsignedInt(word1) + Short.toUnsignedInt(word2);

		cpu.getFlags().setCarry(answer > 0xffff);
		return (short)(answer & 0xffff);
	}

	private static void setFlags(short answer, Cpu cpu) {
		cpu.getFlags().setZero((answer & 0xff) == 0);
		cpu.getFlags().setSigned((answer & 0x80) > 0);
		cpu.getFlags().setParity(isParity((byte) ((answer) & 0xff)));
	}

	private static boolean isParity(byte b) {
		int s = Byte.toUnsignedInt(b) & 0xff;

		boolean isParity = true;
		while (s != 0) {
			isParity = !isParity;
			s = s & (s - 1);
		}

		return isParity;
	}

	public static String getAsHexString(byte byteToConvert) {
		return String.format("%02x", Byte.toUnsignedInt(byteToConvert));
	}

	public static String getAsHexString(short shortToConvert) {
		return String.format("%04x", Short.toUnsignedInt(shortToConvert));
	}

	public static String getAsBinaryString(byte byteToConvert) {
		return Integer.toBinaryString(Byte.toUnsignedInt(byteToConvert));
	}

	public static String getCurrentAddressAsString(Cpu cpu) {
		return String.format("%04x", cpu.getRegisters().getProgramCounter())
				+ ": ";
	}
}


text:
FactoryGirl.define do
  factory :experience do
    job_title { Faker::App.name }
    employer { Faker::Company.name }
    description { Faker::Lorem.sentence }
    from DateTime.now
    to DateTime.now + 1.year
    study false
  end
end


text:
app.directive('newprojectFileread', function(studentProfileSvc) {
  return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
      elem.bind("change", function(changeEvent) {

        var reader = new FileReader();
        reader.onload = function(loadEvent) {
          var encodedImage = loadEvent.target.result;

          var tempArray = elem[0].value.split('\\');

          var fileName = tempArray[tempArray.length - 1];
          studentProfileSvc.storeImage(encodedImage, fileName).then(
            function(result) {

              scope.newProject.picture = result.data.Location;
            })
        }
        reader.readAsDataURL(changeEvent.target.files[0]);
      });
    }
  }
});


text:
@interface PXAnimationView : PXCanvasView {
	NSImage *previousCel;
}

- (void)setPreviousCelImage:(NSImage *)previousCel;

@end