max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,113
<reponame>vbillet/Torque3D<gh_stars>1000+ //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "afx/arcaneFX.h" #include "math/mathIO.h" #include "math/mathUtils.h" #include "afx/afxEffectWrapper.h" #include "afx/afxChoreographer.h" #include "afx/xm/afxXfmMod.h" //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// class afxXM_HeightSamplerData : public afxXM_WeightedBaseData { typedef afxXM_WeightedBaseData Parent; public: /*C*/ afxXM_HeightSamplerData(); /*C*/ afxXM_HeightSamplerData(const afxXM_HeightSamplerData&, bool = false); void packData(BitStream* stream); void unpackData(BitStream* stream); virtual bool allowSubstitutions() const { return true; } static void initPersistFields(); afxXM_Base* create(afxEffectWrapper* fx, bool on_server); DECLARE_CONOBJECT(afxXM_HeightSamplerData); DECLARE_CATEGORY("AFX"); }; //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// class afxConstraint; class afxXM_HeightSampler : public afxXM_WeightedBase { typedef afxXM_WeightedBase Parent; public: /*C*/ afxXM_HeightSampler(afxXM_HeightSamplerData*, afxEffectWrapper*); virtual void updateParams(F32 dt, F32 elapsed, afxXM_Params& params); }; //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// IMPLEMENT_CO_DATABLOCK_V1(afxXM_HeightSamplerData); ConsoleDocClass( afxXM_HeightSamplerData, "@brief An xmod datablock.\n\n" "@ingroup afxXMods\n" "@ingroup AFX\n" "@ingroup Datablocks\n" ); afxXM_HeightSamplerData::afxXM_HeightSamplerData() { } afxXM_HeightSamplerData::afxXM_HeightSamplerData(const afxXM_HeightSamplerData& other, bool temp_clone) : afxXM_WeightedBaseData(other, temp_clone) { } void afxXM_HeightSamplerData::initPersistFields() { Parent::initPersistFields(); } void afxXM_HeightSamplerData::packData(BitStream* stream) { Parent::packData(stream); } void afxXM_HeightSamplerData::unpackData(BitStream* stream) { Parent::unpackData(stream); } afxXM_Base* afxXM_HeightSamplerData::create(afxEffectWrapper* fx, bool on_server) { afxXM_HeightSamplerData* datablock = this; if (getSubstitutionCount() > 0) { datablock = new afxXM_HeightSamplerData(*this, true); this->performSubstitutions(datablock, fx->getChoreographer(), fx->getGroupIndex()); } return new afxXM_HeightSampler(datablock, fx); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// afxXM_HeightSampler::afxXM_HeightSampler(afxXM_HeightSamplerData* db, afxEffectWrapper* fxw) : afxXM_WeightedBase(db, fxw) { } void afxXM_HeightSampler::updateParams(F32 dt, F32 elapsed, afxXM_Params& params) { afxConstraint* pos_cons = fx_wrapper->getPosConstraint(); if (!pos_cons) return; Point3F base_pos; pos_cons->getPosition(base_pos); F32 range = 0.5f; F32 height = (base_pos.z > params.pos.z) ? (base_pos.z - params.pos.z) : 0.0f; F32 factor = mClampF(1.0f - (height/range), 0.0f, 1.0f); //Con::printf("SET height=%g liveScaleFactor=%g", height, factor); fx_wrapper->setField("liveScaleFactor", avar("%g", factor)); fx_wrapper->setField("liveFadeFactor", avar("%g", factor)); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
1,596
1,738
<reponame>jeikabu/lumberyard /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #pragma once #include <AzCore/Component/ComponentBus.h> //////////////////////////////////////////////////////////////////////////////////////////////////// //! Interface class that a scroller component needs to implement. A scroller component provides //! functionality to control the scrolling of scrollable content //! (e.g. UiScrollBarComponent) class UiScrollerInterface : public AZ::ComponentBus { public: // types //! params: sending entity id, newValue, newPosition typedef AZStd::function<void(AZ::EntityId, float)> ValueChangeCallback; //! Scroller orientation enum class Orientation { Horizontal, Vertical }; public: // member functions virtual ~UiScrollerInterface() {} //! Get the current value for the scrollbar (0 - 1) virtual float GetValue() = 0; //! Set the value of the scrollbar (0 - 1) virtual void SetValue(float value) = 0; //! Get the orientation of the scroller virtual Orientation GetOrientation() = 0; //! Set the orientation of the scroller virtual void SetOrientation(Orientation orientation) = 0; //! Get the scrollable entity virtual AZ::EntityId GetScrollableEntity() = 0; //! Set the scrollable entity virtual void SetScrollableEntity(AZ::EntityId entityId) = 0; //! Get the callback invoked while the value is changing virtual ValueChangeCallback GetValueChangingCallback() = 0; //! Set the callback invoked while the value is changing virtual void SetValueChangingCallback(ValueChangeCallback onChange) = 0; //! Get the callback invoked when the value is done changing virtual ValueChangeCallback GetValueChangedCallback() = 0; //! Set the callback invoked when the value is done changing virtual void SetValueChangedCallback(ValueChangeCallback onChange) = 0; //! Get the action triggered while the value is changing virtual const LyShine::ActionName& GetValueChangingActionName() = 0; //! Set the action triggered while the value is changing virtual void SetValueChangingActionName(const LyShine::ActionName& actionName) = 0; //! Get the action triggered when the value is done changing virtual const LyShine::ActionName& GetValueChangedActionName() = 0; //! Set the action triggered when the value is done changing virtual void SetValueChangedActionName(const LyShine::ActionName& actionName) = 0; public: // static member data //! Only one component on a entity can implement the events static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; }; typedef AZ::EBus<UiScrollerInterface> UiScrollerBus; //////////////////////////////////////////////////////////////////////////////////////////////////// //! Interface class that listeners need to implement in order to get notifications when values of the //! scroller change class UiScrollerNotifications : public AZ::ComponentBus { public: // member functions virtual ~UiScrollerNotifications(){} //! Called when the scroller value (0 - 1) is changing virtual void OnScrollerValueChanging(float value) = 0; //! Called when the scroller value (0 - 1) has been changed virtual void OnScrollerValueChanged(float value) = 0; }; typedef AZ::EBus<UiScrollerNotifications> UiScrollerNotificationBus; //////////////////////////////////////////////////////////////////////////////////////////////////// //! Interface class that scrollables need to implement in order to get notifications when the scroller //! changes the value class UiScrollerToScrollableNotifications : public AZ::ComponentBus { public: // member functions virtual ~UiScrollerToScrollableNotifications(){} //! Called when the scroller is changing the scroll value (0 - 1) virtual void OnValueChangingByScroller(float value) = 0; //! Called when the scroller is done changing the scroll value (0 - 1) virtual void OnValueChangedByScroller(float value) = 0; }; typedef AZ::EBus<UiScrollerToScrollableNotifications> UiScrollerToScrollableNotificationBus;
1,267
2,151
<gh_stars>1000+ # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Functions specific to build slaves, shared by several buildbot scripts. """ import datetime import glob import os import re import shutil import subprocess import sys import tempfile import time from common import chromium_utils # These codes used to distinguish true errors from script warnings. ERROR_EXIT_CODE = 1 WARNING_EXIT_CODE = 88 def WriteLogLines(logname, lines, perf=None): logname = logname.rstrip() lines = [line.rstrip() for line in lines] for line in lines: print '@@@STEP_LOG_LINE@%s@%s@@@' % (logname, line) if perf: perf = perf.rstrip() print '@@@STEP_LOG_END_PERF@%s@%s@@@' % (logname, perf) else: print '@@@STEP_LOG_END@%s@@@' % logname
305
348
<filename>docs/data/leg-t1/015/01501172.json {"nom":"Saint-Antoine","circ":"1ère circonscription","dpt":"Cantal","inscrits":95,"abs":38,"votants":57,"blancs":1,"nuls":1,"exp":55,"res":[{"nuance":"REM","nom":"<NAME>","voix":23},{"nuance":"LR","nom":"<NAME>","voix":18},{"nuance":"DVD","nom":"<NAME>","voix":9},{"nuance":"FN","nom":"Mme <NAME>","voix":3},{"nuance":"COM","nom":"M. <NAME>","voix":2},{"nuance":"EXG","nom":"M. <NAME>","voix":0},{"nuance":"FI","nom":"M. <NAME>","voix":0},{"nuance":"ECO","nom":"<NAME>","voix":0},{"nuance":"ECO","nom":"M. <NAME>","voix":0},{"nuance":"DIV","nom":"M. <NAME>","voix":0}]}
252
2,813
<reponame>fernandes-natanael/jabref package org.jabref.model.openoffice; import java.util.Objects; import java.util.Optional; public class CitationEntry implements Comparable<CitationEntry> { private final String refMarkName; private final Optional<String> pageInfo; private final String context; public CitationEntry(String refMarkName, String context) { this(refMarkName, context, Optional.empty()); } public CitationEntry(String refMarkName, String context, String pageInfo) { this(refMarkName, context, Optional.ofNullable(pageInfo)); } public CitationEntry(String refMarkName, String context, Optional<String> pageInfo) { this.refMarkName = refMarkName; this.context = context; this.pageInfo = pageInfo; } public Optional<String> getPageInfo() { return pageInfo; } public String getRefMarkName() { return refMarkName; } @Override public int compareTo(CitationEntry other) { return this.refMarkName.compareTo(other.refMarkName); } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof CitationEntry) { CitationEntry other = (CitationEntry) object; return Objects.equals(this.refMarkName, other.refMarkName); } return false; } @Override public int hashCode() { return Objects.hash(refMarkName); } public String getContext() { return context; } }
594
808
<reponame>avboy1337/Hypervisor-From-Scratch #include <ntddk.h> #include <wdf.h> #include <wdm.h> #include "Common.h" #include "VMX.h" #include "EPT.h" VOID PrintChars(PCHAR BufferAddress, size_t CountChars); NTSTATUS DriverEntry(PDRIVER_OBJECT pDriverObject, PUNICODE_STRING pRegistryPath) { NTSTATUS NtStatus = STATUS_SUCCESS; UINT64 uiIndex = 0; PDEVICE_OBJECT pDeviceObject = NULL; UNICODE_STRING usDriverName, usDosDeviceName; DbgPrint("[*] DriverEntry Called.\n"); RtlInitUnicodeString(&usDriverName, L"\\Device\\MyHypervisorDevice"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\MyHypervisorDevice"); NtStatus = IoCreateDevice(pDriverObject, 0, &usDriverName, FILE_DEVICE_UNKNOWN, FILE_DEVICE_SECURE_OPEN, FALSE, &pDeviceObject); if (NtStatus == STATUS_SUCCESS) { for (uiIndex = 0; uiIndex < IRP_MJ_MAXIMUM_FUNCTION; uiIndex++) pDriverObject->MajorFunction[uiIndex] = DrvUnsupported; DbgPrint("[*] Setting Devices major functions.\n"); pDriverObject->MajorFunction[IRP_MJ_CLOSE] = DrvClose; pDriverObject->MajorFunction[IRP_MJ_CREATE] = DrvCreate; pDriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = DrvIOCTLDispatcher; pDriverObject->MajorFunction[IRP_MJ_READ] = DrvRead; pDriverObject->MajorFunction[IRP_MJ_WRITE] = DrvWrite; pDriverObject->DriverUnload = DrvUnload; IoCreateSymbolicLink(&usDosDeviceName, &usDriverName); } __try { // Initiating EPTP and VMX PEPTP EPTP = Initialize_EPTP(); Initiate_VMX(); for (size_t i = 0; i < (100 * PAGE_SIZE) - 1; i++) { void* TempAsm = "\xF4"; memcpy(VirtualGuestMemoryAddress + i, TempAsm, 1); } // Launching VM for Test (in the 0th virtual processor) int ProcessorID = 0; LaunchVM(ProcessorID, EPTP); } __except (GetExceptionCode()) { } return NtStatus; } VOID DrvUnload(PDRIVER_OBJECT DriverObject) { UNICODE_STRING usDosDeviceName; DbgPrint("[*] DrvUnload Called.\n"); RtlInitUnicodeString(&usDosDeviceName, L"\\DosDevices\\MyHypervisorDevice"); IoDeleteSymbolicLink(&usDosDeviceName); IoDeleteDevice(DriverObject->DeviceObject); } NTSTATUS DrvCreate(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("[*] DrvCreate Called !\n"); // Call VMPTRST // VMPTRST(); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } NTSTATUS DrvRead(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("[*] Not implemented yet :( !\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } NTSTATUS DrvWrite(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("[*] Not implemented yet :( !\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } NTSTATUS DrvClose(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("[*] DrvClose Called !\n"); // executing VMXOFF on every logical processor Terminate_VMX(); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } NTSTATUS DrvUnsupported(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { DbgPrint("[*] This function is not supported :( !\n"); Irp->IoStatus.Status = STATUS_SUCCESS; Irp->IoStatus.Information = 0; IoCompleteRequest(Irp, IO_NO_INCREMENT); return STATUS_SUCCESS; } VOID PrintChars( PCHAR BufferAddress, size_t CountChars ) { PAGED_CODE(); if (CountChars) { while (CountChars--) { if (*BufferAddress > 31 && *BufferAddress != 127) { KdPrint(("%c", *BufferAddress)); } else { KdPrint((".")); } BufferAddress++; } KdPrint(("\n")); } return; } NTSTATUS DrvIOCTLDispatcher(PDEVICE_OBJECT DeviceObject, PIRP Irp) /*++ Routine Description: This routine is called by the I/O system to perform a device I/O control function. Arguments: DeviceObject - a pointer to the object that represents the device that I/O is to be done on. Irp - a pointer to the I/O Request Packet for this request. Return Value: NT status code --*/ { PIO_STACK_LOCATION irpSp;// Pointer to current stack location NTSTATUS ntStatus = STATUS_SUCCESS;// Assume success ULONG inBufLength; // Input buffer length ULONG outBufLength; // Output buffer length PCHAR inBuf, outBuf; // pointer to Input and output buffer PCHAR data = "This String is from Device Driver !!!"; size_t datalen = strlen(data) + 1;//Length of data including null PMDL mdl = NULL; PCHAR buffer = NULL; UNREFERENCED_PARAMETER(DeviceObject); PAGED_CODE(); irpSp = IoGetCurrentIrpStackLocation(Irp); inBufLength = irpSp->Parameters.DeviceIoControl.InputBufferLength; outBufLength = irpSp->Parameters.DeviceIoControl.OutputBufferLength; if (!inBufLength || !outBufLength) { ntStatus = STATUS_INVALID_PARAMETER; goto End; } // // Determine which I/O control code was specified. // switch (irpSp->Parameters.DeviceIoControl.IoControlCode) { case IOCTL_SIOCTL_METHOD_BUFFERED: // // In this method the I/O manager allocates a buffer large enough to // to accommodate larger of the user input buffer and output buffer, // assigns the address to Irp->AssociatedIrp.SystemBuffer, and // copies the content of the user input buffer into this SystemBuffer // DbgPrint("Called IOCTL_SIOCTL_METHOD_BUFFERED\n"); PrintIrpInfo(Irp); // // Input buffer and output buffer is same in this case, read the // content of the buffer before writing to it // inBuf = Irp->AssociatedIrp.SystemBuffer; outBuf = Irp->AssociatedIrp.SystemBuffer; // // Read the data from the buffer // DbgPrint("\tData from User :"); // // We are using the following function to print characters instead // DebugPrint with %s format because we string we get may or // may not be null terminated. // DbgPrint(inBuf); PrintChars(inBuf, inBufLength); // // Write to the buffer over-writes the input buffer content // RtlCopyBytes(outBuf, data, outBufLength); DbgPrint(("\tData to User : ")); PrintChars(outBuf, datalen); // // Assign the length of the data copied to IoStatus.Information // of the Irp and complete the Irp. // Irp->IoStatus.Information = (outBufLength < datalen ? outBufLength : datalen); // // When the Irp is completed the content of the SystemBuffer // is copied to the User output buffer and the SystemBuffer is // is freed. // break; case IOCTL_SIOCTL_METHOD_NEITHER: // // In this type of transfer the I/O manager assigns the user input // to Type3InputBuffer and the output buffer to UserBuffer of the Irp. // The I/O manager doesn't copy or map the buffers to the kernel // buffers. Nor does it perform any validation of user buffer's address // range. // DbgPrint("Called IOCTL_SIOCTL_METHOD_NEITHER\n"); PrintIrpInfo(Irp); // // A driver may access these buffers directly if it is a highest level // driver whose Dispatch routine runs in the context // of the thread that made this request. The driver should always // check the validity of the user buffer's address range and check whether // the appropriate read or write access is permitted on the buffer. // It must also wrap its accesses to the buffer's address range within // an exception handler in case another user thread deallocates the buffer // or attempts to change the access rights for the buffer while the driver // is accessing memory. // inBuf = irpSp->Parameters.DeviceIoControl.Type3InputBuffer; outBuf = Irp->UserBuffer; // // Access the buffers directly if only if you are running in the // context of the calling process. Only top level drivers are // guaranteed to have the context of process that made the request. // try { // // Before accessing user buffer, you must probe for read/write // to make sure the buffer is indeed an userbuffer with proper access // rights and length. ProbeForRead/Write will raise an exception if it's otherwise. // ProbeForRead(inBuf, inBufLength, sizeof(UCHAR)); // // Since the buffer access rights can be changed or buffer can be freed // anytime by another thread of the same process, you must always access // it within an exception handler. // DbgPrint("\tData from User :"); DbgPrint(inBuf); PrintChars(inBuf, inBufLength); } except(EXCEPTION_EXECUTE_HANDLER) { ntStatus = GetExceptionCode(); DbgPrint( "Exception while accessing inBuf 0X%08X in METHOD_NEITHER\n", ntStatus); break; } // // If you are accessing these buffers in an arbitrary thread context, // say in your DPC or ISR, if you are using it for DMA, or passing these buffers to the // next level driver, you should map them in the system process address space. // First allocate an MDL large enough to describe the buffer // and initilize it. Please note that on a x86 system, the maximum size of a buffer // that an MDL can describe is 65508 KB. // mdl = IoAllocateMdl(inBuf, inBufLength, FALSE, TRUE, NULL); if (!mdl) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; break; } try { // // Probe and lock the pages of this buffer in physical memory. // You can specify IoReadAccess, IoWriteAccess or IoModifyAccess // Always perform this operation in a try except block. // MmProbeAndLockPages will raise an exception if it fails. // MmProbeAndLockPages(mdl, UserMode, IoReadAccess); } except(EXCEPTION_EXECUTE_HANDLER) { ntStatus = GetExceptionCode(); DbgPrint(( "Exception while locking inBuf 0X%08X in METHOD_NEITHER\n", ntStatus)); IoFreeMdl(mdl); break; } // // Map the physical pages described by the MDL into system space. // Note: double mapping the buffer this way causes lot of // system overhead for large size buffers. // buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute); if (!buffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; MmUnlockPages(mdl); IoFreeMdl(mdl); break; } // // Now you can safely read the data from the buffer. // DbgPrint("\tData from User (SystemAddress) : "); DbgPrint(buffer); PrintChars(buffer, inBufLength); // // Once the read is over unmap and unlock the pages. // MmUnlockPages(mdl); IoFreeMdl(mdl); // // The same steps can be followed to access the output buffer. // mdl = IoAllocateMdl(outBuf, outBufLength, FALSE, TRUE, NULL); if (!mdl) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; break; } try { // // Probe and lock the pages of this buffer in physical memory. // You can specify IoReadAccess, IoWriteAccess or IoModifyAccess. // MmProbeAndLockPages(mdl, UserMode, IoWriteAccess); } except(EXCEPTION_EXECUTE_HANDLER) { ntStatus = GetExceptionCode(); DbgPrint( "Exception while locking outBuf 0X%08X in METHOD_NEITHER\n", ntStatus); IoFreeMdl(mdl); break; } buffer = MmGetSystemAddressForMdlSafe(mdl, NormalPagePriority | MdlMappingNoExecute); if (!buffer) { MmUnlockPages(mdl); IoFreeMdl(mdl); ntStatus = STATUS_INSUFFICIENT_RESOURCES; break; } // // Write to the buffer // RtlCopyBytes(buffer, data, outBufLength); DbgPrint("\tData to User : %s\n", buffer); PrintChars(buffer, datalen); MmUnlockPages(mdl); // // Free the allocated MDL // IoFreeMdl(mdl); // // Assign the length of the data copied to IoStatus.Information // of the Irp and complete the Irp. // Irp->IoStatus.Information = (outBufLength < datalen ? outBufLength : datalen); break; case IOCTL_SIOCTL_METHOD_IN_DIRECT: // // In this type of transfer, the I/O manager allocates a system buffer // large enough to accommodatethe User input buffer, sets the buffer address // in Irp->AssociatedIrp.SystemBuffer and copies the content of user input buffer // into the SystemBuffer. For the user output buffer, the I/O manager // probes to see whether the virtual address is readable in the callers // access mode, locks the pages in memory and passes the pointer to // MDL describing the buffer in Irp->MdlAddress. // DbgPrint("Called IOCTL_SIOCTL_METHOD_IN_DIRECT\n"); PrintIrpInfo(Irp); inBuf = Irp->AssociatedIrp.SystemBuffer; DbgPrint("\tData from User in InputBuffer: "); DbgPrint(inBuf); PrintChars(inBuf, inBufLength); // // To access the output buffer, just get the system address // for the buffer. For this method, this buffer is intended for transfering data // from the application to the driver. // buffer = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority | MdlMappingNoExecute); if (!buffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; break; } DbgPrint("\tData from User in OutputBuffer: "); DbgPrint(buffer); PrintChars(buffer, outBufLength); // // Return total bytes read from the output buffer. // Note OutBufLength = MmGetMdlByteCount(Irp->MdlAddress) // Irp->IoStatus.Information = MmGetMdlByteCount(Irp->MdlAddress); // // NOTE: Changes made to the SystemBuffer are not copied // to the user input buffer by the I/O manager // break; case IOCTL_SIOCTL_METHOD_OUT_DIRECT: // // In this type of transfer, the I/O manager allocates a system buffer // large enough to accommodate the User input buffer, sets the buffer address // in Irp->AssociatedIrp.SystemBuffer and copies the content of user input buffer // into the SystemBuffer. For the output buffer, the I/O manager // probes to see whether the virtual address is writable in the callers // access mode, locks the pages in memory and passes the pointer to MDL // describing the buffer in Irp->MdlAddress. // DbgPrint("Called IOCTL_SIOCTL_METHOD_OUT_DIRECT\n"); PrintIrpInfo(Irp); inBuf = Irp->AssociatedIrp.SystemBuffer; DbgPrint("\tData from User : "); DbgPrint(inBuf); PrintChars(inBuf, inBufLength); // // To access the output buffer, just get the system address // for the buffer. For this method, this buffer is intended for transfering data // from the driver to the application. // buffer = MmGetSystemAddressForMdlSafe(Irp->MdlAddress, NormalPagePriority | MdlMappingNoExecute); if (!buffer) { ntStatus = STATUS_INSUFFICIENT_RESOURCES; break; } // // Write data to be sent to the user in this buffer // RtlCopyBytes(buffer, data, outBufLength); DbgPrint("\tData to User : "); PrintChars(buffer, datalen); Irp->IoStatus.Information = (outBufLength < datalen ? outBufLength : datalen); // // NOTE: Changes made to the SystemBuffer are not copied // to the user input buffer by the I/O manager // break; default: // // The specified I/O control code is unrecognized by this driver. // ntStatus = STATUS_INVALID_DEVICE_REQUEST; DbgPrint("ERROR: unrecognized IOCTL %x\n", irpSp->Parameters.DeviceIoControl.IoControlCode); break; } End: // // Finish the I/O operation by simply completing the packet and returning // the same status as in the packet itself. // Irp->IoStatus.Status = ntStatus; IoCompleteRequest(Irp, IO_NO_INCREMENT); return ntStatus; } VOID PrintIrpInfo( PIRP Irp) { PIO_STACK_LOCATION irpSp; irpSp = IoGetCurrentIrpStackLocation(Irp); PAGED_CODE(); DbgPrint("\tIrp->AssociatedIrp.SystemBuffer = 0x%p\n", Irp->AssociatedIrp.SystemBuffer); DbgPrint("\tIrp->UserBuffer = 0x%p\n", Irp->UserBuffer); DbgPrint("\tirpSp->Parameters.DeviceIoControl.Type3InputBuffer = 0x%p\n", irpSp->Parameters.DeviceIoControl.Type3InputBuffer); DbgPrint("\tirpSp->Parameters.DeviceIoControl.InputBufferLength = %d\n", irpSp->Parameters.DeviceIoControl.InputBufferLength); DbgPrint("\tirpSp->Parameters.DeviceIoControl.OutputBufferLength = %d\n", irpSp->Parameters.DeviceIoControl.OutputBufferLength); return; }
6,817
4,303
#include "Halide.h" #include <functional> #include <stdio.h> using namespace Halide; using namespace Halide::Internal; typedef std::function<int(int, int, int)> FuncChecker; int check_image(const Realization &r, const std::vector<FuncChecker> &funcs) { for (size_t idx = 0; idx < funcs.size(); idx++) { const Buffer<int> &im = r[idx]; for (int z = 0; z < im.channels(); z++) { for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = funcs[idx](x, y, z); if (im(x, y, z) != correct) { printf("im(%d, %d, %d) = %d instead of %d\n", x, y, z, im(x, y, z), correct); return -1; } } } } } return 0; } int main(int argc, char **argv) { { Var x("x"), y("y"); Func f("f"), h("h"); h(x, y) = x + y; h.compute_root(); f(x, _) = h(_) + 2; // This means f(x, _0, _1) = h(_0, _1) + 2 Realization result = f.realize({100, 100, 100}); auto func = [](int x, int y, int z) { return y + z + 2; }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"), z("z"); Func f("f"), g("g"), h("h"); h(x, y) = x + y; h.compute_root(); f(x, y, z) = x; f.compute_root(); RDom r(0, 2); g(x, _) = h(_) + 1; // This means g(x, _0, _1) = h(_0, _1) + 1 g(clamp(f(r.x, _), 0, 50), _) += 2; // This means g(f(r.x, _0, _1), _0, _1) += 2 Realization result = g.realize({100, 100, 100}); auto func = [](int x, int y, int z) { return (x == 0) || (x == 1) ? y + z + 3 : y + z + 1; }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"); Func f("f"), g("g"), h("h"); h(x, y) = x + y; h.compute_root(); g(x) = x + 2; g.compute_root(); f(x, _) = h(_) + 3; // This means f(x, _0, _1) = h(_0, _1) + 3 f(x, _) += h(_) * g(_); // This means f(x, _0, _1) += h(_0, _1) * g(_0) Realization result = f.realize({100, 100, 100}); auto func = [](int x, int y, int z) { return (y + z + 3) + (y + z) * (y + 2); }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"); Func f("f"), h("h"); h(x, y) = x + y; h.compute_root(); // This is equivalent to: // f(x, _0, _1) = 0 // f(x, _0, _1) += h(_0, _1) + 2 f(x, _) += h(_) + 2; Realization result = f.realize({100, 100, 100}); auto func = [](int x, int y, int z) { return y + z + 2; }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"); Func f("f"), g("g"), h("h"); h(x, y) = x + y; h.compute_root(); g(x) = x + 2; g.compute_root(); // This is equivalent to: // f(_0, _1) = 0 // f(_0, _1) += h(_0, _1)*g(_0) + 3 f(_) += h(_) * g(_) + 3; Realization result = f.realize({100, 100}); auto func = [](int x, int y, int z) { return (x + y) * (x + 2) + 3; }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"); Func f("f"), h("h"); h(x, y) = x + y; h.compute_root(); // This means f(x, _0, _1) = {h(_0, _1) + 2, x + 2} f(x, _) = Tuple(h(_) + 2, x + 2); Realization result = f.realize({100, 100, 100}); auto func1 = [](int x, int y, int z) { return y + z + 2; }; auto func2 = [](int x, int y, int z) { return x + 2; }; if (check_image(result, {func1, func2})) { return -1; } } { Var x("x"), y("y"), z("z"); Func f("f"), g("g"), h("h"); h(x, y) = x + y; h.compute_root(); f(x, y, z) = x; f.compute_root(); RDom r(0, 2); // This means g(x, _0, _1) = {h(_0, _1) + 1} g(x, _) = Tuple(h(_) + 1); // This means g(f(r.x, _0, _1), _0, _1) += {2} g(clamp(f(r.x, _), 0, 50), _) += Tuple(2); Realization result = g.realize({100, 100, 100}); auto func = [](int x, int y, int z) { return (x == 0) || (x == 1) ? y + z + 3 : y + z + 1; }; if (check_image(result, {func})) { return -1; } } { Var x("x"), y("y"); Func f("f"), h("h"); h(x, y) = x + y; h.compute_root(); // This is equivalent to: // f(x, _0, _1) = {1, 1} // f(x, _0, _1) += {h(_0, _1)[0] + 2, h(_0, _1)[1] * 3} f(x, _) *= Tuple(h(_) + 2, h(_) * 3); Realization result = f.realize({100, 100, 100}); auto func1 = [](int x, int y, int z) { return y + z + 2; }; auto func2 = [](int x, int y, int z) { return (y + z) * 3; }; if (check_image(result, {func1, func2})) { return -1; } } { Var x("x"), y("y"); Func f("f"), g("g"), h("h"); h(x, y) = Tuple(x + y, x - y); h.compute_root(); g(x) = Tuple(x + 2, x - 2); g.compute_root(); // This means f(x, _0, _1) = {h(_0, _1)[0] + 3, h(_0, _1)[1] + 4} f(x, _) = Tuple(h(_)[0] + 3, h(_)[1] + 4); // This means f(x, _0, _1) += {h(_0, _1)[0]*g(_0)[0], h(_0, _1)[1]*g(_0)[1]} f(x, _) += Tuple(h(_)[0] * g(_)[0], h(_)[1] * g(_)[1]); Realization result = f.realize({100, 100, 100}); auto func1 = [](int x, int y, int z) { return (y + z + 3) + (y + z) * (y + 2); }; auto func2 = [](int x, int y, int z) { return (y - z + 4) + (y - z) * (y - 2); }; if (check_image(result, {func1, func2})) { return -1; } } { Var x("x"), y("y"); Func f("f"), g("g"), h("h"); h(x, y) = Tuple(x + y, x - y); h.compute_root(); g(x) = Tuple(x + 2, x - 2); g.compute_root(); // This is equivalent to: // f(_0, _1) = 0 // f(_0, _1) += {h(_0, _1)[0]*g(_0)[0] + 3, h(_0, _1)[1]*g(_0)[1] + 4} f(_) += Tuple(h(_)[0] * g(_)[0] + 3, h(_)[1] * g(_)[1] + 4); Realization result = f.realize({100, 100}); auto func1 = [](int x, int y, int z) { return (x + y) * (x + 2) + 3; }; auto func2 = [](int x, int y, int z) { return (x - y) * (x - 2) + 4; }; if (check_image(result, {func1, func2})) { return -1; } } printf("Success!\n"); return 0; }
4,180
302
#include "engineresourcefixedinteger.h" #include "integerresourcehandler.h" #include "every_cpp.h" namespace BrowserAutomationStudioFramework { EngineResourceFixedInteger::EngineResourceFixedInteger(QObject *parent) : EngineResourceAbstract(parent),Active(true) { } void EngineResourceFixedInteger::SetValue(int Value) { this->Value = Value; } IResourceHandler* EngineResourceFixedInteger::GetHandler(const QSet<QString>& refuse) { IntegerResourceHandler *handler = new IntegerResourceHandler(); if(Active) { handler->SetInteger(Value); connect(handler,SIGNAL(DieSignal()),this,SLOT(Die())); connect(handler,SIGNAL(SuccessSignal()),this,SLOT(Success())); connect(handler,SIGNAL(FailSignal()),this,SLOT(Fail())); handler->SetHandlerStatus(IResourceHandler::Ready); }else { handler->SetHandlerStatus(IResourceHandler::NotAvailable); } return handler; } QList<QScriptValue> EngineResourceFixedInteger::GetRandomSubarrayData(int size) { if(size > 0) return QList<QScriptValue>() << QScriptValue(Value); return QList<QScriptValue>(); } QScriptValue EngineResourceFixedInteger::GetAtIndex(int index) { if(index == 0) { return QScriptValue(Value); } return QScriptValue(QScriptValue::NullValue); } void EngineResourceFixedInteger::SetAtIndex(int index, const QString& val) { } int EngineResourceFixedInteger::GetTotalLength() { return 1; } QList<QScriptValue> EngineResourceFixedInteger::GetAllData() { return QList<QScriptValue>() << QScriptValue(Value); } void EngineResourceFixedInteger::Success() { } void EngineResourceFixedInteger::Fail() { } void EngineResourceFixedInteger::Die() { //Active = false; } void EngineResourceFixedInteger::Reload() { Active = true; } void EngineResourceFixedInteger::Insert(const QString& value, bool onlywrite) { } void EngineResourceFixedInteger::Sync() { } }
901
765
<reponame>hyu-iot/gem5<gh_stars>100-1000 /***************************************************************************** * McPAT * SOFTWARE LICENSE AGREEMENT * Copyright 2012 Hewlett-Packard Development Company, L.P. * Copyright (c) 2010-2013 Advanced Micro Devices, Inc. * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ***************************************************************************/ #include "common.h" #include "logic.h" //selection_logic selection_logic::selection_logic(XMLNode* _xml_data, bool _is_default, int _win_entries, int issue_width_, const InputParameter *configure_interface, string _name, double _accesses, double clockRate_, enum Device_ty device_ty_, enum Core_type core_ty_) : McPATComponent(_xml_data), is_default(_is_default), win_entries(_win_entries), issue_width(issue_width_), accesses(_accesses), device_ty(device_ty_), core_ty(core_ty_) { clockRate = clockRate_; name = _name; l_ip = *configure_interface; local_result = init_interface(&l_ip, name); } void selection_logic::computeArea() { output_data.area = local_result.area; } void selection_logic::computeEnergy() { //based on cost effective superscalar processor TR pp27-31 double Ctotal, Cor, Cpencode; int num_arbiter; double WSelORn, WSelORprequ, WSelPn, WSelPp, WSelEnn, WSelEnp; //the 0.8um process data is used. //this was 10 micron for the 0.8 micron process WSelORn = 12.5 * l_ip.F_sz_um; //this was 40 micron for the 0.8 micron process WSelORprequ = 50 * l_ip.F_sz_um; //this was 10mcron for the 0.8 micron process WSelPn = 12.5 * l_ip.F_sz_um; //this was 15 micron for the 0.8 micron process WSelPp = 18.75 * l_ip.F_sz_um; //this was 5 micron for the 0.8 micron process WSelEnn = 6.25 * l_ip.F_sz_um; //this was 10 micron for the 0.8 micron process WSelEnp = 12.5 * l_ip.F_sz_um; Ctotal = 0; num_arbiter = 1; while (win_entries > 4) { win_entries = (int)ceil((double)win_entries / 4.0); num_arbiter += win_entries; } //the 4-input OR logic to generate anyreq Cor = 4 * drain_C_(WSelORn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(WSelORprequ, PCH, 1, 1, g_tp.cell_h_def); power.readOp.gate_leakage = cmos_Ig_leakage(WSelORn, WSelORprequ, 4, nor) * g_tp.peri_global.Vdd; //The total capacity of the 4-bit priority encoder Cpencode = drain_C_(WSelPn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(WSelPp, PCH, 1, 1, g_tp.cell_h_def) + 2 * drain_C_(WSelPn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(WSelPp, PCH, 2, 1, g_tp.cell_h_def) + 3 * drain_C_(WSelPn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(WSelPp, PCH, 3, 1, g_tp.cell_h_def) + 4 * drain_C_(WSelPn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(WSelPp, PCH, 4, 1, g_tp.cell_h_def) +//precompute priority logic 2 * 4 * gate_C(WSelEnn + WSelEnp, 20.0) + 4 * drain_C_(WSelEnn, NCH, 1, 1, g_tp.cell_h_def) + 2 * 4 * drain_C_(WSelEnp, PCH, 1, 1, g_tp.cell_h_def) +//enable logic (2 * 4 + 2 * 3 + 2 * 2 + 2) * gate_C(WSelPn + WSelPp, 10.0);//requests signal Ctotal += issue_width * num_arbiter * (Cor + Cpencode); //2 means the abitration signal need to travel round trip power.readOp.dynamic = Ctotal * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd * 2; power.readOp.leakage = issue_width * num_arbiter * (cmos_Isub_leakage(WSelPn, WSelPp, 2, nor)/*approximate precompute with a nor gate*///grant1p + cmos_Isub_leakage(WSelPn, WSelPp, 3, nor)//grant2p + cmos_Isub_leakage(WSelPn, WSelPp, 4, nor)//grant3p + cmos_Isub_leakage(WSelEnn, WSelEnp, 2, nor)*4//enable logic + cmos_Isub_leakage(WSelEnn, WSelEnp, 1, inv)*2*3//for each grant there are two inverters, there are 3 grant sIsubnals ) * g_tp.peri_global.Vdd; power.readOp.gate_leakage = issue_width * num_arbiter * (cmos_Ig_leakage(WSelPn, WSelPp, 2, nor)/*approximate precompute with a nor gate*///grant1p + cmos_Ig_leakage(WSelPn, WSelPp, 3, nor)//grant2p + cmos_Ig_leakage(WSelPn, WSelPp, 4, nor)//grant3p + cmos_Ig_leakage(WSelEnn, WSelEnp, 2, nor)*4//enable logic + cmos_Ig_leakage(WSelEnn, WSelEnp, 1, inv)*2*3//for each grant there are two inverters, there are 3 grant signals ) * g_tp.peri_global.Vdd; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty, core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; output_data.peak_dynamic_power = power.readOp.dynamic * clockRate; output_data.subthreshold_leakage_power = power.readOp.leakage; output_data.gate_leakage_power = power.readOp.gate_leakage; output_data.runtime_dynamic_energy = power.readOp.dynamic * accesses; } dep_resource_conflict_check::dep_resource_conflict_check( XMLNode* _xml_data, const string _name, const InputParameter *configure_interface, const CoreParameters & dyn_p_, int compare_bits_, double clockRate_, bool _is_default) : McPATComponent(_xml_data), l_ip(*configure_interface), coredynp(dyn_p_), compare_bits(compare_bits_), is_default(_is_default) { name = _name; clockRate = clockRate_; //this was 20.0 micron for the 0.8 micron process Wcompn = 25 * l_ip.F_sz_um; //this was 20.0 micron for the 0.8 micron process Wevalinvp = 25 * l_ip.F_sz_um; //this was 80.0 mcron for the 0.8 micron process Wevalinvn = 100 * l_ip.F_sz_um; //this was 40.0 micron for the 0.8 micron process Wcomppreequ = 50 * l_ip.F_sz_um; //this was 5.4 micron for the 0.8 micron process WNORn = 6.75 * l_ip.F_sz_um; //this was 30.5 micron for the 0.8 micron process WNORp = 38.125 * l_ip.F_sz_um; // To make CACTI happy. l_ip.cache_sz = MIN_BUFFER_SIZE; local_result = init_interface(&l_ip, name); if (coredynp.core_ty == Inorder) //TODO: opcode bits + log(shared resources) + REG TAG BITS --> //opcode comparator compare_bits += 16 + 8 + 8; else compare_bits += 16 + 8 + 8; conflict_check_power(); double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; } void dep_resource_conflict_check::conflict_check_power() { double Ctotal; int num_comparators; //2(N*N-N) is used for source to dest comparison, (N*N-N) is used for //dest to dest comparision. num_comparators = 3 * ((coredynp.decodeW) * (coredynp.decodeW) - coredynp.decodeW); Ctotal = num_comparators * compare_cap(); power.readOp.dynamic = Ctotal * /*CLOCKRATE*/ g_tp.peri_global.Vdd * g_tp.peri_global.Vdd /*AF*/; power.readOp.leakage = num_comparators * compare_bits * 2 * simplified_nmos_leakage(Wcompn, false); double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; power.readOp.gate_leakage = num_comparators * compare_bits * 2 * cmos_Ig_leakage(Wcompn, 0, 2, nmos); } /* estimate comparator power consumption (this comparator is similar to the tag-match structure in a CAM */ double dep_resource_conflict_check::compare_cap() { double c1, c2; //resize the big NOR gate at the DCL according to fan in. WNORp = WNORp * compare_bits / 2.0; /* bottom part of comparator */ c2 = (compare_bits) * (drain_C_(Wcompn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(Wcompn, NCH, 2, 1, g_tp.cell_h_def)) + drain_C_(Wevalinvp, PCH, 1, 1, g_tp.cell_h_def) + drain_C_(Wevalinvn, NCH, 1, 1, g_tp.cell_h_def); /* top part of comparator */ c1 = (compare_bits) * (drain_C_(Wcompn, NCH, 1, 1, g_tp.cell_h_def) + drain_C_(Wcompn, NCH, 2, 1, g_tp.cell_h_def) + drain_C_(Wcomppreequ, NCH, 1, 1, g_tp.cell_h_def)) + gate_C(WNORn + WNORp, 10.0) + drain_C_(WNORp, NCH, 2, 1, g_tp.cell_h_def) + compare_bits * drain_C_(WNORn, NCH, 2, 1, g_tp.cell_h_def); return(c1 + c2); } void dep_resource_conflict_check::leakage_feedback(double temperature) { l_ip.temp = (unsigned int)round(temperature/10.0)*10; uca_org_t init_result = init_interface(&l_ip, name); // init_result is dummy // This is part of conflict_check_power() // 2(N*N-N) is used for source to dest comparison, (N*N-N) is used for dest // to dest comparison. int num_comparators = 3 * ((coredynp.decodeW) * (coredynp.decodeW) - coredynp.decodeW); power.readOp.leakage = num_comparators * compare_bits * 2 * simplified_nmos_leakage(Wcompn, false); double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; power.readOp.gate_leakage = num_comparators * compare_bits * 2 * cmos_Ig_leakage(Wcompn, 0, 2, nmos); } DFFCell::DFFCell( bool _is_dram, double _WdecNANDn, double _WdecNANDp, double _cell_load, const InputParameter *configure_interface) : is_dram(_is_dram), cell_load(_cell_load), WdecNANDn(_WdecNANDn), WdecNANDp(_WdecNANDp) { //this model is based on the NAND2 based DFF. l_ip = *configure_interface; area.set_area(5 * compute_gate_area(NAND, 2,WdecNANDn,WdecNANDp, g_tp.cell_h_def) + compute_gate_area(NAND, 2,WdecNANDn,WdecNANDn, g_tp.cell_h_def)); } double DFFCell::fpfp_node_cap(unsigned int fan_in, unsigned int fan_out) { double Ctotal = 0; /* part 1: drain cap of NAND gate */ Ctotal += drain_C_(WdecNANDn, NCH, 2, 1, g_tp.cell_h_def, is_dram) + fan_in * drain_C_(WdecNANDp, PCH, 1, 1, g_tp.cell_h_def, is_dram); /* part 2: gate cap of NAND gates */ Ctotal += fan_out * gate_C(WdecNANDn + WdecNANDp, 0, is_dram); return Ctotal; } void DFFCell::compute_DFF_cell() { double c1, c2, c3, c4, c5, c6; /* node 5 and node 6 are identical to node 1 in capacitance */ c1 = c5 = c6 = fpfp_node_cap(2, 1); c2 = fpfp_node_cap(2, 3); c3 = fpfp_node_cap(3, 2); c4 = fpfp_node_cap(2, 2); //cap-load of the clock signal in each Dff, actually the clock signal only connected to one NAND2 clock_cap = 2 * gate_C(WdecNANDn + WdecNANDp, 0, is_dram); e_switch.readOp.dynamic += (c4 + c1 + c2 + c3 + c5 + c6 + 2 * cell_load) * 0.5 * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd;; /* no 1/2 for e_keep and e_clock because clock signal switches twice in one cycle */ e_keep_1.readOp.dynamic += c3 * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd ; e_keep_0.readOp.dynamic += c2 * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd ; e_clock.readOp.dynamic += clock_cap * g_tp.peri_global.Vdd * g_tp.peri_global.Vdd;; /* static power */ e_switch.readOp.leakage += (cmos_Isub_leakage(WdecNANDn, WdecNANDp, 2, nand) * 5//5 NAND2 and 1 NAND3 in a DFF + cmos_Isub_leakage(WdecNANDn, WdecNANDn, 3, nand)) * g_tp.peri_global.Vdd; e_switch.readOp.gate_leakage += (cmos_Ig_leakage(WdecNANDn, WdecNANDp, 2, nand) * 5//5 NAND2 and 1 NAND3 in a DFF + cmos_Ig_leakage(WdecNANDn, WdecNANDn, 3, nand)) * g_tp.peri_global.Vdd; } Pipeline::Pipeline(XMLNode* _xml_data, const InputParameter *configure_interface, const CoreParameters & dyn_p_, enum Device_ty device_ty_, bool _is_core_pipeline, bool _is_default) : McPATComponent(_xml_data), l_ip(*configure_interface), coredynp(dyn_p_), device_ty(device_ty_), is_core_pipeline(_is_core_pipeline), is_default(_is_default), num_piperegs(0.0) { name = "Pipeline?"; local_result = init_interface(&l_ip, name); if (!coredynp.Embedded) { process_ind = true; } else { process_ind = false; } //this was 20 micron for the 0.8 micron process WNANDn = (process_ind) ? 25 * l_ip.F_sz_um : g_tp.min_w_nmos_ ; //this was 30 micron for the 0.8 micron process WNANDp = (process_ind) ? 37.5 * l_ip.F_sz_um : g_tp.min_w_nmos_ * pmos_to_nmos_sz_ratio(); load_per_pipeline_stage = 2 * gate_C(WNANDn + WNANDp, 0, false); compute(); } void Pipeline::compute() { compute_stage_vector(); DFFCell pipe_reg(false, WNANDn, WNANDp, load_per_pipeline_stage, &l_ip); pipe_reg.compute_DFF_cell(); double clock_power_pipereg = num_piperegs * pipe_reg.e_clock.readOp.dynamic; //******************pipeline power: currently, we average all the possibilities of the states of DFFs in the pipeline. A better way to do it is to consider //the harming distance of two consecutive signals, However McPAT does not have plan to do this in near future as it focuses on worst case power. double pipe_reg_power = num_piperegs * (pipe_reg.e_switch.readOp.dynamic + pipe_reg.e_keep_0.readOp.dynamic + pipe_reg.e_keep_1.readOp.dynamic) / 3 + clock_power_pipereg; double pipe_reg_leakage = num_piperegs * pipe_reg.e_switch.readOp.leakage; double pipe_reg_gate_leakage = num_piperegs * pipe_reg.e_switch.readOp.gate_leakage; power.readOp.dynamic += pipe_reg_power; power.readOp.leakage += pipe_reg_leakage; power.readOp.gate_leakage += pipe_reg_gate_leakage; area.set_area(num_piperegs * pipe_reg.area.get_area()); double long_channel_device_reduction = longer_channel_device_reduction(device_ty, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double macro_layout_overhead = g_tp.macro_layout_overhead; if (!coredynp.Embedded) area.set_area(area.get_area() * macro_layout_overhead); output_data.area = area.get_area() / 1e6; output_data.peak_dynamic_power = power.readOp.dynamic * clockRate; output_data.subthreshold_leakage_power = power.readOp.leakage; output_data.gate_leakage_power = power.readOp.gate_leakage; output_data.runtime_dynamic_energy = power.readOp.dynamic * total_cycles; } void Pipeline::compute_stage_vector() { double num_stages, tot_stage_vector, per_stage_vector; int opcode_length = coredynp.x86 ? coredynp.micro_opcode_length : coredynp.opcode_width; if (!is_core_pipeline) { //The number of pipeline stages are calculated based on the achievable //throughput and required throughput num_piperegs = l_ip.pipeline_stages * l_ip.per_stage_vector; } else { if (coredynp.core_ty == Inorder) { /* assume 6 pipe stages and try to estimate bits per pipe stage */ /* pipe stage 0/IF */ num_piperegs += coredynp.pc_width * 2 * coredynp.num_hthreads; /* pipe stage IF/ID */ num_piperegs += coredynp.fetchW * (coredynp.instruction_length + coredynp.pc_width) * coredynp.num_hthreads; /* pipe stage IF/ThreadSEL */ if (coredynp.multithreaded) { num_piperegs += coredynp.num_hthreads * coredynp.perThreadState; //8 bit thread states } /* pipe stage ID/EXE */ num_piperegs += coredynp.decodeW * (coredynp.instruction_length + coredynp.pc_width + pow(2.0, opcode_length) + 2 * coredynp.int_data_width) * coredynp.num_hthreads; /* pipe stage EXE/MEM */ num_piperegs += coredynp.issueW * (3 * coredynp.arch_ireg_width + pow(2.0, opcode_length) + 8 * 2 * coredynp.int_data_width/*+2*powers (2,reg_length)*/); /* pipe stage MEM/WB the 2^opcode_length means the total decoded signal for the opcode*/ num_piperegs += coredynp.issueW * (2 * coredynp.int_data_width + pow(2.0, opcode_length) + 8 * 2 * coredynp.int_data_width/*+2*powers (2,reg_length)*/); num_stages = 6; } else { /* assume 12 stage pipe stages and try to estimate bits per pipe stage */ /*OOO: Fetch, decode, rename, IssueQ, dispatch, regread, EXE, MEM, WB, CM */ /* pipe stage 0/1F*/ num_piperegs += coredynp.pc_width * 2 * coredynp.num_hthreads ;//PC and Next PC /* pipe stage IF/ID */ num_piperegs += coredynp.fetchW * (coredynp.instruction_length + coredynp.pc_width) * coredynp.num_hthreads;//PC is used to feed branch predictor in ID /* pipe stage 1D/Renaming*/ num_piperegs += coredynp.decodeW * (coredynp.instruction_length + coredynp.pc_width) * coredynp.num_hthreads;//PC is for branch exe in later stage. /* pipe stage Renaming/wire_drive */ num_piperegs += coredynp.decodeW * (coredynp.instruction_length + coredynp.pc_width); /* pipe stage Renaming/IssueQ */ //3*coredynp.phy_ireg_width means 2 sources and 1 dest num_piperegs += coredynp.issueW * (coredynp.instruction_length + coredynp.pc_width + 3 * coredynp.phy_ireg_width) * coredynp.num_hthreads; /* pipe stage IssueQ/Dispatch */ num_piperegs += coredynp.issueW * (coredynp.instruction_length + 3 * coredynp.phy_ireg_width); /* pipe stage Dispatch/EXE */ num_piperegs += coredynp.issueW * (3 * coredynp.phy_ireg_width + coredynp.pc_width + pow(2.0, opcode_length)/*+2*powers (2,reg_length)*/); /* 2^opcode_length means the total decoded signal for the opcode*/ num_piperegs += coredynp.issueW * (2 * coredynp.int_data_width + pow(2.0, opcode_length) /*+2*powers (2,reg_length)*/); /*2 source operands in EXE; Assume 2EXE stages* since we do not really distinguish OP*/ num_piperegs += coredynp.issueW * (2 * coredynp.int_data_width + pow(2.0, opcode_length) /*+2*powers (2,reg_length)*/); /* pipe stage EXE/MEM, data need to be read/write, address*/ //memory Opcode still need to be passed num_piperegs += coredynp.issueW * (coredynp.int_data_width + coredynp.v_address_width + pow(2.0, opcode_length)/*+2*powers (2,reg_length)*/); /* pipe stage MEM/WB; result data, writeback regs */ num_piperegs += coredynp.issueW * (coredynp.int_data_width + coredynp.phy_ireg_width /* powers (2,opcode_length) + (2,opcode_length)+2*powers (2,reg_length)*/); /* pipe stage WB/CM ; result data, regs need to be updated, address for resolve memory ops in ROB's top*/ num_piperegs += coredynp.commitW * (coredynp.int_data_width + coredynp.v_address_width + coredynp.phy_ireg_width /*+ powers (2,opcode_length)*2*powers (2,reg_length)*/) * coredynp.num_hthreads; num_stages = 12; } /* assume 50% extra in control registers and interrupt registers (rule of thumb) */ num_piperegs = num_piperegs * 1.5; tot_stage_vector = num_piperegs; per_stage_vector = tot_stage_vector / num_stages; if (coredynp.core_ty == Inorder) { if (coredynp.pipeline_stages > 6) num_piperegs = per_stage_vector * coredynp.pipeline_stages; } else { //OOO if (coredynp.pipeline_stages > 12) num_piperegs = per_stage_vector * coredynp.pipeline_stages; } } } FunctionalUnit::FunctionalUnit(XMLNode* _xml_data, InputParameter* interface_ip_, const CoreParameters & _core_params, const CoreStatistics & _core_stats, enum FU_type fu_type_) : McPATComponent(_xml_data), interface_ip(*interface_ip_), core_params(_core_params), core_stats(_core_stats), fu_type(fu_type_) { double area_t; double leakage; double gate_leakage; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); clockRate = core_params.clockRate; uca_org_t result2; // Temp name for the following function call name = "Functional Unit"; result2 = init_interface(&interface_ip, name); if (core_params.Embedded) { if (fu_type == FPU) { num_fu=core_params.num_fpus; //area_t = 8.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 area_t = 4.47*1e6*(g_ip->F_sz_nm*g_ip->F_sz_nm/90.0/90.0);//this is um^2 The base number //4.47 contains both VFP and NEON processing unit, VFP is about 40% and NEON is about 60% if (g_ip->F_sz_nm>90) area_t = 4.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W //energy = 0.3529/10*1e-9;//this is the energy(nJ) for a FP instruction in FPU usually it can have up to 20 cycles. // base_energy = coredynp.core_ty==Inorder? 0: 89e-3*3; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per Hz energy(nJ) //FPU power from Sandia's processor sizing tech report FU_height=(18667*num_fu)*interface_ip.F_sz_um;//FPU from Sun's data } else if (fu_type == ALU) { num_fu=core_params.num_alus; area_t = 280*260*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; // base_energy = coredynp.core_ty==Inorder? 0:89e-3; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15/3/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ) FU_height=(6222*num_fu)*interface_ip.F_sz_um;//integer ALU } else if (fu_type == MUL) { num_fu=core_params.num_muls; area_t = 280*260*3*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; // base_energy = coredynp.core_ty==Inorder? 0:89e-3*2; //W The base energy of ALU average numbers from Intel 4G and 773Mhz (Wattch) // base_energy *=(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2); base_energy = 0; per_access_energy = 1.15*2/3/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ), coefficient based on Wattch FU_height=(9334*num_fu )*interface_ip.F_sz_um;//divider/mul from Sun's data } else { cout<<"Unknown Functional Unit Type"<<endl; exit(0); } per_access_energy *=0.5;//According to ARM data embedded processor has much lower per acc energy } else { if (fu_type == FPU) { name = "Floating Point Unit(s)"; num_fu = core_params.num_fpus; area_t = 8.47 * 1e6 * (g_ip->F_sz_nm * g_ip->F_sz_nm / 90.0 / 90.0);//this is um^2 if (g_ip->F_sz_nm > 90) area_t = 8.47 * 1e6 * g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W //W The base energy of ALU average numbers from Intel 4G and //773Mhz (Wattch) base_energy = core_params.core_ty == Inorder ? 0 : 89e-3 * 3; base_energy *= (g_tp.peri_global.Vdd * g_tp.peri_global.Vdd / 1.2 / 1.2); per_access_energy = 1.15*3/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per op energy(nJ) FU_height=(38667*num_fu)*interface_ip.F_sz_um;//FPU from Sun's data } else if (fu_type == ALU) { name = "Integer ALU(s)"; num_fu = core_params.num_alus; //this is um^2 ALU + MUl area_t = 280 * 260 * 2 * g_tp.scaling_factor.logic_scaling_co_eff; leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; //W The base energy of ALU average numbers from Intel 4G and 773Mhz //(Wattch) base_energy = core_params.core_ty == Inorder ? 0 : 89e-3; base_energy *= (g_tp.peri_global.Vdd * g_tp.peri_global.Vdd / 1.2 / 1.2); per_access_energy = 1.15/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ) FU_height=(6222*num_fu)*interface_ip.F_sz_um;//integer ALU } else if (fu_type == MUL) { name = "Multiply/Divide Unit(s)"; num_fu = core_params.num_muls; //this is um^2 ALU + MUl area_t = 280 * 260 * 2 * 3 * g_tp.scaling_factor.logic_scaling_co_eff; leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; //W The base energy of ALU average numbers from Intel 4G and 773Mhz //(Wattch) base_energy = core_params.core_ty == Inorder ? 0 : 89e-3 * 2; base_energy *= (g_tp.peri_global.Vdd * g_tp.peri_global.Vdd / 1.2 / 1.2); per_access_energy = 1.15*2/1e9/4/1.3/1.3*g_tp.peri_global.Vdd*g_tp.peri_global.Vdd*(g_ip->F_sz_nm/90.0);//(g_tp.peri_global.Vdd*g_tp.peri_global.Vdd/1.2/1.2);//0.00649*1e-9; //This is per cycle energy(nJ), coefficient based on Wattch FU_height=(9334*num_fu )*interface_ip.F_sz_um;//divider/mul from Sun's data } else { cout << "Unknown Functional Unit Type" << endl; exit(0); } } area.set_area(area_t*num_fu); power.readOp.leakage = leakage * num_fu; power.readOp.gate_leakage = gate_leakage * num_fu; double long_channel_device_reduction = longer_channel_device_reduction(Core_device, core_params.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; double macro_layout_overhead = g_tp.macro_layout_overhead; area.set_area(area.get_area()*macro_layout_overhead); } void FunctionalUnit::computeEnergy() { double pppm_t[4] = {1, 1, 1, 1}; double FU_duty_cycle; double sckRation = g_tp.sckt_co_eff; // TDP power calculation //2 means two source operands needs to be passed for each int instruction. set_pppm(pppm_t, 2, 2, 2, 2); tdp_stats.readAc.access = num_fu; if (fu_type == FPU) { FU_duty_cycle = core_stats.FPU_duty_cycle; } else if (fu_type == ALU) { FU_duty_cycle = core_stats.ALU_duty_cycle; } else if (fu_type == MUL) { FU_duty_cycle = core_stats.MUL_duty_cycle; } power.readOp.dynamic = per_access_energy * tdp_stats.readAc.access + base_energy / clockRate; power.readOp.dynamic *= sckRation * FU_duty_cycle; // Runtime power calculation if (fu_type == FPU) { rtp_stats.readAc.access = core_stats.fpu_accesses; } else if (fu_type == ALU) { rtp_stats.readAc.access = core_stats.ialu_accesses; } else if (fu_type == MUL) { rtp_stats.readAc.access = core_stats.mul_accesses; } rt_power.readOp.dynamic = per_access_energy * rtp_stats.readAc.access + base_energy * execution_time; rt_power.readOp.dynamic *= sckRation; output_data.area = area.get_area() / 1e6; output_data.peak_dynamic_power = power.readOp.dynamic * clockRate; output_data.subthreshold_leakage_power = (longer_channel_device) ? power.readOp.longer_channel_leakage : power.readOp.leakage; output_data.gate_leakage_power = power.readOp.gate_leakage; output_data.runtime_dynamic_energy = rt_power.readOp.dynamic; } void FunctionalUnit::leakage_feedback(double temperature) { // Update the temperature and initialize the global interfaces. interface_ip.temp = (unsigned int)round(temperature/10.0)*10; // init_result is dummy uca_org_t init_result = init_interface(&interface_ip, name); // This is part of FunctionalUnit() double area_t, leakage, gate_leakage; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); if (fu_type == FPU) { area_t = 4.47*1e6*(g_ip->F_sz_nm*g_ip->F_sz_nm/90.0/90.0);//this is um^2 The base number if (g_ip->F_sz_nm>90) area_t = 4.47*1e6*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W } else if (fu_type == ALU) { area_t = 280*260*2*num_fu*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; } else if (fu_type == MUL) { area_t = 280*260*2*3*num_fu*g_tp.scaling_factor.logic_scaling_co_eff;//this is um^2 ALU + MUl leakage = area_t *(g_tp.scaling_factor.core_tx_density)*cmos_Isub_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2;//unit W gate_leakage = area_t*(g_tp.scaling_factor.core_tx_density)*cmos_Ig_leakage(20*g_tp.min_w_nmos_, 20*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd/2; } else { cout<<"Unknown Functional Unit Type"<<endl; exit(1); } power.readOp.leakage = leakage*num_fu; power.readOp.gate_leakage = gate_leakage*num_fu; power.readOp.longer_channel_leakage = longer_channel_device_reduction(Core_device, core_params.core_ty); } UndiffCore::UndiffCore(XMLNode* _xml_data, InputParameter* interface_ip_, const CoreParameters & dyn_p_, bool exist_) : McPATComponent(_xml_data), interface_ip(*interface_ip_), coredynp(dyn_p_), core_ty(coredynp.core_ty), embedded(coredynp.Embedded), pipeline_stage(coredynp.pipeline_stages), num_hthreads(coredynp.num_hthreads), issue_width(coredynp.issueW), exist(exist_) { if (!exist) return; name = "Undifferentiated Core"; clockRate = coredynp.clockRate; double undifferentiated_core = 0; double core_tx_density = 0; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); double undifferentiated_core_coe; uca_org_t result2; result2 = init_interface(&interface_ip, name); //Compute undifferentiated core area at 90nm. if (embedded == false) { //Based on the results of polynomial/log curve fitting based on undifferentiated core of Niagara, Niagara2, Merom, Penyrn, Prescott, Opteron die measurements if (core_ty == OOO) { undifferentiated_core = (3.57 * log(pipeline_stage) - 1.2643) > 0 ? (3.57 * log(pipeline_stage) - 1.2643) : 0; } else if (core_ty == Inorder) { undifferentiated_core = (-2.19 * log(pipeline_stage) + 6.55) > 0 ? (-2.19 * log(pipeline_stage) + 6.55) : 0; } else { cout << "invalid core type" << endl; exit(0); } undifferentiated_core *= (1 + logtwo(num_hthreads) * 0.0716); } else { //Based on the results in paper "parametrized processor models" Sandia Labs if (opt_for_clk) undifferentiated_core_coe = 0.05; else undifferentiated_core_coe = 0; undifferentiated_core = (0.4109 * pipeline_stage - 0.776) * undifferentiated_core_coe; undifferentiated_core *= (1 + logtwo(num_hthreads) * 0.0426); } undifferentiated_core *= g_tp.scaling_factor.logic_scaling_co_eff * 1e6;//change from mm^2 to um^2 core_tx_density = g_tp.scaling_factor.core_tx_density; power.readOp.leakage = undifferentiated_core*(core_tx_density)*cmos_Isub_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd;//unit W power.readOp.gate_leakage = undifferentiated_core*(core_tx_density)*cmos_Ig_leakage(5*g_tp.min_w_nmos_, 5*g_tp.min_w_nmos_*pmos_to_nmos_sizing_r, 1, inv)*g_tp.peri_global.Vdd; double long_channel_device_reduction = longer_channel_device_reduction(Core_device, coredynp.core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; area.set_area(undifferentiated_core); scktRatio = g_tp.sckt_co_eff; power.readOp.dynamic *= scktRatio; power.writeOp.dynamic *= scktRatio; power.searchOp.dynamic *= scktRatio; macro_PR_overhead = g_tp.macro_layout_overhead; area.set_area(area.get_area()*macro_PR_overhead); output_data.area = area.get_area() / 1e6; output_data.peak_dynamic_power = power.readOp.dynamic * clockRate; output_data.subthreshold_leakage_power = longer_channel_device ? power.readOp.longer_channel_leakage : power.readOp.leakage; output_data.gate_leakage_power = power.readOp.gate_leakage; } InstructionDecoder::InstructionDecoder(XMLNode* _xml_data, const string _name, bool _is_default, const InputParameter *configure_interface, int opcode_length_, int num_decoders_, bool x86_, double clockRate_, enum Device_ty device_ty_, enum Core_type core_ty_) : McPATComponent(_xml_data), is_default(_is_default), opcode_length(opcode_length_), num_decoders(num_decoders_), x86(x86_), device_ty(device_ty_), core_ty(core_ty_) { /* * Instruction decoder is different from n to 2^n decoders * that are commonly used in row decoders in memory arrays. * The RISC instruction decoder is typically a very simple device. * We can decode an instruction by simply * separating the machine word into small parts using wire slices * The RISC instruction decoder can be approximate by the n to 2^n decoders, * although this approximation usually underestimate power since each decoded * instruction normally has more than 1 active signal. * * However, decoding a CISC instruction word is much more difficult * than the RISC case. A CISC decoder is typically set up as a state machine. * The machine reads the opcode field to determine * what type of instruction it is, * and where the other data values are. * The instruction word is read in piece by piece, * and decisions are made at each stage as to * how the remainder of the instruction word will be read. * (sequencer and ROM are usually needed) * An x86 decoder can be even more complex since * it involve both decoding instructions into u-ops and * merge u-ops when doing micro-ops fusion. */ name = _name; clockRate = clockRate_; bool is_dram = false; double pmos_to_nmos_sizing_r; double load_nmos_width, load_pmos_width; double C_driver_load, R_wire_load; Area cell; l_ip = *configure_interface; local_result = init_interface(&l_ip, name); cell.h = g_tp.cell_h_def; cell.w = g_tp.cell_h_def; num_decoder_segments = (int)ceil(opcode_length / 18.0); if (opcode_length > 18) opcode_length = 18; num_decoded_signals = (int)pow(2.0, opcode_length); pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); load_nmos_width = g_tp.max_w_nmos_ / 2; load_pmos_width = g_tp.max_w_nmos_ * pmos_to_nmos_sizing_r; C_driver_load = 1024 * gate_C(load_nmos_width + load_pmos_width, 0, is_dram); R_wire_load = 3000 * l_ip.F_sz_um * g_tp.wire_outside_mat.R_per_um; final_dec = new Decoder( num_decoded_signals, false, C_driver_load, R_wire_load, false/*is_fa*/, false/*is_dram*/, false/*wl_tr*/, //to use peri device cell); PredecBlk * predec_blk1 = new PredecBlk( num_decoded_signals, final_dec, 0,//Assuming predec and dec are back to back 0, 1,//Each Predec only drives one final dec false/*is_dram*/, true); PredecBlk * predec_blk2 = new PredecBlk( num_decoded_signals, final_dec, 0,//Assuming predec and dec are back to back 0, 1,//Each Predec only drives one final dec false/*is_dram*/, false); PredecBlkDrv * predec_blk_drv1 = new PredecBlkDrv(0, predec_blk1, false); PredecBlkDrv * predec_blk_drv2 = new PredecBlkDrv(0, predec_blk2, false); pre_dec = new Predec(predec_blk_drv1, predec_blk_drv2); double area_decoder = final_dec->area.get_area() * num_decoded_signals * num_decoder_segments * num_decoders; //double w_decoder = area_decoder / area.get_h(); double area_pre_dec = (predec_blk_drv1->area.get_area() + predec_blk_drv2->area.get_area() + predec_blk1->area.get_area() + predec_blk2->area.get_area()) * num_decoder_segments * num_decoders; area.set_area(area.get_area() + area_decoder + area_pre_dec); double macro_layout_overhead = g_tp.macro_layout_overhead; double chip_PR_overhead = g_tp.chip_layout_overhead; area.set_area(area.get_area()*macro_layout_overhead*chip_PR_overhead); inst_decoder_delay_power(); double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty, core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage * long_channel_device_reduction; output_data.area = area.get_area() / 1e6; output_data.peak_dynamic_power = power.readOp.dynamic * clockRate; output_data.subthreshold_leakage_power = power.readOp.leakage; output_data.gate_leakage_power = power.readOp.gate_leakage; } void InstructionDecoder::inst_decoder_delay_power() { double dec_outrisetime; double inrisetime = 0, outrisetime; double pppm_t[4] = {1, 1, 1, 1}; double squencer_passes = x86 ? 2 : 1; outrisetime = pre_dec->compute_delays(inrisetime); dec_outrisetime = final_dec->compute_delays(outrisetime); set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments, squencer_passes*num_decoder_segments, num_decoder_segments); power = power + pre_dec->power * pppm_t; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments*num_decoded_signals, num_decoder_segments*num_decoded_signals, squencer_passes*num_decoder_segments); power = power + final_dec->power * pppm_t; } void InstructionDecoder::leakage_feedback(double temperature) { l_ip.temp = (unsigned int)round(temperature/10.0)*10; uca_org_t init_result = init_interface(&l_ip, name); // init_result is dummy final_dec->leakage_feedback(temperature); pre_dec->leakage_feedback(temperature); double pppm_t[4] = {1,1,1,1}; double squencer_passes = x86?2:1; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments, squencer_passes*num_decoder_segments, num_decoder_segments); power = pre_dec->power*pppm_t; set_pppm(pppm_t, squencer_passes*num_decoder_segments, num_decoder_segments*num_decoded_signals,num_decoder_segments*num_decoded_signals, squencer_passes*num_decoder_segments); power = power + final_dec->power*pppm_t; double sckRation = g_tp.sckt_co_eff; power.readOp.dynamic *= sckRation; power.writeOp.dynamic *= sckRation; power.searchOp.dynamic *= sckRation; double long_channel_device_reduction = longer_channel_device_reduction(device_ty,core_ty); power.readOp.longer_channel_leakage = power.readOp.leakage*long_channel_device_reduction; } InstructionDecoder::~InstructionDecoder() { local_result.cleanup(); delete final_dec; delete pre_dec->blk1; delete pre_dec->blk2; delete pre_dec->drv1; delete pre_dec->drv2; delete pre_dec; }
22,632
477
#!/usr/bin/env python """Test plotting of various GoSubDag options.""" __copyright__ = "Copyright (C) 2016-2017, <NAME>, <NAME>. All rights reserved." __author__ = "<NAME>" import os import sys from goatools.base import get_godag from goatools.base import dnld_gaf from goatools.associations import read_gaf from goatools.semantic import TermCounts from goatools.gosubdag.gosubdag import GoSubDag from goatools.gosubdag.plot.gosubdag_plot import GoSubDagPlot REPO = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../") # TBD MOVE TO GOATOOLS TEST PKG class Run(object): """Objects for running plotting test.""" def __init__(self, obo, gaf, prt): self.prt = prt self.cwd = os.getcwd() # Gene Ontologies self.go2obj_all = get_godag(os.path.join(REPO, "../goatools/", obo)) # Annotations #_file_gaf = dnld_gaf(os.path.join(REPO, gaf)) _file_gaf = dnld_gaf(gaf) print("GAF: {GAF}\n".format(GAF=_file_gaf)) self.gene2gos = read_gaf(_file_gaf) self.tcntobj = TermCounts(self.go2obj_all, self.gene2gos) # GoSubDag self.gosubdag_all = GoSubDag(None, self.go2obj_all, tcntobj=self.tcntobj, prt=prt) self.prtfmt = self.gosubdag_all.prt_attr['fmta'] def prt_goids_all(self, prt): """Print all GO IDs, including alternate GO IDs, in GODag.""" self.gosubdag_all.prt_goids(prtfmt=self.prtfmt, prt=prt) def plt_goids(self, fout_img, go_sources): """Plot GO IDs.""" # % src/bin/go_plot.py GOs --obo=../goatools/data/i86.obo --outfile=t00.jpg --mark_alt_id gosubdag = GoSubDag(go_sources, self.gosubdag_all.go2obj, prt=self.prt, # rcntobj=False, rcntobj=self.gosubdag_all.rcntobj, go2nt=self.gosubdag_all.go2nt) prtfmt = gosubdag.prt_attr['fmta'] goids_plt = GoSubDagPlot(gosubdag).get_goids_plt() self.prt.write("\n{N} GO IDs\n".format(N=len(goids_plt))) gosubdag.prt_goids(goids_plt, prtfmt=prtfmt, prt=self.prt) objplt = GoSubDagPlot(gosubdag, mark_alt_id=True) objplt.plt_dag(os.path.join(self.cwd, fout_img)) def test_plotgosubdag(prt=sys.stdout): """Test plotting of various GoSubDag options.""" objrun = Run("data/i86.obo", "goa_human", prt) # objrun.prt_goids_all(prt) go_sources = set([ 'GO:0000004', # a BP 15 L00 D00 biological_process 'GO:0008151', # a BP 10 L01 D01 B cellular process 'GO:0007516', # BP 0 L04 D05 ABC hemocyte development 'GO:0036476']) # BP 0 L06 D06 AB neuron death in response to hydrogen peroxide objrun.plt_goids("test_gosubdag_tcntobj.png", go_sources) # kws_exp = [ # ({}, {'rcntobj':rcntobj}), # ({'rcntobj':None}, {'rcntobj':None}), # ({'rcntobj':False}, {'rcntobj':None}), # ({'rcntobj':True}, {'rcntobj':rcntobj}), # ({'rcntobj':rcntobj}, {'rcntobj':rcntobj}), # # #({}, {'tcntobj':tcntobj}), # #({'tcntobj':None}, {'tcntobj':None}), # #({'tcntobj':False}, {'tcntobj':None}), # #({'tcntobj':True}, {'tcntobj':tcntobj}), # #({'tcntobj':tcntobj}, {'tcntobj':tcntobj}), # ] # for idx, (kws, expected_fields) in enumerate(kws_exp): # gosubdag = GoSubDag(go_sources, objrun.go2obj_all, prt=prt, **kws) # _chk_obj(getattr(gosubdag, 'rcntobj'), expected_fields['rcntobj'], CountRelatives) # # def _chk_obj(act_obj, exp_obj, cls): # """Check that object creation agrees with expected results.""" # if exp_obj is None: # assert act_obj is None # else: # assert isinstance(act_obj, cls) # # # def _chk_rcntobj(idx, kws, gosubdag, expected_fields): # # """Check that an rcntobj was created or not created.""" # # print idx, kws, expected_fields, gosubdag.rcntobj # # # # goids = kws['GO'] if 'GO' in kws else set(get_go2obj_unique(go2obj)) # # # print('CLI: FAST GoSubDag 0 -------------------') # # # gosubdag = GoSubDag(goids, go2obj, rcntobj=False) # # # print('CLI: RCNTOBJ({})'.format(gosubdag.rcntobj)) # # # gosubdag.prt_goids() # # # print('CLI: FAST GoSubDag 1 -------------------') # # # tcntobj = self._get_tcntobj(kws, gosubdag.go2obj) # # # print('CLI: TermCounts INITed -------------------') # # # self.gosubdag = GoSubDag(goids, go2obj, tcntobj=tcntobj) # # # # self.gosubdag.prt_goids() # # # print('CLI: FAST GoSubDag 2 -------------------') # # # objcolor = Go2Color(self.gosubdag, None) # # # objplt = GoSubDagPlot(self.gosubdag, Go2Color=objcolor, **kws) # # # fout_img = self.get_outfile(goids, **kws) # # # objplt.plt_dag(fout_img) if __name__ == '__main__': test_plotgosubdag() # Copyright (C) 2016-2017, <NAME>, <NAME>. All rights reserved.
2,543
408
{ "extends": [ "eslint:recommended", "plugin:promise/recommended", "plugin:jasmine/recommended" ], "plugins": [ "promise", "jasmine" ], "env": { "browser": false, "commonjs": true }, "parserOptions": { "ecmaVersion": 2017 }, "globals": { "Promise": "readonly" }, "rules": { "jasmine/new-line-before-expect": 0 } }
173
382
<filename>clouddriver-kubernetes/src/test/java/com/netflix/spinnaker/clouddriver/kubernetes/provider/view/KubernetesJobProviderTest.java /* * Copyright 2021 Salesforce.<EMAIL>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.clouddriver.kubernetes.provider.view; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import com.google.common.collect.ImmutableList; import com.google.common.io.Resources; import com.netflix.spinnaker.clouddriver.kubernetes.caching.view.model.KubernetesManifestContainer; import com.netflix.spinnaker.clouddriver.kubernetes.caching.view.provider.KubernetesManifestProvider; import com.netflix.spinnaker.clouddriver.kubernetes.description.manifest.KubernetesManifest; import com.netflix.spinnaker.clouddriver.kubernetes.model.KubernetesJobStatus; import com.netflix.spinnaker.clouddriver.kubernetes.security.KubernetesCredentials; import com.netflix.spinnaker.clouddriver.model.JobState; import com.netflix.spinnaker.clouddriver.security.AccountCredentials; import com.netflix.spinnaker.clouddriver.security.AccountCredentialsProvider; import io.kubernetes.client.util.Yaml; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; class KubernetesJobProviderTest { KubernetesManifestProvider mockManifestProvider; AccountCredentialsProvider credentialsProvider; AccountCredentials accountCredentials; KubernetesCredentials mockCredentials; @BeforeEach public void setup() { mockManifestProvider = mock(KubernetesManifestProvider.class); credentialsProvider = mock(AccountCredentialsProvider.class); accountCredentials = mock(AccountCredentials.class); mockCredentials = mock(KubernetesCredentials.class); doReturn(mockCredentials).when(accountCredentials).getCredentials(); doReturn(accountCredentials).when(credentialsProvider).getCredentials(anyString()); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testFailedJobWithContainerLogsAvailable(boolean detailedPodStatus) { // setup KubernetesManifest testManifest = Yaml.loadAs(getResource("base-with-completions.yml"), KubernetesManifest.class); KubernetesManifest overlay = Yaml.loadAs(getResource("failed-job.yml"), KubernetesManifest.class); testManifest.putAll(overlay); doReturn( KubernetesManifestContainer.builder() .account("mock_account") .name("a") .manifest(testManifest) .build()) .when(mockManifestProvider) .getManifest(anyString(), anyString(), anyString(), anyBoolean()); doReturn(ImmutableList.of(testManifest)).when(mockCredentials).list(any(), isNull(), any()); // when KubernetesJobProvider kubernetesJobProvider = new KubernetesJobProvider(credentialsProvider, mockManifestProvider, detailedPodStatus); KubernetesJobStatus jobStatus = kubernetesJobProvider.collectJob("mock_account", "a", "b"); // then assertNotNull(jobStatus.getJobState()); assertEquals(/* expected= */ JobState.Failed, /* actual= */ jobStatus.getJobState()); assertThat(jobStatus.getMessage()).isEqualTo("Job has reached the specified backoff limit"); assertThat(jobStatus.getReason()).isEqualTo("BackoffLimitExceeded"); if (detailedPodStatus) { assertThat(jobStatus.getPods().size()).isEqualTo(1); } else { assertThat(jobStatus.getPods()).isEmpty(); } assertThat(jobStatus.getFailureDetails()) .isEqualTo( "Pod: 'hello' had errors.\n" + " Container: 'some-container-name' exited with code: 1.\n" + " Status: Error.\n" + " Logs: Failed to download the file: foo.\n" + "GET Request failed with status code', 404, 'Expected', <HTTPStatus.OK: 200>)\n"); } @ParameterizedTest @ValueSource(booleans = {true, false}) void testFailedJobWithoutContainerLogs(boolean detailedPodStatus) { // setup KubernetesManifest testManifest = Yaml.loadAs(getResource("base-with-completions.yml"), KubernetesManifest.class); KubernetesManifest overlay = Yaml.loadAs(getResource("runjob-deadline-exceeded.yml"), KubernetesManifest.class); testManifest.putAll(overlay); doReturn( KubernetesManifestContainer.builder() .account("mock_account") .name("a") .manifest(testManifest) .build()) .when(mockManifestProvider) .getManifest(anyString(), anyString(), anyString(), anyBoolean()); doReturn(ImmutableList.of(testManifest)).when(mockCredentials).list(any(), isNull(), any()); // when KubernetesJobProvider kubernetesJobProvider = new KubernetesJobProvider(credentialsProvider, mockManifestProvider, detailedPodStatus); KubernetesJobStatus jobStatus = kubernetesJobProvider.collectJob("mock_account", "a", "b"); // then assertNotNull(jobStatus.getJobState()); assertEquals(/* expected= */ JobState.Failed, /* actual= */ jobStatus.getJobState()); assertThat(jobStatus.getMessage()).isEqualTo("Job was active longer than specified deadline"); assertThat(jobStatus.getReason()).isEqualTo("DeadlineExceeded"); assertNull(jobStatus.getFailureDetails()); } private String getResource(String name) { try { return Resources.toString( KubernetesJobProviderTest.class.getResource(name), StandardCharsets.UTF_8); } catch (IOException e) { throw new UncheckedIOException(e); } } }
2,429
2,813
package org.jabref.logic.bst; @FunctionalInterface public interface Warn { void warn(String s); }
36
2,338
//===----------------------- OrcRTBootstrap.h -------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // OrcRTPrelinkImpl provides functions that should be linked into the executor // to bootstrap common JIT functionality (e.g. memory allocation and memory // access). // // Call rt_impl::addTo to add these functions to a bootstrap symbols map. // // FIXME: The functionality in this file should probably be moved to an ORC // runtime bootstrap library in compiler-rt. // //===----------------------------------------------------------------------===// #ifndef LIB_EXECUTIONENGINE_ORC_TARGETPROCESS_ORCRTBOOTSTRAP_H #define LIB_EXECUTIONENGINE_ORC_TARGETPROCESS_ORCRTBOOTSTRAP_H #include "llvm/ADT/StringMap.h" #include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h" namespace llvm { namespace orc { namespace rt_bootstrap { void addTo(StringMap<ExecutorAddr> &M); } // namespace rt_bootstrap } // end namespace orc } // end namespace llvm #endif // LLVM_EXECUTIONENGINE_ORC_TARGETPROCESS_ORCRTBOOTSTRAP_H
394
317
<filename>ejb/cart/cart-appclient/src/main/java/javaeetutorial/cart/client/CartClient.java /** * Copyright (c) 2014 Oracle and/or its affiliates. All rights reserved. * * You may not modify, use, reproduce, or distribute this software except in * compliance with the terms of the License at: * https://github.com/javaee/tutorial-examples/LICENSE.txt */ package javaeetutorial.cart.client; import java.util.Iterator; import java.util.List; import javaeetutorial.cart.ejb.Cart; import javaeetutorial.cart.util.BookException; import javax.ejb.EJB; /** * * The client class for the CartBean example. Client adds books to the cart, * prints the contents of the cart, and then removes a book which hasn't been * added yet, causing a BookException. * @author ian */ public class CartClient { @EJB private static Cart cart; public CartClient(String[] args) { } /** * @param args the command line arguments */ public static void main(String[] args) { CartClient client = new CartClient(args); client.doTest(); } public void doTest() { try { cart.initialize("Duke d'Url", "123"); cart.addBook("Infinite Jest"); cart.addBook("Bel Canto"); cart.addBook("Kafka on the Shore"); List<String> bookList = cart.getContents(); Iterator<String> iterator = bookList.iterator(); while (iterator.hasNext()) { String title = iterator.next(); System.out.println("Retrieving book title from cart: " + title); } System.out.println("Removing \"Gravity's Rainbow\" from cart."); cart.removeBook("Gravity's Rainbow"); cart.remove(); System.exit(0); } catch (BookException ex) { System.err.println("Caught a BookException: " + ex.getMessage()); System.exit(0); } } }
774
816
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved. import ctypes as ct from ctypes import * # noqa from collections import OrderedDict class EmuStructException(Exception): """ Container class for struct exceptions """ pass class Enum(object): """ For now, a basic python object will serve as a C style enum """ pass class PtrMeta(type): """ Metaclass for pointer types """ def __mul__(self, mult): return tuple((self, mult)) class Ptr(object, metaclass=PtrMeta): """ Generic object to identify pointer variables that will be expanded according to the "ptr_size" parameter passed to our init """ _points_to_ = None class CMeta(type): """ meta class to hook __call__ and make __dict__ ordered on all versions of python """ @classmethod def __prepare__(self, name, bases): # This is default behavior for Python 3.6+ but lets do this anyway # to make sure __dict__ is ordered on older versions return OrderedDict() def __new__(self, name, bases, classdict): classdict['__ordered__'] = [k for k in classdict.keys() if k not in ('__module__', '__qualname__')] return type.__new__(self, name, bases, classdict) def __call__(cls, *args, **kwargs): obj = type.__call__(cls, *args, **kwargs) obj.create_struct() return obj def __mul__(self, mult): return tuple((self, mult)) class EmuStruct(object, metaclass=CMeta): """ Advanced Python class for interacting with C structures """ # Save the unique types we create here # This is necessary since the ctypes metaclass won't allow us # to assign structures even if the types are identical on the surface. # ctypes will test the id (address) of the type to make sure they match # upon assignment. Otherwise we will hit spurious TypeErrors. __types__ = {} class FilteredStruct(ct.Structure): def __hash__(self): return hash(repr(self)) def __init__(self, ptr_size=0, pack=0): # Set __dict__ directly here to avoid __getattribute__ loops self.__dict__['__pack__'] = pack self.__dict__['__struct__'] = None self.__dict__['__fields__'] = [] self.__dict__['__ptrsize__'] = ptr_size self.__dict__['__filtermap__'] = {} def _is_ctype(self, obj): """ Test whether the object has a ctype base """ tests = (ct._SimpleCData, ct.Structure, ct.Union, ct.Array) return any([issubclass(obj, t) for t in tests]) def create_struct(self, types={}): """ Walk each attribute and handle accordingly. Since ctypes.Structure is a metaclass, we have to build the "_fields_" dynamically via a factory """ if self.__struct__: return for d, obj in self.__dict__.items(): try: if isinstance(obj, tuple): if issubclass(obj[0], EmuStruct): _type, count = obj try: tmp = _type(self.__ptrsize__, self.__pack__) array = [_type(self.__ptrsize__, self.__pack__) for i in range(count)] except TypeError: try: tmp = _type(self.__ptrsize__) array = [_type(self.__ptrsize__) for i in range(count)] except TypeError as e: raise EmuStructException(str(e)) ctarray = tmp.__struct__.__class__ * count self.__filtermap__.update({d: array}) self.__fields__.append((d, ctarray)) elif issubclass(obj[0], Ptr): _type, count = obj ptype = self.get_ptr_field() self.__fields__.append((d, (ptype * count))) except TypeError: continue try: if self._is_ctype(obj): # Simply append ctypes since they will be handled # automatically self.__fields__.append((d, obj)) elif issubclass(obj, Ptr): # Expand pointers to the required width self.__fields__.append((d, self.get_ptr_field())) elif issubclass(obj, EmuStruct): # Allow nesting of this class which we are calling a # "filter class". That is, when fields are accessed in the # underlying ctypes struct, we pass the getattr/setattr through if obj.__name__ != self.__class__.__name__: try: filt = obj(self.__ptrsize__, self.__pack__) except TypeError: try: filt = obj(self.__ptrsize__) except TypeError as e: raise EmuStructException(str(e)) cts = filt.__struct__ self.__filtermap__.update({d: filt}) self.__fields__.append((d, cts.__class__)) except TypeError: continue self.__init_struct() def get_ptr_field(self): """ Get ctypes value for the required pointer size """ if self.__ptrsize__ == 4: return ct.c_uint32 elif self.__ptrsize__ == 8: return ct.c_uint64 else: return ct.c_void_p def get_pack(self): """ Get the required structure pack (defaults to pointer size) """ if self.__pack__: return self.__pack__ else: if self.__ptrsize__: return self.__ptrsize__ * 2 else: return 1 def _link_cstructs(self, obj): """ Link the ctypes structures together in the case of nesting. This will allow the buffer API to convert it to bytes easily """ for fname, subobj in obj.__filtermap__.items(): if isinstance(subobj, list): x = getattr(obj.__struct__, fname) for i, e in enumerate(x): self._link_cstructs(subobj[i]) x[i] = subobj[i].__struct__ elif isinstance(subobj, EmuStruct): self._link_cstructs(subobj) setattr(obj.__struct__, fname, subobj.__struct__) def get_bytes(self): """ Convert the structure to bytes and respecting endianness """ self._link_cstructs(self) struct = self.__struct__ buf = (ct.c_ubyte * ct.sizeof(struct))() ct.memmove(buf, ct.byref(struct), ct.sizeof(struct)) return bytes(buf[:]) def sizeof(self): """ Get the size of the C structure """ return ct.sizeof(self.__struct__) def _deep_cast(self, obj, bytez, offset): obj.__struct__ = type(obj.__struct__).from_buffer(bytearray(bytez[offset[0]:])) for fn, c in obj.__fields__: subobj = obj.__filtermap__.get(fn) if subobj: if isinstance(subobj, list): for sso in subobj: self._deep_cast(sso, bytez, offset) else: self._deep_cast(subobj, bytez, offset) else: offset[0] += ct.sizeof(c) def cast(self, bytez): """ Convert a bytes object to the C structure by "casting" them """ offset = [0] self._deep_cast(self, bytez, offset=offset) return self def get_cstruct(self): return self.__struct__.__class__ def get_sub_field_name(self, cstruc, offset): for (name,t) in cstruc._fields_: noff = cstruc.__dict__[name].offset nsize = cstruc.__dict__[name].size if offset == noff: return name elif noff < offset < noff + nsize: # access into the sub-structure recursively return name + '.' + self.get_sub_field_name(t, offset - noff) def get_field_name(self, offset): cstruc = self.get_cstruct() for (name,t) in self.__fields__: noff = cstruc.__dict__[name].offset nsize = cstruc.__dict__[name].size if offset == noff: return name elif noff < offset < noff + nsize: # access into the sub-structure return name + '.' + self.get_sub_field_name(t, offset - noff) return None def __struct_factory(self, name): """ Factory used to generate ctypes structures using the ctypes metaclass """ _type_name = 'ct' + name + '%d' % (self.__ptrsize__) _type = EmuStruct.__types__.get(_type_name) if not _type: _type = type(_type_name, (self.__class__.FilteredStruct, ), {"_pack_": self.get_pack(), "_fields_": self.__fields__}) EmuStruct.__types__[_type_name] = _type return _type def __init_struct(self): self.__struct__ = self.__struct_factory(self.__class__.__name__)() return self.__struct__ def __setattr__(self, name, value): """ Hook setattr so that accessing the underlying ctypes structure can be handled correctly """ struct = self.__struct__ if struct: fields = struct._fields_ for fn, val in fields: if fn == name: if type(value) == bytes: barray = getattr(struct, fn) barray[:len(value)] = value return struct.__setattr__(fn, value) return super(EmuStruct, self).__setattr__(name, value) def __getattribute__(self, name): """ Hook getattribute so that accessing the underlying ctypes structure can be handled correctly """ try: struct = super(EmuStruct, self).__getattribute__('__struct__') if struct: fields = struct._fields_ for fn, val in fields: if fn == name: val = struct.__getattribute__(name) tests = (EmuStruct.FilteredStruct, EmuUnion.FilteredStruct, ct.Array) if any([isinstance(val, t) for t in tests]): fm = super(EmuStruct, self).__getattribute__('__filtermap__') filt_obj = fm.get(name) if filt_obj: return filt_obj return struct.__getattribute__(name) except AttributeError: pass return super(EmuStruct, self).__getattribute__(name) class EmuUnion(EmuStruct, metaclass=CMeta): class FilteredStruct(ct.Union): def __hash__(self): return hash(repr(self))
5,787
2,232
/* Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: <NAME> */ #pragma once #if defined(__GNUC__) || defined(__clang__) #define LEAN_UNLIKELY(x) (__builtin_expect((x), 0)) #define LEAN_LIKELY(x) (__builtin_expect((x), 1)) #define LEAN_ALWAYS_INLINE __attribute__((always_inline)) #else #define LEAN_UNLIKELY(x) (x) #define LEAN_LIKELY(x) (x) #define LEAN_ALWAYS_INLINE #endif
181
2,505
<gh_stars>1000+ package com.java2nb.novel.mapper; import com.java2nb.novel.vo.BookReadHistoryVO; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author Administrator */ public interface FrontUserReadHistoryMapper extends UserReadHistoryMapper { List<BookReadHistoryVO> listReadHistory(@Param("userId") Long userId); }
118
352
package com.crawljax.plugins.testplugin; import java.io.File; import java.io.FileWriter; import java.util.Map; import com.crawljax.core.CrawlerContext; import com.crawljax.core.configuration.CrawljaxConfiguration; import com.crawljax.core.plugin.HostInterface; import com.crawljax.core.plugin.OnNewStatePlugin; import com.crawljax.core.plugin.PreCrawlingPlugin; import com.crawljax.core.state.StateVertex; public class TestPlugin implements OnNewStatePlugin, PreCrawlingPlugin { private HostInterface hostInterface; public TestPlugin(HostInterface hostInterface) { this.hostInterface = hostInterface; } @Override public void onNewState(CrawlerContext context, StateVertex newState) { try { String dom = context.getBrowser().getStrippedDom(); File file = new File(hostInterface.getOutputDirectory(), context.getCurrentState().getName() + ".html"); FileWriter fw = new FileWriter(file, false); fw.write(dom); fw.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void preCrawling(CrawljaxConfiguration config) throws RuntimeException { try { File file = new File(hostInterface.getOutputDirectory(), "parameters.txt"); FileWriter fw = new FileWriter(file, false); for(Map.Entry<String, String> parameter : hostInterface.getParameters().entrySet()) { fw.write(parameter.getKey() + ": " + parameter.getValue() + System.getProperty("line.separator")); } fw.close(); } catch (Exception e) { e.printStackTrace(); } } }
513
2,059
/* * Copyright 2008 Android4ME * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.spoon.internal.thirdparty.axmlparser; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * @author <NAME> * * Various read helpers. * * TODO: remove? (as we have IntReader now) * */ public class ReadUtil { public static final void readCheckType(InputStream stream,int expectedType) throws IOException { int type=readInt(stream); if (type!=expectedType) { throw new IOException( "Expected chunk of type 0x"+Integer.toHexString(expectedType)+ ", read 0x"+Integer.toHexString(type)+"."); } } public static final void readCheckType(IntReader reader,int expectedType) throws IOException { int type=reader.readInt(); if (type!=expectedType) { throw new IOException( "Expected chunk of type 0x"+Integer.toHexString(expectedType)+ ", read 0x"+Integer.toHexString(type)+"."); } } public static final int[] readIntArray(InputStream stream,int elementCount) throws IOException { int[] result=new int[elementCount]; for (int i=0;i!=elementCount;++i) { result[i]=readInt(stream); } return result; } public static final int readInt(InputStream stream) throws IOException { return readInt(stream,4); } public static final int readShort(InputStream stream) throws IOException { return readInt(stream,2); } public static final String readString(InputStream stream) throws IOException { int length=readShort(stream); StringBuilder builder=new StringBuilder(length); for (int i=0;i!=length;++i) { builder.append((char)readShort(stream)); } readShort(stream); return builder.toString(); } public static final int readInt(InputStream stream,int length) throws IOException { int result=0; for (int i=0;i!=length;++i) { int b=stream.read(); if (b==-1) { throw new EOFException(); } result|=(b<<(i*8)); } return result; } }
1,112
1,473
/* * Autopsy * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.logicalimager.dsp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.List; /** * Utility class for displaying a list of drives */ public final class DriveListUtils { /** * Convert a number of bytes to a human readable string * * @param bytes the number of bytes to convert * @param si whether it takes 1000 or 1024 of a unit to reach the next * unit * * @return a human readable string representing the number of bytes */ public static String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) { return bytes + " B"; //NON-NLS } int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); //NON-NLS return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); //NON-NLS } /** * Empty private constructor for util class */ private DriveListUtils() { //empty private constructor for util class } /** Use the command <code>net</code> to determine what this drive is. * <code>net use</code> will return an error for anything which isn't a share. */ public static boolean isNetworkDrive(String driveLetter) { List<String> cmd = Arrays.asList("cmd", "/c", "net", "use", driveLetter + ":"); try { Process p = new ProcessBuilder(cmd) .redirectErrorStream(true) .start(); p.getOutputStream().close(); StringBuilder consoleOutput = new StringBuilder(); String line; try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) { while ((line = in.readLine()) != null) { consoleOutput.append(line).append("\r\n"); } } int rc = p.waitFor(); return rc == 0; } catch(IOException | InterruptedException e) { return false; // assume not a network drive } } }
1,160
429
# ============================================ __author__ = "<NAME>" __maintainer__ = "<NAME>" # ============================================ import torch import math from torch import nn from fairseq.delight_modules.print_utilities import * class GELU(torch.nn.Module): def __init__(self): super(GELU, self).__init__() def forward(self, x): return torch.nn.functional.gelu(x) class Swish(torch.nn.Module): def __init__(self): super(Swish, self).__init__() self.sigmoid = nn.Sigmoid() def forward(self, x): return x * self.sigmoid(x) activation_list = [ 'relu', 'leaky', 'selu', 'elu', 'celu', 'prelu', 'sigmoid', 'tanh', 'gelu', 'swish' ] def get_activation_layer(name): if name == 'relu': return nn.ReLU(inplace=False) elif name == 'leaky': return nn.LeakyReLU(negative_slope=0.1, inplace=False) elif name == 'selu': return nn.SELU(inplace=True) elif name == 'elu': return nn.ELU(inplace=True) elif name == 'celu': return nn.CELU(inplace=True) elif name == 'prelu': return nn.PReLU() elif name == 'sigmoid': return nn.Sigmoid() elif name == 'tanh': return nn.Tanh() elif name == 'gelu': return GELU() elif name =='swish': return Swish() else: print_error_message('Supported activation functions: {}'.format(activation_list)) return None
639
14,668
<filename>ui/aura/test/x11_event_sender.h // Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_AURA_TEST_X11_EVENT_SENDER_H_ #define UI_AURA_TEST_X11_EVENT_SENDER_H_ #include "ui/aura/window_tree_host.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/x/connection.h" #include "ui/gfx/x/xproto_util.h" namespace aura { namespace test { // The root, time, root_x, and root_y fields of |xevent| may be modified. template <typename T> void PostEventToWindowTreeHost(WindowTreeHost* host, T* xevent) { auto* connection = x11::Connection::Get(); x11::Window xwindow = static_cast<x11::Window>(host->GetAcceleratedWidget()); xevent->event = xwindow; xevent->root = connection->default_root(); xevent->time = x11::Time::CurrentTime; gfx::Point point(xevent->event_x, xevent->event_y); host->ConvertDIPToScreenInPixels(&point); xevent->root_x = point.x(); xevent->root_y = point.y(); x11::SendEvent(*xevent, xwindow, x11::EventMask::NoEvent); connection->Flush(); } } // namespace test } // namespace aura #endif // UI_AURA_TEST_X11_EVENT_SENDER_H_
472
1,254
import rest_framework.serializers from rest_framework_nested.relations import NestedHyperlinkedIdentityField, NestedHyperlinkedRelatedField try: from rest_framework.utils.field_mapping import get_nested_relation_kwargs except ImportError: pass # passing because NestedHyperlinkedModelSerializer can't be used anyway # if version too old. class NestedHyperlinkedModelSerializer(rest_framework.serializers.HyperlinkedModelSerializer): """ A type of `ModelSerializer` that uses hyperlinked relationships with compound keys instead of primary key relationships. Specifically: * A 'url' field is included instead of the 'id' field. * Relationships to other instances are hyperlinks, instead of primary keys. NOTE: this only works with DRF 3.1.0 and above. """ parent_lookup_kwargs = { 'parent_pk': 'parent__pk' } serializer_url_field = NestedHyperlinkedIdentityField serializer_related_field = NestedHyperlinkedRelatedField def __init__(self, *args, **kwargs): self.parent_lookup_kwargs = kwargs.pop('parent_lookup_kwargs', self.parent_lookup_kwargs) super(NestedHyperlinkedModelSerializer, self).__init__(*args, **kwargs) def build_url_field(self, field_name, model_class): field_class, field_kwargs = super(NestedHyperlinkedModelSerializer, self).build_url_field( field_name, model_class ) field_kwargs['parent_lookup_kwargs'] = self.parent_lookup_kwargs return field_class, field_kwargs def build_nested_field(self, field_name, relation_info, nested_depth): """ Create nested fields for forward and reverse relationships. """ class NestedSerializer(NestedHyperlinkedModelSerializer): class Meta: model = relation_info.related_model depth = nested_depth - 1 fields = '__all__' field_class = NestedSerializer field_kwargs = get_nested_relation_kwargs(relation_info) return field_class, field_kwargs
765
694
// metadoc Duration copyright <NAME> 2002 // metadoc Duration license BSD revised #ifndef DURATION_DEFINED #define DURATION_DEFINED 1 #include "Common.h" #include "UArray.h" #include "PortableGettimeofday.h" #ifdef __cplusplus extern "C" { #endif typedef struct { double seconds; } Duration; BASEKIT_API Duration *Duration_new(void); BASEKIT_API Duration *Duration_newWithSeconds_(double s); BASEKIT_API Duration *Duration_clone(const Duration *self); BASEKIT_API void Duration_copy_(Duration *self, const Duration *other); BASEKIT_API void Duration_free(Duration *self); BASEKIT_API int Duration_compare(const Duration *self, const Duration *other); // components BASEKIT_API int Duration_years(const Duration *self); BASEKIT_API void Duration_setYears_(Duration *self, double y); BASEKIT_API int Duration_days(const Duration *self); BASEKIT_API void Duration_setDays_(Duration *self, double d); BASEKIT_API int Duration_hours(const Duration *self); BASEKIT_API void Duration_setHours_(Duration *self, double m); BASEKIT_API int Duration_minutes(const Duration *self); BASEKIT_API void Duration_setMinutes_(Duration *self, double m); BASEKIT_API double Duration_seconds(const Duration *self); BASEKIT_API void Duration_setSeconds_(Duration *self, double s); // total seconds BASEKIT_API double Duration_asSeconds(const Duration *self); BASEKIT_API void Duration_fromSeconds_(Duration *self, double s); // strings BASEKIT_API UArray *Duration_asUArrayWithFormat_(const Duration *self, const char *format); BASEKIT_API void Duration_print(const Duration *self); // math BASEKIT_API void Duration_add_(Duration *self, const Duration *other); BASEKIT_API void Duration_subtract_(Duration *self, const Duration *other); #ifdef __cplusplus } #endif #endif
635
645
<reponame>xuantan/viewfinder # -*- coding: utf-8 -*- # Copyright 2012 Viewfinder Inc. All Rights Reserved. """Tests for Contact. """ __author__ = '<EMAIL> (<NAME>)' from viewfinder.backend.base import util from viewfinder.backend.db import versions from viewfinder.backend.db.contact import Contact from viewfinder.backend.db.identity import Identity from base_test import DBBaseTestCase class ContactTestCase(DBBaseTestCase): def testUnlinkIdentity(self): """Verify unlinking an identity causes every referencing contact to be updated.""" # Create a Peter contact for Spencer. timestamp = util.GetCurrentTimestamp() spencer = self._user contact_identity = 'Email:<EMAIL>' contact_name = '<NAME>' contact_given_name = 'Peter' contact_family_name = 'Mattis' contact_rank = 42 contact = Contact.CreateFromKeywords(spencer.user_id, [(contact_identity, None)], timestamp, Contact.GMAIL, name='<NAME>', given_name='Peter', family_name='Mattis', rank=42) self._RunAsync(contact.Update, self._client) peter_ident = self._RunAsync(Identity.Query, self._client, contact_identity, None) # Unlink peter's identity, which should cause Spencer's contact to be updated. self._RunAsync(peter_ident.UnlinkIdentity, self._client, self._user2.user_id, contact_identity, timestamp + 1) contacts = self._RunAsync(Contact.RangeQuery, self._client, spencer.user_id, None, None, None) self.assertEqual(len(contacts), 1) self.assertEqual(contacts[0].sort_key, Contact.CreateSortKey(contact.contact_id, timestamp + 1)) self.assertEqual(contacts[0].name, contact_name) self.assertEqual(contacts[0].given_name, contact_given_name) self.assertEqual(contacts[0].family_name, contact_family_name) self.assertEqual(contacts[0].rank, contact_rank) def testDerivedAttributes(self): """Test that the identity and identities attributes are being properly derived from the identities_properties attribute. """ # Create a Peter contact for Spencer with multiple identical and nearly identical identities. spencer = self._user contact_identity_a = 'Email:<EMAIL>' contact_identity_b = 'Email:<EMAIL>' contact_identity_c = 'Email:<EMAIL>' timestamp = util.GetCurrentTimestamp() contact = Contact.CreateFromKeywords(spencer.user_id, [(contact_identity_a, None), (contact_identity_b, 'home'), (contact_identity_c, 'work')], timestamp, Contact.GMAIL, name='<NAME>', given_name='Peter', family_name='Mattis', rank=42) self.assertEqual(len(contact.identities_properties), 3) self.assertEqual(len(contact.identities), 2) self.assertFalse(contact_identity_a in contact.identities) self.assertFalse(contact_identity_b in contact.identities) self.assertFalse(contact_identity_c in contact.identities) self.assertTrue(Identity.Canonicalize(contact_identity_a) in contact.identities) self.assertTrue(Identity.Canonicalize(contact_identity_b) in contact.identities) self.assertTrue(Identity.Canonicalize(contact_identity_c) in contact.identities) self.assertTrue([contact_identity_a, None] in contact.identities_properties) self.assertTrue([contact_identity_b, 'home'] in contact.identities_properties) self.assertTrue([contact_identity_c, 'work'] in contact.identities_properties) def testUnicodeContactNames(self): """Test that contact_id generation works correctly when names include non-ascii characters.""" name = u'ààà朋友你好abc123\U00010000\U00010000\x00\x01\b\n\t ' # The following will assert if there are problems when calculating the hash for the contact_id: contact_a = Contact.CreateFromKeywords(1, [('Email:<EMAIL>', None)], util.GetCurrentTimestamp(), Contact.GMAIL, name=name) contact_b = Contact.CreateFromKeywords(1, [('Email:<EMAIL>', None)], util.GetCurrentTimestamp(), Contact.GMAIL, name=u'朋' + name[1:]) # Check that making a slight change to a unicode self.assertNotEqual(contact_a.contact_id, contact_b.contact_id)
2,436
474
<filename>apis/Google.Cloud.Security.PrivateCA.V1Beta1/smoketests.json [ { "method": "ListReusableConfigs", "client": "CertificateAuthorityServiceClient", "arguments": { "parent": "projects/${PROJECT_ID}/locations/us-east1" } }, { "method": "ListCertificateAuthorities", "client": "CertificateAuthorityServiceClient", "arguments": { "parent": "projects/${PROJECT_ID}/locations/us-east1" } } ]
182
689
from pyspark.sql import Row from pyspark.sql.types import * from pyspark.sql import SparkSession spark = (SparkSession .builder .appName("Authors") .getOrCreate()) schema = StructType([ StructField("Author" , StringType(), False), StructField("State", StringType(), False)]) rows = [Row("<NAME>", "CA"), Row("<NAME>", "CA")] authors_df = spark.createDataFrame(rows, schema) authors_df.show()
146
1,130
/* Copyright (c) 2018, <NAME> 2-clause BSD license. */ #ifdef _WINDOWS asm("extern ___GetFileType\n" "global _GetFileType\n" "section .text\n" "_GetFileType:\n" "jmp ___GetFileType"); #endif
101
433
<reponame>redkale/redkale<gh_stars>100-1000 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.redkale.convert; import java.lang.reflect.Type; import java.util.concurrent.CompletableFuture; /** * 对不明类型的对象进行序列化; BSON序列化时将对象的类名写入Writer,JSON则不写入。 * <p> * 详情见: https://redkale.org * * @author zhangjx * @param <T> 序列化的泛型类型 */ public final class AnyEncoder<T> implements Encodeable<Writer, T> { final ConvertFactory factory; AnyEncoder(ConvertFactory factory) { this.factory = factory; } @Override @SuppressWarnings("unchecked") public void convertTo(final Writer out, final T value) { if (value == null) { out.writeClassName(null); out.writeNull(); } else { Class clazz = value.getClass(); if (clazz == Object.class) { out.writeObjectB(value); out.writeObjectE(value); return; } if (out.needWriteClassName()) out.writeClassName(factory.getEntityAlias(clazz)); factory.loadEncoder(clazz).convertTo(out, value); } } @SuppressWarnings("unchecked") public void convertMapTo(final Writer out, final Object... values) { if (values == null) { out.writeNull(); } else { int count = values.length - values.length % 2; if (out.writeMapB(count / 2, (Encodeable) this, (Encodeable) this, values) < 0) { for (int i = 0; i < count; i += 2) { if (i > 0) out.writeArrayMark(); this.convertTo(out, (T) values[i]); out.writeMapMark(); Object val = values[i + 1]; if (val instanceof CompletableFuture) { this.convertTo(out, (T) ((CompletableFuture) val).join()); } else { this.convertTo(out, (T) val); } } } out.writeMapE(); } } @Override public Type getType() { return Object.class; } }
1,236
1,441
// Distributing Ballot Boxes #include <bits/stdc++.h> using namespace std; typedef tuple<double, int, int> dii; // (ratio r, num, den) int main() { int N, B; while (scanf("%d %d", &N, &B), (N != -1 && B != -1)) { priority_queue<dii> pq; // max pq for (int i = 0; i < N; ++i) { int a; scanf("%d", &a); pq.push({(double)a/1.0, a, 1}); // initially, 1 box/city } B -= N; // remaining boxes while (B--) { // extra box->largest city auto [r, num, den] = pq.top(); pq.pop(); // current largest city pq.push({num/(den+1.0), num, den+1}); // reduce its workload } printf("%d\n", (int)ceil(get<0>(pq.top()))); // the final answer } // all other cities in the max pq will have equal or lesser ratio return 0; }
452
778
<reponame>troels/compute-runtime<filename>shared/source/helpers/get_info.h /* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #pragma once #include "get_info_status.h" // Need for linux compatibility with memcpy_s #include "shared/source/helpers/string.h" #include <cstring> #include <limits> namespace GetInfo { constexpr size_t invalidSourceSize = std::numeric_limits<size_t>::max(); inline GetInfoStatus getInfo(void *destParamValue, size_t destParamValueSize, const void *srcParamValue, size_t srcParamValueSize) { if (srcParamValueSize == 0) { // Report ok if there is nothing to copy. return GetInfoStatus::SUCCESS; } if ((srcParamValue == nullptr) || (srcParamValueSize == invalidSourceSize)) { return GetInfoStatus::INVALID_VALUE; } if (destParamValue == nullptr) { // Report ok if only size is queried. return GetInfoStatus::SUCCESS; } if (destParamValueSize < srcParamValueSize) { return GetInfoStatus::INVALID_VALUE; } // Report ok if we can copy safely. memcpy_s(destParamValue, destParamValueSize, srcParamValue, srcParamValueSize); return GetInfoStatus::SUCCESS; } inline void setParamValueReturnSize(size_t *paramValueSizeRet, size_t newValue, GetInfoStatus getInfoStatus) { if ((paramValueSizeRet != nullptr) && (getInfoStatus == GetInfoStatus::SUCCESS)) { *paramValueSizeRet = newValue; } } } // namespace GetInfo struct GetInfoHelper { GetInfoHelper(void *dst, size_t dstSize, size_t *retSize, GetInfoStatus *retVal = nullptr) : dst(dst), dstSize(dstSize), retSize(retSize), retVal(retVal) { } template <typename DataType> GetInfoStatus set(const DataType &val) { auto errCode = GetInfoStatus::SUCCESS; if (retSize != nullptr) { *retSize = sizeof(val); } if (dst != nullptr) { if (dstSize >= sizeof(val)) { *reinterpret_cast<DataType *>(dst) = val; } else { errCode = GetInfoStatus::INVALID_VALUE; } } if (retVal) *retVal = errCode; return errCode; } template <typename DataType> static void set(DataType *dst, DataType val) { if (dst) { *dst = val; } } void *dst; size_t dstSize; size_t *retSize; GetInfoStatus *retVal; }; struct ErrorCodeHelper { ErrorCodeHelper(int *errcodeRet, int defaultCode) : errcodeRet(errcodeRet) { set(defaultCode); } void set(int code) { if (errcodeRet != nullptr) { *errcodeRet = code; } localErrcode = code; } int *errcodeRet; int localErrcode; }; template <typename T> T getValidParam(T param, T defaultVal = 1, T invalidVal = 0) { if (param == invalidVal) { return defaultVal; } return param; }
1,285
1,016
<reponame>peter-ls/kylo package com.thinkbiganalytics.search; /*- * #%L * kylo-search-solr * %% * Copyright (C) 2017 ThinkBig Analytics * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.thinkbiganalytics.search.api.RepositoryIndexConfiguration; import com.thinkbiganalytics.search.config.SolrSearchClientConfiguration; import org.modeshape.jcr.RepositoryConfiguration; import org.modeshape.schematic.document.EditableDocument; import org.modeshape.schematic.document.Editor; import org.modeshape.schematic.document.ParsingException; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; /** * ModeShape configuration for Solr index (lucene) integration */ //TODO: Think about allowing uses to configure just what they want to index. I can build the JSON accordingly. public class SolrSearchModeShapeConfigurationService implements RepositoryIndexConfiguration { private SolrSearchClientConfiguration clientConfig; private static final String LUCENE = "lucene"; public SolrSearchModeShapeConfigurationService(SolrSearchClientConfiguration config) { this.clientConfig = config; } @Override public RepositoryConfiguration build() { RepositoryConfiguration repositoryConfiguration; final String EMPTY_CONFIG = "{}"; final String KYLO_CATEGORIES_METADATA = "kylo-categories-metadata"; final String KYLO_FEEDS_METADATA = "kylo-feeds-metadata"; final String INDEXES = "indexes"; final String INDEX_PROVIDERS = "indexProviders"; try { repositoryConfiguration = RepositoryConfiguration.read(EMPTY_CONFIG); } catch (ParsingException | FileNotFoundException e) { e.printStackTrace(); repositoryConfiguration = new RepositoryConfiguration(); } Editor editor = repositoryConfiguration.edit(); EditableDocument indexesDocument = editor.getOrCreateDocument(INDEXES); EditableDocument categoriesIndexDocument = indexesDocument.getOrCreateDocument(KYLO_CATEGORIES_METADATA); EditableDocument feedsIndexDocument = indexesDocument.getOrCreateDocument(KYLO_FEEDS_METADATA); categoriesIndexDocument.putAll(getCategoriesIndexConfiguration()); feedsIndexDocument.putAll(getFeedsIndexConfiguration()); EditableDocument indexProvidersDocument = editor.getOrCreateDocument(INDEX_PROVIDERS); EditableDocument localNamedIndexProviderDocument = indexProvidersDocument.getOrCreateDocument(LUCENE); localNamedIndexProviderDocument.putAll(getLuceneIndexProviderConfiguration()); repositoryConfiguration = new RepositoryConfiguration(editor, repositoryConfiguration.getName()); return repositoryConfiguration; } private Map<String, Object> getCategoriesIndexConfiguration() { final String VALUE = "value"; final String TBA_CATEGORY = "tba:category"; final String COLUMNS = "jcr:title (STRING), jcr:description (STRING)"; Map<String, Object> categoriesIndexConfigurationMap = new HashMap<>(); categoriesIndexConfigurationMap.put("kind", VALUE); categoriesIndexConfigurationMap.put("provider", LUCENE); categoriesIndexConfigurationMap.put("synchronous", false); categoriesIndexConfigurationMap.put("nodeType", TBA_CATEGORY); categoriesIndexConfigurationMap.put("columns", COLUMNS); return categoriesIndexConfigurationMap; } private Map<String, Object> getFeedsIndexConfiguration() { final String VALUE = "value"; final String FEED_SUMMARY = "tba:feedSummary"; final String COLUMNS = "jcr:title (STRING), jcr:description (STRING), tba:tags (STRING)"; Map<String, Object> feedsIndexConfigurationMap = new HashMap<>(); feedsIndexConfigurationMap.put("kind", VALUE); feedsIndexConfigurationMap.put("provider", LUCENE); feedsIndexConfigurationMap.put("synchronous", false); feedsIndexConfigurationMap.put("nodeType", FEED_SUMMARY); feedsIndexConfigurationMap.put("columns", COLUMNS); return feedsIndexConfigurationMap; } private Map<String, Object> getLuceneIndexProviderConfiguration() { Map<String, Object> luceneIndexProviderConfigurationMap = new HashMap<>(); luceneIndexProviderConfigurationMap.put("classname", LUCENE); luceneIndexProviderConfigurationMap.put("directory", clientConfig.getIndexStorageDirectory()); return luceneIndexProviderConfigurationMap; } }
1,639
776
<gh_stars>100-1000 #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) <NAME>. All rights reserved. # Licensed under the BSD license. See LICENSE file in the project root for full license information. import numpy as np def minmax(X, low, high, minX=None, maxX=None, dtype=np.float): X = np.asarray(X) if minX is None: minX = np.min(X) if maxX is None: maxX = np.max(X) # normalize to [0...1]. X = X - float(minX) X = X / float((maxX - minX)) # scale to [low...high]. X = X * (high-low) X = X + low return np.asarray(X,dtype=dtype) def zscore(X, mean=None, std=None): X = np.asarray(X) if mean is None: mean = X.mean() if std is None: std = X.std() X = (X-mean)/std return X
362
2,360
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RSparsematrixstats(RPackage): """Summary Statistics for Rows and Columns of Sparse Matrices High performance functions for row and column operations on sparse matrices. For example: col / rowMeans2, col / rowMedians, col / rowVars etc. Currently, the optimizations are limited to data in the column sparse format. This package is inspired by the matrixStats package by <NAME>.""" homepage = "https://bioconductor.org/packages/sparseMatrixStats/" git = "https://git.bioconductor.org/packages/sparseMatrixStats" version('1.2.1', commit='<PASSWORD>') depends_on('r-matrixgenerics', type=('build', 'run')) depends_on('r-rcpp', type=('build', 'run')) depends_on('r-matrix', type=('build', 'run')) depends_on('r-matrixstats', type=('build', 'run'))
339
567
<filename>AI_Engine_Development/Feature_Tutorials/09-debug-walkthrough/sw/host.h<gh_stars>100-1000 /********** © Copyright 2020 Xilinx, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. **********/ #pragma once #define CL_HPP_CL_1_2_DEFAULT_BUILD #define CL_HPP_TARGET_OPENCL_VERSION 120 #define CL_HPP_MINIMUM_OPENCL_VERSION 120 #define CL_HPP_ENABLE_PROGRAM_CONSTRUCTION_FROM_ARRAY_COMPATIBILITY 1 #include <CL/cl2.hpp> //Customized buffer allocation for 4K boundary alignment template <typename T> struct aligned_allocator { using value_type = T; T* allocate(std::size_t num) { void* ptr = nullptr; if (posix_memalign(&ptr,4096,num*sizeof(T))) throw std::bad_alloc(); return reinterpret_cast<T*>(ptr); } void deallocate(T* p, std::size_t num) { free(p); } };
444
1,144
/* * PCIe driver for PLX NAS782X SoCs * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/kernel.h> #include <linux/pci.h> #include <linux/clk.h> #include <linux/module.h> #include <linux/mbus.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/of_address.h> #include <linux/of_pci.h> #include <linux/of_irq.h> #include <linux/of_platform.h> #include <linux/of_gpio.h> #include <linux/gpio.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/reset.h> #include <mach/iomap.h> #include <mach/hardware.h> #include <mach/utils.h> #define VERSION_ID_MAGIC 0x082510b5 #define LINK_UP_TIMEOUT_SECONDS 1 #define NUM_CONTROLLERS 1 enum { PCIE_DEVICE_TYPE_MASK = 0x0F, PCIE_DEVICE_TYPE_ENDPOINT = 0, PCIE_DEVICE_TYPE_LEGACY_ENDPOINT = 1, PCIE_DEVICE_TYPE_ROOT = 4, PCIE_LTSSM = BIT(4), PCIE_READY_ENTR_L23 = BIT(9), PCIE_LINK_UP = BIT(11), PCIE_OBTRANS = BIT(12), }; enum { HCSL_BIAS_ON = BIT(0), HCSL_PCIE_EN = BIT(1), HCSL_PCIEA_EN = BIT(2), HCSL_PCIEB_EN = BIT(3), }; enum { /* pcie phy reg offset */ PHY_ADDR = 0, PHY_DATA = 4, /* phy data reg bits */ READ_EN = BIT(16), WRITE_EN = BIT(17), CAP_DATA = BIT(18), }; /* core config registers */ enum { PCI_CONFIG_VERSION_DEVICEID = 0, PCI_CONFIG_COMMAND_STATUS = 4, }; /* inbound config registers */ enum { IB_ADDR_XLATE_ENABLE = 0xFC, /* bits */ ENABLE_IN_ADDR_TRANS = BIT(0), }; /* outbound config registers, offset relative to PCIE_POM0_MEM_ADDR */ enum { PCIE_POM0_MEM_ADDR = 0, PCIE_POM1_MEM_ADDR = 4, PCIE_IN0_MEM_ADDR = 8, PCIE_IN1_MEM_ADDR = 12, PCIE_IN_IO_ADDR = 16, PCIE_IN_CFG0_ADDR = 20, PCIE_IN_CFG1_ADDR = 24, PCIE_IN_MSG_ADDR = 28, PCIE_IN0_MEM_LIMIT = 32, PCIE_IN1_MEM_LIMIT = 36, PCIE_IN_IO_LIMIT = 40, PCIE_IN_CFG0_LIMIT = 44, PCIE_IN_CFG1_LIMIT = 48, PCIE_IN_MSG_LIMIT = 52, PCIE_AHB_SLAVE_CTRL = 56, PCIE_SLAVE_BE_SHIFT = 22, }; #define ADDR_VAL(val) ((val) & 0xFFFF) #define DATA_VAL(val) ((val) & 0xFFFF) #define PCIE_SLAVE_BE(val) ((val) << PCIE_SLAVE_BE_SHIFT) #define PCIE_SLAVE_BE_MASK PCIE_SLAVE_BE(0xF) struct oxnas_pcie_shared { /* seems all access are serialized, no lock required */ int refcount; }; /* Structure representing one PCIe interfaces */ struct oxnas_pcie { void __iomem *cfgbase; void __iomem *base; void __iomem *inbound; void __iomem *outbound; void __iomem *pcie_ctrl; int haslink; struct platform_device *pdev; struct resource io; struct resource cfg; struct resource pre_mem; /* prefetchable */ struct resource non_mem; /* non-prefetchable */ struct resource busn; /* max available bus numbers */ int card_reset; /* gpio pin, optional */ unsigned hcsl_en; /* hcsl pci enable bit */ struct clk *clk; struct clk *busclk; /* for pcie bus, actually the PLLB */ void *private_data[1]; spinlock_t lock; }; static struct oxnas_pcie_shared pcie_shared = { .refcount = 0, }; static inline struct oxnas_pcie *sys_to_pcie(struct pci_sys_data *sys) { return sys->private_data; } static inline void set_out_lanes(struct oxnas_pcie *pcie, unsigned lanes) { oxnas_register_value_mask(pcie->outbound + PCIE_AHB_SLAVE_CTRL, PCIE_SLAVE_BE_MASK, PCIE_SLAVE_BE(lanes)); wmb(); } static int oxnas_pcie_link_up(struct oxnas_pcie *pcie) { unsigned long end; /* Poll for PCIE link up */ end = jiffies + (LINK_UP_TIMEOUT_SECONDS * HZ); while (!time_after(jiffies, end)) { if (readl(pcie->pcie_ctrl) & PCIE_LINK_UP) return 1; } return 0; } static void __init oxnas_pcie_setup_hw(struct oxnas_pcie *pcie) { /* We won't have any inbound address translation. This allows PCI * devices to access anywhere in the AHB address map. Might be regarded * as a bit dangerous, but let's get things working before we worry * about that */ oxnas_register_clear_mask(pcie->inbound + IB_ADDR_XLATE_ENABLE, ENABLE_IN_ADDR_TRANS); wmb(); /* * Program outbound translation windows * * Outbound window is what is referred to as "PCI client" region in HRM * * Could use the larger alternative address space to get >>64M regions * for graphics cards etc., but will not bother at this point. * * IP bug means that AMBA window size must be a power of 2 * * Set mem0 window for first 16MB of outbound window non-prefetchable * Set mem1 window for second 16MB of outbound window prefetchable * Set io window for next 16MB of outbound window * Set cfg0 for final 1MB of outbound window * * Ignore mem1, cfg1 and msg windows for now as no obvious use cases for * 820 that would need them * * Probably ideally want no offset between mem0 window start as seen by * ARM and as seen on PCI bus and get Linux to assign memory regions to * PCI devices using the same "PCI client" region start address as seen * by ARM */ /* Set PCIeA mem0 region to be 1st 16MB of the 64MB PCIeA window */ writel_relaxed(pcie->non_mem.start, pcie->outbound + PCIE_IN0_MEM_ADDR); writel_relaxed(pcie->non_mem.end, pcie->outbound + PCIE_IN0_MEM_LIMIT); writel_relaxed(pcie->non_mem.start, pcie->outbound + PCIE_POM0_MEM_ADDR); /* Set PCIeA mem1 region to be 2nd 16MB of the 64MB PCIeA window */ writel_relaxed(pcie->pre_mem.start, pcie->outbound + PCIE_IN1_MEM_ADDR); writel_relaxed(pcie->pre_mem.end, pcie->outbound + PCIE_IN1_MEM_LIMIT); writel_relaxed(pcie->pre_mem.start, pcie->outbound + PCIE_POM1_MEM_ADDR); /* Set PCIeA io to be third 16M region of the 64MB PCIeA window*/ writel_relaxed(pcie->io.start, pcie->outbound + PCIE_IN_IO_ADDR); writel_relaxed(pcie->io.end, pcie->outbound + PCIE_IN_IO_LIMIT); /* Set PCIeA cgf0 to be last 16M region of the 64MB PCIeA window*/ writel_relaxed(pcie->cfg.start, pcie->outbound + PCIE_IN_CFG0_ADDR); writel_relaxed(pcie->cfg.end, pcie->outbound + PCIE_IN_CFG0_LIMIT); wmb(); /* Enable outbound address translation */ oxnas_register_set_mask(pcie->pcie_ctrl, PCIE_OBTRANS); wmb(); /* * Program PCIe command register for core to: * enable memory space * enable bus master * enable io */ writel_relaxed(7, pcie->base + PCI_CONFIG_COMMAND_STATUS); /* which is which */ wmb(); } static unsigned oxnas_pcie_cfg_to_offset( struct pci_sys_data *sys, unsigned char bus_number, unsigned int devfn, int where) { unsigned int function = PCI_FUNC(devfn); unsigned int slot = PCI_SLOT(devfn); unsigned char bus_number_offset; bus_number_offset = bus_number - sys->busnr; /* * We'll assume for now that the offset, function, slot, bus encoding * should map onto linear, contiguous addresses in PCIe config space, * albeit that the majority will be unused as only slot 0 is valid for * any PCIe bus and most devices have only function 0 * * Could be that PCIe in fact works by not encoding the slot number into * the config space address as it's known that only slot 0 is valid. * We'll have to experiment if/when we get a PCIe switch connected to * the PCIe host */ return (bus_number_offset << 20) | (slot << 15) | (function << 12) | (where & ~3); } /* PCI configuration space write function */ static int oxnas_pcie_wr_conf(struct pci_bus *bus, u32 devfn, int where, int size, u32 val) { unsigned long flags; struct oxnas_pcie *pcie = sys_to_pcie(bus->sysdata); unsigned offset; u32 value; u32 lanes; /* Only a single device per bus for PCIe point-to-point links */ if (PCI_SLOT(devfn) > 0) return PCIBIOS_DEVICE_NOT_FOUND; if (!pcie->haslink) return PCIBIOS_DEVICE_NOT_FOUND; offset = oxnas_pcie_cfg_to_offset(bus->sysdata, bus->number, devfn, where); value = val << (8 * (where & 3)); lanes = (0xf >> (4-size)) << (where & 3); /* it race with mem and io write, but the possibility is low, normally * all config writes happens at driver initialize stage, wont interleave * with others. * and many pcie cards use dword (4bytes) access mem/io access only, * so not bother to copy that ugly work-around now. */ spin_lock_irqsave(&pcie->lock, flags); set_out_lanes(pcie, lanes); writel_relaxed(value, pcie->cfgbase + offset); set_out_lanes(pcie, 0xf); spin_unlock_irqrestore(&pcie->lock, flags); return PCIBIOS_SUCCESSFUL; } /* PCI configuration space read function */ static int oxnas_pcie_rd_conf(struct pci_bus *bus, u32 devfn, int where, int size, u32 *val) { struct oxnas_pcie *pcie = sys_to_pcie(bus->sysdata); unsigned offset; u32 value; u32 left_bytes, right_bytes; /* Only a single device per bus for PCIe point-to-point links */ if (PCI_SLOT(devfn) > 0) { *val = 0xffffffff; return PCIBIOS_DEVICE_NOT_FOUND; } if (!pcie->haslink) { *val = 0xffffffff; return PCIBIOS_DEVICE_NOT_FOUND; } offset = oxnas_pcie_cfg_to_offset(bus->sysdata, bus->number, devfn, where); value = readl_relaxed(pcie->cfgbase + offset); left_bytes = where & 3; right_bytes = 4 - left_bytes - size; value <<= right_bytes * 8; value >>= (left_bytes + right_bytes) * 8; *val = value; return PCIBIOS_SUCCESSFUL; } static struct pci_ops oxnas_pcie_ops = { .read = oxnas_pcie_rd_conf, .write = oxnas_pcie_wr_conf, }; static int __init oxnas_pcie_setup(int nr, struct pci_sys_data *sys) { struct oxnas_pcie *pcie = sys_to_pcie(sys); pci_add_resource_offset(&sys->resources, &pcie->non_mem, sys->mem_offset); pci_add_resource_offset(&sys->resources, &pcie->pre_mem, sys->mem_offset); pci_add_resource_offset(&sys->resources, &pcie->io, sys->io_offset); pci_add_resource(&sys->resources, &pcie->busn); if (sys->busnr == 0) { /* default one */ sys->busnr = pcie->busn.start; } /* do not use devm_ioremap_resource, it does not like cfg resource */ pcie->cfgbase = devm_ioremap(&pcie->pdev->dev, pcie->cfg.start, resource_size(&pcie->cfg)); if (!pcie->cfgbase) return -ENOMEM; oxnas_pcie_setup_hw(pcie); return 1; } static void __init oxnas_pcie_enable(struct device *dev, struct oxnas_pcie *pcie) { struct hw_pci hw; int i; memset(&hw, 0, sizeof(hw)); for (i = 0; i < NUM_CONTROLLERS; i++) pcie->private_data[i] = pcie; hw.nr_controllers = NUM_CONTROLLERS; /* I think use stack pointer is a bad idea though it is valid in this case */ hw.private_data = pcie->private_data; hw.setup = oxnas_pcie_setup; hw.map_irq = of_irq_parse_and_map_pci; hw.ops = &oxnas_pcie_ops; /* pass dev to maintain of tree, interrupt mapping rely on this */ pci_common_init_dev(dev, &hw); } void oxnas_pcie_init_shared_hw(struct platform_device *pdev, void __iomem *phybase) { struct reset_control *rstc; int ret; /* generate clocks from HCSL buffers, shared parts */ writel(HCSL_BIAS_ON|HCSL_PCIE_EN, SYS_CTRL_HCSL_CTRL); /* Ensure PCIe PHY is properly reset */ rstc = reset_control_get(&pdev->dev, "phy"); if (IS_ERR(rstc)) { ret = PTR_ERR(rstc); } else { ret = reset_control_reset(rstc); reset_control_put(rstc); } if (ret) { dev_err(&pdev->dev, "phy reset failed %d\n", ret); return; } /* Enable PCIe Pre-Emphasis: What these value means? */ writel(ADDR_VAL(0x0014), phybase + PHY_ADDR); writel(DATA_VAL(0xce10) | CAP_DATA, phybase + PHY_DATA); writel(DATA_VAL(0xce10) | WRITE_EN, phybase + PHY_DATA); writel(ADDR_VAL(0x2004), phybase + PHY_ADDR); writel(DATA_VAL(0x82c7) | CAP_DATA, phybase + PHY_DATA); writel(DATA_VAL(0x82c7) | WRITE_EN, phybase + PHY_DATA); } static int oxnas_pcie_shared_init(struct platform_device *pdev) { if (++pcie_shared.refcount == 1) { /* we are the first */ struct device_node *np = pdev->dev.of_node; void __iomem *phy = of_iomap(np, 2); if (!phy) { --pcie_shared.refcount; return -ENOMEM; } oxnas_pcie_init_shared_hw(pdev, phy); iounmap(phy); return 0; } else { return 0; } } #if 0 /* maybe we will call it when enter low power state */ static void oxnas_pcie_shared_deinit(struct platform_device *pdev) { if (--pcie_shared.refcount == 0) { /* no cleanup needed */; } } #endif static int __init oxnas_pcie_map_registers(struct platform_device *pdev, struct device_node *np, struct oxnas_pcie *pcie) { struct resource regs; int ret = 0; u32 outbound_ctrl_offset; u32 pcie_ctrl_offset; /* 2 is reserved for shared phy */ ret = of_address_to_resource(np, 0, &regs); if (ret) return -EINVAL; pcie->base = devm_ioremap_resource(&pdev->dev, &regs); if (!pcie->base) return -ENOMEM; ret = of_address_to_resource(np, 1, &regs); if (ret) return -EINVAL; pcie->inbound = devm_ioremap_resource(&pdev->dev, &regs); if (!pcie->inbound) return -ENOMEM; if (of_property_read_u32(np, "plxtech,pcie-outbound-offset", &outbound_ctrl_offset)) return -EINVAL; /* SYSCRTL is shared by too many drivers, so is mapped by board file */ pcie->outbound = IOMEM(OXNAS_SYSCRTL_BASE_VA + outbound_ctrl_offset); if (of_property_read_u32(np, "plxtech,pcie-ctrl-offset", &pcie_ctrl_offset)) return -EINVAL; pcie->pcie_ctrl = IOMEM(OXNAS_SYSCRTL_BASE_VA + pcie_ctrl_offset); return 0; } static int __init oxnas_pcie_init_res(struct platform_device *pdev, struct oxnas_pcie *pcie, struct device_node *np) { struct of_pci_range range; struct of_pci_range_parser parser; int ret; if (of_pci_range_parser_init(&parser, np)) return -EINVAL; /* Get the I/O and memory ranges from DT */ for_each_of_pci_range(&parser, &range) { unsigned long restype = range.flags & IORESOURCE_TYPE_BITS; if (restype == IORESOURCE_IO) { of_pci_range_to_resource(&range, np, &pcie->io); pcie->io.name = "I/O"; } if (restype == IORESOURCE_MEM) { if (range.flags & IORESOURCE_PREFETCH) { of_pci_range_to_resource(&range, np, &pcie->pre_mem); pcie->pre_mem.name = "PRE MEM"; } else { of_pci_range_to_resource(&range, np, &pcie->non_mem); pcie->non_mem.name = "NON MEM"; } } if (restype == 0) of_pci_range_to_resource(&range, np, &pcie->cfg); } /* Get the bus range */ ret = of_pci_parse_bus_range(np, &pcie->busn); if (ret) { dev_err(&pdev->dev, "failed to parse bus-range property: %d\n", ret); return ret; } pcie->card_reset = of_get_gpio(np, 0); if (pcie->card_reset < 0) dev_info(&pdev->dev, "card reset gpio pin not exists\n"); if (of_property_read_u32(np, "plxtech,pcie-hcsl-bit", &pcie->hcsl_en)) return -EINVAL; pcie->clk = of_clk_get_by_name(np, "pcie"); if (IS_ERR(pcie->clk)) { return PTR_ERR(pcie->clk); } pcie->busclk = of_clk_get_by_name(np, "busclk"); if (IS_ERR(pcie->busclk)) { clk_put(pcie->clk); return PTR_ERR(pcie->busclk); } return 0; } static void oxnas_pcie_init_hw(struct platform_device *pdev, struct oxnas_pcie *pcie) { u32 version_id; int ret; clk_prepare_enable(pcie->busclk); /* reset PCIe cards use hard-wired gpio pin */ if (pcie->card_reset >= 0 && !gpio_direction_output(pcie->card_reset, 0)) { wmb(); mdelay(10); /* must tri-state the pin to pull it up */ gpio_direction_input(pcie->card_reset); wmb(); mdelay(100); } oxnas_register_set_mask(SYS_CTRL_HCSL_CTRL, BIT(pcie->hcsl_en)); /* core */ ret = device_reset(&pdev->dev); if (ret) { dev_err(&pdev->dev, "core reset failed %d\n", ret); return; } /* Start PCIe core clocks */ clk_prepare_enable(pcie->clk); version_id = readl_relaxed(pcie->base + PCI_CONFIG_VERSION_DEVICEID); dev_info(&pdev->dev, "PCIe version/deviceID 0x%x\n", version_id); if (version_id != VERSION_ID_MAGIC) { dev_info(&pdev->dev, "PCIe controller not found\n"); pcie->haslink = 0; return; } /* allow entry to L23 state */ oxnas_register_set_mask(pcie->pcie_ctrl, PCIE_READY_ENTR_L23); /* Set PCIe core into RootCore mode */ oxnas_register_value_mask(pcie->pcie_ctrl, PCIE_DEVICE_TYPE_MASK, PCIE_DEVICE_TYPE_ROOT); wmb(); /* Bring up the PCI core */ oxnas_register_set_mask(pcie->pcie_ctrl, PCIE_LTSSM); wmb(); } static int __init oxnas_pcie_probe(struct platform_device *pdev) { struct oxnas_pcie *pcie; struct device_node *np = pdev->dev.of_node; int ret; pcie = devm_kzalloc(&pdev->dev, sizeof(struct oxnas_pcie), GFP_KERNEL); if (!pcie) return -ENOMEM; pcie->pdev = pdev; pcie->haslink = 1; spin_lock_init(&pcie->lock); ret = oxnas_pcie_init_res(pdev, pcie, np); if (ret) return ret; if (pcie->card_reset >= 0) { ret = gpio_request_one(pcie->card_reset, GPIOF_DIR_IN, dev_name(&pdev->dev)); if (ret) { dev_err(&pdev->dev, "cannot request gpio pin %d\n", pcie->card_reset); return ret; } } ret = oxnas_pcie_map_registers(pdev, np, pcie); if (ret) { dev_err(&pdev->dev, "cannot map registers\n"); goto err_free_gpio; } ret = oxnas_pcie_shared_init(pdev); if (ret) goto err_free_gpio; /* if hw not found, haslink cleared */ oxnas_pcie_init_hw(pdev, pcie); if (pcie->haslink && oxnas_pcie_link_up(pcie)) { pcie->haslink = 1; dev_info(&pdev->dev, "link up\n"); } else { pcie->haslink = 0; dev_info(&pdev->dev, "link down\n"); } /* should we register our controller even when pcie->haslink is 0 ? */ /* register the controller with framework */ oxnas_pcie_enable(&pdev->dev, pcie); return 0; err_free_gpio: if (pcie->card_reset) gpio_free(pcie->card_reset); return ret; } static const struct of_device_id oxnas_pcie_of_match_table[] = { { .compatible = "plxtech,nas782x-pcie", }, {}, }; MODULE_DEVICE_TABLE(of, oxnas_pcie_of_match_table); static struct platform_driver oxnas_pcie_driver = { .driver = { .owner = THIS_MODULE, .name = "oxnas-pcie", .of_match_table = of_match_ptr(oxnas_pcie_of_match_table), }, }; static int __init oxnas_pcie_init(void) { return platform_driver_probe(&oxnas_pcie_driver, oxnas_pcie_probe); } subsys_initcall(oxnas_pcie_init); MODULE_AUTHOR("<NAME> <<EMAIL>>"); MODULE_DESCRIPTION("NAS782x PCIe driver"); MODULE_LICENSE("GPLv2");
7,595
628
/* * Copyright (c) 2015-2018 Contributors as noted in the AUTHORS file * * This file is part of Solo5, a sandboxed execution environment. * * Permission to use, copy, modify, and/or distribute this software * for any purpose with or without fee is hereby granted, provided * that the above copyright notice and this permission notice appear * in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "bindings.h" /* * The sys_ functions in this file are intentionally weakly typed as they only * pass through values to/from the system call without interpretation. All * integer values are passed as (long) and all pointer values are passed as * (void *). */ #define SYS_read 3 #define SYS_write 4 #define SYS_pread64 179 #define SYS_pwrite64 180 #define SYS_clock_gettime 246 #define SYS_exit_group 234 #define SYS_epoll_pwait 303 #define SYS_timerfd_settime 311 long sys_read(long fd, void *buf, long size) { register long r0 __asm__("r0") = SYS_read; register long r3 __asm__("r3") = fd; register long r4 __asm__("r4") = (long)buf; register long r5 __asm__("r5") = size; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } long sys_write(long fd, const void *buf, long size) { register long r0 __asm__("r0") = SYS_write; register long r3 __asm__("r3") = fd; register long r4 __asm__("r4") = (long)buf; register long r5 __asm__("r5") = size; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } long sys_pread64(long fd, void *buf, long size, long pos) { register long r0 __asm__("r0") = SYS_pread64; register long r3 __asm__("r3") = fd; register long r4 __asm__("r4") = (long)buf; register long r5 __asm__("r5") = size; register long r6 __asm__("r6") = pos; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5), "r" (r6) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } long sys_pwrite64(long fd, const void *buf, long size, long pos) { register long r0 __asm__("r0") = SYS_pwrite64; register long r3 __asm__("r3") = fd; register long r4 __asm__("r4") = (long)buf; register long r5 __asm__("r5") = size; register long r6 __asm__("r6") = pos; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5), "r" (r6) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } void sys_exit_group(long status) { register long r0 __asm__("r0") = SYS_exit_group; register long r3 __asm__("r3") = status; __asm__ __volatile__ ( "sc" : "=r" (r0) : "r" (r0), "r" (r3) : "memory", "cc" ); for(;;); } long sys_clock_gettime(const long which, void *ts) { register long r0 __asm__("r0") = SYS_clock_gettime; register long r3 __asm__("r3") = which; register long r4 __asm__("r4") = (long)ts; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } long sys_epoll_pwait(long epfd, void *events, long maxevents, long timeout, void *sigmask, long sigsetsize) { register long r0 __asm__("r0") = SYS_epoll_pwait; register long r3 __asm__("r3") = epfd; register long r4 __asm__("r4") = (long)events; register long r5 __asm__("r5") = maxevents; register long r6 __asm__("r6") = timeout; register long r7 __asm__("r7") = (long)sigmask; register long r8 __asm__("r8") = sigsetsize; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5), "r" (r6), "r" (r7), "r" (r8) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; } long sys_timerfd_settime(long fd, long flags, const void *utmr, void *otmr) { register long r0 __asm__("r0") = SYS_timerfd_settime; register long r3 __asm__("r3") = fd; register long r4 __asm__("r4") = flags; register long r5 __asm__("r5") = (long)utmr; register long r6 __asm__("r6") = (long)otmr; long cr; __asm__ __volatile__ ( "sc\n\t" "mfcr %1" : "=r" (r3), "=&r" (cr) : "r" (r0), "r" (r3), "r" (r4), "r" (r5), "r" (r6) : "memory", "cc" ); if (cr & CR0_SO) r3 = -r3; return r3; }
2,780
776
package ghissues; import act.controller.annotation.UrlContext; import org.osgl.mvc.annotation.PostAction; @UrlContext("1284") public class Gh1284 extends BaseController { @PostAction("{id}") public void testPost(String id) { } }
85
995
<gh_stars>100-1000 #ifndef BOOST_THREAD_TSS_HPP #define BOOST_THREAD_TSS_HPP // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // (C) Copyright 2007-8 <NAME> #include <boost/thread/detail/config.hpp> #include <boost/type_traits/add_reference.hpp> #include <boost/config/abi_prefix.hpp> namespace boost { namespace detail { namespace thread { typedef void(*cleanup_func_t)(void*); typedef void(*cleanup_caller_t)(cleanup_func_t, void*); } BOOST_THREAD_DECL void set_tss_data(void const* key,detail::thread::cleanup_caller_t caller,detail::thread::cleanup_func_t func,void* tss_data,bool cleanup_existing); BOOST_THREAD_DECL void* get_tss_data(void const* key); } template <typename T> class thread_specific_ptr { private: thread_specific_ptr(thread_specific_ptr&); thread_specific_ptr& operator=(thread_specific_ptr&); typedef void(*original_cleanup_func_t)(T*); static void default_deleter(T* data) { delete data; } static void cleanup_caller(detail::thread::cleanup_func_t cleanup_function,void* data) { reinterpret_cast<original_cleanup_func_t>(cleanup_function)(static_cast<T*>(data)); } detail::thread::cleanup_func_t cleanup; public: typedef T element_type; thread_specific_ptr(): cleanup(reinterpret_cast<detail::thread::cleanup_func_t>(&default_deleter)) {} explicit thread_specific_ptr(void (*func_)(T*)) : cleanup(reinterpret_cast<detail::thread::cleanup_func_t>(func_)) {} ~thread_specific_ptr() { detail::set_tss_data(this,0,0,0,true); } T* get() const { return static_cast<T*>(detail::get_tss_data(this)); } T* operator->() const { return get(); } typename add_reference<T>::type operator*() const { return *get(); } T* release() { T* const temp=get(); detail::set_tss_data(this,0,0,0,false); return temp; } void reset(T* new_value=0) { T* const current_value=get(); if(current_value!=new_value) { detail::set_tss_data(this,&cleanup_caller,cleanup,new_value,true); } } }; } #include <boost/config/abi_suffix.hpp> #endif
1,381
679
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #include <pam.hxx> // fuer SwPam #include <doc.hxx> #include <ndtxt.hxx> // class SwTxtNode #include <fltini.hxx> // Ww1Reader #include <w1par.hxx> #ifndef _SWFLTOPT_HXX #include <swfltopt.hxx> #endif #include <mdiexp.hxx> // StatLine...() #include <swerror.h> // ERR_WW1_... #ifndef _STATSTR_HRC #include <statstr.hrc> // ResId fuer Statusleiste #endif //---------------------------------------- // Initialisieren der Feld-FilterFlags //---------------------------------------- static sal_uLong WW1_Read_FieldIniFlags() { // sal_uInt16 i; static const sal_Char* aNames[ 1 ] = { "WinWord/WW1F" }; sal_uInt32 aVal[ 1 ]; SwFilterOptions aOpt( 1, aNames, aVal ); sal_uLong nFieldFlags = aVal[ 0 ]; if ( SwFltGetFlag( nFieldFlags, SwFltControlStack::HYPO ) ) { SwFltSetFlag( nFieldFlags, SwFltControlStack::BOOK_TO_VAR_REF ); SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_DO_ID ); SwFltSetFlag( nFieldFlags, SwFltControlStack::TAGS_IN_TEXT ); SwFltSetFlag( nFieldFlags, SwFltControlStack::ALLOW_FLD_CR ); } return nFieldFlags; } ////////////////////////////////////////////////// StarWriter-Interface // // Eine Methode liefern die call-Schnittstelle fuer den Writer. // Read() liest eine Datei. hierzu werden zwei Objekte erzeugt, die Shell, // die die Informationen aufnimmt und der Manager der sie aus der Datei liest. // Diese werden dann einfach per Pipe 'uebertragen'. // sal_uLong WW1Reader::Read(SwDoc& rDoc, const String& rBaseURL, SwPaM& rPam, const String& /*cName*/) { sal_uLong nRet = ERR_SWG_READ_ERROR; ASSERT(pStrm!=NULL, "W1-Read ohne Stream"); if (pStrm != NULL) { sal_Bool bNew = !bInsertMode; // Neues Doc ( kein Einfuegen ) // erstmal eine shell konstruieren: die ist schnittstelle // zum writer-dokument sal_uLong nFieldFlags = WW1_Read_FieldIniFlags(); Ww1Shell* pRdr = new Ww1Shell( rDoc, rPam, rBaseURL, bNew, nFieldFlags ); if( pRdr ) { // dann den manager, der liest die struktur des word-streams Ww1Manager* pMan = new Ww1Manager( *pStrm, nFieldFlags ); if( pMan ) { if( !pMan->GetError() ) { ::StartProgress( STR_STATSTR_W4WREAD, 0, 100, rDoc.GetDocShell() ); ::SetProgressState( 0, rDoc.GetDocShell() ); // jetzt nur noch alles rueberschieben *pRdr << *pMan; if( !pMan->GetError() ) // und nur hier, wenn kein fehler auftrat // fehlerfreiheit melden nRet = 0; // besser waere: WARN_SWG_FEATURES_LOST; ::EndProgress( rDoc.GetDocShell() ); } else { if( pMan->GetFib().GetFIB().fComplexGet() ) //!!! ACHTUNG: hier muss eigentlich ein Error // wegen Fastsave kommen, das der PMW-Filter // das nicht unterstuetzt. Stattdessen temporaer // nur eine Warnung, bis die entsprechende // Meldung und Behandlung weiter oben eingebaut ist. // nRet = WARN_WW6_FASTSAVE_ERR; // Zum Einchecken mit neuem String: nRet = ERR_WW6_FASTSAVE_ERR; } } delete pMan; } delete pRdr; } Ww1Sprm::DeinitTab(); return nRet; } ///////////////////////////////////////////////////////////////// Shell // // Die Shell ist die Schnittstelle vom Filter zum Writer. Sie ist // abgeleitet von der mit ww-filter gemeinsam benutzten Shell // SwFltShell und enthaelt alle fuer ww1 noetigen Erweiterungen. Wie // in einen Stream werden alle Informationen, die aus der Datei // gelesen werden, in die shell ge'piped'. // Ww1Shell::Ww1Shell( SwDoc& rD, SwPaM& rPam, const String& rBaseURL, sal_Bool bNew, sal_uLong nFieldFlags) : SwFltShell(&rD, rPam, rBaseURL, bNew, nFieldFlags) { }
1,823
1,790
/* * Copyright (c) 2015, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"). You may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for * the specific language governing permissions and limitations under the * License. */ package com.cloudera.oryx.common.settings; import java.util.List; import org.junit.Test; import com.cloudera.oryx.common.OryxTest; public final class ConfigToPropertiesTest extends OryxTest { @Test public void testToProperties() { List<String> propertiesLines = ConfigToProperties.buildPropertiesLines(); assertContains(propertiesLines, "oryx.serving.api.secure-port=443"); assertNotContains(propertiesLines, "oryx.id=null"); propertiesLines.forEach(line -> assertTrue(line.startsWith("oryx."))); } }
349
2,504
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "D2DAdvancedColorImagesRenderer.h" #include "DirectXPage.xaml.h" #include "DirectXHelper.h" using namespace D2DAdvancedColorImages; using namespace concurrency; using namespace DirectX; using namespace Microsoft::WRL; using namespace Platform; using namespace std; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::UI::Input; using namespace Windows::UI::Xaml; static const float sc_MaxZoom = 1.0f; // Restrict max zoom to 1:1 scale. static const unsigned int sc_MaxBytesPerPixel = 16; // Covers all supported image formats. static const float sc_nominalRefWhite = 80.0f; // Nominal white nits for sRGB and scRGB. // 400 bins with gamma of 10 lets us measure luminance to within 10% error for any // luminance above ~1.5 nits, up to 1 million nits. static const unsigned int sc_histNumBins = 400; static const float sc_histGamma = 0.1f; static const unsigned int sc_histMaxNits = 1000000; D2DAdvancedColorImagesRenderer::D2DAdvancedColorImagesRenderer( const std::shared_ptr<DX::DeviceResources>& deviceResources ) : m_deviceResources(deviceResources), m_renderEffectKind(RenderEffectKind::None), m_zoom(1.0f), m_minZoom(1.0f), // Dynamically calculated on window size. m_imageOffset(), m_pointerPos(), m_maxCLL(-1.0f), m_brightnessAdjust(1.0f), m_imageInfo{}, m_isComputeSupported(false) { // Register to be notified if the GPU device is lost or recreated. m_deviceResources->RegisterDeviceNotify(this); CreateDeviceIndependentResources(); CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } D2DAdvancedColorImagesRenderer::~D2DAdvancedColorImagesRenderer() { // Deregister device notification. m_deviceResources->RegisterDeviceNotify(nullptr); } void D2DAdvancedColorImagesRenderer::CreateDeviceIndependentResources() { // Register the custom render effects. DX::ThrowIfFailed( ReinhardEffect::Register(m_deviceResources->GetD2DFactory()) ); DX::ThrowIfFailed( FilmicEffect::Register(m_deviceResources->GetD2DFactory()) ); DX::ThrowIfFailed( SdrOverlayEffect::Register(m_deviceResources->GetD2DFactory()) ); DX::ThrowIfFailed( LuminanceHeatmapEffect::Register(m_deviceResources->GetD2DFactory()) ); } void D2DAdvancedColorImagesRenderer::CreateDeviceDependentResources() { // All this app's device-dependent resources also depend on // the loaded image, so they are all created in // CreateImageDependentResources. } void D2DAdvancedColorImagesRenderer::ReleaseDeviceDependentResources() { } // Whenever the app window is resized or changes displays, this method is used // to update the app's sizing and advanced color state. void D2DAdvancedColorImagesRenderer::CreateWindowSizeDependentResources() { FitImageToWindow(); } // White level scale is used to multiply the color values in the image; allows the user to // adjust the brightness of the image on an HDR display. void D2DAdvancedColorImagesRenderer::SetRenderOptions( RenderEffectKind effect, float brightnessAdjustment, AdvancedColorInfo^ acInfo ) { m_dispInfo = acInfo; m_renderEffectKind = effect; m_brightnessAdjust = brightnessAdjustment; auto sdrWhite = m_dispInfo ? m_dispInfo->SdrWhiteLevelInNits : sc_nominalRefWhite; UpdateWhiteLevelScale(m_brightnessAdjust, sdrWhite); // Adjust the Direct2D effect graph based on RenderEffectKind. // Some RenderEffectKind values require us to apply brightness adjustment // after the effect as their numerical output is affected by any luminance boost. switch (m_renderEffectKind) { // Effect graph: ImageSource > ColorManagement > WhiteScale > Reinhard case RenderEffectKind::ReinhardTonemap: m_finalOutput = m_reinhardEffect.Get(); m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get()); break; // Effect graph: ImageSource > ColorManagement > WhiteScale > FilmicTonemap case RenderEffectKind::FilmicTonemap: m_finalOutput = m_filmicEffect.Get(); m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get()); break; // Effect graph: ImageSource > ColorManagement > WhiteScale case RenderEffectKind::None: m_finalOutput = m_whiteScaleEffect.Get(); m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get()); break; // Effect graph: ImageSource > ColorManagement > Heatmap > WhiteScale case RenderEffectKind::LuminanceHeatmap: m_finalOutput = m_whiteScaleEffect.Get(); m_whiteScaleEffect->SetInputEffect(0, m_heatmapEffect.Get()); break; // Effect graph: ImageSource > ColorManagement > SdrOverlay > WhiteScale case RenderEffectKind::SdrOverlay: m_finalOutput = m_whiteScaleEffect.Get(); m_whiteScaleEffect->SetInputEffect(0, m_sdrOverlayEffect.Get()); break; default: throw ref new NotImplementedException(); break; } Draw(); } // Reads the provided data stream and decodes an image from it using WIC. These resources are device- // independent. ImageInfo D2DAdvancedColorImagesRenderer::LoadImageFromWic(_In_ IStream* imageStream) { auto wicFactory = m_deviceResources->GetWicImagingFactory(); // Decode the image using WIC. ComPtr<IWICBitmapDecoder> decoder; DX::ThrowIfFailed( wicFactory->CreateDecoderFromStream( imageStream, nullptr, WICDecodeMetadataCacheOnDemand, &decoder )); ComPtr<IWICBitmapFrameDecode> frame; DX::ThrowIfFailed( decoder->GetFrame(0, &frame) ); return LoadImageCommon(frame.Get()); } // Simplified heuristic to determine what advanced color kind the image is. // Requires that all fields other than imageKind are populated. void D2DAdvancedColorImagesRenderer::PopulateImageInfoACKind(_Inout_ ImageInfo* info) { if (info->bitsPerPixel == 0 || info->bitsPerChannel == 0 || info->size.Width == 0 || info->size.Height == 0) { DX::ThrowIfFailed(E_INVALIDARG); } info->imageKind = AdvancedColorKind::StandardDynamicRange; // Bit depth > 8bpc or color gamut > sRGB signifies a WCG image. // The presence of a color profile is used as an approximation for wide gamut. if (info->bitsPerChannel > 8 || info->numProfiles >= 1) { info->imageKind = AdvancedColorKind::WideColorGamut; } // This application currently only natively supports HDR images with floating point. // An image encoded using the HDR10 colorspace is also HDR, but this // is not automatically detected by the application. if (info->isFloat == true) { info->imageKind = AdvancedColorKind::HighDynamicRange; } } // Configures a Direct2D image pipeline, including source, color management, // tonemapping, and white level, based on the loaded image. void D2DAdvancedColorImagesRenderer::CreateImageDependentResources() { auto d2dFactory = m_deviceResources->GetD2DFactory(); auto context = m_deviceResources->GetD2DDeviceContext(); // Load the image from WIC using ID2D1ImageSource. DX::ThrowIfFailed( m_deviceResources->GetD2DDeviceContext()->CreateImageSourceFromWic( m_formatConvert.Get(), &m_imageSource ) ); // Next, configure the app's effect pipeline, consisting of a color management effect // followed by a tone mapping effect. DX::ThrowIfFailed( context->CreateEffect(CLSID_D2D1ColorManagement, &m_colorManagementEffect) ); DX::ThrowIfFailed( m_colorManagementEffect->SetValue( D2D1_COLORMANAGEMENT_PROP_QUALITY, D2D1_COLORMANAGEMENT_QUALITY_BEST // Required for floating point and DXGI color space support. ) ); // The color management effect takes a source color space and a destination color space, // and performs the appropriate math to convert images between them. UpdateImageColorContext(); // The destination color space is the render target's (swap chain's) color space. This app uses an // FP16 swap chain, which requires the colorspace to be scRGB. ComPtr<ID2D1ColorContext1> destColorContext; DX::ThrowIfFailed( context->CreateColorContextFromDxgiColorSpace( DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709, // scRGB &destColorContext ) ); DX::ThrowIfFailed( m_colorManagementEffect->SetValue( D2D1_COLORMANAGEMENT_PROP_DESTINATION_COLOR_CONTEXT, destColorContext.Get() ) ); // White level scale is used to multiply the color values in the image; this allows the user // to adjust the brightness of the image on an HDR display. DX::ThrowIfFailed(context->CreateEffect(CLSID_D2D1ColorMatrix, &m_whiteScaleEffect)); // Input to white level scale may be modified in SetRenderOptions. m_whiteScaleEffect->SetInputEffect(0, m_colorManagementEffect.Get()); // Set the actual matrix in SetRenderOptions. // Instantiate and cache all of the tonemapping/render effects. // Each effect is implemented as a Direct2D custom effect; see the RenderEffects filter in the // Solution Explorer. DX::ThrowIfFailed( context->CreateEffect(CLSID_CustomReinhardEffect, &m_reinhardEffect) ); DX::ThrowIfFailed( context->CreateEffect(CLSID_CustomFilmicEffect, &m_filmicEffect) ); DX::ThrowIfFailed( context->CreateEffect(CLSID_CustomSdrOverlayEffect, &m_sdrOverlayEffect) ); DX::ThrowIfFailed( context->CreateEffect(CLSID_CustomLuminanceHeatmapEffect, &m_heatmapEffect) ); m_reinhardEffect->SetInputEffect(0, m_whiteScaleEffect.Get()); m_filmicEffect->SetInputEffect(0, m_whiteScaleEffect.Get()); // For the following effects, we want white level scale to be applied after // tonemapping (otherwise brightness adjustments will affect numerical values). m_heatmapEffect->SetInputEffect(0, m_colorManagementEffect.Get()); m_sdrOverlayEffect->SetInputEffect(0, m_colorManagementEffect.Get()); // The remainder of the Direct2D effect graph is constructed in SetRenderOptions based on the // selected RenderEffectKind. CreateHistogramResources(); } // Perform histogram pipeline setup; this should occur as part of image resource creation. // Histogram results in no visual output but is used to calculate HDR metadata for the image. void D2DAdvancedColorImagesRenderer::CreateHistogramResources() { auto context = m_deviceResources->GetD2DDeviceContext(); // We need to preprocess the image data before running the histogram. // 1. Spatial downscale to reduce the amount of processing needed. DX::ThrowIfFailed( context->CreateEffect(CLSID_D2D1Scale, &m_histogramPrescale) ); DX::ThrowIfFailed( m_histogramPrescale->SetValue(D2D1_SCALE_PROP_SCALE, D2D1::Vector2F(0.5f, 0.5f)) ); // The right place to compute HDR metadata is after color management to the // image's native colorspace but before any tonemapping or adjustments for the display. m_histogramPrescale->SetInputEffect(0, m_colorManagementEffect.Get()); // 2. Convert scRGB data into luminance (nits). // 3. Normalize color values. Histogram operates on [0-1] numeric range, // while FP16 can go up to 65504 (5+ million nits). // Both steps are performed in the same color matrix. ComPtr<ID2D1Effect> histogramMatrix; DX::ThrowIfFailed( context->CreateEffect(CLSID_D2D1ColorMatrix, &histogramMatrix) ); histogramMatrix->SetInputEffect(0, m_histogramPrescale.Get()); float scale = sc_histMaxNits / sc_nominalRefWhite; D2D1_MATRIX_5X4_F rgbtoYnorm = D2D1::Matrix5x4F( 0.2126f / scale, 0, 0, 0, 0.7152f / scale, 0, 0, 0, 0.0722f / scale, 0, 0, 0, 0 , 0, 0, 1, 0 , 0, 0, 0); // 1st column: [R] output, contains normalized Y (CIEXYZ). // 2nd column: [G] output, unused. // 3rd column: [B] output, unused. // 4th column: [A] output, alpha passthrough. // We explicitly calculate Y; this deviates from the CEA 861.3 definition of MaxCLL // which approximates luminance with max(R, G, B). DX::ThrowIfFailed(histogramMatrix->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, rgbtoYnorm)); // 4. Apply a gamma to allocate more histogram bins to lower luminance levels. ComPtr<ID2D1Effect> histogramGamma; DX::ThrowIfFailed( context->CreateEffect(CLSID_D2D1GammaTransfer, &histogramGamma) ); histogramGamma->SetInputEffect(0, histogramMatrix.Get()); // Gamma function offers an acceptable tradeoff between simplicity and efficient bin allocation. // A more sophisticated pipeline would use a more perceptually linear function than gamma. DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_RED_EXPONENT, sc_histGamma)); // All other channels are passthrough. DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_GREEN_DISABLE, TRUE)); DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_BLUE_DISABLE, TRUE)); DX::ThrowIfFailed(histogramGamma->SetValue(D2D1_GAMMATRANSFER_PROP_ALPHA_DISABLE, TRUE)); // 5. Finally, the histogram itself. HRESULT hr = context->CreateEffect(CLSID_D2D1Histogram, &m_histogramEffect); if (hr == D2DERR_INSUFFICIENT_DEVICE_CAPABILITIES) { // The GPU doesn't support compute shaders and we can't run histogram on it. m_isComputeSupported = false; } else { DX::ThrowIfFailed(hr); m_isComputeSupported = true; DX::ThrowIfFailed(m_histogramEffect->SetValue(D2D1_HISTOGRAM_PROP_NUM_BINS, sc_histNumBins)); m_histogramEffect->SetInputEffect(0, histogramGamma.Get()); } } void D2DAdvancedColorImagesRenderer::ReleaseImageDependentResources() { m_imageSource.Reset(); m_scaledImage.Reset(); m_colorManagementEffect.Reset(); m_whiteScaleEffect.Reset(); m_reinhardEffect.Reset(); m_filmicEffect.Reset(); m_sdrOverlayEffect.Reset(); m_heatmapEffect.Reset(); m_histogramPrescale.Reset(); m_histogramEffect.Reset(); m_finalOutput.Reset(); } void D2DAdvancedColorImagesRenderer::UpdateManipulationState(_In_ ManipulationUpdatedEventArgs^ args) { Point position = args->Position; Point positionDelta = args->Delta.Translation; float zoomDelta = args->Delta.Scale; m_imageOffset.x += positionDelta.X; m_imageOffset.y += positionDelta.Y; // We want to have any zoom operation be "centered" around the pointer position, which // requires recalculating the view position based on the new zoom and pointer position. // Step 1: Calculate the absolute pointer position (image position). D2D1_POINT_2F pointerAbsolutePosition = D2D1::Point2F( (m_imageOffset.x - position.X) / m_zoom, (m_imageOffset.y - position.Y) / m_zoom ); // Step 2: Apply the zoom; do not allow user to go beyond max zoom level. m_zoom *= zoomDelta; m_zoom = min(m_zoom, sc_MaxZoom); // Step 3: Adjust the view position based on the new m_zoom value. m_imageOffset.x = pointerAbsolutePosition.x * m_zoom + position.X; m_imageOffset.y = pointerAbsolutePosition.y * m_zoom + position.Y; // Step 4: Clamp the translation to the window bounds. Size panelSize = m_deviceResources->GetLogicalSize(); m_imageOffset.x = Clamp(m_imageOffset.x, panelSize.Width - m_imageInfo.size.Width * m_zoom, 0); m_imageOffset.y = Clamp(m_imageOffset.y, panelSize.Height - m_imageInfo.size.Height * m_zoom, 0); UpdateImageTransformState(); Draw(); } // Overrides any pan/zoom state set by the user to fit image to the window size. // Returns the computed MaxCLL of the image in nits. float D2DAdvancedColorImagesRenderer::FitImageToWindow() { if (m_imageSource) { Size panelSize = m_deviceResources->GetLogicalSize(); // Set image to be letterboxed in the window, up to the max allowed scale factor. float letterboxZoom = min( panelSize.Width / m_imageInfo.size.Width, panelSize.Height / m_imageInfo.size.Height); m_zoom = min(sc_MaxZoom, letterboxZoom); // Center the image. m_imageOffset = D2D1::Point2F( (panelSize.Width - (m_imageInfo.size.Width * m_zoom)) / 2.0f, (panelSize.Height - (m_imageInfo.size.Height * m_zoom)) / 2.0f ); UpdateImageTransformState(); // HDR metadata is supposed to be independent of any rendering options, but // we can't compute it until the full effect graph is hooked up, which is here. ComputeHdrMetadata(); } return m_maxCLL; } // After initial decode, obtain image information and do common setup. // Populates all members of ImageInfo. ImageInfo D2DAdvancedColorImagesRenderer::LoadImageCommon(_In_ IWICBitmapSource* source) { auto wicFactory = m_deviceResources->GetWicImagingFactory(); m_imageInfo = {}; // Attempt to read the embedded color profile from the image; only valid for WIC images. ComPtr<IWICBitmapFrameDecode> frame; if (SUCCEEDED(source->QueryInterface(IID_PPV_ARGS(&frame)))) { DX::ThrowIfFailed( wicFactory->CreateColorContext(&m_wicColorContext) ); DX::ThrowIfFailed( frame->GetColorContexts( 1, m_wicColorContext.GetAddressOf(), &m_imageInfo.numProfiles ) ); } // Check whether the image data is natively stored in a floating-point format, and // decode to the appropriate WIC pixel format. WICPixelFormatGUID pixelFormat; DX::ThrowIfFailed( source->GetPixelFormat(&pixelFormat) ); ComPtr<IWICComponentInfo> componentInfo; DX::ThrowIfFailed( wicFactory->CreateComponentInfo( pixelFormat, &componentInfo ) ); ComPtr<IWICPixelFormatInfo2> pixelFormatInfo; DX::ThrowIfFailed( componentInfo.As(&pixelFormatInfo) ); WICPixelFormatNumericRepresentation formatNumber; DX::ThrowIfFailed( pixelFormatInfo->GetNumericRepresentation(&formatNumber) ); DX::ThrowIfFailed(pixelFormatInfo->GetBitsPerPixel(&m_imageInfo.bitsPerPixel)); // Calculate the bits per channel (bit depth) using GetChannelMask. // This accounts for nonstandard color channel packing and padding, e.g. 32bppRGB. unsigned char channelMaskBytes[sc_MaxBytesPerPixel]; ZeroMemory(channelMaskBytes, ARRAYSIZE(channelMaskBytes)); unsigned int maskSize; DX::ThrowIfFailed( pixelFormatInfo->GetChannelMask( 0, // Read the first color channel. ARRAYSIZE(channelMaskBytes), channelMaskBytes, &maskSize) ); // Count up the number of bits set in the mask for the first color channel. for (unsigned int i = 0; i < maskSize * 8; i++) { unsigned int byte = i / 8; unsigned int bit = i % 8; if ((channelMaskBytes[byte] & (1 << bit)) != 0) { m_imageInfo.bitsPerChannel += 1; } } m_imageInfo.isFloat = (WICPixelFormatNumericRepresentationFloat == formatNumber) ? true : false; // When decoding, preserve the numeric representation (float vs. non-float) // of the native image data. This avoids WIC performing an implicit gamma conversion // which occurs when converting between a fixed-point/integer pixel format (sRGB gamma) // and a float-point pixel format (linear gamma). Gamma adjustment, if specified by // the ICC profile, will be performed by the Direct2D color management effect. WICPixelFormatGUID fmt = {}; if (m_imageInfo.isFloat) { fmt = GUID_WICPixelFormat64bppPRGBAHalf; // Equivalent to DXGI_FORMAT_R16G16B16A16_FLOAT. } else { fmt = GUID_WICPixelFormat64bppPRGBA; // Equivalent to DXGI_FORMAT_R16G16B16A16_UNORM. // Many SDR images (e.g. JPEG) use <=32bpp, so it // is possible to further optimize this for memory usage. } DX::ThrowIfFailed( wicFactory->CreateFormatConverter(&m_formatConvert) ); DX::ThrowIfFailed( m_formatConvert->Initialize( source, fmt, WICBitmapDitherTypeNone, nullptr, 0.0f, WICBitmapPaletteTypeCustom ) ); UINT width; UINT height; DX::ThrowIfFailed( m_formatConvert->GetSize(&width, &height) ); m_imageInfo.size = Size(static_cast<float>(width), static_cast<float>(height)); PopulateImageInfoACKind(&m_imageInfo); return m_imageInfo; } // Derive the source color context from the image (embedded ICC profile or metadata). void D2DAdvancedColorImagesRenderer::UpdateImageColorContext() { auto context = m_deviceResources->GetD2DDeviceContext(); ComPtr<ID2D1ColorContext> sourceColorContext; // For most image types, automatically derive the color context from the image. if (m_imageInfo.numProfiles >= 1) { DX::ThrowIfFailed( context->CreateColorContextFromWicColorContext( m_wicColorContext.Get(), &sourceColorContext ) ); } else { // Since no embedded color profile/metadata exists, select a default // based on the pixel format: floating point == scRGB, others == sRGB. DX::ThrowIfFailed( context->CreateColorContext( m_imageInfo.isFloat ? D2D1_COLOR_SPACE_SCRGB : D2D1_COLOR_SPACE_SRGB, nullptr, 0, &sourceColorContext ) ); } DX::ThrowIfFailed( m_colorManagementEffect->SetValue( D2D1_COLORMANAGEMENT_PROP_SOURCE_COLOR_CONTEXT, sourceColorContext.Get() ) ); } // When connected to an HDR display, the OS renders SDR content (e.g. 8888 UNORM) at // a user configurable white level; this typically is around 200-300 nits. It is the responsibility // of an advanced color app (e.g. FP16 scRGB) to emulate the OS-implemented SDR white level adjustment, // BUT only for non-HDR content (SDR or WCG). void D2DAdvancedColorImagesRenderer::UpdateWhiteLevelScale(float brightnessAdjustment, float sdrWhiteLevel) { float scale = 1.0f; switch (m_imageInfo.imageKind) { case AdvancedColorKind::HighDynamicRange: // HDR content should not be compensated by the SdrWhiteLevel parameter. scale = 1.0f; break; case AdvancedColorKind::StandardDynamicRange: case AdvancedColorKind::WideColorGamut: default: scale = sdrWhiteLevel / sc_nominalRefWhite; break; } // The user may want to manually adjust brightness specifically for this image, on top of any // white level adjustment for SDR/WCG content. Brightness adjustment using a linear gamma scale // is mainly useful for HDR displays, but can be useful for HDR content tonemapped to an SDR/WCG display. scale *= brightnessAdjustment; // SDR white level scaling is performing by multiplying RGB color values in linear gamma. // We implement this with a Direct2D matrix effect. D2D1_MATRIX_5X4_F matrix = D2D1::Matrix5x4F( scale, 0, 0, 0, // [R] Multiply each color channel 0, scale, 0, 0, // [G] by the scale factor in 0, 0, scale, 0, // [B] linear gamma space. 0, 0, 0 , 1, // [A] Preserve alpha values. 0, 0, 0 , 0); // No offset. DX::ThrowIfFailed(m_whiteScaleEffect->SetValue(D2D1_COLORMATRIX_PROP_COLOR_MATRIX, matrix)); } // Call this after updating any spatial transform state to regenerate the effect graph. void D2DAdvancedColorImagesRenderer::UpdateImageTransformState() { if (m_imageSource) { // When using ID2D1ImageSource, the recommend method of scaling is to use // ID2D1TransformedImageSource. It is inexpensive to recreate this object. D2D1_TRANSFORMED_IMAGE_SOURCE_PROPERTIES props = { D2D1_ORIENTATION_DEFAULT, m_zoom, m_zoom, D2D1_INTERPOLATION_MODE_LINEAR, // This is ignored when using DrawImage. D2D1_TRANSFORMED_IMAGE_SOURCE_OPTIONS_NONE }; DX::ThrowIfFailed( m_deviceResources->GetD2DDeviceContext()->CreateTransformedImageSource( m_imageSource.Get(), &props, &m_scaledImage ) ); // Set the new image as the new source to the effect pipeline. m_colorManagementEffect->SetInput(0, m_scaledImage.Get()); } } // Uses a histogram to compute a modified version of MaxCLL (ST.2086 max content light level). // Performs Begin/EndDraw on the D2D context. void D2DAdvancedColorImagesRenderer::ComputeHdrMetadata() { // Initialize with a sentinel value. m_maxCLL = -1.0f; // MaxCLL is not meaningful for SDR or WCG images. if ((!m_isComputeSupported) || (m_imageInfo.imageKind != AdvancedColorKind::HighDynamicRange)) { return; } // MaxCLL is nominally calculated for the single brightest pixel in a frame. // But we take a slightly more conservative definition that takes the 99.99th percentile // to account for extreme outliers in the image. float maxCLLPercent = 0.9999f; auto ctx = m_deviceResources->GetD2DDeviceContext(); ctx->BeginDraw(); ctx->DrawImage(m_histogramEffect.Get()); // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device // is lost. It will be handled during the next call to Present. HRESULT hr = ctx->EndDraw(); if (hr != D2DERR_RECREATE_TARGET) { DX::ThrowIfFailed(hr); } float *histogramData = new float[sc_histNumBins]; DX::ThrowIfFailed( m_histogramEffect->GetValue(D2D1_HISTOGRAM_PROP_HISTOGRAM_OUTPUT, reinterpret_cast<BYTE*>(histogramData), sc_histNumBins * sizeof(float) ) ); unsigned int maxCLLbin = 0; float runningSum = 0.0f; // Cumulative sum of values in histogram is 1.0. for (int i = sc_histNumBins - 1; i >= 0; i--) { runningSum += histogramData[i]; maxCLLbin = i; if (runningSum >= 1.0f - maxCLLPercent) { break; } } float binNorm = static_cast<float>(maxCLLbin) / static_cast<float>(sc_histNumBins); m_maxCLL = powf(binNorm, 1 / sc_histGamma) * sc_histMaxNits; // Some drivers have a bug where histogram will always return 0. Treat this as unknown. m_maxCLL = (m_maxCLL == 0.0f) ? -1.0f : m_maxCLL; } // Set HDR10 metadata to allow HDR displays to optimize behavior based on our content. void D2DAdvancedColorImagesRenderer::EmitHdrMetadata() { auto acKind = m_dispInfo ? m_dispInfo->CurrentAdvancedColorKind : AdvancedColorKind::StandardDynamicRange; if (acKind == AdvancedColorKind::HighDynamicRange) { DXGI_HDR_METADATA_HDR10 metadata = {}; // This sample doesn't do any chrominance (e.g. xy) gamut mapping, so just use default // color primaries values; a more sophisticated app will explicitly set these. // DXGI_HDR_METADATA_HDR10 defines primaries as 1/50000 of a unit in xy space. metadata.RedPrimary[0] = static_cast<UINT16>(m_dispInfo->RedPrimary.X * 50000.0f); metadata.RedPrimary[1] = static_cast<UINT16>(m_dispInfo->RedPrimary.Y * 50000.0f); metadata.GreenPrimary[0] = static_cast<UINT16>(m_dispInfo->GreenPrimary.X * 50000.0f); metadata.GreenPrimary[1] = static_cast<UINT16>(m_dispInfo->GreenPrimary.Y * 50000.0f); metadata.BluePrimary[0] = static_cast<UINT16>(m_dispInfo->BluePrimary.X * 50000.0f); metadata.BluePrimary[1] = static_cast<UINT16>(m_dispInfo->BluePrimary.Y * 50000.0f); metadata.WhitePoint[0] = static_cast<UINT16>(m_dispInfo->WhitePoint.X * 50000.0f); metadata.WhitePoint[1] = static_cast<UINT16>(m_dispInfo->WhitePoint.Y * 50000.0f); float effectiveMaxCLL = 0; switch (m_renderEffectKind) { // Currently only the "None" render effect results in pixel values that exceed // the OS-specified SDR white level, as it just passes through HDR color values. case RenderEffectKind::None: effectiveMaxCLL = max(m_maxCLL, 0.0f) * m_brightnessAdjust; break; default: effectiveMaxCLL = m_dispInfo->SdrWhiteLevelInNits * m_brightnessAdjust; break; } // DXGI_HDR_METADATA_HDR10 defines MaxCLL in integer nits. metadata.MaxContentLightLevel = static_cast<UINT16>(effectiveMaxCLL); // The luminance analysis doesn't calculate MaxFrameAverageLightLevel. We also don't have mastering // information (i.e. reference display in a studio), so Min/MaxMasteringLuminance is not relevant. // Leave these values as 0. auto sc = m_deviceResources->GetSwapChain(); ComPtr<IDXGISwapChain4> sc4; DX::ThrowIfFailed(sc->QueryInterface(IID_PPV_ARGS(&sc4))); DX::ThrowIfFailed(sc4->SetHDRMetaData(DXGI_HDR_METADATA_TYPE_HDR10, sizeof(metadata), &metadata)); } } // Renders the loaded image with user-specified options. void D2DAdvancedColorImagesRenderer::Draw() { auto d2dContext = m_deviceResources->GetD2DDeviceContext(); d2dContext->BeginDraw(); d2dContext->Clear(D2D1::ColorF(D2D1::ColorF::Black)); d2dContext->SetTransform(m_deviceResources->GetOrientationTransform2D()); if (m_scaledImage) { d2dContext->DrawImage(m_finalOutput.Get(), m_imageOffset); EmitHdrMetadata(); } // We ignore D2DERR_RECREATE_TARGET here. This error indicates that the device // is lost. It will be handled during the next call to Present. HRESULT hr = d2dContext->EndDraw(); if (hr != D2DERR_RECREATE_TARGET) { DX::ThrowIfFailed(hr); } m_deviceResources->Present(); } // Notifies renderers that device resources need to be released. void D2DAdvancedColorImagesRenderer::OnDeviceLost() { ReleaseImageDependentResources(); ReleaseDeviceDependentResources(); } // Notifies renderers that device resources may now be recreated. void D2DAdvancedColorImagesRenderer::OnDeviceRestored() { CreateDeviceDependentResources(); CreateImageDependentResources(); CreateWindowSizeDependentResources(); Draw(); }
13,038
1,719
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.retry.stats; import static org.junit.Assert.assertEquals; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.retry.RetryContext; import org.springframework.retry.RetryStatistics; import org.springframework.retry.annotation.CircuitBreaker; import org.springframework.retry.annotation.EnableRetry; import org.springframework.retry.annotation.Recover; import org.springframework.retry.support.RetrySynchronizationManager; /** * @author <NAME> * */ public class CircuitBreakerInterceptorStatisticsTests { private static final String RECOVERED = "RECOVERED"; private static final String RESULT = "RESULT"; private Service callback; private StatisticsRepository repository; private AnnotationConfigApplicationContext context; @Before public void init() { context = new AnnotationConfigApplicationContext(TestConfiguration.class); this.callback = context.getBean(Service.class); this.repository = context.getBean(StatisticsRepository.class); this.callback.setAttemptsBeforeSuccess(1); } @After public void close() { if (context != null) { context.close(); } } @Test public void testCircuitOpenWhenNotRetryable() throws Throwable { Object result = callback.service("one"); RetryStatistics stats = repository.findOne("test"); // System.err.println(stats); assertEquals(1, stats.getStartedCount()); assertEquals(RECOVERED, result); result = callback.service("two"); assertEquals(RECOVERED, result); assertEquals("There should be two recoveries", 2, stats.getRecoveryCount()); assertEquals("There should only be one error because the circuit is now open", 1, stats.getErrorCount()); } @Configuration @EnableRetry protected static class TestConfiguration { @Bean public StatisticsRepository repository() { return new DefaultStatisticsRepository(); } @Bean public StatisticsListener listener(StatisticsRepository repository) { return new StatisticsListener(repository); } @Bean public Service service() { return new Service(); } } protected static class Service { private int attemptsBeforeSuccess; private Exception exceptionToThrow = new Exception(); private RetryContext status; @CircuitBreaker(label = "test", maxAttempts = 1) public Object service(String input) throws Exception { this.status = RetrySynchronizationManager.getContext(); Integer attempts = (Integer) status.getAttribute("attempts"); if (attempts == null) { attempts = 0; } attempts++; this.status.setAttribute("attempts", attempts); if (attempts <= this.attemptsBeforeSuccess) { throw this.exceptionToThrow; } return RESULT; } @Recover public Object recover() { this.status.setAttribute(RECOVERED, true); return RECOVERED; } public boolean isOpen() { return this.status != null && this.status.getAttribute("open") == Boolean.TRUE; } public void setAttemptsBeforeSuccess(int attemptsBeforeSuccess) { this.attemptsBeforeSuccess = attemptsBeforeSuccess; } public void setExceptionToThrow(Exception exceptionToThrow) { this.exceptionToThrow = exceptionToThrow; } } }
1,212
1,117
<reponame>imloama/radar package com.pgmmers.radar.service.engine; import com.pgmmers.radar.vo.model.PreItemVO; import java.util.Map; import java.util.StringJoiner; public interface PluginServiceV2 { default String pluginName() { return this.getClass().getSimpleName(); } Integer key(); String desc(); String getType(); default String getMeta() { return null; } Object handle(PreItemVO item, Map<String, Object> jsonInfo, String[] sourceField); default String info() { return new StringJoiner(", ", this.getClass().getSimpleName() + "[", "]") .add("key='" + key() + "'") .add("desc='" + desc() + "'") .add("type='" + getType() + "'") .add("meta='" + getMeta() + "'") .toString(); } }
362
2,542
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once #include "../tstore/TestStateSerializer.h" #define RCQ_TAG 'rtCQ' namespace Data { using namespace TStore; namespace Collections { // // Start with 512 slots and we'll double in every new segment // In debug we start with 4 to exercise the path more often // #ifdef _DEBUG #define QUEUE_SEGMENT_START_SIZE 0x4 #else #define QUEUE_SEGMENT_START_SIZE 0x200 #endif // // Maximum is 64K slots (=65536) // If it is too large in rare race conditions the duplicate segment initialization may take too long // Of course, this needs to be measured // In debug we use a small-ish number to force creating more segments (and smaller) and flush out // issues // #ifdef _DEBUG #define QUEUE_SEGMENT_MAX_SIZE 0x10 #else #define QUEUE_SEGMENT_MAX_SIZE 0x10000 #endif template <typename TValue> class ReliableConcurrentQueue : public TStore::Store<LONG64, TValue> , public IReliableConcurrentQueue<TValue> { K_FORCE_SHARED(ReliableConcurrentQueue) K_SHARED_INTERFACE_IMP(IReliableConcurrentQueue) public: using typename TStore::Store<LONG64, TValue>::HashFunctionType; static NTSTATUS Create( __in KAllocator& allocator, __in PartitionedReplicaId const & traceId, __in KUriView & name, __in FABRIC_STATE_PROVIDER_ID stateProviderId, __in Data::StateManager::IStateSerializer<TValue>& valueStateSerializer, __out SPtr & result); ktl::Awaitable<void> EnqueueAsync( __in TxnReplicator::TransactionBase& replicatorTransaction, __in TValue value, __in Common::TimeSpan timeout, __in ktl::CancellationToken const & cancellationToken) override; ktl::Awaitable<bool> TryDequeueAsync( __in TxnReplicator::TransactionBase& replicatorTransaction, __out TValue& value, __in Common::TimeSpan timeout, __in ktl::CancellationToken const & cancellationToken) override; LONG64 GetQueueCount() const override { return this->Count; } ConcurrentQueue<LONG64> &GetInternalQueue() { return *queue_; } private: // // Forwards Store Add/Remove events to the queue // class DictionaryChangeForwarder : public KObject<DictionaryChangeForwarder> , public KShared<DictionaryChangeForwarder> , public IDictionaryChangeHandler<LONG64, TValue> { K_FORCE_SHARED(DictionaryChangeForwarder); K_SHARED_INTERFACE_IMP(IDictionaryChangeHandler); public: static HRESULT Create( __in KAllocator& allocator, __in ReliableConcurrentQueue<TValue> *queue, __out typename DictionaryChangeForwarder::SPtr& result) { DictionaryChangeForwarder* pointer = _new(RCQ_TAG, allocator) DictionaryChangeForwarder(queue); if (!pointer) { return E_OUTOFMEMORY; } result = pointer; return S_OK; } public : // // IDictionaryChangeHandler methods // ktl::Awaitable<void> OnAddedAsync( __in TxnReplicator::TransactionBase const& replicatorTransaction, __in LONG64 key, __in TValue value, __in LONG64 sequenceNumber, __in bool isPrimary) noexcept { UNREFERENCED_PARAMETER(replicatorTransaction); UNREFERENCED_PARAMETER(sequenceNumber); UNREFERENCED_PARAMETER(value); queue_->OnAddedAsyncCallback(key, isPrimary); co_return; } ktl::Awaitable<void> OnUpdatedAsync( __in TxnReplicator::TransactionBase const& replicatorTransaction, __in LONG64 key, __in TValue value, __in LONG64 sequenceNumber, __in bool isPrimary) noexcept { UNREFERENCED_PARAMETER(replicatorTransaction); UNREFERENCED_PARAMETER(sequenceNumber); UNREFERENCED_PARAMETER(key); UNREFERENCED_PARAMETER(value); UNREFERENCED_PARAMETER(isPrimary); CODING_ASSERT("Should never receive OnUpdatedAsync events in queue"); } ktl::Awaitable<void> OnRemovedAsync( __in TxnReplicator::TransactionBase const& replicatorTransaction, __in LONG64 key, __in LONG64 sequenceNumber, __in bool isPrimary) noexcept { UNREFERENCED_PARAMETER(replicatorTransaction); UNREFERENCED_PARAMETER(sequenceNumber); queue_->OnRemovedAsyncCallback(key, isPrimary); co_return; } ktl::Awaitable<void> OnRebuiltAsync(__in Utilities::IAsyncEnumerator<KeyValuePair<LONG64, KeyValuePair<LONG64, TValue>>> & enumerableState) noexcept { UNREFERENCED_PARAMETER(enumerableState); CODING_ASSERT("Should never receive OnRebuildAsync event in queue as it is masked"); } private: DictionaryChangeForwarder(__in ReliableConcurrentQueue<TValue> *queue) { queue_ = queue; } private: // Use raw pointer to avoid cycles - queue derives from store which sends the notifications // so they have the same lifetime ReliableConcurrentQueue<TValue> *queue_; }; // // Forwards Unlock events from StoreTransaction to queue // class QueueTransaction : public StoreTransaction<LONG64, TValue> { K_FORCE_SHARED(QueueTransaction) public: static NTSTATUS Create( __in TxnReplicator::IStateProvider2 *stateProvider, __in LONG64 id, __in TxnReplicator::TransactionBase& replicatorTransaction, __in LONG64 owner, __in ConcurrentDictionary2<LONG64, KSharedPtr<StoreTransaction<LONG64, TValue>>>& container, __in IComparer<LONG64>& keyComparer, __in StoreTraceComponent & traceComponent, __in KAllocator& allocator, __out SPtr& result) { NTSTATUS status; SPtr output = _new(STORETRANSACTION_TAG, allocator) QueueTransaction(stateProvider, id, replicatorTransaction, owner, container, keyComparer, traceComponent); if (!output) { status = STATUS_INSUFFICIENT_RESOURCES; return status; } status = output->Status(); if (!NT_SUCCESS(status)) { return status; } result = Ktl::Move(output); return STATUS_SUCCESS; } QueueTransaction( __in TxnReplicator::IStateProvider2 *stateProvider, __in LONG64 id, __in TxnReplicator::TransactionBase& transaction, __in LONG64 owner, __in ConcurrentDictionary2<LONG64, KSharedPtr<StoreTransaction<LONG64, TValue>>>& container, __in IComparer<LONG64> & keyComparer, __in StoreTraceComponent & traceComponent) :StoreTransaction<LONG64, TValue>(id, transaction, owner, container, keyComparer, traceComponent), stateProviderSPtr_(stateProvider) { } protected: void OnClearLocks() override { typename ReliableConcurrentQueue<TValue>::SPtr rcqSPtr = static_cast<ReliableConcurrentQueue<TValue> *>(stateProviderSPtr_.RawPtr()); rcqSPtr->OnUnlockedCallback(*this); } private : typename TxnReplicator::IStateProvider2::SPtr stateProviderSPtr_; }; private: void OnAddedAsyncCallback(LONG64 key, bool isPrimary) { // For both primary & secondary UNREFERENCED_PARAMETER(isPrimary); if (!isPrimary) { // Make sure ID is up-to-date UpdateId(key); } NTSTATUS status = queue_->Enqueue(key); if (!NT_SUCCESS(status)) { throw ktl::Exception(status); } } void OnRemovedAsyncCallback(LONG64 key, bool isPrimary) { UNREFERENCED_PARAMETER(key); if (isPrimary) { // do nothing in primary - dequeue happens immediately in transaction so in commit // we have nothing to do } else { // in secondary / recovery, we need to mutate the in-memory data structure // note that apply for different transactions may be coming in in parallel which means // we need to remove that specific key instead of dequeue // This unfortunately introduces "gaps" which we'll need to handle as well NTSTATUS status = queue_->Remove(key); if (!NT_SUCCESS(status)) { throw ktl::Exception(status); } } } void OnRecoverKeyCallback(__in LONG64 key, __in VersionedItem<TValue>& value) override { // STORE_ASSERT(value->GetRecordKind() == RecordKind::InsertedVersion, "Should only see InsertedValue in recovery", value->GetRecordKind()); if (value.GetRecordKind() == RecordKind::InsertedVersion) { // Make sure ID is up-to-date UpdateId(key); NTSTATUS status = queue_->Enqueue(key); if (!NT_SUCCESS(status)) { throw ktl::Exception(status); } } } void UpdateId(LONG64 newId) { while (true) { LONG64 curId = id_; // We've already past that if (curId >= newId) break; // Otherwise, increase to that ID if (InterlockedCompareExchange64(&id_, newId, curId) == curId) { break; } } } void OnUnlockedCallback(__in StoreTransaction<LONG64, TValue> &storeTransaction) { KSharedPtr<WriteSetStoreComponent<LONG64, TValue>> component = storeTransaction.GetComponent(this->GetFunc()); NTSTATUS status; auto enumerator = component->GetEnumerator(); while (enumerator->MoveNext()) { auto kv = enumerator->Current(); auto key = kv.Key; auto versionedItem = kv.Value.LatestValue; if (versionedItem->GetRecordKind() == RecordKind::DeletedVersion && versionedItem->GetVersionSequenceNumber() == 0) { // Dequeue that haven't yet been applied (otherwise it would have a valid version sequence number) // Abort the dequeue by enqueuing the ID status = queue_->Enqueue(key); if (!NT_SUCCESS(status)) { throw ktl::Exception(status); } } } } protected: NTSTATUS OnCreateStoreTransaction( __in LONG64 id, __in TxnReplicator::TransactionBase& transaction, __in LONG64 owner, __in ConcurrentDictionary2<LONG64, KSharedPtr<StoreTransaction<LONG64, TValue>>>& container, __in IComparer<LONG64> & keyComparer, __out typename StoreTransaction<LONG64, TValue>::SPtr& result) override { typename QueueTransaction::SPtr ptr; NTSTATUS status = QueueTransaction::Create(this, id, transaction, owner, container, keyComparer, *this->TraceComponent, this->GetThisAllocator(), ptr); if (!NT_SUCCESS(status)) { return status; } result = ptr.RawPtr(); return status; } private: FAILABLE ReliableConcurrentQueue( __in PartitionedReplicaId const & traceId, __in IComparer<LONG64>& keyComparer, __in HashFunctionType func, __in KUriView& name, __in FABRIC_STATE_PROVIDER_ID stateProviderId, __in Data::StateManager::IStateSerializer<LONG64>& keyStateSerializer, __in Data::StateManager::IStateSerializer<TValue>& valueStateSerializer); private: #pragma region IStateProviderInfo implementation StateProviderKind GetKind() const override { return StateProviderKind::ConcurrentQueue; } #pragma endregion private: LONG64 id_; typename ConcurrentQueue<LONG64>::SPtr queue_; typename DictionaryChangeForwarder::SPtr dictionaryChangeForwarder_; private: LONG64 GetNextId(); }; template <typename TValue> ReliableConcurrentQueue<TValue>::QueueTransaction::~QueueTransaction() {} template <typename TValue> ReliableConcurrentQueue<TValue>::DictionaryChangeForwarder::~DictionaryChangeForwarder() {} template <typename TValue> NTSTATUS ReliableConcurrentQueue<TValue>::Create( __in KAllocator &allocator, __in PartitionedReplicaId const & traceId, __in KUriView & name, __in FABRIC_STATE_PROVIDER_ID stateProviderId, __in Data::StateManager::IStateSerializer<TValue>& valueStateSerializer, __out SPtr & result) { NTSTATUS status; KSharedPtr<LongComparer> keyComparerSPtr = nullptr; LongComparer::Create(allocator, keyComparerSPtr); KSharedPtr<TStoreTests::TestStateSerializer<LONG64>> keySerializerSPtr = nullptr; status = TStoreTests::TestStateSerializer<LONG64>::Create(allocator, keySerializerSPtr); if (!NT_SUCCESS(status)) { return status; } SPtr output = _new(RCQ_TAG, allocator) ReliableConcurrentQueue(traceId, *keyComparerSPtr, K_DefaultHashFunction, name, stateProviderId, *keySerializerSPtr, valueStateSerializer); if (!output) { return STATUS_INSUFFICIENT_RESOURCES; } status = output->Status(); if (!NT_SUCCESS(status)) { return status; } result = Ktl::Move(output); return STATUS_SUCCESS; } #pragma region IReliableConcurrentQueue implementation template <typename TValue> ktl::Awaitable<void> ReliableConcurrentQueue<TValue>::EnqueueAsync( __in TxnReplicator::TransactionBase& replicatorTransaction, __in TValue value, __in Common::TimeSpan timeout, __in ktl::CancellationToken const & cancellationToken) { ApiEntry(); KSharedPtr<IStoreTransaction<LONG64, TValue>> storeTransaction = nullptr; this->CreateOrFindTransaction(replicatorTransaction, storeTransaction); LONG64 id = GetNextId(); // Add into store - only when apply comes we'll put the items into queue co_await this->AddAsync(*storeTransaction, id, value, timeout, cancellationToken); } template <typename TValue> ktl::Awaitable<bool> ReliableConcurrentQueue<TValue>::TryDequeueAsync( __in TxnReplicator::TransactionBase& replicatorTransaction, __out TValue& value, __in Common::TimeSpan timeout, __in ktl::CancellationToken const & cancellationToken) { ApiEntry(); KSharedPtr<IStoreTransaction<LONG64, TValue>> storeTransaction = nullptr; this->CreateOrFindTransaction(replicatorTransaction, storeTransaction); LONG64 current; bool succeeded; NTSTATUS status = queue_->TryDequeue(current, succeeded); if (!NT_SUCCESS(status)) { throw ktl::Exception(status); } if (!succeeded) { // @TODO - Implement "Read your own write" by inspecting WriteSet // However this means we'll also have a small in-memory queue here to properly keep track // of status of each item. We can do it in a future release co_return false; } KeyValuePair<LONG64, TValue> result; // @TODO - Merge these two calls into one call // Retrieve the value bool gotValue = co_await this->ConditionalGetAsync(*storeTransaction, current, timeout, result, cancellationToken); ASSERT_IFNOT(gotValue, "nRCQ: ConditionalGetAsync should always succeed"); // Remove the item bool removed = co_await this->ConditionalRemoveAsync(*storeTransaction, current, timeout, cancellationToken); ASSERT_IFNOT(removed, "nRCQ: ConditionalRemoveAsync should always succeed"); value = result.Value; co_return true; } #pragma endregion IReliableConcurrentQueue implementation template <typename TValue> LONG64 ReliableConcurrentQueue<TValue>::GetNextId() { return InterlockedIncrement64((LONG64 *)&id_); } template <typename TValue> ReliableConcurrentQueue<TValue>::ReliableConcurrentQueue() : id_(0) { } template <typename TValue> ReliableConcurrentQueue<TValue>::ReliableConcurrentQueue( __in PartitionedReplicaId const & traceId, __in IComparer<LONG64>& keyComparer, __in HashFunctionType func, __in KUriView& name, __in FABRIC_STATE_PROVIDER_ID stateProviderId, __in Data::StateManager::IStateSerializer<LONG64>& keyStateSerializer, __in Data::StateManager::IStateSerializer<TValue>& valueStateSerializer) : TStore::Store<LONG64, TValue>(traceId, keyComparer, func, name, stateProviderId, keyStateSerializer, valueStateSerializer) , id_(0) { NTSTATUS status; status = ConcurrentQueue<LONG64>::Create(this->GetThisAllocator(), QUEUE_SEGMENT_START_SIZE, QUEUE_SEGMENT_MAX_SIZE, queue_); if (!NT_SUCCESS(status)) { this->SetConstructorStatus(status); return; } status = DictionaryChangeForwarder::Create(this->GetThisAllocator(), this, dictionaryChangeForwarder_); if (!NT_SUCCESS(status)) { this->SetConstructorStatus(status); return; } this->set_DictionaryChangeHandler(dictionaryChangeForwarder_.RawPtr()); // Only need Add/Remove. Not going to receive Update ever. Don't want Rebuilt events as we have // a special override that doesn't aggressively load values this->set_DictionaryChangeHandlerMask(static_cast<DictionaryChangeEventMask::Enum>(DictionaryChangeEventMask::Add | DictionaryChangeEventMask::Remove)); } template <typename TValue> ReliableConcurrentQueue<TValue>::~ReliableConcurrentQueue() { } } }
11,086
1,144
/* * #%L * de.metas.shipper.gateway.dhl * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package de.metas.shipper.gateway.dhl; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import de.metas.location.CountryCode; import de.metas.mpackage.PackageId; import de.metas.shipper.gateway.dhl.model.DhlCustomDeliveryData; import de.metas.shipper.gateway.dhl.model.DhlCustomDeliveryDataDetail; import de.metas.shipper.gateway.dhl.model.DhlSequenceNumber; import de.metas.shipper.gateway.dhl.model.DhlShipperProduct; import de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrder; import de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest; import de.metas.shipper.gateway.spi.DeliveryOrderId; import de.metas.shipper.gateway.spi.DeliveryOrderRepository; import de.metas.shipper.gateway.spi.model.Address; import de.metas.shipper.gateway.spi.model.ContactPerson; import de.metas.shipper.gateway.spi.model.DeliveryOrder; import de.metas.shipper.gateway.spi.model.DeliveryPosition; import de.metas.shipper.gateway.spi.model.PackageDimensions; import de.metas.shipper.gateway.spi.model.PickupDate; import de.metas.shipping.ShipperId; import de.metas.shipping.model.ShipperTransportationId; import de.metas.util.Check; import de.metas.util.Services; import lombok.NonNull; import org.adempiere.ad.dao.IQueryBL; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.lang.ITableRecordReference; import org.adempiere.util.lang.impl.TableRecordReference; import org.springframework.stereotype.Repository; import java.math.BigDecimal; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List; @Repository public class DhlDeliveryOrderRepository implements DeliveryOrderRepository { @Override public String getShipperGatewayId() { return DhlConstants.SHIPPER_GATEWAY_ID; } @NonNull @Override public ITableRecordReference toTableRecordReference(@NonNull final DeliveryOrder deliveryOrder) { final DeliveryOrderId deliveryOrderRepoId = deliveryOrder.getId(); Check.assumeNotNull(deliveryOrderRepoId, "DeliveryOrder ID must not be null for deliveryOrder " + deliveryOrder); return TableRecordReference.of(I_DHL_ShipmentOrderRequest.Table_Name, deliveryOrderRepoId); } @NonNull @Override public DeliveryOrder getByRepoId(@NonNull final DeliveryOrderId deliveryOrderRepoId) { final I_DHL_ShipmentOrderRequest dhlShipmentOrderRequest = InterfaceWrapperHelper.load(deliveryOrderRepoId, I_DHL_ShipmentOrderRequest.class); Check.assumeNotNull(dhlShipmentOrderRequest, "DHL delivery order must exist for ID={}", deliveryOrderRepoId); return toDeliveryOrderFromPO(dhlShipmentOrderRequest); } /** * Explanation of the different data structures: * <p> * - DeliveryOrder is the DTO * - I_DHL_ShipmentOrderRequest is the persisted object for that DTO with data relevant for DHL. * Each different shipper has its own "shipper-PO" with its own relevant data. */ @NonNull @Override public DeliveryOrder save(@NonNull final DeliveryOrder deliveryOrder) { if (deliveryOrder.getId() != null) { updateShipmentOrderRequestPO(deliveryOrder); return deliveryOrder; } else { final I_DHL_ShipmentOrderRequest orderRequestPO = createShipmentOrderRequestPO(deliveryOrder); return deliveryOrder .toBuilder() .id(DeliveryOrderId.ofRepoId(orderRequestPO.getDHL_ShipmentOrderRequest_ID())) .build(); } } /** * Read the DHL specific PO and return a DTO. * <p> * keep in sync with {@link #createShipmentOrderRequestPO(DeliveryOrder)} and {@link DhlDraftDeliveryOrderCreator#createDraftDeliveryOrder(de.metas.shipper.gateway.spi.DraftDeliveryOrderCreator.CreateDraftDeliveryOrderRequest)} */ @NonNull private DeliveryOrder toDeliveryOrderFromPO(@NonNull final I_DHL_ShipmentOrderRequest requestPo) { final List<I_DHL_ShipmentOrder> ordersPo = getAllShipmentOrdersForRequest(requestPo.getDHL_ShipmentOrderRequest_ID()); final I_DHL_ShipmentOrder firstOrder = ordersPo.get(0); final ImmutableList<DhlCustomDeliveryDataDetail> dhlCustomDeliveryDataDetail = ordersPo.stream() .map(po -> { // DhlCustomsDocument customsDocument = null; // if (po.isInternationalDelivery()) // { // customsDocument = DhlCustomsDocument.builder() // .exportType(po.getExportType()) // .exportTypeDescription(po.getExportTypeDescription()) // .additionalFee(po.getAdditionalFee()) // .electronicExportNotification(po.getElectronicExportNotification()) // .packageDescription(po.getPackageDescription()) // .customsTariffNumber(po.getCustomsTariffNumber()) // .customsAmount(BigInteger.valueOf(po.getCustomsAmount())) // .netWeightInKg(po.getNetWeightKg()) // .customsValue(po.getCustomsValue()) // .invoiceId(CustomsInvoiceId.ofRepoId(po.getC_Customs_Invoice_ID())) // .invoiceLineId(CustomsInvoiceLineId.ofRepoIdOrNull(CustomsInvoiceId.ofRepoId(po.getC_Customs_Invoice_ID()), po.getC_Customs_Invoice_Line_ID())) // .build(); // } return DhlCustomDeliveryDataDetail.builder() .packageId(po.getPackageId()) .awb(po.getawb()) .sequenceNumber(DhlSequenceNumber.of(po.getDHL_ShipmentOrder_ID())) .pdfLabelData(po.getPdfLabelData()) .trackingUrl(po.getTrackingURL()) .internationalDelivery(po.isInternationalDelivery()) // .customsDocument(customsDocument) .build(); }) .collect(ImmutableList.toImmutableList()); final ImmutableSet<PackageId> packageIds = dhlCustomDeliveryDataDetail.stream() .map(dhlCustomDeliveryDataDetail1 -> PackageId.ofRepoId(dhlCustomDeliveryDataDetail1.getPackageId())) .collect(ImmutableSet.toImmutableSet()); return DeliveryOrder.builder() .id(DeliveryOrderId.ofRepoId(requestPo.getDHL_ShipmentOrderRequest_ID())) .deliveryAddress(Address.builder() .bpartnerId(firstOrder.getC_BPartner_ID()) .companyName1(firstOrder.getDHL_Receiver_Name1()) .companyName2(firstOrder.getDHL_Receiver_Name2()) .street1(firstOrder.getDHL_Receiver_StreetName1()) .street2(firstOrder.getDHL_Receiver_StreetName2()) .houseNo(firstOrder.getDHL_Receiver_StreetNumber()) .zipCode(firstOrder.getDHL_Receiver_ZipCode()) .city(firstOrder.getDHL_Receiver_City()) .country(CountryCode.builder() .alpha2(firstOrder.getDHL_Receiver_CountryISO2Code()) .alpha3(firstOrder.getDHL_Receiver_CountryISO3Code()) .build()) .build()) .deliveryContact(ContactPerson.builder() .simplePhoneNumber(firstOrder.getDHL_Receiver_Phone()) .emailAddress(firstOrder.getDHL_Receiver_Email()) .build()) .pickupAddress(Address.builder() .companyName1(firstOrder.getDHL_Shipper_Name1()) .companyName2(firstOrder.getDHL_Shipper_Name2()) .street1(firstOrder.getDHL_Shipper_StreetName1()) .street2(firstOrder.getDHL_Shipper_StreetName2()) .houseNo(firstOrder.getDHL_Shipper_StreetNumber()) .zipCode(firstOrder.getDHL_Shipper_ZipCode()) .city(firstOrder.getDHL_Shipper_City()) .country(CountryCode.builder() .alpha2(firstOrder.getDHL_Shipper_CountryISO2Code()) .alpha3(firstOrder.getDHL_Shipper_CountryISO3Code()) .build()) .build()) .pickupDate(PickupDate.builder() .date(LocalDate.parse(firstOrder.getDHL_ShipmentDate(), DateTimeFormatter.ISO_LOCAL_DATE)) .build()) // other .customerReference(firstOrder.getCustomerReference()) .shipperProduct(DhlShipperProduct.forCode(firstOrder.getDHL_Product())) .deliveryPositions(constructDeliveryPositions(firstOrder, packageIds)) .shipperId(ShipperId.ofRepoId(firstOrder.getM_Shipper_ID())) .shipperTransportationId(ShipperTransportationId.ofRepoId(firstOrder.getM_ShipperTransportation_ID())) .customDeliveryData(DhlCustomDeliveryData.builder() .details(dhlCustomDeliveryDataDetail) .build()) .build(); } private static List<I_DHL_ShipmentOrder> getAllShipmentOrdersForRequest(final int requestId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_DHL_ShipmentOrder.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_DHL_ShipmentOrderRequest_ID, requestId) .create() .list(); } @NonNull private Iterable<? extends DeliveryPosition> constructDeliveryPositions( @NonNull final I_DHL_ShipmentOrder firstOrder, @NonNull final ImmutableSet<PackageId> packageIds) { final DeliveryPosition singleDeliveryPosition = DeliveryPosition.builder() .packageDimensions(PackageDimensions.builder() .widthInCM(firstOrder.getDHL_WidthInCm()) .lengthInCM(firstOrder.getDHL_LengthInCm()) .heightInCM(firstOrder.getDHL_HeightInCm()) .build()) .grossWeightKg(firstOrder.getDHL_WeightInKg().intValue()) .numberOfPackages(packageIds.size()) .packageIds(packageIds) .build(); return Collections.singleton(singleDeliveryPosition); } /** * Persists the shipper-dependant DeliveryOrder details * <p> * keep in sync with {@link #toDeliveryOrderFromPO(I_DHL_ShipmentOrderRequest)} * and {@link DhlDraftDeliveryOrderCreator#createDraftDeliveryOrder(de.metas.shipper.gateway.spi.DraftDeliveryOrderCreator.CreateDraftDeliveryOrderRequest)} */ @NonNull private I_DHL_ShipmentOrderRequest createShipmentOrderRequestPO(@NonNull final DeliveryOrder deliveryOrder) { final I_DHL_ShipmentOrderRequest shipmentOrderRequest = InterfaceWrapperHelper.newInstance(I_DHL_ShipmentOrderRequest.class); InterfaceWrapperHelper.save(shipmentOrderRequest); // maybe this will be removed in the future, but for now it simplifies the PO deserialization implementation and other implementation details dramatically, ref: constructDeliveryPositions() // therefore please ignore the for loops over `deliveryOrder.getDeliveryPositions()` as they don't help at all Check.errorIf(deliveryOrder.getDeliveryPositions().size() != 1, "The DHL implementation needs to always create DeliveryOrders with exactly 1 DeliveryPosition; deliveryOrder={}", deliveryOrder); for (final DeliveryPosition deliveryPosition : deliveryOrder.getDeliveryPositions()) // only a single delivery position should exist { final ImmutableList<PackageId> packageIdsAsList = deliveryPosition.getPackageIds().asList(); for (int i = 0; i < deliveryPosition.getNumberOfPackages(); i++) { final ContactPerson deliveryContact = deliveryOrder.getDeliveryContact(); final I_DHL_ShipmentOrder shipmentOrder = InterfaceWrapperHelper.newInstance(I_DHL_ShipmentOrder.class); shipmentOrder.setDHL_ShipmentOrderRequest_ID(shipmentOrderRequest.getDHL_ShipmentOrderRequest_ID()); // save to parent { // // Misc which doesn't fit dhl structure final Address deliveryAddress = deliveryOrder.getDeliveryAddress(); shipmentOrder.setPackageId(packageIdsAsList.get(i).getRepoId()); shipmentOrder.setC_BPartner_ID(deliveryAddress.getBpartnerId()); shipmentOrder.setM_Shipper_ID(deliveryOrder.getShipperId().getRepoId()); shipmentOrder.setM_ShipperTransportation_ID(deliveryOrder.getShipperTransportationId().getRepoId()); } { // (2.2.1) Shipment Details aka PackageDetails shipmentOrder.setDHL_Product(deliveryOrder.getShipperProduct().getCode()); //noinspection ConstantConditions shipmentOrder.setCustomerReference(deliveryOrder.getCustomerReference()); shipmentOrder.setDHL_ShipmentDate(deliveryOrder.getPickupDate().getDate().format(DateTimeFormatter.ISO_LOCAL_DATE)); // (2.2.1.8) final PackageDimensions packageDimensions = deliveryPosition.getPackageDimensions(); if (packageDimensions != null) { shipmentOrder.setDHL_HeightInCm(packageDimensions.getHeightInCM()); shipmentOrder.setDHL_LengthInCm(packageDimensions.getLengthInCM()); shipmentOrder.setDHL_WidthInCm(packageDimensions.getWidthInCM()); } shipmentOrder.setDHL_WeightInKg(BigDecimal.valueOf(deliveryPosition.getGrossWeightKg())); // (2.2.1.10) //noinspection ConstantConditions shipmentOrder.setDHL_RecipientEmailAddress(deliveryContact != null ? deliveryContact.getEmailAddress() : null); } { // (2.2.4) Receiver aka Delivery final Address deliveryAddress = deliveryOrder.getDeliveryAddress(); shipmentOrder.setDHL_Receiver_Name1(deliveryAddress.getCompanyName1()); // (2.2.4.2) shipmentOrder.setDHL_Receiver_Name2(deliveryAddress.getCompanyName2()); shipmentOrder.setDHL_Receiver_StreetName1(deliveryAddress.getStreet1()); shipmentOrder.setDHL_Receiver_StreetName2(deliveryAddress.getStreet2()); shipmentOrder.setDHL_Receiver_StreetNumber(deliveryAddress.getHouseNo()); shipmentOrder.setDHL_Receiver_ZipCode(deliveryAddress.getZipCode()); shipmentOrder.setDHL_Receiver_City(deliveryAddress.getCity()); // (2.2.4.2.10) shipmentOrder.setDHL_Receiver_CountryISO2Code(deliveryAddress.getCountry().getAlpha2()); shipmentOrder.setDHL_Receiver_CountryISO3Code(deliveryAddress.getCountry().getAlpha3()); // (2.2.4.2) //noinspection ConstantConditions shipmentOrder.setDHL_Receiver_Email(deliveryContact != null ? deliveryContact.getEmailAddress() : null); //noinspection ConstantConditions shipmentOrder.setDHL_Receiver_Phone(deliveryContact != null ? deliveryContact.getPhoneAsStringOrNull() : null); } { // (2.2.2) Shipper aka Pickup final Address pickupAddress = deliveryOrder.getPickupAddress(); // (2.2.2.1) shipmentOrder.setDHL_Shipper_Name1(pickupAddress.getCompanyName1()); shipmentOrder.setDHL_Shipper_Name2(pickupAddress.getCompanyName2()); // (2.2.2.2) shipmentOrder.setDHL_Shipper_StreetName1(pickupAddress.getStreet1()); shipmentOrder.setDHL_Shipper_StreetName2(pickupAddress.getStreet2()); shipmentOrder.setDHL_Shipper_StreetNumber(pickupAddress.getHouseNo()); shipmentOrder.setDHL_Shipper_ZipCode(pickupAddress.getZipCode()); shipmentOrder.setDHL_Shipper_City(pickupAddress.getCity()); // (2.2.2.2.8) shipmentOrder.setDHL_Shipper_CountryISO2Code(pickupAddress.getCountry().getAlpha2()); shipmentOrder.setDHL_Shipper_CountryISO3Code(pickupAddress.getCountry().getAlpha3()); } // { // // (2.2.6) Export Document - only for international shipments // // //noinspection ConstantConditions // final DhlCustomDeliveryData dhlCustomDeliveryData = DhlCustomDeliveryData.cast(deliveryOrder.getCustomDeliveryData()); // final DhlCustomDeliveryDataDetail deliveryDataDetail = dhlCustomDeliveryData.getDetailByPackageId(packageIdsAsList.get(i)); // if (deliveryDataDetail.isInternationalDelivery()) // { // final DhlCustomsDocument customsDocument = deliveryDataDetail.getCustomsDocument(); // // //noinspection ConstantConditions // shipmentOrder.setExportType(customsDocument.getExportType()); // shipmentOrder.setExportTypeDescription(customsDocument.getExportTypeDescription()); // shipmentOrder.setAdditionalFee(customsDocument.getAdditionalFee()); // // (2.2.6.9) // shipmentOrder.setElectronicExportNotification(customsDocument.getElectronicExportNotification()); // // (2.2.6.10) // shipmentOrder.setPackageDescription(customsDocument.getPackageDescription()); // shipmentOrder.setCustomsTariffNumber(customsDocument.getCustomsTariffNumber()); // shipmentOrder.setCustomsAmount(customsDocument.getCustomsAmount().intValue()); // shipmentOrder.setNetWeightKg(customsDocument.getNetWeightInKg()); // shipmentOrder.setCustomsValue(customsDocument.getCustomsValue()); // shipmentOrder.setC_Customs_Invoice_ID(customsDocument.getInvoiceId().getRepoId()); // shipmentOrder.setC_Customs_Invoice_Line_ID(customsDocument.getInvoiceLineId().getRepoId()); // } // } InterfaceWrapperHelper.save(shipmentOrder); { // (2.1) The id column (I_DHL_ShipmentOrder_ID) is used as ShipmentOrder.sequenceNumber since it's unique // nothing to persist here, but must be filled when retrieving the PO } } // fori loop } return shipmentOrderRequest; } private void updateShipmentOrderRequestPO(@NonNull final DeliveryOrder deliveryOrder) { for (final DeliveryPosition deliveryPosition : deliveryOrder.getDeliveryPositions()) // only a single delivery position should exist { final ImmutableList<PackageId> packageIdsAsList = deliveryPosition.getPackageIds().asList(); for (int i = 0; i < deliveryPosition.getNumberOfPackages(); i++) { //noinspection ConstantConditions final DhlCustomDeliveryData customDeliveryData = DhlCustomDeliveryData.cast(deliveryOrder.getCustomDeliveryData()); final I_DHL_ShipmentOrder shipmentOrder = getShipmentOrderByRequestIdAndPackageId(deliveryOrder.getId().getRepoId(), packageIdsAsList.get(i).getRepoId()); final DhlCustomDeliveryDataDetail deliveryDetail = customDeliveryData.getDetailBySequenceNumber(DhlSequenceNumber.of(shipmentOrder.getDHL_ShipmentOrder_ID())); final String awb = deliveryDetail.getAwb(); if (awb != null) { shipmentOrder.setawb(awb); } final byte[] pdfData = deliveryDetail.getPdfLabelData(); if (pdfData != null) { shipmentOrder.setPdfLabelData(pdfData); } final String trackingUrl = deliveryDetail.getTrackingUrl(); if (trackingUrl != null) { shipmentOrder.setTrackingURL(trackingUrl); } InterfaceWrapperHelper.save(shipmentOrder); } } } @VisibleForTesting I_DHL_ShipmentOrder getShipmentOrderByRequestIdAndPackageId(final int requestId, final int packageId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_DHL_ShipmentOrder.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_DHL_ShipmentOrderRequest_ID, requestId) .addEqualsFilter(I_DHL_ShipmentOrder.COLUMNNAME_PackageId, packageId) .create() .first(); } }
7,078
3,631
<gh_stars>1000+ /* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.dmn.feel.runtime.functions; import java.math.BigDecimal; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.kie.dmn.feel.lang.EvaluationContext; import org.kie.dmn.feel.lang.Symbol; import org.kie.dmn.feel.runtime.FEELFunction; import org.kie.dmn.feel.runtime.events.InvalidParametersEvent; public class SortFunctionTest { private SortFunction sortFunction; @Before public void setUp() { sortFunction = new SortFunction(); } @Test public void invokeListParamNull() { FunctionTestUtil.assertResultError(sortFunction.invoke(null), InvalidParametersEvent.class); } @Test public void invokeListEmpty() { FunctionTestUtil.assertResultList(sortFunction.invoke(Collections.emptyList()), Collections.emptyList()); } @Test public void invokeListSingleItem() { FunctionTestUtil.assertResultList(sortFunction.invoke(Collections.singletonList(10)), Collections.singletonList(10)); } @Test public void invokeListTypeHeterogenous() { FunctionTestUtil.assertResultError( sortFunction.invoke(Arrays.asList(10, "test", BigDecimal.TEN)), InvalidParametersEvent.class); } @Test public void invokeList() { FunctionTestUtil.assertResultList(sortFunction.invoke(Arrays.asList(10, 4, 5, 12)), Arrays.asList(4, 5, 10, 12)); FunctionTestUtil.assertResultList(sortFunction.invoke(Arrays.asList("a", "c", "b")), Arrays.asList("a", "b", "c")); } @Test public void invokeWithSortFunctionNull() { FunctionTestUtil.assertResultList( sortFunction.invoke(null, Arrays.asList(10, 4, 5, 12), null), Arrays.asList(4, 5, 10, 12)); } @Test public void invokeWithSortFunction() { FunctionTestUtil.assertResultList( sortFunction.invoke(null, Arrays.asList(10, 4, 5, 12), getBooleanFunction(true)), Arrays.asList(12, 5, 4, 10)); FunctionTestUtil.assertResultList( sortFunction.invoke(null, Arrays.asList(10, 4, 5, 12), getBooleanFunction(false)), Arrays.asList(10, 4, 5, 12)); } @Test public void invokeExceptionInSortFunction() { FunctionTestUtil.assertResultError( sortFunction.invoke(null, Arrays.asList(10, 4, 5, 12), getFunctionThrowingException()), InvalidParametersEvent.class); } private FEELFunction getBooleanFunction(final boolean functionResult) { return new FEELFunction() { @Override public String getName() { return "alwaysBoolean"; } @Override public Symbol getSymbol() { return null; } @Override public List<List<Param>> getParameters() { return null; } @Override public Object invokeReflectively(final EvaluationContext ctx, final Object[] params) { return functionResult; } }; } private FEELFunction getFunctionThrowingException() { return new FEELFunction() { @Override public String getName() { return "throwException"; } @Override public Symbol getSymbol() { return null; } @Override public List<List<Param>> getParameters() { return null; } @Override public Object invokeReflectively(final EvaluationContext ctx, final Object[] params) { throw new IllegalStateException("test exception"); } }; } }
1,794
3,897
<gh_stars>1000+ /* mbed Microcontroller Library * Copyright (c) 2017-2020 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_ATOMIC_USAGE_H #define MBED_ATOMIC_USAGE_H #include "BlockDevice.h" /** * Setup the given block device to test littlefs atomic operations * * Format the blockdevice with a littlefs filesystem and create * the files and directories required to test atomic operations. * * @param bd Block device format and setup * @param force_rebuild Force a reformat even if the device is already setup * @return true if the block device was formatted, false otherwise * @note utest asserts are used to detect fatal errors so utest must be * initialized before calling this function. */ bool setup_atomic_operations(BlockDevice *bd, bool force_rebuild); /** * Perform a set of atomic littlefs operations on the block device * * Mount the block device as a littlefs filesystem and a series of * atomic operations on it. Since the operations performed are atomic * the file system will always be in a well defined state. The block * device must have been setup by calling setup_atomic_operations. * * @param bd Block device to perform the operations on * @return -1 if flash is exhausted, otherwise the cycle count on the fs * @note utest asserts are used to detect fatal errors so utest must be * initialized before calling this function. */ int64_t perform_atomic_operations(BlockDevice *bd); /** * Check that the littlefs image on the block device is in a good state * * Mount the block device as a littlefs filesystem and check the files * and directories to ensure they are valid. Since all the operations * performed are atomic the filesystem should always be in a good * state. * * @param bd Block device to check * @note This function does not change the contents of the block device * @note utest asserts are used to detect fatal errors so utest must be * initialized before calling this function. */ void check_atomic_operations(BlockDevice *bd); #endif
660
5,169
{ "name": "NSObject+description", "version": "1.0.0", "summary": "Helps you produce description method output formatted same way as Apple's classes' description output", "description": "Helps you produce description method output formatted same way as Apple's classes' description output. Have your custom - (NSString *)description methods return the output from descriptionWithMembers: and manually specify attributes or have all properties of your object included automatically by using descriptionWithAllProperties.", "homepage": "https://github.com/niklasberglund/NSObject-description", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "<NAME>": "<EMAIL>" }, "platforms": { "ios": "5.0", "osx": "10.7" }, "source": { "git": "https://github.com/niklasberglund/NSObject-description.git", "tag": "1.0.0" }, "source_files": "NSObject+description.{h,m}" }
291
14,668
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.browser_ui.widget; import android.content.Context; import android.graphics.drawable.GradientDrawable; import android.util.AttributeSet; import android.widget.FrameLayout; import org.chromium.components.browser_ui.styles.ChromeColors; /** * Extension of {@link FrameLayout} that sets background resource to a rounded corner rectangle, * with dynamic background color from ElevationOverlayProvider based on card elevation. * Reuse the name of MaterialCardViewNoShadow to keep the same usage. * But this class is no longer an extension of MaterialCardView. */ public class MaterialCardViewNoShadow extends FrameLayout { public MaterialCardViewNoShadow(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MaterialCardViewNoShadow(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setBackgroundResource(R.drawable.card_with_corners_background); GradientDrawable gradientDrawable = (GradientDrawable) getBackground(); gradientDrawable.setColor( ChromeColors.getSurfaceColor(getContext(), R.dimen.card_elevation)); } }
411
461
/* empty stub to allow objectlist.awk.in to be created */
16
682
<reponame>209creative/arcgis-runtime-samples-android { "category": "Edit and Manage Data", "description": "Access the expiration information of an expired mobile map package.", "formal_name": "HonorMobileMapPackageExpirationDate", "ignore": false, "images": [ "honor-mobile-map-package-expiration-date.png" ], "keywords": [ "expiration", "mmpk" ], "language": "java", "provision_from": [ "https://arcgisruntime.maps.arcgis.com/home/item.html?id=174150279af74a2ba6f8b87a567f480b" ], "provision_to": [ "/LothianRiversAnno.mmpk" ], "relevant_apis": [ "Expiration", "MobileMapPackage" ], "snippets": [ "src/main/java/com/esri/arcgisruntime/sample/honormobilemappackageexpirationdate/MainActivity.java" ], "title": "Honor mobile map package expiration date" }
394
984
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.phoenix.end2end.index; import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Properties; import org.apache.phoenix.compile.ExplainPlan; import org.apache.phoenix.compile.ExplainPlanAttributes; import org.apache.phoenix.end2end.ParallelStatsEnabledIT; import org.apache.phoenix.end2end.ParallelStatsEnabledTest; import org.apache.phoenix.jdbc.PhoenixPreparedStatement; import org.apache.phoenix.util.PropertiesUtil; import org.junit.Test; import org.junit.experimental.categories.Category; @Category(ParallelStatsEnabledTest.class) public class ImmutableIndexWithStatsIT extends ParallelStatsEnabledIT { @Test public void testIndexCreationDeadlockWithStats() throws Exception { String query; ResultSet rs; String tableName = generateUniqueName(); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); conn.setAutoCommit(false); conn.createStatement().execute("CREATE TABLE " + tableName + " (k VARCHAR NOT NULL PRIMARY KEY, v VARCHAR) IMMUTABLE_ROWS=TRUE"); query = "SELECT * FROM " + tableName; rs = conn.createStatement().executeQuery(query); assertFalse(rs.next()); PreparedStatement stmt = conn.prepareStatement("UPSERT INTO " + tableName + " VALUES(?,?)"); for (int i=0; i<6;i++) { stmt.setString(1, "kkkkkkkkkk" + i); stmt.setString(2, "vvvvvvvvvv" + i ); stmt.execute(); } conn.commit(); conn.createStatement().execute("UPDATE STATISTICS " + tableName); query = "SELECT COUNT(*) FROM " + tableName; ExplainPlan plan = conn.prepareStatement(query) .unwrap(PhoenixPreparedStatement.class).optimizeQuery() .getExplainPlan(); ExplainPlanAttributes explainPlanAttributes = plan.getPlanStepsAsAttributes(); assertEquals("PARALLEL 1-WAY", explainPlanAttributes.getIteratorTypeAndScanSize()); assertEquals("FULL SCAN ", explainPlanAttributes.getExplainScanType()); String indexName = "I_" + generateUniqueName(); conn.createStatement().execute("CREATE INDEX " + indexName + " ON " + tableName + " (v)"); query = "SELECT * FROM " + indexName; rs = conn.createStatement().executeQuery(query); assertTrue(rs.next()); } }
1,238
676
package com.alorma.github.ui.activity; import android.app.Activity; import android.app.Fragment; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import com.android.vending.billing.IInAppBillingService; import java.util.ArrayList; import java.util.Collections; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; /** * Created by bernat.borras on 24/10/15. */ public class PurchasesFragment extends Fragment { private static final String SKU_MULTI_ACCOUNT = "com.alorma.github.multiaccount"; private IInAppBillingService mService; ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); } }; private String purchaseId; private PurchasesCallback purchasesCallback; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); createBillingService(); } private void createBillingService() { Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); serviceIntent.setPackage("com.android.vending"); if (mService == null) { getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } } public void checkSku(PurchasesCallback purchasesCallback) { this.purchasesCallback = purchasesCallback; SKUTask task = new SKUTask(); task.execute(SKU_MULTI_ACCOUNT); } public void finishPurchase(int requestCode, int resultCode, Intent data, PurchasesCallback callback) { if (requestCode == 1001) { String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); if (resultCode == Activity.RESULT_OK) { try { JSONObject jo = new JSONObject(purchaseData); String sku = jo.getString("productId"); String developerPayload = jo.getString("developerPayload"); if (callback != null) { boolean purchased = developerPayload.equals(purchaseId) && SKU_MULTI_ACCOUNT.equals(sku); callback.onMultiAccountPurchaseResult(purchased); } } catch (JSONException e) { e.printStackTrace(); } } else { int response_code = data.getIntExtra("RESPONSE_CODE", 0); if (callback != null) { callback.onMultiAccountPurchaseResult(response_code == 6); } } } } public void showDialogBuyMultiAccount() { try { purchaseId = UUID.randomUUID().toString(); Bundle buyIntentBundle = mService.getBuyIntent(3, getActivity().getPackageName(), SKU_MULTI_ACCOUNT, "inapp", purchaseId); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); getActivity().startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), 0, 0, 0); } catch (RemoteException | IntentSender.SendIntentException e) { e.printStackTrace(); } } public interface PurchasesCallback { void onMultiAccountPurchaseResult(boolean multiAccountPurchased); } private class SKUTask extends AsyncTask<String, Void, Bundle> { @Override protected Bundle doInBackground(String... strings) { if (strings != null) { ArrayList<String> skuList = new ArrayList<>(); Collections.addAll(skuList, strings); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); try { return mService.getPurchases(3, getActivity().getPackageName(), "inapp", null); } catch (RemoteException e) { e.printStackTrace(); } } return null; } @Override protected void onPostExecute(Bundle ownedItems) { super.onPostExecute(ownedItems); if (ownedItems != null) { int response = ownedItems.getInt("RESPONSE_CODE"); if (response == 0) { ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST"); if (ownedSkus != null && purchasesCallback != null) { purchasesCallback.onMultiAccountPurchaseResult(!ownedSkus.isEmpty()); } } } } } }
1,700
1,527
{ "$schema": "http://json-schema.org/draft-07/schema#", "title": "Lowdefy Request Schema - GoogleSheetDeleteOne", "type": "object", "required": ["filter"], "properties": { "filter": { "type": "object", "description": "A MongoDB query expression to filter the data. The first row matched by the filter will be deleted.", "errorMessage": { "type": "GoogleSheetDeleteOne request property \"filter\" should be an object." } }, "options": { "type": "object", "properties": { "limit": { "type": "number", "description": "The maximum number of rows to fetch.", "errorMessage": { "type": "GoogleSheetDeleteOne request property \"options.limit\" should be a number." } }, "skip": { "type": "number", "description": "The number of rows to skip from the top of the sheet.", "errorMessage": { "type": "GoogleSheetDeleteOne request property \"options.skip\" should be a number." } } } } }, "errorMessage": { "type": "GoogleSheetDeleteOne request properties should be an object.", "required": { "filter": "GoogleSheetDeleteOne request should have required property \"filter\"." } } }
522
623
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Part of Injectable Generic Camera System // Copyright(c) 2017, <NAME> // All rights reserved. // https://github.com/FransBouma/InjectableGenericCameraSystem // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met : // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and / or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Console.h" #include "GameConstants.h" using namespace std; namespace IGCS::Console { #define CONSOLE_WHITE 15 #define CONSOLE_NORMAL 7 static bool _consoleInitialized = false; void Init(); void EnsureConsole() { if (_consoleInitialized) { return; } Init(); } void Release() { if (_consoleInitialized) { FreeConsole(); _consoleInitialized = false; } } void WriteLine(const string& toWrite, int color) { EnsureConsole(); SetColor(color); WriteLine(toWrite); SetColor(CONSOLE_NORMAL); } void WriteLine(const string& toWrite) { EnsureConsole(); cout << toWrite << endl; } void WriteError(const string& error) { EnsureConsole(); cerr << error << endl; } void Init() { AllocConsole(); AttachConsole(GetCurrentProcessId()); // Redirect the CRT standard output, and error handles to the console FILE *fp; freopen_s(&fp, "CONOUT$", "w", stdout); freopen_s(&fp, "CONOUT$", "w", stderr); //Clear the error state for each of the C++ standard stream objects. wcout.clear(); cout.clear(); wcerr.clear(); cerr.clear(); wcin.clear(); cin.clear(); SetColor(15); SetConsoleTextAttribute(GetStdHandle(STD_ERROR_HANDLE), 12); _consoleInitialized = true; } void SetColor(int color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } }
971
2,338
//===- ComplexToStandard.h - Utils to convert from the complex dialect ----===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_ #define MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_ #include <memory> #include "mlir/Transforms/DialectConversion.h" namespace mlir { class FuncOp; class RewritePatternSet; template <typename T> class OperationPass; /// Populate the given list with patterns that convert from Complex to Standard. void populateComplexToStandardConversionPatterns(RewritePatternSet &patterns); /// Create a pass to convert Complex operations to the Standard dialect. std::unique_ptr<OperationPass<FuncOp>> createConvertComplexToStandardPass(); } // namespace mlir #endif // MLIR_CONVERSION_COMPLEXTOSTANDARD_COMPLEXTOSTANDARD_H_
314
2,338
<filename>clang/test/Analysis/SpecialFunctionsCFError.cpp<gh_stars>1000+ // RUN: %clang_analyze_cc1 -analyzer-checker=core,osx.coreFoundation.CFError \ // RUN: -verify %s typedef unsigned long size_t; struct __CFError {}; typedef struct __CFError *CFErrorRef; void *malloc(size_t); class Foo { public: Foo(CFErrorRef *error) {} // no-warning void operator delete(void *pointer, CFErrorRef *error) { // no-warning return; } void operator delete[](void *pointer, CFErrorRef *error) { // no-warning return; } // Check that we report warnings for operators when it can be useful void operator()(CFErrorRef *error) {} // expected-warning {{Function accepting CFErrorRef* should have a non-void return value to indicate whether or not an error occurred}} }; // Check that global delete operator is not bothered as well void operator delete(void *pointer, CFErrorRef *error) { // no-warning return; }
290
14,668
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_CERT_INTERNAL_CERT_ISSUER_SOURCE_H_ #define NET_CERT_INTERNAL_CERT_ISSUER_SOURCE_H_ #include <memory> #include <vector> #include "net/base/net_export.h" #include "net/cert/internal/parsed_certificate.h" namespace net { // Interface for looking up issuers of a certificate during path building. // Provides a synchronous and asynchronous method for retrieving issuers, so the // path builder can try to complete synchronously first. The caller is expected // to call SyncGetIssuersOf first, see if it can make progress with those // results, and if not, then fall back to calling AsyncGetIssuersOf. // An implementations may choose to return results from either one of the Get // methods, or from both. class NET_EXPORT CertIssuerSource { public: class NET_EXPORT Request { public: Request() = default; Request(const Request&) = delete; Request& operator=(const Request&) = delete; // Destruction of the Request cancels it. virtual ~Request() = default; // Retrieves issuers and appends them to |issuers|. // // GetNext should be called again to retrieve any remaining issuers. // // If no issuers are left then |issuers| will not be modified. This // indicates that the issuers have been exhausted and GetNext() should // not be called again. virtual void GetNext(ParsedCertificateList* issuers) = 0; }; virtual ~CertIssuerSource() = default; // Finds certificates whose Subject matches |cert|'s Issuer. // Matches are appended to |issuers|. Any existing contents of |issuers| will // not be modified. If the implementation does not support synchronous // lookups, or if there are no matches, |issuers| is not modified. virtual void SyncGetIssuersOf(const ParsedCertificate* cert, ParsedCertificateList* issuers) = 0; // Finds certificates whose Subject matches |cert|'s Issuer. // If the implementation does not support asynchronous lookups or can // determine synchronously that it would return no results, |*out_req| // will be set to nullptr. // // Otherwise a request is started and saved to |out_req|. The results can be // read through the Request interface. virtual void AsyncGetIssuersOf(const ParsedCertificate* cert, std::unique_ptr<Request>* out_req) = 0; }; } // namespace net #endif // NET_CERT_INTERNAL_CERT_ISSUER_SOURCE_H_
811
324
<gh_stars>100-1000 { "machineType": "https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/machineTypes/n1-standard-1", "name": "test-1", "networkInterfaces": [ { "network": "https://www.googleapis.com/compute/v1/projects/party/global/networks/default", "accessConfigs": [ { "type": "ONE_TO_ONE_NAT" } ] } ], "disks": [ { "type": "PERSISTENT", "source": "https://www.googleapis.com/compute/v1/projects/party/zones/us-central1-a/disks/test", "boot": true, "autoDelete": false } ], "description": "desc", "tags": { "items": [] }, "metadata": { "items": [ { "key": "aKey", "value": "aValue" } ] } }
379
348
{"nom":"Mirambeau","circ":"4ème circonscription","dpt":"Charente-Maritime","inscrits":1060,"abs":624,"votants":436,"blancs":8,"nuls":39,"exp":389,"res":[{"nuance":"REM","nom":"<NAME>","voix":202},{"nuance":"LR","nom":"<NAME>","voix":187}]}
95
515
<gh_stars>100-1000 # Copyright (c) 2021-2022, InterDigital Communications, Inc # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted (subject to the limitations in the disclaimer # below) provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of InterDigital Communications, Inc nor the names of its # contributors may be used to endorse or promote products derived from this # software without specific prior written permission. # NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY # THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND # CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT # NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Update the CDFs parameters of a trained model. To be called on a model checkpoint after training. This will update the internal CDFs related buffers required for entropy coding. """ import argparse import hashlib import sys from pathlib import Path from typing import Dict import torch from compressai.models.google import ( FactorizedPrior, JointAutoregressiveHierarchicalPriors, MeanScaleHyperprior, ScaleHyperprior, ) from compressai.models.video.google import ScaleSpaceFlow from compressai.zoo import load_state_dict from compressai.zoo.image import model_architectures as zoo_models def sha256_file(filepath: Path, len_hash_prefix: int = 8) -> str: # from pytorch github repo sha256 = hashlib.sha256() with filepath.open("rb") as f: while True: buf = f.read(8192) if len(buf) == 0: break sha256.update(buf) digest = sha256.hexdigest() return digest[:len_hash_prefix] def load_checkpoint(filepath: Path) -> Dict[str, torch.Tensor]: checkpoint = torch.load(filepath, map_location="cpu") if "network" in checkpoint: state_dict = checkpoint["network"] elif "state_dict" in checkpoint: state_dict = checkpoint["state_dict"] else: state_dict = checkpoint state_dict = load_state_dict(state_dict) return state_dict description = """ Export a trained model to a new checkpoint with an updated CDFs parameters and a hash prefix, so that it can be loaded later via `load_state_dict_from_url`. """.strip() models = { "factorized-prior": FactorizedPrior, "jarhp": JointAutoregressiveHierarchicalPriors, "mean-scale-hyperprior": MeanScaleHyperprior, "scale-hyperprior": ScaleHyperprior, "ssf2020": ScaleSpaceFlow, } models.update(zoo_models) def setup_args(): parser = argparse.ArgumentParser(description=description) parser.add_argument( "filepath", type=str, help="Path to the checkpoint model to be exported." ) parser.add_argument("-n", "--name", type=str, help="Exported model name.") parser.add_argument("-d", "--dir", type=str, help="Exported model directory.") parser.add_argument( "--no-update", action="store_true", default=False, help="Do not update the model CDFs parameters.", ) parser.add_argument( "-a", "--architecture", default="scale-hyperprior", choices=models.keys(), help="Set model architecture (default: %(default)s).", ) return parser def main(argv): args = setup_args().parse_args(argv) filepath = Path(args.filepath).resolve() if not filepath.is_file(): raise RuntimeError(f'"{filepath}" is not a valid file.') state_dict = load_checkpoint(filepath) model_cls_or_entrypoint = models[args.architecture] if not isinstance(model_cls_or_entrypoint, type): model_cls = model_cls_or_entrypoint() else: model_cls = model_cls_or_entrypoint net = model_cls.from_state_dict(state_dict) if not args.no_update: net.update(force=True) state_dict = net.state_dict() if not args.name: filename = filepath while filename.suffixes: filename = Path(filename.stem) else: filename = args.name ext = "".join(filepath.suffixes) if args.dir is not None: output_dir = Path(args.dir) Path(output_dir).mkdir(exist_ok=True) else: output_dir = Path.cwd() filepath = output_dir / f"{filename}{ext}" torch.save(state_dict, filepath) hash_prefix = sha256_file(filepath) filepath.rename(f"{output_dir}/{filename}-{hash_prefix}{ext}") if __name__ == "__main__": main(sys.argv[1:])
1,953
826
/*************************************************************************** * Copyright 1998-2018 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #include <cstdio> #include <cstdlib> #include <fstream> #include <iostream> #include <string> #include <sstream> #include <stdexcept> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <boost/format.hpp> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string/case_conv.hpp> #include "luxrays/utils/oclerror.h" #include "luxcore/luxcore.h" using namespace std; using namespace luxrays; using namespace luxcore; static string GetFileNameExt(const string &fileName) { return boost::algorithm::to_lower_copy(boost::filesystem::path(fileName).extension().string()); } static void BatchRendering(RenderConfig *config, RenderState *startState, Film *startFilm, const bool showDevicesStats) { RenderSession *session = RenderSession::Create(config, startState, startFilm); const unsigned int haltTime = config->GetProperty("batch.halttime").Get<unsigned int>(); const unsigned int haltSpp = config->GetProperty("batch.haltspp").Get<unsigned int>(0); // Start the rendering session->Start(); const Properties &stats = session->GetStats(); while (!session->HasDone()) { boost::this_thread::sleep(boost::posix_time::millisec(1000)); session->UpdateStats(); const double elapsedTime = stats.Get("stats.renderengine.time").Get<double>(); const unsigned int pass = stats.Get("stats.renderengine.pass").Get<unsigned int>(); // Convergence test is update inside UpdateFilm() const float convergence = stats.Get("stats.renderengine.convergence").Get<float>(); // Print some information about the rendering progress LC_LOG(boost::str(boost::format("[Elapsed time: %3d/%dsec][Samples %4d/%d][Convergence %f%%][Avg. samples/sec % 3.2fM on %.1fK tris]") % int(elapsedTime) % int(haltTime) % pass % haltSpp % (100.f * convergence) % (stats.Get("stats.renderengine.total.samplesec").Get<double>() / 1000000.0) % (stats.Get("stats.dataset.trianglecount").Get<double>() / 1000.0))); if (showDevicesStats) { // Intersection devices const Property &deviceNames = stats.Get("stats.renderengine.devices"); double minPerf = numeric_limits<double>::infinity(); double totalPerf = 0.0; for (unsigned int i = 0; i < deviceNames.GetSize(); ++i) { const string deviceName = deviceNames.Get<string>(i); const double perf = stats.Get("stats.renderengine.devices." + deviceName + ".performance.total").Get<double>(); minPerf = Min(minPerf, perf); totalPerf += perf; } for (unsigned int i = 0; i < deviceNames.GetSize(); ++i) { const string deviceName = deviceNames.Get<string>(i); LC_LOG(boost::str(boost::format(" %s: [Rays/sec %dK (%dK + %dK)][Prf Idx %.2f][Wrkld %.1f%%][Mem %dM/%dM]") % deviceName % int(stats.Get("stats.renderengine.devices." + deviceName + ".performance.total").Get<double>() / 1000.0) % int(stats.Get("stats.renderengine.devices." + deviceName + ".performance.serial").Get<double>() / 1000.0) % int(stats.Get("stats.renderengine.devices." + deviceName + ".performance.dataparallel").Get<double>() / 1000.0) % (stats.Get("stats.renderengine.devices." + deviceName + ".performance.total").Get<double>() / minPerf) % (100.0 * stats.Get("stats.renderengine.devices." + deviceName + ".performance.total").Get<double>() / totalPerf) % int(stats.Get("stats.renderengine.devices." + deviceName + ".memory.used").Get<double>() / (1024 * 1024)) % int(stats.Get("stats.renderengine.devices." + deviceName + ".memory.total").Get<double>() / (1024 * 1024)))); } } } // Stop the rendering session->Stop(); const string renderEngine = config->GetProperty("renderengine.type").Get<string>(); if (renderEngine != "FILESAVER") { // Save the rendered image session->GetFilm().SaveOutputs(); } delete session; } int main(int argc, char *argv[]) { // This is required to run AMD GPU profiler //XInitThreads(); try { // Initialize LuxCore luxcore::Init(); bool removeUnused = false; bool showDevicesStats = false; Properties cmdLineProp; string configFileName; for (int i = 1; i < argc; i++) { if (argv[i][0] == '-') { // I should check for out of range array index... if (argv[i][1] == 'h') { LC_LOG("Usage: " << argv[0] << " [options] [configuration file]" << endl << " -o [configuration file]" << endl << " -f [scene file]" << endl << " -w [film width]" << endl << " -e [film height]" << endl << " -D [property name] [property value]" << endl << " -d [current directory path]" << endl << " -c <remove all unused meshes, materials, textures and image maps>" << endl << " -s" << endl << " -h <display this help and exit>"); exit(EXIT_SUCCESS); } else if (argv[i][1] == 'o') { if (configFileName.compare("") != 0) throw runtime_error("Used multiple configuration files"); configFileName = string(argv[++i]); } else if (argv[i][1] == 'e') cmdLineProp.Set(Property("film.height")(argv[++i])); else if (argv[i][1] == 'w') cmdLineProp.Set(Property("film.width")(argv[++i])); else if (argv[i][1] == 'f') cmdLineProp.Set(Property("scene.file")(argv[++i])); else if (argv[i][1] == 'D') { cmdLineProp.Set(Property(argv[i + 1]).Add(argv[i + 2])); i += 2; } else if (argv[i][1] == 'd') boost::filesystem::current_path(boost::filesystem::path(argv[++i])); else if (argv[i][1] == 'c') removeUnused = true; else if (argv[i][1] == 's') showDevicesStats = true; else { LC_LOG("Invalid option: " << argv[i]); exit(EXIT_FAILURE); } } else { const string fileName = argv[i]; const string ext = GetFileNameExt(argv[i]); if ((ext == ".cfg") || (ext == ".lxs") || (ext == ".bcf") || (ext == ".rsm")) { if (configFileName.compare("") != 0) throw runtime_error("Used multiple configuration files"); configFileName = fileName; } else throw runtime_error("Unknown file extension: " + fileName); } } // Load the Scene if (configFileName.compare("") == 0) throw runtime_error("You must specify a file to render"); // Check if we have to parse a LuxCore SDL file or a LuxRender SDL file Scene *scene = NULL; RenderConfig *config; RenderState *startRenderState = NULL; Film *startFilm = NULL; if (configFileName.compare("") != 0) { // Clear the file name resolver list luxcore::ClearFileNameResolverPaths(); // Add the current directory to the list of place where to look for files luxcore::AddFileNameResolverPath("."); // Add the .cfg directory to the list of place where to look for files boost::filesystem::path path(configFileName); luxcore::AddFileNameResolverPath(path.parent_path().generic_string()); } const string configFileNameExt = GetFileNameExt(configFileName); if (configFileNameExt == ".lxs") { // It is a LuxRender SDL file LC_LOG("Parsing LuxRender SDL file..."); Properties renderConfigProps, sceneProps; luxcore::ParseLXS(configFileName, renderConfigProps, sceneProps); // For debugging //LC_LOG("RenderConfig: \n" << renderConfigProps); //LC_LOG("Scene: \n" << sceneProps); renderConfigProps.Set(cmdLineProp); scene = Scene::Create(); scene->Parse(sceneProps); config = RenderConfig::Create(renderConfigProps.Set(cmdLineProp), scene); } else if (configFileNameExt == ".cfg") { // It is a LuxCore SDL file config = RenderConfig::Create(Properties(configFileName).Set(cmdLineProp)); } else if (configFileNameExt == ".bcf") { // It is a LuxCore RenderConfig binary archive config = RenderConfig::Create(configFileName); config->Parse(cmdLineProp); } else if (configFileNameExt == ".rsm") { // It is a rendering resume file config = RenderConfig::Create(configFileName, &startRenderState, &startFilm); config->Parse(cmdLineProp); } else throw runtime_error("Unknown file extension: " + configFileName); if (removeUnused) { // Remove unused Meshes, Image maps, materials and textures config->GetScene().RemoveUnusedMeshes(); config->GetScene().RemoveUnusedImageMaps(); config->GetScene().RemoveUnusedMaterials(); config->GetScene().RemoveUnusedTextures(); } const bool fileSaverRenderEngine = (config->GetProperty("renderengine.type").Get<string>() == "FILESAVER"); if (!fileSaverRenderEngine) { // Force the film update at 2.5secs (mostly used by PathOCL) config->Parse(Properties().Set(Property("screen.refresh.interval")(2500))); } BatchRendering(config, startRenderState, startFilm, showDevicesStats); delete config; delete scene; LC_LOG("Done."); } catch (runtime_error &err) { LC_LOG("RUNTIME ERROR: " << err.what()); return EXIT_FAILURE; } catch (exception &err) { LC_LOG("ERROR: " << err.what()); return EXIT_FAILURE; } return EXIT_SUCCESS; }
4,028
5,169
{ "name": "XYVolumeHandler", "version": "0.0.3", "summary": "Graceful handle the volume changes in your iOS apps like Instagram.", "description": "Graceful handle the volume changes in your iOS apps like Instagram. YEAH!", "homepage": "https://github.com/X140Yu/XYVolumeHandler", "license": { "type": "MIT", "file": "LICENSE" }, "authors": { "X140Yu": "<EMAIL>" }, "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/X140Yu/XYVolumeHandler.git", "tag": "0.0.3" }, "source_files": "Classes/*.{h,m}" }
230
335
{ "word": "Plane", "definitions": [ "A flat surface on which a straight line joining any two points on it would wholly lie.", "An imaginary flat surface through or joining material objects.", "A flat or level surface of a material object.", "A flat surface producing lift by the action of air or water over and under it.", "A level of existence, thought, or development." ], "parts-of-speech": "Noun" }
153
2,023
<reponame>tdiprima/code # cal.py # # This code has been released to the Public Domain. # # finds the number of days between two particular dates # from string import * FALSE,TRUE = range(2) # Standard number of days for each month. months = (31,28,31,30,31,30,31,31,30,31,30,31) JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC = range(len(months)) def leapyear(year): return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def main(): days=sum=0 month = atoi(raw_input("Enter Month 1: ")) day = atoi(raw_input("Enter Day 1: ")) year = atoi(raw_input("Enter Year 1: ")) emonth = atoi(raw_input("Enter Month 2: ")) eday = atoi(raw_input("Enter Day 2: ")) eyear = atoi(raw_input("Enter Year 2: ")) month = month - 1 emonth = emonth - 1 if month == JAN: if leapyear(year): days = days + (366 - day) else: days = days + (365 - day) else: i = 0 while i < month: sum = sum + months[i] i = i + 1 sum = sum + day if leapyear(year): days = days + (366 - sum) else: days = days + (365 - sum) print "Days first year ==",days print "Number of years between ==",eyear - year i = year + 1 while i < eyear: if leapyear(i): days = days + 366 else: days = days + 365 print "in year",i i = i + 1 print "Total days not including last year ==",days if emonth == JAN: days = days + eday else: i = 0 while i < emonth: days = days + months[i] i = i + 1 days = days + day if leapyear(year) and emonth > FEB: days = days + 1 print "Final total days ==",days if __name__ == '__main__': main()
874
348
{"nom":"Blodelsheim","circ":"4ème circonscription","dpt":"Haut-Rhin","inscrits":1461,"abs":920,"votants":541,"blancs":33,"nuls":12,"exp":496,"res":[{"nuance":"REM","nom":"<NAME>","voix":249},{"nuance":"LR","nom":"<NAME>","voix":247}]}
94
852
#ifndef _CSCCHIPSPEEDCORRECTIONDBCONDITIONS_H #define _CSCCHIPSPEEDCORRECTIONDBCONDITIONS_H #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/ESProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/EventSetupRecordIntervalFinder.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/SourceFactory.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include <cmath> #include <memory> #include "CondFormats/CSCObjects/interface/CSCDBChipSpeedCorrection.h" #include "CondFormats/DataRecord/interface/CSCDBChipSpeedCorrectionRcd.h" #include "DataFormats/MuonDetId/interface/CSCIndexer.h" #include <DataFormats/MuonDetId/interface/CSCDetId.h> class CSCChipSpeedCorrectionDBConditions : public edm::ESProducer, public edm::EventSetupRecordIntervalFinder { public: CSCChipSpeedCorrectionDBConditions(const edm::ParameterSet &); ~CSCChipSpeedCorrectionDBConditions() override; inline static CSCDBChipSpeedCorrection *prefillDBChipSpeedCorrection(bool isForMC, std::string dataCorrFileName, float dataOffse); typedef std::unique_ptr<CSCDBChipSpeedCorrection> ReturnType; ReturnType produceDBChipSpeedCorrection(const CSCDBChipSpeedCorrectionRcd &); private: // ----------member data --------------------------- void setIntervalFor(const edm::eventsetup::EventSetupRecordKey &, const edm::IOVSyncValue &, edm::ValidityInterval &) override; CSCDBChipSpeedCorrection *cndbChipCorr; // Flag for determining if this is for setting MC or data corrections bool isForMC; // File for reading <= 15768 data chip corrections. MC will be fake (only one // value for every chip); std::string dataCorrFileName; float dataOffset; }; #include "CondFormats/CSCObjects/interface/CSCDBChipSpeedCorrection.h" #include "CondFormats/DataRecord/interface/CSCDBChipSpeedCorrectionRcd.h" #include <DataFormats/MuonDetId/interface/CSCDetId.h> #include <fstream> #include <iostream> #include <vector> // to workaround plugin library inline CSCDBChipSpeedCorrection *CSCChipSpeedCorrectionDBConditions::prefillDBChipSpeedCorrection(bool isMC, std::string filename, float dataOffset) { if (isMC) printf("\n Generating fake DB constants for MC\n"); else { printf("\n Reading chip corrections from file %s \n", filename.data()); printf("my data offset value is %f \n", dataOffset); } CSCIndexer indexer; const int CHIP_FACTOR = 100; const int MAX_SIZE = 15768; const int MAX_SHORT = 32767; CSCDBChipSpeedCorrection *cndbChipCorr = new CSCDBChipSpeedCorrection(); CSCDBChipSpeedCorrection::ChipSpeedContainer &itemvector = cndbChipCorr->chipSpeedCorr; itemvector.resize(MAX_SIZE); cndbChipCorr->factor_speedCorr = int(CHIP_FACTOR); // Fill chip corrections for MC is very simple if (isMC) { for (int i = 0; i < MAX_SIZE; i++) { itemvector[i].speedCorr = 0; } return cndbChipCorr; } // Filling for data takes a little more time FILE *fin = fopen(filename.data(), "r"); int serialChamber, endcap, station, ring, chamber, chip; float t, dt; int nPulses; std::vector<int> new_index_id; std::vector<float> new_chipPulse; double runningTotal = 0; int numNonZero = 0; while (!feof(fin)) { // note space at end of format string to convert last \n // int check = fscanf(fin,"%d %d %f %f \n",&serialChamber,&chip,&t,&dt); int check = fscanf(fin, "%d %d %d %d %d %d %f %f %d \n", &serialChamber, &endcap, &station, &ring, &chamber, &chip, &t, &dt, &nPulses); if (check != 9) { printf("The input file format is not as expected\n"); assert(0); } int serialChamber_safecopy = serialChamber; // Now to map from <NAME>'s serialChamber index convention // ME+1/1-ME+41 = 1 -234 // ME+4/2 = 235-270* // ME-1/1-ME-41 = 271-504* // ME-4/2 = 505-540 // To the convention used in /DataFormats/MuonDetId/interface/CSCIndexer.h // ME+1/1-ME+41 = 1 -234 // ME+4/2 = 469-504* // ME-1/1-ME-41 = 235-468* // ME-4/2 = 505-540 // Only the chambers marked * need to be remapped if (serialChamber >= 235 && serialChamber <= 270) serialChamber += 234; else { // not in ME+4\2 if (serialChamber >= 271 && serialChamber <= 504) serialChamber -= 36; } CSCDetId chamberId = indexer.detIdFromChamberIndex(serialChamber); // Now to map from S. Durkin's chip index convention 0-29 (with // 4,9,14,19,24,29 unused in ME1/3) To the convention used in // /DataFormats/MuonDetId/interface/CSCIndexer.h Layer 1-6 and chip 1-5 for // all chambers except ME1/3 which is chip 1-4 int layer = (chip) / 5 + 1; CSCDetId cscId(chamberId.endcap(), chamberId.station(), chamberId.ring(), chamberId.chamber(), layer); // This should yield the same CSCDetId as decoding the chamber serial does // If not, some debugging is needed CSCDetId cscId_doubleCheck(endcap, station, ring, chamber, layer); if (cscId != cscId_doubleCheck) { printf("Why doesn't chamberSerial %d map to e: %d s: %d r: %d c: %d ? \n", serialChamber_safecopy, endcap, station, ring, chamber); assert(0); } chip = (chip % 5) + 1; // The file produced by Stan starts from the geometrical strip number stored // in the CSCStripDigi When the strip digis are built, the conversion from // electronics channel to geometrical strip (reversing ME+1/1a and, more // importantly, ME-1/1b) is done before the digi is filled // (EventFilter/CSCRawToDigi/src/CSCCFEBData.cc). Since we're filling an // electronics channel database, I'll flip again ME-1/1b if (endcap == 2 && station == 1 && ring == 1 && chip < 5) { chip = 5 - chip; // change 1-4 to 4-1 } new_index_id.push_back(indexer.chipIndex(cscId, chip)); new_chipPulse.push_back(t); if (t != 0) { runningTotal += t; numNonZero++; } } fclose(fin); // Fill the chip corrections with zeros to start for (int i = 0; i < MAX_SIZE; i++) { itemvector[i].speedCorr = 0; } for (unsigned int i = 0; i < new_index_id.size(); i++) { if ((short int)(fabs((dataOffset - new_chipPulse[i]) * CHIP_FACTOR + 0.5)) < MAX_SHORT) itemvector[new_index_id[i] - 1].speedCorr = (short int)((dataOffset - new_chipPulse[i]) * CHIP_FACTOR + 0.5 * (dataOffset >= new_chipPulse[i]) - 0.5 * (dataOffset < new_chipPulse[i])); // printf("i= %d \t new index id = %d \t corr = %f \n",i,new_index_id[i], // new_chipPulse[i]); } // For now, calculate the mean chip correction and use it for all chambers // that don't have calibration pulse data (speedCorr ==0) or had values of // zero (speedCorr == dataOffset) This should be a temporary fix until all // chips that will read out in data have calibration information Since there // is only a handful out of 15K chips with values more than 3 ns away from the // average, this is probably very safe to first order float ave = runningTotal / numNonZero; for (int i = 0; i < MAX_SIZE; i++) { if (itemvector[i].speedCorr == 0 || itemvector[i].speedCorr == (short int)(dataOffset * CHIP_FACTOR + 0.5)) itemvector[i].speedCorr = (short int)((dataOffset - ave) * CHIP_FACTOR + 0.5 * (dataOffset >= ave) - 0.5 * (dataOffset < ave)); } return cndbChipCorr; } #endif
3,490
726
<reponame>HolyBayes/rep<filename>rep/estimators/_mnkit.py<gh_stars>100-1000 from __future__ import print_function, division, absolute_import import os import shutil import requests JSON_HEADER = {'Content-type': 'application/json'} __author__ = '<NAME>' class ServerError(Exception): pass def check_result(result): result.raise_for_status() json = result.json() if json['success']: return json['data'] else: raise ServerError(json['exception']) def mn_post(*args, **kwargs): return check_result(requests.post(*args, **kwargs)) def mn_get(*args, **kwargs): return check_result(requests.get(*args, **kwargs)) def mn_delete(*args, **kwargs): return check_result(requests.delete(*args, **kwargs)) def mn_put(*args, **kwargs): return check_result(requests.put(*args, **kwargs)) class MatrixNetClient(object): def __init__(self, api_url, token): self.api_url = api_url self.bucket_kwargs = {'headers': {"X-Yacern-Token": token}} self.cls_kwargs = {'headers': {"X-Yacern-Token": token, 'Content-type': 'application/json'}} self.auth_token = token def bucket(self, **kwargs): return Bucket(self.api_url, requests_kwargs=self.bucket_kwargs, **kwargs) def classifier(self, **kwargs): return Estimator(api_url=self.api_url, classifier_type='mn', requests_kwargs=self.cls_kwargs, **kwargs) class Bucket(object): """ Bucket is a proxy for a dataset placed on the server. """ def __init__(self, api_url, bucket_id=None, requests_kwargs=None): if requests_kwargs is None: requests_kwargs = {} self.api_url = api_url self.all_buckets_url = os.path.join(self.api_url, "buckets") self.requests_kwargs = requests_kwargs if bucket_id: self.bucket_id = bucket_id self.bucket_url = os.path.join(self.all_buckets_url, self.bucket_id) # Check if exists, create if does not. exists_resp = requests.get(self.bucket_url, **self.requests_kwargs) if exists_resp.status_code == 404: _ = mn_put( self.all_buckets_url, data={"bucket_id": self.bucket_id}, **self.requests_kwargs ) else: exists_resp.raise_for_status() else: response = mn_put(self.all_buckets_url, **self.requests_kwargs) self.bucket_id = response['bucket_id'] self.bucket_url = os.path.join(self.all_buckets_url, self.bucket_id) def ls(self): return mn_get(self.bucket_url, **self.requests_kwargs) def remove(self): return mn_delete(self.bucket_url, **self.requests_kwargs) def upload(self, local_filepath): files = {'file': open(local_filepath, 'rb')} result = mn_put( self.bucket_url, files=files, **self.requests_kwargs ) return result['uploaded'] == 'ok' class Estimator(object): def __init__( self, api_url, classifier_type, parameters, description, bucket_id, requests_kwargs=None ): """ :param api_url: URL of server API :param classifier_type: string, for instance, 'mn' :param parameters: parameters of a classifier :param description: description of model :param bucket_id: associated bucked_id :param requests_kwargs: kwargs passed to request """ if requests_kwargs is None: requests_kwargs = {'headers': JSON_HEADER} self.api_url = api_url self.all_cl_url = os.path.join(self.api_url, "classifiers") self.requests_kwargs = requests_kwargs self.status = None self._iterations = None self._debug = None self.classifier_type = classifier_type self.parameters = parameters self.description = description self.bucket_id = bucket_id def _update_with_dict(self, data): self.classifier_id = data['classifier_id'] self.bucket_id = data['bucket_id'] self.description = data['description'] self.parameters = data['parameters'] self.classifier_type = data['type'] def _update_iteration_and_debug(self): response = mn_get(self._get_classifier_url_for('iterations'), **self.requests_kwargs) self._iterations = response.get('iterations') self._debug = response.get('debug') def _get_classifier_url(self): return os.path.join(self.all_cl_url, self.classifier_id) def _get_classifier_url_for(self, action): return os.path.join(self._get_classifier_url(), action) def load_from_api(self): data = mn_get(self._get_classifier_url(), **self.requests_kwargs) self._update_with_dict(data) def upload(self): payload = { 'description': self.description, 'type': self.classifier_type, 'parameters': self.parameters, 'bucket_id': self.bucket_id } data = mn_put( self.all_cl_url, json=payload, **self.requests_kwargs ) self._update_with_dict(data) return True def get_status(self): self.status = mn_get(self._get_classifier_url_for('status'), **self.requests_kwargs)['status'] return self.status def resubmit(self): self._iterations = None return mn_post(self._get_classifier_url_for('resubmit'), **self.requests_kwargs)['resubmit'] def get_iterations(self): self._update_iteration_and_debug() return self._iterations def get_debug(self): self._update_iteration_and_debug() return self._debug def save_formula(self, path): response = requests.get(self._get_classifier_url_for('formula'), stream=True, **self.requests_kwargs) if not response.ok: raise ServerError('Error during formula downloading, {}'.format(response)) with open(path, 'wb') as f: shutil.copyfileobj(response.raw, f) def save_stats(self, path): response = requests.get(self._get_classifier_url_for('stats'), stream=True, **self.requests_kwargs) if not response.ok: raise ServerError('Error during feature importances downloading, {}'.format(response)) with open(path, 'wb') as f: shutil.copyfileobj(response.raw, f)
2,901
337
<filename>BMAIL/__init__.py #coding=utf-8 #!/usr/bin/python import smtplib, time, os, getpass, sys def psb(z): for e in z + '\n': sys.stdout.write(e) sys.stdout.flush() time.sleep(0.01) class bcolors: OKGREEN = '\033[1;92;40m' WARNING = '\033[96m' FAIL = '\033[91m' ENDC = '\033[0m' WHAT = '\033[1;92m' def bababomb(): os.system('clear') print bcolors.WHAT + ''' _______ _________ _______ _______ _________ ( ____ \\__ __/( ___ )( ____ )\__ __/ | ( \/ ) ( | ( ) || ( )| ) ( | (_____ | | | (___) || (____)| | | (_____ ) | | | ___ || __) | | ) | | | | ( ) || (\ ( | | /\____) | | | | ) ( || ) \ \__ | | \_______) )_( |/ \||/ \__/ )_( \n\n\n''' + bcolors.ENDC def bain(): os.system('clear') os.system("pip2 install --upgrade bain") os.system('clear') print(u"\u001b[38;5;198m"' ______ _______ _________ _ ') print(u"\u001b[38;5;197m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;198m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;197m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;198m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;197m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;198m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;197m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") print(u"\u001b[38;5;135m"'\nSELECT SERVER :\n') psb(u"\u001b[38;5;36m"" [01] GMAIL BOMBER") psb(u"\u001b[38;5;37m"" [02] YAHOO BOMBER") psb(u"\u001b[38;5;38m"" [03] HOTMAIL BOMBER") psb(u"\u001b[38;5;39m"" [04] UPDATE TOOL") psb(u"\u001b[38;5;33m"" [00] EXIT NOW") baction() def baction(): babaserver = raw_input(bcolors.OKGREEN + (u"\u001b[38;5;135m"'\n > ') + bcolors.ENDC) if babaserver =='': print '[!] Fill in correctly' baction() elif babaserver =="1" or babaserver == '01': os.system('clear') print(u"\u001b[38;5;198m"' ______ _______ _________ _ ') print(u"\u001b[38;5;197m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;198m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;197m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;198m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;197m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;198m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;197m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") user = raw_input(bcolors.OKGREEN + '\n \033[1;91m•\033[1;92mYOUR EMAIL \033[1;93m: ' + bcolors.ENDC) pwd = getpass.getpass(bcolors.OKGREEN + ' \033[1;91m•\033[1;92mPASSWORD \033[1;93m: ' + bcolors.ENDC) os.system('clear') print(u"\u001b[38;5;198m"' ______ _______ _________ _ ') print(u"\u001b[38;5;197m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;198m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;197m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;198m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;197m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;198m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;197m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") to = raw_input(bcolors.OKGREEN + '\n TO : ' + bcolors.ENDC) headers = (' BOTOL BABA FUCK YOU ') subject = raw_input(bcolors.OKGREEN + ' SUBJECT : ' + bcolors.ENDC) body = raw_input(bcolors.OKGREEN + ' MESSAGE : ' + bcolors.ENDC) nomes = input(bcolors.OKGREEN + ' THREAT : ' + bcolors.ENDC) no = 0 message = 'From: ' + user + headers + '\nSUBJECT : ' + subject + '\n' + body bababomb() babaserver = smtplib.SMTP("smtp.gmail.com", 587) babaserver.ehlo() babaserver.starttls() try: babaserver.login(user, pwd) except smtplib.SMTPAuthenticationError: print bcolors.FAIL + '''Your Username or Password is incorrect, please try again using the correct credentials Or you need to enable less secure apps On Gmail: https://myaccount.google.com/lesssecureapps ''' + bcolors.ENDC os.system('xdg-open https://myaccount.google.com/lesssecureapps') sys.exit() while no != nomes: try: babaserver.sendmail(user, to, message) print bcolors.WARNING + 'SUCCESSFULLY SENT ' + str(no+1) + ' MAIL' + bcolors.ENDC no += 1 time.sleep(.2) except KeyboardInterrupt: print bcolors.FAIL + '\nCANCELED' + bcolors.ENDC sys.exit() except: print "FAILED TO SEND" raw_input("\n[ Back ]") bain() elif babaserver == '2' or babaserver == '02': os.system('clear') print(u"\u001b[38;5;191m"' ______ _______ _________ _ ') print(u"\u001b[38;5;192m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;132m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;133m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;137m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;199m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;197m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;198m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") user = raw_input(bcolors.OKGREEN + '\n \033[1;91m•\033[1;92mYOUR EMAIL \033[1;93m: ' + bcolors.ENDC) pwd = getpass.getpass(bcolors.OKGREEN + ' \033[1;91m•\033[1;92mPASSWORD \033[1;93m: ' + bcolors.ENDC) os.system('clear') print(u"\u001b[38;5;191m"' ______ _______ _________ _ ') print(u"\u001b[38;5;192m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;132m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;133m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;137m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;199m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;197m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;198m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") to = raw_input(bcolors.OKGREEN + '\n TO : ' + bcolors.ENDC) headers = (' BOTOL BABA FUCK YOU ') subject = raw_input(bcolors.OKGREEN + ' SUBJECT : ' + bcolors.ENDC) body = raw_input(bcolors.OKGREEN + ' MESSAGE : ' + bcolors.ENDC) nomes = input(bcolors.OKGREEN + ' THREAT : ' + bcolors.ENDC) no = 0 message = 'From: ' + user + headers + '\nSUBJECT : ' + subject + '\n' + body bababomb() babaserver = smtplib.SMTP("smtp.mail.yahoo.com", 587) babaserver.ehlo() babaserver.starttls() try: babaserver.login(user, pwd) except smtplib.SMTPAuthenticationError: print bcolors.FAIL + '''Your Username or Password is incorrect, please try again using the correct credentials Or you need to enable less secure apps On Yahoo: https://login.yahoo.com/account/security?.scrumb=Tiby8TXUvJt#less-secure-apps ''' + bcolors.ENDC os.system('xdg-open https://login.yahoo.com/account/security?.scrumb=Tiby8TXUvJt#less-secure-apps') sys.exit() while no != nomes: try: babaserver.sendmail(user, to, message) print bcolors.WARNING + 'SUCCESSFULLY SENT ' + str(no + 1) + ' MAIL' + bcolors.ENDC no += 1 time.sleep(.2) except KeyboardInterrupt: print bcolors.FAIL + '\nCANCELED' + bcolors.ENDC sys.exit() except: print "FAILED TO SEND" raw_input("\n[ Back ]") bain() elif babaserver == '3' or babaserver == '03': os.system('clear') print(u"\u001b[38;5;191m"' ______ _______ _________ _ ') print(u"\u001b[38;5;192m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;132m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;133m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;137m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;199m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;197m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;198m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") user = raw_input(bcolors.OKGREEN + '\n \033[1;91m•\033[1;92mYOUR EMAIL \033[1;93m: ' + bcolors.ENDC) pwd = getpass.getpass(bcolors.OKGREEN + ' \033[1;91m•\033[1;92mPASSWORD \033[1;93m: ' + bcolors.ENDC) os.system('clear') print(u"\u001b[38;5;191m"' ______ _______ _________ _ ') print(u"\u001b[38;5;192m"'( ___ \ ( ___ )\__ __/( ( /|') print(u"\u001b[38;5;132m"'| ( ) )| ( ) | ) ( | \ ( |') print(u"\u001b[38;5;133m"'| (__/ / | (___) | | | | \ | |') print(u"\u001b[38;5;137m"'| __ ( | ___ | | | | (\ \) |') print(u"\u001b[38;5;199m"'| ( \ \ | ( ) | | | | | \ |') print(u"\u001b[38;5;197m"'| )___) )| ) ( |___) (___| ) \ |') print(u"\u001b[38;5;198m"'|/ \___/ |/ \|\_______/|/ )_)') print('''\n \033[1;90mALL IN ONE BOMBER BY \033[1;92mBOTOL BABA''') print(40 * "\033[1;94m_") print('''\n\033[1;96mAUTHOR : <NAME>\nFACEBOOK : FACEBOOK.COM/THEMEHTAN\nYOUTUBE : YOUTUBE.COM/MASTERTRICK1\nGITHUB : GITHUB.COM/BOTOLMEHEDI''') print(40 * "\033[1;94m_") to = raw_input(bcolors.OKGREEN + '\n TO : ' + bcolors.ENDC) headers = (' BOTOL BABA FUCK YOU ') subject = raw_input(bcolors.OKGREEN + ' SUBJECT : ' + bcolors.ENDC) body = raw_input(bcolors.OKGREEN + ' MESSAGE : ' + bcolors.ENDC) nomes = input(bcolors.OKGREEN + ' THREAT : ' + bcolors.ENDC) no = 0 message = 'From: ' + user + headers + '\nSUBJECT : ' + subject + '\n' + body bababomb() babaserver = smtplib.SMTP("smtp-mail.outlook.com", 587) babaserver.ehlo() babaserver.starttls() try: babaserver.login(user, pwd) except smtplib.SMTPAuthenticationError: print bcolors.FAIL + 'Your Username or Password is incorrect, please try again using the correct credentials' + bcolors.ENDC sys.exit() while no != nomes: try: babaserver.sendmail(user, to, message) print bcolors.WARNING + 'SUCCESSFULLY SENT ' + str(no + 1) + ' MAIL' + bcolors.ENDC no += 1 time.sleep(.2) except KeyboardInterrupt: print bcolors.FAIL + '\nCANCELED' + bcolors.ENDC sys.exit() except smtplib.SMTPAuthenticationError: print '\nThe username or password you entered is incorrect.' sys.exit() except: print "FAILED TO SEND " raw_input("\n[ Back ]") bain() elif babaserver == '4' or babaserver == '04': os.system("pip2 install --upgrade bain") elif babaserver == '0' or babaserver == '00': sys.exit() elif babaserver == '5' or babaserver == '6' or babaserver == '7' or babaserver == '8': print ' Works only with Gmail, Yahoo, Outlook and Hotmail. ' os.system('xdg-open https://facebook.com/TheMehtan') os.system("bain") if __name__ == '__main__': bain()
6,749
876
""" Displays result of a Prometheus query. Configuration parameters: color: Text colour. Supports py3status colour names. Examples: GOOD, DEGRADED, BAD, #E9967A (default None) format: Formatting of query result. Can refer to all labels from the query result. Query value placeholder __v. (default "{__v:.0f}") join: If query returned multiple rows, join them using this string. If you want to show just one, update your query. (default None) query: The PromQL query (default None) query_interval: Re-query interval in seconds. (default 60) server: str, URL pointing at your Prometheus(-compatible) server, example: http://prom.int.mydomain.net:9090 (default None) units: Dict with py3.format_units arguments, if you want human-readable unit formatting. Example: {"unit": "Wh", "si": True} If used, __v placeholder will contain formatted output. __n and __u will contain number and unit separately if you want to more finely control formatting. (default None) Dynamic format placeholders: All query result labels are available as format placeholders. The vector values themselves are in placeholder __v. (Or __n and __u if you specified units). Examples: # If blackbox exporter ran into any failures, show it. If everything # is healthy this will produce 0 rows hence not shown. query = "probe_success == 0" format = "💀 {job} {instance} 💀" color = "bad" # Basic Prometheus stat query = "sum(prometheus_sd_discovered_targets)" format = "{__v:.0f} targets monitored" color = "ok" @author github.com/Wilm0r SAMPLE OUTPUT {"full_text": "Ceph 21% (944GiB/4.4TiB)", "instance": "", "name": "prometheus"} """ class Py3status: # available configuration parameters color = None format = "{__v:.0f}" join = None query = None query_interval = 60 server = None units = None def prometheus(self): self._rows = [] self._rownum = 0 rows = self._query(self.query) res = [] for row in rows: val = float(row["value"][1]) if self.units: num, unit = self.py3.format_units(val, **self.units) val = f"{num}{unit}" else: num = val unit = None vars = dict(row["metric"]) vars.update({"__v": val, "__n": num, "__u": unit}) res.append(self.format.format(**vars)) if res: join = self.join or "" res = join.join(res) else: res = "" ret = dict(full_text=res, cached_until=self.py3.time_in(self.query_interval)) if self.color: if self.color.startswith("#"): ret["color"] = self.color else: entry = "COLOR_" + self.color.upper() if getattr(self.py3, entry): ret["color"] = getattr(self.py3, entry) return ret def _query(self, query): r = self.py3.request(self.server + "/api/v1/query", params={"query": query}) if r.status_code != 200: return [] r = r.json() if r["status"] != "success" or r["data"]["resultType"] != "vector": return [] return r["data"]["result"] if __name__ == "__main__": from py3status.module_test import module_test module_test(Py3status)
1,509
1,338
/* * Copyright 2008-10, <NAME>, <oliver.ruiz.dorantes_at_gmail.com> * All rights reserved. Distributed under the terms of the MIT License. */ #include "BluetoothWindow.h" #include "RemoteDevicesView.h" #include <Button.h> #include <Catalog.h> #include <LayoutBuilder.h> #include <Messenger.h> #include <Roster.h> #include <SeparatorView.h> #include <TabView.h> #include <stdio.h> #include <bluetooth/LocalDevice.h> #include "defs.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Window" static const uint32 kMsgSetDefaults = 'dflt'; static const uint32 kMsgRevert = 'rvrt'; static const uint32 kMsgStartServices = 'SrSR'; static const uint32 kMsgStopServices = 'StST'; LocalDevice* ActiveLocalDevice = NULL; BluetoothWindow::BluetoothWindow(BRect frame) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME("Bluetooth"), B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { fDefaultsButton = new BButton("defaults", B_TRANSLATE("Defaults"), new BMessage(kMsgSetDefaults), B_WILL_DRAW); fDefaultsButton->SetEnabled(false); fRevertButton = new BButton("revert", B_TRANSLATE("Revert"), new BMessage(kMsgRevert), B_WILL_DRAW); fRevertButton->SetEnabled(false); // Add the menu bar fMenubar = new BMenuBar(Bounds(), "menu_bar"); // Add File menu to menu bar BMenu* menu = new BMenu(B_TRANSLATE("Server")); menu->AddItem(new BMenuItem( B_TRANSLATE("Start bluetooth services" B_UTF8_ELLIPSIS), new BMessage(kMsgStartServices), 0)); menu->AddItem(new BMenuItem( B_TRANSLATE("Stop bluetooth services" B_UTF8_ELLIPSIS), new BMessage(kMsgStopServices), 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Refresh local devices" B_UTF8_ELLIPSIS), new BMessage(kMsgRefresh), 0)); fMenubar->AddItem(menu); menu = new BMenu(B_TRANSLATE("Help")); menu->AddItem(new BMenuItem(B_TRANSLATE("About Bluetooth" B_UTF8_ELLIPSIS), new BMessage(B_ABOUT_REQUESTED), 0)); fMenubar->AddItem(menu); BTabView* tabView = new BTabView("tabview", B_WIDTH_FROM_LABEL); tabView->SetBorder(B_NO_BORDER); fSettingsView = new BluetoothSettingsView(B_TRANSLATE("Settings")); fRemoteDevices = new RemoteDevicesView( B_TRANSLATE("Remote devices"), B_WILL_DRAW); tabView->AddTab(fRemoteDevices); tabView->AddTab(fSettingsView); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .SetInsets(0) .Add(fMenubar) .AddStrut(B_USE_HALF_ITEM_SPACING) .Add(tabView) .AddStrut(B_USE_HALF_ITEM_SPACING) .Add(new BSeparatorView(B_HORIZONTAL)) .AddGroup(B_HORIZONTAL) .SetInsets(B_USE_WINDOW_SPACING, B_USE_DEFAULT_SPACING, B_USE_WINDOW_SPACING, B_USE_WINDOW_SPACING) .Add(fDefaultsButton) .Add(fRevertButton) .AddGlue() .End() .End(); } void BluetoothWindow::MessageReceived(BMessage* message) { //message->PrintToStream(); switch (message->what) { case kMsgSetConnectionPolicy: case kMsgSetDeviceClass: fSettingsView->MessageReceived(message); break; case kMsgSetDefaults: /* fColorsView -> MessageReceived(new BMessage(DEFAULT_SETTINGS)); fAntialiasingSettings->SetDefaults(); fDefaultsButton->SetEnabled(false); fRevertButton->SetEnabled(true); */ break; case kMsgRevert: /* fColorsView -> MessageReceived(new BMessage(REVERT_SETTINGS)); fAntialiasingSettings->Revert(); fDefaultsButton->SetEnabled(fColorsView->IsDefaultable() || fAntialiasingSettings->IsDefaultable()); fRevertButton->SetEnabled(false); */ break; case kMsgStartServices: if (!be_roster->IsRunning(BLUETOOTH_SIGNATURE)) { status_t error = be_roster->Launch(BLUETOOTH_SIGNATURE); printf("kMsgStartServices: %s\n", strerror(error)); } break; case kMsgStopServices: if (be_roster->IsRunning(BLUETOOTH_SIGNATURE)) { status_t error = BMessenger(BLUETOOTH_SIGNATURE).SendMessage(B_QUIT_REQUESTED); printf("kMsgStopServices: %s\n", strerror(error)); } break; case kMsgAddToRemoteList: PostMessage(message, fRemoteDevices); break; case kMsgRefresh: fSettingsView->MessageReceived(message); break; case B_ABOUT_REQUESTED: be_app->PostMessage(message); break; default: BWindow::MessageReceived(message); break; } } bool BluetoothWindow::QuitRequested() { be_app->PostMessage(B_QUIT_REQUESTED); return true; }
1,760
335
{ "word": "Exultation", "definitions": [ "A feeling of triumphant elation or jubilation; rejoicing." ], "parts-of-speech": "Noun" }
67
14,668
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef REMOTING_HOST_DESKTOP_RESIZER_H_ #define REMOTING_HOST_DESKTOP_RESIZER_H_ #include <list> #include <memory> #include "remoting/host/base/screen_resolution.h" namespace remoting { class DesktopResizer { public: virtual ~DesktopResizer() {} // Create a platform-specific DesktopResizer instance. static std::unique_ptr<DesktopResizer> Create(); // Return the current resolution of the desktop. virtual ScreenResolution GetCurrentResolution() = 0; // Get the list of supported resolutions, which should ideally include // |preferred|. Implementations will generally do one of the following: // 1. Return the list of resolutions supported by the underlying video // driver, regardless of |preferred|. // 2. Return a list containing just |preferred|, perhaps after imposing // some minimum size constraint. This will typically be the case if // there are no constraints imposed by the underlying video driver. // 3. Return an empty list if resize is not supported. virtual std::list<ScreenResolution> GetSupportedResolutions( const ScreenResolution& preferred) = 0; // Set the resolution of the desktop. |resolution| must be one of the // resolutions previously returned by |GetSupportedResolutions|. Note that // implementations should fail gracefully if the specified resolution is no // longer supported, since monitor configurations may change on the fly. virtual void SetResolution(const ScreenResolution& resolution) = 0; // Restore the original desktop resolution. The caller must provide the // original resolution of the desktop, as returned by |GetCurrentResolution|, // as a hint. However, implementations are free to ignore this. For example, // virtual hosts will typically ignore it to avoid unnecessary resizes. virtual void RestoreResolution(const ScreenResolution& original) = 0; }; } // namespace remoting #endif // REMOTING_HOST_DESKTOP_RESIZER_H_
570
427
<reponame>Cwc-Test/CpcdosOS2.1<filename>CONTRIB/LLVM/src/rt/test/tsan/large_malloc_meta.cc // RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s #include "test.h" #include <sys/mman.h> // Test for previously unbounded memory consumption for large mallocs. // Code allocates a large memory block (that is handled by LargeMmapAllocator), // and forces allocation of meta shadow for the block. Then freed the block. // But meta shadow was not unmapped. Then code occupies the virtual memory // range of the block with something else (that does not need meta shadow). // And repeats. As the result meta shadow growed infinitely. // This program used to consume >2GB. Now it consumes <50MB. int main() { for (int i = 0; i < 1000; i++) { const int kSize = 1 << 20; const int kPageSize = 4 << 10; volatile int *p = new int[kSize]; for (int j = 0; j < kSize; j += kPageSize / sizeof(*p)) __atomic_store_n(&p[i], 1, __ATOMIC_RELEASE); delete[] p; mmap(0, kSize * sizeof(*p) + kPageSize, PROT_NONE, MAP_PRIVATE | MAP_ANON, -1, 0); } fprintf(stderr, "DONE\n"); return 0; } // CHECK: DONE
427
592
<gh_stars>100-1000 // // UIBezierPath+MMShapes.h // LooseLeaf // // Created by <NAME> on 7/27/18. // Copyright © 2018 Milestone Made, LLC. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UIBezierPath (MMShapes) + (UIBezierPath*)pentagonPath; + (UIBezierPath*)trianglePath; + (UIBezierPath*)hexagonPath; + (UIBezierPath*)octagonPath; + (UIBezierPath*)rombusPath; + (UIBezierPath*)starPath; + (UIBezierPath*)star2Path; + (UIBezierPath*)star3Path; + (UIBezierPath*)trekPath; + (UIBezierPath*)locationPath; + (UIBezierPath*)tetrisPath; + (UIBezierPath*)lPath; + (UIBezierPath*)reverseLPath; + (UIBezierPath*)sPath; + (UIBezierPath*)zPath; + (UIBezierPath*)eggPath; + (UIBezierPath*)plusPath; + (UIBezierPath*)diamondPath; + (UIBezierPath*)infinityPath; + (UIBezierPath*)heartPath; + (UIBezierPath*)arrowPath; + (UIBezierPath*)housePath; @end NS_ASSUME_NONNULL_END
422
1,058
<gh_stars>1000+ /* * Copyright (c) 2017-2019 TIBCO Software Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package io.snappydata.hydra.udfs; import org.apache.spark.sql.api.java.UDF8; import java.util.ArrayList; public class JavaUDF8 implements UDF8<Long,Long,Long,Long,Long,Long,Long,Long,Short> { // User provides the 8 Long numbers. Purpose is to test the Long as input, Short as output. // Below function add all the Long numbers to ArrayList and returns the size of ArrayList as Short. public Short call(Long l1, Long l2, Long l3, Long l4, Long l5, Long l6, Long l7, Long l8) throws Exception { ArrayList<Long> al = new ArrayList<Long>(); al.add(l1); al.add(l2); al.add(l3); al.add(l4); al.add(l5); al.add(l6); al.add(l7); al.add(l8); Integer iSize = al.size(); short size = iSize.shortValue(); return size; } }
541
678
/** * This header is generated by class-dump-z 0.2b. * * Source: /System/Library/PrivateFrameworks/Symbolication.framework/Symbolication */ typedef struct _VMURange { unsigned long long location; unsigned long long length; } VMURange; typedef struct dyld_image_info_64 { unsigned long long _field1; unsigned long long _field2; unsigned long long _field3; } dyld_image_info_64; typedef struct nlist_64 { union { unsigned _field1; } _field1; unsigned char _field2; unsigned char _field3; unsigned short _field4; unsigned long long _field5; } nlist_64; /* iOSOpenDev: commented-out (since already defined in SDK) typedef struct timeval { int tv_sec; int tv_usec; } timeval; */ // iOSOpenDev: added (since definition was commented-out) // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __timeval__ #define __timeval__ 1 typedef struct timeval timeval; #endif typedef struct sampling_context_t sampling_context_t; typedef struct _CSTypeRef { unsigned _opaque_1; unsigned _opaque_2; } CSTypeRef; /* iOSOpenDev: wrapped with define check (since occurs in other dumped files) typedef struct __sbuf { char *_base; int _size; } sbuf; */ // iOSOpenDev: added (since definition was commented-out) // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __sbuf__ #define __sbuf__ 1 typedef struct __sbuf sbuf; #endif // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __sFILEX__ #define __sFILEX__ 1 typedef struct __sFILEX sFILEX; #endif /* iOSOpenDev: wrapped with define check (since occurs in other dumped files) typedef struct __sFILE { char *_field1; int _field2; int _field3; short _field4; short _field5; sbuf _field6; int _field7; void *_field8; /function-pointer/ void *_field9; /function-pointer/ void *_field10; /function-pointer/ void *_field11; /function-pointer/ void *_field12; sbuf _field13; sFILEX *_field14; int _field15; unsigned char _field16[3]; unsigned char _field17[1]; sbuf _field18; int _field19; long long _field20; } FILE; */ // iOSOpenDev: added (since definition was commented-out) // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __sFILE__ #define __sFILE__ 1 typedef struct __sFILE FILE; #endif typedef struct mapped_memory_t mapped_memory_t; typedef struct { unsigned _field1; unsigned _field2; unsigned _field3; unsigned _field4; } XXStruct_qFPbxC; typedef struct { unsigned _field1; unsigned _field2; unsigned _field3; unsigned *_field4; unsigned _field5; unsigned _field6; unsigned _field7[2]; XXStruct_qFPbxC _field8[0]; } XXStruct_KGqEpA; typedef struct objc_ivar objc_ivar; // iOSOpenDev: added since struct was unknown // iOSOpenDev: wrapped with define check (since occurs in other dumped files) #ifndef __CFRuntimeBase__ #define __CFRuntimeBase__ 1 typedef struct __CFRuntimeBase { uintptr_t _cfisa; uint8_t _cfinfo[4]; #if __LP64__ uint32_t _rc; #endif } CFRuntimeBase; #endif
1,090
12,278
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /****************************************************************************** * Copyright (C) 2008-2016, International Business Machines * Corporation and others. All Rights Reserved. ******************************************************************************* */ #ifndef __PKG_ICU_H__ #define __PKG_ICU_H__ #include "unicode/utypes.h" #include "package.h" #define U_PKG_RESERVED_CHARS "\"%&'()*+,-./:;<=>?_" U_CAPI int U_EXPORT2 writePackageDatFile(const char *outFilename, const char *outComment, const char *sourcePath, const char *addList, icu::Package *pkg, char outType); U_CAPI icu::Package * U_EXPORT2 readList(const char *filesPath, const char *listname, UBool readContents, icu::Package *listPkgIn); #endif
302
666
// EnterChannelDlg.cpp : 实现文件 // #include "stdafx.h" #include "OpenVideoCall.h" #include "EnterChannelDlg.h" #include "afxdialogex.h" // CEnterChannelDlg 对话框 IMPLEMENT_DYNAMIC(CEnterChannelDlg, CDialogEx) CEnterChannelDlg::CEnterChannelDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CEnterChannelDlg::IDD, pParent) { } CEnterChannelDlg::~CEnterChannelDlg() { } void CEnterChannelDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDCHNAME_CHANNEL, m_ctrChannel); DDX_Control(pDX, IDC_EDENCKEY_CHANNEL, m_ctrEncKey); DDX_Control(pDX, IDC_BTNTEST_CHANNEL, m_btnTest); DDX_Control(pDX, IDC_BTNJOIN_CHANNEL, m_btnJoin); DDX_Control(pDX, IDC_BTNSET_CHANNEL, m_btnSetup); } BEGIN_MESSAGE_MAP(CEnterChannelDlg, CDialogEx) ON_WM_NCHITTEST() ON_WM_PAINT() ON_BN_CLICKED(IDC_BTNTEST_CHANNEL, &CEnterChannelDlg::OnBnClickedBtntestChannel) ON_BN_CLICKED(IDC_BTNJOIN_CHANNEL, &CEnterChannelDlg::OnBnClickedBtnjoinChannel) ON_BN_CLICKED(IDC_BTNSET_CHANNEL, &CEnterChannelDlg::OnBnClickedBtnsetChannel) END_MESSAGE_MAP() // CEnterChannelDlg 消息处理程序 BOOL CEnterChannelDlg::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN){ switch (pMsg->wParam){ case VK_ESCAPE: return FALSE; case VK_RETURN: OnBnClickedBtnjoinChannel(); return FALSE; } } return CDialogEx::PreTranslateMessage(pMsg); } BOOL CEnterChannelDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 m_ftEncy.CreateFont(17, 0, 0, 0, FW_BOLD, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial")); m_ftHead.CreateFont(15, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial")); m_ftDesc.CreateFont(15, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial")); m_ftBtn.CreateFont(16, 0, 0, 0, FW_NORMAL, FALSE, FALSE, 0, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial")); m_penFrame.CreatePen(PS_SOLID, 1, RGB(0xD8, 0xD8, 0xD8)); m_dlgDevice.Create(CDeviceDlg::IDD, this); m_dlgDevice.EnableDeviceTest(TRUE); SetBackgroundColor(RGB(0xFF, 0xFF, 0xFF)); InitCtrls(); return TRUE; // return TRUE unless you set the focus to a control } void CEnterChannelDlg::InitCtrls() { CRect ClientRect; // MoveWindow(0, 0, 320, 450, 1); GetClientRect(&ClientRect); m_ctrChannel.MoveWindow(ClientRect.Width()/2-160, 128, 320, 22, TRUE); m_ctrChannel.SetFont(&m_ftHead); m_ctrChannel.SetCaretPos(CPoint(12, 148)); m_ctrChannel.ShowCaret(); m_ctrChannel.SetTip(LANG_STR("IDS_CHN_CHTIP")); m_ctrEncKey.MoveWindow(ClientRect.Width() / 2 - 160, 176, 160, 22, TRUE); m_ctrEncKey.SetFont(&m_ftHead); m_ctrEncKey.SetCaretPos(CPoint(12, 148)); m_ctrEncKey.ShowCaret(); m_ctrEncKey.SetTip(LANG_STR("IDS_CHN_KEYTIP")); m_cmbEncType.Create(WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | CBS_OWNERDRAWVARIABLE, CRect(ClientRect.Width() / 2 + 1, 168, 180, 32), this, IDC_CMBENCTYPE_CHANNEL); m_cmbEncType.MoveWindow(ClientRect.Width() / 2 + 50, 173, 120, 22, TRUE); m_cmbEncType.SetFont(&m_ftHead); m_cmbEncType.SetButtonImage(IDB_CMBBTN, 12, 12, RGB(0xFF, 0x00, 0xFF)); m_cmbEncType.SetFaceColor(RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF)); m_cmbEncType.InsertString(0, LANG_STR("IDS_CHN_AES128XTS")); m_cmbEncType.InsertString(1, LANG_STR("IDS_CHN_AES256XTS")); m_cmbEncType.InsertString(2, LANG_STR("IDS_CHN_AES_128_ECB")); m_cmbEncType.InsertString(3, LANG_STR("IDS_CHN_SM4_128ECB")); m_cmbEncType.SetCurSel(0); m_btnJoin.MoveWindow(ClientRect.Width() / 2 - 180, 212, 360, 36, TRUE); m_btnTest.MoveWindow(ClientRect.Width() / 2 - 180, 314, 108, 36, TRUE); m_btnSetup.MoveWindow(ClientRect.Width()/2-60, 314, 240, 36, TRUE); m_btnJoin.SetBackColor(RGB(0x00, 0xA0, 0xE9), RGB(0x05, 0x78, 0xAA), RGB(0x05, 0x78, 0xAA), RGB(0xE6, 0xE6, 0xE6)); m_btnJoin.SetFont(&m_ftBtn); m_btnJoin.SetTextColor(RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xCC, 0xCC, 0xCC)); m_btnJoin.SetWindowText(LANG_STR("IDS_CHN_BTJOIN")); m_btnTest.SetBorderColor(RGB(0xD8, 0xD8, 0xD8), RGB(0x00, 0xA0, 0xE9), RGB(0x00, 0xA0, 0xE9), RGB(0xCC, 0xCC, 0xCC)); m_btnTest.SetBackColor(RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF)); m_btnTest.SetFont(&m_ftBtn); m_btnTest.SetTextColor(RGB(0x55, 0x58, 0x5A), RGB(0x00, 0xA0, 0xE9), RGB(0x00, 0xA0, 0xE9), RGB(0xCC, 0xCC, 0xCC)); m_btnTest.SetWindowText(LANG_STR("IDS_CHN_BTTEST")); m_btnSetup.SetBorderColor(RGB(0xD8, 0xD8, 0xD8), RGB(0x00, 0xA0, 0xE9), RGB(0x00, 0xA0, 0xE9), RGB(0xCC, 0xCC, 0xCC)); m_btnSetup.SetBackColor(RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF), RGB(0xFF, 0xFF, 0xFF)); m_btnSetup.SetFont(&m_ftBtn); m_btnSetup.SetTextColor(RGB(0x55, 0x58, 0x5A), RGB(0x00, 0xA0, 0xE9), RGB(0x00, 0xA0, 0xE9), RGB(0xCC, 0xCC, 0xCC)); m_btnSetup.SetWindowText(_T("1920*1080,15fps, 3mbps")); CMFCButton::EnableWindowsTheming(FALSE); } void CEnterChannelDlg::OnPaint() { CPaintDC dc(this); // device context for painting DrawClient(&dc); } void CEnterChannelDlg::DrawClient(CDC *lpDC) { CRect rcText; CRect rcClient; LPCTSTR lpString = NULL; GetClientRect(&rcClient); CFont* defFont = lpDC->SelectObject(&m_ftHead); lpDC->SetBkColor(RGB(0xFF, 0xFF, 0xFF)); lpDC->SetTextColor(RGB(0x44, 0x45, 0x46)); lpString = LANG_STR("IDS_CHN_TITLE"); lpDC->TextOut(12, 10, lpString, _tcslen(lpString)); lpDC->SelectObject(&m_penFrame); rcText.SetRect(rcClient.Width() / 2 - 188, 120, rcClient.Width() / 2 + 172, 152); lpDC->RoundRect(&rcText, CPoint(32, 32)); rcText.OffsetRect(0, 48); lpDC->RoundRect(&rcText, CPoint(32, 32)); lpDC->SelectObject(&m_ftDesc); lpDC->SetTextColor(RGB(0x91, 0x96, 0xA0)); lpString = LANG_STR("IDS_CHN_DSC1"); lpDC->TextOut(12, 45, lpString, _tcslen(lpString)); lpString = LANG_STR("IDS_CHN_DSC2"); lpDC->TextOut(12, 65, lpString, _tcslen(lpString)); lpDC->SetTextColor(RGB(0xD8, 0xD8, 0xD8)); lpString = LANG_STR("IDS_CHN_ENCTYPE"); lpDC->TextOut(240, 176, lpString, _tcslen(lpString)); lpDC->SelectObject(defFont); // Done with the font. Delete the font object. // font.DeleteObject(); } void CEnterChannelDlg::OnBnClickedBtntestChannel() { m_dlgDevice.ShowWindow(SW_SHOW); m_dlgDevice.CenterWindow(); } void CEnterChannelDlg::OnBnClickedBtnjoinChannel() { // CString str = CAgoraObject::GetAgoraObject()->GetCallID(); CString strKey; m_ctrEncKey.GetWindowText(strKey); if (strKey.GetLength() > 0) { // configuration of encrypt EncryptionConfig config; // set encrypt mode config.encryptionMode = ENCRYPTION_MODE(m_cmbEncType.GetCurSel() + 1); // set encrypt key char szKey[520] = { 0 }; WideCharToMultiByte(CP_UTF8, 0, strKey.GetBuffer(0), strKey.GetLength(), szKey, 520, NULL, NULL); config.encryptionKey = szKey; // EnableEncryption of engine. CAgoraObject::GetAgoraObject()->EnableEncryption(true, config); } GetParent()->SendMessage(WM_JOINCHANNEL, 0, 0); } void CEnterChannelDlg::OnBnClickedBtnsetChannel() { // SHORT sKeyStat = ::GetAsyncKeyState(VK_CONTROL); GetParent()->SendMessage(WM_GONEXT, 0, 0); } CString CEnterChannelDlg::GetChannelName() { CString strChannelName; m_ctrChannel.GetWindowText(strChannelName); return strChannelName; } void CEnterChannelDlg::SetVideoString(LPCTSTR lpVideoString) { m_btnSetup.SetWindowText(lpVideoString); } void CEnterChannelDlg::CleanEncryptionSecret() { m_ctrEncKey.SetWindowText(_T("")); } void CEnterChannelDlg::SetCtrlPos() { CRect ClientRect; GetClientRect(&ClientRect); m_ctrChannel.MoveWindow(ClientRect.Width() / 2 - 160, 128, 320, 22, TRUE); m_ctrEncKey.MoveWindow(ClientRect.Width() / 2 - 160, 176, 140, 22, TRUE); m_cmbEncType.MoveWindow(ClientRect.Width() / 2 + 50, 173, 120, 22, TRUE); int height = 36; m_btnJoin.MoveWindow(ClientRect.Width() / 2 - 180, 310, 360, height, TRUE); m_btnTest.MoveWindow(ClientRect.Width() / 2 - 180, 355, 108, height, TRUE); m_btnSetup.MoveWindow(ClientRect.Width() / 2 - 60, 355, 240, height, TRUE); }
3,890
506
// https://open.kattis.com/problems/acm #include <iostream> #include <tuple> #include <vector> using namespace std; int main() { vector<tuple<int, char, string>> v; while (true) { int m; char p; string r; cin >> m; if (m == -1) break; cin >> p >> r; v.push_back(make_tuple(m, p, r)); } bool solved[26]; for (int i = 0; i < 26; i++) solved[i] = false; int s = 0; int t = 0; for (int i = v.size() - 1; i >= 0; i--) { int m; char p; string r; tie(m, p, r) = v[i]; if (r == "right") { s++; t += m; solved[p - 'A'] = true; } else { if (solved[p - 'A']) t += 20; } } cout << s << " " << t << endl; }
329
399
<gh_stars>100-1000 package edu.wpi.grip.core; import edu.wpi.grip.core.cuda.AccelerationMode; import edu.wpi.grip.core.cuda.CudaDetector; import edu.wpi.grip.core.cuda.CudaVerifier; import edu.wpi.grip.core.cuda.NullAccelerationMode; import edu.wpi.grip.core.cuda.NullCudaDetector; import edu.wpi.grip.core.events.EventLogger; import edu.wpi.grip.core.events.UnexpectedThrowableEvent; import edu.wpi.grip.core.metrics.BenchmarkRunner; import edu.wpi.grip.core.metrics.Timer; import edu.wpi.grip.core.serialization.Project; import edu.wpi.grip.core.settings.SettingsProvider; import edu.wpi.grip.core.sockets.InputSocket; import edu.wpi.grip.core.sockets.InputSocketImpl; import edu.wpi.grip.core.sockets.OutputSocket; import edu.wpi.grip.core.sockets.OutputSocketImpl; import edu.wpi.grip.core.sources.CameraSource; import edu.wpi.grip.core.sources.ClassifierSource; import edu.wpi.grip.core.sources.HttpSource; import edu.wpi.grip.core.sources.ImageFileSource; import edu.wpi.grip.core.sources.MultiImageFileSource; import edu.wpi.grip.core.sources.NetworkTableEntrySource; import edu.wpi.grip.core.sources.VideoFileSource; import edu.wpi.grip.core.util.ExceptionWitness; import edu.wpi.grip.core.util.GripMode; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.SubscriberExceptionContext; import com.google.inject.AbstractModule; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.assistedinject.FactoryModuleBuilder; import com.google.inject.matcher.Matchers; import com.google.inject.name.Names; import com.google.inject.spi.InjectionListener; import com.google.inject.spi.TypeEncounter; import com.google.inject.spi.TypeListener; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** * A Guice {@link com.google.inject.Module} for GRIP's core package. This is where instances of * {@link Pipeline}, {@link Palette}, {@link Project}, etc... are created. */ @SuppressWarnings({"PMD.MoreThanOneLogger", "PMD.CouplingBetweenObjects"}) public class GripCoreModule extends AbstractModule { private final EventBus eventBus; private static final Logger logger = Logger.getLogger(GripCoreModule.class.getName()); /* * This class should not be used in tests. Use GRIPCoreTestModule for tests. */ @SuppressWarnings("JavadocMethod") public GripCoreModule() { this.eventBus = new EventBus(this::onSubscriberException); // TODO: HACK! Don't assign the global thread handler to an instance method. Creates global // state. Thread.setDefaultUncaughtExceptionHandler(this::onThreadException); } @Override protected void configure() { bind(GripMode.class).toInstance(GripMode.HEADLESS); // Register any injected object on the event bus bindListener(Matchers.any(), new TypeListener() { @Override public <I> void hear(TypeLiteral<I> type, TypeEncounter<I> encounter) { encounter.register((InjectionListener<I>) eventBus::register); } }); bind(EventBus.class).toInstance(eventBus); bind(EventLogger.class).asEagerSingleton(); // Allow for just injecting the settings provider, instead of the whole pipeline bind(SettingsProvider.class).to(Pipeline.class); install(new FactoryModuleBuilder().build(new TypeLiteral<Connection.Factory<Object>>() { })); bind(StepIndexer.class).to(Pipeline.class); bind(ConnectionValidator.class).to(Pipeline.class); bind(Source.SourceFactory.class).to(Source.SourceFactoryImpl.class); // Bind CUDA-specific stuff to default values // These will be overridden by the GripCudaModule at app runtime, but this lets // automated tests assume CPU-only operation modes bind(CudaDetector.class).to(NullCudaDetector.class); bind(AccelerationMode.class).to(NullAccelerationMode.class); bind(CudaVerifier.class).in(Scopes.SINGLETON); bind(Properties.class) .annotatedWith(Names.named("cudaProperties")) .toInstance(new Properties()); bind(InputSocket.Factory.class).to(InputSocketImpl.FactoryImpl.class); bind(OutputSocket.Factory.class).to(OutputSocketImpl.FactoryImpl.class); install(new FactoryModuleBuilder() .implement(CameraSource.class, CameraSource.class) .build(CameraSource.Factory.class)); install(new FactoryModuleBuilder() .implement(ImageFileSource.class, ImageFileSource.class) .build(ImageFileSource.Factory.class)); install(new FactoryModuleBuilder() .implement(MultiImageFileSource.class, MultiImageFileSource.class) .build(MultiImageFileSource.Factory.class)); install(new FactoryModuleBuilder() .implement(HttpSource.class, HttpSource.class) .build(HttpSource.Factory.class)); install(new FactoryModuleBuilder() .implement(NetworkTableEntrySource.class, NetworkTableEntrySource.class) .build(NetworkTableEntrySource.Factory.class)); install(new FactoryModuleBuilder() .implement(ClassifierSource.class, ClassifierSource.class) .build(ClassifierSource.Factory.class)); install(new FactoryModuleBuilder() .implement(VideoFileSource.class, VideoFileSource.class) .build(VideoFileSource.Factory.class)); install(new FactoryModuleBuilder().build(ExceptionWitness.Factory.class)); install(new FactoryModuleBuilder().build(Timer.Factory.class)); bind(BenchmarkRunner.class).asEagerSingleton(); bind(Cleaner.class).asEagerSingleton(); } protected void onSubscriberException(Throwable exception, @Nullable SubscriberExceptionContext exceptionContext) { if (exception instanceof InterruptedException) { logger.log(Level.FINE, "EventBus Subscriber threw InterruptedException", exception); Thread.currentThread().interrupt(); } else { logger.log(Level.SEVERE, "An event subscriber threw an exception", exception); eventBus.post(new UnexpectedThrowableEvent(exception, "An event subscriber threw an " + "exception on thread '" + Thread.currentThread().getName() + "'")); } } /* * We intentionally catch the throwable because we can't be sure what will happen. * We drop the last throwable because we clearly have a problem beyond our control. */ @SuppressWarnings({"PMD.AvoidCatchingThrowable", "PMD.EmptyCatchBlock"}) protected void onThreadException(Thread thread, Throwable exception) { // Don't do anything outside of a try catch block when dealing with thread death try { if (exception instanceof Error && !(exception instanceof AssertionError)) { // Try, this may not work. but its worth a shot. logger.log(Level.SEVERE, "Error from " + thread, exception); } else if (exception instanceof InterruptedException) { logger.log(Level.FINE, "InterruptedException from thread " + thread, exception); Thread.currentThread().interrupt(); } else { // This can potentially happen before the main class has even been loaded to handle these // exceptions logger.log(Level.SEVERE, "Uncaught Exception on thread " + thread, exception); final UnexpectedThrowableEvent event = new UnexpectedThrowableEvent(exception, thread + " threw an exception"); eventBus.post(event); // It is possible that the event was never handled. // If it wasn't we want to perform the shutdown hook here. event.shutdownIfFatal(); } } catch (Throwable throwable) { try { logger.log(Level.SEVERE, "Failed to handle thread exception", throwable); } catch (Throwable throwable1) { // Seriously, just give up at this point. } } // Don't do anything outside of a try catch block when dealing with thread death } }
2,709
2,728
<reponame>rsdoherty/azure-sdk-for-python<filename>sdk/mixedreality/azure-mixedreality-authentication/tests/test_static_access_token_credential.py # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- from azure.core.credentials import AccessToken from azure.mixedreality.authentication._shared.static_access_token_credential import StaticAccessTokenCredential class TestStaticAccessTokenCredential: def test_get_token(self): token = "My access token" expiration = 0 access_token = AccessToken(token=token, expires_on=expiration) staticAccessToken = StaticAccessTokenCredential(access_token) actual = staticAccessToken.get_token() assert access_token == actual
273
335
<filename>E/Evangelical_noun.json { "word": "Evangelical", "definitions": [ "A member of the evangelical tradition in the Christian Church." ], "parts-of-speech": "Noun" }
78
640
// automatically generated by m4 from headers in proto subdir #ifndef __CTYPE_H__ #define __CTYPE_H__ extern int __LIB__ isalnum(int) __smallc __z88dk_fastcall; extern int __LIB__ isalpha(int) __smallc __z88dk_fastcall; extern int __LIB__ isascii(int) __smallc __z88dk_fastcall; extern int __LIB__ isbdigit(int) __smallc __z88dk_fastcall; extern int __LIB__ isblank(int) __smallc __z88dk_fastcall; extern int __LIB__ iscntrl(int) __smallc __z88dk_fastcall; extern int __LIB__ isdigit(int) __smallc __z88dk_fastcall; extern int __LIB__ isgraph(int) __smallc __z88dk_fastcall; extern int __LIB__ islower(int) __smallc __z88dk_fastcall; extern int __LIB__ isodigit(int) __smallc __z88dk_fastcall; extern int __LIB__ isprint(int) __smallc __z88dk_fastcall; extern int __LIB__ ispunct(int) __smallc __z88dk_fastcall; extern int __LIB__ isspace(int) __smallc __z88dk_fastcall; extern int __LIB__ isupper(int) __smallc __z88dk_fastcall; extern int __LIB__ isxdigit(int) __smallc __z88dk_fastcall; extern int __LIB__ toascii(int) __smallc __z88dk_fastcall; extern int __LIB__ tolower(int) __smallc __z88dk_fastcall; extern int __LIB__ toupper(int) __smallc __z88dk_fastcall; #endif
486
5,169
{ "name": "NewLLDebugTool", "version": "1.3.2", "summary": "NewLLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.", "homepage": "https://github.com/didiaodanding/NewLLDebugTool", "license": "MIT", "authors": { "haleli": "<EMAIL>" }, "social_media_url": "https://github.com/didiaodanding", "platforms": { "ios": "8.0" }, "source": { "git": "https://github.com/didiaodanding/NewLLDebugTool.git", "tag": "1.3.2" }, "requires_arc": true, "public_header_files": "NewLLDebugTool/**/*.h", "source_files": "NewLLDebugTool/**/*.{h,m}", "resources": "NewLLDebugTool/**/*.{xib,storyboard,bundle,js}", "frameworks": "IOKit", "subspecs": [ { "name": "Network", "source_files": "NewLLDebugTool/Components/Network/**/*.{h,m}", "resources": "NewLLDebugTool/Components/Network/**/*.{xib,storyboard,bundle}", "public_header_files": "NewLLDebugTool/Components/Network/**/*.h", "dependencies": { "NewLLDebugTool/StorageManager": [ ] } }, { "name": "Log", "source_files": "NewLLDebugTool/Components/Log/**/*.{h,m}", "resources": "NewLLDebugTool/Components/Log/**/*.{xib,storyboard,bundle}", "public_header_files": "NewLLDebugTool/Components/Log/**/*.h", "dependencies": { "NewLLDebugTool/StorageManager": [ ] } }, { "name": "Crash", "source_files": "NewLLDebugTool/Components/Crash/**/*.{h,m}", "resources": "NewLLDebugTool/Components/Crash/**/*.{xib,storyboard,bundle}", "public_header_files": "NewLLDebugTool/Components/Crash/**/*.h", "dependencies": { "NewLLDebugTool/StorageManager": [ ] } }, { "name": "AppInfo", "source_files": "NewLLDebugTool/Components/AppInfo/**/*.{h,m}", "public_header_files": "NewLLDebugTool/Components/AppInfo/**/*.h", "dependencies": { "NewLLDebugTool/General": [ ] } }, { "name": "Sandbox", "source_files": "NewLLDebugTool/Components/Sandbox/**/*.{h,m}", "resources": "NewLLDebugTool/Components/Sandbox/**/*.{xib,storyboard,bundle}", "public_header_files": "NewLLDebugTool/Components/Sandbox/**/*.h", "dependencies": { "NewLLDebugTool/General": [ ], "SSZipArchive": [ ] } }, { "name": "Screenshot", "source_files": "NewLLDebugTool/Components/Screenshot/**/*.{h,m}", "public_header_files": "NewLLDebugTool/Components/Screenshot/**/*.h", "dependencies": { "NewLLDebugTool/General": [ ] } }, { "name": "StorageManager", "source_files": "NewLLDebugTool/Components/StorageManager/**/*.{h,m}", "public_header_files": "NewLLDebugTool/Components/StorageManager/**/*.h", "dependencies": { "FMDB": [ ], "NewLLDebugTool/General": [ ] } }, { "name": "General", "source_files": [ "NewLLDebugTool/Config/*.{h,m}", "NewLLDebugTool/Components/General/**/*.{h,m}" ], "resources": "NewLLDebugTool/Components/General/**/*.{xib,storyboard,bundle}", "public_header_files": [ "NewLLDebugTool/Config/*.h", "NewLLDebugTool/Components/General/**/*.h" ] } ] }
1,545
559
<reponame>amaiorano/Native_SDK /*! \brief Class containing internal data of the PowerVR Shell. \file PVRShell/ShellData.h \author PowerVR by Imagination, Developer Technology Team \copyright Copyright (c) Imagination Technologies Limited. */ #pragma once #include "PVRCore/commandline/CommandLine.h" #include "PVRCore/texture/PixelFormat.h" #include "PVRCore/types/Types.h" #include "PVRCore/Time_.h" /*! This file simply defines a version std::string. It can be commented out. */ #include "sdkver.h" #if !defined(PVRSDK_BUILD) #define PVRSDK_BUILD "n.n@nnnnnnn" #endif /*! Define the txt file that we can load command-line options from. */ #if !defined(PVRSHELL_COMMANDLINE_TXT_FILE) #define PVRSHELL_COMMANDLINE_TXT_FILE "PVRShellCL.txt" #endif namespace pvr { namespace platform { class ShellOS; /// <summary>Internal. Contains and tracks internal data necessary to power the pvr::Shell.</summary> struct ShellData { Time timer; //!< A timer uint64_t timeAtInitApplication; //!< The time when initApplication is called uint64_t lastFrameTime; //!< The time take for the last frame uint64_t currentFrameTime; //!< The time taken for the current frame std::string exitMessage; //!< A message to print upon exitting the application ShellOS* os; //!< An abstraction of the OS specific shell DisplayAttributes attributes; //!< A set of display attributes CommandLineParser* commandLine; //!< A Command line parser int32_t captureFrameStart; //!< The frame at which to start capturing frames int32_t captureFrameStop; //!< The frame at which to stop capturing frames uint32_t captureFrameScale; //!< A scaling factor to apply to each captured frame bool trapPointerOnDrag; //!< Whether to trap the pointer when dragging bool forceFrameTime; //!< Indicates whether frame time animation should be used uint32_t fakeFrameTime; //!< The fake time used for each frame bool exiting; //!< Indicates that the application is exiting uint32_t frameNo; //!< The current frame number bool forceReleaseInitWindow; //!< Forces a release cycle to happen, calling ReleaseView and then recreating the window as well bool forceReleaseInitView; //!< Forces a release cycle to happen, calling ReleaseView. The window is not recreated int32_t dieAfterFrame; //!< Specifies a frame after which the application will exit float dieAfterTime; //!< Specifies a time after which the application will exit int64_t startTime; //!< Indicates the time at which the application was started bool outputInfo; //!< Indicates that the output information should be printed bool weAreDone; //!< Indicates that the application is finished float FPS; //!< The current frames per second bool showFPS; //!< Indicates whether the current fps should be printed Api contextType; //!< The API used Api minContextType; //!< The minimum API supported /// <summary>Default constructor.</summary> ShellData() : os(0), commandLine(0), captureFrameStart(-1), captureFrameStop(-1), captureFrameScale(1), trapPointerOnDrag(true), forceFrameTime(false), fakeFrameTime(16), exiting(false), frameNo(0), forceReleaseInitWindow(false), forceReleaseInitView(false), dieAfterFrame(-1), dieAfterTime(-1), startTime(0), outputInfo(false), weAreDone(false), FPS(0.0f), showFPS(false), contextType(Api::Unspecified), minContextType(Api::Unspecified), currentFrameTime(static_cast<uint64_t>(-1)), lastFrameTime(static_cast<uint64_t>(-1)), timeAtInitApplication(static_cast<uint64_t>(-1)){}; }; } // namespace platform } // namespace pvr
1,055
1,754
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ratpack.exec.util.retry; import ratpack.exec.Promise; import java.time.Duration; /** * A fixed duration based implementation of {@link Delay}. * @since 1.7 */ public class FixedDelay implements Delay { private final Duration delay; private FixedDelay(Duration delay) { this.delay = delay; } /** * Builds a fixed duration delay. * @param duration the fixed duration * @return a fixed delay */ public static FixedDelay of(Duration duration) { return new FixedDelay(duration); } /** * {@inheritDoc} */ @Override public Promise<Duration> delay(Integer attempt) { return Promise.value(delay); } }
369
9,782
<filename>presto-benchmark-runner/src/main/java/com/facebook/presto/benchmark/framework/BenchmarkRunner.java /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.benchmark.framework; import com.facebook.airlift.event.client.EventClient; import com.facebook.presto.benchmark.event.BenchmarkPhaseEvent; import com.facebook.presto.benchmark.event.BenchmarkSuiteEvent; import com.facebook.presto.benchmark.source.BenchmarkSuiteSupplier; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; import javax.annotation.PostConstruct; import java.util.Set; import static com.facebook.presto.benchmark.event.BenchmarkPhaseEvent.Status.FAILED; import static com.facebook.presto.benchmark.event.BenchmarkPhaseEvent.Status.SUCCEEDED; import static com.facebook.presto.benchmark.framework.ExecutionStrategy.CONCURRENT; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class BenchmarkRunner { private final BenchmarkSuiteSupplier benchmarkSuiteSupplier; private final ConcurrentPhaseExecutor concurrentPhaseExecutor; private final Set<EventClient> eventClients; private final boolean continueOnFailure; @Inject public BenchmarkRunner( BenchmarkSuiteSupplier benchmarkSuiteSupplier, ConcurrentPhaseExecutor concurrentPhaseExecutor, Set<EventClient> eventClients, BenchmarkRunnerConfig config) { this.benchmarkSuiteSupplier = requireNonNull(benchmarkSuiteSupplier, "benchmarkSuiteSupplier is null"); this.concurrentPhaseExecutor = requireNonNull(concurrentPhaseExecutor, "concurrentPhaseExecutor is null"); this.eventClients = ImmutableSet.copyOf(requireNonNull(eventClients, "eventClients is null")); this.continueOnFailure = config.isContinueOnFailure(); } @PostConstruct public void start() { BenchmarkSuiteEvent suiteEvent = runSuite(benchmarkSuiteSupplier.get()); eventClients.forEach(client -> client.post(suiteEvent)); } private BenchmarkSuiteEvent runSuite(BenchmarkSuite suite) { int successfulPhases = 0; for (PhaseSpecification phase : suite.getPhases()) { BenchmarkPhaseEvent phaseEvent = getPhaseExecutor(phase).runPhase(phase, suite); eventClients.forEach(client -> client.post(phaseEvent)); if (phaseEvent.getEventStatus() == SUCCEEDED) { successfulPhases++; } else if (phaseEvent.getEventStatus() == FAILED && !continueOnFailure) { return BenchmarkSuiteEvent.failed(suite.getSuite()); } } if (successfulPhases < suite.getPhases().size()) { return BenchmarkSuiteEvent.completedWithFailures(suite.getSuite()); } else { return BenchmarkSuiteEvent.succeeded(suite.getSuite()); } } @SuppressWarnings("unchecked") private <T extends PhaseSpecification> PhaseExecutor<T> getPhaseExecutor(T phase) { if (phase.getExecutionStrategy() == CONCURRENT) { return (PhaseExecutor<T>) concurrentPhaseExecutor; } throw new IllegalArgumentException(format("Unsupported execution strategy: %s", phase.getExecutionStrategy())); } }
1,353
806
<gh_stars>100-1000 package com.github.davidmoten.rx.jdbc; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.concurrent.atomic.AtomicBoolean; class State { volatile Connection con; volatile PreparedStatement ps; volatile ResultSet rs; final AtomicBoolean closed = new AtomicBoolean(false); }
120
2,338
// RUN: %clang_cc1 -triple x86_64-unknown-linux -emit-llvm -DUNWIND -fcxx-exceptions -fexceptions -o - %s | FileCheck -check-prefixes CHECK,CHECK-UNWIND %s // RUN: %clang_cc1 -triple x86_64-unknown-linux -emit-llvm -fcxx-exceptions -fexceptions -o - %s | FileCheck -check-prefixes CHECK,CHECK-NO-UNWIND %s extern "C" void printf(const char *fmt, ...); struct DropBomb { bool defused = false; ~DropBomb() { if (defused) { return; } printf("Boom!\n"); } }; extern "C" void trap() { throw "Trap"; } // CHECK: define dso_local void @test() extern "C" void test() { DropBomb bomb; // CHECK-UNWIND: invoke void asm sideeffect unwind "call trap" // CHECK-NO-UNWIND: call void asm sideeffect "call trap" #ifdef UNWIND asm volatile("call trap" :: : "unwind"); #else asm volatile("call trap" :: :); #endif bomb.defused = true; }
382
335
<gh_stars>100-1000 #!/usr/bin/env python3 # See LICENSE for licensing information. # # Copyright (c) 2016-2021 Regents of the University of California # All rights reserved. # import debug import design from tech import cell_properties as props class sky130_row_cap(design.design): def __init__(self, version, name=""): if version == "rowend": cell_name = "sky130_fd_bd_sram__sram_sp_rowend" elif version == "rowenda": cell_name = "sky130_fd_bd_sram__sram_sp_rowenda" elif version == "rowend_replica": cell_name = "sky130_fd_bd_sram__openram_sp_rowend_replica" elif version == "rowenda_replica": cell_name = "sky130_fd_bd_sram__openram_sp_rowenda_replica" else: debug.error("Invalid type for row_end", -1) super().__init__(name=name, cell_name=cell_name, prop=props.row_cap_1port_cell)
392
10,225
package io.quarkus.arc.processor; import org.jboss.jandex.DotName; public class BeanDefiningAnnotation { private final DotName annotation; private final DotName defaultScope; public BeanDefiningAnnotation(DotName annotation, DotName defaultScope) { this.annotation = annotation; this.defaultScope = defaultScope; } public DotName getAnnotation() { return annotation; } public DotName getDefaultScope() { return defaultScope; } }
176
705
package src; import becker.robots.*; /* CS1A: Assignment 1: Part 1 - Robot Pipe Cleaning */ public class A1_Part_1 extends Object { public static void main(String[] args) { City theCity= new City( 11, 5); // 11 means "show me 11 streets - streets 0, 1, ..., 9, 10" // 5 means "show me 5 avenues - avenues 0, 1, 2, 3, 4 Robot karel = new Robot(theCity, 9, 1, Direction.NORTH, 0); new Thing(theCity, 1, 1); new Thing(theCity, 9, 2); // the 'backstop' for the robot: new Wall(theCity, 9, 1, Direction.SOUTH); // First build the west-most pipe // The west edge of the west-most pipe: new Wall(theCity, 1, 1, Direction.WEST); new Wall(theCity, 2, 1, Direction.WEST); new Wall(theCity, 3, 1, Direction.WEST); new Wall(theCity, 4, 1, Direction.WEST); new Wall(theCity, 5, 1, Direction.WEST); new Wall(theCity, 6, 1, Direction.WEST); new Wall(theCity, 7, 1, Direction.WEST); new Wall(theCity, 8, 1, Direction.WEST); new Wall(theCity, 9, 1, Direction.WEST); // The east edge of the west-most pipe: new Wall(theCity, 2, 1, Direction.EAST); new Wall(theCity, 3, 1, Direction.EAST); new Wall(theCity, 4, 1, Direction.EAST); new Wall(theCity, 5, 1, Direction.EAST); new Wall(theCity, 6, 1, Direction.EAST); new Wall(theCity, 7, 1, Direction.EAST); new Wall(theCity, 8, 1, Direction.EAST); new Wall(theCity, 9, 1, Direction.EAST); // the 'cap' at the top new Wall(theCity, 1, 1, Direction.NORTH); new Wall(theCity, 1, 2, Direction.NORTH); new Wall(theCity, 1, 2, Direction.EAST); // The west edge of the east-most pipe new Wall(theCity, 2, 2, Direction.WEST); new Wall(theCity, 3, 2, Direction.WEST); new Wall(theCity, 4, 2, Direction.WEST); new Wall(theCity, 5, 2, Direction.WEST); new Wall(theCity, 6, 2, Direction.WEST); new Wall(theCity, 7, 2, Direction.WEST); new Wall(theCity, 8, 2, Direction.WEST); new Wall(theCity, 9, 2, Direction.WEST); // The east edge of the east-most pipe new Wall(theCity, 1, 2, Direction.EAST); new Wall(theCity, 2, 2, Direction.EAST); new Wall(theCity, 3, 2, Direction.EAST); new Wall(theCity, 4, 2, Direction.EAST); new Wall(theCity, 5, 2, Direction.EAST); new Wall(theCity, 6, 2, Direction.EAST); new Wall(theCity, 7, 2, Direction.EAST); new Wall(theCity, 8, 2, Direction.EAST); new Wall(theCity, 9, 2, Direction.EAST); // that final stopping wall new Wall(theCity, 9, 2, Direction.SOUTH); int num=0; /* PUT YOUR CODE HERE */ for(num=0;num<8;num++) karel.move(); karel.pickThing(); // reach & pick first for(num=0;num<2;num++) karel.turnLeft(); for(num=0;num<8;num++) karel.move(); karel.putThing(); for(num=0;num<2;num++) karel.turnLeft(); // back and put thing down, also return to first position for(num=0;num<8;num++) karel.move(); for(num=0;num<3;num++) karel.turnLeft(); karel.move(); for(num=0;num<3;num++) karel.turnLeft(); for(num=0;num<8;num++) karel.move(); karel.pickThing(); // reach & pick second for(num=0;num<2;num++) karel.turnLeft(); for(num=0;num<8;num++) karel.move(); karel.turnLeft(); karel.move(); karel.turnLeft(); for(num=0;num<7;num++) karel.move(); karel.putThing(); for(num=0;num<2;num++) karel.turnLeft(); karel.move(); } }
1,976
831
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.sdk; import static com.android.tools.idea.sdk.SdkPaths.validateAndroidNdk; import static com.intellij.openapi.util.text.StringUtil.isEmpty; import static com.intellij.openapi.vfs.VfsUtilCore.virtualToIoFile; import com.android.SdkConstants; import com.android.tools.idea.io.FilePaths; import com.android.tools.idea.sdk.SdkPaths.ValidationResult; import com.android.tools.idea.sdk.wizard.SdkQuickfixUtils; import com.android.tools.idea.wizard.model.ModelWizardDialog; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.ui.ComponentWithBrowseButton; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.TextComponentAccessor; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBLabel; import java.io.File; import java.util.List; import javax.swing.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SelectNdkDialog extends DialogWrapper { private boolean myHasBeenEdited = false; private JPanel myPanel; private JBLabel myInvalidNdkPathLabel; private JRadioButton myRemoveInvalidNdkRadioButton; private JRadioButton mySelectValidNdkRadioButton; private TextFieldWithBrowseButton myNdkTextFieldWithButton; private JRadioButton myDownloadNdkRadioButton; private JBLabel myHeaderText; private JBLabel myErrorLabel; private JBLabel myChoiceLabel; private String myNdkPath = ""; /** * Displays NDK selection dialog. * * @param invalidNdkPath path to the invalid Android Ndk. If {@code null}, no NDK path is set but one is required. */ public SelectNdkDialog(@Nullable String invalidNdkPath, boolean showRemove, boolean showDownload) { super(false); init(); setTitle("Select Android NDK"); myInvalidNdkPathLabel.setText(invalidNdkPath); configureNdkTextField(); if (showDownload) { myDownloadNdkRadioButton.setSelected(true); myNdkTextFieldWithButton.setEnabled(false); } else { myDownloadNdkRadioButton.setVisible(false); mySelectValidNdkRadioButton.setSelected(true); myNdkTextFieldWithButton.setEnabled(true); getOKAction().setEnabled(false); } if (!showDownload && !showRemove) { mySelectValidNdkRadioButton.setVisible(false); myChoiceLabel.setVisible(false); } if (showRemove) { myRemoveInvalidNdkRadioButton.addActionListener( actionEvent -> myNdkTextFieldWithButton.setEnabled(!myRemoveInvalidNdkRadioButton.isSelected())); } else { myRemoveInvalidNdkRadioButton.setVisible(false); } if (invalidNdkPath == null) { myHeaderText.setText("The project's local.properties doesn't contain an NDK path."); } else { myHeaderText.setText("The project's local.properties file contains an invalid NDK path:"); myErrorLabel.setText(validateAndroidNdk(new File(invalidNdkPath), false).message); myErrorLabel.setVisible(true); myErrorLabel.setForeground(JBColor.RED); } mySelectValidNdkRadioButton.addChangeListener(e -> myNdkTextFieldWithButton.setEnabled(mySelectValidNdkRadioButton.isSelected())); } private void configureNdkTextField() { myNdkTextFieldWithButton.setTextFieldPreferredWidth(50); FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false) { @Override public void validateSelectedFiles(@NotNull VirtualFile[] files) throws Exception { for (VirtualFile virtualFile : files) { File file = virtualToIoFile(virtualFile); ValidationResult validationResult = validateAndroidNdk(file, false); if (!validationResult.success) { String msg = validationResult.message; if (isEmpty(msg)) { msg = "Please choose a valid Android NDK directory."; } throw new IllegalArgumentException(msg); } } } }; if (SystemInfo.isMac) { descriptor.withShowHiddenFiles(true); } descriptor.setTitle("Choose Android NDK Location"); myNdkTextFieldWithButton.addActionListener(new ComponentWithBrowseButton.BrowseFolderActionListener<>( "Select Android NDK Home", null, myNdkTextFieldWithButton, null, descriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT)); } @Nullable @Override protected JComponent createCenterPanel() { return myPanel; } @Override protected boolean postponeValidation() { return false; } @Nullable @Override protected ValidationInfo doValidate() { if (!mySelectValidNdkRadioButton.isSelected()) { return null; } String ndkPath = myNdkTextFieldWithButton.getText().trim(); if (!Strings.isNullOrEmpty(ndkPath)) { myHasBeenEdited = true; } if (!myHasBeenEdited) { return null; } String ndkError = validateAndroidNdkPath(ndkPath); if (ndkError != null) { return new ValidationInfo(ndkError, myNdkTextFieldWithButton.getTextField()); } return null; } @Nullable private static String validateAndroidNdkPath(@Nullable String path) { if (isEmpty(path)) { return "Android NDK path not specified."; } ValidationResult validationResult = validateAndroidNdk(FilePaths.stringToFile(path), false); if (!validationResult.success) { // Show error message in new line. Long lines trigger incorrect layout rendering. // See https://code.google.com/p/android/issues/detail?id=78291 return String.format("Invalid Android NDK path:<br>%1$s", validationResult.message); } else { return null; } } @Override protected void doOKAction() { if (myDownloadNdkRadioButton.isSelected()) { List<String> requested = ImmutableList.of(SdkConstants.FD_NDK); ModelWizardDialog dialog = SdkQuickfixUtils.createDialogForPaths(myPanel, requested, false); if (dialog != null && dialog.showAndGet()) { File ndk = IdeSdks.getInstance().getAndroidNdkPath(); if (ndk != null) { myNdkPath = ndk.getPath(); } } } if (mySelectValidNdkRadioButton.isSelected()) { myNdkPath = myNdkTextFieldWithButton.getText(); } super.doOKAction(); } @NotNull public String getAndroidNdkPath() { return myNdkPath; } }
2,571
483
/* * Copyright (c) 2017-2021 Nitrite author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dizitart.no2.integration; import org.apache.commons.io.FileUtils; import org.dizitart.no2.Nitrite; import org.dizitart.no2.common.util.StringUtils; import org.dizitart.no2.exceptions.InvalidOperationException; import org.dizitart.no2.exceptions.NitriteIOException; import org.dizitart.no2.mvstore.MVStoreModule; import org.junit.After; import org.junit.Rule; import org.junit.Test; import java.io.File; import static org.dizitart.no2.integration.TestUtil.createDb; import static org.dizitart.no2.integration.TestUtil.getRandomTempDbFile; /** * @author <NAME>. */ public class NitriteBuilderNegativeTest { private Nitrite db; private String filePath; @Rule public Retry retry = new Retry(3); @Test(expected = NitriteIOException.class) public void testCreateReadonlyDatabase() { filePath = getRandomTempDbFile(); MVStoreModule storeModule = MVStoreModule.withConfig() .filePath(filePath) .readOnly(true) .build(); db = Nitrite.builder() .loadModule(storeModule) .openOrCreate(); db.close(); } @Test(expected = InvalidOperationException.class) public void testCreateReadonlyInMemoryDatabase() { MVStoreModule storeModule = MVStoreModule.withConfig() .readOnly(true) .build(); db = Nitrite.builder() .loadModule(storeModule) .openOrCreate(); db.close(); } @Test(expected = NitriteIOException.class) public void testOpenWithLock() { filePath = getRandomTempDbFile(); db = createDb(filePath); db = createDb(filePath); } @Test(expected = NitriteIOException.class) public void testInvalidDirectory() { filePath = "/ytgr/hfurh/frij.db"; db = createDb(filePath); } @After public void cleanUp() { if (db != null && !db.isClosed()) { db.close(); } if (!StringUtils.isNullOrEmpty(filePath)) { FileUtils.deleteQuietly(new File(filePath)); } } }
1,064
852
<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # # Ecal part # from RecoLocalCalo.Configuration.ecalLocalRecoSequence_cff import * #defines a sequence ecalLocalRecoSequence # # Hcal part # # calo geometry # # changed by tommaso. now the calibrations are read from Configuration/StaqndardSequences/data/*Conditions.cff # # HCAL calibrations #include "CalibCalorimetry/HcalPlugins/data/hardwired_conditions.cfi" #HCAL reconstruction from RecoLocalCalo.Configuration.hcalLocalReco_cff import * from RecoLocalCalo.Configuration.hcalGlobalReco_cff import * # hfreco.firstSample = 2 hfreco.samplesToAdd = 2 #--- special temporary DB-usage unsetting hfreco.tsFromDB = False hfreco.digiTimeFromDB = False # # sequence CaloLocalReco and CaloGlobalReco # calolocalrecoTask = cms.Task(ecalLocalRecoTask,hcalLocalRecoTask) calolocalreco = cms.Sequence(calolocalrecoTask) # # R.Ofierzynski (29.Oct.2009): add NZS sequence # from RecoLocalCalo.Configuration.hcalLocalRecoNZS_cff import * calolocalrecoTaskNZS = cms.Task(ecalLocalRecoTask,hcalLocalRecoTask,hcalLocalRecoTaskNZS) calolocalrecoNZS = cms.Sequence(calolocalrecoTaskNZS)
422
2,962
package com.pushtorefresh.storio3.sample.sqldelight; // //import android.content.ContentValues; //import android.database.Cursor; //import android.os.Bundle; //import android.support.annotation.Nullable; //import android.support.v7.widget.DividerItemDecoration; //import android.support.v7.widget.LinearLayoutManager; //import android.support.v7.widget.RecyclerView; //import android.view.LayoutInflater; // //import com.pushtorefresh.storio3.sample.R; //import com.pushtorefresh.storio3.sample.SampleApp; //import com.pushtorefresh.storio3.sample.sqldelight.entities.Customer; //import com.pushtorefresh.storio3.sample.ui.UiStateController; //import com.pushtorefresh.storio3.sample.ui.activity.BaseActivity; //import com.pushtorefresh.storio3.sqlite.StorIOSQLite; // //import java.util.ArrayList; //import java.util.Collections; //import java.util.List; // //import javax.inject.Inject; // //import butterknife.Bind; //import butterknife.ButterKnife; //import butterknife.OnClick; //import io.reactivex.disposables.Disposable; //import io.reactivex.functions.Action; //import io.reactivex.functions.Consumer; //import io.reactivex.functions.Function; //import timber.log.Timber; // //import static com.pushtorefresh.storio3.sample.sqldelight.SQLUtils.makeReadQuery; //import static com.pushtorefresh.storio3.sample.sqldelight.SQLUtils.mapFromCursor; //import static com.pushtorefresh.storio3.sample.ui.Toasts.safeShowShortToast; //import static io.reactivex.BackpressureStrategy.LATEST; //import static io.reactivex.android.schedulers.AndroidSchedulers.mainThread; // //public class SqlDelightActivity extends BaseActivity { // // @Inject // StorIOSQLite storIOSQLite; // // UiStateController uiStateController; // // @Bind(R.id.customers_recycler_view) // RecyclerView recyclerView; // // CustomersAdapter customersAdapter; // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_sqldelight); // SampleApp.get(this).appComponent().inject(this); // customersAdapter = new CustomersAdapter(LayoutInflater.from(this)); // // ButterKnife.bind(this); // // recyclerView.setLayoutManager(new LinearLayoutManager(this)); // recyclerView.setAdapter(customersAdapter); // recyclerView.setHasFixedSize(true); // recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); // // uiStateController = new UiStateController.Builder() // .withLoadingUi(findViewById(R.id.customer_loading_ui)) // .withErrorUi(findViewById(R.id.customers_error_ui)) // .withEmptyUi(findViewById(R.id.customers_empty_ui)) // .withContentUi(recyclerView) // .build(); // } // // @Override // public void onStart() { // super.onStart(); // loadData(); // } // // void loadData() { // uiStateController.setUiStateLoading(); // // final Disposable disposable = storIOSQLite // .get() // .cursor() // .withQuery(makeReadQuery(Customer.FACTORY.select_all())) // .prepare() // .asRxFlowable(LATEST) // .map(new Function<Cursor, List<Customer>>() { // @Override // public List<Customer> apply(Cursor cursor) { // return mapFromCursor(cursor, Customer.CURSOR_MAPPER); // } // }) // .observeOn(mainThread()) // .subscribe(new Consumer<List<Customer>>() { // @Override // public void accept(List<Customer> customers) { // if (customers.isEmpty()) { // uiStateController.setUiStateEmpty(); // customersAdapter.setCustomers(Collections.<Customer>emptyList()); // } else { // uiStateController.setUiStateContent(); // customersAdapter.setCustomers(customers); // } // } // }, new Consumer<Throwable>() { // @Override // public void accept(Throwable throwable) { // Timber.e(throwable, "loadData()"); // uiStateController.setUiStateError(); // customersAdapter.setCustomers(Collections.<Customer>emptyList()); // } // }); // disposeOnStop(disposable); // } // // @OnClick(R.id.customers_empty_ui_add_button) // void addContent() { // final List<Customer> customers = new ArrayList<Customer>(); // // customers.add(Customer.builder().name("Elon").surname("Musk").city("Boring").build()); // customers.add(Customer.builder().name("Jake").surname("Wharton").city("Pittsburgh").build()); // // List<ContentValues> contentValues = new ArrayList<ContentValues>(customers.size()); // for (Customer customer : customers) { // contentValues.add(Customer.FACTORY.marshal(customer).asContentValues()); // } // // disposeOnStop(storIOSQLite // .put() // .contentValues(contentValues) // .withPutResolver(Customer.CV_PUT_RESOLVER) // .prepare() // .asRxCompletable() // .observeOn(mainThread()) // .subscribe( // new Action() { // @Override // public void run() { // // no impl required // } // }, // new Consumer<Throwable>() { // @Override // public void accept(Throwable throwable) { // safeShowShortToast(SqlDelightActivity.this, R.string.common_error); // } // })); // } //} //
2,953
1,403
<reponame>moroten/scons #!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" """ Verify use of the nargs='?' keyword argument to specify a long command-line option with an optional argument value. """ import TestSCons test = TestSCons.TestSCons() test.write('SConstruct', """\ AddOption('--install', nargs='?', dest='install', default='/default/directory', const='/called/default/directory', action='store', type='string', metavar='DIR', help='installation directory') print(GetOption('install')) """) test.run('-Q -q', stdout="/default/directory\n") test.run('-Q -q next-arg', stdout="/default/directory\n", status=1) test.run('-Q -q . --install', stdout="/called/default/directory\n") test.run('-Q -q . --install next-arg', stdout="/called/default/directory\n", status=1) test.run('-Q -q . first-arg --install', stdout="/called/default/directory\n", status=1) test.run('-Q -q . first-arg --install next-arg', stdout="/called/default/directory\n", status=1) test.run('-Q -q . --install=/command/line/directory', stdout="/command/line/directory\n") test.run('-Q -q . --install=/command/line/directory next-arg', stdout="/command/line/directory\n", status=1) test.run('-Q -q . first-arg --install=/command/line/directory', stdout="/command/line/directory\n", status=1) test.run('-Q -q . first-arg --install=/command/line/directory next-arg', stdout="/command/line/directory\n", status=1) test.write('SConstruct', """\ AddOption('-X', nargs='?') """) expect = r""" scons: \*\*\* option -X: nargs='\?' is incompatible with short options File "[^"]+", line \d+, in \S+ """ test.run(status=2, stderr=expect, match=TestSCons.match_re) test.pass_test() # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
1,164