text:
from ctypes import *

lib = cdll.LoadLibrary('libcortex_sdk.so')

# --------------------------------- constants ------------------------------------

MAX_N_BODIES = 100

# Data for one segment
tSegmentData = c_double * 7 # !<  X,Y,Z, aX,aY,aZ, Length
# Data for one marker
tMarkerData  = c_float * 3  # !<  X,Y,Z
# Data for one forceplate
tForceData   = c_float * 7  # !<  X,Y,Z, fX,fY,fZ, mZ
# Data for one degree of freedom
tDofData     = c_double     # !<  Usually an angle value in degrees

# ---------------------------------- structs -------------------------------------

class sHostInfo(Structure):
    '''
    ! The description of the connection to Cortex.
    ! This contains information about the host machine, the host program, and the connection status.
    '''
    _fields_ = [("bFoundHost", c_int),               # !< True = have talked to Cortex
                ("LatestConfirmationTime", c_int),   # !< Time of last receipt from Cortex
                ("szHostMachineName",c_char * 128),  # !< Name of machine Cortex is running on
                ("HostMachineAddress", c_ubyte * 4), # !< IP Address of that machine
                ("szHostProgramName", c_char * 128), # !< Name of module communicating with
                ("HostProgramVersion", c_ubyte * 4)] # !< Version number of that module

class sHierarchy(Structure):
    '''
    ! The rudimentary description of a skeleton's bones and hierarchy.
    ! This description is defined by szSegmentNames[iSegment], and iParent[iSegment]
    '''
    _fields_ = [("nSegments", c_int),                       # !< Number of segments
                ("szSegmentNames", POINTER(c_char_p)),# !< Array of segment names
                ("iParents", POINTER(c_int) )]         # !< Array of segment parents (defines the hierarchy)

class sBodyDef(Structure):
    '''
    ! The description of a single tracking object that will have streaming data.
    ! This description includes the object's name, the marker names, the skeleton hierarchy, and the DOF names.
    '''
    _fields_ = [("szName", c_char_p),                      # !< Name of the object
                ("nMarkers", c_int),                       # !< Number of markers
                ("szMarkerNames", POINTER(c_char_p)), # !< Array of marker names
                ("Hierarchy", sHierarchy),                 # !< The Skeleton description for HTR data
                ("nDofs", c_int),                          # !< Number of degrees of freedom
                ("szDofNames", POINTER(c_char_p))]       # !< Array of degrees of freedom names

class sBodyDefs (Structure):
    '''
    ! The description of all the data that will stream from Cortex.
    ! This description includes all the body descriptions, the analog channels,
    ! and the number of forceplates.
    '''
    _fields_ = [("nBodyDefs", c_int),                             # !< Number of bodies being tracked
                ("BodyDefs", sBodyDef * MAX_N_BODIES),            # !< The definition of each body
                ("nAnalogChannels", c_int),                       # !< The number of active analog channels
                                                                  # !< The names given to each channel
                ("szAnalogChannelNames", POINTER(c_char_p)),
                ("nForcePlates", c_int),                          # !< The number of active forceplates
                ("AllocatedSpace", c_void_p)]                     # !< Private space (DON'T TOUCH)

class sBodyData (Structure):
    '''
    ! A structure containing ALL the data to drive one markerset.
    ! This contains the markerset's name, the marker positions, the segment
    ! positions relative to each segment's parent, and the DOFs.
    '''
    _fields_ = [("szName", c_char * 128),        # !< For dynamic matching of objects.
                ("nMarkers", c_int),             # !< Number of markers defined
                # ! [nMarkers][3] array.  Markers[iMarker][0] == XEMPTY means no data.
                ("Markers", POINTER(tMarkerData)),
                ("fAvgMarkerResidual", c_float), # !< Average residual of the marker triangulations
                ("nSegments", c_int),            # !< Number of segments
                ("Segments", POINTER(tSegmentData)),             # !< [nSegments][7] array
                ("nDofs", c_int),                # !< Number of degrees-of-freedom
                ("Dofs", POINTER(tDofData)),   # !< Array of degree-of-freedom angles
                ("fAvgDofResidual", c_float),    # !< Average residual from the solve
                ("nIterations", c_int),          # !< Number of iterations to solve
                ("ZoomEncoderValue", c_int),     # !< Zoom value from the Camera Tracker Encoder
                ("FocusEncoderValue", c_int)]    # !< Focus value from the Camera Tracker Encoder

class sAnalogData (Structure):
    '''
    ! All the analog data for one frame's worth of time.
    ! This includes the raw analog samples, processed forces, and also angle encoder values (if available).
    '''
    _fields_ = [("nAnalogChannels", c_int),                  # !< Total number of active channels
                ("nAnalogSamples", c_int),                   # !< The number of samples in the current frame
                ("AnalogSamples", POINTER(c_short)),    # !< The data: nChannels * nSamples of these
                ("nForcePlates", c_int),                     # !< Total number of active forceplates
                ("nForceSamples", c_int),                    # !< The number of samples in the current frame
                ("Forces", POINTER(tForceData)),     # !< The forces: nForcePlates * nForceSamples of these
                ("nAngleEncoders", c_int),                   # !< Number of encoders
                ("nAngleEncoderSamples", c_int),             # !< Number of samples per encoder
                ("AngleEncoderSamples", POINTER(c_double))]  # !< The angles: nEncoders*nEncoderSamples of these

class sRecordingStatus (Structure):
    '''
    ! The recording status tells us the frame numbers and capture filename.
    '''
    _fields_ = [("bRecording", c_int), # !< 0=Not Recording, anything else=Recording
                # ! The frame number of the first data frame to be recorded from Cortex Live Mode
                ("iFirstFrame", c_int),
                # ! The frame number of the last data frame to be recorded from Cortex Live Mode
                ("iLastFrame", c_int),
                ("szFilename", c_char * 256)] # !< The full capture filename

class sFrameOfData (Structure):
    '''
    ! ALL the data for one frame streamed from Cortex.
    ! This include the two items that describe the frame. The first is the frame number.
    ! The second is the time delay measuring the delay between the real world action
    ! and the host sending this frame. The actual data for the frame includes the data
    ! for each body, the unidentified markers, and data that is associated with the analog captures.
    '''
    _fields_ = [("iFrame", c_int),                     # !< Cortex's frame number
                # ! Total time (seconds) from Camera to the Host sending the data
                ("fDelay", c_float),
                ("nBodies", c_int),                    # !< The bodies should match the descriptions
                ("BodyData", sBodyData * MAX_N_BODIES),# !< The data for each body
                ("nUnidentifiedMarkers", c_int),       # !< Number of unrecognized markers
                ("UnidentifiedMarkers", POINTER(tMarkerData)),# !< The unrecognized markers
                ("AnalogData", sAnalogData),           # !< The analog data packaged
                ("RecordingStatus", sRecordingStatus)] # !< Info about name and frames being recorded

# ---------------------------------- methods -------------------------------------

def Cortex_GetSdkVersion(version = [4, 1, 3, 1]):
    '''
    This function returns a 4-byte version number.
    Version - An array of four bytes: ModuleID, Major, Minor, Bugfix
    RC_Okay
    '''
    _Cortex_GetSdkVersion = lib.Cortex_GetSdkVersion
    _Cortex_GetSdkVersion.argtypes = [c_ubyte * 4]
    return _Cortex_GetSdkVersion((c_ubyte*4)(*version))

def Cortex_SetVerbosityLevel(iLevel):
    '''
    This function sets the filter level of the LogMessages.
    The default verbosity level is VL_Warning.
    iLevel - one of the maVerbosityLevel enum values.
    RC_Okay
    '''
    _Cortex_SetVerbosityLevel = lib.Cortex_SetVerbosityLevel
    _Cortex_SetVerbosityLevel = [c_int]
    return _Cortex_SetVerbosityLevel(iLevel)

callback_pointer = [None, None]

def Cortex_SetErrorMsgHandlerFunc(callback):
    '''
    The user supplied function handles text messages posted from within the SDK.
    Logging messages is done as a utility to help code and/or run using the SDK.
    Various messages get posted for help with error conditions or events that happen.
    Each message has a Log-Level assigned to it so the user can.
    Cortex_SetVerbosityLevel
    MyFunction - This user defined function handles messages from the SDK.
    maReturnCode - RC_Okay
    '''
    _Cortex_SetErrorMsgHandlerFunc = lib.Cortex_SetErrorMsgHandlerFunc
    func_pointer = CFUNCTYPE(c_void_p, c_int, POINTER(c_char))
    _Cortex_SetErrorMsgHandlerFunc.argtypes = [func_pointer]
    _Cortex_SetErrorMsgHandlerFunc.restype = None
    #callback_pointer[0] = func_pointer(MyErrorHandler)
    callback_pointer[0] = func_pointer(callback)
    return _Cortex_SetErrorMsgHandlerFunc(callback_pointer[0])

def Cortex_SetDataHandlerFunc(callback):
    '''
    The user supplied function will be called whenever a frame of data arrives.

    The ethernet servicing is done via a thread created
    when the connection to Cortex is made.  This function is
    called from that thread.  Some tasks are not sharable
    directly across threads.  Window redrawing, for example,
    should be done via events or messages.
    MyFunction - This user supply callback function handles the streaming data
    maReturnCode - RC_Okay

    Notes: The data parameter points to "hot" data. That frame of data
           will be overwritten with the next call to the callback function.
    '''
    _Cortex_SetDataHandlerFunc = lib.Cortex_SetDataHandlerFunc
    func_pointer = CFUNCTYPE(c_void_p, POINTER(sFrameOfData))
    _Cortex_SetDataHandlerFunc.argtypes = [func_pointer]
    _Cortex_SetDataHandlerFunc.restype = None
    callback_pointer[1] = func_pointer(callback)
    return _Cortex_SetDataHandlerFunc(callback_pointer[1])

def Cortex_Initialize(szMyNicCardAddress = "", szCortexNicCardAddress = ""):
    '''
    This function defines the connection routes to talk to Cortex.

    Machines can have more than one ethernet interface.  This function
    is used to either set the ethernet interface to use, or to let
    the SDK auto-select the local interface, and/or the Cortex host.
    This function should only be called once at startup.

    szMyNicCardAddress - "a.b.c.d" or HostName.  "" and NULL mean AutoSelect
    szCortexNicCardAddress - "a.b.c.d" or HostName.  "" and NULL mean AutoSelect
    maReturnCode - RC_Okay, RC_ApiError, RC_NetworkError, RC_GeneralError

    MY ADVICE: USE WITHOUT PARAMETERS!!!
    '''
    _Cortex_Initialize = lib.Cortex_Initialize
    _Cortex_Initialize.argtypes = [c_char_p, c_char_p]
    return _Cortex_Initialize(szMyNicCardAddress, szCortexNicCardAddress)

def Cortex_GetHostInfo(pHostInfo):
    '''
    This function gets information about the connection to Cortex

    This function returns IP-Address information and Cortex version information.
    The version info can be used to handle incompatible changes in either our code
    or your code.
    pHostInfo - Structure containing connection information
    RC_Okay, RC_NetworkError
    '''
    if type(pHostInfo) != sHostInfo:
        print("ERROR: Argument must be of type sHostInfo")
        exit(0)
    _Cortex_GetHostInfo = lib.Cortex_GetSdkVersion
    return _Cortex_GetHostInfo(byref(pHostInfo))

def Cortex_Exit():
    '''
    This function stops all activity of the SDK.

    This function should be called once before exiting.
    '''
    _Cortex_Exit = lib.Cortex_Exit
    return _Cortex_Exit()

def Cortex_Request(szCommand, ppResponse, pnBytes):
    '''
    This function sends commands to Cortex and returns a response.

    This function is an extendable interface between the Client programs
    and the Host (Cortex) program.  The commands are sent as readable text strings.
    The response is returned unaltered.

    szCommand - The request to send the Cortex
    ppResponse - The reply
    pnBytes - The number of bytes in the response

    \verbatim
    Example:
    void *pResponse=NULL;
    Cortex_Request("GetContextFrameRate", &pResponse, sizeof(void*));
    fFrameRate = *(float*)pResponse;
    \endverbatim

    return RC_Okay, RC_TimeOut, RC_NotRecognized, RC_GeneralError
    '''
    # cast python objects
    _szCommand = c_char_p(szCommand)
    _ppResponse = c_void_p()
    _pnBytes = c_int()
    # call cortex method
    _Cortex_Request = lib.Cortex_Request
    ret = _Cortex_Request(_szCommand, byref(_ppResponse), byref(_pnBytes))
    # get pointer values
    ppResponse = _ppResponse
    pnBytes = _pnBytes
    return ret

def Cortex_GetBodyDefs():
    '''
    This function queries Cortex for its set of tracking objects.

    sBodyDefs* - This is a pointer to the internal storage of
                 the results of the latest call to this function.
    sa Cortex_FreeBodyDefs
    '''
    _Cortex_GetBodyDefs = lib.Cortex_GetBodyDefs
    _Cortex_GetBodyDefs.restype = POINTER(sBodyDefs)
    return _Cortex_GetBodyDefs()

def Cortex_FreeBodyDefs(pBodyDefs):
    '''
    This function frees the memory allocated by Cortex_GetBodyDefs

    The data within the structure is freed and also the structure itself.

    pBodyDefs - The item to free.
    RC_Okay
    '''
    if type(pBodyDefs) != POINTER(sBodyDefs):
        print("ERROR: Argument must be a pointer of sBodyDefs")
        print("Argumentis type: ", type(pBodyDefs))
        exit(0)
    _Cortex_FreeBodyDefs = lib.Cortex_FreeBodyDefs
    return _Cortex_FreeBodyDefs(pBodyDefs)

def Cortex_GetCurrentFrame():
    '''
    This function polls Cortex for the current frame

    The SDK user has the streaming data available via the callback function.
    In addition, this function is available to get a frame directly.
    Note: Cortex considers the current frame to be the latest LiveMode frame completed or,
          if not in LiveMode, the current frame is the one that is displayed on the screen.

    return sFrameOfData
    '''
    _Cortex_GetCurrentFrame = lib.Cortex_GetCurrentFrame
    _Cortex_GetCurrentFrame.restype = POINTER(sFrameOfData)
    return _Cortex_GetCurrentFrame()# Can POLL for the current frame.

def Cortex_CopyFrame(pSrc, pDst):
    '''
    This function copies a frame of data.

    The Destination frame should start initialized to all zeros.  The CopyFrame
    and FreeFrame functions will handle the memory allocations necessary to fill
    out the data.

    param pSrc - The frame to copy FROM.
    param pDst - The frame to copy TO

    return RC_Okay, RC_MemoryError
    '''
    if type(pSrc) != POINTER(sFrameOfData) or type(pDst) != POINTER(sFrameOfData):
        print("ERROR: Arguments must be sFrameOfData pointers")
        exit(0)
    _Cortex_CopyFrame = lib.Cortex_CopyFrame
    return _Cortex_CopyFrame(pSrc, pDst) # Allocates or reallocates pointers

def Cortex_FreeFrame(pFrame):
    '''
    This function frees memory within the structure.

    The sFrameOfData structure includes pointers to various pieces of data.
    That data is dynamically allocated or reallocated to be consistent with
    the data that has arrived from Cortex.  To properly use the sFrameOfData
    structure, you should use the utility functions supplied.  It is possible
    to reuse sFrameOfData variables without ever freeing them.  The SDK will
    reallocate the components for you.

    param pFrame - The frame of data to free.

    return RC_Okay
    '''
    if type(pFrame) != POINTER(sFrameOfData):
        print("ERROR: Argument must be a sFrameOfData pointer")
        exit(0)
    _Cortex_FreeFrame = lib.Cortex_FreeFrame
    return _Cortex_FreeFrame(pFrame)

# there are more functions which are not implemented mainly skeleton related


text:
package com.steelbridgelabs.oss.neo4j.structure;

import org.apache.tinkerpop.gremlin.GraphProviderClass;
import org.apache.tinkerpop.gremlin.structure.StructureStandardSuite;
import org.junit.runner.RunWith;

/**
 * @author Rogelio J. Baucells
 */
@RunWith(StructureStandardSuite.class)
@GraphProviderClass(provider = Neo4JTestGraphProvider.class, graph = Neo4JGraph.class)
public class Neo4JStructureStandardTest {

}

redpajama_set_name: RedPajamaGithub


text:
require 'euler/prob12'

describe Euler::Prob12 do
  context ".generate_triangular_number(7)" do
    subject { Euler::Prob12.generate_triangular_number(7) }
    it {should == 28 }
  end

  context ".num_factors_triangular_number" do
    subject { Euler::Prob12.find_factor_count(28) }
    it {should == 6 }
  end

  context '#find_answer' do
    subject { Euler::Prob12.find_answer(5) }
    it {should == 28}
  end
end


text:
@class DPFlippedView;

@interface DPScrollView : NSScrollView {

    DPFlippedView *flippedView;
}

@property(nonatomic, strong) DPFlippedView *flippedView;
@end


text:
@interface MSNineSliceAction : MSProEventHandlerAction
{
}
- (BOOL)validate;
- (BOOL)validateMenuItem:(id)arg1;
- (void)nineSlice:(id)arg1;
@end


text:
import type { NextPage, GetStaticProps } from 'next';
import Head from 'next/head';
import Script from 'next/script';
import styles from '../styles/Index.module.scss';
import getStaticContent from '../lib/contentData';
import Hero, { HeroProps } from '../components/hero';
import { HeroData, NavData } from '../lib/types';
import Nav from '../components/nav';

type Props = {
  hero: HeroData;
  nav: NavData;
}

const Index: NextPage<Props> = ({ hero, nav }): JSX.Element => {
  const { name, tags } = hero;
  const { links } = nav;

  return (
    <>
      <Head>
        <title>Solomon Rubin</title>
        <script defer data-domain="serubin.net" src="https://stats.serubin.net/js/script.js"></script>
      </Head>
      <Script id="stat-js" src="https://stats.serubin.net/js/app.js" data-domain="serubin-net" strategy="lazyOnload" />
      <Nav links={links} />
      <div className={styles.container}>
          <Hero name={name} tags={tags} />
      </div>
    </>
  );
};

export const getStaticProps: GetStaticProps = async () => {
  const data: any = getStaticContent(['hero', 'nav']);

  return {
    props: {
      ...data,
    }
  };
};

export default Index;


text:
class Cart # rubocop:disable ClassLength
  include ActiveModel::Validations
  include CartValidations
  validates :reserver_id, :start_date, :due_date, presence: true

  attr_accessor :items, :start_date, :due_date, :reserver_id

  def initialize
    @errors = ActiveModel::Errors.new(self)
    @items = {}
    @start_date = Time.zone.today
    @due_date = Time.zone.today + 1.day
    @reserver_id = nil
  end

  def persisted?
    false
  end

  ## Item methods

  def get_items # rubocop:disable AccessorMethodName
    # Used in cart_validations
    # Return items where the key is the full equipment model object
    # uses 1 database call and eager loads the requirements
    full_hash = {}
    EquipmentModel
      .includes(:requirements).find(items.keys).each do |em|
      full_hash[em] = items[em.id]
    end
    full_hash
  end

  # Adds equipment model id to items hash
  def add_item(equipment_model, _quantity = nil)
    return if equipment_model.nil?
    key = equipment_model.id
    items[key] = items[key] ? items[key] + 1 : 1
  end

  def edit_cart_item(equipment_model, quantity)
    return if equipment_model.nil?
    return if quantity < 0
    key = equipment_model.id
    items[key] = items[key] ? quantity : 0
    self.items = items.except(key) if items[key] == 0
  end

  def empty?
    @items.empty?
  end

  # remove all items from cart
  def purge_all
    initialize
  end

  # return array of reservations crafted from the cart contents
  def prepare_all
    reservations = []
    @items.each do |id, quantity|
      quantity.times do
        reservations << Reservation.new(reserver: reserver,
                                        start_date: @start_date,
                                        due_date: @due_date,
                                        equipment_model_id: id)
      end
    end
    reservations
  end

  def reserve_all(user, res_notes = '', request = false)
    # reserve all the items in the cart!
    # takes 3 arguments which is the current user, whether or not
    # the equipment should be requested or reserved,
    # and what notes the reservations should be initialized with
    reservations = prepare_all
    msgs = []

    if request
      reservations.each { |r| msgs << create_request(r, user, res_notes) }
    else
      reservations.each { |r| msgs << create_reservation(r, user, res_notes) }
    end

    purge_all

    msgs.join(' ') # return flash message
  end

  def request_all(user, notes = '')
    reserve_all(user, notes, true)
  end

  # Returns the cart's duration
  def duration # in days
    @due_date - @start_date + 1
  end

  # Returns the reserver
  def reserver
    User.find(@reserver_id)
  end

  def fix_due_date
    return unless @start_date > @due_date
    @due_date = @start_date + 1.day
  end

  # make sure that we don't have any non-existant models in our cart that
  # would cause errors when rendering
  def fix_items
    valid_items = EquipmentModel.where(id: items.keys).collect(&:id)
    self.items = items.select { |em, _count| valid_items.include? em }
  end

  private

  # create a reservation with the appropriate notes and update the message
  # array appropriately; returns the updated message array
  def create_reservation(res, user, res_notes)
    errors = res.validate
    notes = "### Reserved on #{Time.zone.now.to_s(:long)} by "\
          "#{user.md_link} for #{res.reserver.md_link}"
    notes += "\n\n#### Notes:\n#{res_notes}" unless res_notes.nil? ||
                                                    res_notes.empty?
    res.status = 'reserved'
    res.notes = notes
    res.save!

    if AppConfig.get(:notify_admin_on_create) # send e-mail if configured to
      AdminMailer.reservation_created_admin(res).deliver
    end
    "Reservation for #{res.equipment_model.md_link} created "\
      "successfully#{', even though ' + errors.to_sentence[0, 1].downcase\
      + errors.to_sentence[1..-1] unless errors.empty?}.\n"
  end

  # create a request with the appropriate notes and update the message array
  # appropriately; returns the updated message array
  def create_request(res, user, res_notes)
    errors = res.validate
    notes = "### Requested on #{Time.zone.now.to_s(:long)} by "\
      "#{user.md_link}\n\n#### Notes:\n#{res_notes}"
    res.flag(:request)
    res.status = 'requested'
    res.notes = notes
    res.save!

    AdminMailer.request_filed(res).deliver # send request notification
    "Request for #{res.equipment_model.md_link} filed successfully. "\
      "#{errors.to_sentence}\n"
  end
end


text:
describe('Collection', function () {
  it('should be able to be created')
  it('should be able to be assigned as a child')
  it('should return children')
  it('should return affiliated articles')
})


text:
package com.netflix.astyanax.query;

import com.netflix.astyanax.Execution;
import com.netflix.astyanax.model.CqlResult;

/**
 * Interface for executing a CQL query.
 *
 * @author elandau
 *
 * @param <K>
 * @param <C>
 */
public interface CqlQuery<K, C> extends Execution<CqlResult<K, C>> {
    /**
     * Turns on compression for the response
     *
     * @return
     */
    CqlQuery<K, C> useCompression();

    /**
     * Prepares the provided CQL statement.  The statement is not executed
     * here.  Call, withPreparedStatement to execute the prepared statement
     * with variables.
     * @return
     */
    PreparedCqlQuery<K,C> asPreparedStatement();
}


text:
package bingo.meta.edm.types;

import bingo.meta.annotations.ComplexType;

@ComplexType
public class Address {

	private String country;

	private String postCode;

	private String region;

	private String street;

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getPostCode() {
		return postCode;
	}

	public void setPostCode(String postCode) {
		this.postCode = postCode;
	}

	public String getRegion() {
		return region;
	}

	public void setRegion(String region) {
		this.region = region;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}
}


text:
module Csound.Control.Overload(
    Outs(..), onArg, MidiInstr(..), MidiInstrTemp(..), AmpInstr(..), CpsInstr(..)
) where

import Csound.Control.Overload.Outs
import Csound.Control.Overload.MidiInstr
import Csound.Control.Overload.SpecInstr


text:
namespace CefSharp
{
    namespace Internals
    {
        namespace Async
        {
            private ref class JavascriptAsyncMethodCallback
            {
            private:
                MCefRefPtr<CefV8Context> _context;
                MCefRefPtr<CefV8Value> _resolve;
                MCefRefPtr<CefV8Value> _reject;

            public:
                JavascriptAsyncMethodCallback(CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Value> resolve, CefRefPtr<CefV8Value> reject)
                    :_context(context), _resolve(resolve.get()), _reject(reject.get())
                {

                }

                !JavascriptAsyncMethodCallback()
                {
                    _resolve = nullptr;
                    _reject = nullptr;
                    _context = nullptr;
                }

                ~JavascriptAsyncMethodCallback()
                {
                    this->!JavascriptAsyncMethodCallback();
                }

                void Success(const CefRefPtr<CefV8Value>& result);

                void Fail(const CefString& exception);
            };
        }
    }
}


text:
@interface TTKeyboardphobia ()
@property (nonatomic, strong) NSMutableArray *views;
@property (nonatomic, assign) CGPoint contentOffset;
@property (nonatomic, assign) UIEdgeInsets contentInset;
@property (nonatomic, assign) UIEdgeInsets scrollIndicatorInsets;
@property (nonatomic, assign, readwrite) BOOL isKeyboardVisible;

@end

@implementation TTKeyboardphobia

+ (BOOL)isKeyboardVisible {
    return [[self sharedInstance] isKeyboardVisible];
}

+ (void)load {
    [self sharedInstance];
}

- (id)init {
    self = [super init];
    if (self) {
        _isKeyboardVisible = NO;
        _views = [@[] mutableCopy];
        _contentOffset = CGPointZero;
        _contentInset = UIEdgeInsetsZero;
        _scrollIndicatorInsets = UIEdgeInsetsZero;
        [self addObservers];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self unregisterViews];
}

- (void)registerView:(UIView *)view {
    [self registerView:view inScrollView:nil];
}

- (void)registerView:(UIView *)view inScrollView:(UIScrollView *)scrollView {
    if (scrollView) {
        [self.views addObject:NSDictionaryOfVariableBindings(view, scrollView)];
    } else {
        [self.views addObject:NSDictionaryOfVariableBindings(view)];
    }
}

- (void)unregisterView:(UIView *)view {
    NSDictionary *doomedPair = nil;

    for (NSDictionary *pair in self.views) {
        UIView *pairView = pair[@"view"];
        if (pairView == view) {
            doomedPair = pair;
            break;
        }
    }

    if (doomedPair) {
        [self.views removeObject:doomedPair];
    }

    if ([self.views count] == 0) {
        [self unregisterViews];
    }
}

- (void)unregisterViews {
    self.views = [@[] mutableCopy];
}

#pragma mark - Private

+ (TTKeyboardphobia *)sharedInstance {
    static TTKeyboardphobia *sharedInstance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (void)keyboardDidShowNotification:(NSNotification *)notification {
    self.hideKeyboardTap.enabled = YES;
}

- (void)keyboardDidHideNotification:(NSNotification *)notification {
    self.isKeyboardVisible = NO;
    self.hideKeyboardTap.enabled = NO;
}

- (void)keyboardWillShowNotification:(NSNotification *)notification {
    BOOL keyboardAlreadyVisible = self.isKeyboardVisible;
    self.isKeyboardVisible = YES;
    NSDictionary *pair = [self viewContainingFirstResponder];

    if (pair) {
        UIView *view = pair[@"view"];
        UIScrollView *scrollView = pair[@"scrollView"];

        if (scrollView) {
            CGSize kbSize = [self keyboardSizeForNotification:notification];

            if (keyboardAlreadyVisible) {
                CGPoint contentOffsetMinusKeyboard = CGPointMake(scrollView.contentOffset.x, scrollView.contentOffset.y - kbSize.height);
                self.contentOffset = contentOffsetMinusKeyboard;
            } else {
                self.contentInset = scrollView.contentInset;
                self.scrollIndicatorInsets = scrollView.scrollIndicatorInsets;
                self.contentOffset = scrollView.contentOffset;
            }

            UIResponder *responder = [self firstResponderInView:view];

            [self scrollToView:view inScrollView:scrollView forNotification:notification withResponder:responder keyboardAlreadyVisible:keyboardAlreadyVisible];
        }
    }
}

- (void)keyboardWillHideNotification:(NSNotification *)notification {
    NSDictionary *pair = [self viewContainingFirstResponder];

    if (pair) {
        UIScrollView *scrollView = pair[@"scrollView"];

        if (scrollView) {
            [self resetScrollView:scrollView forNotification:notification];
        }
    }
}

- (NSDictionary *)viewContainingFirstResponder {
    for (NSDictionary *pair in self.views) {
        if ([self viewContainsFirstResponder:pair[@"view"]]) {
            return pair;
        }
    }

    return nil;
}

- (BOOL)viewContainsFirstResponder:(UIView *)view {
    return [self firstResponderInView:view] != nil;
}

- (UIResponder *)firstResponderInView:(UIView *)view {
    if ([view isFirstResponder]) {
        return view;
    }

    for (UIView *subview in [view subviews]) {
        UIResponder *responder = [self firstResponderInView:subview];

        if (responder) {
            return responder;
        }
    }

    return nil;
}

- (NSString *)keyForView:(UIView *)view {
    return [NSString stringWithFormat:@"%p", view];
}

- (void)scrollToView:(UIView *)view inScrollView:(UIScrollView *)scrollView forNotification:(NSNotification *)notification withResponder:(UIResponder *)responder keyboardAlreadyVisible:(BOOL)keyboardAlreadyVisible {
    CGSize kbSize = [self keyboardSizeForNotification:notification];
    [self setInsetsOnScrollView:scrollView forKeyboardSize:kbSize];

    UIView *accessoryView = responder.inputAccessoryView;
    CGRect visibleRect = scrollView.superview.frame;
    visibleRect.size.height -= kbSize.height;

    if (accessoryView) {
        visibleRect.size.height -= accessoryView.frame.size.height;
    }

    CGPoint origin = [view.superview convertPoint:view.frame.origin toView:scrollView.superview];

    if (visibleRect.origin.y > 0) {
        // In a view that contains a navigation bar, the scrollView's superview
        // Y coordiante will reflect this. However the editable view's superview
        // (which is likely a inside a content view) will have a Y coordinate of 0.
        // We need to act as if the both superviews are at the same coordinate.
        origin.y += visibleRect.origin.y;
    }

    CGPoint bottom = origin;
    bottom.y += view.frame.size.height;

    if (!CGRectContainsPoint(visibleRect, origin) || !CGRectContainsPoint(visibleRect, bottom)) {
        CGRect frame = view.frame;
        BOOL isOversized = frame.size.height > visibleRect.size.height;
        BOOL hasAccessoryView = accessoryView != nil;

        if (isOversized) {
            frame.size.height = visibleRect.size.height;

            if (hasAccessoryView) {
                // Oversized views with an inputAccessoryView need their Y origin
                // pushed down to ensure the to edge pins to the top of the superview.
                frame.origin.y += accessoryView.frame.size.height;
            }

            [self scrollRectToVisible:frame inScrollView:scrollView forNotification:notification keyboardAlreadyVisible:keyboardAlreadyVisible];
            return;
        }

        if (hasAccessoryView && keyboardAlreadyVisible) {
            // When an input becomes first responder and the keyboard is already
            // visible, the inputAccessoryView is not yet visible and scrollRectToVisible
            // is not able to correctly calculate the contentOffset.
            frame.origin.y += accessoryView.frame.size.height;
        }

        [self scrollRectToVisible:frame inScrollView:scrollView forNotification:notification keyboardAlreadyVisible:keyboardAlreadyVisible];
    }
}

- (void)scrollRectToVisible:(CGRect)frame inScrollView:(UIScrollView *)scrollView forNotification:(NSNotification *)notification keyboardAlreadyVisible:(BOOL)keyboardAlreadyVisible {
    if (keyboardAlreadyVisible) {
        [scrollView scrollRectToVisible:frame animated:YES];
    } else {
        [UIView tt_animateWithKeyboardNotification:notification animations:^{
            [scrollView scrollRectToVisible:frame animated:NO];
        }];
    }
}

- (void)resetScrollView:(UIScrollView *)scrollView forNotification:(NSNotification *)notification {
    [UIView tt_animateWithKeyboardNotification:notification animations:^{
        scrollView.contentOffset = self.contentOffset;
        scrollView.contentInset = self.contentInset;
        scrollView.scrollIndicatorInsets = self.scrollIndicatorInsets;
    }];
}

- (void)setInsetsOnScrollView:(UIScrollView *)scrollView forKeyboardSize:(CGSize)kbSize {
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;
}

- (CGSize)keyboardSizeForNotification:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    return [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
}

- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShowNotification:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidShowNotification:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHideNotification:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHideNotification:)
                                                 name:UIKeyboardDidHideNotification object:nil];
}

@end


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class AddHalo5MatchesFields extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('halo5_matches', function (Blueprint $table) {
            $table->uuid('map_variant')->nullable();
            $table->uuid('game_variant')->nullable();
            $table->uuid('playlist_id')->nullable(); // Playlist
            $table->uuid('map_id')->nullable(); // Map
            $table->uuid('gamebase_id')->nullable(); // GameType
            $table->uuid('season_id')->nullable(); // Season

            $table->index('playlist_id');
            $table->index('map_id');
            $table->index('gamebase_id');
            $table->index('season_id');

            $table->foreign('playlist_id')->references('contentId')->on('halo5_playlists');
            $table->foreign('map_id')->references('uuid')->on('halo5_maps');
            $table->foreign('gamebase_id')->references('uuid')->on('halo5_gametypes');
            $table->foreign('season_id')->references('contentId')->on('halo5_seasons');
            $table->boolean('isTeamGame');
        });

        Schema::create('halo5_matches_teams', function (Blueprint $table) {
            $table->uuid('uuid')->unique();
            $table->uuid('game_id');

            $table->string('key', 38)->unique();

            $table->tinyInteger('team_id', false, true);
            $table->integer('score', false, true);
            $table->integer('rank', false, true);
            $table->json('round_stats')->nullable();

            $table->index('key');

            $table->foreign('team_id')->references('id')->on('halo5_teams');
            $table->foreign('game_id')->references('uuid')->on('halo5_matches');
            $table->primary('uuid');
        });

        Schema::create('halo5_matches_players', function (Blueprint $table) {
            $table->uuid('uuid')->unique();
            $table->primary('uuid');
            $table->uuid('game_id');

            $table->integer('account_id', false, true);
            $table->string('team_id', 38)->nullable();
            $table->index('team_id');

            $table->json('killed');
            $table->json('killed_by');
            $table->json('medals');
            $table->json('enemies');
            $table->json('weapons');
            $table->json('impulses');

            $table->tinyInteger('warzone_req', false, true)->nullable();
            $table->mediumInteger('total_pies', false, true)->nullable();

            $table->tinyInteger('rank', false, true);
            $table->boolean('dnf');
            $table->integer('avg_lifestime', false, true);

            $table->integer('totalKills', false, true);
            $table->integer('totalSpartanKills', false, true);
            $table->integer('totalAiKills', false, true);
            $table->integer('totalHeadshots', false, true);
            $table->integer('totalDeaths', false, true);
            $table->integer('totalAssists', false, true);
            $table->integer('totalTimePlayed', false, true);

            $table->float('weapon_dmg', 10, 4);
            $table->integer('shots_fired', false, true);
            $table->integer('shots_landed', false, true);

            $table->integer('totalMeleeKills', false, true);
            $table->integer('totalAssassinations', false, true);
            $table->integer('totalGroundPounds', false, true);
            $table->integer('totalShoulderBash', false, true);
            $table->integer('totalGrenadeKills', false, true);
            $table->integer('totalPowerWeaponKills', false, true);

            $table->integer('totalPowerWeaponTime', false, true);

            $table->tinyInteger('spartanRank', false, true);
            $table->tinyInteger('CsrTier', false, true)->nullable();
            $table->tinyInteger('CsrDesignationId', false, true)->nullable();
            $table->integer('Csr', false, true)->nullable();
            $table->integer('percentNext', false, true)->nullable();
            $table->integer('ChampionRank', false, true)->nullable();

            $table->foreign('game_id')->references('uuid')->on('halo5_matches');
            $table->foreign('CsrTier')->references('designationId')->on('halo5_csrs');
            $table->foreign('team_id')->references('key')->on('halo5_matches_teams');
            $table->foreign('account_id')->references('id')->on('accounts');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('halo5_matches', function (Blueprint $table) {
            $table->dropForeign('halo5_matches_gamebase_id_foreign');
            $table->dropForeign('halo5_matches_map_id_foreign');
            $table->dropForeign('halo5_matches_playlist_id_foreign');
            $table->dropForeign('halo5_matches_season_id_foreign');

            $table->dropColumn([
                'map_variant',
                'game_variant',
                'playlist_id',
                'map_id',
                'gamebase_id',
                'season_id',
                'isTeamGame',
            ]);
        });

        Schema::dropIfExists('halo5_matches_teams');

        Schema::dropIfExists('halo5_matches_players');
    }
}


text:
<?php

namespace LegalThings\DataEnricher\Processor;

use LegalThings\DataEnricher\Node;
use LegalThings\DataEnricher\Processor;

/**
 * @covers LegalThings\DataEnricher\Processor\Serialize
 */
class SerializeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Processor\Serialize;
     */
    protected $processor;

    public function setUp()
    {
        $this->processor = new Processor\Serialize('<serialize>');
    }

    public function instructionProvider()
    {
        return [
            [['input' => ['foo' => 'bar', 'flag' => true], 'format' => 'json'], '{"foo":"bar","flag":true}'],
            [['input' => ['foo' => 'bar', 'flag' => true], 'format' => 'url'], 'foo=bar&flag=1']
        ];
    }

    /**
     * @dataProvider instructionProvider
     *
     * @param string|object|array $instruction
     * @param object              $source
     * @param array|object        $target
     * @param string|object|array $result
     */
    public function testApplyToNode($instruction, $result)
    {
        $node = $this->createMock(Node::class);

        $node->expects($this->atLeastOnce())
            ->method('getInstruction')
            ->with($this->processor)
            ->willReturn($instruction);

        $node->expects($this->atLeastOnce())
            ->method('setResult')
            ->with($result);

        $this->processor->applyToNode($node);
    }
}


text:
%% $Date: 2012-07-06 17:42:54#$
%% $Revision: 148 $
\index{temp\_static\_cnrm}
\algdesc{Static Temperature}
{ %%%%%% Algorithm name %%%%%%
temp\_static\_cnrm
}
{ %%%%%% Algorithm summary %%%%%%
Calculates static temperature of the air from total temperature.
This method applies to probe types such as the Rosemount.
}
{ %%%%%% Category %%%%%%
Thermodynamics
}
{ %%%%%% Inputs %%%%%%
$T_t$ &	Vector & Measured total temperature [K] \\
${\Delta}P$ & Vector & Dynamic pressure [hPa] \\
$P_s$ & Vector & Static pressure [hPa] \\
$r_f$ & Coeff. & Probe recovery coefficient \\
$R_a/c_{pa}$ & Coeff. & Gas constant of air divided by specific heat of air at constant pressure
}
{ %%%%%% Outputs %%%%%%
$T_s$ & Vector & Static temperature [K]
}
{ %%%%%% Formula %%%%%%
\begin{displaymath}
 T_s = \frac{T_t}{1+r_f \left(\left(1+\frac{\Delta P}{P_s}\right)^{R_a/c_{pa}}-1\right)} \nonumber
\end{displaymath}
}
{ %%%%%% Author %%%%%%
CNRM/GMEI/TRAMM
}
{ %%%%%% References %%%%%%
}


text:
import React, { useState } from 'react';
import { Button, Checkbox } from 'antd';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';

const App: React.FC = () => {
  const [checked, setChecked] = useState(true);
  const [disabled, setDisabled] = useState(false);

  const toggleChecked = () => {
    setChecked(!checked);
  };

  const toggleDisable = () => {
    setDisabled(!disabled);
  };

  const onChange = (e: CheckboxChangeEvent) => {
    console.log('checked = ', e.target.checked);
    setChecked(e.target.checked);
  };

  const label = `${checked ? 'Checked' : 'Unchecked'}-${disabled ? 'Disabled' : 'Enabled'}`;

  return (
    <>

        <Checkbox checked={checked} disabled={disabled} onChange={onChange}>
          {label}
        </Checkbox>

        <Button type="primary" size="small" onClick={toggleChecked}>
          {!checked ? 'Check' : 'Uncheck'}
        </Button>
        <Button style={{ margin: '0 10px' }} type="primary" size="small" onClick={toggleDisable}>
          {!disabled ? 'Disable' : 'Enable'}
        </Button>

    </>
  );
};

export default App;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('forum', '0003_auto_20150525_0031'),
    ]

    operations = [
        migrations.AddField(
            model_name='link',
            name='disagree',
            field=models.IntegerField(default=0),
        ),
    ]


text:
//
//  VTNodeDevice+Chroma.h
//  Copyright (c) 2013 Variable Technologies. All rights reserved.
//

#include "VTRGBCReading.h"
#include "VTChromaMatchColorSet.h"

/**
 The `NodeChromaDeviceDelegate` protocol defines the optional Chroma module related methods implemented by delegates of the `VTNodeDevice` class
 */
@protocol NodeChromaDeviceDelegate <NSObject>
@optional
/** Invoked to provide app with requested Chroma Device to use for getting Chroma readings. Provided in response to requestVTChromaDeviceInstance
 @param device The device that communicated the reading
 @param chromaDevice - VTChromaDevice for use with requestChromaReading
 */
-(void) nodeDeviceDidUpdate:(VTNodeDevice *)device withVTChromaDevice:(VTChromaDevice*)chromaDevice;

/** Invoked to provide the app with progress information for the handshake process in requestVTChromaDeviceInstance
 @param device The device that communicated the reading
 @param progressPercent A float representation of the % completion of handshake
 @param message NSString information on handshake progress - can be printed to screen in the app if desired.
 */
-(void) nodeDeviceDidUpdateHandshakeProgress:(VTNodeDevice *)device withProgress:(NSNumber*)progressPercent withMessage:(NSString*)message;

/** Invoked when a Node device has communicated a color reading from an attached Chroma module
 @param device The device that communicated the reading
 @param reading A VTRGBCReading object containing the color values read
 */
-(void) nodeDeviceDidUpdateChromaReading:(VTNodeDevice *) device withReading:(VTRGBCReading *) reading;

/** Invoked when a Node device has communicated a temperature reading in C from an attached Chroma module
 @param device The device that communicated the reading
 @param temperature A float representation of the temp in chroma in deg C
 */
-(void) nodeDeviceDidUpdateChromaTemp:(VTNodeDevice *) device withTemperature:(float)temperature;

/** Invoked to notify app that the connected Chroma has completed the requested whitepoint calibration
 @param device The device that communicated the reading
 @param status Pass/Fail condition of whitepoint calibration
 */
-(void)nodeDeviceDidCompleteChromaWhitePointCal:(VTNodeDevice *) device withStatus:(BOOL)status;

/** Invoked to notify app that has communicated a best match against a color set
 @param device The device that communicated the reading
 @param chromaDevice Chroma Instance that the reading was performed on
 @param reading "unadjusted" reading used for performing library lookup
 @param results array of VTChromaMatchColor objects providing the best matches
 @param error shows any related error data if lookup failed.
 @param adjustedReading is the adjusted reading that shows the most accurate (closest to spectrometer) data value for this scan
 */
-(void)nodeDeviceDidProvideChromaMatchResults:(VTNodeDevice *) device usingVTChromaDevice: (VTChromaDevice *)chromaDevice usingReading: (VTRGBCReading *)reading withResults:(NSArray *)results error:(NSError*)error adjustedReading:(VTRGBCReading*)adjustedReading;

@end

@interface VTNodeDevice (Chroma)

/** Request the NODE API to create a VTChromaDevice instance with all the required calibration/batching data and provide instance back to the app layer
    This method performs an HTTP request to retrieve the required Chroma data.
 */
-(void)requestVTChromaDeviceInstance;

/** Request a Chroma reading for a specific device
 @param chromaDevice The Chroma device's class w/ specific parameters for calibration and type
 */
-(void) requestChromaReadingWChromaDevice:(VTChromaDevice *)chromaDevice;

/** Request a Chroma reading for a specific device using 2˚ or 10˚ math
 @param chromaDevice The Chroma device's class w/ specific parameters for calibration and type
 @param observer Standard Observer functions (options are either 1964 10˚ observer or 1931 2˚ observer (2˚ is the default and most commonly used)
 */
-(void)requestChromaReadingWChromaDevice:(VTChromaDevice *)chromaDevice observer:(VTColorUtilsObserver)observer;

/** Request a "Batch Relative" Chroma reading for a specific device.
 Batch relative readings are readings that guarantee that your color reading will be within ∆E1.5 to the batch master unit that the Chroma belongs to.
 @param chromaDevice The Chroma device's class w/ specific parameters for calibration and type
 */
-(void) requestBatchRelativeChromaReadingWChromaDevice:(VTChromaDevice *)chromaDevice;

/** Request Chroma  1.1+ to perform whitepoint calibration using end cap and
 @param cryptoSet array from Chroma module (get this using requestCryptoData).
 */
-(void)requestChromaWhitePointCalWith:(VTChromaDevice *)chromaDevice;

/** Clear Chroma  1.1+ whitepoint calibration - use default calibration
 */
-(void)clearChromaWhitePointCal;

/** Request a the temperature in degrees C within the Chroma module (valid for CHroma 1.1 and newer).
    The requestChromaReadingWChromaDevice: auto-sends temperature to delegate, so the below is depreciated
 @param takeNewTemperatureReading is a bool used to request new temp reading instead of the last reading seen @ color read
 */
-(void) requestChromaTemp:(BOOL)takeNewTemperatureReading __deprecated;;

/**
    Request a Chroma match reading
    @param colorset The VTChromaMatchColorSet from which to match
    @param device A valid VTChromaDevice object to use for color math
 */
- (void) requestChromaMatchReadingUsingColorSet: (VTChromaMatchColorSet *)colorSet withDevice: (VTChromaDevice *)device;

/**
 Request a Chroma match reading from all available color sets.
 @param device A valid VTChromaDevice object to use for color math
 */
- (void) requestChromaMatchReadingUsingColorSets: (NSArray *)colorSets UsingDevice: (VTChromaDevice *)device;

@end


text:
import AssignName from './AssignName';
import TagDoc from './TagDoc';
import { YardMethod } from './DocData';

export type MethodDocProps = {
  method: YardMethod;
  prefix?: string;
};

function MethodDoc({ method, prefix }: MethodDocProps): JSX.Element {
  if (method.tags.some((tag) => tag.tag_name === 'api')) {
    return <></>;
  }

  const sortedTags = method.tags.sort((a, b) => {
    // examples go last
    if (a.tag_name === 'example' && b.tag_name !== 'example') {
      return 1;
    }

    if (b.tag_name === 'example' && a.tag_name !== 'example') {
      return -1;
    }

    return 0;
  });

  return (

          <AssignName assign={method} prefix={prefix} />

      {method.docstring &&
{method.docstring}
}

        {sortedTags.map((tag, i) => (
          // eslint-disable-next-line react/no-array-index-key
          <TagDoc tag={tag} key={`${tag.tag_name}-${i}`} method={method} prefix={prefix} />
        ))}

  );
}

export default MethodDoc;


text:
/*
 * @test
 * @bug 6471865 6675768
 * @summary DescriptorSupport constructors throw IAE when traces are enabled;
 * RequiredModelMBean.addAttributeChangeNotificationListener throws exception
 * when traces enabled and no attributes.
 * @author Luis-Miguel Alventosa
 * @author Paul Cheeseman
 */

import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.modelmbean.DescriptorSupport;
import javax.management.modelmbean.RequiredModelMBean;

public class LoggingExceptionTest {
    private static final String tests[] = new String[] {
        "DescriptorSupport()",
        "DescriptorSupport(int)",
        "DescriptorSupport(String)",
        "DescriptorSupport(String...)",
        "DescriptorSupport(String[], Object[])",
        "DescriptorSupport(DescriptorSupport)",
        "RequiredModelMBean.addAttributeChangeNotificationListener",
    };
    public static void main(String[] args) {
        Handler handler = new ConsoleHandler();
        Logger logger = Logger.getLogger("javax.management.modelmbean");
        logger.addHandler(handler);
        logger.setLevel(Level.FINEST);
        try {
            for (int i = 0; i < tests.length; i++) {
                System.out.println(">>> DescriptorSupportLoggingTest: Test Case " + i);
                DescriptorSupport ds;
                String msg = "Instantiate " + tests[i];
                System.out.println(msg);
                switch (i) {
                    case 0:
                        ds = new DescriptorSupport();
                        break;
                    case 1:
                        ds = new DescriptorSupport(10);
                        break;
                    case 2:
                        ds = new DescriptorSupport(new DescriptorSupport().toXMLString());
                        break;
                    case 3:
                        ds = new DescriptorSupport("name1=value1", "name2=value2");
                        break;
                    case 4:
                        ds = new DescriptorSupport(new String[] {"name"}, new Object[] {"value"});
                        break;
                    case 5:
                        ds = new DescriptorSupport(new DescriptorSupport());
                        break;
                    case 6:
                        RequiredModelMBean mbean = new RequiredModelMBean();
                        NotificationListener nl = new NotificationListener() {
                            public void handleNotification(Notification notification,
                                                           Object handback) {}
                        };
                        mbean.addAttributeChangeNotificationListener(nl, null, null);
                        break;
                    default:
                        throw new AssertionError();
                }
                System.out.println(msg + " OK");
            }
        } catch (Exception e) {
            System.out.println("Got unexpected exception = " + e);
            String msg = "Test FAILED!";
            System.out.println(msg);
            throw new IllegalArgumentException(msg);
        }
        System.out.println("Test PASSED!");
    }
}


text:
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import PropTypes from 'prop-types';

import * as actionCreators from '../../actions/data';

class Posts extends React.Component {

    static propTypes = {
        isFetching: PropTypes.bool.isRequired,
        data: PropTypes.object,
        actions: PropTypes.shape({
            dataFetchData: PropTypes.func.isRequired
        }).isRequired
    };

    static defaultProps = {
        data: ''
    };

    // Note: have to use componentWillMount, if I add this in constructor will get error:
    // Warning: setState(...): Cannot update during an existing state transition (such as within `render`).
    // Render methods should be a pure function of props and state.
    componentWillMount() {
        this.props.actions.dataFetchData(this.props.location);
    }

    renderContent(data) {
      if(data) {
        return (

{data.title}

              {data.text}

            {data.post_type}

        );
      }
    }

    render() {
      const props = this.props;
      console.log('da props', props.data);
        return (

                {this.renderContent(props.data)}

        );
    }
}

const mapStateToProps = (state) => {
    return {
        data: state.data.data,
        isFetching: state.data.isFetching
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        actions: bindActionCreators(actionCreators, dispatch)
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(Posts);
export { Posts as PostsNotConnected };


text:
function IoU = bbIntersectionOverUnion( candidates, reference )
%bbIntersectionOverUnion computes the IoU score between bounding boxes.
% For two bounding boxes the IoU score is the area of the intersection divided by the area of the union
%
% IoU = bbIntersectionOverUnion( candidates, reference );
%
% Input:
%   candidates - the candidate bounding boxes, double[ numBoundingBoxes x 4]
%   reference - the reference bounding box, double[ 1 x 4]
%
%   Format for the bounding box representation: [x y w h]
%       (x, y) - position of the upper left corner
%       origin (0, 0) is the upper left corner of the image
%
% Output:
%   IoU - vector of the scores, double[ numBoundingBoxes, 1 ]

if ~isnumeric( candidates ) || size( candidates, 2 ) ~= 4
    error('bbIntersectionOverUnion:badInputCandidates', 'Input <candidates> is of incorrect format');
end
if ~isnumeric( reference ) || size( reference, 2 ) ~= 4 || size( reference, 1 ) ~= 1
    error('bbIntersectionOverUnion:badInputReference', 'Input <reference> is of incorrect format');
end

area = bbIntersectionArea( candidates, reference );
IoU = area ./ (candidates(:,3) .* candidates(:,4) + reference(3) * reference(4) - area);

end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

    <title>DeviceInterfaceModule</title>
    <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

            Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.qualcomm.robotcore.hardware

Interface DeviceInterfaceModule

All Superinterfaces:

                        AnalogInputController,
                        AnalogOutputController,
                        DigitalChannelController,
                        HardwareDevice,
                        I2cController,
                        PWMOutputController

public interface DeviceInterfaceModule
extends DigitalChannelController, AnalogInputController, PWMOutputController, I2cController, AnalogOutputController

DeviceInterfaceModule for working with various devices

Nested Class Summary

Nested classes/interfaces inherited from interface com.qualcomm.robotcore.hardware.DigitalChannelController

                                DigitalChannelController.Mode

Nested classes/interfaces inherited from interface com.qualcomm.robotcore.hardware.I2cController

                                I2cController.I2cPortReadyBeginEndNotifications,
                                    I2cController.I2cPortReadyCallback

Nested classes/interfaces inherited from interface com.qualcomm.robotcore.hardware.HardwareDevice

                                HardwareDevice.Manufacturer

Field Summary

Fields inherited from interface com.qualcomm.robotcore.hardware.I2cController

                                I2C_BUFFER_START_ADDRESS

Method Summary

Methods

                                Modifier and Type
                                Method and Description

                                int
                                getDigitalInputStateByte()

A byte containing the current logic levels
                                        present in the D7-D0 channel pins.

                                byte
                                getDigitalIOControlByte()

Get the digital IO control byte

                                byte
                                getDigitalOutputStateByte()

The D7-D0 output set field is a byte
                                        containing the required I/O output of the D7-D0
                                        channel pins.

                                boolean
                                getLEDState(int channel)

Indicates whether the LED on the given
                                        channel is on or not

                                void
                                setDigitalIOControlByte(byte input)

If a particular bit is set to one, the
                                        corresponding channel pin will be in output mode.

                                void
                                setDigitalOutputByte(byte input)

If a a particular control field bit is set to
                                        one, the channel pin will be in output mode and
                                        will reflect the value of the corresponding field bit.

                                void
                                setLED(int channel,
                                    boolean state)

Turn on or off a particular LED

Methods inherited from interface com.qualcomm.robotcore.hardware.DigitalChannelController

                                getDigitalChannelMode,
                                    getDigitalChannelState,
                                    getSerialNumber,
                                    setDigitalChannelMode,
                                    setDigitalChannelState

Methods inherited from interface com.qualcomm.robotcore.hardware.AnalogInputController

                                getAnalogInputVoltage,
                                    getMaxAnalogInputVoltage,
                                    getSerialNumber

Methods inherited from interface com.qualcomm.robotcore.hardware.PWMOutputController

                                getPulseWidthOutputTime,
                                    getPulseWidthPeriod,
                                    getSerialNumber,
                                    setPulseWidthOutputTime,
                                    setPulseWidthPeriod

Methods inherited from interface com.qualcomm.robotcore.hardware.I2cController

                                clearI2cPortActionFlag,
                                    copyBufferIntoWriteBuffer,
                                    deregisterForPortReadyBeginEndCallback,
                                    deregisterForPortReadyCallback,
                                    enableI2cReadMode,
                                    enableI2cWriteMode,
                                    getCopyOfReadBuffer,
                                    getCopyOfWriteBuffer,
                                    getI2cPortReadyCallback,
                                    getI2cReadCache,
                                    getI2cReadCacheLock,
                                    getI2cWriteCache,
                                    getI2cWriteCacheLock,
                                    getPortReadyBeginEndCallback,
                                    getSerialNumber,
                                    isArmed,
                                    isI2cPortActionFlagSet,
                                    isI2cPortInReadMode,
                                    isI2cPortInWriteMode,
                                    isI2cPortReady,
                                    readI2cCacheFromController,
                                    readI2cCacheFromModule,
                                    registerForI2cPortReadyCallback,
                                    registerForPortReadyBeginEndCallback,
                                    setI2cPortActionFlag,
                                    writeI2cCacheToController,
                                    writeI2cCacheToModule,
                                    writeI2cPortFlagOnlyToController,
                                    writeI2cPortFlagOnlyToModule

Methods inherited from interface com.qualcomm.robotcore.hardware.AnalogOutputController

                                getSerialNumber,
                                    setAnalogOutputFrequency,
                                    setAnalogOutputMode,
                                    setAnalogOutputVoltage

Methods inherited from interface com.qualcomm.robotcore.hardware.HardwareDevice

                                close,
                                    getConnectionInfo,
                                    getDeviceName,
                                    getManufacturer,
                                    getVersion,
                                    resetDeviceConfigurationForOpMode

Method Detail

getDigitalInputStateByte

int getDigitalInputStateByte()

A byte containing the current logic levels
                                    present in the D7-D0 channel pins.
                                    If a particular pin is in output mode, the current output state
                                    will be reported.

setDigitalIOControlByte

void setDigitalIOControlByte(byte input)

If a particular bit is set to one, the
                                    corresponding channel pin will be in output mode.
                                    Else it will be in input mode.

Parameters:

input - - the desired setting for each channel
                                        pin.

getDigitalIOControlByte

byte getDigitalIOControlByte()

Get the digital IO control byte

Returns:

control byte

setDigitalOutputByte

void setDigitalOutputByte(byte input)

If a a particular control field bit is set to
                                    one, the channel pin will be in output mode and
                                    will reflect the value of the corresponding field bit.

Parameters:

input - with output state of the digital pins.

getDigitalOutputStateByte

byte getDigitalOutputStateByte()

The D7-D0 output set field is a byte containing
                                    the required I/O output of the D7-D0
                                    channel pins. If the corresponding Dy-D0 I/O control field bit
                                    is set to one, the channel pin
                                    will be in output mode and will reflect the value of the
                                    corresponding D7-D0 output set field bit.

Returns:

D7-D0 output set field.

getLEDState

boolean getLEDState(int channel)

Indicates whether the LED on the given channel is
                                    on or not

Returns:

true for ON, false for OFF

setLED

void setLED(int channel,
          boolean state)

Turn on or off a particular LED

Parameters:

channel - - int indicating the ID of the LED.

state - - byte containing the desired setting.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

            Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package org.jboss.netty.channel.socket.nio;

import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelConfig;

/**
 * Special {@link ChannelConfig} sub-type which offers extra methods which are useful for NIO.
 *
 */
public interface NioChannelConfig extends ChannelConfig {

    /**
     * Returns the high water mark of the write buffer.  If the number of bytes
     * queued in the write buffer exceeds this value, {@link Channel#isWritable()}
     * will start to return {@code false}.
     */
    int getWriteBufferHighWaterMark();

    /**
     * Sets the high water mark of the write buffer.  If the number of bytes
     * queued in the write buffer exceeds this value, {@link Channel#isWritable()}
     * will start to return {@code false}.
     */
    void setWriteBufferHighWaterMark(int writeBufferHighWaterMark);

    /**
     * Returns the low water mark of the write buffer.  Once the number of bytes
     * queued in the write buffer exceeded the
     * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
     * dropped down below this value, {@link Channel#isWritable()} will start to return
     * {@code true} again.
     */
    int getWriteBufferLowWaterMark();

    /**
     * Sets the low water mark of the write buffer.  Once the number of bytes
     * queued in the write buffer exceeded the
     * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then
     * dropped down below this value, {@link Channel#isWritable()} will start toreturn
     * {@code true} again.
     */
    void setWriteBufferLowWaterMark(int writeBufferLowWaterMark);

    /**
     * Returns the maximum loop count for a write operation until
     * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
     * It is similar to what a spin lock is used for in concurrency programming.
     * It improves memory utilization and write throughput depending on
     * the platform that JVM runs on.  The default value is {@code 16}.
     */
    int getWriteSpinCount();

    /**
     * Sets the maximum loop count for a write operation until
     * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value.
     * It is similar to what a spin lock is used for in concurrency programming.
     * It improves memory utilization and write throughput depending on
     * the platform that JVM runs on.  The default value is {@code 16}.
     *
     * @throws IllegalArgumentException
     *         if the specified value is {@code 0} or less than {@code 0}
     */
    void setWriteSpinCount(int writeSpinCount);
}


text:
module RssAppHelpers
  # It's a utility function so it has :reek:FeatureEnvy
  def linkify(text)
    return '' unless !text.nil? && text.is_a?(String)

    # return the text unchanged if links are already embedded
    return text if text =~ /<a/

    text.gsub(%r{(https?://\S+)}, '\1')
  rescue => e
    warn "rescue: #{e.inspect}"
    ''
  end

  # It's a utility function so it has :reek:FeatureEnvy
  def process_cdata(string)
    pos = string =~ /<!\[CDATA\[/

    warn 'CDATA found after string beginning' if !pos.nil? && pos.positive?

    string.gsub(/<!\[CDATA\[([^\]]+)\]\]>/, '\1')
  end

  module_function :linkify
  module_function :process_cdata
end


text:
<?php
namespace TYPO3\CMS\Install\Configuration\Context;

use TYPO3\CMS\Install\Configuration;

/**
 * Live preset
 */
class LivePreset extends Configuration\AbstractPreset
{
    /**
     * @var string Name of preset
     */
    protected $name = 'Live';

    /**
     * @var int Priority of preset
     */
    protected $priority = 50;

    /**
     * @var array Configuration values handled by this preset
     */
    protected $configurationValues = [
        'BE/debug' => false,
        'FE/debug' => false,
        'SYS/devIPmask' => '',
        'SYS/displayErrors' => 0,
        'SYS/enableDeprecationLog' => false,
        'SYS/sqlDebug' => 0,
        'SYS/systemLogLevel' => 2,
        'SYS/clearCacheSystem' => false,
        // E_RECOVERABLE_ERROR | E_USER_DEPRECATED
        'SYS/exceptionalErrors' => 20480,
    ];

    /**
     * Production preset is always available
     *
     * @return bool TRUE if mbstring PHP module is loaded
     */
    public function isAvailable()
    {
        return true;
    }

    /**
     * If context is set to production, priority
     * of this preset is raised.
     *
     * @return int Priority of preset
     */
    public function getPriority()
    {
        $context = \TYPO3\CMS\Core\Utility\GeneralUtility::getApplicationContext();
        $priority = $this->priority;
        if ($context->isProduction()) {
            $priority = $priority + 20;
        }
        return $priority;
    }
}


text:
#include <lua/lua.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <catch.hpp>
#include <stdio.h>
#include <fmt/format.h>
#include "heightmap.hpp"
#include "matrixstacksingleton.hpp"
#include "logiccontext.hpp"
#include "visualcontext.hpp"
#include "terrian_config.hpp"
#include "luae/script.hpp"
#include "luae/scriptmanager.hpp"
#include "luae/scriptheightmap.hpp"
#include "luae/Utilities.hpp"

//For stringifying preprocessor values
#define xstr(s) str(s)
     #define str(s) #s
#define concat(first, second) first second

TEST_CASE("Heightmap"){

	GLuint* indices = new GLuint[54];
	GLfloat* vertices = new GLfloat[27];

	indices[0] = 0;
	indices[1] = 1;
	indices[2] = 2;
	indices[3] = 2;
	indices[4] = 3;
	indices[5] = 0;

	indices[6] = 1;
	indices[7] = 4;
	indices[8] = 5;
	indices[9] = 5;
	indices[10] = 3;
	indices[11] = 1;

	indices[12] = 12;
	indices[13] = 18;
	indices[14] = 21;
	indices[15] = 21;
	indices[16] = 15;
	indices[17] = 12;

	indices[18] = 24;
	indices[19] = 27;
	indices[20] = 1;
	indices[21] = 1;
	indices[22] = 0;
	indices[23] = 24;

	indices[24] = 27;
	indices[29] = 27;
	Heightmap heightmap(vertices, indices);

	SECTION("getIndexOfSquare"){

		int s0 = heightmap.getIndexOfSquare(1);
		REQUIRE(s0 == 0);
		int s3 = heightmap.getIndexOfSquare(3);
		REQUIRE(s3 == 12);
		int s5 = heightmap.getIndexOfSquare(5);
		REQUIRE(s5 == 27);
	}
	SECTION("getIndexOfSquareVertex"){
		int v3 = heightmap.getIndexOfSquareVertex(3, 3);
		int v2 = heightmap.getIndexOfSquareVertex(3, 2);
		int v1 = heightmap.getIndexOfSquareVertex(3, 1);
		//21 is the start of the eighth vertex
		REQUIRE(v3 == 21);
		REQUIRE(v2 == 18);
		REQUIRE(v1 == 12);

	}

}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {

}
/*
TEST_CASE("Heightmap Collision"){
	struct LogicContext logicContext;
	GLFWwindow *window = VisualContext::CreateGLFWWindow(key_callback);
	GLuint shader_program = VisualContext::make_shader_program(concat(xstr(SHADERS_DIR), "/shader.vert"), concat(xstr(SHADERS_DIR), "/shader.frag"));
	glUseProgram(shader_program);
	GLuint uloc_project   = glGetUniformLocation(shader_program, "project");
	GLuint uloc_modelview = glGetUniformLocation(shader_program, "modelview");

	// Compute the projection matrix
	VisualContext::projection_matrix = glm::perspective(VisualContext::view_angle, VisualContext::aspect_ratio, VisualContext::z_near, VisualContext::z_far);

	logicContext.uloc_modelview = uloc_modelview;
    // Set the camera position
	logicContext.modelview = glm::translate(logicContext.modelview, glm::vec3(0.0f, 0.0f, -7.0f));
	logicContext.modelview = glm::rotate(logicContext.modelview, 1.57f, glm::vec3(-1.0f, 0.0f, 0.0f));

	SECTION("getIndexOfSquareIntersectingLine"){
		glm::vec4 a = glm::vec4(0.0f, 0.0f, 0.0f, 0.0f) * logicContext.modelview;
		glm::vec4 b = glm::vec4(0.0f, 0.0f, -20.0f, 0.0f) * logicContext.modelview;
		HeightmapSettings heightmapSettings;

		heightmapSettings.widthDensity = 10;
		heightmapSettings.origin = glm::vec3(0.0f, 0.0f, 0.0f);

		Heightmap heightmap(heightmapSettings);
		heightmap.build(heightmapSettings);

		REQUIRE( heightmap.getIndexOfSquareIntersectingLine(glm::vec3(a), glm::vec3(b)) == 0);

	}
}
*/
TEST_CASE("Lua script tests"){

	struct LogicContext logicContext;
	GLFWwindow *window = VisualContext::CreateGLFWWindow(key_callback);
	GLuint shader_program = VisualContext::make_shader_program(concat(xstr(SHADERS_DIR), "/shader.vert"), concat(xstr(SHADERS_DIR), "/shader.frag"));
	glUseProgram(shader_program);
	GLuint uloc_project   = glGetUniformLocation(shader_program, "project");
	GLuint uloc_modelview = glGetUniformLocation(shader_program, "modelview");

	// Compute the projection matrix
	VisualContext::projection_matrix = glm::perspective(VisualContext::view_angle, VisualContext::aspect_ratio, VisualContext::z_near, VisualContext::z_far);

	logicContext.uloc_modelview = uloc_modelview;
    // Set the camera position
	logicContext.modelview = glm::translate(logicContext.modelview, glm::vec3(0.0f, 0.0f, -7.0f));
	logicContext.modelview = glm::rotate(logicContext.modelview, 1.57f, glm::vec3(-1.0f, 0.0f, 0.0f));

	lua_State* l = Luae::ScriptManager::instance()->getState();
	Luae::ScriptHeightMap::AddToLib();
	Luae::Script* script = Luae::Script::Load("scriptheightmaptests.lua");
	SECTION("Heightmap init"){
		script->call("init");
		script->push();
		lua_getglobal(l, "HeightmapObject");
		script->pop();
		Heightmap* heightmapTwo = *(Heightmap**)lua_touserdata(l, -1);
		HeightmapSettings *settings = heightmapTwo->getSettings();

		REQUIRE(settings->width == 20);
		REQUIRE(settings->origin.x == 10);
		REQUIRE(settings->origin.y == 5.5);
		REQUIRE(settings->origin.z == -10.0);
		REQUIRE(settings->widthDensity == 10);
	}
	Luae::ScriptManager::Close();
}


text:
using System.Linq;

namespace Kingdom.OrTools.Sat.Parameters
{
    using static Ordinals;

    public class DoubleRepeatedParameter : RepeatedParameter<double>
    {
        public DoubleRepeatedParameter() : this(default)
        {
        }

        public DoubleRepeatedParameter(double value, params double[] others) : base(new[] {value}.Concat(others), InternalOrdinal)
        {
        }
    }
}


text:
class HighResTimer {

public:
	HighResTimer();
	~HighResTimer();
	void Start();
	void Stop();
	void Reset();
	void ResetStart();
	double GetElapsedTime();
	double GetCurrentElapsedTime(bool reset = false);

private:
	double ElapsedTime;
	double StartTime;
	int running;

	static double GetFrequency();
	static double GetTime();
#ifndef GPUCODE
	static double Frequency;
#endif
};

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annls mycol. 22: 385 (1924)

#### Original name
Sphaerella leucothoes Cooke

### Remarks
null


text:
package okta

import (
	"sync"
	"time"

	"github.com/Cloud-Foundations/golib/pkg/log"
	"github.com/Cloud-Foundations/keymaster/lib/simplestorage"
)

// This module implements the PasswordAuthenticator interface and will implement
// a unified 2FA backend interface at some future time.

type authCacheData struct {
	response OktaApiPrimaryResponseType
	expires  time.Time
}

type PasswordAuthenticator struct {
	authnURL       string
	logger         log.DebugLogger
	usernameSuffix string
	mutex          sync.Mutex               // Protect everything below.
	recentAuth     map[string]authCacheData // Key: username (before "@")
}

type PushResponse int

const (
	PushResponseRejected PushResponse = iota
	PushResponseApproved
	PushResponseWaiting
	PushResonseTimeout
)

// New creates a new PasswordAuthenticator using Okta as the backend. The Okta
// Public Application API is used, so rate limits apply.
// The Okta domain to check must be given by oktaDomain.
// Log messages are written to logger. A new *PasswordAuthenticator is returned.
func NewPublic(oktaDomain string, usernameSuffix string,
	logger log.DebugLogger) (*PasswordAuthenticator, error) {
	return newPublicAuthenticator(oktaDomain, usernameSuffix, logger)
}

// NewPublicTesting creates a new public authenticator, but
// pointing to an explicit authenticator url intead of okta urls.
// Log messages are written to logger. A new *PasswordAuthenticator is returned.
func NewPublicTesting(authnURL string, logger log.DebugLogger) (
	*PasswordAuthenticator, error) {
	pa, err := newPublicAuthenticator("example.com", "", logger)
	if err != nil {
		return pa, err
	}
	pa.authnURL = authnURL
	return pa, nil
}

// PasswordAuthenticate will authenticate a user using the provided username and
// password.
// It returns true if the user is authenticated, else false (due to either
// invalid username or incorrect password), and an error.
func (pa *PasswordAuthenticator) PasswordAuthenticate(username string,
	password []byte) (bool, error) {
	return pa.passwordAuthenticate(username, password)
}

func (pa *PasswordAuthenticator) UpdateStorage(storage simplestorage.SimpleStore) error {
	return nil
}

// ValidateUserOTP validates the otp value for an authenticated user.
// Assumes the user has a recent password authentication transaction.
// Returns true if the OTP value is valid according to okta, false otherwise.
func (pa *PasswordAuthenticator) ValidateUserOTP(username string, otpValue int) (bool, error) {
	return pa.validateUserOTP(username, otpValue)
}

// ValidateUserPush initializes or checks if a user MFA push has succeed for
// a specific user. Returns one of PushRessponse.
func (pa *PasswordAuthenticator) ValidateUserPush(username string) (PushResponse, error) {
	return pa.validateUserPush(username)
}


text:
<?php

namespace Symfony\Component\Security\Acl\Tests\Domain;

class AuditLoggerTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider getTestLogData
     */
    public function testLogIfNeeded($granting, $audit)
    {
        $logger = $this->getLogger();
        $ace = $this->getEntry();

        if (true === $granting) {
            $ace
                ->expects($this->once())
                ->method('isAuditSuccess')
                ->will($this->returnValue($audit))
           ;

           $ace
               ->expects($this->never())
               ->method('isAuditFailure')
           ;
        } else {
            $ace
                ->expects($this->never())
                ->method('isAuditSuccess')
            ;

            $ace
                ->expects($this->once())
                ->method('isAuditFailure')
                ->will($this->returnValue($audit))
            ;
        }

        if (true === $audit) {
            $logger
               ->expects($this->once())
               ->method('doLog')
               ->with($this->equalTo($granting), $this->equalTo($ace))
            ;
        } else {
            $logger
                ->expects($this->never())
                ->method('doLog')
            ;
        }

        $logger->logIfNeeded($granting, $ace);
    }

    public function getTestLogData()
    {
        return array(
            array(true, false),
            array(true, true),
            array(false, false),
            array(false, true),
        );
    }

    protected function getEntry()
    {
        return $this->getMock('Symfony\Component\Security\Acl\Model\AuditableEntryInterface');
    }

    protected function getLogger()
    {
        return $this->getMockForAbstractClass('Symfony\Component\Security\Acl\Domain\AuditLogger');
    }
}


text:
package fundamentals;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.function.Function;

/**
 * Given an array, find the int that appears an odd number of times.
 *
 * There will always be only one integer that appears an odd number of times.
 *
 * //TODO Find faster solution
 * @author dheraclio@gmail.com
 */
public class FindOdd {

  /**
   *
   * @param array of int to search
   * @return the odd number
   * @throws RuntimeException case od int not found
   */
   public static int findIt(int[] A) {
    //Uses a map to count int occurrences
    HashMap<Integer, Integer> map = new HashMap<>(A.length);
    for (int i = 0; i < A.length; i++)
      map.put(A[i], map.get(A[i]) != null ? map.get(A[i]) + 1 : 1);

    //find the first number which was found odd time
    for (Map.Entry<Integer, Integer> entry : map.entrySet())
      if (entry.getValue() % 2 != 0) return entry.getKey();

    throw new RuntimeException("Odd int not found");
  }

/*
  //Best solution found on Codewars to me
  public static int findIt(int[] A) {
    int xor = 0;
    //Since the problem stats that there will always be a single odd int, the XOR works.
    for (int i : A) {
      xor ^= i;
    }
    return xor;
  }
*/
/*
//Java 8 solution, slow but ok
public static int findIt(int[] a) {
    return Arrays.stream(a)
                 .boxed()
                 .collect(Collectors.groupingBy(Function.identity()))
                 .entrySet()
                 .stream()
                 .filter(e -> e.getValue().size() % 2 == 1)
                 .mapToInt(e -> e.getKey())
                 .findFirst()
                 .getAsInt();
    }
*/
/*
//Clever but too expensive
  public static int findIt(int[] A) {
    final TreeSet<Integer> set = new TreeSet<>();
    for (int x : A) {
      if (set.contains(x)) {
        set.remove(x);
      } else {
        set.add(x);
      }
    }
    return set.first();
  }
  */
}


text:
package org.alljoyn.bus;

import org.alljoyn.bus.BusException;
import org.alljoyn.bus.annotation.BusInterface;
import org.alljoyn.bus.annotation.BusMethod;

@BusInterface(name = "org.alljoyn.bus.SimpleNoDescriptionInterface",
                description="This is a simple interface")

public interface SimpleNoDescriptionInterface {
    @BusMethod(name="Ping", description="The ping method sends a small piece of data")
    String ping(String inStr) throws BusException;
}


text:
require 'pathname'
require 'digest/md5'
require 'fileutils'
require 'json'

OUTPUT_DIRECTORY = "mdtempoutput"

def print_usage
	puts "Usage: <private_key> <new_MD_app> <old_MD_app1> <old_MD_app2> ..."
	puts "Old apps should be listed with the most recent versions first"
end

def execute_command(command)
	`#{command}`
	if $?.exitstatus != 0
		puts "Exit status is a failure from last command.."
		exit 3
	end
end

def print_and_execute_command(command)
	puts command
	execute_command(command)
end

def build_and_short_version_from_app(app_path)
	info_path = Pathname.new(app_path) + "Contents/Info.plist"
	temp_path = Pathname.new(OUTPUT_DIRECTORY) + "tempinfo.json"
	execute_command("plutil -convert json \"#{info_path}\" -o \"#{temp_path}\"")
	jsonContents = JSON.parse(IO.read(temp_path))
	FileUtils.rm(temp_path)
	return [jsonContents["CFBundleVersion"].to_i, jsonContents["CFBundleShortVersionString"]]
end

def sign_file(file_path, private_key_path)
	temp_path = Pathname.new(OUTPUT_DIRECTORY) + "sig"
	print_and_execute_command("./sign_update \"#{file_path}\" \"#{private_key_path}\" > \"#{temp_path}\"")
	signature = IO.read(temp_path).strip()
	FileUtils.rm(temp_path)
	return signature
end

def make_old_app_patch(new_app_path, old_app_path, new_build_number, old_build_number, private_key_path)
	patch_name = "#{old_build_number}-to-#{new_build_number}.delta"
	patch_path = Pathname.new(OUTPUT_DIRECTORY) + patch_name
	delta_create_command = "./BinaryDelta create"
	delta_create_command += " --version=1" if old_build_number <= 1090
	print_and_execute_command("#{delta_create_command} \"#{old_app_path}\" \"#{new_app_path}\" \"#{patch_path}\"")
	return [patch_name, sign_file(patch_path, private_key_path), File.stat(patch_path).size]
end

if not File.exist? "BinaryDelta"
	puts "Error: cannot find BinaryDelta"
	exit(1)
end

if ARGV.length < 2
	print_usage()
	exit(1)
end

private_key_path = ARGV[0]
unless File.exist? private_key_path
	puts "ERROR: private key at path #{private_key_path} does not exist"
	print_usage()
	exit(1)
end

##Just a little app/map validation
halomd_path = ARGV[1]
halomd_maps_path = Pathname.new(halomd_path) + "Contents/Resources/Data/DoNotTouchOrModify/Maps/"
stock_maps = ["bloodgulch", "crossing", "barrier", "bitmaps", "ui", "sounds"]
map_hashes = ["dde1ec328ed9527542e8be94d988b4e0", "8881f2749b1c0396581ec8a12256f01b", "30d76559112bbe58655319d551f6aa98", "3aa76ba21068930d25f57abd48a36b5a", "8cdd73b429308fe5abd3a74627d0618b", "45e064c46685ddcb4da717b3978662a4"]
stock_map_paths = stock_maps.map {|map| halomd_maps_path + "#{map}.map"}

stock_map_paths.each_with_index do |path, index|
	unless File.exists? path
		puts "ERROR: Failed to locate stock map at #{path}"
		exit(1)
	end

	hash = Digest::MD5.hexdigest(IO.read(path))
	unless hash == map_hashes[index]
		puts "ERROR: #{path} md5 hash is not #{hash}"
		exit(1)
	end
end
##

if File.exists? OUTPUT_DIRECTORY
	FileUtils.rm_rf(OUTPUT_DIRECTORY)
end
Dir.mkdir OUTPUT_DIRECTORY

build_and_short_version = build_and_short_version_from_app(halomd_path)
old_build_and_short_versons = []

old_app_paths = ARGV[2..-1]
last_old_app_build = 0
old_app_paths.each do |path|
	unless File.exists? path
		print_usage()
		puts "ERROR: Failed to locate old MD app at #{path}"
		exit(1)
	end

	old_build_and_short_versons << build_and_short_version_from_app(path)

	if old_build_and_short_versons[-1][0] >= build_and_short_version[0]
		puts "ERROR: Old app build #{old_build_and_short_versons[-1][0]} is >= new build #{build_and_short_version[0]}"
		exit(1)
	end

	if old_build_and_short_versons.count > 1 and old_build_and_short_versons[-1][0] >= last_old_app_build
		puts "ERROR: Old app paths are not passed in order from newest to oldest!"
		exit(1)
	end
	last_old_app_build = old_build_and_short_versons[-1][0]
end

md_output_directory = Pathname.new(OUTPUT_DIRECTORY) + "HaloMD"
Dir.mkdir md_output_directory

how_to_run_path = "Install.rtfd"

halomd_dest_path = Pathname.new(md_output_directory) + "HaloMD.app"

print_and_execute_command("cp -R \"#{how_to_run_path}\" \"#{md_output_directory}\"")
print_and_execute_command("ditto \"#{halomd_path}\" \"#{halomd_dest_path}\"")
puts "Creating zip..."
current_directory =  Dir.pwd
Dir.chdir(OUTPUT_DIRECTORY)

zip_name = "HaloMDnew.zip"
zip_path = Pathname.new(OUTPUT_DIRECTORY) + zip_name

execute_command("ditto -c -k --sequesterRsrc --keepParent HaloMD \"#{zip_name}\"")
Dir.chdir(current_directory)

#Create the dmg
puts "Creating dmg..."
dmg_name = "HaloMDnew.dmg"
dmg_path = Pathname.new(OUTPUT_DIRECTORY) + dmg_name
print_and_execute_command("./create-dmg \"#{halomd_path}\" \"#{dmg_path}\"")

zip_signature = sign_file(zip_path, private_key_path)
zip_size = File.stat(zip_path).size

FileUtils.rm_rf(md_output_directory)

delta_items = []
old_app_paths.each_with_index do |old_path, index|
	patch_name, signature, size = make_old_app_patch(halomd_path, old_path, build_and_short_version[0], old_build_and_short_versons[index][0], private_key_path)
	delta_item = '<enclosure url="https://halomd.macgamingmods.com/' +  patch_name + '" ' +
		'sparkle:version="' + build_and_short_version[0].to_s + '" ' +
		'sparkle:shortVersionString="' + build_and_short_version[1] + '" ' +
		'sparkle:deltaFrom="' + old_build_and_short_versons[index][0].to_s + '" ' +
		'length="' + size.to_s + '" ' +
		'type="application/octet-stream" ' +
		'sparkle:dsaSignature="' + signature + '" />'
	delta_items << delta_item
end

appcast_template_contents = IO.read("appcast_template.xml")
new_contents = appcast_template_contents.gsub("$DELTA_ITEMS", delta_items.join("\n")).gsub("$MD_HUMAN_VERSION", build_and_short_version[1].to_s).gsub("$MD_BUILD", build_and_short_version[0].to_s).gsub("$MD_ZIP_LENGTH", zip_size.to_s).gsub("$MD_CODE_SIG", zip_signature).gsub("$MD_PUB_DATE", Time.now.strftime("%a, %-d %b %Y"))

IO.write(Pathname.new(OUTPUT_DIRECTORY) + "halomd_appcast.xml", new_contents)

puts "Wrote files to #{OUTPUT_DIRECTORY}. Verify that the app inside the dmg & zip opens and works (sometimes macOS can be wonky..). These files will be uploaded to the top level directory of the server. Make sure to upload #{dmg_name} and #{zip_name} first, move and rename the old stable version dmg into old_releases/ appropriately, and then rename the uploaded dmg & zip to without the 'new' suffix. Then update and upload the releasenotes.html with new info, upload the the delta patch file(s). Finally, upload/replace the appcast as the last step. Note the dmg is for users, and the zip is for Sparkle updates. Users should typically not download the zipped version manually."


text:
/**
 * Webpack
 *
 * ---------------------------------------------------------------
 *
 * Module loader, JSX transform, Minification, Sourcemaps
 *
 * For usage docs see:
 *    https://github.com/webpack/grunt-webpack
 */

var assign = require('object-assign');
var webpack = require('webpack');
var path = require('path');

module.exports = function(grunt) {

  /** **************************************************************************
   * Build
   */
  var buildOptions = assign({}, require('./webpack.config'), {
    // Clear default plugins so we can override through grunt
    plugins: []
  });

  grunt.config.set('webpack', {

    options: buildOptions,

    dev: {
      plugins: [
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.OccurenceOrderPlugin(true)
      ]
    },

    dist : {
      output: {
        filename: '[name].min.js'
      },

      plugins: [
        new webpack.optimize.OccurenceOrderPlugin(true),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin()
      ]
    }
  });

  /** **************************************************************************
   * Development Server
   */
  var serverOptions = assign({}, require('./webpack.config'), {
    plugins: [],
    entry : {
      bundle: path.resolve(__dirname, '../../examples/index.jsx')
    },
    output: {
      filename: 'bundle.js'
    },
    devtool: 'eval',
    eslint: {
      failOnWarning: false
    }
  });

  // Remove Extract Plugin. Gotta clone to prevent changing above config
  serverOptions.module = assign({}, serverOptions.module);

  grunt.config.set('webpack-dev-server', {
    options: {
      webpack: serverOptions,
      host: 'localhost',
      contentBase: 'examples/',
      publicPath: '/assets/',
      filename: 'bundle.js',
      keepalive: true,
      inline: true,
      hot: true,
      quiet: false,
      noInfo: false
    },

    dev: {}
  });

  grunt.loadNpmTasks('grunt-webpack');
};


text:
'use strict';

var path = require('path');
var packageJson = path.join(process.cwd(), 'package.json');

module.exports = {
	read: function() {
		return require(packageJson);
	}
};


text:
package config

import clientcmdapi "k8s.io/client-go/1.4/tools/clientcmd/api"

type Cluster struct {
	Server                   string `json:"server"`
	InsecureSkipTLSVerify    bool   `json:"insecure_skip_tls_verify,omitempty"`
	CertificateAuthorityData string `json:"certificate_authority_data"`
}

type AuthInfo struct {
	ClientCertificateData string `json:"client_certificate_data,omitempty"`
	ClientKeyData         string `json:"client_key_data,omitempty"`
	Token                 string `json:"token,omitempty"`
	Username              string `json:"username,omitempty"`
	Password              string `json:"password,omitempty"`
}

type Context struct {
	Cluster   string `json:"cluster"`
	AuthInfo  string `json:"user"`
	Namespace string `json:"namespace"`
}

type Kubernetes struct {
	Clusters       map[string]*Cluster  `json:"clusters"`
	AuthInfos      map[string]*AuthInfo `json:"users"`
	Contexts       map[string]*Context  `json:"contexts"`
	CurrentContext string               `json:"current_context"`
}

func (k Kubernetes) ClientConfig() clientcmdapi.Config {
	cc := clientcmdapi.NewConfig()
	cc.CurrentContext = k.CurrentContext
	for k, v := range k.Clusters {
		cc.Clusters[k] = v.api()
	}
	for k, v := range k.AuthInfos {
		cc.AuthInfos[k] = v.api()
	}
	for k, v := range k.Contexts {
		cc.Contexts[k] = v.api()
	}
	cc.Preferences = *clientcmdapi.NewPreferences()
	return *cc
}

func (a *AuthInfo) api() *clientcmdapi.AuthInfo {
	info := clientcmdapi.NewAuthInfo()
	info.Token = a.Token
	info.Username = a.Username
	info.Password = a.Password
	if len(a.ClientCertificateData) != 0 {
		info.ClientCertificateData = []byte(a.ClientCertificateData)
	}
	if len(a.ClientKeyData) != 0 {
		info.ClientKeyData = []byte(a.ClientKeyData)
	}
	return info
}

func (c *Cluster) api() *clientcmdapi.Cluster {
	cluster := clientcmdapi.NewCluster()
	cluster.Server = c.Server
	cluster.InsecureSkipTLSVerify = c.InsecureSkipTLSVerify
	if len(c.CertificateAuthorityData) != 0 {
		cluster.CertificateAuthorityData = []byte(c.CertificateAuthorityData)
	}
	return cluster
}

func (c *Context) api() *clientcmdapi.Context {
	context := clientcmdapi.NewContext()
	context.Cluster = c.Cluster
	context.AuthInfo = c.AuthInfo
	context.Namespace = c.Namespace
	return context
}


text:
from distutils.version import LooseVersion
import platform
import subprocess
import logging
import os

def supported_instruction_sets():
    """
    Returns the set of supported CPU features, see
    https://github.com/numpy/numpy/blob/master/numpy/core/src/common/npy_cpu_features.h
    for the list of features that this set may contain per architecture.

    Example:
    >>> supported_instruction_sets()  # for x86
    {"SSE2", "AVX2", ...}
    >>> supported_instruction_sets()  # for PPC
    {"VSX", "VSX2", ...}
    >>> supported_instruction_sets()  # for ARM
    {"NEON", "ASIMD", ...}
    """
    import numpy
    if LooseVersion(numpy.__version__) >= "1.19":
        # use private API as next-best thing until numpy/numpy#18058 is solved
        from numpy.core._multiarray_umath import __cpu_features__
        # __cpu_features__ is a dictionary with CPU features
        # as keys, and True / False as values
        supported = {k for k, v in __cpu_features__.items() if v}
        for f in os.getenv("FAISS_DISABLE_CPU_FEATURES", "").split(", \t\n\r"):
            supported.discard(f)
        return supported

    # platform-dependent legacy fallback before numpy 1.19, no windows
    if platform.system() == "Darwin":
        if subprocess.check_output(["/usr/sbin/sysctl", "hw.optional.avx2_0"])[-1] == '1':
            return {"AVX2"}
    elif platform.system() == "Linux":
        import numpy.distutils.cpuinfo
        if "avx2" in numpy.distutils.cpuinfo.cpu.info[0].get('flags', ""):
            return {"AVX2"}
    return set()

logger = logging.getLogger(__name__)

has_AVX2 = "AVX2" in supported_instruction_sets()
if has_AVX2:
    try:
        logger.info("Loading faiss with AVX2 support.")
        from .swigfaiss_avx2 import *
        logger.info("Successfully loaded faiss with AVX2 support.")
    except ImportError as e:
        logger.info(f"Could not load library with AVX2 support due to:\n{e!r}")
        # reset so that we load without AVX2 below
        has_AVX2 = False

if not has_AVX2:
    # we import * so that the symbol X can be accessed as faiss.X
    logger.info("Loading faiss.")
    from .swigfaiss import *
    logger.info("Successfully loaded faiss.")