text:
# Import a whole load of stuff
from System.IO import *
from System.Drawing import *
from System.Runtime.Remoting import *
from System.Threading import *
from System.Windows.Forms import *
from System.Xml.Serialization import *
from System import *

from Analysis.EDM import *
from DAQ.Environment import *
from EDMConfig import *

def saveBlockConfig(path, config):
	fs = FileStream(path, FileMode.Create)
	s = XmlSerializer(BlockConfig)
	s.Serialize(fs,config)
	fs.Close()

def loadBlockConfig(path):
	fs = FileStream(path, FileMode.Open)
	s = XmlSerializer(BlockConfig)
	bc = s.Deserialize(fs)
	fs.Close()
	return bc

def writeLatestBlockNotificationFile(cluster, blockIndex):
	fs = FileStream(Environs.FileSystem.Paths["settingsPath"] + "\\BlockHead\\latestBlock.txt", FileMode.Create)
	sw = StreamWriter(fs)
	sw.WriteLine(cluster + "\t" + str(blockIndex))
	sw.Close()
	fs.Close()

def checkYAGAndFix():
	interlockFailed = hc.YAGInterlockFailed;
	if (interlockFailed):
		bh.StopPattern();
		bh.StartPattern();

def printWaveformCode(bc, name):
	print(name + ": " + str(bc.GetModulationByName(name).Waveform.Code) + " -- " + str(bc.GetModulationByName(name).Waveform.Inverted))

def prompt(text):
	sys.stdout.write(text)
	return sys.stdin.readline().strip()

def measureParametersAndMakeBC(cluster, eState, bState, rfState, mwState, scramblerV):
	fileSystem = Environs.FileSystem
	print("Measuring parameters ...")
	bh.StopPattern()
	#hc.UpdateRFPowerMonitor()
	#hc.UpdateRFFrequencyMonitor()
	bh.StartPattern()
	#hc.UpdateBCurrentMonitor()
	hc.UpdateVMonitor()
	#hc.UpdateProbeAOMV()
	#hc.UpdatePumpAOMFreqMonitor()
	#hc.CheckPiMonitor()
	#print("Measuring polarizer angle")
	#hc.UpdateProbePolAngleMonitor()
	#hc.UpdatePumpPolAngleMonitor()
	#pumpPolAngle = hc.pumpPolAngle
	#probePolAngle = hc.probePolAngle
	print("V plus: " + str(hc.CPlusMonitorVoltage * hc.CPlusMonitorScale))
	print("V minus: " + str(hc.CMinusMonitorVoltage * hc.CMinusMonitorScale))
	print("Bias: " + str(hc.BiasCurrent))
	print("B step: " + str(abs(hc.FlipStepCurrent)))
	print("DB step: " + str(abs(hc.CalStepCurrent)))
	print("Phase Lock Error (deg): "+ str(pl.PhaseError))
	# load a default BlockConfig and customise it appropriately
	settingsPath = fileSystem.Paths["settingsPath"] + "\\BlockHead\\"
	bc = loadBlockConfig(settingsPath + "default.xml")
	bc.Settings["cluster"] = cluster
	bc.Settings["eState"] = eState
	bc.Settings["bState"] = bState
	bc.Settings["rfState"] = rfState
	bc.Settings["mwState"] = mwState
	bc.Settings["phaseScramblerV"] = scramblerV
	bc.Settings["ePlus"] = hc.CPlusMonitorVoltage * hc.CPlusMonitorScale
	bc.Settings["eMinus"] = hc.CMinusMonitorVoltage * hc.CMinusMonitorScale
	bc.Settings["bBiasV"] = hc.SteppingBiasVoltage
	bc.Settings["greenDCFM"] = hc.GreenSynthDCFM
	bc.Settings["greenAmp"] = hc.GreenSynthOnAmplitude
	bc.Settings["greenFreq"] = hc.GreenSynthOnFrequency
	bc.Settings["rf1CentreTime"] = sm.GetPGSetting("rf1CentreTime")
	bc.Settings["rf2CentreTime"] = sm.GetPGSetting("rf2CentreTime")
	bc.GetModulationByName("B").Centre = (hc.BiasCurrent)/1000
	bc.GetModulationByName("B").Step = abs(hc.FlipStepCurrent)/1000
	bc.GetModulationByName("DB").Step = abs(hc.CalStepCurrent)/1000
	# these next 3, seemingly redundant, lines are to preserve backward compatibility
	bc.GetModulationByName("B").PhysicalCentre = (hc.BiasCurrent)/1000
	bc.GetModulationByName("B").PhysicalStep = abs(hc.FlipStepCurrent)/1000
	bc.GetModulationByName("DB").PhysicalStep = abs(hc.CalStepCurrent)/1000
	bc.GetModulationByName("RF1A").Centre = hc.RF1AttCentre
	bc.GetModulationByName("RF1A").Step = hc.RF1AttStep
	bc.GetModulationByName("RF1A").PhysicalCentre = hc.RF1PowerCentre
	bc.GetModulationByName("RF1A").PhysicalStep = hc.RF1PowerStep
	bc.GetModulationByName("RF2A").Centre = hc.RF2AttCentre
	bc.GetModulationByName("RF2A").Step = hc.RF2AttStep
	bc.GetModulationByName("RF2A").PhysicalCentre = hc.RF2PowerCentre
	bc.GetModulationByName("RF2A").PhysicalStep = hc.RF2PowerStep
	bc.GetModulationByName("RF1F").Centre = hc.RF1FMCentre
	bc.GetModulationByName("RF1F").Step = hc.RF1FMStep
	bc.GetModulationByName("RF1F").PhysicalCentre = hc.RF1FrequencyCentre
	bc.GetModulationByName("RF1F").PhysicalStep = hc.RF1FrequencyStep
	bc.GetModulationByName("RF2F").Centre = hc.RF2FMCentre
	bc.GetModulationByName("RF2F").Step = hc.RF2FMStep
	bc.GetModulationByName("RF2F").PhysicalCentre = hc.RF2FrequencyCentre
	bc.GetModulationByName("RF2F").PhysicalStep = hc.RF2FrequencyStep
	# laser frequency stuff goes here
	bc.GetModulationByName("LF1").PhysicalCentre = hc.ProbeAOMFrequencyCentre
	bc.GetModulationByName("LF1").PhysicalStep = hc.ProbeAOMFrequencyStep
	# generate the waveform codes
	print("Generating waveform codes ...")
	eWave = bc.GetModulationByName("E").Waveform
	eWave.Name = "E"
	##lf1Wave = bc.GetModulationByName("LF1").Waveform
	##lf1Wave.Name = "LF1"
	##mwWave = bc.GetModulationByName("MW").Waveform
	##mwWave.Name = "MW"
	ws = WaveformSetGenerator.GenerateWaveforms( (eWave,), ("B","DB","PI","RF1A","RF2A","RF1F","RF2F","LF1") )
	bc.GetModulationByName("B").Waveform = ws["B"]
	bc.GetModulationByName("DB").Waveform = ws["DB"]
	bc.GetModulationByName("PI").Waveform = ws["PI"]
	bc.GetModulationByName("RF1A").Waveform = ws["RF1A"]
	bc.GetModulationByName("RF2A").Waveform = ws["RF2A"]
	bc.GetModulationByName("RF1F").Waveform = ws["RF1F"]
	bc.GetModulationByName("RF2F").Waveform = ws["RF2F"]
	bc.GetModulationByName("LF1").Waveform = ws["LF1"]
	# change the inversions of the static codes E
	bc.GetModulationByName("E").Waveform.Inverted = WaveformSetGenerator.RandomBool()
	# Do the same for the microwave channel
	# bc.GetModulationByName("MW").Waveform.Inverted = WaveformSetGenerator.RandomBool()
	# print the waveform codes
	# printWaveformCode(bc, "E")
	# printWaveformCode(bc, "B")
	# printWaveformCode(bc, "DB")
	# printWaveformCode(bc, "PI")
	# printWaveformCode(bc, "RF1A")
	# printWaveformCode(bc, "RF2A")
	# printWaveformCode(bc, "RF1F")
	# printWaveformCode(bc, "RF2F")
	# printWaveformCode(bc, "LF1")
	# printWaveformCode(bc, "LF2")
	# store e-switch info in block config
	print("Storing E switch parameters ...")
	bc.Settings["eRampDownTime"] = hc.ERampDownTime
	bc.Settings["eRampDownDelay"] = hc.ERampDownDelay
	bc.Settings["eBleedTime"] = hc.EBleedTime
	bc.Settings["eSwitchTime"] = hc.ESwitchTime
	bc.Settings["eRampUpTime"] = hc.ERampUpTime
	bc.Settings["eRampUpDelay"] = hc.ERampUpDelay
	bc.Settings["eOvershootFactor"] = hc.EOvershootFactor
	# store the E switch asymmetry in the block
	bc.Settings["E0PlusBoost"] = hc.E0PlusBoost
	# number of times to step the target looking for a good target spot, step size is 2 (coded in Acquisitor)
	bc.Settings["maximumNumberOfTimesToStepTarget"] = 2000
	# minimum signal in the first detector, in Vus
	bc.Settings["minimumSignalToRun"] = 100.0
	bc.Settings["targetStepperGateStartTime"] = 2380.0
	bc.Settings["targetStepperGateEndTime"] = 2580.0
	return bc

# lock gains
# microamps of current per volt of control input
kSteppingBiasCurrentPerVolt = 2453.06
# max change in the b-bias voltage per block
kBMaxChange = 0.05
# volts of rf*a input required per cal's worth of offset
kRFAVoltsPerCal = 3.2
kRFAMaxChange = 0.05
# volts of rf*f input required per cal's worth of offset
kRFFVoltsPerCal = 8
kRFFMaxChange = 0.05

def updateLocks(bState):
	bottomProbeChannelValues = bh.DBlock.ChannelValues[0]
	# note the weird python syntax for a one element list
	sigValue = bottomProbeChannelValues.GetValue(("SIG",))
	bValue = bottomProbeChannelValues.GetValue(("B","MW"))
	dbValue = bottomProbeChannelValues.GetValue(("DB","MW"))
	rf1aValue = bottomProbeChannelValues.GetValue(("RF1A","DB","MW"))
	rf2aValue = bottomProbeChannelValues.GetValue(("RF2A","DB","MW"))
	rf1fValue = bottomProbeChannelValues.GetValue(("RF1F","DB","MW"))
	rf2fValue = bottomProbeChannelValues.GetValue(("RF2F","DB","MW"))
	print "SIG: " + str(sigValue)
	print "B: " + str(bValue) + " DB: " + str(dbValue)
	print "RF1A: " + str(rf1aValue) + " RF2A: " + str(rf2aValue)
	print "RF1F: " + str(rf1fValue) + " RF2F: " + str(rf2fValue)
	if dbValue < 4:
		print "DB value too low, not applying feedback"
	else:
		print "feeding back to Bias and rf parameters"
		# B bias lock
		# the sign of the feedback depends on the b-state and the microwave state
		if bState:
			feedbackSign = 1
		else:
			feedbackSign = -1
		deltaBias = - (1.0/10.0) * feedbackSign * (hc.CalStepCurrent * (bValue / dbValue)) / kSteppingBiasCurrentPerVolt
		deltaBias = windowValue(deltaBias, -kBMaxChange, kBMaxChange)
		print "Attempting to change stepping B bias by " + str(deltaBias) + " V."
		newBiasVoltage = windowValue( hc.SteppingBiasVoltage - deltaBias, -5, 5)
		hc.SetSteppingBBiasVoltage( newBiasVoltage )
		# RFA  locks
		deltaRF1A = - (6.0/3.0) * (rf1aValue / dbValue) * kRFAVoltsPerCal
		deltaRF1A = windowValue(deltaRF1A, -kRFAMaxChange, kRFAMaxChange)
		print "Attempting to change RF1A by " + str(deltaRF1A) + " V."
		newRF1A = windowValue( hc.RF1AttCentre - deltaRF1A, hc.RF1AttStep, 5 - hc.RF1AttStep)
		hc.SetRF1AttCentre( newRF1A )
		#
		deltaRF2A = - (6.0/3.0) * (rf2aValue / dbValue) * kRFAVoltsPerCal
		deltaRF2A = windowValue(deltaRF2A, -kRFAMaxChange, kRFAMaxChange)
		print "Attempting to change RF2A by " + str(deltaRF2A) + " V."
		newRF2A = windowValue( hc.RF2AttCentre - deltaRF2A, hc.RF2AttStep, 5 - hc.RF2AttStep )
		hc.SetRF2AttCentre( newRF2A )
		# RFF  locks
		deltaRF1F = - (10.0/4.0) * (rf1fValue / dbValue) * kRFFVoltsPerCal
		deltaRF1F = windowValue(deltaRF1F, -kRFFMaxChange, kRFFMaxChange)
		print "Attempting to change RF1F by " + str(deltaRF1F) + " V."
		newRF1F = windowValue( hc.RF1FMCentre - deltaRF1F, hc.RF1FMStep, 5 - hc.RF1FMStep)
		hc.SetRF1FMCentre( newRF1F )
		#
		deltaRF2F = - (10.0/4.0) * (rf2fValue / dbValue) * kRFFVoltsPerCal
		deltaRF2F = windowValue(deltaRF2F, -kRFFMaxChange, kRFFMaxChange)
		print "Attempting to change RF2F by " + str(deltaRF2F) + " V."
		newRF2F = windowValue( hc.RF2FMCentre - deltaRF2F, hc.RF2FMStep, 5 - hc.RF2FMStep )
		hc.SetRF2FMCentre( newRF2F )

def updateLocksNL(bState):
	pmtChannelValues = bh.DBlock.ChannelValues[0]
	normedpmtChannelValues = bh.DBlock.ChannelValues[8]
	rf1ampReftChannelValues = bh.DBlock.ChannelValues[6]
	rf2ampReftChannelValues = bh.DBlock.ChannelValues[7]
	# note the weird python syntax for a one element list
	sigValue = pmtChannelValues.GetValue(("SIG",))
	bValue = pmtChannelValues.GetValue(("B",))
	dbValue = pmtChannelValues.GetValue(("DB",))
	bDBValue = normedpmtChannelValues.GetSpecialValue("BDB")
	rf1aValue = pmtChannelValues.GetValue(("RF1A",))
	rf1adbdbValue = normedpmtChannelValues.GetSpecialValue("RF1ADBDB")
	rf2aValue = pmtChannelValues.GetValue(("RF2A",))
	rf2adbdbValue = normedpmtChannelValues.GetSpecialValue("RF2ADBDB")
	rf1fValue = pmtChannelValues.GetValue(("RF1F",))
	rf1fdbdbValue = normedpmtChannelValues.GetSpecialValue("RF1FDBDB")
	rf2fValue = pmtChannelValues.GetValue(("RF2F",))
	rf2fdbdbValue = normedpmtChannelValues.GetSpecialValue("RF2FDBDB")
	lf1Value = pmtChannelValues.GetValue(("LF1",))
	lf1dbdbValue = normedpmtChannelValues.GetSpecialValue("LF1DBDB")
	lf1dbValue = normedpmtChannelValues.GetSpecialValue("LF1DB")
	lf2Value = pmtChannelValues.GetValue(("LF2",))
	lf2dbdbValue = pmtChannelValues.GetSpecialValue("LF2DBDB")
	rf1ampRefSig = rf1ampReftChannelValues.GetValue(("SIG",))
	rf2ampRefSig = rf2ampReftChannelValues.GetValue(("SIG",))
	rf1ampRefE = rf1ampReftChannelValues.GetValue(("E",))
	rf2ampRefE = rf2ampReftChannelValues.GetValue(("E",))
	rf1ampRefEErr = rf1ampReftChannelValues.GetError(("E",))
	rf2ampRefEErr = rf2ampReftChannelValues.GetError(("E",))

	print "SIG: " + str(sigValue)
	print "B: " + str(bValue) + " DB: " + str(dbValue)
	print "B/DB" + str(bDBValue)
	print "RF1A: " + str(rf1aValue) + " RF2A: " + str(rf2aValue)
	print "RF1A.DB/DB: " + str(rf1adbdbValue) + " RF2A.DB/DB: " + str(rf2adbdbValue)
	print "RF1F: " + str(rf1fValue) + " RF2F: " + str(rf2fValue)
	print "LF1: " + str(lf1Value) + " LF1.DB/DB: " + str(lf1dbdbValue)
	print "LF2: " + str(lf2Value) + " LF2.DB/DB: " + str(lf2dbdbValue)
	print "RF1 Reflected: " + str(rf1ampRefSig) +  " RF2 Reflected: " + str(rf2ampRefSig)
	print "{E}_RF1 Reflected: {" + str(rf1ampRefE) + " , " + str(rf1ampRefEErr) + " }"
	print "{E}_RF2 Reflected: {" + str(rf2ampRefE) + " , " + str(rf2ampRefEErr) + " }"

	# B bias lock
	# the sign of the feedback depends on the b-state and the microwave state
	if bState:
		feedbackSign = 1
	else:
		feedbackSign = -1
	deltaBias = - (1.0/10.0) * feedbackSign * (hc.CalStepCurrent * bDBValue) / kSteppingBiasCurrentPerVolt
	deltaBias = windowValue(deltaBias, -kBMaxChange, kBMaxChange)
	#deltaBias = 0
	print "Attempting to change stepping B bias by " + str(deltaBias) + " V."
	newBiasVoltage = windowValue( hc.SteppingBiasVoltage - deltaBias, -5, 5)
	hc.SetSteppingBBiasVoltage( newBiasVoltage )
	# RFA  locks
	deltaRF1A = - (1.0/2.0) * rf1adbdbValue * kRFAVoltsPerCal
	deltaRF1A = windowValue(deltaRF1A, -kRFAMaxChange, kRFAMaxChange)
	#deltaRF1A = 0
	newRF1A = windowValue( hc.RF1AttCentre - deltaRF1A, hc.RF1AttStep, 5 - hc.RF1AttStep)
	if (newRF1A == 4.9):
		newSynthAmp =  hc.GreenSynthOnAmplitude + 1
		print "RF1A pinned, increasing synth to  " + str(newSynthAmp) + " dBm."
		print "Setting RF1A to 4.5 V."
		newRF1A = 4.5
		hc.SetRF1AttCentre( newRF1A )
		hc.SetGreenSynthAmp(newSynthAmp)
	else:
		print "Attempting to change RF1A by " + str(deltaRF1A) + " V."
		hc.SetRF1AttCentre( newRF1A )
	#
	deltaRF2A = - (1.0/2.0) * rf2adbdbValue * kRFAVoltsPerCal
	deltaRF2A = windowValue(deltaRF2A, -kRFAMaxChange, kRFAMaxChange)
	#deltaRF2A = 0
	newRF2A = windowValue( hc.RF2AttCentre - deltaRF2A, hc.RF2AttStep, 5 - hc.RF2AttStep )
	if (newRF2A == 4.9):
		newSynthAmp =  hc.GreenSynthOnAmplitude + 1
		print "RF2A pinned, increasing synth to  " + str(newSynthAmp) + " dBm."
		print "Setting RF2A to 4.5 V."
		newRF2A = 4.5
		hc.SetRF2AttCentre( newRF2A )
		hc.SetGreenSynthAmp(newSynthAmp)
	else:
		print "Attempting to change RF2A by " + str(deltaRF2A) + " V."
		hc.SetRF2AttCentre( newRF2A )

	# RFF  locks
	deltaRF1F = - (1.0/2.0) * rf1fdbdbValue * kRFFVoltsPerCal
	deltaRF1F = windowValue(deltaRF1F, -kRFFMaxChange, kRFFMaxChange)
	#deltaRF1F = 0
	print "Attempting to change RF1F by " + str(deltaRF1F) + " V."
	newRF1F = windowValue( hc.RF1FMCentre - deltaRF1F, hc.RF1FMStep, 1.1 - hc.RF1FMStep)
	hc.SetRF1FMCentre( newRF1F )
	#
	deltaRF2F = - (1.0/2.0) * rf2fdbdbValue * kRFFVoltsPerCal
	deltaRF2F = windowValue(deltaRF2F, -kRFFMaxChange, kRFFMaxChange)
	#deltaRF2F = 0
	print "Attempting to change RF2F by " + str(deltaRF2F) + " V."
	newRF2F = windowValue( hc.RF2FMCentre - deltaRF2F, hc.RF2FMStep, 1.1 - hc.RF2FMStep )
	hc.SetRF2FMCentre( newRF2F )

	# Laser frequency lock (-ve multiplier in f0 mode and +ve in f1)
	deltaLF1 = -2.5* ( lf1dbdbValue)
	deltaLF1 = windowValue(deltaLF1, -0.1, 0.1)
	#deltaLF1 = 0
	print "Attempting to change LF1 by " + str(deltaLF1) + " V."
	newLF1 = windowValue( hc.probeAOMVoltage - deltaLF1, hc.probeAOMStep, 10 - hc.probeAOMStep )
	hc.SetprobeAOMVoltage( newLF1 )

	# Laser frequency lock (-ve multiplier in f0 mode and +ve in f1)
	deltaLF2 =  - 2.5 * lf2dbdbValue
	deltaLF2 = windowValue(deltaLF2, -0.1, 0.1)
	#deltaLF2 = 0
	print "Attempting to change LF2 by " + str(deltaLF2) + " V."
	newLF2 = windowValue( hc.PumpAOMVoltage - deltaLF2, hc.PumpAOMStep, 10 - hc.PumpAOMStep )
	hc.SetPumpAOMVoltage( newLF2 )

def windowValue(value, minValue, maxValue):
	if ( (value < maxValue) & (value > minValue) ):
		return value
	else:
		if (value < minValue):
			return minValue
		else:
			return maxValue

kTargetRotationPeriod = 10
kReZeroLeakageMonitorsPeriod = 10
r = Random()

def QuSpinGo():
	# Setup
	f = None
	fileSystem = Environs.FileSystem
	dataPath = fileSystem.GetDataDirectory(fileSystem.Paths["edmDataPath"])
	settingsPath = fileSystem.Paths["settingsPath"] + "\\BlockHead\\"
	print("Data directory is : " + dataPath)
	print("")
	suggestedClusterName = fileSystem.GenerateNextDataFileName()
	sm.SelectProfile("Scan B")

	# User inputs data
	cluster = prompt("Cluster name [" + suggestedClusterName +"]: ")
	if cluster == "":
		cluster = suggestedClusterName
		print("Using cluster " + suggestedClusterName)
	eState = hc.EManualState
	print("E-state: " + str(eState))
	bState = hc.BManualState
	print("B-state: " + str(bState))
	rfState = hc.RFManualState
	print("rf-state: " + str(rfState))
	mwState = hc.MWManualState
	print("mw-state: " + str(mwState))
	# this is to make sure the B current monitor is in a sensible state
	#hc.UpdateBCurrentMonitor()
	# randomise Ramsey phase
	scramblerV = 0.97156 * r.NextDouble()
	hc.SetScramblerVoltage(scramblerV)

	# calibrate leakage monitors
	print("calibrating leakage monitors..")
	print("E-field off")
	hc.EnableGreenSynth( False )
	hc.EnableEField( False )
	System.Threading.Thread.Sleep(10000)
	hc.EnableBleed( True )
	System.Threading.Thread.Sleep(5000)
	hc.CalibrateIMonitors()
	hc.EnableBleed( False )
	System.Threading.Thread.Sleep(500)
	print("E-field on")
	hc.EnableEField( True )
	hc.EnableGreenSynth( True )
	print("leakage monitors calibrated")

	bc = measureParametersAndMakeBC(cluster, eState, bState, rfState, mwState, scramblerV)

	# loop and take data
	blockIndex = 0
	maxBlockIndex = 10000
	dbValueList = []
	Emag1List =[]
	Emini1List=[]
	Emini2List=[]
	Emini3List=[]
	while blockIndex < maxBlockIndex:
		print("Acquiring MAGNETIC FIELD block " + str(blockIndex) + " ...")
		# save the block config and load into blockhead
		print("Saving temp config.")
		bc.Settings["clusterIndex"] = blockIndex
		tempConfigFile ='%(p)stemp%(c)s_%(i)s.xml' % {'p': settingsPath, 'c': cluster, 'i': blockIndex}
		saveBlockConfig(tempConfigFile, bc)
		System.Threading.Thread.Sleep(500)
		print("Loading temp config.")
		bh.LoadConfig(tempConfigFile)
		# take the block and save it
		print("Running magnetic field data acquisition ...")
		bh.StartMagDataAcquisitionAndWait()
		print("Done.")
		blockPath = '%(p)s%(c)s_%(i)s.zip' % {'p': dataPath, 'c': cluster, 'i': blockIndex}
		bh.SaveBlock(blockPath)
		print("Saved block "+ str(blockIndex) + ".")
		# give mma a chance to analyse the block
		print("Notifying Mathematica and waiting ...")
		writeLatestBlockNotificationFile(cluster, blockIndex)
		System.Threading.Thread.Sleep(5000)
		print("Done.")
		# increment and loop
		File.Delete(tempConfigFile)
		# checkYAGAndFix()
		blockIndex = blockIndex + 1
		#updateLocks(bState)
		# randomise Ramsey phase
		scramblerV = 0.97156 * r.NextDouble()
		hc.SetScramblerVoltage(scramblerV)

		bc = measureParametersAndMakeBC(cluster, eState, bState, rfState, mwState, scramblerV)

		#hc.EnableAnapicoListSweep( True )
		#print("ListSweep for microwaves enabled")

		# some code to stop EDMLoop if the laser unlocks.
		# This averages the last 3 db values and stops the loop if the average is below 1

		#bValueList.append(dbValue)
		#if (len(dbValueList) == 4):
		#	del dbValueList[0]
		#print "DB values for last 3 blocks " + str(dbValueList).strip('[]')
		#runningdbMean =float(sum(dbValueList)) / len(dbValueList)
		#if ( runningdbMean < 1 and nightBool is "Y" ):
		#	hc.EnableEField( False )
		#	hc.SetArgonShutter( True )
		#	break

		#Emag1List.append(magEValue)
		#if (len(Emag1List) == 11):
		#	del Emag1List[0]
		#print "E_{Mag} for the last 10 blocks " + str(Emag1List).strip('[]')
		#runningEmag1Mean =float(sum(Emag1List)) / len(Emag1List)
		#print "Average E_{Mag} for the last 10 blocks " + str(runningEmag1Mean)

		#if (dbValue < 8):
		#	print("Dodgy spot target rotation.")
		#	for i in range(3):
		#		hc.StepTarget(2)
		#		System.Threading.Thread.Sleep(500)
		if ((blockIndex % kReZeroLeakageMonitorsPeriod) == 0):
			print("Recalibrating leakage monitors.")
			# calibrate leakage monitors
			print("calibrating leakage monitors..")
			print("E-field off")
			hc.EnableEField( False )
			System.Threading.Thread.Sleep(10000)
			hc.EnableBleed( True )
			System.Threading.Thread.Sleep(5000)
			hc.CalibrateIMonitors()
			hc.EnableBleed( False )
			System.Threading.Thread.Sleep(500)
			print("E-field on")
			hc.EnableEField( True )
			print("leakage monitors calibrated")

	bh.StopPattern()

def run_script():
	QuSpinGo()


text:
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>QUnit Test Suite</title>
  <link rel="stylesheet" href="vendor/qunit.css" type="text/css" media="screen">

QUnit Tests

redpajama_set_name: RedPajamaGithub


text:
module.exports = function (config) {
    config.set({
        basePath: '../../../',
        frameworks: ['jasmine'],
        files: [
            'src/main/webapp/report/hello.js',
            'src/test/js/**/*.js'
        ],
        exclude: [],
        preprocessors: {
            'src/main/webapp/report/hello.js': ['coverage']
        },
        reporters: ['progress', 'coverage'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome', 'PhantomJS'],
        singleRun: false,
        plugins: [
            'karma-jasmine',
            'karma-chrome-launcher',
            'karma-phantomjs-launcher',
            'karma-junit-reporter',
            'karma-coverage'
        ],
        coverageReporter: {
            type: 'html',
            dir: 'target/coverage/'
        }
    });
};


text:
package org.sagebionetworks.web.client.widget.refresh;

import org.gwtbootstrap3.client.ui.Button;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class RefreshAlertViewImpl implements RefreshAlertView {

	@UiField
	Button refreshButton;

	public interface Binder extends UiBinder<Widget, RefreshAlertViewImpl> {
	}

	Widget w;
	Presenter presenter;

	@Inject
	public RefreshAlertViewImpl(Binder binder) {
		this.w = binder.createAndBindUi(this);
		refreshButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				presenter.onRefresh();
			}
		});
		w.addAttachHandler(new AttachEvent.Handler() {
			@Override
			public void onAttachOrDetach(AttachEvent event) {
				if (event.isAttached()) {
					presenter.onAttach();
				}
			}
		});
	}

	@Override
	public void setPresenter(final Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public Widget asWidget() {
		return w;
	}

	@Override
	public void setVisible(boolean visible) {
		w.setVisible(visible);
	}

	@Override
	public boolean isAttached() {
		return w.isAttached();
	}
}


text:
<?php
# MetInfo Enterprise Content Management System
# Copyright (C) MetInfo Co.,Ltd (http://www.metinfo.cn). All rights reserved.
$depth='../';
require_once $depth.'../login/login_check.php';
require_once ROOTPATH.'public/php/searchhtml.inc.php';
$query="select * from $met_admin_array where array_type='1' and lang='$lang'";
$menber_array_temp=$db->get_all($query);
foreach($menber_array_temp as $key=>$val){
$menber_array[$val['id']]=$val['array_name'];
}
$menber_array[0]=$lang_access0;
$menber_array[3]=$lang_access3;
$module=2;
if($class1){
	$class1_info=$met_class[$class1];
	if(!$class1_info)metsave('-1',$lang_dataerror,$depth);
	$sqlclass1=" and class1=$class1  ";
}else{
	if(count($met_classindex[$module])==1){
		$class1=$met_classindex[$module][0]['id'];
		$class1_info=$met_class[$class1];
		$sqlclass1=" and class1=$class1  ";
	}else{
		foreach($met_classindex[$module] as $key=>$val){
			$admin_column_power="admin_popc".$val[id];
			if(!($metinfo_admin_pop=='metinfo'||$$admin_column_power=='metinfo'))continue;
			$sqlclass1.=$sqlclass1?" or class1=$val[id] ":" class1=$val[id] ";
		}
		$sqlclass1="and ($sqlclass1) ";
		$class2=0;
		$class3=0;
	}
}
$serch_sql=" where lang='$lang' and (recycle='0' or recycle='-1') $sqlclass1 ";
if($admincp_ok['admin_issueok']==1)$serch_sql.= " and(issue='$metinfo_admin_name' or issue='') ";
if($class2)$serch_sql .= " and class2=$class2";
if($class3){$serch_sql .= " and class3=$class3"; }
$classnow=$class3?$class3:($class2?$class2:$class1);
$order_sql=list_order($met_class[$classnow][list_order]);
if($search == "detail_search"){
	if($title)$serch_sql .= " and title like '%$title%' ";
	if(isset($displaytype) && $displaytype!="all" && $displaytype!="") { $serch_sql .= " and displaytype ='$displaytype' "; }
	if(isset($recommend) && $recommend!="all" && $recommend!="") { $serch_sql .= " and com_ok ='$recommend' "; }
	if(isset($top) && $top!="all" && $top!="") { $serch_sql .= " and top_ok ='$top' "; }
	$total_count = $db->counter($met_news, "$serch_sql", "*");
}else{
	$total_count = $db->counter($met_news, "$serch_sql", "*");
}
require_once 'include/pager.class.php';
$page = (int)$page;
if($page_input){$page=$page_input;}
$list_num = 20;
$rowset = new Pager($total_count,$list_num,$page);
$from_record = $rowset->_offset();
$query = "SELECT * FROM {$met_news} $serch_sql $order_sql LIMIT $from_record, $list_num";
$result = $db->query($query);
while($list= $db->fetch_array($result)){
	if($met_member_use){
		$list['access']=$menber_array[$list['access']];
	}
	$list[img_ok1] = $list[img_ok] ? $lang_yes : $lang_no;
	$list[com_ok1] = $list[com_ok] ? $lang_yes : $lang_no;
	$list[displaytype1] = $list[displaytype] ? $lang_yes : $lang_no;
	$list[top_ok1] = $list[top_ok] ? $lang_yes : $lang_no;
	$list[wap_ok1] = $list[wap_ok] ? $lang_yes : $lang_no;
	$list[updatetime] = date('Y-m-d',strtotime($list[updatetime]));
	$num = 48;
	if (preg_match("/[\x7f-\xff]/",$list['title']))$num=38;
	$list['titles']=utf8substr($list['title'],0,$num);
	$news_list[]=$list;
}
$page_list = $rowset->link("index.php?anyid={$anyid}&lang=$lang&class1=$class1&class2=$class2&class3=$class3&search=$search&title=$title&page=");
switch($recommend){
	case '1':$recommend1="selected='selected'";break;
	case '0':$recommend2="selected='selected'";break;
	default:$recommend0="selected='selected'";break;
}
switch($top){
	case '1':$top1="selected='selected'";break;
	case '0':$top2="selected='selected'";break;
	default:$top0="selected='selected'";break;
}
switch($displaytype){
	case '1':$displaytype1="selected='selected'";break;
	case '0':$displaytype2="selected='selected'";break;
	default:$displaytype0="selected='selected'";break;
}
$cengci=$class3?3:($class2?2:1);
$css_url=$depth."../templates/".$met_skin."/css";
$img_url=$depth."../templates/".$met_skin."/images";
include template('content/article/article');
footer();
# This program is an open source system, commercial use, please consciously to purchase commercial license.
# Copyright (C) MetInfo Co., Ltd. (http://www.metinfo.cn). All rights reserved.
?>


text:
<?php

if (defined('MINDTOUCH_DEKI')) :

/**
 * Definitions of the NS_ constants are in Defines.php
 * @private
 */
$wgCanonicalNamespaceNames = array(
	NS_ADMIN			=> 'Admin',
	NS_MEDIA            => 'Media',
	NS_SPECIAL          => 'Special',
	NS_TALK	            => 'Talk',
	NS_USER             => 'User',
	NS_USER_TALK        => 'User_talk',
	NS_PROJECT          => 'Project',
	NS_PROJECT_TALK     => 'Project_talk',
	NS_IMAGE            => 'Image',
	NS_IMAGE_TALK       => 'Image_talk',
	NS_MEDIAWIKI        => 'MediaWiki',
#	NS_MEDIAWIKI_TALK   => 'MediaWiki_talk',
	NS_TEMPLATE         => 'Template',
	NS_TEMPLATE_TALK    => 'Template_talk',
	NS_HELP             => 'Help',
	NS_HELP_TALK        => 'Help_talk',
	NS_CATEGORY	        => 'Category',
	NS_CATEGORY_TALK    => 'Category_talk',
	NS_ATTACHMENT	    => 'File',
);

/**
 * This is a utility class with only static functions
 * for dealing with namespaces that encodes all the
 * "magic" behaviors of them based on index.  The textual
 * names of the namespaces are handled by Language.php.
 *
 * These are synonyms for the names given in the language file
 * Users and translators should not change them
 */
class DekiNamespace
{
	/**
	 * Check if the given namespace might be moved
	 * @return bool
	 */
	public static  function isMovable($index)
	{
		if ( $index < NS_MAIN || $index == NS_ADMIN  || $index == NS_SPECIAL ) {
			return false;
		}
		return true;
	}

	/**
	 * Check if the give namespace is a talk page
	 * @return bool
	 */
	public static function isTalk($index)
	{
		return ( $index == NS_TALK           || $index == NS_USER_TALK     ||
				 /* MT ursm $index == NS_PROJECT_TALK  || */ $index == NS_IMAGE_TALK    ||
				 /* MT ursm $index == NS_MEDIAWIKI_TALK || */ $index == NS_TEMPLATE_TALK ||
				 $index == NS_HELP_TALK      || $index == NS_CATEGORY_TALK
				 );
	}

	/**
	 * Get the talk namespace corresponding to the given index
	 */
	public static function getTalk($index)
	{
		if (DekiNamespace::isTalk($index)) {
			return $index;
		} else {
			# FIXME
			return $index + 1;
		}
	}

	public static function getSubject($index)
	{
		if (DekiNamespace::isTalk($index)) {
			return $index - 1;
		} else {
			return $index;
		}
	}

	/**
	 * Returns the canonical (English Wikipedia) name for a given index
	 */
	public static function &getCanonicalName($index)
	{
		global $wgCanonicalNamespaceNames;
		return $wgCanonicalNamespaceNames[$index];
	}

	/**
	 * Returns the index for a given canonical name, or NULL
	 * The input *must* be converted to lower case first
	 */
	public static function &getCanonicalIndex($name)
	{
		global $wgCanonicalNamespaceNames, $wgCanonicalAlternateNamespaces;
		static $xNamespaces = false;
		if ( $xNamespaces === false ) {
			$xNamespaces = array();
			foreach ( $wgCanonicalNamespaceNames as $i => $text ) {
				$xNamespaces[strtolower($text)] = $i;
			}
		}
		if ( array_key_exists( $name, $xNamespaces ) ) {
			return $xNamespaces[$name];
		} else {
			if (!empty($wgCanonicalAlternateNamespaces) && array_key_exists(mb_strtolower($name), $wgCanonicalAlternateNamespaces)) {
				return $wgCanonicalAlternateNamespaces[mb_strtolower($name)];
			}
		    $ret = false;
			return $ret;
		}
	}
}

endif;


text:
title: Hexagonal tile differences
localeTitle: Шестигранные различия плиток
---
## Задача 128: Различия в гексагональной черепице

Это заглушка. [Помогите нашему сообществу расширить его](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/project-euler/problem-128-hexagonal-tile-differences/index.md) .

[Это руководство по быстрому стилю поможет вам принять ваш запрос на тягу](https://github.com/freecodecamp/guides/blob/master/README.md) .


text:
/* NetHack 3.7	align.h	$NHDT-Date: 1604269810 2020/11/01 22:30:10 $  $NHDT-Branch: NetHack-3.7 $:$NHDT-Revision: 1.15 $ */
/* Copyright (c) Mike Stephenson, Izchak Miller  1991.		  */
/* NetHack may be freely redistributed.  See license for details. */

#ifndef ALIGN_H
#define ALIGN_H

typedef schar aligntyp; /* basic alignment type */

typedef struct align { /* alignment & record */
    aligntyp type;
    int record;
} align;

/* bounds for "record" -- respect initial alignments of 10 */
#define ALIGNLIM (10L + (g.moves / 200L))

#define A_NONE (-128) /* the value range of type */

#define A_CHAOTIC (-1)
#define A_NEUTRAL 0
#define A_LAWFUL 1

#define A_COALIGNED 1
#define A_OPALIGNED (-1)

/* align masks */
#define AM_NONE         0x00
#define AM_CHAOTIC      0x01
#define AM_NEUTRAL      0x02
#define AM_LAWFUL       0x04
#define AM_MASK         0x07 /* mask for "normal" alignment values */

/* Some altars are considered shrines, add a flag for that
   for the altarmask field of struct rm. */
#define AM_SHRINE       0x08

/* special level flags, gone by the time the level has been loaded */
#define AM_SPLEV_CO     0x10 /* co-aligned: force alignment to match hero's  */
#define AM_SPLEV_NONCO  0x20 /* non-co-aligned: force alignment to not match */
#define AM_SPLEV_RANDOM 0x40

#define Amask2align(x) \
    ((aligntyp) ((((x) & AM_MASK) == 0) ? A_NONE                \
                 : (((x) & AM_MASK) == AM_LAWFUL) ? A_LAWFUL    \
                   : ((int) ((x) & AM_MASK)) - 2)) /* 2 => 0, 1 => -1 */
#define Align2amask(x) \
    ((unsigned) (((x) == A_NONE) ? AM_NONE                      \
                 : ((x) == A_LAWFUL) ? AM_LAWFUL                \
                   : ((x) + 2))) /* -1 => 1, 0 => 2 */

/* Because clearly Nethack needs more ways to specify alignment...
   Amask2msa(): 1, 2, 4 converted to 1, 2, 3 to fit within a width 2 bitfield;
   Msa2amask(): 1, 2, 3 converted back to 1, 2, 4;
   For Amask2msa(), 'x' might have the shrine bit set so strip that off. */
#define Amask2msa(x) ((((x) & AM_MASK) == 4) ? 3 : (x) & AM_MASK)
#define Msa2amask(x) (((x) == 3) ? 4 : (x))
#define MSA_NONE    0  /* unaligned or multiple alignments */

#endif /* ALIGN_H */


text:
ALTER TABLE PART ADD PRIMARY KEY (P_PARTKEY);
ALTER TABLE SUPPLIER ADD PRIMARY KEY (S_SUPPKEY);
ALTER TABLE PARTSUPP ADD PRIMARY KEY (PS_PARTKEY, PS_SUPPKEY);
ALTER TABLE CUSTOMER ADD PRIMARY KEY (C_CUSTKEY);
ALTER TABLE ORDERS ADD PRIMARY KEY (O_ORDERKEY);
ALTER TABLE LINEITEM ADD PRIMARY KEY (L_ORDERKEY, L_LINENUMBER);
ALTER TABLE NATION ADD PRIMARY KEY (N_NATIONKEY);
ALTER TABLE REGION ADD PRIMARY KEY (R_REGIONKEY);


text:
package org.apache.derby.client.net;

import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.SSLSocket;

import org.apache.derby.iapi.services.info.JVMInfo;

public class OpenSocketAction implements java.security.PrivilegedExceptionAction {
    private String server_;
    private int port_;
    private int clientSSLMode_;

    public OpenSocketAction(String server, int port, int clientSSLMode) {
        server_ = server;
        port_ = port;
        clientSSLMode_ = clientSSLMode;
    }

    public Object run()
        throws java.net.UnknownHostException,
               java.io.IOException,
               java.security.NoSuchAlgorithmException,
               java.security.KeyManagementException,
               java.security.NoSuchProviderException,
               java.security.KeyStoreException,
               java.security.UnrecoverableKeyException,
               java.security.cert.CertificateException
    {

        SocketFactory sf;
        switch (clientSSLMode_) {
        case org.apache.derby.jdbc.ClientBaseDataSource.SSL_BASIC:
            sf = NaiveTrustManager.getSocketFactory();
            break;
        case org.apache.derby.jdbc.ClientBaseDataSource.SSL_PEER_AUTHENTICATION:
            sf = (SocketFactory)SSLSocketFactory.getDefault();
            break;
        case org.apache.derby.jdbc.ClientBaseDataSource.SSL_OFF:
            sf = SocketFactory.getDefault();
            break;
        default:
            // Assumes cleartext for undefined values
            sf = SocketFactory.getDefault();
            break;
        }

        //DERBY-6778(SSL tests are failing on 10.8 codeline with
        // IBM jdk 1.4.2 after poodle security backport)
        //In order to work around the IBM jdk 1.4.2 issue, do not
        // try to disable SSLv3 and SSLV2Hello protocols for this
        // specific jdk.
        //The SSLv3 and SSLV2Hello protocols can lead to poodle
        // security issue and that is why they are getting disabled
        // for all the other jdks as per DERBY-6764.
        boolean SSLclient = false;//are we working with SSL enabled client
        if ((clientSSLMode_ == org.apache.derby.jdbc.ClientBaseDataSource.SSL_BASIC ||
                clientSSLMode_ == org.apache.derby.jdbc.ClientBaseDataSource.SSL_PEER_AUTHENTICATION))
        	SSLclient = true;

        boolean ibmJdk142 = false;//are we working with IBM jdk 1.4.2
        if (JVMInfo.isIBMJVM() && JVMInfo.JDK_ID == JVMInfo.J2SE_142)
        	ibmJdk142 = true;

        if (SSLclient && !ibmJdk142) {
        	//DERBY-6764(analyze impact of poodle security alert on Derby
        	// client - server ssl support)
        	//If SSLv3 and/or SSLv2Hello is one of the enabled protocols,
        	// then we want to remove it from the list of enabled protocols
        	// because of poodle security breach
        	SSLSocket sSocket = (SSLSocket)sf.createSocket(server_, port_);
        	String[] enabledProtocols = sSocket.getEnabledProtocols();

            //If SSLv3 and/or SSLv2Hello is one of the enabled protocols,
            // then remove it from the list of enabled protocols because of
            // its security breach.
            String[] supportedProtocols = new String[enabledProtocols.length];
            int supportedProtocolsCount  = 0;
            for ( int i = 0; i < enabledProtocols.length; i++ )
            {
                if (!(enabledProtocols[i].toUpperCase().indexOf ("SSLV3") >=0 ||
                    enabledProtocols[i].toUpperCase().indexOf("SSLV2HELLO") >=0 )) {
                	supportedProtocols[supportedProtocolsCount] =
                			enabledProtocols[i];
                	supportedProtocolsCount++;
                }
            }
            if(supportedProtocolsCount < enabledProtocols.length) {
            	String[] newEnabledProtocolsList = null;
            	//We found that SSLv3 and or SSLv2Hello is one of the enabled
            	// protocols for this jvm. Following code will remove it from
            	// enabled list.
            	newEnabledProtocolsList =
            			new String[supportedProtocolsCount];
            	System.arraycopy(supportedProtocols, 0,
            			newEnabledProtocolsList, 0,
            			supportedProtocolsCount);
            	sSocket.setEnabledProtocols(newEnabledProtocolsList);
            }
            return sSocket;
        } else
            return sf.createSocket(server_, port_);
    }

}


text:
/* global angular */
(function () {
    "use strict";

    angular
        .module('app')
        .component('scientillaAccomplishmentForm', {
            templateUrl: 'partials/scientilla-accomplishment-form.html',
            controller: scientillaAccomplishmentFormController,
            controllerAs: 'vm',
            bindings: {
                accomplishment: "<",
                closeFn: "&",
                checkAndClose: "&"
            }
        });

    scientillaAccomplishmentFormController.$inject = [
        'AccomplishmentService',
        'EventsService',
        'accomplishmentFieldsRules',
        'accomplishmentEventTypes',
        '$scope',
        '$timeout',
        'ResearchItemTypesService',
        'context',
        'Restangular',
        'ModalService',
        'SourceService'
    ];

    function scientillaAccomplishmentFormController(
        AccomplishmentService,
        EventsService,
        accomplishmentFieldsRules,
        accomplishmentEventTypes,
        $scope,
        $timeout,
        ResearchItemTypesService,
        context,
        Restangular,
        ModalService,
        SourceService
    ) {
        const vm = this;

        vm.saveStatus = saveStatus();
        vm.verifyStatus = verifyStatus();

        vm.cancel = close;
        vm.verify = verify;
        vm.save = save;
        vm.getConferences = getConferences;
        vm.getSources = getSources;
        vm.getTitles = getTitles;
        vm.openSourceFormModal = openSourceFormModal;
        vm.fieldsRules = accomplishmentFieldsRules;
        vm.eventTypes = vm.accomplishment.eventType ?
            accomplishmentEventTypes :
            [{key: null, label: 'Select'}].concat(accomplishmentEventTypes);

        vm.eventTypesLabels = {null: {label: 'Place'}};
        accomplishmentEventTypes.forEach(aet => vm.eventTypesLabels[aet.key] = aet);

        vm.newSource = {};

        vm.errors = {};
        vm.errorText = '';
        vm.unsavedData = false;
        vm.mode = 'draft';
        vm.resetErrors = resetErrors;
        vm.checkValidation = checkValidation;
        vm.fieldValueHasChanged = fieldValueHasChanged;
        vm.formatSource = SourceService.formatSource;

        let timeout;

        const delay = 500;

        /* jshint ignore:start */
        vm.$onInit = async function () {
            vm.researchEntity = await context.getResearchEntity();
            vm.types = await ResearchItemTypesService.getTypes('accomplishment');

            $scope.$watch('form.$pristine', formUntouched => vm.unsavedData = !formUntouched);

            if (vm.accomplishment.id) {
                vm.errorText = '';
                vm.errors = AccomplishmentService.validate(vm.accomplishment);

                if (!_.isEmpty(vm.errors)) {
                    vm.errorText = 'Please fix the warnings before verifying!';
                }
            }
        };

        function resetErrors() {
            vm.errors = {};
            vm.errorText = '';
        }

        function checkValidation(field = false) {
            vm.errors[field] = AccomplishmentService.validate(vm.accomplishment, field);

            if (!vm.errors[field])
                delete vm.errors[field];

            vm.errorText = !_.isEmpty(vm.errors) ? 'Please fix the warnings before verifying!' : '';
        }

        /* jshint ignore:end */
        function fieldValueHasChanged(field = false) {
            $timeout.cancel(timeout);

            timeout = $timeout(() => checkValidation(field), delay);
        }

        function saveStatus() {
            return {
                setState: function (state) {
                    this.state = state;

                    vm.mode = 'draft';

                    switch (state) {
                        case 'ready to save':
                            this.message = 'Save draft';
                            break;
                        case 'saving':
                            this.message = 'Saving draft';
                            break;
                        case 'saved':
                            this.message = 'Draft is saved!';
                            $scope.form.$setPristine();
                            break;
                        case 'failed':
                            this.message = 'Failed to save draft!';
                            $scope.form.$setPristine();
                            break;
                    }
                },
                state: 'ready to save',
                message: 'Save draft'
            };
        }

        function verifyStatus() {
            return {
                setState: function (state) {
                    this.state = state;

                    vm.mode = 'verify';

                    switch (state) {
                        case 'ready to verify':
                            this.message = 'Save & verify';
                            break;
                        case 'verifying':
                            this.message = 'Verifying draft';
                            break;
                        case 'verified':
                            this.message = 'Draft is Verified!';
                            $scope.form.$setPristine();
                            break;
                        case 'failed':
                            this.message = 'Failed to verify!';
                            $scope.form.$setPristine();
                            break;
                    }
                },
                state: 'ready to verify',
                message: 'Save & verify'
            };
        }

        function save() {
            vm.errors = {};
            vm.errorText = '';
            return processSave(true);
        }

        /* jshint ignore:start */
        async function processSave(updateState = false) {
            if (updateState)
                vm.saveStatus.setState('saving');

            vm.errorText = '';
            vm.errors = AccomplishmentService.validate(vm.accomplishment);

            if (!_.isEmpty(vm.errors))
                vm.errorText = 'The draft has been saved but please fix the warnings before verifying!';

            if (vm.accomplishment.type.key === 'editorship')
                vm.accomplishment.title = vm.accomplishment.source ? vm.accomplishment.source.title : null;

            const filteredAccomplishment = AccomplishmentService.filterFields(vm.accomplishment);

            if (filteredAccomplishment.id)
                await AccomplishmentService.update(vm.researchEntity, filteredAccomplishment);
            else {
                const draft = await AccomplishmentService.create(vm.researchEntity, filteredAccomplishment);
                vm.accomplishment.id = draft.researchItem.id;
            }

            if (updateState) {
                vm.saveStatus.setState('saved');
                $timeout(() => vm.saveStatus.setState('ready to save'), 1000);
            }

            vm.unsavedData = false;
        }

        async function getSources(searchText) {
            const qs = {
                where: {
                    title: {
                        contains: searchText
                    }
                },
                limit: 99999
            };
            return await SourceService.searchAndFilter(qs, searchText);
        }
        /* jshint ignore:end */

        function getConferences(searchText) {
            if (vm.accomplishment.eventType === 'scientific_conference') {
                const qs = {where: {title: {contains: searchText}, type: 'conference'}};
                return Restangular.all('sources').getList(qs);
            }

            return false;
        }

        /* jshint ignore:start */
        async function getTitles(searchText) {
            const types = await ResearchItemTypesService.getTypes();
            const type = types.filter(t => t.key === 'organized_event')[0];
            const qs = {where: {title: {contains: searchText}, type: type.id}};
            let accomplishments = await Restangular.all('accomplishments').getList(qs);

            accomplishments = accomplishments.map(accomplishment => accomplishment.title);
            const distinct = (value, index, self) => {
                return self.indexOf(value) === index;
            };

            return accomplishments.filter(distinct);
        }

        async function openSourceFormModal($event) {

            // Stop event from bubbling up to parents
            $event.stopPropagation();

            // Subscribe to custom event SOURCE_CREATED, execute following function when event is fired
            EventsService.subscribe(vm, EventsService.SOURCE_CREATED, function (event, source) {
                vm.accomplishment.source = source;
                vm.getSources(source.title);
                vm.unsavedData = true;

                vm.errors = AccomplishmentService.validate(vm.accomplishment);
                return checkValidation();
            });

            // Open source type modal
            ModalService.openSourceTypeModal();
        }

        async function verify() {
            vm.errorText = '';
            vm.errors = {};
            vm.verifyStatus.setState('verifying');

            $timeout(async function () {
                vm.errors = await AccomplishmentService.validate(vm.accomplishment);

                if (Object.keys(vm.errors).length === 0) {
                    // Is valid
                    await processSave();
                    vm.verifyStatus.setState('verified');
                    await vm.closeFn()();
                    AccomplishmentService.verify(vm.researchEntity, vm.accomplishment);
                } else {
                    // Is not valid
                    vm.verifyStatus.setState('failed');
                    vm.errorText = 'The draft has been saved but not been verified! Please correct the errors on this form!';

                    await processSave(false);

                    $timeout(function () {
                        vm.verifyStatus.setState('ready to verify');
                    }, 1000);
                }
            }, 200);
        }
        /* jshint ignore:end */

        function close() {
            if (_.isFunction(vm.checkAndClose()))
                vm.checkAndClose()(() => !vm.unsavedData);
        }
    }
})();


text:
package ptichka

import (
	"bytes"
	"errors"
	"fmt"
	"html"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"sort"
	"text/template"
	"time"

	"github.com/BurntSushi/toml"

	"gopkg.in/jordan-wright/email.v2"
)

// Version is an package version.
const Version = "0.7.2"

// tweet is a simplified anaconda.Tweet.
type tweet struct {
	IDStr          string
	UserScreenName string
	Date           time.Time
	Text           string
	Medias         []*media
}

// title returns string with label, user name and time
// for example "[twitter] @JohnDoe 1970-01-01 00:00 +0000"
func (t tweet) title(config *configuration) string {
	return fmt.Sprintf(
		"%s@%s %s",
		config.Label,
		t.UserScreenName,
		t.Date.Format("2006-01-02 15:04 -0700"))
}

func (t tweet) text() (string, error) {
	tmpl, err := template.New("tweet").Parse(
		`@{{.UserScreenName}}

{{.Text}}

https://twitter.com/{{.UserScreenName}}/status/{{.IDStr}}`)
	if err != nil {
		return "", err
	}

	var b bytes.Buffer

	err = tmpl.Execute(&b, tweet{
		IDStr:          t.IDStr,
		UserScreenName: t.UserScreenName,
		Text:           html.UnescapeString(t.Text)})

	return b.String(), err
}

// media is an simplified anaconda EntityMedia.
type media struct {
	IDStr          string
	MediaURLHttps  string
	DownloadedPath string
}

// tweetsByDate is a slice of tweet
// with ability to be sorted by date from older to newer.
type tweetsByDate []*tweet

// <https://github.com/wskinner/anaconda/commit/d0c12d8fba671d7d5ce27d3abd1809aedcc59195>,
// <http://nerdyworm.com/blog/2013/05/15/sorting-a-slice-of-structs-in-go/>.

// Len is the number of elements in the collection.
func (a tweetsByDate) Len() int { return len(a) }

// Less reports whether the element with index i should sort before
// the element with index j.
func (a tweetsByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

// Swap swaps the elements with indexes i and j.
func (a tweetsByDate) Less(i, j int) bool { return a[i].Date.Before(a[j].Date) }

// Ptichka is the synchronous entry point which initiate asynchronous routines
// for fetching/sending.
func Ptichka(
	pathToConfig,
	rawConfig string,
	fetcher Fetcher,
	sender Sender) []error {

	// verboseOut, infOut, errOut *io.Writer
	var err error
	var errs []error

	var configs *Configurations
	if len(rawConfig) > 0 {
		if _, err = toml.Decode(rawConfig, &configs); err != nil {
			errs = append(errs, err)
			return errs
		}
	} else if len(pathToConfig) > 0 {
		_, err = toml.DecodeFile(pathToConfig, &configs)
		if err != nil {
			errs = append(errs, err)
			return errs
		}
	} else {
		errs = append(errs, errors.New("Config not provided"))
		return errs
	}

	errCh := make(chan error)
	for _, config := range configs.Accounts {
		var infHandler, errHandler io.Writer

		if len(config.LogFile) > 0 {
			logFile, err := os.OpenFile(
				config.LogFile,
				os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
			if err != nil {
				errs = append(errs, err)
				return errs
			}
			defer func() { _ = logFile.Close() }()
			infHandler, errHandler = logFile, logFile
		} else {
			infHandler = os.Stdout
			errHandler = os.Stderr
		}

		if !config.Verbose {
			infHandler = ioutil.Discard
		}

		go Fly(
			config,
			fetcher,
			sender,
			errCh,
			log.New(infHandler, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile),
			log.New(errHandler, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile))
	}

	for range configs.Accounts {
		err := <-errCh
		if err != nil {
			errs = append(errs, err)
		}
	}

	return errs
}

// Fly fetch home timeline and sends by SMTP.
func Fly(
	config *configuration,
	fetcher Fetcher,
	sender Sender,
	errCh chan<- error,
	infLogger, errLogger *log.Logger) {

	oldIds, err := loadCache(config.CacheFile)
	if err != nil {
		errCh <- err
		return
	}

	infLogger.Printf("%sCache loaded: %s", config.Label, config.CacheFile)

	messages, err := fetch(config, fetcher, oldIds, infLogger, errLogger)
	if err != nil {
		errCh <- err
		return
	}

	infLogger.Printf("%sFetched messages: %d", config.Label, len(messages))

	newIds := make([]string, 0, len(messages))

	// Sends mails without goroutines
	// to preserve sort order of the mails (tweets).
	var smtpErr error

	for IDStr, message := range messages {
		smtpErr = sender.send(config, message)

		if smtpErr != nil {
			break
		}

		infLogger.Printf("%sMessages sent: %s", config.Label, IDStr)
		newIds = append(newIds, IDStr)
	}

	var cacheErr error
	if len(newIds) > 0 {
		cacheErr = saveCache(config.CacheFile, append(oldIds, newIds...))
	}

	if smtpErr != nil {
		errLogger.Printf("%sSent messages: %d, messages does not sent: %d",
			config.Label, len(newIds), len(messages)-len(newIds))

		errCh <- smtpErr
		return
	}
	infLogger.Printf("%sSent messages: %d", config.Label, len(newIds))

	if cacheErr != nil {
		errLogger.Printf("%sCache does not saved: %s",
			config.Label, config.CacheFile)

		errCh <- cacheErr
		return
	}
	if len(newIds) > 0 {
		infLogger.Printf("%sCache saved: %s", config.Label, config.CacheFile)
	}

	errCh <- nil
}

// fetch fetch home timeline and returns
// array of the raw email messages
// (with headers, text and attachments encoded in base64).
func fetch(
	config *configuration,
	fetcher Fetcher,
	oldIds []string,
	infLogger, errLogger *log.Logger) (map[string][]byte, error) {

	messages := make(map[string][]byte)
	var err error

	anacondaTweets, err := fetcher.fetch(config)
	if err != nil {
		errLogger.Printf("%sTweets does not fetched", config.Label)
		return messages, err
	}
	infLogger.Printf("%sTweets fetched: %d", config.Label, len(anacondaTweets))

	tweets, err := anacondaTweets.toTweets()
	if err != nil {
		return messages, err
	}

	sort.Sort(tweets)

	newTweets := make(tweetsByDate, 0, len(tweets))
	newMedias := make(map[string]*media)

	mediaCh := make(chan *media)
	mediaErrCh := make(chan error)
	for _, currentTweet := range tweets {
		if contains(oldIds, currentTweet.IDStr) {
			continue
		}

		newTweets = append(newTweets, currentTweet)

		for _, m := range currentTweet.Medias {
			newMedias[m.IDStr] = m
		}
	}

	if len(newTweets) > 0 {
		infLogger.Printf("%sNew tweets fetched: %d", config.Label, len(newTweets))
	}

	var tempDirPath string
	if len(newMedias) > 0 {
		tempDirPath, err = ioutil.TempDir(os.TempDir(), "ptichka_")
		if err != nil {
			errLogger.Printf("%sTemporary directory does not created: %s",
				config.Label, tempDirPath)
			return messages, err
		}
		defer func(err error) {
			err = os.RemoveAll(tempDirPath)
			if err != nil {
				errLogger.Printf("%sTemporary directory does not removed: %s %v",
					config.Label, tempDirPath, err)
			} else {
				infLogger.Printf("%sTemporary directory removed: %s",
					config.Label, tempDirPath)
			}
		}(err)
		infLogger.Printf("%sTemporary directory created: %s",
			config.Label, tempDirPath)
	}
	for _, m := range newMedias {
		go getMedia(
			config,
			m,
			tempDirPath,
			mediaCh, mediaErrCh,
			infLogger, errLogger)
	}

	for range newMedias {
		newMedia := <-mediaCh
		newMedias[newMedia.IDStr] = newMedia
	}
	var errs []error
	for range newMedias {
		err = <-mediaErrCh
		if err != nil {
			errs = append(errs, err)
		}
	}
	infLogger.Printf("%sAttachments downloaded: %d", config.Label, len(newMedias))
	if len(errs) > 0 {
		errLogger.Printf("%sErrors when downloading attachments: %v",
			config.Label, errs)
		return messages, errs[0]
	}

	for _, newTweet := range newTweets {
		text, err := newTweet.text()
		if err != nil {
			return messages, err
		}

		message := &email.Email{
			From:    config.mailFrom(),
			To:      []string{config.mailTo()},
			Subject: newTweet.title(config),
			Text:    []byte(text)}

		for _, m := range newTweet.Medias {
			// Follow the assumption that the medias id_str is unique
			// for the whole Twitter.
			_, err = message.AttachFile(newMedias[m.IDStr].DownloadedPath)
			if err != nil {
				errLogger.Printf("%sAttaching error: %s %v",
					config.Label, newMedias[m.IDStr].DownloadedPath, err)
				return messages, err
			}
			infLogger.Printf("%sAttached: %s",
				config.Label, newMedias[m.IDStr].DownloadedPath)
		}

		rawMessage, err := message.Bytes()
		if err != nil {
			errLogger.Printf("%sError when generating raw mail: %s %v",
				config.Label, newTweet.IDStr, errs)

			return messages, err
		}

		infLogger.Printf("%sRaw mail generated: %s", config.Label, newTweet.IDStr)
		messages[newTweet.IDStr] = rawMessage
	}

	return messages, nil
}

func getMedia(
	config *configuration,
	newMedia *media,
	tempDirPath string,
	ch chan<- *media,
	errCh chan<- error,
	infLogger, errLogger *log.Logger) {

	var err error

	response, err := http.Get(newMedia.MediaURLHttps)
	if err != nil {
		errLogger.Printf("%sError downloading attachment: %s %s %v",
			config.Label, newMedia.IDStr, newMedia.MediaURLHttps, err)

		ch <- newMedia
		errCh <- err
		return
	}
	defer func(err error) {
		err = response.Body.Close()
		if err != nil {
			errLogger.Printf("%sAttachment response body does not closed: %s %s %v",
				config.Label, newMedia.IDStr, newMedia.MediaURLHttps, err)
		} else {
			infLogger.Printf("%sAttachment response body closed: %s %s",
				config.Label, newMedia.IDStr, newMedia.MediaURLHttps)
		}
	}(err)
	infLogger.Printf("%sAttachment downloaded: %s %s",
		config.Label, newMedia.IDStr, newMedia.MediaURLHttps)

	_, fileName := filepath.Split(newMedia.MediaURLHttps)

	tempFilePath := fmt.Sprintf("%s/%s", tempDirPath, fileName)

	tempFile, err := os.Create(tempFilePath)
	if err != nil {
		errLogger.Printf("%sError creating temporary file: %s %v",
			config.Label, tempDirPath, err)

		ch <- newMedia
		errCh <- err
		return
	}
	defer func(err error) {
		err = tempFile.Close()
		if err != nil {
			errLogger.Printf("%sTemporary file does not closed: %s %v",
				config.Label, tempDirPath, err)
		} else {
			infLogger.Printf("%sTemporary file closed: %s",
				config.Label, tempFilePath)
		}
	}(err)
	infLogger.Printf("%sTemporary file created: %s", config.Label, tempFilePath)

	_, err = io.Copy(tempFile, response.Body)
	if err != nil {
		errLogger.Printf("%sError copying temporary file: %s %v",
			config.Label, tempDirPath, err)

		ch <- newMedia
		errCh <- err
		return
	}
	infLogger.Printf("%sTemporary file copied: %s", config.Label, tempFilePath)

	newMedia.DownloadedPath = tempFilePath

	ch <- newMedia
	errCh <- nil
}

func contains(ids []string, id string) bool {
	for _, i := range ids {
		if i == id {
			return true
		}
	}
	return false
}


text:
var React = require("react"),
    PureRenderMixin = require('react/addons').addons.PureRenderMixin,
    Immutable = require("immutable"),
    BoardStore = require("../stores/BoardStore"),
    FootbarActionCreators = require("../actions/FootbarActionCreators");

function getStateFromStores() {
    return {data: Immutable.Map({
        "canRegret": BoardStore.canRegret(),
        "gameOver": BoardStore.gameOver(),
    })};
}

var FootbarSection = React.createClass({

    mixins: [PureRenderMixin],

    getInitialState: function() {
        return getStateFromStores();
    },

    componentDidMount: function() {
        BoardStore.addChangeListener(this._onChange);
    },

    componentWillUnmount: function() {
        BoardStore.removeChangeListener(this._onChange);
    },

    render: function() {
        var regretDisable = !this.state.data.get("canRegret"),
            gameOver = this.state.data.get("gameOver"),
            regretButton;

        if (regretDisable || gameOver) {
            regretButton = <input type="Button" className="footbar__right button button--danger" onClick={this._regret} disabled="disabled" value="Regret"/>
        } else {
            regretButton = <input type="Button" className="footbar__right button button--danger" onClick={this._regret} value="Regret"/>
        }

        return (
            <div className="footbar">
                <input type="button" className="footbar__left button button--success" onClick={this._start} value="New Game"/>
                {regretButton}
            </div>
        );
    },

    _start: function() {
        FootbarActionCreators.startGame();
    },

    _regret: function() {
        FootbarActionCreators.regret();
    },

    _onChange: function() {
        this.setState(getStateFromStores());
    }
});

module.exports = FootbarSection;


text:
USE [ANTERO]
GO
IF  EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 DROP COLUMN jarjestys_maanosa_koodi
END

IF  EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa2_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 DROP COLUMN jarjestys_maanosa2_koodi
END

IF  EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa3_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 DROP COLUMN jarjestys_maanosa3_koodi
END

IF  EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maatjavaltiot2_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 DROP COLUMN jarjestys_maatjavaltiot2_koodi
END

IF NOT EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 ADD jarjestys_maanosa_koodi AS case when maanosa_koodi = '-1' then 'ZZZZZ'  else cast(maanosa_koodi as varchar(10))
  END
END

IF NOT EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa2_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 ADD jarjestys_maanosa2_koodi AS case when maanosa2_koodi = '-1' then 'ZZZZZ'  else cast(maanosa2_koodi as varchar(10))
  END
END

IF NOT EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maanosa3_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 ADD jarjestys_maanosa3_koodi AS case when maanosa3_koodi = '-1' then 'ZZZZZ' else cast(maanosa3_koodi as varchar(10))
  END
END

IF NOT EXISTS (
	SELECT * FROM INFORMATION_SCHEMA.COLUMNS
	WHERE TABLE_SCHEMA='dw' AND TABLE_NAME='d_maatjavaltiot2' AND COLUMN_NAME='jarjestys_maatjavaltiot2_koodi')

BEGIN
	ALTER TABLE dw.d_maatjavaltiot2 ADD jarjestys_maatjavaltiot2_koodi AS case when maatjavaltiot2_koodi = '-1' then 'ZZZZZ' else cast(maatjavaltiot2_koodi as varchar(10))
  END
END


text:
<?php
namespace Chadicus\Marvel\Api\Entities;

/**
 * Unit tests for the Price class.
 *
 * @coversDefaultClass \Chadicus\Marvel\Api\Entities\Price
 * @covers ::<protected>
 */
final class PriceTest extends \PHPUnit\Framework\TestCase
{
    /**
     * Verify invalid constructor parameters cause exceptions.
     *
     * @param mixed $type  The description of the price.
     * @param mixed $price The price of the price.
     *
     * @test
     * @dataProvider constructorBadData
     * @expectedException \InvalidArgumentException
     *
     * @return void
     */
    public function constructWithInvalidParameters($type, $price)
    {
        new Price(['type' => $type, 'price' => $price]);
    }

    /**
     * Data provider for constructWithInvalidParameters.
     *
     * @return array
     */
    public function constructorBadData()
    {
        return [
            'type is empty' => ['', 'a price'],
            'type is whitespace' => ["\t \n", 'a price'],
            'type is not a string' => [true, 'a price'],
            'price is not a float' => ['a type', false],
        ];
    }

    /**
     * Verify valid constructor parameters cause no exceptions.
     *
     * @param mixed $type  The description of the price.
     * @param mixed $price The price of the price.
     *
     * @test
     * @dataProvider constructorGoodData
     *
     * @return void
     */
    public function constructWithValidParameters($type, $price)
    {
        $entity = new Price(['type' => $type, 'price' => $price]);
        $this->assertSame($type, $entity->getType());
        $this->assertSame($price, $entity->getPrice());
    }

    /**
     * Data provider for constructWithInvalidParameters.
     *
     * @return array
     */
    public function constructorGoodData()
    {
        return [
            'type is null, price is null' => [null, null],
            'type is null, price is float' => [null, 1.0],
            'type is string, price is null' => ['a type', null],
            'type is string, price is float' => ['a type', 1.0],
        ];
    }

    /**
     * Verify basic behavior of fromArray().
     *
     * @test
     *
     * @return void
     */
    public function fromArray()
    {
        $price = Price::fromArray(['type' => 'a type', 'price' => 1.0]);
        $this->assertSame('a type', $price->getType());
        $this->assertSame(1.0, $price->getPrice());
    }

    /**
     * Verify fromArray throws when input is invalid.
     *
     * @test
     * @expectedException \Exception
     *
     * @return void
     */
    public function fromArrayWithInvalidInput()
    {
        Price::fromArray(['type' => 'a type', 'price' => 'price not a float']);
    }

    /**
     * Verify basic behavior of fromArrays().
     *
     * @test
     *
     * @return void
     */
    public function fromArrays()
    {
        $prices = Price::fromArrays(
            [
                ['type' => 'a type', 'price' => 1.0],
                ['type' => 'another type', 'price' => 2.0],
            ]
        );

        $this->assertSame(2, count($prices));
        $this->assertSame('a type', $prices[0]->getType());
        $this->assertSame(1.0, $prices[0]->getPrice());
        $this->assertSame('another type', $prices[1]->getType());
        $this->assertSame(2.0, $prices[1]->getPrice());
    }

    /**
     * Verify fromArrays throws when input is invalid.
     *
     * @test
     * @expectedException \Exception
     *
     * @return void
     */
    public function fromArraysWithInvalidInput()
    {
        Price::fromArrays(
            [
                ['type' => 'a type', 'price' => 1.0],
                ['type' => '', 'price' => 2.0],
            ]
        );
    }
}


text:
module Elasticsearch
  module QueryDsl
    class MatchQuery < Query
      attribute_methods :type, :field, :query, :operator, :analyzer, :fuzziness,
                        :prefix_length, :max_expansions, :zero_terms_query,
                        :cutoff_frequency, :lenient

      def to_hash(params={})
        h = {}
        h[:operator]         = @operator unless @operator.nil?
        h[:analyzer]         = @analyzer unless @analyzer.nil?
        h[:fuzziness]        = @fuzziness unless @fuzziness.nil?
        h[:prefix_length]    = @prefix_length unless @prefix_length.nil?
        h[:max_expansions]   = @max_expansions unless @max_expansions.nil?
        h[:zero_terms_query] = @zero_terms_query unless @zero_terms_query.nil?
        h[:cutoff_frequency] = @cutoff_frequency unless @cutoff_frequency.nil?
        h[:lenient]          = @lenient unless @lenient.nil?
        if h.empty?
          {get_type => {@field => @query}}
        else
          h[:query] = @query
          {get_type => {@field => h}}
        end
      end

      protected

      def get_type
        type || :match
      end
    end
  end
end


text:
<?php

namespace App\Exception;

class TemperaturaOutOfBoundsException extends \Exception {

}


text:
The authoringInfo is an object containing metadata about the authoring process for creating a renderer object. This allows the authoring clients to save specific overridable settings so that next time it is accessed via an authoring client, their selections are remembered. Non-authoring clients can ignore it. Properties for color/size/transparency sliders, theme selection, classification information, and additional properties are saved within this object.

**Referenced by:** [ClassBreaks Renderer](classBreaksRenderer.md), [Raster ClassBreaks Renderer](rasterClassBreaksRenderer.md), [Raster UniqueValue Renderer](rasterUniqueValueRenderer.md), [Simple Renderer](simpleRenderer.md), [UniqueValue Renderer](uniqueValueRenderer.md)

### Properties

| Property | Details
| --- | ---
| classificationMethod | Used for classed color or size. The default value is `esriClassifyManual`.
If property is present, must be one of the following values:

`esriClassifyDefinedInterval`

`esriClassifyEqualInterval`

`esriClassifyManual`

`esriClassifyNaturalBreaks`

`esriClassifyQuantile`

`esriClassifyStandardDeviation`

| [colorRamp](colorRamp.md) | A colorRamp object is used to specify a range of colors that are applied to a group of symbols.
| [field1](field_authoringInfo.md) | Contains information about an attribute field relating to Relationship renderers.
| [field2](field_authoringInfo.md) | Contains information about an attribute field relating to Relationship renderers.
| fields | An array of string values representing field names used for creating predominance renderers.
| focus | Optional. Used for Relationship renderer. If not set, the legend will default to being square.
If property is present, must be one of the following values:

`HH`

`HL`

`LH`

`LL`

| lengthUnit | Unit used in user interfaces to display world/map sizes and distances
If property is present, must be one of the following values:

`centimeters`

`decimal-degrees`

`decimeters`

`feet`

`inches`

`kilometers`

`meters`

`miles`

`millimeters`

`nautical-miles`

`yards`

| numClasses | Number of classes to be associated with the relationship. Used for Relationship renderer.
| standardDeviationInterval | Use this property if the classificationMethod is `esriClassifyStandardDeviation`.
If property is present, must be one of the following values:

`0.25`

`0.33`

`0.5`

`1`

| type | Type:`String`
If property is present, must be one of the following values:

`classedColor`

`classedSize`

`predominance`

`relationship`

`univariateColorSize`

| [visualVariables](authoringInfo_visualVariable.md) | An array of visualVariable objects containing additional information needed when authoring the renderer.

### Additional information

The authoringInfo object is not required with a renderer. It is only used if rendering was generated using the Scene Viewer rendering tools. All snippets provided below show a portion of what is contained within `authoringInfo`. Please refer to the sample snippets in the [authoringInfo visual variable](authoringInfo_visualVariable.md) object for additional help.

### Classed Size Renderer (Option 1) Example

```json
{
  "authoringInfo": {
    "type": "classedSize",
    "classificationMethod": "esriClassifyNaturalBreaks"
  }
}
```
### Classed Size Renderer (Option 2) Example

```json
{
  "authoringInfo": {
    "type": "classedSize",
    "classificationMethod": "esriClassifyStandardDeviation",
    "standardDeviationInterval": 0.5
  }
}
```
### Classed Color Renderer (Option 1) Example

```json
{
  "authoringInfo": {
    "type": "classedColor",
    "classificationMethod": "esriClassifyNaturalBreaks"
  }
}
```
### Classed Color Renderer (Option 2) Example

```json
{
  "authoringInfo": {
    "type": "classedColor",
    "classificationMethod": "esriClassifyStandardDeviation",
    "standardDeviationInterval": 0.5
  }
}
```
### Predominance Renderer Example

```json
{
  "authoringInfo": {
    "type": "predominance",
    "fields": [
      "COST",
      "DOLLARS",
      "PRICE"
    ]
  }
}
```
### Univariate Color Size Renderer Example

```json
{
  "authoringInfo": {
    "type": "univariateColorSize",
    "visualVariables": [
      {
        "type": "sizeInfo",
        "minSliderValue": 1,
        "maxSliderValue": 1000
      },
      {
        "type": "colorInfo",
        "minSliderValue": 1,
        "maxSliderValue": 1000,
        "theme": "high-to-low"
      }
    ]
  }
}
```
### Relationship Renderer Example

```json
{
  "authoringInfo": {
    "classificationMethod": "esriClassifyQuantile",
    "field1": {
      "field": "VOTE_TURNOUT",
      "classBreakInfos": [
        {
          "minValue": 1.0844,
          "maxValue": 54.0946
        },
        {
          "minValue": 54.0946,
          "maxValue": 4083.8235
        }
      ]
    },
    "field2": {
      "field": "MP06026a_B",
      "normalizationField": "TOTPOP_CY",
      "classBreakInfos": [
        {
          "minValue": 0.101322,
          "maxValue": 0.197619
        },
        {
          "minValue": 0.197619,
          "maxValue": 0.266094
        }
      ]
    },
    "focus": "HH",
    "numClasses": 2,
    "type": "relationship"
  }
}
```


text:
{% extends 'osdc/tukey_admin/base.html' %}
{% load i18n %}
{% block title %}{% trans "Add Shibboleth Info to Login" %}{% endblock %}

{% block page_header %}
  {% include "horizon/common/_page_header.html" with title=_("Add Shibboleth Info to Login") %}
{% endblock page_header %}

{% block main %}
  {% include 'osdc/tukey_admin/_create_login_shibboleth.html' %}
{% endblock %}


text: Continuous deployment manager for Azure


text:
using blink::WebString;
using blink::WebURL;
using blink::WebURLLoader;
using blink::WebURLLoaderOptions;
using blink::WebURLRequest;
using blink::WebURLResponse;

namespace content {

namespace {

// URL used to create a relay session.
const char kCreateRelaySessionURL[] = "/create_session";

// Number of times we will try to request relay session.
const int kRelaySessionRetries = 3;

// Manimum relay server size we would try to parse.
const int kMaximumRelayResponseSize = 102400;

bool ParsePortNumber(
    const std::string& string, int* value) {
  if (!base::StringToInt(string, value) || *value <= 0 || *value >= 65536) {
    LOG(ERROR) << "Received invalid port number from relay server: " << string;
    return false;
  }
  return true;
}

}  // namespace

P2PPortAllocator::Config::Config()
    : legacy_relay(true),
      disable_tcp_transport(false) {
}

P2PPortAllocator::Config::~Config() {
}

P2PPortAllocator::Config::RelayServerConfig::RelayServerConfig()
    : port(0) {
}

P2PPortAllocator::Config::RelayServerConfig::~RelayServerConfig() {
}

P2PPortAllocator::P2PPortAllocator(
    blink::WebFrame* web_frame,
    P2PSocketDispatcher* socket_dispatcher,
    rtc::NetworkManager* network_manager,
    rtc::PacketSocketFactory* socket_factory,
    const Config& config)
    : cricket::BasicPortAllocator(network_manager, socket_factory),
      web_frame_(web_frame),
      socket_dispatcher_(socket_dispatcher),
      config_(config) {
  uint32 flags = 0;
  if (config_.disable_tcp_transport)
    flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
  set_flags(flags);
  set_allow_tcp_listen(false);
}

P2PPortAllocator::~P2PPortAllocator() {
}

cricket::PortAllocatorSession* P2PPortAllocator::CreateSessionInternal(
    const std::string& content_name,
    int component,
    const std::string& ice_username_fragment,
    const std::string& ice_password) {
  return new P2PPortAllocatorSession(
      this, content_name, component, ice_username_fragment, ice_password);
}

P2PPortAllocatorSession::P2PPortAllocatorSession(
    P2PPortAllocator* allocator,
    const std::string& content_name,
    int component,
    const std::string& ice_username_fragment,
    const std::string& ice_password)
    : cricket::BasicPortAllocatorSession(
        allocator, content_name, component,
        ice_username_fragment, ice_password),
      allocator_(allocator),
      relay_session_attempts_(0),
      relay_udp_port_(0),
      relay_tcp_port_(0),
      relay_ssltcp_port_(0),
      pending_relay_requests_(0) {
}

P2PPortAllocatorSession::~P2PPortAllocatorSession() {
}

void P2PPortAllocatorSession::didReceiveData(
    WebURLLoader* loader, const char* data,
    int data_length, int encoded_data_length) {
  DCHECK_EQ(loader, relay_session_request_.get());
  if (static_cast<int>(relay_session_response_.size()) + data_length >
      kMaximumRelayResponseSize) {
    LOG(ERROR) << "Response received from the server is too big.";
    loader->cancel();
    return;
  }
  relay_session_response_.append(data, data + data_length);
}

void P2PPortAllocatorSession::didFinishLoading(
    WebURLLoader* loader, double finish_time,
    int64_t total_encoded_data_length) {
  ParseRelayResponse();
}

void P2PPortAllocatorSession::didFail(blink::WebURLLoader* loader,
                                      const blink::WebURLError& error) {
  DCHECK_EQ(loader, relay_session_request_.get());
  DCHECK_NE(error.reason, 0);

  LOG(ERROR) << "Relay session request failed.";

  // Retry the request.
  AllocateLegacyRelaySession();
}

void P2PPortAllocatorSession::GetPortConfigurations() {
  if (allocator_->config_.legacy_relay) {
    AllocateLegacyRelaySession();
  }
  AddConfig();
}

void P2PPortAllocatorSession::AllocateLegacyRelaySession() {
  if (allocator_->config_.relays.empty())
    return;
  // If we are using legacy relay, we will have only one entry in relay server
  // list.
  P2PPortAllocator::Config::RelayServerConfig relay_config =
      allocator_->config_.relays[0];

  if (relay_session_attempts_ > kRelaySessionRetries)
    return;
  relay_session_attempts_++;

  relay_session_response_.clear();

  WebURLLoaderOptions options;
  options.allowCredentials = false;

  options.crossOriginRequestPolicy =
      WebURLLoaderOptions::CrossOriginRequestPolicyUseAccessControl;

  relay_session_request_.reset(
      allocator_->web_frame_->createAssociatedURLLoader(options));
  if (!relay_session_request_) {
    LOG(ERROR) << "Failed to create URL loader.";
    return;
  }

  std::string url = "https://" + relay_config.server_address +
      kCreateRelaySessionURL +
      "?username=" + net::EscapeUrlEncodedData(username(), true) +
      "&password=" + net::EscapeUrlEncodedData(password(), true);

  WebURLRequest request;
  request.initialize();
  request.setURL(WebURL(GURL(url)));
  request.setAllowStoredCredentials(false);
  request.setCachePolicy(WebURLRequest::ReloadIgnoringCacheData);
  request.setHTTPMethod("GET");
  request.addHTTPHeaderField(
      WebString::fromUTF8("X-Talk-Google-Relay-Auth"),
      WebString::fromUTF8(relay_config.password));
  request.addHTTPHeaderField(
      WebString::fromUTF8("X-Google-Relay-Auth"),
      WebString::fromUTF8(relay_config.username));
  request.addHTTPHeaderField(WebString::fromUTF8("X-Stream-Type"),
                             WebString::fromUTF8("chromoting"));

  relay_session_request_->loadAsynchronously(request, this);
}

void P2PPortAllocatorSession::ParseRelayResponse() {
  base::StringPairs value_pairs;
  if (!base::SplitStringIntoKeyValuePairs(relay_session_response_, '=', '\n',
                                          &value_pairs)) {
    LOG(ERROR) << "Received invalid response from relay server";
    return;
  }

  relay_ip_.Clear();
  relay_udp_port_ = 0;
  relay_tcp_port_ = 0;
  relay_ssltcp_port_ = 0;

  for (base::StringPairs::iterator it = value_pairs.begin();
       it != value_pairs.end(); ++it) {
    std::string key;
    std::string value;
    base::TrimWhitespaceASCII(it->first, base::TRIM_ALL, &key);
    base::TrimWhitespaceASCII(it->second, base::TRIM_ALL, &value);

    if (key == "username") {
      if (value != username()) {
        LOG(ERROR) << "When creating relay session received user name "
            " that was different from the value specified in the query.";
        return;
      }
    } else if (key == "password") {
      if (value != password()) {
        LOG(ERROR) << "When creating relay session received password "
            "that was different from the value specified in the query.";
        return;
      }
    } else if (key == "relay.ip") {
      relay_ip_.SetIP(value);
      if (relay_ip_.ip() == 0) {
        LOG(ERROR) << "Received unresolved relay server address: " << value;
        return;
      }
    } else if (key == "relay.udp_port") {
      if (!ParsePortNumber(value, &relay_udp_port_))
        return;
    } else if (key == "relay.tcp_port") {
      if (!ParsePortNumber(value, &relay_tcp_port_))
        return;
    } else if (key == "relay.ssltcp_port") {
      if (!ParsePortNumber(value, &relay_ssltcp_port_))
        return;
    }
  }

  AddConfig();
}

void P2PPortAllocatorSession::AddConfig() {
  const P2PPortAllocator::Config& config = allocator_->config_;
  cricket::PortConfiguration* port_config = new cricket::PortConfiguration(
      config.stun_servers, std::string(), std::string());

  for (size_t i = 0; i < config.relays.size(); ++i) {
    cricket::RelayCredentials credentials(config.relays[i].username,
                                          config.relays[i].password);
    cricket::RelayServerConfig relay_server(cricket::RELAY_TURN);
    cricket::ProtocolType protocol;
    if (!cricket::StringToProto(config.relays[i].transport_type.c_str(),
                                &protocol)) {
      DLOG(WARNING) << "Ignoring TURN server "
                    << config.relays[i].server_address << ". "
                    << "Reason= Incorrect "
                    << config.relays[i].transport_type
                    << " transport parameter.";
      continue;
    }

    relay_server.ports.push_back(cricket::ProtocolAddress(
        rtc::SocketAddress(config.relays[i].server_address,
                                 config.relays[i].port),
        protocol,
        config.relays[i].secure));
    relay_server.credentials = credentials;
    port_config->AddRelay(relay_server);
  }
  ConfigReady(port_config);
}

}  // namespace content


text:
package org.springframework.boot.autoconfigure.web.embedded;

import org.junit.Before;
import org.junit.Test;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.mock.env.MockEnvironment;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

/**
 * Tests for {@link NettyWebServerFactoryCustomizer}.
 *
 * @author Brian Clozel
 */
public class NettyWebServerFactoryCustomizerTests {

	private MockEnvironment environment;

	private ServerProperties serverProperties;

	private NettyWebServerFactoryCustomizer customizer;

	@Before
	public void setup() {
		this.environment = new MockEnvironment();
		this.serverProperties = new ServerProperties();
		ConfigurationPropertySources.attach(this.environment);
		this.customizer = new NettyWebServerFactoryCustomizer(this.environment,
				this.serverProperties);
	}

	@Test
	public void deduceUseForwardHeaders() {
		this.environment.setProperty("DYNO", "-");
		NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
		this.customizer.customize(factory);
		verify(factory).setUseForwardHeaders(true);
	}

	@Test
	public void defaultUseForwardHeaders() {
		NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
		this.customizer.customize(factory);
		verify(factory).setUseForwardHeaders(false);
	}

	@Test
	public void setUseForwardHeaders() {
		this.serverProperties.setUseForwardHeaders(true);
		NettyReactiveWebServerFactory factory = mock(NettyReactiveWebServerFactory.class);
		this.customizer.customize(factory);
		verify(factory).setUseForwardHeaders(true);
	}

}


text:
Was geht denn hier ab?<lively-code-mirror mode="text/jsx" overscroll="contain" class="lively-content" style="position: absolute; left: 375px; top: 103px; width: 732px; height: 171px;" id="editor">this.style.backgroundColor = "white"

this.style.display = "block";

this.style.display = "flex";
this.style["align-items"] = "center";
// stretch|center|flex-start|flex-end|baseline|initial|inherit;

this.style["justify-content"] = "center";
//  flex-start|flex-end|center|space-between|space-around|initial|inherit

</lively-code-mirror>


text:
package user_interface;

import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import team15.articlemanagerclient.R;

public class DownloadScreen extends AppCompatActivity {

    // ALL POPUP CODE IS DONE IN THE CLASS THAT CALLS THE POPUP!

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_screen);
    }
}


text:
Solution::Solution() {
    this->maxFacilityCount = 0;
}
Solution::Solution(int maxFacilityCount) {
    this->maxFacilityCount = maxFacilityCount;
}

//getters
int Solution::getScore() const {
    return score;
}

int Solution::getCurrentFacilityCount() const {
    return facilities.size();
}

int Solution::getFacility(int position) const {
    return facilities[position];
}

//setters
void Solution::setScore(int score) {
    this->score = score;
}

void Solution::setMaxFacilityCount(int maxFacilityCount) {
    this->maxFacilityCount = maxFacilityCount;
}

void Solution::setFacilityAt(int facilityNumber,int index) {
    facilities[index] = facilityNumber;
    std::sort(facilities.begin(),facilities.end());
}

void Solution::addFacility(int facilityNumber) {
    if(this->getCurrentFacilityCount() < this->maxFacilityCount) {
        facilities.push_back(facilityNumber);
        std::sort(facilities.begin(),facilities.end());
    }
}

//helper functions
bool Solution::isFacilityInSolution(int facilityNumber) {
    return (find(facilities.begin(),facilities.end(),facilityNumber) != facilities.end());
}

void Solution::computeScore(Graph & graph) {
    int tempScore = -999999;
    FORN(currentCity,graph.getNumberOfNodes()) {
       int distanceToNearestFacility = MAX_VALUE;

       FORN(currentFacilityCount,this->getCurrentFacilityCount()) {
           int facilityNumber = facilities[currentFacilityCount];
           distanceToNearestFacility = std::min(distanceToNearestFacility,graph.getEdgeWeight(currentCity,facilityNumber));
       }

       tempScore = std::max(tempScore,distanceToNearestFacility);
    }
    this->score = tempScore;
}

int Solution::getDifference(Solution & other) {
    int difference = 0;
    FORN(i,other.getCurrentFacilityCount()) {
        if(!this->isFacilityInSolution(other.getFacility(i)))
            difference++;
    }

    return difference;
}

void Solution::clear() {
    score = MIN_VALUE;
    facilities.clear();
}

std::string Solution::toString() {
    std::string returnString;

    returnString += "Facilties: ";
    for(int i: facilities)
        returnString += std::to_string(i) + " ";
    returnString += "Score: ";
    returnString += std::to_string(this->getScore());

    return returnString;
}

bool Solution::operator<(const Solution & rhs) const {
    return (this->getScore() < rhs.getScore());
}


text:
<?php

declare(strict_types=1);

namespace Humbug\PhpScoper\PhpParser\NodeVisitor;

use Humbug\PhpScoper\PhpParser\StringNodePrefixer;
use PhpParser\Node;
use PhpParser\Node\Expr\Eval_;
use PhpParser\Node\Scalar\String_;
use PhpParser\NodeVisitorAbstract;

final class EvalPrefixer extends NodeVisitorAbstract
{
    private StringNodePrefixer $stringPrefixer;

    public function __construct(StringNodePrefixer $stringPrefixer)
    {
        $this->stringPrefixer = $stringPrefixer;
    }

    public function enterNode(Node $node): Node
    {
        if ($node instanceof String_
            && ParentNodeAppender::findParent($node) instanceof Eval_
        ) {
            $this->stringPrefixer->prefixStringValue($node);
        }

        return $node;
    }
}


text:
package net.firejack.platform.core.config.translate.sql.discriminator;

public class FullNameDiscriminatorColumnStrategy implements IDiscriminatorColumnStrategy {

    @Override
    public String getDiscriminatorValue(String entityName) {
        return entityName;
    }

}


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../../../shared/complex/numeric/imag', __FILE__)

ruby_version_is ""..."1.9" do

  require 'complex'
  require 'rational'

  describe "Numeric#imag" do
    it_behaves_like :numeric_imag, :imag
  end
end


text:
class AddTargetIdToTestimonial < ActiveRecord::Migration
  def self.up
    add_column :testimonials, :target_id, :string
  end

  def self.down
    remove_column :testimonials, :target_id
  end
end


text:
<?php

require_once 'Codec.php';

/**
 * Reference implementation of the Windows codec.
 *
 * @category  OWASP
 * @package   ESAPI_Codecs
 * @author    Linden Darling <Linden.Darling@jds.net.au>
 * @author    Mike Boberski <boberski_michael@bah.com>
 * @copyright 2009-2010 The OWASP Foundation
 * @license   http://www.opensource.org/licenses/bsd-license.php New BSD license
 * @version   Release: @package_version@
 * @link      http://www.owasp.org/index.php/ESAPI
 */
class WindowsCodec extends Codec
{
    /**
     * Public Constructor
     */
    function __construct()
    {
        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    public function encodeCharacter($immune, $c)
    {
        //detect encoding, special-handling for chr(172) and chr(128) to chr(159)
        //which fail to be detected by mb_detect_encoding()
        $initialEncoding = $this->detectEncoding($c);

        // Normalize encoding to UTF-32
        $_4ByteUnencodedOutput = $this->normalizeEncoding($c);

        // Start with nothing; format it to match the encoding of the string passed
        //as an argument.
        $encodedOutput = mb_convert_encoding("", $initialEncoding);

        // Grab the 4 byte character.
        $_4ByteCharacter = $this->forceToSingleCharacter($_4ByteUnencodedOutput);

        // Get the ordinal value of the character.
        list(, $ordinalValue) = unpack("N", $_4ByteCharacter);

        // check for immune characters
        foreach ($immune as $immuneCharacter) {
            // Convert to UTF-32 (4 byte characters, regardless of actual number of
            //bytes in the character).
            $_4ByteImmuneCharacter = $this->normalizeEncoding($immuneCharacter);

            // Ensure it's a single 4 byte character (since $immune is an array of
            //strings) by grabbing only the 1st multi-byte character.
            $_4ByteImmuneCharacter = $this->forceToSingleCharacter(
                $_4ByteImmuneCharacter
            );

            // If the character is immune then return it.
            if ($_4ByteCharacter === $_4ByteImmuneCharacter) {
                return $encodedOutput . chr($ordinalValue);
            }
        }

        // Check for alphanumeric characters
        $hex = $this->getHexForNonAlphanumeric($_4ByteCharacter);
        if ($hex === null) {
            return $encodedOutput . chr($ordinalValue);
        }

        return $encodedOutput . "^" . $c;
    }

    /**
     * {@inheritdoc}
     */
    public function decodeCharacter($input)
    {
        // Assumption/prerequisite: $c is a UTF-32 encoded string
        $_4ByteEncodedInput = $input;

        if (mb_substr($_4ByteEncodedInput, 0, 1, "UTF-32") === null) {
            // 1st character is null, so return null
            // eat the 1st character off the string and return null
            //todo: no point in doing this
            $_4ByteEncodedInput = mb_substr(
                $input, 1, mb_strlen($_4ByteEncodedInput, "UTF-32"), "UTF-32"
            );
            return array(
                'decodedCharacter' => null,
                'encodedString' => null
            );
        }

        // if this is not an encoded character, return null
        if (mb_substr($_4ByteEncodedInput, 0, 1, "UTF-32") != $this->normalizeEncoding('^')) {
            // 1st character is not part of encoding pattern, so return null
            return array(
                'decodedCharacter' => null,
                'encodedString' => null
            );
        }

        // 1st character is part of encoding pattern...
        $second = mb_substr($_4ByteEncodedInput, 1, 1, "UTF-32");

        return array(
            'decodedCharacter' => $second,
            'encodedString' => mb_substr($input, 0, 2, "UTF-32")
        );
    }
}


text:
#ifndef CDBMIRROREDAPPENDONLY_H
#define CDBMIRROREDAPPENDONLY_H

#include "utils/palloc.h"
#include "storage/fd.h"
#include "storage/relfilenode.h"
#include "storage/smgr.h"
#include "cdb/cdbfilerepprimary.h"
#include "cdb/cdbpersistentstore.h"

/*
 * This module is for doing mirrored writes for Append-Only relation files privately being written
 * by a backend process.
 *
 * It is intended for Append-Only relation files not under the management of the Buffer Pool.
 */

/*
 * This structure contains write open information.  Consider the fields
 * inside to be private.
 */
typedef struct MirroredAppendOnlyOpen
{
	bool	isActive;

	RelFileNode	relFileNode;

	uint32		segmentFileNum;

	char		mirrorFilespaceLocation[MAXPGPATH+1];
					// UNDONE: Consider palloc'ing this instead of statically allocating
					// UNDONE: to use less stack space...

	File		primaryFile;

	MirrorDataLossTrackingState mirrorDataLossTrackingState;

	int64						mirrorDataLossTrackingSessionNum;

	bool						create;

	bool						primaryOnlyToLetResynchronizeWork;

	bool						mirrorOnly;

	bool						copyToMirror;

	bool						guardOtherCallsWithMirroredLock;

	StorageManagerMirrorMode	mirrorMode;

	bool						mirrorDataLossOccurred;
} MirroredAppendOnlyOpen;

// -----------------------------------------------------------------------------
// Open, Flush, and Close
// -----------------------------------------------------------------------------

/*
 * We call MirroredAppendOnly_Create with the MirroredLock already held.
 */
extern void MirroredAppendOnly_Create(
	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	int32						segmentFileNum,
				/* Which segment file. */

	char						*relationName,
					/* For tracing only.  Can be NULL in some execution paths. */

	MirrorDataLossTrackingState mirrorDataLossTrackingState,

	int64						mirrorDataLossTrackingSessionNum,

	int 						*primaryError,

	bool						*mirrorDataLossOccurred);

extern void MirroredAppendOnly_MirrorReCreate(
	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	int32						segmentFileNum,
				/* Which segment file. */

	MirrorDataLossTrackingState mirrorDataLossTrackingState,

	int64						mirrorDataLossTrackingSessionNum,

	bool						*mirrorDataLossOccurred);

/*
 * MirroredAppendOnly_OpenReadWrite will acquire and release the MirroredLock.
 */
extern void MirroredAppendOnly_OpenReadWrite(
	MirroredAppendOnlyOpen		*open,
				/* The resulting open struct. */

	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	int32						segmentFileNum,
				/* Which segment file. */

	char						*relationName,
					/* For tracing only.  Can be NULL in some execution paths. */

	int64						logicalEof,
				/* The logical EOF to begin appending the new data. */

	bool						traceOpenFlags,

	ItemPointer					persistentTid,

	int64						persistentSerialNum,

	int 						*primaryError);

extern void MirroredAppendOnly_AddMirrorResyncEofs(
	RelFileNode						*relFileNode,

	int32							segmentFileNum,

	char							*relationName,

	ItemPointer						persistentTid,

	int64							persistentSerialNum,

	MirroredLockLocalVars 			*mirroredLockByRefVars,

	bool							originalMirrorCatchupRequired,

	MirrorDataLossTrackingState 	originalMirrorDataLossTrackingState,

	int64 							originalMirrorDataLossTrackingSessionNum,

	int64							mirrorNewEof);

extern void MirroredAppendOnly_EndXactCatchup(
		int 							entryIndex,

		RelFileNode 					*relFileNode,

		int32							segmentFileNum,

		int 							nestLevel,

		char							*relationName,

		ItemPointer 					persistentTid,

		int64							persistentSerialNum,

		MirroredLockLocalVars			*mirroredLockVarsByRef,

		bool							lastMirrorCatchupRequired,

		MirrorDataLossTrackingState 	lastMirrorDataLossTrackingState,

		int64							lastMirrorDataLossTrackingSessionNum,

		int64							mirrorNewEof);

extern void MirroredAppendOnly_OpenResynchonize(
	MirroredAppendOnlyOpen		*open,
				/* The resulting open struct. */

	RelFileNode 				*relFileNode,
				/* The tablespace, database, and relation OIDs for the open. */

	int32						segmentFileNum,
				/* Which segment file. */

	int64						logicalEof,
				/* The logical EOF to begin appending the new data. */

	int 						*primaryError,

	bool						*mirrorDataLossOccurred);

/*
 * Flush and Close an Append-Only relation file.
 *
 * If the flush is unable to complete on the mirror, then information (segment file, old EOF,
 * new EOF) on the new Append-Only data will be added to the commit, distributed commit,
 * distributed prepared and commit prepared XLOG records so that data can be resynchronized
 * later.
 */
extern void MirroredAppendOnly_FlushAndClose(
	MirroredAppendOnlyOpen 		*open,
				/* The open struct. */

	int 						*primaryError,

	bool					*mirrorDataLossOccurred,

	bool					*mirrorCatchupRequired,

	MirrorDataLossTrackingState 	*originalMirrorDataLossTrackingState,

	int64 							*originalMirrorDataLossTrackingSessionNum);

/*
 * Flush an Append-Only relation file.
 */
extern void MirroredAppendOnly_Flush(
	MirroredAppendOnlyOpen 		*open,
				/* The open struct. */

	int 						*primaryError,

	bool						*mirrorDataLossOccurred);

/*
 * Close an Append-Only relation file.
 */
extern void MirroredAppendOnly_Close(
	MirroredAppendOnlyOpen 	*open,
				/* The open struct. */

	bool					*mirrorDataLossOccurred);

extern void MirroredAppendOnly_Drop(
	RelFileNode					*relFileNode,

	int32						segmentFileNum,

	char						*relationName,
					/* For tracing only.  Can be NULL in some execution paths. */

	bool  						primaryOnly,

	int							*primaryError,

	bool						*mirrorDataLossOccurred);

extern void MirroredAppendOnly_MirrorReDrop(
	RelFileNode					*relFileNode,

	int32						segmentFileNum,

	MirrorDataLossTrackingState mirrorDataLossTrackingState,

	int64						mirrorDataLossTrackingSessionNum,

	bool						*mirrorDataLossOccurred);

// -----------------------------------------------------------------------------
// Append
// -----------------------------------------------------------------------------

/*
 * Append mirrored.
 */
extern void MirroredAppendOnly_Append(
	MirroredAppendOnlyOpen *open,
				/* The open struct. */

	void		*appendData,
				/* Pointer to the Append-Only data. */

	int32		appendDataLen,

				/* The byte length of the Append-Only data. */
	int 		*primaryError,

	bool		*mirrorDataLossOccurred);

// -----------------------------------------------------------------------------
// Truncate
// ----------------------------------------------------------------------------
extern void MirroredAppendOnly_Truncate(
	MirroredAppendOnlyOpen *open,
				/* The open struct. */

	int64		position,
				/* The position to cutoff the data. */

	int 		*primaryError,

	bool		*mirrorDataLossOccurred);

// -----------------------------------------------------------------------------
// Read local side (primary segment)
// ----------------------------------------------------------------------------
extern int MirroredAppendOnly_Read(
	MirroredAppendOnlyOpen *open,
	/* The open struct. */

	void					*buffer,
	/* Pointer to the buffer. */

	int32					bufferLen);

#endif   /* CDBMIRROREDAPPENDONLY_H */