code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
var com = com || {}; com.hiyoko = com.hiyoko || {}; com.hiyoko.component = com.hiyoko.component || {}; com.hiyoko.component.UlList = function($html){}; com.hiyoko.util.extend(com.hiyoko.component.ApplicationBase, com.hiyoko.component.UlList); com.hiyoko.component.UlList.prototype.renderDefaultLi = function($li, item) { if(item.type !== 'node') { var $text = $('<span></span>') $text.text(item.text); $text.addClass('com-hiyoko-component-ul-list-li-text'); $li.append($text); } $li.attr('title', item.value); return $li; } com.hiyoko.component.UlList.prototype.buildList = function(list, opt_option) { this.$html.empty(); var $ul = $('<ul></ul>'); var option = opt_option || {renderer: this.renderDefaultLi.bind(this)}; list.forEach(function(item){ var $li = $('<li></li>'); $li = option.renderer($li, item, option); if(item.type !== 'leaf') { var tmpOption = opt_option || {renderer: this.renderDefaultLi.bind(this)}; tmpOption.child = true; $li.append(this.buildList(item.list, tmpOption)); } if(option.child) { $li.addClass('com-hiyoko-component-ul-list-li-child'); } else { $li.addClass('com-hiyoko-component-ul-list-li'); } $ul.append($li); }.bind(this)); this.$html.append($ul); return $ul; }; com.hiyoko.component.UlList.prototype.getValueLi = function($li) { var result = {}; var text = $li.children('.com-hiyoko-component-ul-list-li-text').text(); result.text = text; var $ul = $li.children('ul'); if($ul.length) { result.list = this.getValue($ul); } if(result.text && result.list) { result.type = 'namednode'; } else if(result.list) { result.type = 'node'; } else { result.type = 'leaf'; } return result; }; com.hiyoko.component.UlList.prototype.getValue = function(opt_$html) { if(opt_$html) { var $html = $(opt_$html); var result = []; $.each($html.children('li'), function(i, v){ result.push(this.getValueLi($(v))); }.bind(this)); return result; } else { return this.getValue(this.$html.children('ul')); } };
Shunshun94/shared
jquery/com/hiyoko/components/v1/UlList.js
JavaScript
gpl-3.0
2,032
/* This file is part of SevenZipSharp. SevenZipSharp is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SevenZipSharp 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 Lesser General public License for more details. You should have received a copy of the GNU Lesser General public License along with SevenZipSharp. If not, see <http://www.gnu.org/licenses/>. */ #define DOTNET20 #define UNMANAGED #define COMPRESS using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security.Permissions; #if !WINCE using FILETIME=System.Runtime.InteropServices.ComTypes.FILETIME; #elif WINCE using FILETIME=OpenNETCF.Runtime.InteropServices.ComTypes.FILETIME; #endif namespace SevenZip { #if UNMANAGED /// <summary> /// The structure to fix x64 and x32 variant size mismatch. /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct PropArray { uint _cElems; IntPtr _pElems; } /// <summary> /// COM VARIANT structure with special interface routines. /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct PropVariant { [FieldOffset(0)] private ushort _vt; /// <summary> /// IntPtr variant value. /// </summary> [FieldOffset(8)] private IntPtr _value; /*/// <summary> /// Byte variant value. /// </summary> [FieldOffset(8)] private byte _ByteValue;*/ /// <summary> /// Signed int variant value. /// </summary> [FieldOffset(8)] private Int32 _int32Value; /// <summary> /// Unsigned int variant value. /// </summary> [FieldOffset(8)] private UInt32 _uInt32Value; /// <summary> /// Long variant value. /// </summary> [FieldOffset(8)] private Int64 _int64Value; /// <summary> /// Unsigned long variant value. /// </summary> [FieldOffset(8)] private UInt64 _uInt64Value; /// <summary> /// FILETIME variant value. /// </summary> [FieldOffset(8)] private FILETIME _fileTime; /// <summary> /// The PropArray instance to fix the variant size on x64 bit systems. /// </summary> [FieldOffset(8)] private PropArray _propArray; /// <summary> /// Gets or sets variant type. /// </summary> public VarEnum VarType { private get { return (VarEnum) _vt; } set { _vt = (ushort) value; } } /// <summary> /// Gets or sets the pointer value of the COM variant /// </summary> public IntPtr Value { private get { return _value; } set { _value = value; } } /* /// <summary> /// Gets or sets the byte value of the COM variant /// </summary> public byte ByteValue { get { return _ByteValue; } set { _ByteValue = value; } } */ /// <summary> /// Gets or sets the UInt32 value of the COM variant. /// </summary> public UInt32 UInt32Value { private get { return _uInt32Value; } set { _uInt32Value = value; } } /// <summary> /// Gets or sets the UInt32 value of the COM variant. /// </summary> public Int32 Int32Value { private get { return _int32Value; } set { _int32Value = value; } } /// <summary> /// Gets or sets the Int64 value of the COM variant /// </summary> public Int64 Int64Value { private get { return _int64Value; } set { _int64Value = value; } } /// <summary> /// Gets or sets the UInt64 value of the COM variant /// </summary> public UInt64 UInt64Value { private get { return _uInt64Value; } set { _uInt64Value = value; } } /* /// <summary> /// Gets or sets the FILETIME value of the COM variant /// </summary> public System.Runtime.InteropServices.ComTypes.FILETIME FileTime { get { return _fileTime; } set { _fileTime = value; } } */ /*/// <summary> /// Gets or sets variant type (ushort). /// </summary> public ushort VarTypeNative { get { return _vt; } set { _vt = value; } }*/ /*/// <summary> /// Clears variant /// </summary> public void Clear() { switch (VarType) { case VarEnum.VT_EMPTY: break; case VarEnum.VT_NULL: case VarEnum.VT_I2: case VarEnum.VT_I4: case VarEnum.VT_R4: case VarEnum.VT_R8: case VarEnum.VT_CY: case VarEnum.VT_DATE: case VarEnum.VT_ERROR: case VarEnum.VT_BOOL: case VarEnum.VT_I1: case VarEnum.VT_UI1: case VarEnum.VT_UI2: case VarEnum.VT_UI4: case VarEnum.VT_I8: case VarEnum.VT_UI8: case VarEnum.VT_INT: case VarEnum.VT_UINT: case VarEnum.VT_HRESULT: case VarEnum.VT_FILETIME: _vt = 0; break; default: if (NativeMethods.PropVariantClear(ref this) != (int)OperationResult.Ok) { throw new ArgumentException("PropVariantClear has failed for some reason."); } break; } }*/ /// <summary> /// Gets the object for this PropVariant. /// </summary> /// <returns></returns> public object Object { get { #if !WINCE var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); #endif switch (VarType) { case VarEnum.VT_EMPTY: return null; case VarEnum.VT_FILETIME: try { return DateTime.FromFileTime(Int64Value); } catch (ArgumentOutOfRangeException) { return DateTime.MinValue; } default: GCHandle propHandle = GCHandle.Alloc(this, GCHandleType.Pinned); try { return Marshal.GetObjectForNativeVariant(propHandle.AddrOfPinnedObject()); } #if WINCE catch (NotSupportedException) { switch (VarType) { case VarEnum.VT_UI8: return UInt64Value; case VarEnum.VT_UI4: return UInt32Value; case VarEnum.VT_I8: return Int64Value; case VarEnum.VT_I4: return Int32Value; default: return 0; } } #endif finally { propHandle.Free(); } } } } /// <summary> /// Determines whether the specified System.Object is equal to the current PropVariant. /// </summary> /// <param name="obj">The System.Object to compare with the current PropVariant.</param> /// <returns>true if the specified System.Object is equal to the current PropVariant; otherwise, false.</returns> public override bool Equals(object obj) { return (obj is PropVariant) ? Equals((PropVariant) obj) : false; } /// <summary> /// Determines whether the specified PropVariant is equal to the current PropVariant. /// </summary> /// <param name="afi">The PropVariant to compare with the current PropVariant.</param> /// <returns>true if the specified PropVariant is equal to the current PropVariant; otherwise, false.</returns> private bool Equals(PropVariant afi) { if (afi.VarType != VarType) { return false; } if (VarType != VarEnum.VT_BSTR) { return afi.Int64Value == Int64Value; } return afi.Value == Value; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> A hash code for the current PropVariant.</returns> public override int GetHashCode() { return Value.GetHashCode(); } /// <summary> /// Returns a System.String that represents the current PropVariant. /// </summary> /// <returns>A System.String that represents the current PropVariant.</returns> public override string ToString() { return "[" + Value + "] " + Int64Value.ToString(CultureInfo.CurrentCulture); } /// <summary> /// Determines whether the specified PropVariant instances are considered equal. /// </summary> /// <param name="afi1">The first PropVariant to compare.</param> /// <param name="afi2">The second PropVariant to compare.</param> /// <returns>true if the specified PropVariant instances are considered equal; otherwise, false.</returns> public static bool operator ==(PropVariant afi1, PropVariant afi2) { return afi1.Equals(afi2); } /// <summary> /// Determines whether the specified PropVariant instances are not considered equal. /// </summary> /// <param name="afi1">The first PropVariant to compare.</param> /// <param name="afi2">The second PropVariant to compare.</param> /// <returns>true if the specified PropVariant instances are not considered equal; otherwise, false.</returns> public static bool operator !=(PropVariant afi1, PropVariant afi2) { return !afi1.Equals(afi2); } } /// <summary> /// Stores file extraction modes. /// </summary> internal enum AskMode { /// <summary> /// Extraction mode /// </summary> Extract = 0, /// <summary> /// Test mode /// </summary> Test, /// <summary> /// Skip mode /// </summary> Skip } /// <summary> /// Stores operation result values /// </summary> public enum OperationResult { /// <summary> /// Success /// </summary> Ok = 0, /// <summary> /// Method is unsupported /// </summary> UnsupportedMethod, /// <summary> /// Data error has occured /// </summary> DataError, /// <summary> /// CrcError has occured /// </summary> CrcError } /// <summary> /// Codes of item properities /// </summary> internal enum ItemPropId : uint { /// <summary> /// No property /// </summary> NoProperty = 0, /// <summary> /// Handler item index /// </summary> HandlerItemIndex = 2, /// <summary> /// Item path /// </summary> Path, /// <summary> /// Item name /// </summary> Name, /// <summary> /// Item extension /// </summary> Extension, /// <summary> /// true if the item is a folder; otherwise, false /// </summary> IsDirectory, /// <summary> /// Item size /// </summary> Size, /// <summary> /// Item packed sise; usually absent /// </summary> PackedSize, /// <summary> /// Item attributes; usually absent /// </summary> Attributes, /// <summary> /// Item creation time; usually absent /// </summary> CreationTime, /// <summary> /// Item last access time; usually absent /// </summary> LastAccessTime, /// <summary> /// Item last write time /// </summary> LastWriteTime, /// <summary> /// true if the item is solid; otherwise, false /// </summary> Solid, /// <summary> /// true if the item is commented; otherwise, false /// </summary> Commented, /// <summary> /// true if the item is encrypted; otherwise, false /// </summary> Encrypted, /// <summary> /// (?) /// </summary> SplitBefore, /// <summary> /// (?) /// </summary> SplitAfter, /// <summary> /// Dictionary size(?) /// </summary> DictionarySize, /// <summary> /// Item CRC checksum /// </summary> Crc, /// <summary> /// Item type(?) /// </summary> Type, /// <summary> /// (?) /// </summary> IsAnti, /// <summary> /// Compression method /// </summary> Method, /// <summary> /// (?); usually absent /// </summary> HostOS, /// <summary> /// Item file system; usually absent /// </summary> FileSystem, /// <summary> /// Item user(?); usually absent /// </summary> User, /// <summary> /// Item group(?); usually absent /// </summary> Group, /// <summary> /// Bloack size(?) /// </summary> Block, /// <summary> /// Item comment; usually absent /// </summary> Comment, /// <summary> /// Item position /// </summary> Position, /// <summary> /// Item prefix(?) /// </summary> Prefix, /// <summary> /// Number of subdirectories /// </summary> NumSubDirs, /// <summary> /// Numbers of subfiles /// </summary> NumSubFiles, /// <summary> /// The archive legacy unpacker version /// </summary> UnpackVersion, /// <summary> /// Volume(?) /// </summary> Volume, /// <summary> /// Is a volume /// </summary> IsVolume, /// <summary> /// Offset value(?) /// </summary> Offset, /// <summary> /// Links(?) /// </summary> Links, /// <summary> /// Number of blocks /// </summary> NumBlocks, /// <summary> /// Number of volumes(?) /// </summary> NumVolumes, /// <summary> /// Time type(?) /// </summary> TimeType, /// <summary> /// 64-bit(?) /// </summary> Bit64, /// <summary> /// BigEndian /// </summary> BigEndian, /// <summary> /// Cpu(?) /// </summary> Cpu, /// <summary> /// Physical archive size /// </summary> PhysicalSize, /// <summary> /// Headers size /// </summary> HeadersSize, /// <summary> /// Archive checksum /// </summary> Checksum, /// <summary> /// (?) /// </summary> TotalSize = 0x1100, /// <summary> /// (?) /// </summary> FreeSpace, /// <summary> /// Cluster size(?) /// </summary> ClusterSize, /// <summary> /// Volume name(?) /// </summary> VolumeName, /// <summary> /// Local item name(?); usually absent /// </summary> LocalName = 0x1200, /// <summary> /// (?) /// </summary> Provider, /// <summary> /// User defined property; usually absent /// </summary> UserDefined = 0x10000 } /*/// <summary> /// Codes of archive properties or modes. /// </summary> internal enum ArchivePropId : uint { Name = 0, ClassID, Extension, AddExtension, Update, KeepName, StartSignature, FinishSignature, Associate }*/ /// <summary> /// PropId string names dictionary wrapper. /// </summary> internal static class PropIdToName { /// <summary> /// PropId string names /// </summary> public static readonly Dictionary<ItemPropId, string> PropIdNames = #region Initialization new Dictionary<ItemPropId, string>(46) { {ItemPropId.Path, "Path"}, {ItemPropId.Name, "Name"}, {ItemPropId.IsDirectory, "Folder"}, {ItemPropId.Size, "Size"}, {ItemPropId.PackedSize, "Packed Size"}, {ItemPropId.Attributes, "Attributes"}, {ItemPropId.CreationTime, "Created"}, {ItemPropId.LastAccessTime, "Accessed"}, {ItemPropId.LastWriteTime, "Modified"}, {ItemPropId.Solid, "Solid"}, {ItemPropId.Commented, "Commented"}, {ItemPropId.Encrypted, "Encrypted"}, {ItemPropId.SplitBefore, "Split Before"}, {ItemPropId.SplitAfter, "Split After"}, { ItemPropId.DictionarySize, "Dictionary Size" }, {ItemPropId.Crc, "CRC"}, {ItemPropId.Type, "Type"}, {ItemPropId.IsAnti, "Anti"}, {ItemPropId.Method, "Method"}, {ItemPropId.HostOS, "Host OS"}, {ItemPropId.FileSystem, "File System"}, {ItemPropId.User, "User"}, {ItemPropId.Group, "Group"}, {ItemPropId.Block, "Block"}, {ItemPropId.Comment, "Comment"}, {ItemPropId.Position, "Position"}, {ItemPropId.Prefix, "Prefix"}, { ItemPropId.NumSubDirs, "Number of subdirectories" }, { ItemPropId.NumSubFiles, "Number of subfiles" }, { ItemPropId.UnpackVersion, "Unpacker version" }, {ItemPropId.Volume, "Volume"}, {ItemPropId.IsVolume, "IsVolume"}, {ItemPropId.Offset, "Offset"}, {ItemPropId.Links, "Links"}, { ItemPropId.NumBlocks, "Number of blocks" }, { ItemPropId.NumVolumes, "Number of volumes" }, {ItemPropId.TimeType, "Time type"}, {ItemPropId.Bit64, "64-bit"}, {ItemPropId.BigEndian, "Big endian"}, {ItemPropId.Cpu, "CPU"}, { ItemPropId.PhysicalSize, "Physical Size" }, {ItemPropId.HeadersSize, "Headers Size"}, {ItemPropId.Checksum, "Checksum"}, {ItemPropId.FreeSpace, "Free Space"}, {ItemPropId.ClusterSize, "Cluster Size"} }; #endregion } /// <summary> /// 7-zip IArchiveOpenCallback imported interface to handle the opening of an archive. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600100000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IArchiveOpenCallback { // ref ulong replaced with IntPtr because handlers often pass null value // read actual value with Marshal.ReadInt64 /// <summary> /// Sets total data size /// </summary> /// <param name="files">Files pointer</param> /// <param name="bytes">Total size in bytes</param> void SetTotal( IntPtr files, IntPtr bytes); /// <summary> /// Sets completed size /// </summary> /// <param name="files">Files pointer</param> /// <param name="bytes">Completed size in bytes</param> void SetCompleted( IntPtr files, IntPtr bytes); } /// <summary> /// 7-zip ICryptoGetTextPassword imported interface to get the archive password. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000500100000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ICryptoGetTextPassword { /// <summary> /// Gets password for the archive /// </summary> /// <param name="password">Password for the archive</param> /// <returns>Zero if everything is OK</returns> [PreserveSig] int CryptoGetTextPassword( [MarshalAs(UnmanagedType.BStr)] out string password); } /// <summary> /// 7-zip ICryptoGetTextPassword2 imported interface for setting the archive password. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000500110000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ICryptoGetTextPassword2 { /// <summary> /// Sets password for the archive /// </summary> /// <param name="passwordIsDefined">Specifies whether archive has a password or not (0 if not)</param> /// <param name="password">Password for the archive</param> /// <returns>Zero if everything is OK</returns> [PreserveSig] int CryptoGetTextPassword2( ref int passwordIsDefined, [MarshalAs(UnmanagedType.BStr)] out string password); } /// <summary> /// 7-zip IArchiveExtractCallback imported interface. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600200000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IArchiveExtractCallback { /// <summary> /// Gives the size of the unpacked archive files /// </summary> /// <param name="total">Size of the unpacked archive files (in bytes)</param> void SetTotal(ulong total); /// <summary> /// SetCompleted 7-zip function /// </summary> /// <param name="completeValue"></param> void SetCompleted([In] ref ulong completeValue); /// <summary> /// Gets the stream for file extraction /// </summary> /// <param name="index">File index in the archive file table</param> /// <param name="outStream">Pointer to the stream</param> /// <param name="askExtractMode">Extraction mode</param> /// <returns>S_OK - OK, S_FALSE - skip this file</returns> [PreserveSig] int GetStream( uint index, [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialOutStream outStream, AskMode askExtractMode); /// <summary> /// PrepareOperation 7-zip function /// </summary> /// <param name="askExtractMode">Ask mode</param> void PrepareOperation(AskMode askExtractMode); /// <summary> /// Sets the operaton result /// </summary> /// <param name="operationResult">The operation result</param> void SetOperationResult(OperationResult operationResult); } /// <summary> /// 7-zip IArchiveUpdateCallback imported interface. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600800000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IArchiveUpdateCallback { /// <summary> /// Gives the size of the unpacked archive files. /// </summary> /// <param name="total">Size of the unpacked archive files (in bytes)</param> void SetTotal(ulong total); /// <summary> /// SetCompleted 7-zip internal function. /// </summary> /// <param name="completeValue"></param> void SetCompleted([In] ref ulong completeValue); /// <summary> /// Gets archive update mode. /// </summary> /// <param name="index">File index</param> /// <param name="newData">1 if new, 0 if not</param> /// <param name="newProperties">1 if new, 0 if not</param> /// <param name="indexInArchive">-1 if doesn't matter</param> /// <returns></returns> [PreserveSig] int GetUpdateItemInfo( uint index, ref int newData, ref int newProperties, ref uint indexInArchive); /// <summary> /// Gets the archive item property data. /// </summary> /// <param name="index">Item index</param> /// <param name="propId">Property identificator</param> /// <param name="value">Property value</param> /// <returns>Zero if Ok</returns> [PreserveSig] int GetProperty(uint index, ItemPropId propId, ref PropVariant value); /// <summary> /// Gets the stream for reading. /// </summary> /// <param name="index">The item index.</param> /// <param name="inStream">The ISequentialInStream pointer for reading.</param> /// <returns>Zero if Ok</returns> [PreserveSig] int GetStream( uint index, [Out, MarshalAs(UnmanagedType.Interface)] out ISequentialInStream inStream); /// <summary> /// Sets the result for currently performed operation. /// </summary> /// <param name="operationResult">The result value.</param> void SetOperationResult(OperationResult operationResult); /// <summary> /// EnumProperties 7-zip internal function. /// </summary> /// <param name="enumerator">The enumerator pointer.</param> /// <returns></returns> long EnumProperties(IntPtr enumerator); } /// <summary> /// 7-zip IArchiveOpenVolumeCallback imported interface to handle archive volumes. /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600300000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IArchiveOpenVolumeCallback { /// <summary> /// Gets the archive property data. /// </summary> /// <param name="propId">The property identificator.</param> /// <param name="value">The property value.</param> [PreserveSig] int GetProperty( ItemPropId propId, ref PropVariant value); /// <summary> /// Gets the stream for reading the volume. /// </summary> /// <param name="name">The volume file name.</param> /// <param name="inStream">The IInStream pointer for reading.</param> /// <returns>Zero if Ok</returns> [PreserveSig] int GetStream( [MarshalAs(UnmanagedType.LPWStr)] string name, [Out, MarshalAs(UnmanagedType.Interface)] out IInStream inStream); } /// <summary> /// 7-zip ISequentialInStream imported interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000300010000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISequentialInStream { /// <summary> /// Writes data to 7-zip packer /// </summary> /// <param name="data">Array of bytes available for writing</param> /// <param name="size">Array size</param> /// <returns>S_OK if success</returns> /// <remarks>If (size > 0) and there are bytes in stream, /// this function must read at least 1 byte. /// This function is allowed to read less than "size" bytes. /// You must call Read function in loop, if you need exact amount of data. /// </remarks> int Read( [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, uint size); } /// <summary> /// 7-zip ISequentialOutStream imported interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000300020000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISequentialOutStream { /// <summary> /// Writes data to unpacked file stream /// </summary> /// <param name="data">Array of bytes available for reading</param> /// <param name="size">Array size</param> /// <param name="processedSize">Processed data size</param> /// <returns>S_OK if success</returns> /// <remarks>If size != 0, return value is S_OK and (*processedSize == 0), /// then there are no more bytes in stream. /// If (size > 0) and there are bytes in stream, /// this function must read at least 1 byte. /// This function is allowed to rwrite less than "size" bytes. /// You must call Write function in loop, if you need exact amount of data. /// </remarks> [PreserveSig] int Write( [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, uint size, IntPtr processedSize); } /// <summary> /// 7-zip IInStream imported interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000300030000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IInStream { /// <summary> /// Read routine /// </summary> /// <param name="data">Array of bytes to set</param> /// <param name="size">Array size</param> /// <returns>Zero if Ok</returns> int Read( [Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, uint size); /// <summary> /// Seek routine /// </summary> /// <param name="offset">Offset value</param> /// <param name="seekOrigin">Seek origin value</param> /// <param name="newPosition">New position pointer</param> void Seek( long offset, SeekOrigin seekOrigin, IntPtr newPosition); } /// <summary> /// 7-zip IOutStream imported interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000300040000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IOutStream { /// <summary> /// Write routine /// </summary> /// <param name="data">Array of bytes to get</param> /// <param name="size">Array size</param> /// <param name="processedSize">Processed size</param> /// <returns>Zero if Ok</returns> [PreserveSig] int Write( [In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data, uint size, IntPtr processedSize); /// <summary> /// Seek routine /// </summary> /// <param name="offset">Offset value</param> /// <param name="seekOrigin">Seek origin value</param> /// <param name="newPosition">New position pointer</param> void Seek( long offset, SeekOrigin seekOrigin, IntPtr newPosition); /// <summary> /// Set size routine /// </summary> /// <param name="newSize">New size value</param> /// <returns>Zero if Ok</returns> [PreserveSig] int SetSize(long newSize); } /// <summary> /// 7-zip essential in archive interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600600000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IInArchive { /// <summary> /// Opens archive for reading. /// </summary> /// <param name="stream">Archive file stream</param> /// <param name="maxCheckStartPosition">Maximum start position for checking</param> /// <param name="openArchiveCallback">Callback for opening archive</param> /// <returns></returns> [PreserveSig] int Open( IInStream stream, [In] ref ulong maxCheckStartPosition, [MarshalAs(UnmanagedType.Interface)] IArchiveOpenCallback openArchiveCallback); /// <summary> /// Closes the archive. /// </summary> void Close(); /// <summary> /// Gets the number of files in the archive file table . /// </summary> /// <returns>The number of files in the archive</returns> uint GetNumberOfItems(); /// <summary> /// Retrieves specific property data. /// </summary> /// <param name="index">File index in the archive file table</param> /// <param name="propId">Property code</param> /// <param name="value">Property variant value</param> void GetProperty( uint index, ItemPropId propId, ref PropVariant value); // PropVariant /// <summary> /// Extracts files from the opened archive. /// </summary> /// <param name="indexes">indexes of files to be extracted (must be sorted)</param> /// <param name="numItems">0xFFFFFFFF means all files</param> /// <param name="testMode">testMode != 0 means "test files operation"</param> /// <param name="extractCallback">IArchiveExtractCallback for operations handling</param> /// <returns>0 if success</returns> [PreserveSig] int Extract( [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] uint[] indexes, uint numItems, int testMode, [MarshalAs(UnmanagedType.Interface)] IArchiveExtractCallback extractCallback); /// <summary> /// Gets archive property data /// </summary> /// <param name="propId">Archive property identificator</param> /// <param name="value">Archive property value</param> void GetArchiveProperty( ItemPropId propId, // PROPID ref PropVariant value); // PropVariant /// <summary> /// Gets the number of properties /// </summary> /// <returns>The number of properties</returns> uint GetNumberOfProperties(); /// <summary> /// Gets property information /// </summary> /// <param name="index">Item index</param> /// <param name="name">Name</param> /// <param name="propId">Property identificator</param> /// <param name="varType">Variant type</param> void GetPropertyInfo( uint index, [MarshalAs(UnmanagedType.BStr)] out string name, out ItemPropId propId, // PROPID out ushort varType); //VARTYPE /// <summary> /// Gets the number of archive properties /// </summary> /// <returns>The number of archive properties</returns> uint GetNumberOfArchiveProperties(); /// <summary> /// Gets the archive property information /// </summary> /// <param name="index">Item index</param> /// <param name="name">Name</param> /// <param name="propId">Property identificator</param> /// <param name="varType">Variant type</param> void GetArchivePropertyInfo( uint index, [MarshalAs(UnmanagedType.BStr)] out string name, out ItemPropId propId, // PROPID out ushort varType); //VARTYPE } /// <summary> /// 7-zip essential out archive interface /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600A00000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IOutArchive { /// <summary> /// Updates archive items /// </summary> /// <param name="outStream">The ISequentialOutStream pointer for writing the archive data</param> /// <param name="numItems">Number of archive items</param> /// <param name="updateCallback">The IArchiveUpdateCallback pointer</param> /// <returns>Zero if Ok</returns> [PreserveSig] int UpdateItems( [MarshalAs(UnmanagedType.Interface)] ISequentialOutStream outStream, uint numItems, [MarshalAs(UnmanagedType.Interface)] IArchiveUpdateCallback updateCallback); /// <summary> /// Gets file time type(?) /// </summary> /// <param name="type">Type pointer</param> void GetFileTimeType(IntPtr type); } /// <summary> /// 7-zip ISetProperties interface for setting various archive properties /// </summary> [ComImport] [Guid("23170F69-40C1-278A-0000-000600030000")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISetProperties { /// <summary> /// Sets the archive properties /// </summary> /// <param name="names">The names of the properties</param> /// <param name="values">The values of the properties</param> /// <param name="numProperties">The properties count</param> /// <returns></returns> int SetProperties(IntPtr names, IntPtr values, int numProperties); } #endif }
Nhakin/hakchi2
SevenZip/COM.cs
C#
gpl-3.0
39,542
#!python # log/urls.py from django.conf.urls import url from . import views # We are adding a URL called /home urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^clients/$', views.clients, name='clients'), url(r'^clients/(?P<id>\d+)/$', views.client_detail, name='client_detail'), url(r'^clients/new/$', views.client_new, name='client_new'), url(r'^clients/(?P<id>\d+)/edit/$', views.client_edit, name='client_edit'), url(r'^clients/sevices/$', views.clients_services_count, name='clients_services_count'), url(r'^clients/bills/(?P<id>\d+)/$', views.all_clients_bills, name='all_clients_bills'), url(r'^clients/bills/$', views.fresh_clients, name='fresh_clients'), url(r'^clients/del/(?P<id>\d+)/$', views.delete_client, name='delete_client'), url(r'^contracts/$', views.contracts, name='contracts'), url(r'^contracts/(?P<id>\d+)/$', views.contract_detail, name='contract_detail'), url(r'^contracts/new/$', views.contract_new, name='contract_new'), url(r'^contracts/(?P<id>\d+)/edit/$', views.contract_edit, name='contract_edit'), url(r'^contracts/list/(?P<id>\d+)/$', views.all_clients_contracts, name='all_clients_contracts'), url(r'^contracts/list/$', views.contracts_services, name='contracts_services'), url(r'^contracts/del/(?P<id>\d+)/$', views.delete_contract, name='delete_contract'), url(r'^manager/$', views.managers, name='managers'), url(r'^manager/(?P<id>\d+)/$', views.manager_detail, name='manager_detail'), url(r'^manager/new/$', views.manager_new, name='manager_new'), url(r'^manager/(?P<id>\d+)/edit/$', views.manager_edit, name='manager_edit'), url(r'^manager/clients/$', views.managers_clients_count, name='managers_clients_count'), url(r'^managers/del/(?P<id>\d+)/$', views.delete_manager, name='delete_manager'), url(r'^briefs/$', views.brief, name='briefs'), url(r'^briefs/(?P<id>\d+)/$', views.brief_detail, name='brief_detail'), url(r'^briefs/new/$', views.brief_new, name='brief_new'), url(r'^briefs/(?P<id>\d+)/edit/$', views.brief_edit, name='brief_edit'), url(r'^briefs/del/(?P<id>\d+)/$', views.delete_brief, name='delete_brief'), url(r'^briefs/list/(?P<id>\d+)/$', views.all_clients_briefs, name='all_clients_briefs'), url(r'^services/$', views.services, name='services'), url(r'^services/(?P<id>\d+)/$', views.service_detail, name='service_detail'), url(r'^services/new/$', views.services_new, name='services_new'), url(r'^services/(?P<id>\d+)/edit/$', views.service_edit, name='service_edit'), url(r'^services/table/(?P<id>\d+)/$', views.service_all_clients, name='service_all_clients'), url(r'^services/del/(?P<id>\d+)/$', views.delete_service, name='delete_service'), url(r'^contractors/$', views.contractors, name='contractors'), url(r'^contractors/(?P<id>\d+)/$', views.contractor_detail, name='contractor_detail'), url(r'^contractors/new/$', views.contractors_new, name='contractors_new'), url(r'^contractors/(?P<id>\d+)/edit/$', views.contractor_edit, name='contractor_edit'), url(r'^contractors/newest/$', views.newest_contractors, name='newest_contractors'), url(r'^contractors/del/(?P<id>\d+)/$', views.delete_contractor, name='delete_contractor'), url(r'^acts/$', views.acts, name='acts'), url(r'^acts/(?P<id>\d+)/$', views.act_detail, name='act_detail'), url(r'^acts/new/$', views.act_new, name='act_new'), url(r'^acts/(?P<id>\d+)/edit/$', views.act_edit, name='act_edit'), url(r'^acts/del/(?P<id>\d+)/$', views.delete_act, name='delete_act'), url(r'^bills/$', views.bills, name='bills'), url(r'^bills/(?P<id>\d+)/$', views.bills_detail, name='bills_detail'), url(r'^bills/new/$', views.bills_new, name='bills_new'), url(r'^bills/(?P<id>\d+)/edit/$', views.bills_edit, name='bills_edit'), url(r'^bill/del/(?P<id>\d+)/$', views.delete_bill, name='delete_bill'), ]
alexeyshulzhenko/OBDZ_Project
OnlineAgecy/urls.py
Python
gpl-3.0
3,927
/** Copyright 2010 Christian Kästner This file is part of CIDE. CIDE 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, version 3 of the License. CIDE 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 CIDE. If not, see <http://www.gnu.org/licenses/>. See http://www.fosd.de/cide/ for further information. */ package cide.gast; import java.util.ArrayList; public class ASTStringNode extends ASTNode { private String value; public ASTStringNode(String value, IToken token) { super(new ArrayList<Property>(), token, token); this.value = value; } public String getValue() { return value; } public String toString() { return value; } @Override public IASTNode deepCopy() { return new ASTStringNode(new String(value), firstToken); } @Override public String render() { return getValue(); } }
ckaestne/CIDE
CIDE2_ast/src/cide/gast/ASTStringNode.java
Java
gpl-3.0
1,275
# Executa somatorio sobre uma colecao module EstatisticaDescritiva def ordenar sort! true end end
TiagoTi/tvaderonline
lib/estatistica_descritiva/ordenar.rb
Ruby
gpl-3.0
110
#!/usr/bin/python # bigcinemas class InvalidAge(Exception): def __init__(self,age): self.age = age def validate_age(age): if age < 18: raise InvalidAge(age) else: return "Welcome to the movies!!" age = int(raw_input("please enter your age:")) #print validate_age(age) try: validate_age(age) # except Exception as e: except InvalidAge as e: print "Buddy!! you are very young at {}!! Grow up a bit.".format(e.age) else: print validate_age(age)
tuxfux-hlp-notes/python-batches
archieves/batch-64/14-oop/sixth.py
Python
gpl-3.0
462
#include "querycondition.h" queryCondition::queryCondition(const QString &fieldName, const conditionOperator condition, const QStringList &values, QObject *parent) : QObject(parent) { _fieldName = fieldName; _condition = condition; _values = values; } queryCondition::~queryCondition() { } QString queryCondition::fieldName() const { return _fieldName; } queryCondition::conditionOperator queryCondition::condition() const { return _condition; } QStringList queryCondition::values() const { return _values; }
diegowald/atlas
atlas/db/querycondition.cpp
C++
gpl-3.0
538
<?php /** * @package pkg_projectspoon * * @author Kon Angelopoulos (angek) * @copyright Copyright (C) 2018 Kon Angelopoulos. All rights reserved. * @license http://www.gnu.org/licenses/gpl.html GNU/GPL, see LICENSE.txt */ // No direct access. defined('_JEXEC') or die; class PktimeControllerTimesheets extends JControllerLegacy { public function getModel($name = 'timesheet', $prefix = 'PktimeModel', $config = array()) { $model = parent::getModel($name, $prefix, array('ignore_request' => true)); return $model; } public function getTaskOptions() { $project_id = JFactory::getApplication()->input->getUInt('project_id', 0, 'integer'); $model = $this->getModel(); if ($project_id <= 0) { $items = array(); } else { $items = $model->getAssigneeTasksOptions($project_id); } echo new JResponseJson($items); } public function getAssigneeRate() { $assignee = JFactory::getApplication()->input->getUInt('uid', 0, 'integer'); $model = $this->getModel(); if ($assignee <=0) { $rate = array(); } else { $rate = $model->getAssigneeRate($assignee); } echo new JResponseJson($rate); } public function getAssignees() { $project_id = JFactory::getApplication()->input->getUInt('project_id', 0, 'integer'); $task_id = JFactory::getApplication()->input->getUInt('task_id', 0, 'integer'); $model = $this->getModel(); if ($project_id <= 0) { $items = array(); } elseif($task_id <= 0) { $items = array(); } else { $items = $model->getAssignees($project_id, $task_id); } echo new JResponseJson($items); } }
angek/ProjectSpoon
source/components/com_pktime/admin/controllers/timesheets.json.php
PHP
gpl-3.0
1,779
package v2ch10.compiler; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.net.URI; import javax.tools.SimpleJavaFileObject; /** * A Java class that holds the byte codes in a byte array. Created by ZHEN on 16/9/18. */ public class ByteArrayJavaClass extends SimpleJavaFileObject { private ByteArrayOutputStream stream; public ByteArrayJavaClass(String name) { super(URI.create("bytes:///" + name), Kind.CLASS); this.stream = new ByteArrayOutputStream(); } public OutputStream openOutputStream() { return stream; } public byte[] getBytes() { return stream.toByteArray(); } }
Token3/books-source-code
corejava9/src/main/java/v2ch10/compiler/ByteArrayJavaClass.java
Java
gpl-3.0
656
package org.cardiacatlas.xpacs.repository; import org.cardiacatlas.xpacs.domain.PatientInfo; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the PatientInfo entity. */ @SuppressWarnings("unused") public interface PatientInfoRepository extends JpaRepository<PatientInfo,Long> { }
CardiacAtlasProject/xpacs-web
src/main/java/org/cardiacatlas/xpacs/repository/PatientInfoRepository.java
Java
gpl-3.0
348
/* Craft Compiler v0.1.0 - The standard compiler for the Craft programming language. Copyright (C) 2016 Daniel McCarthy 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 3 of the License, or 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/>. */ /* * File: OffsetableBranch.cpp * Author: Daniel McCarthy * * Created on 01 January 2017, 21:32 * * Description: */ #include "OffsetableBranch.h" OffsetableBranch::OffsetableBranch(Compiler* compiler, std::shared_ptr<SegmentBranch> segment_branch, std::string type, std::string value) : ChildOfSegment(compiler, segment_branch, type, value) { this->next_offsetable_branch = NULL; } OffsetableBranch::~OffsetableBranch() { } void OffsetableBranch::setOffset(int offset) { this->offset = offset; } int OffsetableBranch::getOffset() { return this->offset; } void OffsetableBranch::setNextOffsetableBranch(std::shared_ptr<OffsetableBranch> branch) { this->next_offsetable_branch = branch; } std::shared_ptr<OffsetableBranch> OffsetableBranch::getNextOffsetableBranch() { return this->next_offsetable_branch; } void OffsetableBranch::imp_clone(std::shared_ptr<Branch> cloned_branch) { ChildOfSegment::imp_clone(cloned_branch); std::shared_ptr<OffsetableBranch> cloned_offsetable_branch = std::dynamic_pointer_cast<OffsetableBranch>(cloned_branch); cloned_offsetable_branch->setOffset(getOffset()); } std::shared_ptr<Branch> OffsetableBranch::create_clone() { return std::shared_ptr<OffsetableBranch>(new OffsetableBranch(getCompiler(), getSegmentBranch(), getType(), getValue())); }
nibblebits/craft-compiler
codegens/8086CodeGen/src/OffsetableBranch.cpp
C++
gpl-3.0
2,100
Fox.define('language', [], function () { var Language = function (cache) { this.cache = cache || null; this.data = {}; }; _.extend(Language.prototype, { data: null, cache: null, url: 'I18n', has: function (name, category, scope) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return true; } } } }, get: function (scope, category, name) { if (scope in this.data) { if (category in this.data[scope]) { if (name in this.data[scope][category]) { return this.data[scope][category][name]; } } } if (scope == 'Global') { return name; } return false; }, translate: function (name, category, scope) { scope = scope || 'Global'; category = category || 'labels'; var res = this.get(scope, category, name); if (res === false && scope != 'Global') { res = this.get('Global', category, name); } return res; }, translateOption: function (value, field, scope) { var translation = this.translate(field, 'options', scope); if (typeof translation != 'object') { translation = {}; } return translation[value] || value; }, loadFromCache: function () { if (this.cache) { var cached = this.cache.get('app', 'language'); if (cached) { this.data = cached; return true; } } return null; }, clearCache: function () { if (this.cache) { this.cache.clear('app', 'language'); } }, storeToCache: function () { if (this.cache) { this.cache.set('app', 'language', this.data); } }, load: function (callback, disableCache) { this.once('sync', callback); if (!disableCache) { if (this.loadFromCache()) { this.trigger('sync'); return; } } this.fetch(); }, fetch: function (sync) { var self = this; $.ajax({ url: this.url, type: 'GET', dataType: 'JSON', async: !(sync || false), success: function (data) { self.data = data; self.storeToCache(); self.trigger('sync'); } }); }, }, Backbone.Events); return Language; });
ilovefox8/zhcrm
client/src/language.js
JavaScript
gpl-3.0
3,025
# Copyright 2015 The TensorFlow Authors. 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. # ============================================================================== """A binary to train CIFAR-10 using a single GPU. Accuracy: cifar10_train.py achieves ~86% accuracy after 100K steps (256 epochs of data) as judged by cifar10_eval.py. Speed: With batch_size 128. System | Step Time (sec/batch) | Accuracy ------------------------------------------------------------------ 1 Tesla K20m | 0.35-0.60 | ~86% at 60K steps (5 hours) 1 Tesla K40m | 0.25-0.35 | ~86% at 100K steps (4 hours) Usage: Please see the tutorial and website for how to download the CIFAR-10 data set, compile the program and train the model. http://tensorflow.org/tutorials/deep_cnn/ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import time import tensorflow as tf import cifar10 FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string('train_dir', '/tmp/cifar10_train', """Directory where to write event logs """ """and checkpoint.""") tf.app.flags.DEFINE_integer('max_steps', 100000, #reduced significantly -daniel """Number of batches to run.""") tf.app.flags.DEFINE_boolean('log_device_placement', False, """Whether to log device placement.""") def train(): """Train CIFAR-10 for a number of steps.""" with tf.Graph().as_default(): global_step = tf.contrib.framework.get_or_create_global_step() # Get images and labels for CIFAR-10. images, labels = cifar10.distorted_inputs() # Build a Graph that computes the logits predictions from the # inference model. logits = cifar10.inference(images) # Calculate loss. loss = cifar10.loss(logits, labels) # Build a Graph that trains the model with one batch of examples and # updates the model parameters. train_op = cifar10.train(loss, global_step) class _LoggerHook(tf.train.SessionRunHook): """Logs loss and runtime.""" def begin(self): self._step = -1 def before_run(self, run_context): self._step += 1 self._start_time = time.time() return tf.train.SessionRunArgs(loss) # Asks for loss value. def after_run(self, run_context, run_values): duration = time.time() - self._start_time loss_value = run_values.results if self._step % 10 == 0: num_examples_per_step = FLAGS.batch_size examples_per_sec = num_examples_per_step / duration sec_per_batch = float(duration) format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f ' 'sec/batch)') print (format_str % (datetime.now(), self._step, loss_value, examples_per_sec, sec_per_batch)) with tf.train.MonitoredTrainingSession( checkpoint_dir=FLAGS.train_dir, hooks=[tf.train.StopAtStepHook(last_step=FLAGS.max_steps), tf.train.NanTensorHook(loss), _LoggerHook()], config=tf.ConfigProto( log_device_placement=FLAGS.log_device_placement)) as mon_sess: while not mon_sess.should_stop(): mon_sess.run(train_op) def main(argv=None): # pylint: disable=unused-argument cifar10.maybe_download_and_extract() if tf.gfile.Exists(FLAGS.train_dir): tf.gfile.DeleteRecursively(FLAGS.train_dir) tf.gfile.MakeDirs(FLAGS.train_dir) train() if __name__ == '__main__': tf.app.run()
dpaschall/test_TensorFlow
bin/cifar10test/cifar10_train.py
Python
gpl-3.0
4,167
package net.shadowmage.ancientwarfare.automation.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraftforge.common.util.Constants; import net.shadowmage.ancientwarfare.automation.tile.warehouse2.IWarehouseStorageTile; import net.shadowmage.ancientwarfare.automation.tile.warehouse2.TileControlled; import net.shadowmage.ancientwarfare.automation.tile.warehouse2.TileWarehouseStorage; import net.shadowmage.ancientwarfare.automation.tile.warehouse2.WarehouseStorageFilter; import net.shadowmage.ancientwarfare.core.container.ContainerBase; import net.shadowmage.ancientwarfare.core.container.ContainerTileBase; import net.shadowmage.ancientwarfare.core.inventory.ItemQuantityMap; import net.shadowmage.ancientwarfare.core.inventory.ItemQuantityMap.ItemHashEntry; import java.util.ArrayList; import java.util.List; public class ContainerWarehouseStorage extends ContainerTileBase<TileWarehouseStorage> { public int guiHeight; public int areaSize; int playerSlotsSize; int playerSlotsY; boolean shouldSynch = true; public ItemQuantityMap itemMap = new ItemQuantityMap(); public ItemQuantityMap cache = new ItemQuantityMap(); public List<WarehouseStorageFilter> filters = new ArrayList<WarehouseStorageFilter>(); public ContainerWarehouseStorage(EntityPlayer player, int x, int y, int z) { super(player, x, y, z); tileEntity.addViewer(this); areaSize = 5 * 18 + 16; playerSlotsY = 148 + 8; playerSlotsSize = 8 + 4 + 4 * 18; guiHeight = playerSlotsY + playerSlotsSize; filters.addAll(tileEntity.getFilters()); addPlayerSlots(8, playerSlotsY, 4); } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotClickedIndex) { if (player.worldObj.isRemote) { return null; } Slot slot = this.getSlot(slotClickedIndex); if (slot == null || !slot.getHasStack()) { return null; } ItemStack stack = slot.getStack(); stack = tileEntity.tryAdd(stack); if (stack == null) { slot.putStack(null); } detectAndSendChanges(); return null; } public void handleClientRequestSpecific(ItemStack stack, boolean isShiftClick) { NBTTagCompound tag = new NBTTagCompound(); if (stack != null) { tag.setTag("reqItem", stack.writeToNBT(new NBTTagCompound())); } tag.setBoolean("isShiftClick", isShiftClick); NBTTagCompound pktTag = new NBTTagCompound(); pktTag.setTag("slotClick", tag); sendDataToServer(pktTag); } @Override public void sendInitData() { NBTTagCompound tag = new NBTTagCompound(); tag.setTag("filterList", WarehouseStorageFilter.writeFilterList(filters)); sendDataToClient(tag); } public void sendFiltersToServer() { NBTTagCompound tag = new NBTTagCompound(); tag.setTag("filterList", WarehouseStorageFilter.writeFilterList(filters)); sendDataToServer(tag); } @Override public void handlePacketData(NBTTagCompound tag) { if (tag.hasKey("filterList")) { List<WarehouseStorageFilter> filters = WarehouseStorageFilter.readFilterList(tag.getTagList("filterList", Constants.NBT.TAG_COMPOUND), new ArrayList<WarehouseStorageFilter>()); if (player.worldObj.isRemote) { this.filters.clear(); this.filters.addAll(filters); refreshGui(); } else { tileEntity.setFilters(filters); } } if (tag.hasKey("slotClick")) { NBTTagCompound reqTag = tag.getCompoundTag("slotClick"); ItemStack item = null; if (reqTag.hasKey("reqItem")) { item = ItemStack.loadItemStackFromNBT(reqTag.getCompoundTag("reqItem")); } tileEntity.handleSlotClick(player, item, reqTag.getBoolean("isShiftClick")); } if (tag.hasKey("changeList")) { handleChangeList(tag.getTagList("changeList", Constants.NBT.TAG_COMPOUND)); refreshGui(); } super.handlePacketData(tag); } @Override public void detectAndSendChanges() { super.detectAndSendChanges(); if (shouldSynch) { synchItemMaps(); shouldSynch = false; } } private void handleChangeList(NBTTagList changeList) { NBTTagCompound tag; int qty; ItemHashEntry wrap = null; for (int i = 0; i < changeList.tagCount(); i++) { tag = changeList.getCompoundTagAt(i); wrap = ItemHashEntry.readFromNBT(tag); qty = tag.getInteger("qty"); if (qty == 0) { itemMap.remove(wrap); } else { itemMap.put(wrap, qty); } } } private void synchItemMaps() { /** * * need to loop through this.itemMap and compare quantities to warehouse.itemMap * add any changes to change-list * need to loop through warehouse.itemMap and find new entries * add any new entries to change-list */ cache.clear(); tileEntity.addItems(cache); ItemQuantityMap warehouseItemMap = cache; int qty; NBTTagList changeList = new NBTTagList(); NBTTagCompound tag; for (ItemHashEntry wrap : this.itemMap.keySet()) { qty = this.itemMap.getCount(wrap); if (qty != warehouseItemMap.getCount(wrap)) { qty = warehouseItemMap.getCount(wrap); tag = wrap.writeToNBT(new NBTTagCompound()); tag.setInteger("qty", qty); changeList.appendTag(tag); this.itemMap.put(wrap, qty); } } for (ItemHashEntry entry : warehouseItemMap.keySet()) { if (!itemMap.contains(entry)) { qty = warehouseItemMap.getCount(entry); tag = ItemHashEntry.writeToNBT(entry, new NBTTagCompound()); tag.setInteger("qty", qty); changeList.appendTag(tag); this.itemMap.put(entry, qty); } } if (changeList.tagCount() > 0) { tag = new NBTTagCompound(); tag.setTag("changeList", changeList); sendDataToClient(tag); } } public void onStorageInventoryUpdated() { shouldSynch = true; } public void onFilterListUpdated() { this.filters.clear(); this.filters.addAll(tileEntity.getFilters()); sendInitData(); } @Override public void onContainerClosed(EntityPlayer par1EntityPlayer) { tileEntity.removeViewer(this); super.onContainerClosed(par1EntityPlayer); } }
GotoLink/AncientWarfare2
src/main/java/net/shadowmage/ancientwarfare/automation/container/ContainerWarehouseStorage.java
Java
gpl-3.0
7,239
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package server.maps; import java.rmi.RemoteException; import java.util.List; import client.MapleCharacter; import java.util.ArrayList; import net.world.remote.WorldChannelInterface; import server.TimerManager; import tools.MaplePacketCreator; /* * MapleTVEffect * @author MrXotic */ public class MapleTVEffect { private List<String> message = new ArrayList<String>(5); private MapleCharacter user; private static boolean active; private int type; private MapleCharacter partner; public MapleTVEffect(MapleCharacter user_, MapleCharacter partner_, List<String> msg, int type_) { this.message = msg; this.user = user_; this.type = type_; this.partner = partner_; broadcastTV(true); } public static boolean isActive() { return active; } private void setActive(boolean set) { active = set; } private void broadcastTV(boolean active_) { WorldChannelInterface wci = user.getClient().getChannelServer().getWorldInterface(); setActive(active_); try { if (active_) { wci.broadcastMessage(null, MaplePacketCreator.enableTV().getBytes()); wci.broadcastMessage(null, MaplePacketCreator.sendTV(user, message, type <= 2 ? type : type - 3, partner).getBytes()); int delay = 15000; if (type == 4) { delay = 30000; } else if (type == 5) { delay = 60000; } TimerManager.getInstance().schedule(new Runnable() { @Override public void run() { broadcastTV(false); } }, delay); } else { wci.broadcastMessage(null, MaplePacketCreator.removeTV().getBytes()); } } catch (RemoteException re) { user.getClient().getChannelServer().reconnectWorld(); } } }
am910021/YuriMS
src/server/maps/MapleTVEffect.java
Java
gpl-3.0
2,984
//Created by: Jack Melvin //RPG game //v0.36 //Rules of the program //Variables are lowercase. //Functios start with upper case per word //Known Bugs //Hp doesnt raise after you talk with the inn keeper. //doom doesnt kill you. //Always glanceing blow. //To-Do //Finish Atk formula //equip items //working backpack //map borders //working enemies //working shop // V0.36 // * Added Input Logic Function // * Advanced Combat System // V0.35 updates // * Added attack formula and combat test system // V0.34 updates // * if to switch for Input function. // * Valid to invalid function. // * Moved world and HUD from input into play loop around play // * DOOOOOOOOM! #include <iostream> #include <iomanip> #include <cmath> #include <ctime> #include <string> #include <limits> #include <stdexcept> #include <windows.h> #include <stdio.h> using namespace std; //---------------[Global Variables]----------------------- //Player stats string name; int lvl = 1; int Php = 1; int PhpT = 20; int PhpP = Php * 100 / PhpT; int Patk = 1; int Pdef = 0; int turns = 1; int gold = 0; //Players Position int Px; int Py; //enemy int Eatk; int Ehp = 0; int Edef = 50; //GameVariables int mainmenu = 0; int leavegame = 0; int activate = 0; int doom = 0; string continuecode; int Pchoice, Echoice; //Items int map = 0; int backpack = 0; //----------------------[Classes]-------------- //-------------------[Window size]--------- struct console { console(unsigned width, unsigned height) { SMALL_RECT r; COORD c; hConOut = GetStdHandle(STD_OUTPUT_HANDLE); if (!GetConsoleScreenBufferInfo(hConOut, &csbi)) throw runtime_error("You must be attached to a human."); r.Left = r.Top = 0; r.Right = width - 1; r.Bottom = height - 1; SetConsoleWindowInfo(hConOut, TRUE, &r); c.X = width; c.Y = height; SetConsoleScreenBufferSize(hConOut, c); } ~console() { SetConsoleTextAttribute(hConOut, csbi.wAttributes); SetConsoleScreenBufferSize(hConOut, csbi.dwSize); SetConsoleWindowInfo(hConOut, TRUE, &csbi.srWindow); } void color(WORD color = 0x07) { SetConsoleTextAttribute(hConOut, color); } HANDLE hConOut; CONSOLE_SCREEN_BUFFER_INFO csbi; }; console con(55, 30); //--------------[Established Functions]------------------- void Opener(); void MainMenu(); void Play(); void Howtoplay(); void Credits(); void GameOver(); //world functions void World(); void EWDR(); void NWSEDR(); void LH(); void IKO(); void Enemies(); //game void HUD(); void Input(); void InputLogic(char); void Attack(int, int, int&, int, int, int, int&, int); void CombatTraining(); void Backpack(); void Map(); void Key(); //system void Invalid(); void HitEnter(); void Doom(); //--------------------[Main]------------------------------- int main() { Opener(); while (mainmenu != 1) { MainMenu(); } return 0; } //-------------------[Functions]------------------------- //Opening Screen void Opener() { cout << "\n\n\n\n\n"; cout << "\n xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"; cout << "\n xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"; cout << "\n ____ ____ _______ _ "; cout << "\n | \\ / | |__ __|___ ____ | | "; cout << "\n | \\ / | ___ | | / _ \\ / __| | |__ "; cout << "\n | |\\ \\/ /| | |___| | | / |_| \\ / / | _ \\ "; cout << "\n | | \\ / | | | | \\ ___/ \\ \\__ | / \\ \\ "; cout << "\n |__| \\__/ |__| |_| \\___/ \\____| |_| |_| "; cout << "\n\n\t\t\tStudios"; cout << "\n\n\t\tHit [Enter] to continue\n"; cout << "\n xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"; cout << "\n xXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"; cout << "\n\n\n\n\n\n\n\n\n"; HitEnter(); system("cls"); } //Main menu void MainMenu() { int mainmenuchoice; char input; system("cls"); cout << "\n\n\n\n\n"; cout << "\n\t\t|===================|"; cout << "\n\t\t| RPG Game |"; cout << "\n\t\t|===================|"; cout << "\n\t\t| 1 - New Game |"; cout << "\n\t\t| 2 - Continue Game |"; cout << "\n\t\t| 3 -Combat Training|"; cout << "\n\t\t| 4 - How to play |"; cout << "\n\t\t| 5 - Credits |"; cout << "\n\t\t| 6 - Quit |"; cout << "\n\t\t|===================|"; cout << "\n\t\t Choose one: "; cin >> mainmenuchoice; switch (mainmenuchoice) { case 1: Play(); break; case 2: //Code(); map = 1; Play(); break; case 3: CombatTraining(); MainMenu(); break; case 4: Howtoplay(); MainMenu(); break; case 5: Credits(); MainMenu(); break; case 6: system("cls"); cout << "\n\n Are you sure you want to quit? <Y/N> "; cin >> input; if (input == 'Y' || input == 'y') mainmenu = 1; else if (input == 'N' || input == 'n') MainMenu(); else { cout << "\n\tPlease make a valid selection.\n\n\t"; system("pause"); MainMenu(); } break; default: Invalid(); cin.clear(); cin.ignore(80, '\n'); MainMenu(); break; } } //Play void Play() { while (leavegame != 1) { system("cls"); if (Php = 0) leavegame = 1; HUD(); World(); Input(); } GameOver(); } //How to Play void Howtoplay() { system("cls"); cout << "\n\t| | -|- __ | "; cout << "\n\t|-| /\\ \\ / | /\\ | \\ | /\\ \\ /"; cout << "\n\t| | \\/ \\/\\/ | \\/ |_/ | \\/\\ \\/"; cout << "\n | /"; cout << "\n======================================================="; cout << "\n\t\t N "; cout << "\n\t\t | "; cout << "\n\t\t W--+--E "; cout << "\n\t\t | "; cout << "\n\t\t S \n"; cout << "\n\t Hit N, E, S, or W to move in that directon"; cout << "\n\t Hit A to Interact with you surroundings."; cout << "\n\t Hit B to open your backpack."; cout << "\n\t Hit M to open your map."; cout << "\n\t Hit Q to quit.\n\n\t-"; system("pause"); } //Displays HUD void HUD() { cout << "|Name:" << setw(10) << left << name << "|Level:" << setw(2) << lvl; cout << "|Life:" << setw(3) << right << PhpP << "%|ATK:+" << setw(2) << left << Patk; cout << "|Armour:+" << setw(2) << Pdef << "|"; cout << "|===============|========|=========|=======|==========|"; } //World void World() { int randomenemy; int doom; string x; srand((unsigned)time(0)); randomenemy = (rand() % 30); doom = (rand() % 1000000); cout << "\n Location: " << Px << " ," << Py; //dirt road if (Px <= 0 && Px >= -6 && Py == 1 || Px <= 7 && Px >= 2 && Py == 1 || Px == 10 && Py == 0) EWDR(); else if (Px == 8 && Py == 1 || Px == 9 && Py == 0 || Px == -7 && Py == 1 || Px == -8 && Py == 2 || Px == -9 && Py == 3 || Px == -10 && Py == 4) NWSEDR(); //dirt road 1 w/INN else if (Px == 1 && Py == 1) { if (activate == 1) { IKO(); activate = 0; Input(); } else { cout << "\n\n\tYou enter a clearing."; cout << "\n" << Php << "\n\tA dirt road runs east to west with an"; cout << "\n\n\tInn on the north side of the road."; cout << "\n\n\n\n\n\n\n\n\n\n\n"; } } //Lake Hiliya else if (Px >= 3 && Px <= 7 && Py == 7 || Px >= 3 && Px <= 9 && Py == 8 || Px >= 6 && Px <= 8 && Py == 10 || Px == 7 && Py == 11) LH(); //Forest with chance of random enemy else { //Boar if (randomenemy == 1) { cout << "\n\n\tYou are surrounded by trees."; cout << "\n\n\tA wild boar appears!"; cout << "\n\n\n\n\n\n\n\n\n\n\n\n"; } //Doom else if (doom == 1) { cout << "\n\n\tYou are surrounded by trees."; cout << "\n\n\tA deeps raspy voice echos out..."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n"; cout << "\n\n======================================================="; cout << "\n A N B\t\t\t\t Turn: " << turns; cout << "\n | "; cout << "\n W--X--E \t\t\t\t Gold: " << gold; cout << "\n | "; cout << "\n M S Q\t You cant move. \n\n\t "; system("pause"); Doom(); leavegame = doom = 0; } //Forest else { cout << "\n\n\tYou are surrounded by trees."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; } } } //east west dirt road void EWDR() { cout << "\n\n\tYou are surrounded by trees."; cout << "\n\n\tA dirt road runs east to west."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n"; } //Northwest Southeast dirt road void NWSEDR() { cout << "\n\n\tYou are surrounded by trees."; cout << "\n\n\tA dirt road runs form the"; cout << "\n\tnorth west, to south east."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n"; } //Lake Hiliya void LH() { cout << "\n\n\tYou are in Lake Hiliya."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; } //Player Controls. void Input() { char input; cout << "\n\n======================================================="; cout << "\n A N B\t\t\t\t Turn: " << turns; cout << "\n | "; cout << "\n W--X--E \t\t\t\t Gold: " << gold; cout << "\n | "; cout << "\n M S Q\tWhat do you want to do? "; cin >> input; InputLogic(input); Play(); } //Input Logic void InputLogic(char input) { switch (input) //Moving { case 'N': case 'n': Py = Py + 1; turns++; break; case 'E': case 'e': Px = Px + 1; turns++; break; case 'S': case 's': Py = Py - 1; turns++; break; case 'W': case 'w': Px = Px - 1; turns++; break; //Activate case 'A': case 'a': activate = 1; turns++; break; //Check Map case 'M': case 'm': if (map == 1) { Map(); system("color 07"); } else { system("cls"); cout << "\n\n\t You dont have a map.\n\n\t-"; system("pause"); } break; //Open Backpack case 'B': case 'b': Backpack(); break; //Quit game case 'Q': case 'q': system("cls"); cout << "\n\n\n\n\t Are you sure you want to quit? <Y/N> "; cin >> input; if (input == 'Y' || input == 'y') leavegame = 1; else break; //Invalid default: Invalid(); break; } } //Combat Training setup void CombatTraining() { system("cls"); cout << "\n\tChoose your Atk: "; cin >> Patk; cout << "\n\tChoose your Defense: "; cin >> Pdef; cout << "\n\tChoose your HP: "; cin >> Php; //if you have HP while (Php > 0) { system("cls"); //Fight Enemy if (Ehp > 0) { cout << "\n\n\tYour HP :" << Php; cout << "\n\tEnemy HP :" << Ehp << endl; cout << "\n Move|Description"; cout << "\n ====|==========="; cout << "\n\t 1 | Atk x 1"; cout << "\n\t 2 | Atk x 2"; cout << "\n\t 3 | Atk x 3"; cout << "\n\t 4 | Block"; cout << "\n\n\tPick your move: "; cin >> Pchoice; Echoice = (rand() % 3 + 1); cout << "\n\n\tPlayer move choice = " << Pchoice; cout << "\n\n\tEnemy move choice = " << Echoice; Attack(Patk, Pdef, Php, Pchoice, Eatk, Edef, Ehp, Echoice); cout << "\n\n\t- "; system("pause"); } //New enemy else { cout << "\n\tChoose Enemy Atk: "; cin >> Eatk; cout << "\n\tChoose Enemy Defense: "; cin >> Edef; cout << "\n\tChoose Enemy HP: "; cin >> Ehp; } } } //attack Formula void Attack(int Patk, int Pdef, int &Php, int Pchoice, int Eatk, int Edef, int &Ehp, int Echoice) { int PTatk, PTdef, ETatk, ETdef; int hit, Phit = 1, Ehit = 1; hit = (rand() % 19); cout << "\n hit = " << hit; if (hit = 0) { ETdef = Edef / 2; cout << "\n\tCritical hit.\n"; } else if (hit > 15 || hit < 20) { ETdef = Edef * 1.5; cout << "\n\t Glanceing blow.\n"; } else { ETdef = Edef; cout << "\n\n"; } PTdef = Pdef; //attack formula switch (Pchoice) { case 1: //player hit enemy if (Echoice == 2 || Echoice == 3) { PTatk = Patk * 1; if (PTatk < ETdef) Phit = 0; Ehp = Ehp - (PTatk - ETdef) * Phit; } //enemy hit player else if (Echoice == 4) { ETatk = Eatk * 1; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } break; case 2: //player and enemy hit each other if (Echoice == 2) { PTatk = Patk * 2; if (PTatk < ETdef) Phit = 0; Ehp = Ehp - (PTatk - ETdef) * Phit; ETatk = Eatk * 2; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } //player hits enemy else if (Echoice == 3 || Echoice == 4) { PTatk = Patk * 2; if (PTatk < ETdef) Phit = 0; Ehp = Ehp - (PTatk - ETdef) * Phit; } //enemy hits player else if (Echoice == 1) { ETatk = Eatk * 2; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } break; case 3: //player and enemy hit each other if (Echoice == 3) { PTatk = Patk * 3; if (PTatk < ETdef) Phit = 0; Ehp = Ehp - (PTatk - ETdef) * Phit; ETatk = Eatk * 3; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } //player hit enemy else if (Echoice == 4) { PTatk = Patk * 3; if (PTatk < ETdef) Phit = 0; Ehp = Ehp - (PTatk - ETdef) * Phit; } //enemy hit player else if (Echoice == 1) { ETatk = Eatk * 1; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } break; case 4: //Enemy Hit player if (Echoice == 3) { ETatk = Eatk * 3; if (ETatk < PTdef) Ehit = 0; Php = Php - (ETatk - ETdef) * Ehit; } break; } } //Map void Map() { char key; system("cls"); system("Color 21"); cout << "|=====================================================|"; cout << "|#####################################################|"; cout << "|#######~~~########## #####################|"; cout << "|################ ##############|"; cout << "|##~~~######### # #########|"; cout << "|###~~~~####### ### ########|"; cout << "|############# ####### ########|"; cout << "|############ ##### #######|"; cout << "|##~~~####### #########|"; cout << "|####~~~#######TT ##########|"; cout << "|#############TTT\\ ###########|"; cout << "|##~~~####### \\ #####~~######|"; cout << "|######### \\ ##############|"; cout << "|###### \\-------I------\\ #####~~~######|"; cout << "|~~### \\-H###############|"; cout << "|#### #############|"; cout << "|#### ############|"; cout << "|### _A #########|"; cout << "|## /\\ / \\ /\\ ######|"; cout << "|### /^^/^^^^\\/ \\ #####|"; cout << "|#### / / /^^^^\\ #####|"; cout << "|############ ######|"; cout << "|##~~~############## #######|"; cout << "|##N########################### ########|"; cout << "|=====|###~~~####################### ###########|"; cout << "| N |##~~~##########################################|"; cout << "| W+E |=========|=====================|===============|"; cout << "| S | [K] Key | Dragon Isle | [Q] Close map |"; cout << "|=====|=========|=====================|===============|"; cin >> key; if (key == 'K' || key == 'k') Key(); } //Key for map void Key() { char map; system("cls"); system("color 07"); cout << "|=====================================================|"; cout << "| __ |"; cout << "| | / | \\ / |"; cout << "| |/ |_ \\ / |"; cout << "| |\\ | | |"; cout << "| | \\ |__ | |"; cout << "| |"; cout << "| |"; cout << "| * T = Town |"; cout << "| * H = Harbor |"; cout << "| * I = Gus\'s Inn |"; cout << "| * A = Dragons Peak |"; cout << "| * -,\\,/ = Road |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "| |"; cout << "|================|================|===================|"; cout << "| [M] = Map | Dragons Isle | [Q] = Close map |"; cout << "|================|================|===================|"; cin >> map; if (map == 'M' || map == 'm') Map(); } //Displays Items in backpack void Backpack() { system("cls"); if (backpack == 1) { cout << " Small backpack || 10 slots\n"; cout << "======================================================="; } else if (backpack == 2) { cout << " Medium Backpack || 20 slots\n"; cout << "======================================================="; } else if (backpack == 3) { cout << " Large Backpack || 40 slots\n"; cout << "======================================================="; } else { cout << "you dont have a backpack"; } system("pause"); } //Game over display void GameOver() { system("cls"); cout << "\n\t __ __"; cout << "\n\t / \\ /\\ |\\ /| | "; cout << "\n\t / __ /__\\ | \\/ | |_"; cout << "\n\t \\ / / \\ | | |"; cout << "\n\t \\__/ / \\ | | |__"; cout << "\n\t __ __ _"; cout << "\n\t / \\ \\ / | | \\"; cout << "\n\t / \\ \\ / |_ |_/"; cout << "\n\t \\ / \\ / | |\\"; cout << "\n\t \\__/ \\/ |__ | \\"; cout << "\n\n|===============|========|=========|=======|==========|"; HUD(); cout << "\n\n\t\tTotal Turns: " << turns; cout << "\n\n\t"; system("pause"); } //hit enter to continue void HitEnter() { int enter; fflush(stdout); do enter = getchar(); while ((enter != '\n') && (enter != EOF)); } //Invalid: Please make valid selection void Invalid() { system("cls"); cout << "\n\n\n\n\n\n\tPlease make a valid selection\n\n\t"; system("pause"); } //credits void Credits() { system("cls"); cout << "\n\n\n\n\t Made in C++."; cout << "\n\t Programed by: Jack Melvin.\n\n\t-"; system("pause"); } //Innkeeper void IKO() { system("cls"); HUD(); cout << "\n *you step into a seemingly empty Inn.*"; cout << "\n\n"; cout << "\t|=================|\n"; cout << "\t|Gus the Innkeeper|\n"; cout << "\t|=================|\n\n"; cout << "\tso Traveler,"; cout << "\n\tWhat be your name?"; cout << "\n\n\t Name: "; cin >> name; system("cls"); //------------------------------------------------------------ HUD(); cout << "\n\n\n"; cout << "\t|=================|\n"; cout << "\t|Gus the Innkeeper|\n"; cout << "\t|=================|\n\n"; cout << "\tYou look weary from travel,\n"; cout << "\tWhy dont you take a rest."; cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n -"; Php = 20; //Not working. not sure if i shoud be referencing Php. cout << Php; system("pause"); system("cls"); //------------------------------------------------------------ HUD(); cout << "\n\n\n"; cout << Php; cout << "\t|=================|\n"; cout << "\t|Gus the Innkeeper|\n"; cout << "\t|=================|\n\n"; cout << "\tSo you say your on an adveture eh?\n"; cout << "\tSounds like your gonna need some\n"; cout << "\tprotection. Here, take this! \n\n"; cout << "\t(You obtained a Rusty Sword +1 ATK)\n"; Patk++; cout << "\t(You obtained a leather armour +1 Armour)\n\n"; Pdef++; cout << "\tSome bum traded it for a pint of beer,\n"; cout << "\tand I have no use for it, so keep it.\n\n\n\n\n\n\n\n\n -"; system("pause"); system("cls"); //------------------------------------------------------------ } //DOOM! void Doom() { system("cls"); cout << "\n\n\n\t\t Welcome to your"; //DOOM cout << "\n\t ____ __ __"; cout << "\n\t | \\ ___ ___ | \\ / |"; cout << "\n\t | |\\ \\ / _ \\ / _ \\ | \\ / |"; cout << "\n\t | | \\ \\ / / \\ \\ / / \\ \\ | |\\ \\/ /| |"; cout << "\n\t | |_/ / \\ \\_/ / \\ \\_/ / | | \\__/ | |"; cout << "\n\t |_____/ \\___/ \\___/ |_| |_|"; cout << "\n\n\t You realise you are about to die,"; cout << "\n\n\t as you see death pull out your soul.\n\n\t "; system("pause"); }
M-Tech212/TRPG-game
RPG game base v0.36.cpp
C++
gpl-3.0
21,180
// Copyright 2015 Google 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. #include "benchmark/reporter.h" #include "complexity.h" #include <algorithm> #include <cstdint> #include <iostream> #include <string> #include <tuple> #include <vector> #include "string_util.h" #include "walltime.h" namespace benchmark { namespace { std::string FormatKV(std::string const& key, std::string const& value) { return StringPrintF("\"%s\": \"%s\"", key.c_str(), value.c_str()); } std::string FormatKV(std::string const& key, const char* value) { return StringPrintF("\"%s\": \"%s\"", key.c_str(), value); } std::string FormatKV(std::string const& key, bool value) { return StringPrintF("\"%s\": %s", key.c_str(), value ? "true" : "false"); } std::string FormatKV(std::string const& key, int64_t value) { std::stringstream ss; ss << '"' << key << "\": " << value; return ss.str(); } int64_t RoundDouble(double v) { return static_cast<int64_t>(v + 0.5); } } // end namespace bool JSONReporter::ReportContext(const Context& context) { std::ostream& out = GetOutputStream(); out << "{\n"; std::string inner_indent(2, ' '); // Open context block and print context information. out << inner_indent << "\"context\": {\n"; std::string indent(4, ' '); std::string walltime_value = LocalDateTimeString(); out << indent << FormatKV("date", walltime_value) << ",\n"; out << indent << FormatKV("num_cpus", static_cast<int64_t>(context.num_cpus)) << ",\n"; out << indent << FormatKV("mhz_per_cpu", RoundDouble(context.mhz_per_cpu)) << ",\n"; out << indent << FormatKV("cpu_scaling_enabled", context.cpu_scaling_enabled) << ",\n"; #if defined(NDEBUG) const char build_type[] = "release"; #else const char build_type[] = "debug"; #endif out << indent << FormatKV("library_build_type", build_type) << "\n"; // Close context block and open the list of benchmarks. out << inner_indent << "},\n"; out << inner_indent << "\"benchmarks\": [\n"; return true; } void JSONReporter::ReportRuns(std::vector<Run> const& reports) { if (reports.empty()) { return; } std::string indent(4, ' '); std::ostream& out = GetOutputStream(); if (!first_report_) { out << ",\n"; } first_report_ = false; for (auto it = reports.begin(); it != reports.end(); ++it) { out << indent << "{\n"; PrintRunData(*it); out << indent << '}'; auto it_cp = it; if (++it_cp != reports.end()) { out << ",\n"; } } } void JSONReporter::Finalize() { // Close the list of benchmarks and the top level object. GetOutputStream() << "\n ]\n}\n"; } void JSONReporter::PrintRunData(Run const& run) { std::string indent(6, ' '); std::ostream& out = GetOutputStream(); out << indent << FormatKV("name", run.benchmark_name) << ",\n"; if (run.error_occurred) { out << indent << FormatKV("error_occurred", run.error_occurred) << ",\n"; out << indent << FormatKV("error_message", run.error_message) << ",\n"; } if (!run.report_big_o && !run.report_rms) { out << indent << FormatKV("iterations", run.iterations) << ",\n"; out << indent << FormatKV("real_time", RoundDouble(run.GetAdjustedRealTime())) << ",\n"; out << indent << FormatKV("cpu_time", RoundDouble(run.GetAdjustedCPUTime())); out << ",\n" << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); } else if (run.report_big_o) { out << indent << FormatKV("cpu_coefficient", RoundDouble(run.GetAdjustedCPUTime())) << ",\n"; out << indent << FormatKV("real_coefficient", RoundDouble(run.GetAdjustedRealTime())) << ",\n"; out << indent << FormatKV("big_o", GetBigOString(run.complexity)) << ",\n"; out << indent << FormatKV("time_unit", GetTimeUnitString(run.time_unit)); } else if(run.report_rms) { out << indent << FormatKV("rms", RoundDouble(run.GetAdjustedCPUTime()*100)) << '%'; } if (run.bytes_per_second > 0.0) { out << ",\n" << indent << FormatKV("bytes_per_second", RoundDouble(run.bytes_per_second)); } if (run.items_per_second > 0.0) { out << ",\n" << indent << FormatKV("items_per_second", RoundDouble(run.items_per_second)); } if (!run.report_label.empty()) { out << ",\n" << indent << FormatKV("label", run.report_label); } out << '\n'; } } // end namespace benchmark
HexHive/datashield
libcxx/libcxx/utils/google-benchmark/src/json_reporter.cc
C++
gpl-3.0
5,178
from django.apps import AppConfig class CirculoConfig(AppConfig): name = 'circulo'
jstitch/gift_circle
GiftCircle/circulo/apps.py
Python
gpl-3.0
89
/* * ARTarget.cpp * ARToolKit5 * * This file generate a special actor who defines a NFT target * File descriptions: ARTarget contains very important features like size of the target, * the offset calcultation for the NFT track point, a plane to display the target just for editor mode * * ARToolKit is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ARToolKit 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ARToolKit. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, and to * copy and distribute the resulting executable under terms of your choice, * provided that you also meet, for each linked independent module, the terms and * conditions of the license of that module. An independent module is a module * which is neither derived from nor based on this library. If you modify this * library, you may extend this exception to your version of the library, but you * are not obligated to do so. If you do not wish to do so, delete this exception * statement from your version. * * Copyright 2015 Daqri, LLC. * Copyright 2010-2015 ARToolworks, Inc. * * Author(s): Philip Lamb, Julian Looser. * * Plugin Author(s): Jorge CR (AKA karmakun) * * Special Thanks: tgraupmann (your android knowledge helps a lot) */ #include "ARPrivatePCH.h" #include "ARTarget.h" #include "FileManagerGeneric.h" // Fix WinBase.h override #undef UpdateResource #define UpdateResource UpdateResource DEFINE_LOG_CATEGORY_STATIC(LogARToolKits, Log, All); AARTarget::AARTarget() { //create components targetPivot = CreateDefaultSubobject<USceneComponent>("Target Pivot"); targetPivot->SetMobility(EComponentMobility::Static); RootComponent = targetPivot; #if WITH_EDITOR //Editor only: create static mesh component and display plane plane = CreateDefaultSubobject<UStaticMeshComponent>("Target Plane"); plane->SetupAttachment(targetPivot); UMaterial* targetMat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/AR/targetMat"))); if (targetMat != NULL) { plane->SetMaterial(0, targetMat); } // set dummy texture by default UStaticMesh* myMeshPlane = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/AR/Plane"))); if (myMeshPlane != NULL) { plane->SetStaticMesh(myMeshPlane); plane->SetRelativeScale3D(FVector(1, sizeMM.X, sizeMM.Y)); plane->SetRelativeRotation(FQuat(FRotator(-90, 0, 0))); plane->SetMobility(EComponentMobility::Static); } defaultTexture = Cast<UTexture2D>(StaticLoadObject(UTexture2D::StaticClass(), NULL, TEXT("/AR/icon128"))); #endif //create shadow plane component shadowPlane = CreateDefaultSubobject<UStaticMeshComponent>("shadow plane"); shadowPlane->SetupAttachment(RootComponent); UStaticMesh* myMeshPlane2 = Cast<UStaticMesh>(StaticLoadObject(UStaticMesh::StaticClass(), NULL, TEXT("/AR/Plane"))); if (myMeshPlane2 != NULL) { shadowPlane->SetStaticMesh(myMeshPlane2); shadowPlane->SetRelativeScale3D(FVector(1, shadowPlaneScale, shadowPlaneScale)); shadowPlane->SetRelativeRotation(FQuat(FRotator(-90, 0, 0))); shadowPlane->SetRelativeLocation(FVector(0, 0, 1)); UMaterial* shadowMat = Cast<UMaterial>(StaticLoadObject(UMaterial::StaticClass(), NULL, TEXT("/AR/shadowPlane_mat"))); if (shadowMat != NULL) { shadowPlane->SetMaterial(0, shadowMat); } } } void AARTarget::OnConstruction(const FTransform& Transform) { Super::OnConstruction(Transform); //set scale based on custom value SetActorScale3D(FVector(scale, scale, scale)); #if WITH_EDITOR if (targetName != "" && prevAcceptTargetName != targetName) { //load target from content FString thisTarget = FPaths::GameContentDir() + "AR/" + targetName; if (FPaths::FileExists(thisTarget + ".iset")) { AR2ImageSetT* imageSet = ar2ReadImageSet(TCHAR_TO_ANSI(*thisTarget)); if (imageSet != NULL) { //int32 halfIndex = imageSet->num / 2; int32 halfIndex = 0; int32 w = imageSet->scale[halfIndex]->xsize; int32 h = imageSet->scale[halfIndex]->ysize; int32 dpi = imageSet->scale[0]->dpi; //UE_LOG(LogARToolKits, Log, TEXT("target size found: %i , %i , %i"), imageSet->scale[i]->xsize, imageSet->scale[i]->ysize, imageSet->scale[i]->dpi); unsigned char* RawData = imageSet->scale[halfIndex]->imgBW; targetTexture = UTexture2D::CreateTransient(w, h, PF_B8G8R8A8); TArray<FColor> rawData; rawData.Init(FColor(0, 0, 0, 255), w* h); for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int i = x + (y * w); rawData[i].B = RawData[i]; rawData[i].G = RawData[i]; rawData[i].R = RawData[i]; } } FTexture2DMipMap& Mip = targetTexture->PlatformData->Mips[0]; void* Data = Mip.BulkData.Lock(LOCK_READ_WRITE); FMemory::Memcpy(Data,rawData.GetData(), w * h * 4); Mip.BulkData.Unlock(); targetTexture->UpdateResource(); UMaterialInstanceDynamic* materialInstance = plane->CreateDynamicMaterialInstance(0); if (materialInstance != NULL) { materialInstance->SetTextureParameterValue("tex", targetTexture); sizeMM.X = w; sizeMM.Y = h; UE_LOG(LogARToolKits, Log, TEXT("target found name: %s, pixel size: (w: %i , h: %i), UE real size: (w: %f , h: %f)"), *targetName, w,h,pixels2millimeter(w), pixels2millimeter(h)); prevAcceptTargetName = targetName; } } } else { UMaterialInstanceDynamic* materialInstance = plane->CreateDynamicMaterialInstance(0); if (materialInstance != NULL) { materialInstance->SetTextureParameterValue("tex", defaultTexture); sizeMM.X = defaultTexture->GetSizeX() * 40; sizeMM.Y = defaultTexture->GetSizeY() * 40; UE_LOG(LogARToolKits, Warning, TEXT("this name is not found in AR content folder, check if really exists!")); prevAcceptTargetName = ""; } } } //set plane size based on image target plane->SetRelativeScale3D(FVector(1, pixels2millimeter(sizeMM.X), pixels2millimeter(sizeMM.Y))); #endif //toogle shadow plane shadowPlane->SetVisibility(AllowShadowPlane); //set shadow plane sacle shadowPlane->SetRelativeScale3D(FVector(1, shadowPlaneScale, shadowPlaneScale)); } void AARTarget::BeginPlay() { Super::BeginPlay(); if (!AllowShadowPlane) { shadowPlane->DestroyComponent(); } else { //if plane exist set camera texture UMaterialInstanceDynamic* shadowDynamicMaterial = shadowPlane->CreateDynamicMaterialInstance(0); if (shadowDynamicMaterial != NULL) { shadowDynamicMaterial->SetTextureParameterValue("tex", IARModule::Get().GetARToolKit()->getTexture()); } } } void AARTarget::setTargetActorsHiddenInGame(bool bHidden) { TArray<USceneComponent*> childs; targetPivot->GetChildrenComponents(true, childs); for (auto& child : childs) { if (child != NULL && child != plane) { child->SetHiddenInGame(bHidden); } } for (auto& movable : movableObjectList) { if (movable != NULL) movable->SetActorHiddenInGame(bHidden); } plane->SetHiddenInGame(true, false); } FRotator AARTarget::getTargetRotation() { return GetActorRotation(); }
zkarmakun/ARToolKit-5.3-for-Unreal-Engine
AR/Source/AR/Private/ARTarget.cpp
C++
gpl-3.0
7,722
# Generated by Django 2.2 on 2019-06-20 09:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('scoping', '0294_titlevecmodel'), ] operations = [ migrations.AddField( model_name='doc', name='tslug', field=models.TextField(null=True), ), ]
mcallaghan/tmv
BasicBrowser/scoping/migrations/0295_doc_tslug.py
Python
gpl-3.0
369
/** * Copyright 2014 IBM Corp. * * 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. **/ // If you use this as a template, update the copyright with your own name. // Sample Node-RED node file module.exports = function(RED) { "use strict"; // require any external libraries we may need.... //var foo = require("foo-library"); // The main node definition - most things happen in here function mobileactuatorNode(n) { // Create a RED node RED.nodes.createNode(this,n); // Store local copies of the node configuration (as defined in the .html) this.topic = n.topic; this.mobile_type = n.mobile_type; this.mobile_port = n.mobile_port; // copy "this" object in case we need it in context of callbacks of other functions. var node = this; // Do whatever you need to do in here - declare callbacks etc // Note: this sample doesn't do anything much - it will only send // this message once at startup... // Look at other real nodes for some better ideas of what to do.... var msg = {}; msg.topic = this.topic; msg.payload = "Hello world !" // send out the message to the rest of the workspace. // ... this message will get sent at startup so you may not see it in a debug node. //this.send(msg); // respond to inputs.... this.on('input', function (msg) { //node.warn("I saw a payload: "+msg.payload); // in this example just send it straight on... should process it here really if (msg.payload[0] == this.mobile_type && msg.payload[1] == 0){ msg.payload = msg.payload.substr(2) node.send(msg); } }); this.on("close", function() { // Called when the node is shutdown - eg on redeploy. // Allows ports to be closed, connections dropped etc. // eg: node.client.disconnect(); }); } RED.nodes.registerType("mobile actuator",mobileactuatorNode); }
lemio/w-esp
w-esp-node-red/nodes/94-mobile_actuator.js
JavaScript
gpl-3.0
2,532
// RUN: %clang_cc1 -fsyntax-only -fopenmp -x c++ -std=c++11 -fexceptions -fcxx-exceptions -verify %s class S { int a; S() : a(0) {} public: S(int v) : a(v) {} S(const S &s) : a(s.a) {} }; static int sii; #pragma omp threadprivate(sii) static int globalii; int test_iteration_spaces() { const int N = 100; float a[N], b[N], c[N]; int ii, jj, kk; float fii; double dii; #pragma omp parallel for for (int i = 0; i < 10; i += 1) { c[i] = a[i] + b[i]; } #pragma omp parallel for for (char i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } #pragma omp parallel for for (char i = 0; i < 10; i += '\1') { c[i] = a[i] + b[i]; } #pragma omp parallel for for (long long i = 0; i < 10; i++) { c[i] = a[i] + b[i]; } // expected-error@+2 {{expression must have integral or unscoped enumeration type, not 'double'}} #pragma omp parallel for for (long long i = 0; i < 10; i += 1.5) { c[i] = a[i] + b[i]; } #pragma omp parallel for for (long long i = 0; i < 'z'; i += 1u) { c[i] = a[i] + b[i]; } // expected-error@+2 {{variable must be of integer or random access iterator type}} #pragma omp parallel for for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or random access iterator type}} #pragma omp parallel for for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (int &ref = ii; ref < 10; ref++) { } // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (int i; i < 10; i++) c[i] = a[i]; // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (int i = 0, j = 0; i < 10; ++i) c[i] = a[i]; // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (; ii < 10; ++ii) c[ii] = a[ii]; // expected-warning@+3 {{expression result unused}} // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (ii + 1; ii < 10; ++ii) c[ii] = a[ii]; // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (c[ii] = 0; ii < 10; ++ii) c[ii] = a[ii]; // Ok to skip parenthesises. #pragma omp parallel for for (((ii)) = 0; ii < 10; ++ii) c[ii] = a[ii]; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} #pragma omp parallel for for (int i = 0; i; i++) c[i] = a[i]; // expected-error@+3 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'i'}} #pragma omp parallel for for (int i = 0; jj < kk; ii++) c[i] = a[i]; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} #pragma omp parallel for for (int i = 0; !!i; i++) c[i] = a[i]; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} #pragma omp parallel for for (int i = 0; i != 1; i++) c[i] = a[i]; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'i'}} #pragma omp parallel for for (int i = 0;; i++) c[i] = a[i]; // Ok. #pragma omp parallel for for (int i = 11; i > 10; i--) c[i] = a[i]; // Ok. #pragma omp parallel for for (int i = 0; i < 10; ++i) c[i] = a[i]; // Ok. #pragma omp parallel for for (ii = 0; ii < 10; ++ii) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; ++jj) c[ii] = a[jj]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; ++++ii) c[ii] = a[ii]; // Ok but undefined behavior (in general, cannot check that incr // is really loop-invariant). #pragma omp parallel for for (ii = 0; ii < 10; ii = ii + ii) c[ii] = a[ii]; // expected-error@+2 {{expression must have integral or unscoped enumeration type, not 'float'}} #pragma omp parallel for for (ii = 0; ii < 10; ii = ii + 1.0f) c[ii] = a[ii]; // Ok - step was converted to integer type. #pragma omp parallel for for (ii = 0; ii < 10; ii = ii + (int)1.1f) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; jj = ii + 2) c[ii] = a[ii]; // expected-warning@+3 {{relational comparison result unused}} // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii<10; jj> kk + 2) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10;) c[ii] = a[ii]; // expected-warning@+3 {{expression result unused}} // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; !ii) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; ii ? ++ii : ++jj) c[ii] = a[ii]; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'ii'}} #pragma omp parallel for for (ii = 0; ii < 10; ii = ii < 10) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; ii < 10; ii = ii + 0) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; ii < 10; ii = ii + (int)(0.8 - 0.45)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; (ii) < 10; ii -= 25) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; (ii < 10); ii -= 0) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; ii > 10; (ii += 0)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; ii < 10; (ii) = (1 - 1) + (ii)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for ((ii = 0); ii > 10; (ii -= 0)) c[ii] = a[ii]; // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'ii' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (ii = 0; (ii < 10); (ii -= 0)) c[ii] = a[ii]; // expected-note@+2 {{defined as firstprivate}} // expected-error@+2 {{loop iteration variable in the associated loop of 'omp parallel for' directive may not be firstprivate, predetermined as private}} #pragma omp parallel for firstprivate(ii) for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; // expected-note@+2 {{defined as linear}} // expected-error@+2 {{loop iteration variable in the associated loop of 'omp parallel for' directive may not be linear, predetermined as private}} #pragma omp parallel for linear(ii) for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; #pragma omp parallel for private(ii) for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; #pragma omp parallel for lastprivate(ii) for (ii = 0; ii < 10; ii++) c[ii] = a[ii]; { #pragma omp parallel for for (sii = 0; sii < 10; sii += 1) c[sii] = a[sii]; } { #pragma omp parallel for for (globalii = 0; globalii < 10; globalii += 1) c[globalii] = a[globalii]; } { #pragma omp parallel for collapse(2) for (ii = 0; ii < 10; ii += 1) for (globalii = 0; globalii < 10; globalii += 1) c[globalii] += a[globalii] + ii; } // expected-error@+2 {{statement after '#pragma omp parallel for' must be a for loop}} #pragma omp parallel for for (auto &item : a) { item = item + 1; } // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'i' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (unsigned i = 9; i < 10; i--) { c[i] = a[i] + b[i]; } int(*lb)[4] = nullptr; #pragma omp parallel for for (int(*p)[4] = lb; p < lb + 8; ++p) { } // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (int a{0}; a < 10; ++a) { } return 0; } // Iterators allowed in openmp for-loops. namespace std { struct random_access_iterator_tag {}; template <class Iter> struct iterator_traits { typedef typename Iter::difference_type difference_type; typedef typename Iter::iterator_category iterator_category; }; template <class Iter> typename iterator_traits<Iter>::difference_type distance(Iter first, Iter last) { return first - last; } } class Iter0 { public: Iter0() {} Iter0(const Iter0 &) {} Iter0 operator++() { return *this; } Iter0 operator--() { return *this; } bool operator<(Iter0 a) { return true; } }; // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'Iter0' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'Iter0' for 1st argument}} int operator-(Iter0 a, Iter0 b) { return 0; } class Iter1 { public: Iter1(float f = 0.0f, double d = 0.0) {} Iter1(const Iter1 &) {} Iter1 operator++() { return *this; } Iter1 operator--() { return *this; } bool operator<(Iter1 a) { return true; } bool operator>=(Iter1 a) { return false; } }; class GoodIter { public: GoodIter() {} GoodIter(const GoodIter &) {} GoodIter(int fst, int snd) {} GoodIter &operator=(const GoodIter &that) { return *this; } GoodIter &operator=(const Iter0 &that) { return *this; } GoodIter &operator+=(int x) { return *this; } GoodIter &operator-=(int x) { return *this; } explicit GoodIter(void *) {} GoodIter operator++() { return *this; } GoodIter operator--() { return *this; } bool operator!() { return true; } bool operator<(GoodIter a) { return true; } bool operator<=(GoodIter a) { return true; } bool operator>=(GoodIter a) { return false; } typedef int difference_type; typedef std::random_access_iterator_tag iterator_category; }; // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'GoodIter' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} int operator-(GoodIter a, GoodIter b) { return 0; } // expected-note@+1 3 {{candidate function not viable: requires single argument 'a', but 2 arguments were provided}} GoodIter operator-(GoodIter a) { return a; } // expected-note@+2 {{candidate function not viable: no known conversion from 'const Iter0' to 'int' for 2nd argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'GoodIter' for 1st argument}} GoodIter operator-(GoodIter a, int v) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'GoodIter' for 1st argument}} GoodIter operator+(GoodIter a, int v) { return GoodIter(); } // expected-note@+2 {{candidate function not viable: no known conversion from 'GoodIter' to 'int' for 1st argument}} // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter1' to 'int' for 1st argument}} GoodIter operator-(int v, GoodIter a) { return GoodIter(); } // expected-note@+1 2 {{candidate function not viable: no known conversion from 'Iter0' to 'int' for 1st argument}} GoodIter operator+(int v, GoodIter a) { return GoodIter(); } int test_with_random_access_iterator() { GoodIter begin, end; Iter0 begin0, end0; #pragma omp parallel for for (GoodIter I = begin; I < end; ++I) ++I; // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (GoodIter &I = begin; I < end; ++I) ++I; #pragma omp parallel for for (GoodIter I = begin; I >= end; --I) ++I; // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (GoodIter I(begin); I < end; ++I) ++I; // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (GoodIter I(nullptr); I < end; ++I) ++I; // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (GoodIter I(0); I < end; ++I) ++I; // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (GoodIter I(1, 2); I < end; ++I) ++I; #pragma omp parallel for for (begin = GoodIter(0); begin < end; ++begin) ++begin; // expected-error@+3 {{invalid operands to binary expression ('GoodIter' and 'const Iter0')}} // expected-error@+2 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} #pragma omp parallel for for (begin = begin0; begin < end; ++begin) ++begin; // expected-error@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (++begin; begin < end; ++begin) ++begin; #pragma omp parallel for for (begin = end; begin < end; ++begin) ++begin; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} #pragma omp parallel for for (GoodIter I = begin; I - I; ++I) ++I; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} #pragma omp parallel for for (GoodIter I = begin; begin < end; ++I) ++I; // expected-error@+2 {{condition of OpenMP for loop must be a relational comparison ('<', '<=', '>', or '>=') of loop variable 'I'}} #pragma omp parallel for for (GoodIter I = begin; !I; ++I) ++I; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (GoodIter I = begin; I >= end; I = I + 1) ++I; #pragma omp parallel for for (GoodIter I = begin; I >= end; I = I - 1) ++I; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} #pragma omp parallel for for (GoodIter I = begin; I >= end; I = -I) ++I; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (GoodIter I = begin; I >= end; I = 2 + I) ++I; // expected-error@+2 {{increment clause of OpenMP for loop must perform simple addition or subtraction on loop variable 'I'}} #pragma omp parallel for for (GoodIter I = begin; I >= end; I = 2 - I) ++I; // expected-error@+2 {{invalid operands to binary expression ('Iter0' and 'int')}} #pragma omp parallel for for (Iter0 I = begin0; I < end0; ++I) ++I; // Initializer is constructor without params. // expected-error@+3 {{invalid operands to binary expression ('Iter0' and 'int')}} // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (Iter0 I; I < end0; ++I) ++I; Iter1 begin1, end1; // expected-error@+3 {{invalid operands to binary expression ('Iter1' and 'Iter1')}} // expected-error@+2 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} #pragma omp parallel for for (Iter1 I = begin1; I < end1; ++I) ++I; // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (Iter1 I = begin1; I >= end1; ++I) ++I; // expected-error@+5 {{invalid operands to binary expression ('Iter1' and 'float')}} // expected-error@+4 {{could not calculate number of iterations calling 'operator-' with upper and lower loop bounds}} // Initializer is constructor with all default params. // expected-warning@+2 {{initialization clause of OpenMP for loop is not in canonical form ('var = init' or 'T var = init')}} #pragma omp parallel for for (Iter1 I; I < end1; ++I) { } return 0; } template <typename IT, int ST> class TC { public: int dotest_lt(IT begin, IT end) { // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (IT I = begin; I < end; I = I + ST) { ++I; } // expected-note@+3 {{loop step is expected to be positive due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to increase on each iteration of OpenMP for loop}} #pragma omp parallel for for (IT I = begin; I <= end; I += ST) { ++I; } #pragma omp parallel for for (IT I = begin; I < end; ++I) { ++I; } } static IT step() { return IT(ST); } }; template <typename IT, int ST = 0> int dotest_gt(IT begin, IT end) { // expected-note@+3 2 {{loop step is expected to be negative due to this condition}} // expected-error@+2 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (IT I = begin; I >= end; I = I + ST) { ++I; } // expected-note@+3 2 {{loop step is expected to be negative due to this condition}} // expected-error@+2 2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (IT I = begin; I >= end; I += ST) { ++I; } // expected-note@+3 {{loop step is expected to be negative due to this condition}} // expected-error@+2 {{increment expression must cause 'I' to decrease on each iteration of OpenMP for loop}} #pragma omp parallel for for (IT I = begin; I >= end; ++I) { ++I; } #pragma omp parallel for for (IT I = begin; I < end; I += TC<int, ST>::step()) { ++I; } } void test_with_template() { GoodIter begin, end; TC<GoodIter, 100> t1; TC<GoodIter, -100> t2; t1.dotest_lt(begin, end); t2.dotest_lt(begin, end); // expected-note {{in instantiation of member function 'TC<GoodIter, -100>::dotest_lt' requested here}} dotest_gt(begin, end); // expected-note {{in instantiation of function template specialization 'dotest_gt<GoodIter, 0>' requested here}} dotest_gt<unsigned, -10>(0, 100); // expected-note {{in instantiation of function template specialization 'dotest_gt<unsigned int, -10>' requested here}} } void test_loop_break() { const int N = 100; float a[N], b[N], c[N]; #pragma omp parallel for for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) break; // OK in nested loop } switch (i) { case 1: b[i]++; break; default: break; } if (c[i] > 10) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} if (c[i] > 11) break; // expected-error {{'break' statement cannot be used in OpenMP for loop}} } #pragma omp parallel for for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { c[i] = a[i] + b[i]; if (c[i] > 10) { if (c[i] < 20) { break; // OK } } } } } void test_loop_eh() { const int N = 100; float a[N], b[N], c[N]; #pragma omp parallel for for (int i = 0; i < 10; i++) { c[i] = a[i] + b[i]; try { for (int j = 0; j < 10; ++j) { if (a[i] > b[j]) throw a[i]; } throw a[i]; } catch (float f) { if (f > 0.1) throw a[i]; return; // expected-error {{cannot return from OpenMP region}} } switch (i) { case 1: b[i]++; break; default: break; } for (int j = 0; j < 10; j++) { if (c[i] > 10) throw c[i]; } } if (c[9] > 10) throw c[9]; // OK #pragma omp parallel for for (int i = 0; i < 10; ++i) { struct S { void g() { throw 0; } }; } } void test_loop_firstprivate_lastprivate() { S s(4); #pragma omp parallel for lastprivate(s) firstprivate(s) for (int i = 0; i < 16; ++i) ; }
syntheticpp/metashell
3rd/templight/llvm/tools/clang/test/OpenMP/parallel_for_loop_messages.cpp
C++
gpl-3.0
22,881
/* * Copyright (C) 2017 Saxon State and University Library Dresden (SLUB) * * 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 3 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/>. */ package de.slub.urn; /** * An Exception which is thrown if a URN or any part of a URN cannot be parsed due to violations of the URN syntax. * <p> * It supports three different syntax errors and stores a reference to the RFC that has been violated. * * @author Ralf Claussnitzer */ public class URNSyntaxError extends Exception { private ErrorTypes error; private RFC violatedRfc; /** * Construct a new syntax error exception. * * @param msg Error message * @param error The identified violation error * @param violatedRfc The violated RFC */ public URNSyntaxError(String msg, ErrorTypes error, RFC violatedRfc) { super(msg); this.error = error; this.violatedRfc = violatedRfc; } /** * @see Exception#Exception(String) */ public URNSyntaxError(String msg) { super(msg); } /** * @see Exception#Exception(String, Throwable) */ public URNSyntaxError(String msg, Throwable t) { super(msg, t); } /** * Create a new syntax error representing a `reserved identifier` error. * * @param rfc The violated RFC * @param nid The namespace identifier * @return URNSyntaxError exception for throwing */ public static URNSyntaxError reservedIdentifier(RFC rfc, String nid) { return new URNSyntaxError( String.format("Namespace identifier can not be '%s'", nid), ErrorTypes.RESERVED, rfc); } /** * Create a new syntax error representing a `syntactically invalid identifier` error. * * @param rfc The violated RFC * @param msg A detailed error message * @return URNSyntaxError exception for throwing */ public static URNSyntaxError syntaxError(RFC rfc, String msg) { return new URNSyntaxError(msg, ErrorTypes.SYNTAX_ERROR, rfc); } /** * Create a new syntax error representing a `length` error. * * @param rfc The violated RFC * @param nid The namespace identifier * @return URNSyntaxError exception for throwing */ public static URNSyntaxError lengthError(RFC rfc, String nid) { return new URNSyntaxError( String.format("Namespace Identifier '%s' is too long. Only 32 characters are allowed.", nid), ErrorTypes.LENGTH_ERROR, rfc); } public ErrorTypes getError() { return error; } public RFC getViolatedRfc() { return violatedRfc; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s [Error %3d]\n\nThis is probably a violation of %s", getMessage(), error.getCode(), violatedRfc.name())); if (!error.getViolatedRfcSection().isEmpty()) { sb.append(", section ").append(error.getViolatedRfcSection()); } sb.append("\nSee ").append(violatedRfc.url()); return sb.toString(); } public enum ErrorTypes { RESERVED(10, "2.1"), SYNTAX_ERROR(15, ""), LENGTH_ERROR(20, "2"); private final int code; private final String violatedRfcSection; ErrorTypes(int code, String violatedRfcSection) { this.code = code; this.violatedRfcSection = violatedRfcSection; } public int getCode() { return code; } public String getViolatedRfcSection() { return violatedRfcSection; } } }
slub/urnlib
src/main/java/de/slub/urn/URNSyntaxError.java
Java
gpl-3.0
4,308
using System.IO; using System.Runtime.Serialization; using WolvenKit.CR2W.Reflection; using FastMember; using static WolvenKit.CR2W.Types.Enums; namespace WolvenKit.CR2W.Types { [DataContract(Namespace = "")] [REDMeta] public class CStorySceneEventScenePropPlacement : CStorySceneEvent { [Ordinal(1)] [RED("propId")] public CName PropId { get; set;} [Ordinal(2)] [RED("placement")] public EngineTransform Placement { get; set;} [Ordinal(3)] [RED("showHide")] public CBool ShowHide { get; set;} [Ordinal(4)] [RED("rotationCyclesPitch")] public CUInt32 RotationCyclesPitch { get; set;} [Ordinal(5)] [RED("rotationCyclesRoll")] public CUInt32 RotationCyclesRoll { get; set;} [Ordinal(6)] [RED("rotationCyclesYaw")] public CUInt32 RotationCyclesYaw { get; set;} public CStorySceneEventScenePropPlacement(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CStorySceneEventScenePropPlacement(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
Traderain/Wolven-kit
WolvenKit.CR2W/Types/W3/RTTIConvert/CStorySceneEventScenePropPlacement.cs
C#
gpl-3.0
1,221
function parseCategory(aCategory, aFunction) { if(document.location.host == '' || document.location.host == 'localhost' ) var url = 'test.html'; else var url = categoryGetURLPrivate(aCategory); $.ajax({ type: "GET", url: url, dataType:'html', success: function(responseText) { var aData = {}; aData.categories = []; aData.alternative = []; aData.related = []; aData.sitesCooled = []; aData.sites = []; aData.alphabar = []; aData.groups = []; aData.editors = []; aData.moz = ''; var tmp = 0; //subcategories and links $(responseText).find('.dir-1').each(function() { aData.categories[tmp] = []; $(this).find('li').each(function() { aData.categories[tmp][aData.categories[tmp].length] = $(this).html().replace(/href="/, 'href="#/Top'); }) aData.categories[tmp].sort(ODPy.sortLocale); tmp++; }); //alternative languages $(responseText).find('.language').find('li').each(function() { aData.alternative[aData.alternative.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.alternative = aData.alternative.sort(ODPy.sortLocale); //related categories $(responseText).find('fieldset.fieldcap .directory').find('li').each(function() { aData.related[aData.related.length] = $(this).html().replace(/href="/, 'href="#/Top'); }); aData.related.sort(ODPy.sortLocale); //sites cooled $(responseText).find('.directory-url').find('li.star').each(function() { aData.sitesCooled[aData.sitesCooled.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); //alert(aData.sitesCooled.toString()); aData.sitesCooled.sort(ODPy.sortLocale); //sites not cooled $(responseText).find('.directory-url').find('li:not(.star)').each(function() { aData.sites[aData.sites.length] = $(this).html().replace(/href="/, ' target="_blank" href="'); }); aData.sites.sort(ODPy.sortLocale); //alphabar $(responseText).find('.alphanumeric a').each(function() { aData.alphabar[aData.alphabar.length] = $(this).html(); }); aData.alphabar.sort(ODPy.sortLocale); //groups $(responseText).find('.fieldcapRn .float-l li:first').each(function() { var item = $(this).html(); if(item.indexOf('search') != -1){} else aData.groups[aData.groups.length] = item; return; }); aData.groups.sort(ODPy.sortLocale); //editors $(responseText).find('.volEditN a').each(function() { if(trim(stripTags($(this).html()))) aData.editors[aData.editors.length] = '<a href="http://editors.dmoz.org/public/profile?editor='+$(this).html()+'">'+$(this).html()+'</a>'; }); //mozzie if(responseText.indexOf('img/moz') != -1) { try { aData.moz = responseText.split('/img/moz/')[1].split('"')[0]; } catch(e){} } //aData.editors.sort(ODPy.sortLocale); aFunction(aCategory, aData); }, error :function() { ODPy.statusSet('Error category "'+categoryTitle(aCategory)+'" no exists'); ODPy.statusHide(); } }); }
titoBouzout/ODPy
lib/ODP/categoryParser.js
JavaScript
gpl-3.0
3,590
# coding: utf-8 class EditorController < ApplicationController before_filter :authenticate_user! def index if params.has_key? 'order' order = params[:order] else order = 'name' end if params.has_key? 'show' show = params[:show] else show = 10 end @texts = case params[:display] when "no-tags" then need_to_tag = [] Text.all.each do |e| need_to_tag << e if e.tag_list.blank? end @texts = need_to_tag.paginate :page => params[:page], :order => order, :per_page => show when "no-author" then need_to_tag = [] Text.all.each do |e| need_to_tag << e if e.author_list.blank? end @texts = need_to_tag.paginate :page => params[:page], :order => order, :per_page => show else Text.paginate :page => params[:page], :order => order, :per_page => show end respond_to do |format| format.html # show.html.erb format.xml { render :xml => @texts } end end def update @texts = params[:texts][:text] @texts.each do |text| @text = Text.find(text[0]) @text.update_attributes(text[1]) @text.save() end redirect_to :back end end
bjesus/asam
app/controllers/editor_controller.rb
Ruby
gpl-3.0
1,252
/* * file_utils.cc * Copyright (C) 2016 elasticlog <elasticlog01@gmail.com> * * Distributed under terms of the GNU GENERAL PUBLIC LICENSE. */ #include "file_utils.h" #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <dirent.h> #include <errno.h> #include <string.h> #include "logging.h" using ::baidu::common::INFO; using ::baidu::common::WARNING; namespace el { bool Mkdir(const std::string& path) { const int dir_mode = 0777; int ret = ::mkdir(path.c_str(), dir_mode); if (ret == 0 || errno == EEXIST) { return true; } LOG(WARNING, "mkdir %s failed err[%d: %s]", path.c_str(), errno, strerror(errno)); return false; } bool MkdirRecur(const std::string& dir_path) { size_t beg = 0; size_t seg = dir_path.find('/', beg); while (seg != std::string::npos) { if (seg + 1 >= dir_path.size()) { break; } if (!Mkdir(dir_path.substr(0, seg + 1))) { return false; } beg = seg + 1; seg = dir_path.find('/', beg); } return Mkdir(dir_path); } }
elasticlog/elasticlog
src/agent/file_utils.cc
C++
gpl-3.0
1,065
import re CJDNS_IP_REGEX = re.compile(r'^fc[0-9a-f]{2}(:[0-9a-f]{4}){7}$', re.IGNORECASE) class Node(object): def __init__(self, ip, version=None, label=None): if not valid_cjdns_ip(ip): raise ValueError('Invalid IP address') if not valid_version(version): raise ValueError('Invalid version') self.ip = ip self.version = int(version) self.label = ip[-4:] or label def __lt__(self, b): return self.ip < b.ip def __repr__(self): return 'Node(ip="%s", version=%s, label="%s")' % ( self.ip, self.version, self.label) class Edge(object): def __init__(self, a, b): self.a, self.b = sorted([a, b]) def __eq__(self, that): return self.a.ip == that.a.ip and self.b.ip == that.b.ip def __repr__(self): return 'Edge(a.ip="{}", b.ip="{}")'.format(self.a.ip, self.b.ip) def valid_cjdns_ip(ip): return CJDNS_IP_REGEX.match(ip) def valid_version(version): try: return int(version) < 30 except ValueError: return False
vdloo/raptiformica-map
raptiformica_map/graph.py
Python
gpl-3.0
1,111
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2016 Considered Hamster * * 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 3 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/> */ package com.consideredhamster.yetanotherpixeldungeon.levels.traps; import com.consideredhamster.yetanotherpixeldungeon.actors.Actor; import com.consideredhamster.yetanotherpixeldungeon.actors.Char; import com.watabou.noosa.audio.Sample; import com.consideredhamster.yetanotherpixeldungeon.visuals.Assets; import com.consideredhamster.yetanotherpixeldungeon.Dungeon; import com.consideredhamster.yetanotherpixeldungeon.actors.mobs.Mob; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.CellEmitter; import com.consideredhamster.yetanotherpixeldungeon.visuals.effects.Speck; import com.consideredhamster.yetanotherpixeldungeon.misc.utils.GLog; public class AlarmTrap extends Trap { // 0xDD3333 public static void trigger( int pos, Char ch ) { for (Mob mob : Dungeon.level.mobs) { if (mob.pos != pos) { mob.beckon( pos ); } } if (Dungeon.visible[pos]) { GLog.w( "The trap emits a piercing sound that echoes throughout the dungeon!" ); CellEmitter.center( pos ).start( Speck.factory( Speck.SCREAM ), 0.3f, 3 ); } Sample.INSTANCE.play( Assets.SND_ALERT ); } }
ConsideredHamster/YetAnotherPixelDungeon
app/src/main/java/com/consideredhamster/yetanotherpixeldungeon/levels/traps/AlarmTrap.java
Java
gpl-3.0
1,902
Ext.define('User', { extend: 'Ext.data.Model', fields: [ {name: 'name', type: 'string', convert: function(value,record) { return record.get('name')+' the barbarian'); } }, {name: 'age', type: 'int'}, {name: 'phone', type: 'string'}, {name: 'alive', type: 'boolean', defaultValue: true} ], });
veltzer/demos-javascript
src/extjs/examples/model/model_change.js
JavaScript
gpl-3.0
316
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_STEREO_HPP__ #define __OPENCV_STEREO_HPP__ #include "opencv2/core.hpp" #include "opencv2/stereo/descriptor.hpp" #include <opencv2/stereo/quasi_dense_stereo.hpp> /** @defgroup stereo Stereo Correspondance Algorithms */ namespace cv { namespace stereo { //! @addtogroup stereo //! @{ /** @brief Filters off small noise blobs (speckles) in the disparity map @param img The input 16-bit signed disparity image @param newVal The disparity value used to paint-off the speckles @param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not affected by the algorithm @param maxDiff Maximum difference between neighbor disparity pixels to put them into the same blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point disparity map, where disparity values are multiplied by 16, this scale factor should be taken into account when specifying this parameter value. @param buf The optional temporary buffer to avoid memory allocation within the function. */ /** @brief The base class for stereo correspondence algorithms. */ class StereoMatcher : public Algorithm { public: enum { DISP_SHIFT = 4, DISP_SCALE = (1 << DISP_SHIFT) }; /** @brief Computes disparity map for the specified stereo pair @param left Left 8-bit single-channel image. @param right Right image of the same size and the same type as the left one. @param disparity Output disparity map. It has the same size as the input images. Some algorithms, like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. */ virtual void compute( InputArray left, InputArray right, OutputArray disparity ) = 0; virtual int getMinDisparity() const = 0; virtual void setMinDisparity(int minDisparity) = 0; virtual int getNumDisparities() const = 0; virtual void setNumDisparities(int numDisparities) = 0; virtual int getBlockSize() const = 0; virtual void setBlockSize(int blockSize) = 0; virtual int getSpeckleWindowSize() const = 0; virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; virtual int getSpeckleRange() const = 0; virtual void setSpeckleRange(int speckleRange) = 0; virtual int getDisp12MaxDiff() const = 0; virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; }; //!speckle removal algorithms. These algorithms have the purpose of removing small regions enum { CV_SPECKLE_REMOVAL_ALGORITHM, CV_SPECKLE_REMOVAL_AVG_ALGORITHM }; //!subpixel interpolationm methods for disparities. enum{ CV_QUADRATIC_INTERPOLATION, CV_SIMETRICV_INTERPOLATION }; /** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and contributed to OpenCV by K. Konolige. */ class StereoBinaryBM : public StereoMatcher { public: enum { PREFILTER_NORMALIZED_RESPONSE = 0, PREFILTER_XSOBEL = 1 }; virtual int getPreFilterType() const = 0; virtual void setPreFilterType(int preFilterType) = 0; virtual int getPreFilterSize() const = 0; virtual void setPreFilterSize(int preFilterSize) = 0; virtual int getPreFilterCap() const = 0; virtual void setPreFilterCap(int preFilterCap) = 0; virtual int getTextureThreshold() const = 0; virtual void setTextureThreshold(int textureThreshold) = 0; virtual int getUniquenessRatio() const = 0; virtual void setUniquenessRatio(int uniquenessRatio) = 0; virtual int getSmallerBlockSize() const = 0; virtual void setSmallerBlockSize(int blockSize) = 0; virtual int getScalleFactor() const = 0 ; virtual void setScalleFactor(int factor) = 0; virtual int getSpekleRemovalTechnique() const = 0 ; virtual void setSpekleRemovalTechnique(int factor) = 0; virtual bool getUsePrefilter() const = 0 ; virtual void setUsePrefilter(bool factor) = 0; virtual int getBinaryKernelType() const = 0; virtual void setBinaryKernelType(int value) = 0; virtual int getAgregationWindowSize() const = 0; virtual void setAgregationWindowSize(int value) = 0; /** @brief Creates StereoBM object @param numDisparities the disparity search range. For each pixel algorithm will find the best disparity from 0 (default minimum disparity) to numDisparities. The search range can then be shifted by changing the minimum disparity. @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd (as the block is centered at the current pixel). Larger block size implies smoother, though less accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher chance for algorithm to find a wrong correspondence. The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for a specific stereo pair. */ CV_EXPORTS static Ptr< cv::stereo::StereoBinaryBM > create(int numDisparities = 0, int blockSize = 9); }; /** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original one as follows: - By default, the algorithm is single-pass, which means that you consider only 5 directions instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the algorithm but beware that it may consume a lot of memory. - The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the blocks to single pixels. - Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. - Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness check, quadratic interpolation and speckle filtering). @note - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found at opencv_source_code/samples/python2/stereo_match.py */ class StereoBinarySGBM : public StereoMatcher { public: enum { MODE_SGBM = 0, MODE_HH = 1 }; virtual int getPreFilterCap() const = 0; virtual void setPreFilterCap(int preFilterCap) = 0; virtual int getUniquenessRatio() const = 0; virtual void setUniquenessRatio(int uniquenessRatio) = 0; virtual int getP1() const = 0; virtual void setP1(int P1) = 0; virtual int getP2() const = 0; virtual void setP2(int P2) = 0; virtual int getMode() const = 0; virtual void setMode(int mode) = 0; virtual int getSpekleRemovalTechnique() const = 0 ; virtual void setSpekleRemovalTechnique(int factor) = 0; virtual int getBinaryKernelType() const = 0; virtual void setBinaryKernelType(int value) = 0; virtual int getSubPixelInterpolationMethod() const = 0; virtual void setSubPixelInterpolationMethod(int value) = 0; /** @brief Creates StereoSGBM object @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than zero. In the current implementation, this parameter must be divisible by 16. @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be somewhere in the 3..11 range. @param P1 The first parameter controlling the disparity smoothness.This parameter is used for the case of slanted surfaces (not fronto parallel). @param P2 The second parameter controlling the disparity smoothness.This parameter is used for "solving" the depth discontinuities problem. The larger the values are, the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good P1 and P2 values are shown (like 8\*number_of_image_channels\*SADWindowSize\*SADWindowSize and 32\*number_of_image_channels\*SADWindowSize\*SADWindowSize , respectively). @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right disparity check. Set it to a non-positive value to disable the check. @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. The result values are passed to the Birchfield-Tomasi pixel cost function. @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function value should "win" the second best value to consider the found match correct. Normally, a value within the 5-15 range is good enough. @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the 50-200 range. @param speckleRange Maximum disparity variation within each connected component. If you do speckle filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. Normally, 1 or 2 is good enough. @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and huge for HD-size pictures. By default, it is set to false . The first constructor initializes StereoSGBM with all the default parameters. So, you only have to set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter to a custom value. */ CV_EXPORTS static Ptr<cv::stereo::StereoBinarySGBM> create(int minDisparity, int numDisparities, int blockSize, int P1 = 100, int P2 = 1000, int disp12MaxDiff = 1, int preFilterCap = 0, int uniquenessRatio = 5, int speckleWindowSize = 400, int speckleRange = 200, int mode = StereoBinarySGBM::MODE_SGBM); }; //! @} }//stereo } // cv #endif
cpvrlab/ImagePlay
IPL/include/opencv/opencv2/stereo.hpp
C++
gpl-3.0
14,099
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>DataTypePointInTimeのJavaクラス。 * * <p>次のスキーマ・フラグメントは、このクラス内に含まれる予期されるコンテンツを指定します。 * <p> * <pre> * &lt;simpleType name="DataTypePointInTime"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="TS"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "DataTypePointInTime") @XmlEnum public enum DataTypePointInTime { TS; public String value() { return name(); } public static DataTypePointInTime fromValue(String v) { return valueOf(v); } }
ricecakesoftware/CommunityMedicalLink
ricecakesoftware.communitymedicallink.hl7/src/org/hl7/v3/DataTypePointInTime.java
Java
gpl-3.0
786
<?php /********************************************************************************* * Zurmo is a customer relationship management program developed by * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc. * * Zurmo is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * Zurmo 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207, * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com. ********************************************************************************/ /** * Override to accomodate a value type of 'ZURMO_MODEL_NAME'. This would represent a model 'name' attribute value * that can be used as a unique identifier to map to existing models. An example is when importing a contact, and * the account name is provided. If the name is found, then the contact will be connected to the existing account * otherwise a new account is created with the name provided. * @see IdValueTypeBatchAttributeValueDataAnalyzer */ class RelatedModelNameOrIdValueTypeBatchAttributeValueDataAnalyzer extends IdValueTypeBatchAttributeValueDataAnalyzer { /** * The max allowed length of the name. * @var integer */ protected $maxNameLength; /** * If the name provide is larger than the $maxNameLength * @var string */ const NEW_NAME_TO0_LONG = 'New name too long'; /** * Override to ensure the $attributeName is a single value and also to resolve the max name length. * @param string $modelClassName * @param string $attributeName */ public function __construct($modelClassName, $attributeName) { parent:: __construct($modelClassName, $attributeName); assert('is_string($attributeName)'); $attributeModelClassName = $this->attributeModelClassName; $model = new $attributeModelClassName(false); assert('$model->isAttribute("name")'); $this->maxNameLength = StringValidatorHelper:: getMaxLengthByModelAndAttributeName($model, 'name'); $this->messageCountData[static::NEW_NAME_TO0_LONG] = 0; } /** * @see IdValueTypeBatchAttributeValueDataAnalyzer::ensureTypeValueIsValid() */ protected function ensureTypeValueIsValid($type) { assert('$type == RelatedModelValueTypeMappingRuleForm::ZURMO_MODEL_ID || $type == RelatedModelValueTypeMappingRuleForm::EXTERNAL_SYSTEM_ID || $type == RelatedModelValueTypeMappingRuleForm::ZURMO_MODEL_NAME'); } /** * @see IdValueTypeBatchAttributeValueDataAnalyzer::analyzeByValue() */ protected function analyzeByValue($value) { $modelClassName = $this->attributeModelClassName; if ($this->type == RelatedModelValueTypeMappingRuleForm::ZURMO_MODEL_ID) { $found = $this->resolveFoundIdByValue($value); } elseif ($this->type == RelatedModelValueTypeMappingRuleForm::ZURMO_MODEL_NAME) { if ($value == null) { $found = false; } else { $modelClassName = $this->attributeModelClassName; if (!method_exists($modelClassName, 'getByName')) { throw new NotSupportedException(); } $modelsFound = $modelClassName::getByName($value); if (count($modelsFound) == 0) { $found = false; if (strlen($value) > $this->maxNameLength) { $this->messageCountData[static::NEW_NAME_TO0_LONG] ++; } } else { $found = true; } } } else { $found = $this->resolveFoundExternalSystemIdByValue($value); } if ($found) { $this->messageCountData[static::FOUND] ++; } else { $this->messageCountData[static::UNFOUND] ++; } if ($this->type == IdValueTypeMappingRuleForm::EXTERNAL_SYSTEM_ID) { if (strlen($value) > $this->externalSystemIdMaxLength) { $this->messageCountData[static::EXTERNAL_SYSTEM_ID_TOO_LONG] ++; } } } /** * @see IdValueTypeBatchAttributeValueDataAnalyzer::makeMessages() */ protected function makeMessages() { if ($this->type == RelatedModelValueTypeMappingRuleForm::ZURMO_MODEL_ID || $this->type == RelatedModelValueTypeMappingRuleForm::EXTERNAL_SYSTEM_ID) { $label = '{found} record(s) will be updated '; $label .= 'and {unfound} record(s) will be skipped during import.'; } else { $label = '{found} record(s) will be updated and '; $label .= '{unfound} record(s) will be created during the import.'; } $this->addMessage(Yii::t('Default', $label, array('{found}' => $this->messageCountData[static::FOUND], '{unfound}' => $this->messageCountData[static::UNFOUND]))); if ($this->messageCountData[static::NEW_NAME_TO0_LONG] > 0) { $label = '{invalid} name value(s) is/are too long.'; $label .= 'These records will be skipped during import.'; $this->addMessage(Yii::t('Default', $label, array('{invalid}' => $this->messageCountData[static::NEW_NAME_TO0_LONG]))); } $this->resolveMakeExternalSystemIdTooLargeMessage(); } } ?>
theclanks/zurmo
app/protected/modules/import/utils/analyzers/RelatedModelNameOrIdValueTypeBatchAttributeValueDataAnalyzer.php
PHP
gpl-3.0
7,298
angular.module('CareFull', ['ui.router','rzModule']);
danielcaldas/carefull
public/app/modules.js
JavaScript
gpl-3.0
54
// Copyright 2012, MapGuideForm user group, Frederikssund Kommune and Helsingør Kommune - att. Anette Poulsen and Erling Kristensen // // This file is part of "RapportFraStedet". // "RapportFraStedet" 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 3 of the License, or any later version. // "RapportFraStedet" 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 "RapportFraStedet". If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace RapportFraStedet.Models { public class RoleModel { [Required] [DataType(DataType.Text)] [Display(Name = "Role Name")] public string RoleName { get; set; } public MultiSelectList Users { get; set; } [Display(Name = "Users")] public string[] SelectedUsers { get; set; } } }
RapportFraStedet/MapGuideForms
RapportFraStedet/Models/RoleModel.cs
C#
gpl-3.0
1,318
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2016 Alberto Gacías <alberto@migasfree.org> # Copyright (c) 2015-2016 Jose Antonio Chavarría <jachavar@gmail.com> # # 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 3 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/>. import gettext _ = gettext.gettext from gi.repository import Gtk class Console(Gtk.Window): def __init__(self): super(Console, self).__init__() sw = Gtk.ScrolledWindow() sw.set_policy( Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC ) self.textview = Gtk.TextView() self.textbuffer = self.textview.get_buffer() self.textview.set_editable(False) self.textview.set_wrap_mode(Gtk.WrapMode.WORD) sw.add(self.textview) self.set_title(_('Migasfree Console')) self.set_icon_name('migasfree') self.resize(640, 420) self.set_decorated(True) self.set_border_width(10) self.connect('delete-event', self.on_click_hide) box = Gtk.Box(spacing=6, orientation='vertical') box.pack_start(sw, expand=True, fill=True, padding=0) self.progress = Gtk.ProgressBar() self.progress.set_pulse_step(0.02) progress_box = Gtk.Box(False, 0, orientation='vertical') progress_box.pack_start(self.progress, False, True, 0) box.pack_start(progress_box, expand=False, fill=True, padding=0) self.add(box) def on_timeout(self, user_data): self.progress.pulse() return True def on_click_hide(self, widget, data=None): self.hide() return True
migasfree/migasfree-launcher
migasfree_indicator/console.py
Python
gpl-3.0
2,190
/* Copyright 2010 Statoil ASA. This file is part of The Open Porous Media project (OPM). OPM 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 3 of the License, or (at your option) any later version. OPM 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 OPM. If not, see <http://www.gnu.org/licenses/>. */ /** @file upscale_relperm.C @brief Upscales relative permeability as a fuction of water saturation assuming capillary equilibrium. Description: Reads in a lithofacies geometry in Eclipse format, reads in J(S_w) and relpermcurve(S_w) for each stone type, and calculates upscaled (three directions) relative permeability curves as a function of Sw. The relative permeability computation is based on - Capillary equilibrium, p_c is spatially invariant. - Optional gravitational effects. If gravity is not specified, gravity will be assumed to be zero. Units handling: - Assumes cornerpoint file reports lengths in cm. - Input surface tension is in dynes/cm - Input density is in g/cm^3 - The denominator \sigma * cos(\phi) in J-function scaling is what we call "surface tension". If angle dependency is to be included, calculate the "surface tension" yourself. - Outputted capillary pressure is in Pascals. Steps in the code: 1: Process command line options. 2: Read Eclipse file 3: Read relperm- and J-function for each stone-type. 4: Tesselate the grid (Sintef code) 5: Find minimum and maximum capillary pressure from the J-functions in each cell. 6: Upscale water saturation as a function of capillary pressure 7: Upscale single phase permeability. 8: Upscale phase permeability for capillary pressures that corresponds to a uniform saturation grid, and compute relative permeability. 9: Print output to screen and optionally to file. */ #include <config.h> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <ctime> #include <cmath> #include <cfloat> // for DBL_MAX/DBL_MIN #include <map> #include <sys/utsname.h> #include <dune/common/version.hh> #if DUNE_VERSION_NEWER(DUNE_COMMON, 2, 3) #include <dune/common/parallel/mpihelper.hh> #else #include <dune/common/mpihelper.hh> #endif #include <opm/core/utility/Units.hpp> #include <opm/upscaling/SinglePhaseUpscaler.hpp> #include <opm/upscaling/ParserAdditions.hpp> #include <opm/upscaling/RelPermUtils.hpp> using namespace Opm; using namespace std; static void usage() { cerr << "Usage: upscale_relperm <options> <eclipsefile> stoneA.txt stoneB.txt ..." << endl << "where the options are:" << endl << " -bc <string> -- which boundary conditions to use." << endl << " Possible values are f (fixed), l (linear)" << endl << " and p (periodic). Default f (fixed)." << endl << " -points <integer> -- Number of saturation points to upscale for." << endl << " Uniformly distributed within saturation endpoints." << endl << " Default 30." << endl << " -relPermCurve <integer> -- For isotropic input, the column number in the stone-files" << endl << " that represents the phase to be upscaled," << endl << " typically 2 (default) for water and 3 for oil." << endl << " -jFunctionCurve <integer> -- the column number in the stone-files that" << endl << " represent the Leverett J-function. Default 4." << endl << " -upscaleBothPhases <bool> -- If this is true, relperm for both phases will be upscaled" << endl << " and both will be outputted to Eclipse format. Default true." << endl << " For isotropic input, relPermCurves is assumed to be 2 and 3," << endl << " for anisotropic input, relPermCurves are assumed to be 3-5" << endl << " and 6-8 respectively for the two phases" << endl << " -gravity <float> -- use 9.81 for standard gravity. Default zero. Unit m/s^2." << endl << " -surfaceTension <float> -- Surface tension to use in J-function/Pc conversion." << endl << " Default 11 dynes/cm (oil-water systems). In absence of" << endl << " a correct value, the surface tension for gas-oil systems " << endl << " could be 22.5 dynes/cm." << endl << " -waterDensity <float> -- density of water, only applicable to non-zero" << endl << " gravity, g/cm³. Default 1" << endl << " -oilDensity <float> -- density of oil, only applicable to non-zero" << endl << " gravity, g/cm³. Default 0.6" << endl << " -output <string> -- filename for where to write upscaled values." << endl << " If not supplied, output will only go to " << endl << " the terminal (standard out)." << endl << " -interpolate <integer> -- If supplied, the output data points will be" << endl << " interpolated using monotone cubic interpolation" << endl << " on a uniform grid with the specified number of" << endl << " points. Suggested value: 1000." << endl << " -maxPermContrast <float> -- maximal permeability contrast in model." << endl << " Default 10^7" << endl << " -minPerm <float> -- Minimum floating point value allowed for" << endl << " phase permeability in computations. If set to zero," << endl << " some models can end up singular. Default 10^-12" << endl << " -maxPerm <float> -- Maximum floating point value allowed for" << endl << " permeability. " << endl << " Default 100000. Unit Millidarcy." << endl << " -fluids <string> -- Either ow for oil/water systems or go for gas/oil systems. Default ow." << endl << " In case of go, the waterDensity option should be set to gas density" << endl << " Also remember to specify the correct surface tension" << endl << " -krowxswirr <float> -- Oil relative permeability in x-direction at Swirr(from SWOF table)." << endl << " In case of oil/gas, this value is needed to ensure consistensy" << endl << " between SWOF and SGOF tables. Only has affect if fluids is set to go" << endl << " and upscaleBothPhases is true." << endl << " If not set, the point is not inserted into the final table." << endl << " -krowyswirr <float> -- Oil relative permeability in y-direction at Swirr(from SWOF table). See krowxswirr." << endl << " -krowzswirr <float> -- Oil relative permeability in z-direction at Swirr(from SWOF table). See krowxswirr." << endl << " -doEclipseCheck <bool> -- Default true. Check that input relperm curves includes relperms at critical" << endl << " saturation points, i.e. that krw(swcrit)=0 and krow(swmax) = 0 and similar for oil/gas." << endl << " -critRelpermThresh <float> -- If minimum relperm values are less than this threshold, they are set to zero" << endl << " and will pass the EclipseCheck. Default 10^-6" << endl << "If only one stone-file is supplied, it is used for all stone-types defined" << endl << "in the geometry. If more than one, it corresponds to the SATNUM-values." << endl; // "minPoro" intentionally left undocumented // "saturationThreshold" also } static void usageandexit() { usage(); exit(1); } //! \brief Parse command line arguments into string map. //! \param[in,out] options The map of options. Should be filled with default values on entry. //! \param[in] varnum Number of arguments //! \param[in] vararg The arguments //! \param[in] verbose Whether or not to print parsed command line arguments //! \returns index of input file if positive, negated index to offending argument on failure. static int parseCommandLine(std::map<std::string,std::string>& options, int varnum, char** vararg, bool verbose) { int argeclindex = 0; for (int argidx = 1; argidx < varnum; argidx += 2) { if (string(vararg[argidx]).substr(0,1) == "-") { string searchfor = string(vararg[argidx]).substr(1); // Chop off leading '-' /* Check if it is a match */ if (options.count(searchfor) == 1) { options[searchfor] = string(vararg[argidx+1]); if (verbose) cout << "Parsed command line option: " << searchfor << " := " << vararg[argidx+1] << endl; argeclindex = argidx + 2; } else return -argidx; } else { // if vararg[argidx] does not start in '-', // assume we have found the position of the Eclipse-file. argeclindex = argidx; break; // out of for-loop, } } return argeclindex; } //! \brief Return eclipse-style output filename. //! \param[in] opfname Base output file name. //! \param[in] comp Component (X, Y, Z). //! \param[in] sat Fluid system type. //! \return Eclipse-style filename for requested component/fluid system combination. static std::string getEclipseOutputFile(const std::string& opfname, char comp, char sat) { string fnbase = opfname.substr(0,opfname.find_first_of('.')); return fnbase + "-" +comp + ".S" + sat + "OF"; } //! \brief Write eclipse-style output file. //! \param[in] RelPermValues RelPerm values to write. //! \param[in] Satvalues Saturation values to write. //! \param[in] Pvalues Pressure values to write. //! \param[in] options Option structure. //! \param[in] component Component to write (0..2). //! \param[in] owsystem Fluid system type. template<class Lazy> static void writeEclipseOutput(Lazy& RelPermValues, const std::vector<double>& Satvalues, const std::vector<double>& Pvalues, std::map<std::string,std::string>& options, int component, bool owsystem) { std::stringstream swof; char sat = (owsystem?'W':'G'); char comp = 'x'+component; std::string krowstring = std::string("krow") + comp + "swirr"; double krowswirr = atof(options[krowstring].c_str()); const int outputprecision = atoi(options["outputprecision"].c_str()); const int fieldwidth = outputprecision + 8; // x-direction swof << "-- This file is based on the results in " << endl << "-- " << options["output"] << endl << "-- for relperm in " << comp << "-direction." << endl << "-- Pressure values (Pc) given in bars." << endl << "-- S" << (char)std::tolower(sat) << " Kr" << (char)std::tolower(sat) << comp << comp << " Kro" << (char)std::tolower(sat) << comp << comp << " Pc(bar)" << endl << "--S" << sat << "OF" << endl; if (krowswirr > 0) { swof << showpoint << setw(fieldwidth) << setprecision(outputprecision) << 0 << showpoint << setw(fieldwidth) << setprecision(outputprecision) << 0 << showpoint << setw(fieldwidth) << setprecision(outputprecision) << krowswirr << showpoint << setw(fieldwidth) << setprecision(outputprecision) << 0 << endl; } for (size_t i=0; i < Satvalues.size(); ++i) { swof << showpoint << setw(fieldwidth) << setprecision(outputprecision) << Satvalues[i] << showpoint << setw(fieldwidth) << setprecision(outputprecision) << RelPermValues[0][component][i] << showpoint << setw(fieldwidth) << setprecision(outputprecision) << RelPermValues[1][component][i] << showpoint << setw(fieldwidth) << setprecision(outputprecision) << Pvalues[i]/100000.0 << endl; } swof << "/" << endl; std::ofstream file; file.open(getEclipseOutputFile(options["output"], std::toupper(comp), sat), std::ios::out | std::ios::trunc); file << swof.str(); file.close(); } int main(int varnum, char** vararg) try { // Variables used for timing/profiling: clock_t start, finish; double timeused = 0.0, timeused_tesselation = 0.0; double timeused_upscale_wallclock = 0.0; /****************************************************************************** * Step 1: * Process command line options */ Dune::MPIHelper& mpi=Dune::MPIHelper::instance(varnum, vararg); const int mpi_rank = mpi.rank(); #ifdef HAVE_MPI const int mpi_nodecount = mpi.size(); #endif if (varnum == 1) { /* If no arguments supplied ("upscale_relperm" is the first "argument") */ usage(); exit(1); } /* Populate options-map with default values */ map<string,string> options = {{"bc", "f"}, // Fixed boundary conditions {"points", "30"}, // Number of saturation points (uniformly distributed within saturation endpoints) {"relPermCurve", "2"}, // Which column in the rock types are upscaled {"upscaleBothPhases", "true"}, // Whether to upscale for both phases in the same run. Default true. {"jFunctionCurve", "4"}, // Which column in the rock type file is the J-function curve {"surfaceTension", "11"}, // Surface tension given in dynes/cm {"output", ""}, // If this is set, output goes to screen and to this file. {"gravity", "0.0"}, // default is no gravitational effects {"waterDensity", "1.0"}, // default density of water, only applicable to gravity {"oilDensity", "0.6"}, // ditto {"interpolate", "0"}, // default is not to interpolate {"maxpoints", "1000"}, // maximal number of saturation points. {"outputprecision", "4"}, // number of significant numbers to print {"maxPermContrast", "1e7"}, // maximum allowed contrast in each single-phase computation {"minPerm", "1e-12"}, // absolute minimum for allowed cell permeability {"maxPerm", "100000"}, // maximal allowed cell permeability {"minPoro", "0.0001"}, // this limit is necessary for pcmin/max computation {"saturationThreshold", "0.00001"}, // accuracy threshold for saturation, we ignore Pc values that // give so small contributions near endpoints. {"linsolver_tolerance", "1e-12"}, // residual tolerance for linear solver {"linsolver_verbosity", "0"}, // verbosity level for linear solver {"linsolver_max_iterations", "0"}, // Maximum number of iterations allow, specify 0 for default {"linsolver_type", "3"}, // Type of linear solver: 0 = ILU0/CG, 1 = AMG/CG, 2 KAMG/CG, 3 FAST_AMG/CG {"linsolver_prolongate_factor", "1.0"}, // Prolongation factor in AMG {"linsolver_smooth_steps", "1"}, // Number of smoothing steps in AMG {"fluids", "ow"}, // Whether upscaling for oil/water (ow) or gas/oil (go) {"krowxswirr", "-1"}, // Relative permeability in x direction of oil in corresponding oil/water system {"krowyswirr", "-1"}, // Relative permeability in y direction of oil in corresponding oil/water system {"krowzswirr", "-1"}, // Relative permeability in z direction of oil in corresponding oil/water system {"doEclipseCheck", "true"}, // Check if minimum relpermvalues in input are zero (specify critical saturations) {"critRelpermThresh", "1e-6"}};// Threshold for setting minimum relperm to 0 (thus specify critical saturations) /* Check first if there is anything on the command line to look for */ if (varnum == 1) { if (mpi_rank == 0) cout << "Error: No Eclipsefile or stonefiles found on command line." << endl; usageandexit(); } /* 'argeclindex' is so that vararg[argeclindex] = the eclipse filename. */ int argeclindex = parseCommandLine(options, varnum, vararg, mpi_rank == 0); if (argeclindex < 0) { if (mpi_rank == 0) cout << "Option -" << vararg[-argeclindex] << " unrecognized." << endl; usageandexit(); } RelPermUpscaleHelper helper(mpi_rank, options); bool owsystem = helper.saturationstring == "Sw"; // argeclindex should now point to the eclipse file static char* ECLIPSEFILENAME(vararg[argeclindex]); argeclindex += 1; // argeclindex jumps to next input argument, now it points to the stone files. // argeclindex now points to the first J-function. This index is not // to be touched now. static int rockfileindex = argeclindex; /* Check if at least one J-function is supplied on command line */ if (varnum <= rockfileindex) throw std::runtime_error("Error: No J-functions found on command line."); /* Check validity of boundary conditions chosen, and make booleans for boundary conditions, this allows more readable code later. */ helper.setupBoundaryConditions(); bool isFixed = helper.boundaryCondition == SinglePhaseUpscaler::Fixed, isLinear = helper.boundaryCondition == SinglePhaseUpscaler::Linear, isPeriodic = helper.boundaryCondition == SinglePhaseUpscaler::Periodic; // If this number is 1 or higher, the output will be interpolated, if not // the computed data is untouched. const int interpolationPoints = atoi(options["interpolate"].c_str()); bool doInterpolate = false; if (interpolationPoints > 1) { doInterpolate = true; } /*********************************************************************** * Step 2: * Load geometry and data from Eclipse file */ // Read data from the Eclipse file and // populate our vectors with data from the file // Test if filename exists and is readable ifstream eclipsefile(ECLIPSEFILENAME, ios::in); if (eclipsefile.fail()) { std::stringstream str; str << "Error: Filename " << ECLIPSEFILENAME << " not found or not readable."; throw str.str(); } eclipsefile.close(); if (helper.isMaster) cout << "Parsing Eclipse file <" << ECLIPSEFILENAME << "> ... "; flush(cout); start = clock(); Opm::ParseMode parseMode; Opm::ParserPtr parser(new Opm::Parser()); Opm::addNonStandardUpscalingKeywords(parser); Opm::DeckConstPtr deck(parser->parseFile(ECLIPSEFILENAME , parseMode)); finish = clock(); timeused = (double(finish)-double(start))/CLOCKS_PER_SEC; if (helper.isMaster) cout << " (" << timeused <<" secs)" << endl; Opm::DeckRecordConstPtr specgridRecord = deck->getKeyword("SPECGRID")->getRecord(0); std::array<int,3> res; res[0] = specgridRecord->getItem("NX")->getInt(0); res[1] = specgridRecord->getItem("NY")->getInt(0); res[2] = specgridRecord->getItem("NZ")->getInt(0); const double minPerm = atof(options["minPerm"].c_str()); const double maxPerm = atof(options["maxPerm"].c_str()); const double minPoro = atof(options["minPoro"].c_str()); helper.sanityCheckInput(deck, minPerm, maxPerm, minPoro); /*************************************************************************** * Step 3: * Load relperm- and J-function-curves for the stone types. * We read columns from text-files, syntax allowed is determined * by MonotCubicInterpolator which actually opens and parses the * text files. * * If a standard eclipse data file is given as input, the data columns * should be: * Sw Krw Kro J-func * (In this case, the option -relPermCurve determines which of Krw or Kro is used) * * If output from this very program is given as input, then the data columns read * Pc Sw Krx Kry Krz * * (and the option -relPermCurve and -jFunctionCurve are ignored) * * How do we determine which mode of operation? * - If PERMY and PERMZ are present in grdecl-file, we are in the anisotropic mode * */ // Number of stone-types is max(satnums): // If there is only one J-function supplied on the command line, // use that for all stone types. int stone_types = int(*(max_element(helper.satnums.begin(), helper.satnums.end()))); std::vector<string> JfunctionNames; // Placeholder for the names of the loaded J-functions. // This decides whether we are upscaling water or oil relative permeability const int relPermCurve = atoi(options["relPermCurve"].c_str()); // This decides whether we are upscaling both phases in this run or only one helper.upscaleBothPhases = (options["upscaleBothPhases"] == "true"); const int jFunctionCurve = atoi(options["jFunctionCurve"].c_str()); helper.points = atoi(options["points"].c_str()); const double gravity = atof(options["gravity"].c_str()); // Input for surfaceTension is dynes/cm // SI units are Joules/square metre const double surfaceTension = atof(options["surfaceTension"].c_str()) * 1e-3; // multiply with 10^-3 to obtain SI units const bool includeGravity = (fabs(gravity) > DBL_MIN); // true for non-zero gravity const int outputprecision = atoi(options["outputprecision"].c_str()); // Handle two command line input formats, either one J-function for all stone types // or one each. If there is only one stone type, both code blocks below are equivalent. if (varnum != rockfileindex + stone_types && varnum != rockfileindex + 1) throw std::runtime_error("Error: Wrong number of stone-functions provided."); for (int i=0 ; i < stone_types; ++i) { const char* ROCKFILENAME = vararg[rockfileindex+stone_types==varnum?rockfileindex+i:rockfileindex]; // Check if rock file exists and is readable: ifstream rockfile(ROCKFILENAME, ios::in); if (rockfile.fail()) { std::stringstream str; str << "Error: Filename " << ROCKFILENAME << " not found or not readable."; throw std::runtime_error(str.str()); } rockfile.close(); if (! helper.anisotropic_input) { MonotCubicInterpolator Jtmp; try { Jtmp = MonotCubicInterpolator(ROCKFILENAME, 1, jFunctionCurve); } catch (const char * errormessage) { std::stringstream str; str << "Error: " << errormessage << endl << "Check filename and -jFunctionCurve" << endl; throw std::runtime_error(str.str()); } // Invert J-function, now we get saturation as a function of pressure: if (Jtmp.isStrictlyMonotone()) { helper.InvJfunctions.push_back(MonotCubicInterpolator(Jtmp.get_fVector(), Jtmp.get_xVector())); JfunctionNames.push_back(ROCKFILENAME); if (helper.upscaleBothPhases) { helper.Krfunctions[0][0].push_back(MonotCubicInterpolator(ROCKFILENAME, 1, 2)); helper.Krfunctions[0][1].push_back(MonotCubicInterpolator(ROCKFILENAME, 1, 3)); } else { helper.Krfunctions[0][0].push_back(MonotCubicInterpolator(ROCKFILENAME, 1, relPermCurve)); } } else { std::stringstream str; str << "Error: Jfunction " << i+1 << " in rock file " << ROCKFILENAME << " was not invertible."; throw std::runtime_error(str.str()); } } else { // If input is anisotropic, then we are in second mode with different input file format MonotCubicInterpolator Pctmp; try { Pctmp = MonotCubicInterpolator(ROCKFILENAME, 2, 1); } catch (const char * errormessage) { std::stringstream str; str << "Error: " << errormessage << endl << "Check filename and columns 1 and 2 (Pc and " << helper.saturationstring <<")"; throw str.str(); } // Invert Pc(Sw) curve into Sw(Pc): if (Pctmp.isStrictlyMonotone()) { helper.SwPcfunctions.push_back(MonotCubicInterpolator(Pctmp.get_fVector(), Pctmp.get_xVector())); JfunctionNames.push_back(ROCKFILENAME); helper.Krfunctions[0][0].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 3)); helper.Krfunctions[1][0].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 4)); helper.Krfunctions[2][0].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 5)); if (helper.upscaleBothPhases) { helper.Krfunctions[0][1].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 6)); helper.Krfunctions[1][1].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 7)); helper.Krfunctions[2][1].push_back(MonotCubicInterpolator(ROCKFILENAME, 2, 8)); } } else { std::stringstream str; str << "Error: Pc(" << helper.saturationstring << ") curve " << i+1 << " in rock file " << ROCKFILENAME << " was not invertible."; throw std::runtime_error(str.str()); } } } // Check if input relperm curves satisfy Eclipse requirement of specifying critical saturations if (helper.doEclipseCheck) helper.checkCriticalSaturations(); /***************************************************************************** * Step 4: * Generate tesselated grid: * This is a step needed for the later discretization code to figure out which * cells are connected to which. Each cornerpoint-cell is tesselated into 8 tetrahedrons. * * In case of non-zero gravity, calculate z-values of every cell: * 1) Compute height of model by averaging z-values of the top layer corners. * 2) Calculate density difference between phases in SI-units * 3) Go through each cell and find the z-values of the eight corners of the cell. * Set height of cell equal to average of z-values of the corners minus half of * model height. Now the cell height is relative to model centre. * Set pressure difference for the cell equal to density difference times gravity * constant times cell height times factor 10^-7 to obtain bars (same as p_c) */ timeused_tesselation = helper.tesselateGrid(deck); /* If gravity is to be included, calculate z-values of every cell: */ if (includeGravity) helper.calculateCellPressureGradients(res); /****************************************************************************** * Step 5: * Go through each cell and calculate the minimum and * maximum capillary pressure possible in the cell, given poro, * perm and the J-function for the cell. This depends on the * J-function in that they represent all possible saturations, * ie. we do not want to extrapolate the J-functions (but we might * have to do that later in the computations). * * The user-supplied surface tension is ignored until * the final output of results. */ helper.calculateMinMaxCapillaryPressure(); /*************************************************************************** * Step 6: * Upscale capillary pressure function. * * This is upscaled in advance in order to be able to have uniformly distributed * saturation points for which upscaling is performed. * * Capillary pressure points are chosen heuristically in order to * ensure largest saturation interval between two saturation points * is 1/500 of the saturation interval. Monotone cubic interpolation * will be used afterwards for accessing the tabulated values. */ helper.upscaleCapillaryPressure(); /***************************************************************************** * Step 7: * Upscale single phase permeability * This uses the PERMX in the eclipse file as data, and upscales using * fixed boundary (no-flow) conditions * * In an MPI-environment, this is only done on the master node. */ helper.upscaleSinglePhasePermeability(); /***************************************************************** * Step 8: * * Loop through a given number of uniformly distributed saturation points * and upscale relative permeability for each of them. * a: Make vector of capillary pressure points corresponding to uniformly * distributed water saturation points between saturation endpoints. * b: Loop over capillary pressure points * 1) Loop over all cells to find the saturation value given the * capillary pressure found in (a). Given the saturation value, find the * phase permeability in the cell given input relperm curve and input * permeability values. * 2) Upscale phase permeability for the geometry. * c: Calculate relperm tensors from all the phase perm tensors. */ double avg_upscaling_time_pr_point; std::tie(timeused_upscale_wallclock, avg_upscaling_time_pr_point) = helper.upscalePermeability(mpi_rank); /* * Step 8c: Make relperm values from phaseperms * (only master node can do this) */ std::array<vector<vector<double>>,2> RelPermValues; RelPermValues[0] = helper.getRelPerm(0); if (helper.upscaleBothPhases) RelPermValues[1] = helper.getRelPerm(1); /********************************************************************************* * Step 9 * * Output results to stdout and optionally to file. Note, we only output to * file if the '-outputWater'-option and/or '-outputOil' has been set, as this option is an * empty string by default. */ if (helper.isMaster) { stringstream outputtmp; // Print a table of all computed values: outputtmp << "######################################################################" << endl; outputtmp << "# Results from upscaling relative permeability."<< endl; outputtmp << "#" << endl; #if HAVE_MPI outputtmp << "# (MPI-version)" << endl; #endif time_t now = std::time(NULL); outputtmp << "# Finished: " << asctime(localtime(&now)); utsname hostname; uname(&hostname); outputtmp << "# Hostname: " << hostname.nodename << endl; outputtmp << "#" << endl; outputtmp << "# Eclipse file: " << ECLIPSEFILENAME << endl; outputtmp << "# cells: " << helper.tesselatedCells << endl; outputtmp << "# Pore volume: " << helper.poreVolume << endl; outputtmp << "# volume: " << helper.volume << endl; outputtmp << "# Porosity: " << helper.poreVolume/helper.volume << endl; outputtmp << "#" << endl; if (! helper.anisotropic_input) { for (int i=0; i < stone_types ; ++i) { outputtmp << "# Stone " << i+1 << ": " << JfunctionNames[i] << " (" << helper.InvJfunctions[i].getSize() << " points)" << endl; } outputtmp << "# jFunctionCurve: " << options["jFunctionCurve"] << endl; if (!helper.upscaleBothPhases) outputtmp << "# relPermCurve: " << options["relPermCurve"] << endl; } else { // anisotropic input, not J-functions that are supplied on command line (but vector JfunctionNames is still used) for (int i=0; i < stone_types ; ++i) { outputtmp << "# Stone " << i+1 << ": " << JfunctionNames[i] << " (" << helper.Krfunctions[0][0][i].getSize() << " points)" << endl; } } outputtmp << "#" << endl; outputtmp << "# Timings: Tesselation: " << timeused_tesselation << " secs" << endl; outputtmp << "# Upscaling: " << timeused_upscale_wallclock << " secs"; #ifdef HAVE_MPI outputtmp << " (wallclock time)" << endl; outputtmp << "# " << avg_upscaling_time_pr_point << " secs pr. saturation point" << endl; outputtmp << "# MPI-nodes: " << mpi_nodecount << endl; // Single phase upscaling time is included here, in possibly a hairy way. double speedup = (avg_upscaling_time_pr_point * (helper.points + 1) + timeused_tesselation)/(timeused_upscale_wallclock + avg_upscaling_time_pr_point + timeused_tesselation); outputtmp << "# Speedup: " << speedup << ", efficiency: " << speedup/mpi_nodecount << endl; #else outputtmp << ", " << avg_upscaling_time_pr_point << " secs avg for " << helper.points << " runs" << endl; #endif outputtmp << "# " << endl; outputtmp << "# Options used:" << endl; outputtmp << "# Boundary conditions: "; if (isFixed) outputtmp << "Fixed (no-flow)" << endl; if (isPeriodic) outputtmp << "Periodic" << endl; if (isLinear) outputtmp << "Linear" << endl; outputtmp << "# points: " << options["points"] << endl; outputtmp << "# maxPermContrast: " << options["maxPermContrast"] << endl; outputtmp << "# minPerm: " << options["minPerm"] << endl; outputtmp << "# minPoro: " << options["minPoro"] << endl; outputtmp << "# surfaceTension: " << options["surfaceTension"] << " dynes/cm" << endl; if (includeGravity) { outputtmp << "# gravity: " << options["gravity"] << " m/s²" << endl; if (owsystem) outputtmp << "# waterDensity: " << options["waterDensity"] << " g/cm³" << endl; else outputtmp << "# gasDensity: " << options["waterDensity"] << " g/cm³" << endl; outputtmp << "# oilDensity: " << options["oilDensity"] << " g/cm³" << endl; } else { outputtmp << "# gravity: 0" << endl; } if (doInterpolate) { outputtmp << "# interpolate: " << options["interpolate"] << " points" << endl; } outputtmp << "# " << endl; outputtmp << "# Single phase permeability" << endl; outputtmp << "# |Kxx Kxy Kxz| = " << helper.permTensor(0,0) << " " << helper.permTensor(0,1) << " " << helper.permTensor(0,2) << endl; outputtmp << "# |Kyx Kyy Kyz| = " << helper.permTensor(1,0) << " " << helper.permTensor(1,1) << " " << helper.permTensor(1,2) << endl; outputtmp << "# |Kzx Kzy Kzz| = " << helper.permTensor(2,0) << " " << helper.permTensor(2,1) << " " << helper.permTensor(2,2) << endl; outputtmp << "# " << endl; if (doInterpolate) { outputtmp << "# NB: Data points shown are interpolated." << endl; } outputtmp << "######################################################################" << endl; if (helper.upscaleBothPhases) { string phase1, phase2; if (owsystem) phase1="w"; else phase1="g"; phase2="o"; if (isFixed) { outputtmp << "# Pc (Pa) " << helper.saturationstring << " Kr" << phase1 << "xx Kr" << phase1 << "yy Kr" << phase1 << "zz" << " Kr" << phase2 << "xx Kr" << phase2 << "yy Kr" << phase2 << "zz" << endl; } else if (isPeriodic || isLinear) { outputtmp << "# Pc (Pa) " << helper.saturationstring << " Kr" << phase1 << "xx Kr" << phase1 << "yy Kr" << phase1 << "zz Kr" << phase1 << "yz Kr" << phase1 << "xz Kr" << phase1 << "xy Kr" << phase1 << "zy Kr" << phase1 << "zx Kr" << phase1 << "yx" << " Kr" << phase2 << "xx Kr" << phase2 << "yy Kr" << phase2 << "zz Kr" << phase2 << "yz Kr" << phase2 << "xz Kr" << phase2 << "xy Kr" << phase2 << "zy Kr" << phase2 << "zx Kr" << phase2 << "yx" << endl; } } else { if (isFixed) { outputtmp << "# Pc (Pa) " << helper.saturationstring << " Krxx Kryy Krzz" << endl; } else if (isPeriodic || isLinear) { outputtmp << "# Pc (Pa) " << helper.saturationstring << " Krxx Kryy Krzz Kryz Krxz Krxy Krzy Krzx Kryx" << endl; } } vector<double> Pvalues = helper.pressurePoints; // Multiply all pressures with the surface tension (potentially) supplied // at the command line. This multiplication has been postponed to here // to avoid division by zero and to avoid special handling of negative // capillary pressure in the code above. std::transform(Pvalues.begin(), Pvalues.end(), Pvalues.begin(), std::bind1st(std::multiplies<double>(), surfaceTension)); vector<double> Satvalues = helper.WaterSaturation; //.get_fVector(); // If user wants interpolated output, do monotone cubic interpolation // by modifying the data vectors that are to be printed if (doInterpolate) { // Find min and max for saturation values double xmin = +DBL_MAX; double xmax = -DBL_MAX; for (unsigned int i = 0; i < Satvalues.size(); ++i) { if (Satvalues[i] < xmin) { xmin = Satvalues[i]; } if (Satvalues[i] > xmax) { xmax = Satvalues[i]; } } // Make uniform grid in saturation axis vector<double> SatvaluesInterp; for (int i = 0; i < interpolationPoints; ++i) { SatvaluesInterp.push_back(xmin + ((double)i)/((double)interpolationPoints-1)*(xmax-xmin)); } // Now capillary pressure and computed relperm-values must be viewed as functions // of saturation, and then interpolated on the uniform saturation grid. // Now overwrite existing Pvalues and relperm-data with interpolated data: MonotCubicInterpolator PvaluesVsSaturation(Satvalues, Pvalues); Pvalues.clear(); for (int i = 0; i < interpolationPoints; ++i) { Pvalues.push_back(PvaluesVsSaturation.evaluate(SatvaluesInterp[i])); } for (int voigtIdx = 0; voigtIdx < helper.tensorElementCount; ++voigtIdx) { MonotCubicInterpolator RelPermVsSaturation(Satvalues, RelPermValues[0][voigtIdx]); RelPermValues[0][voigtIdx].clear(); for (int i=0; i < interpolationPoints; ++i) { RelPermValues[0][voigtIdx].push_back(RelPermVsSaturation.evaluate(SatvaluesInterp[i])); } } if (helper.upscaleBothPhases) { for (int voigtIdx = 0; voigtIdx < helper.tensorElementCount; ++voigtIdx) { MonotCubicInterpolator RelPermVsSaturation(Satvalues, RelPermValues[1][voigtIdx]); RelPermValues[1][voigtIdx].clear(); for (int i=0; i < interpolationPoints; ++i) { RelPermValues[1][voigtIdx].push_back(RelPermVsSaturation.evaluate(SatvaluesInterp[i])); } } } // Now also overwrite Satvalues Satvalues.clear(); Satvalues = SatvaluesInterp; } // The code below does not care whether the data is interpolated or not. const int fieldwidth = outputprecision + 8; for (unsigned int i=0; i < Satvalues.size(); ++i) { outputtmp << showpoint << setw(fieldwidth) << setprecision(outputprecision) << Pvalues[i]; outputtmp << showpoint << setw(fieldwidth) << setprecision(outputprecision) << Satvalues[i]; for (int voigtIdx = 0; voigtIdx < helper.tensorElementCount; ++voigtIdx) { outputtmp << showpoint << setw(fieldwidth) << setprecision(outputprecision) << RelPermValues[0][voigtIdx][i]; } if (helper.upscaleBothPhases) { for (int voigtIdx = 0; voigtIdx < helper.tensorElementCount; ++voigtIdx) { outputtmp << showpoint << setw(fieldwidth) << setprecision(outputprecision) << RelPermValues[1][voigtIdx][i]; } } outputtmp << endl; } cout << outputtmp.str(); if (options["output"] != "") { cout << "Writing results to " << options["output"] << endl; ofstream outfile; outfile.open(options["output"].c_str(), ios::out | ios::trunc); outfile << outputtmp.str(); outfile.close(); } // If both phases are upscaled and output is specyfied, create SWOF or SGOF files for Eclipse if (options["output"] != "" && helper.upscaleBothPhases) { cout << "Writing Eclipse compatible files to " << getEclipseOutputFile(options["output"],'X',owsystem?'W':'G') << ", " << getEclipseOutputFile(options["output"],'Y',owsystem?'W':'G') << " and " << getEclipseOutputFile(options["output"],'Z',owsystem?'W':'G')<< endl; for (int comp=0;comp<3;++comp) writeEclipseOutput(RelPermValues, Satvalues, Pvalues, options, comp, owsystem); } } return 0; } catch (const std::exception &e) { std::cerr << e.what() << "\n"; usageandexit(); }
lkerrand/opm-upscaling
examples/upscale_relperm.cpp
C++
gpl-3.0
43,577
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ #include "ns3/uinteger.h" #include "ns3/names.h" #include "tracker-helper.h" namespace ns3 { TrackerHelper::TrackerHelper () { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("Port", UintegerValue (9)); SetAttribute ("RemoteAddress", AddressValue (Ipv4Address ("10.255.255.255"))); SetAttribute ("RemotePort", UintegerValue (9)); } /* TrackerHelper::TrackerHelper(uint16_t port) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("Port", UintegerValue (port)); } TrackerHelper::TrackerHelper(Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } TrackerHelper::TrackerHelper(Ipv4Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } TrackerHelper::TrackerHelper(Ipv6Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } TrackerHelper::TrackerHelper(uint16_t port, Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("Port", UintegerValue (port)); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } TrackerHelper::TrackerHelper(uint16_t port, Ipv4Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("Port", UintegerValue (port)); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } TrackerHelper::TrackerHelper(uint16_t port, Ipv6Address address, uint16_t remotePort) { m_factory.SetTypeId (Tracker::GetTypeId ()); SetAttribute ("Port", UintegerValue (port)); SetAttribute ("RemoteAddress", AddressValue (address)); SetAttribute ("RemotePort", UintegerValue (remotePort)); } */ void TrackerHelper::SetAttribute (std::string name, const AttributeValue &value) { m_factory.Set (name, value); } ApplicationContainer TrackerHelper::Install (Ptr<Node> node) const { return ApplicationContainer (InstallPriv (node)); } ApplicationContainer TrackerHelper::Install (std::string nodeName) const { Ptr<Node> node = Names::Find<Node> (nodeName); return ApplicationContainer (InstallPriv (node)); } ApplicationContainer TrackerHelper::Install (NodeContainer c) const { ApplicationContainer apps; for (NodeContainer::Iterator i = c.Begin (); i != c.End (); ++i) { apps.Add (InstallPriv (*i)); } return apps; } Ptr<Application> TrackerHelper::InstallPriv (Ptr<Node> node) const { Ptr<Application> app = m_factory.Create<Tracker> (); node->AddApplication (app); return app; } //------------------------------------------------------------------------- /* Fonctions pour le coté client: */ //------------------------------------------------------------------------- void TrackerHelper::SetFill (Ptr<Application> app, std::string fill) { app->GetObject<Tracker>()->SetFill (fill); } /* void TrackerHelper::SetFill (Ptr<Application> app, uint8_t fill, uint32_t dataLength) { app->GetObject<Tracker>()->SetFill (fill, dataLength); } //*/ /* void TrackerHelper::SetFill (Ptr<Application> app, uint8_t *fill, uint32_t fillLength, uint32_t dataLength) { app->GetObject<Tracker>()->SetFill (fill, fillLength, dataLength); } //*/ } // namespace ns3
sT4R3K/Tracker-2013
source/tracker/helper/tracker-helper.cc
C++
gpl-3.0
3,629
<?php use_helper('DateForm') ?> <?php echo select_time_tag("turno[hora_inicio]", $turno->getHoraInicio(), array('include_second' => false, '12hour_time' => true));?>
carpe-diem/conectar-igualdad-server-apps
apps/src/intranet/alba/apps/principal/modules/turno/templates/_hora_inicio.php
PHP
gpl-3.0
166
/** \file wxsimagetreeeditordlg.cpp * * This file is part of wxSmith plugin for Code::Blocks Studio * Copyright (C) 2010 Gary Harris * * wxSmith 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 3 of the License, or * (at your option) any later version. * * wxSmith 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 wxSmith. If not, see <http://www.gnu.org/licenses/>. * * This code was taken from the wxSmithImage plug-in, copyright Ron Collins * and released under the GPL. * */ #include "wxsimagetreeeditordlg.h" //(*InternalHeaders(wxsImageTreeEditDialog) #include <wx/font.h> #include <wx/intl.h> #include <wx/string.h> //*) #include <wx/msgdlg.h> #include "../properties/wxsimagelisteditordlg.h" //(*IdInit(wxsImageTreeEditorDlg) const long wxsImageTreeEditorDlg::ID_STATICTEXT1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_TREECTRL1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_IMAGEBUTTON1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_IMAGEBUTTON2 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT3 = wxNewId(); const long wxsImageTreeEditorDlg::ID_IMAGEBUTTON3 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT4 = wxNewId(); const long wxsImageTreeEditorDlg::ID_IMAGEBUTTON4 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT5 = wxNewId(); const long wxsImageTreeEditorDlg::ID_BUTTON3 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT6 = wxNewId(); const long wxsImageTreeEditorDlg::ID_CHECKBOX1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_IMAGEBUTTON5 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT11 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT12 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT13 = wxNewId(); const long wxsImageTreeEditorDlg::ID_COMBOBOX1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT7 = wxNewId(); const long wxsImageTreeEditorDlg::ID_COMBOBOX2 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT8 = wxNewId(); const long wxsImageTreeEditorDlg::ID_COMBOBOX3 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT9 = wxNewId(); const long wxsImageTreeEditorDlg::ID_COMBOBOX4 = wxNewId(); const long wxsImageTreeEditorDlg::ID_STATICTEXT10 = wxNewId(); const long wxsImageTreeEditorDlg::ID_BUTTON1 = wxNewId(); const long wxsImageTreeEditorDlg::ID_BUTTON2 = wxNewId(); //*) BEGIN_EVENT_TABLE(wxsImageTreeEditorDlg, wxDialog) //(*EventTable(wxsImageTreeEditorDlg) //*) END_EVENT_TABLE() wxsImageTreeEditorDlg::wxsImageTreeEditorDlg(wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size) { //(*Initialize(wxsImageTreeEditorDlg) wxGridSizer* GridSizer1; wxBoxSizer* BoxSizer3; wxBoxSizer* BoxSizer10; wxBoxSizer* BoxSizer7; wxBoxSizer* BoxSizer11; wxBoxSizer* BoxSizer13; wxBoxSizer* BoxSizer2; wxBoxSizer* BoxSizer9; wxBoxSizer* BoxSizer4; wxBoxSizer* BoxSizer8; wxBoxSizer* BoxSizer1; wxBoxSizer* BoxSizer12; wxBoxSizer* BoxSizer6; wxBoxSizer* BoxSizer5; Create(parent, wxID_ANY, _("Tree Item Editor"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE, _T("wxID_ANY")); wxFont thisFont(8,wxSWISS,wxFONTSTYLE_NORMAL,wxNORMAL,false,_T("Arial"),wxFONTENCODING_DEFAULT); SetFont(thisFont); BoxSizer1 = new wxBoxSizer(wxVERTICAL); BoxSizer2 = new wxBoxSizer(wxHORIZONTAL); StaticText1 = new wxStaticText(this, ID_STATICTEXT1, _("Edit Tree Items"), wxPoint(0,0), wxSize(400,20), wxST_NO_AUTORESIZE|wxALIGN_CENTRE, _T("ID_STATICTEXT1")); wxFont StaticText1Font(10,wxSWISS,wxFONTSTYLE_NORMAL,wxBOLD,false,_T("Arial"),wxFONTENCODING_DEFAULT); StaticText1->SetFont(StaticText1Font); BoxSizer2->Add(StaticText1, 1, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0); BoxSizer1->Add(BoxSizer2, 0, wxEXPAND|wxALIGN_CENTER_HORIZONTAL|wxALIGN_CENTER_VERTICAL, 0); BoxSizer3 = new wxBoxSizer(wxHORIZONTAL); BoxSizer5 = new wxBoxSizer(wxHORIZONTAL); StaticBoxSizer1 = new wxStaticBoxSizer(wxHORIZONTAL, this, _("tree-name")); Tree1 = new wxTreeCtrl(this, ID_TREECTRL1, wxPoint(2,36), wxSize(246,359), wxTR_EDIT_LABELS|wxTR_DEFAULT_STYLE, wxDefaultValidator, _T("ID_TREECTRL1")); StaticBoxSizer1->Add(Tree1, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer5->Add(StaticBoxSizer1, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer3->Add(BoxSizer5, 0, wxALL|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 0); BoxSizer6 = new wxBoxSizer(wxHORIZONTAL); StaticBoxSizer2 = new wxStaticBoxSizer(wxVERTICAL, this, _("Attributes")); BoxSizer7 = new wxBoxSizer(wxHORIZONTAL); bAddItem = new wxBitmapButton(this, ID_IMAGEBUTTON1, wxNullBitmap, wxPoint(256,36), wxSize(24,23), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_IMAGEBUTTON1")); bAddItem->SetToolTip(_("Add A New Item")); BoxSizer7->Add(bAddItem, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText2 = new wxStaticText(this, wxID_ANY, _("Add Item"), wxPoint(290,40), wxDefaultSize, 0, _T("wxID_ANY")); BoxSizer7->Add(StaticText2, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer7, 0, wxEXPAND|wxALIGN_LEFT|wxALIGN_TOP, 0); BoxSizer8 = new wxBoxSizer(wxHORIZONTAL); bAddSubItem = new wxBitmapButton(this, ID_IMAGEBUTTON2, wxNullBitmap, wxPoint(256,66), wxSize(24,23), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_IMAGEBUTTON2")); bAddSubItem->SetToolTip(_("Add A New Child")); BoxSizer8->Add(bAddSubItem, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText3 = new wxStaticText(this, ID_STATICTEXT3, _("Add Sub-Item"), wxPoint(290,70), wxDefaultSize, 0, _T("ID_STATICTEXT3")); BoxSizer8->Add(StaticText3, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer8, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer9 = new wxBoxSizer(wxHORIZONTAL); bDelItem = new wxBitmapButton(this, ID_IMAGEBUTTON3, wxNullBitmap, wxPoint(256,96), wxSize(24,23), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_IMAGEBUTTON3")); bDelItem->SetToolTip(_("Delete Current Item")); BoxSizer9->Add(bDelItem, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText4 = new wxStaticText(this, ID_STATICTEXT4, _("Delete Current Item"), wxPoint(290,100), wxDefaultSize, 0, _T("ID_STATICTEXT4")); BoxSizer9->Add(StaticText4, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer9, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer10 = new wxBoxSizer(wxHORIZONTAL); bDelAllItems = new wxBitmapButton(this, ID_IMAGEBUTTON4, wxNullBitmap, wxPoint(256,126), wxSize(24,23), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_IMAGEBUTTON4")); bDelAllItems->SetToolTip(_("Delete All Items")); BoxSizer10->Add(bDelAllItems, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText5 = new wxStaticText(this, ID_STATICTEXT5, _("Delete All Items"), wxPoint(290,130), wxDefaultSize, 0, _T("ID_STATICTEXT5")); BoxSizer10->Add(StaticText5, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer10, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer11 = new wxBoxSizer(wxHORIZONTAL); bItemColor = new wxButton(this, ID_BUTTON3, _("C"), wxPoint(256,156), wxSize(24,24), 0, wxDefaultValidator, _T("ID_BUTTON3")); wxFont bItemColorFont(10,wxSWISS,wxFONTSTYLE_NORMAL,wxBOLD,false,_T("Arial Black"),wxFONTENCODING_DEFAULT); bItemColor->SetFont(bItemColorFont); bItemColor->SetToolTip(_("Set Item Text Color")); BoxSizer11->Add(bItemColor, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText6 = new wxStaticText(this, ID_STATICTEXT6, _("Set Item Text Color"), wxPoint(290,160), wxDefaultSize, 0, _T("ID_STATICTEXT6")); BoxSizer11->Add(StaticText6, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer11, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer12 = new wxBoxSizer(wxHORIZONTAL); cxItemBold = new wxCheckBox(this, ID_CHECKBOX1, _(" Set Item Text Bold"), wxPoint(262,192), wxDefaultSize, 0, wxDefaultValidator, _T("ID_CHECKBOX1")); cxItemBold->SetValue(false); cxItemBold->SetToolTip(_("Set Item Text Bold")); BoxSizer12->Add(cxItemBold, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer12, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer13 = new wxBoxSizer(wxHORIZONTAL); bEditItem = new wxBitmapButton(this, ID_IMAGEBUTTON5, wxNullBitmap, wxPoint(256,216), wxSize(24,23), wxBU_AUTODRAW, wxDefaultValidator, _T("ID_IMAGEBUTTON5")); bEditItem->SetToolTip(_("Start Editor On Current Item")); BoxSizer13->Add(bEditItem, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); StaticText11 = new wxStaticText(this, ID_STATICTEXT11, _("Edit Current Item"), wxPoint(290,220), wxDefaultSize, 0, _T("ID_STATICTEXT11")); BoxSizer13->Add(StaticText11, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticBoxSizer2->Add(BoxSizer13, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); GridSizer1 = new wxGridSizer(5, 2, 0, 0); StaticText12 = new wxStaticText(this, ID_STATICTEXT12, _("Image-List"), wxPoint(256,272), wxDefaultSize, 0, _T("ID_STATICTEXT12")); GridSizer1->Add(StaticText12, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); StaticText13 = new wxStaticText(this, ID_STATICTEXT13, _("Label"), wxPoint(310,272), wxSize(82,14), wxST_NO_AUTORESIZE, _T("ID_STATICTEXT13")); StaticText13->SetForegroundColour(wxColour(0,0,255)); GridSizer1->Add(StaticText13, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 5); cbNormal = new wxBitmapComboBox(this, ID_COMBOBOX1, wxEmptyString, wxPoint(256,296), wxSize(48,22), 0, NULL, wxCB_READONLY, wxDefaultValidator, _T("ID_COMBOBOX1")); GridSizer1->Add(cbNormal, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 3); StaticText7 = new wxStaticText(this, ID_STATICTEXT7, _("Normal Image"), wxPoint(310,300), wxDefaultSize, 0, _T("ID_STATICTEXT7")); GridSizer1->Add(StaticText7, 0, wxTOP|wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); cbSelected = new wxBitmapComboBox(this, ID_COMBOBOX2, wxEmptyString, wxPoint(256,326), wxSize(48,22), 0, NULL, wxCB_READONLY, wxDefaultValidator, _T("ID_COMBOBOX2")); GridSizer1->Add(cbSelected, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); StaticText8 = new wxStaticText(this, ID_STATICTEXT8, _("Selected Image"), wxPoint(310,330), wxDefaultSize, 0, _T("ID_STATICTEXT8")); GridSizer1->Add(StaticText8, 0, wxTOP|wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); cbExpanded = new wxBitmapComboBox(this, ID_COMBOBOX3, wxEmptyString, wxPoint(256,356), wxSize(48,22), 0, NULL, wxCB_READONLY, wxDefaultValidator, _T("ID_COMBOBOX3")); GridSizer1->Add(cbExpanded, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); StaticText9 = new wxStaticText(this, ID_STATICTEXT9, _("Expanded Image"), wxPoint(310,360), wxDefaultSize, 0, _T("ID_STATICTEXT9")); GridSizer1->Add(StaticText9, 0, wxTOP|wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); cbSelExpanded = new wxBitmapComboBox(this, ID_COMBOBOX4, wxEmptyString, wxPoint(256,386), wxSize(48,22), 0, NULL, wxCB_READONLY, wxDefaultValidator, _T("ID_COMBOBOX4")); GridSizer1->Add(cbSelExpanded, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 3); StaticText10 = new wxStaticText(this, ID_STATICTEXT10, _("Sel+Exp Image"), wxPoint(310,390), wxDefaultSize, 0, _T("ID_STATICTEXT10")); GridSizer1->Add(StaticText10, 0, wxTOP|wxLEFT|wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL, 3); StaticBoxSizer2->Add(GridSizer1, 0, wxTOP|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer6->Add(StaticBoxSizer2, 0, wxLEFT|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer3->Add(BoxSizer6, 0, wxALL|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 0); BoxSizer1->Add(BoxSizer3, 0, wxALL|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 0); BoxSizer4 = new wxBoxSizer(wxHORIZONTAL); bOK = new wxButton(this, ID_BUTTON1, _("OK"), wxPoint(48,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON1")); bOK->SetDefault(); BoxSizer4->Add(bOK, 0, wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer4->Add(-1,-1,1, wxLEFT|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); bCancel = new wxButton(this, ID_BUTTON2, _("Cancel"), wxPoint(280,440), wxDefaultSize, 0, wxDefaultValidator, _T("ID_BUTTON2")); BoxSizer4->Add(bCancel, 0, wxLEFT|wxALIGN_LEFT|wxALIGN_BOTTOM, 5); BoxSizer1->Add(BoxSizer4, 0, wxTOP|wxEXPAND|wxALIGN_LEFT|wxALIGN_BOTTOM, 0); SetSizer(BoxSizer1); static const char *ImageList1_0_XPM[] = { "16 16 3 1", ". c Black", "X c #00C000", "_ c None", "________......._", "________.XXXXX._", "___..___.XXXXX._", "___..___.XXXXX._", "_......_.XXXXX._", "_......_.XXXXX._", "___..___.XXXXX._", "___..___.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XX.XX._", "________.X._.X._", "________..___.._", "................" }; static const char *ImageList1_1_XPM[] = { "16 16 4 1", "o c Black", ". c #000080", "X c #0000FF", "_ c None", "________......._", "________.XXXXX._", "___oo___.XXXXX._", "___oo___.XXXXX._", "_oooooo_.XXXXX._", "_oooooo_.XXXXX._", "___oo___.XXXXX._", "___oo___.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XX.XX._", "________.X._.X._", "________..___.._", "oooooooooooooooo" }; static const char *ImageList1_2_XPM[] = { "16 16 3 1", ". c Black", "_ c None", "X c #FF4040", "________......._", "________.XXXXX._", "__.___._.XXXXX._", "__.._.._.XXXXX._", "___...__.XXXXX._", "____.___.XXXXX._", "___...__.XXXXX._", "__.._.._.XXXXX._", "__.___._.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XXXXX._", "________.XX.XX._", "________.X._.X._", "________..___.._", "................" }; static const char *ImageList1_3_XPM[] = { "16 16 22 1", "4 c Black", "3 c #A5AEBD", "= c #5478B4", "1 c #95A3BB", "O c #9AA7BC", ": c #758EB7", "$ c #6986B6", "# c #4971B2", "* c #8A9CBA", "X c #8598B9", "o c #ABB2BE", "; c #7F95B9", "- c #4E74B3", "2 c #A0ABBC", "+ c #6F8AB7", "_ c None", ". c #B5B9BF", "@ c #3E69B1", "< c #90A0BA", "> c #6483B5", ", c #5A7BB4", "& c #5F7FB5", "________________", "____.Xo______OO_", "____+@#.____$@&_", "____*@@X__.=@=o_", "_____-@-_.=@=.__", "_____;@@X=@=.___", "_____.#@@@$.____", "______:@@>______", "_____:@@@+______", "___.,@#&@@._____", "__o=@=oO@@<_____", "_1#@=._.@@-_____", "*@@$____>@@2____", ":#*_____3#,.____", "________________", "4444444444444444" }; static const char *ImageList1_4_XPM[] = { "16 16 2 1", ". c Black", "_ c None", "________________", "______..________", "______..._______", "_____...._______", "_____._...______", "____.._...______", "____.___..______", "___..___..._____", "___._____.._____", "___.........____", "__.._____...____", "__._______...___", "_.._______...___", "_....___......._", "________________", "................" }; ImageList1 = new wxImageList(16, 16, 6); ImageList1->Add(wxBitmap(ImageList1_0_XPM)); ImageList1->Add(wxBitmap(ImageList1_1_XPM)); ImageList1->Add(wxBitmap(ImageList1_2_XPM)); ImageList1->Add(wxBitmap(ImageList1_3_XPM)); ImageList1->Add(wxBitmap(ImageList1_4_XPM)); ColourDialog1 = new wxColourDialog(this); BoxSizer1->Fit(this); BoxSizer1->SetSizeHints(this); Connect(ID_TREECTRL1,wxEVT_COMMAND_TREE_SEL_CHANGED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnTreeCtrl1SelectionChanged); // Set the bitmaps for bAddItem. bAddItem->SetBitmapLabel(ImageList1->GetBitmap(0)); Connect(ID_IMAGEBUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbAddItemClick); // Set the bitmaps for bAddSubItem. bAddSubItem->SetBitmapLabel(ImageList1->GetBitmap(1)); Connect(ID_IMAGEBUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbAddSubItemClick); // Set the bitmaps for bDelItem. bDelItem->SetBitmapLabel(ImageList1->GetBitmap(2)); Connect(ID_IMAGEBUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbDelItemClick); // Set the bitmaps for bDelAllItems. bDelAllItems->SetBitmapLabel(ImageList1->GetBitmap(3)); Connect(ID_IMAGEBUTTON4,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbDelAllItemsClick); Connect(ID_BUTTON3,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbItemColorClick); Connect(ID_CHECKBOX1,wxEVT_COMMAND_CHECKBOX_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OncxItemBoldClick); // Set the bitmaps for bEditItem. bEditItem->SetBitmapLabel(ImageList1->GetBitmap(4)); Connect(ID_IMAGEBUTTON5,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbEditItemClick); Connect(ID_COMBOBOX1,wxEVT_COMMAND_COMBOBOX_SELECTED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OncbNormalSelect); Connect(ID_COMBOBOX2,wxEVT_COMMAND_COMBOBOX_SELECTED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OncbSelectedSelect); Connect(ID_COMBOBOX3,wxEVT_COMMAND_COMBOBOX_SELECTED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OncbExpandedSelect); Connect(ID_COMBOBOX4,wxEVT_COMMAND_COMBOBOX_SELECTED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OncbSelExpandedSelect); Connect(ID_BUTTON1,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbOKClick); Connect(ID_BUTTON2,wxEVT_COMMAND_BUTTON_CLICKED,(wxObjectEventFunction)&wxsImageTreeEditorDlg::OnbCancelClick); //*) } wxsImageTreeEditorDlg::~wxsImageTreeEditorDlg() { //(*Destroy(wxsImageTreeEditorDlg) //*) } /*! \brief Run the dialogue. * * \param aItems wxArrayString& * \return bool * */ bool wxsImageTreeEditorDlg::Execute(wxArrayString &aItems) { int i, n; int jv, j1, j2, j3, j4; wxColor jc; bool jb; wxString jt; wxTreeItemId jp[32]; wxString ss, tt; wxTreeItemId root; wxTreeItemId item; wxBitmap bmp; wxsImageList *ilist; // get name of combo-box and image-list n = aItems.GetCount(); m_sTreeName = _("<unknown>"); m_sImageName = _("<none>"); if(n >= 1){ m_sTreeName = aItems.Item(0); } if(n >= 2){ m_sImageName = aItems.Item(1); } // show the names ss = _("Tree Control: ") + m_sTreeName; StaticBoxSizer1->GetStaticBox()->SetLabel(ss); ss = m_sImageName; StaticText13->SetLabel(ss); // clear old junk Tree1->DeleteAllItems(); // a valid image-list given? m_imageList.RemoveAll(); ilist = (wxsImageList *) wxsImageListEditorDlg::FindTool(NULL, m_sImageName); if(ilist != NULL){ ilist->GetImageList(m_imageList); } SetImageList(m_imageList); // add all the new items n = aItems.GetCount(); for(i = 2; i < n; i++){ ss = aItems.Item(i); ParseTreeItem(ss, jv, jc, jb, j1, j2, j3, j4, jt); if(jv == 0){ item = Tree1->AddRoot(jt); } else{ item = Tree1->AppendItem(jp[jv-1], jt); } jp[jv] = item; if(jc.IsOk()){ Tree1->SetItemTextColour(item, jc); } Tree1->SetItemBold(item, jb); Tree1->SetItemImage(item, j1, wxTreeItemIcon_Normal); Tree1->SetItemImage(item, j2, wxTreeItemIcon_Selected); Tree1->SetItemImage(item, j3, wxTreeItemIcon_Expanded); Tree1->SetItemImage(item, j4, wxTreeItemIcon_SelectedExpanded); } Tree1->ExpandAll(); // show the dialog and wait for a response n = ShowModal(); // save all new stuff? if(n == wxOK){ // must save combo-box name and image-list name aItems.Clear(); aItems.Add(m_sTreeName); aItems.Add(m_sImageName); // save the root item and all it's children // this effectively saves every item in the tree // I wanted to use a simple loop here, but it works MUCH easier with a recursive function root = Tree1->GetRootItem(); if(root.IsOk()){ EncodeTreeItems(root, 0, aItems); } } // done return (n == wxOK); } /*! \brief Set the image list. * * \param inImageList wxImageList& * \return void * */ void wxsImageTreeEditorDlg::SetImageList(wxImageList &inImageList) { int i, n; wxString ss, tt; wxBitmap bmp; // save the image list in the tree control Tree1->SetImageList(&inImageList); // valid list given? n = inImageList.GetImageCount(); if(n <= 0){ cbNormal->Enable(false); cbSelected->Enable(false); cbExpanded->Enable(false); cbSelExpanded->Enable(false); } else { cbNormal->Enable(true); cbSelected->Enable(true); cbExpanded->Enable(true); cbSelExpanded->Enable(true); } // set images in the drop-down lists cbNormal->Clear(); cbSelected->Clear(); cbExpanded->Clear(); cbSelExpanded->Clear(); ss = _("<none>"); cbNormal->Append(ss); cbSelected->Append(ss); cbExpanded->Append(ss); cbSelExpanded->Append(ss); for(i = 0; i < n; i++){ ss.Printf(wxT("%d"), i); bmp = inImageList.GetBitmap(i); cbNormal->Append(ss, bmp); cbSelected->Append(ss, bmp); cbExpanded->Append(ss, bmp); cbSelExpanded->Append(ss, bmp); } // default selections cbNormal->SetSelection(0); cbSelected->SetSelection(0); cbExpanded->SetSelection(0); cbSelExpanded->SetSelection(0); } /*! \brief Add a new item as a sibling of the current item. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbAddItemClick(wxCommandEvent &event) { int n; wxTreeItemId current; // how many items? n = Tree1->GetCount(); // and current selection current = Tree1->GetSelection(); // add a root item? if(n <= 0){ current.Unset(); AddItem(current); } // no current item? else if(! current.IsOk()){ current = Tree1->GetRootItem(); AddItem(current); } // else a sibling else { current = Tree1->GetItemParent(current); AddItem(current); } } /*! \brief Add a new item as a child of the current item. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbAddSubItemClick(wxCommandEvent &event) { int n; wxTreeItemId current; // how many items? n = Tree1->GetCount(); // and current selection current = Tree1->GetSelection(); // add a root item? if(n <= 0){ current.Unset(); AddItem(current); } // no current item? else if(! current.IsOk()){ current = Tree1->GetRootItem(); AddItem(current); } // else a child else { AddItem(current); } // make sure it is expanded Tree1->Expand(current); } /*! \brief Add a new item to the tree. * * \param inParent wxTreeItemId& * \return void * */ void wxsImageTreeEditorDlg::AddItem(wxTreeItemId &inParent){ int n; wxString ss, tt; wxTreeItemId parent, current; wxColour cc; bool b; // how many items? n = Tree1->GetCount(); // add a root item? if(n <= 0){ ss = _("root"); current = Tree1->AddRoot(ss); } // bad parent? else if(! inParent.IsOk()){ ss.Printf(_("item %d"), n); parent = Tree1->GetRootItem(); current = Tree1->AppendItem(parent, ss); } // else a child of whatever else { ss.Printf(_("item %d"), n); current = Tree1->AppendItem(inParent, ss); } // if it failed, skip the rest of this if(! current.IsOk()){ return; } // set text colour cc = bItemColor->GetForegroundColour(); Tree1->SetItemTextColour(current, cc); // bold or plain b = cxItemBold->GetValue(); Tree1->SetItemBold(current, b); // the images n = cbNormal->GetSelection() - 1; if(n >= 0){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Normal); } n = cbSelected->GetSelection() - 1; if(n >= 0){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Selected); } n = cbExpanded->GetSelection() - 1; if(n >= 0){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Expanded); } n = cbSelExpanded->GetSelection() - 1; if(n >= 0){ Tree1->SetItemImage(current, n, wxTreeItemIcon_SelectedExpanded); } // redraw the whole thing Tree1->Refresh(); } /*! \brief Delete a tree item. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbDelItemClick(wxCommandEvent &event) { wxTreeItemId current; // current selection current = Tree1->GetSelection(); // delete it if(current.IsOk()){ Tree1->Delete(current); } } /*! \brief Delete all tree items. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbDelAllItemsClick(wxCommandEvent &event) { int n; wxString ss; n = wxMessageBox(_("Delete ALL Items In Tree?"), _("Clear"), wxYES_NO); if(n == wxYES){ Tree1->DeleteAllItems(); } } /*! \brief Select the item's colour. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbItemColorClick(wxCommandEvent &event) { int n; wxColourData cd; wxColour cc; wxTreeItemId current; // ask user for a new color n = ColourDialog1->ShowModal(); if(n != wxID_OK){ return; } // get the color cd = ColourDialog1->GetColourData(); cc = cd.GetColour(); // set the button text bItemColor->SetForegroundColour(cc); // and the current item current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemTextColour(current, cc); } } /*! \brief Make the item text bold. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OncxItemBoldClick(wxCommandEvent &event) { bool b; wxTreeItemId current; // get checkbox value b = cxItemBold->GetValue(); // and set the current item current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemBold(current, b); } } /*! \brief Edit an item. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbEditItemClick(wxCommandEvent &event) { wxTreeItemId current; // current selection current = Tree1->GetSelection(); // delete it if(current.IsOk()){ Tree1->EditLabel(current); } } /*! \brief Select the normal state image. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OncbNormalSelect(wxCommandEvent &event) { int n; wxTreeItemId current; n = cbNormal->GetSelection(); n -= 1; current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Normal); } } /*! \brief Select the selected state image. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OncbSelectedSelect(wxCommandEvent &event) { int n; wxTreeItemId current; n = cbSelected->GetSelection(); n -= 1; current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Selected); } } /*! \brief Select the expanded state image. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OncbExpandedSelect(wxCommandEvent &event) { int n; wxTreeItemId current; n = cbExpanded->GetSelection(); n -= 1; current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemImage(current, n, wxTreeItemIcon_Expanded); } } /*! \brief Select the selected and expanded state image. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OncbSelExpandedSelect(wxCommandEvent &event) { int n; wxTreeItemId current; n = cbSelExpanded->GetSelection(); n -= 1; current = Tree1->GetSelection(); if(current.IsOk()){ Tree1->SetItemImage(current, n, wxTreeItemIcon_SelectedExpanded); } } /*! \brief The tree item selection was changed. * * \param event wxTreeEvent& * \return void * */ void wxsImageTreeEditorDlg::OnTreeCtrl1SelectionChanged(wxTreeEvent &event) { int n; wxTreeItemId current; wxColour cc; bool b; // get current item current = Tree1->GetSelection(); if(! current.IsOk()){ return; } // current text colour cc = Tree1->GetItemTextColour(current); bItemColor->SetForegroundColour(cc); // bold or plain b = Tree1->IsBold(current); cxItemBold->SetValue(b); // image indices n = Tree1->GetItemImage(current, wxTreeItemIcon_Normal); n += 1; cbNormal->SetSelection(n); n = Tree1->GetItemImage(current, wxTreeItemIcon_Selected); n += 1; cbSelected->SetSelection(n); n = Tree1->GetItemImage(current, wxTreeItemIcon_Expanded); n += 1; cbExpanded->SetSelection(n); n = Tree1->GetItemImage(current, wxTreeItemIcon_SelectedExpanded); n += 1; cbSelExpanded->SetSelection(n); } /*! \brief Parse tree item text. * * \param aSource wxString * \param outLevel int& * \param outColour wxColour& * \param outBold bool& * \param outImage1 int& * \param outImage2 int& * \param outImage3 int& * \param outImage4 int& * \param outText wxString& * \return void * */ void wxsImageTreeEditorDlg::ParseTreeItem(wxString aSource, int &outLevel, wxColour &outColour, bool &outBold, int &outImage1, int &outImage2, int &outImage3, int &outImage4, wxString &outText) { int i, n; long ll; wxString ss, tt; // working copy ss = aSource; // the depth level outLevel = 1; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)) outLevel = ll; } // the color outColour.Set(wxT("?")); i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); outColour.Set(tt); } // bold or normal text n = 0; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)){ n = ll; } } outBold = (n != 0); // 4 image indices outImage1 = -1; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)){ outImage1 = ll; } } outImage2 = -1; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)){ outImage2 = ll; } } outImage3 = -1; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)){ outImage3 = ll; } } outImage4 = -1; i = ss.Find(wxT(",")); if(i != wxNOT_FOUND){ tt = ss.Left(i); ss.erase(0, i + 1); if(tt.ToLong(&ll)){ outImage4 = ll; } } // everything else is the text ss.Trim(true); ss.Trim(false); outText = ss; } /*! \brief Encode tree item text. * * \param inParent wxTreeItemId * \param inLevel int * \param outList wxArrayString& * \return void * */ void wxsImageTreeEditorDlg::EncodeTreeItems(wxTreeItemId inParent, int inLevel, wxArrayString &outList) { int n; wxColour cc; wxString ss, tt; wxTreeItemId child; wxTreeItemIdValue cookie; // nothing yet ss = wxEmptyString; // start with this item tt.Printf(wxT("%d,"), inLevel); ss += tt; cc = Tree1->GetItemTextColour(inParent); tt = cc.GetAsString(wxC2S_HTML_SYNTAX); tt += wxT(","); ss += tt; if(Tree1->IsBold(inParent)){ tt = wxT("1,"); } else{ tt = wxT("0,"); } ss += tt; n = Tree1->GetItemImage(inParent, wxTreeItemIcon_Normal); tt.Printf(wxT("%d,"), n); ss += tt; n = Tree1->GetItemImage(inParent, wxTreeItemIcon_Selected); tt.Printf(wxT("%d,"), n); ss += tt; n = Tree1->GetItemImage(inParent, wxTreeItemIcon_Expanded); tt.Printf(wxT("%d,"), n); ss += tt; n = Tree1->GetItemImage(inParent, wxTreeItemIcon_SelectedExpanded); tt.Printf(wxT("%d,"), n); ss += tt; tt = Tree1->GetItemText(inParent); ss += tt; // save it outList.Add(ss); // and all the children child = Tree1->GetFirstChild(inParent, cookie); while(child.IsOk()){ EncodeTreeItems(child, inLevel + 1, outList); child = Tree1->GetNextChild(inParent, cookie); } } /*! \brief The OK button was clicked. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbOKClick(wxCommandEvent &event) { EndModal(wxOK); } /*! \brief The Cancel button was clicked. * * \param event wxCommandEvent& * \return void * */ void wxsImageTreeEditorDlg::OnbCancelClick(wxCommandEvent &event) { EndModal(wxCANCEL); }
SaturnSDK/Saturn-SDK-IDE
src/plugins/contrib/wxSmith/wxwidgets/properties/wxsimagetreeeditordlg.cpp
C++
gpl-3.0
34,340
import React, { Component } from 'react' import PropTypes from 'prop-types' import ModalsContainer from '../containers/ModalsContainer' import { bytesToSize } from '../common' const Store = window.require('electron-store') import './ViewSwitcher.css' class PersonalFiles extends Component { constructor(props) { super(props) this.onSearchInputChange = this.onSearchInputChange.bind(this) this.selectFile = this.selectFile.bind(this) this.isSelected = this.isSelected.bind(this) this.refresh = this.refresh.bind(this) this.handleCancelRestore = this.handleCancelRestore.bind(this) this.handleValidateRestore = this.handleValidateRestore.bind(this) this.store = new Store() this.state = { searchTerm: '', matchingFiles: [], target_directory: '/', refresh: 0, lock: false, } } componentDidMount() { this.props.dispatch.init() clearInterval(this.interval) this.interval = setInterval(this.refresh, 250) } componentWillUnmount() { this.props.dispatch.end() clearInterval(this.interval) } shouldComponentUpdate(nextProps, nextState) { if(nextProps.state.files !== this.props.state.files) this.setState(Object.assign(this.state, {lock: false})) if(nextProps.state.socket.loading && !this.props.state.socket.loading && nextProps.state.view.loading_animation) return true if(!nextState.lock && nextProps.state.view.loading_animation && !this.props.state.view.loading_animation) return true if(nextProps.state.breadcrumb[nextProps.state.breadcrumb.length - 1].route !== this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route) return true var newFiles = [] for (var i = nextProps.state.files.length - 1; i >= 0; i--) { newFiles.push([nextProps.state.files[i].path, nextProps.state.files[i].type]) } var oldFiles = [] for (i = this.props.state.files.length - 1; i >= 0; i--) { oldFiles.push([this.props.state.files[i].path, this.props.state.files[i].type]) } if(newFiles.length !== oldFiles.length || (newFiles.length > 1 && newFiles.every(function(item, i) {return item[0] !== oldFiles[i][0] || item[1] !== oldFiles[i][1]}))) return true var newSelectedFiles = [] for (i = nextProps.state.selection.selected.length - 1; i >= 0; i--) { newSelectedFiles.push([nextProps.state.selection.selected[i].path, nextProps.state.selection.selected[i].type]) } var oldSelectedFiles = [] for (i = this.props.state.selection.selected.length - 1; i >= 0; i--) { oldSelectedFiles.push([this.props.state.selection.selected[i].path, this.props.state.selection.selected[i].type]) } if(newSelectedFiles.length !== oldSelectedFiles.length || (newSelectedFiles.length > 1 && newSelectedFiles.every(function(item, i) {return item[0] !== oldSelectedFiles[i][0] || item[1] !== oldSelectedFiles[i][1]}))) return true return false } refresh() { var new_refresh_state = 0 if(this.state.refresh >= 12) new_refresh_state = 0 else new_refresh_state = this.state.refresh + 1 this.setState(Object.assign(this.state, {refresh: new_refresh_state})) if(this.state.target_directory === this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route && new_refresh_state !== 1) return var animate = false var target_directory = this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route if(this.state.target_directory !== target_directory) { target_directory = this.state.target_directory animate = true } if(!this.state.lock) { this.setState(Object.assign(this.state, {lock: true})) this.props.dispatch.listDir(target_directory, animate) } } onSearchInputChange(event, route) { var grep = function(what, where, callback) { console.log('onSearchInputChange') console.log(route) console.log(what) console.log(where) var exec = window.require('child_process').exec; where = where.replace(' ', '\\ ') console.log(where) exec('grep -l ' + what + ' ' + where + ' 2> /dev/null', function(err, stdin, stdout) { console.log('GREP') console.log(stdin) console.log(stdout) console.log(err) var results = stdin.split('\n') console.log('RES') console.log(results) console.log('RES2') results.pop() console.log(results) callback(results) }); } var target = event.target.value console.log('SEARCH IN') if (target.toLowerCase() === '') { console.log('EMPTY TARGET') this.setState({ matchingFiles: [], searchTerm: target.toLowerCase() }) } else { if (!route.endsWith('/')) route += '/' grep(target, route + '*.txt', function(list) { this.setState({ matchingFiles: list, searchTerm: target.toLowerCase() }) console.log('MATCHING') console.log(list) }.bind(this)) } } isSelected(file) { for(var i = 0; i < this.props.state.selection.selected.length; i++) { if(this.props.state.selection.selected[i].path === file.path) { // console.log(file.path + ' selected') return true } } return false } selectFile(event, file) { const selected = !this.isSelected(file) this.props.dispatch.selectFile(file, selected) } handleCancelRestore(event) { this.props.dispatch.restoring(false) } handleValidateRestore(event) { } render() { var files = this.props.state.files const selected = this.props.state.selection.selected const view = this.props.state.view const loading = this.props.state.socket.loading const loading_animation = this.props.state.view.loading_animation const breadcrumb = this.props.state.breadcrumb this.currentPath = breadcrumb[breadcrumb.length -1] const openFile = this.props.dispatch.openFile files.sort((a, b) => { if(a.type === 'folder' && b.type === 'file') return -1 else if (a.type === 'file' && b.type === 'folder') return 1 if (a.name > b.name) return 1 if (b.name > a.name) return -1 return 0 }) let displayedFiles = files.filter(file => { // console.log('filtre') // console.log(this.state.searchTerm) // console.log(this.state.matchingFiles) return this.state.searchTerm === '' || file.name.toLowerCase().includes(this.state.searchTerm) || this.state.matchingFiles.indexOf(file.mountpoint) !== -1 }) class IconFormatter extends React.Component { static propTypes = { file: PropTypes.object.isRequired } render() { const file = this.props.file var re = /(?:\.([^.]+))?$/ var type = re.exec(file['name'])[1] const icons = { folder: 'fa-folder-o', file: 'fa-file-o', zip: 'fa-file-archive-o', mp3: 'fa-file-audio-o', py: 'fa-file-code-o', xls: 'fa-file-excel-o', jpg: 'fa-file-image-o', pdf: 'fa-file-pdf-o', txt: 'fa-file-text-o', avi: 'fa-file-video-o', doc: 'fa-file-word-o' } if (type === undefined || !(type in icons) || file['type'] === 'folder') type = file['type'] return ( <div className='icon'> <i className={'fa ' + icons[type]}/> </div> ) } } const ListFiles = () => { if(loading && loading_animation) return (<div id="loader-wrapper"><div id="loader"></div></div>) if(files.length === 0) return ( <div className="empty-list"> <i className="fa fa-folder-open-o"/> <h1>This folder is empty</h1> </div> ) const listFiles = displayedFiles.map((file) => { const details = file.type === 'file' ? bytesToSize(file['size']) : file.children.length + ' element' + (file.children.length > 1 ? 's' : '') const hidden = (selected.length === 0) ? 'hidden' : '' var selected_file = this.isSelected(file) return ( <a key={file.path} onClick={(event) => { if(selected.length === 0) { if(file.type === 'folder') { this.setState(Object.assign(this.state, {target_directory: file.path})) } else { openFile(file) } } else { this.selectFile(event, file) } }}> <li className="file-item" id={file.path}> <input className={hidden} id={'select_' + file.path} name={file.path} type="checkbox" title={selected_file ? 'Deselect' : 'Select'} onClick={(event) => {this.selectFile(event, file); event.stopPropagation()}} checked={selected_file} readOnly/> <IconFormatter file={file}/> <div className="title">{file.name}</div> <div className="details">{details}</div> </li> </a> ) }) return ( <div className={view.list ? 'file-view list-view' : 'file-view grid-view'}> <ul>{ listFiles }</ul> </div> ) } return ( <div className="view-switcher"> <div className="header"> <div className="title"> Personal Files </div> <div className="search"> <span className="fa fa-search"></span> <input onKeyUp={(event) => this.onSearchInputChange(event, this.store.get('mountpoint', '') + this.currentPath.route)} placeholder="Search"/> </div> <div className="breadcrumb"> <ul> <li> <div className="dropdown-content"> {breadcrumb.map((path, i) => <button key={path.route} onClick={() => {this.setState(Object.assign(this.state, {target_directory: path.route}))}} className={`button path-button ${i === 0 ? 'first-path-button' : ''} ${(i + 1) === breadcrumb.length ? 'last-path-button' : ''}`}>{(i + 1) === breadcrumb.length ? <i className="fa fa-folder-open"/> : ''} {path.libelle}</button> )} </div> </li> </ul> </div> <div className="clear"></div> </div> { ListFiles() } <ModalsContainer></ModalsContainer> </div> ) } } export default PersonalFiles
Scille/parsec-gui
src/components/PersonalFiles.js
JavaScript
gpl-3.0
10,526
package com.bukkit.gemo.FalseBook.Cart.utils; import net.minecraft.server.v1_6_R3.Container; import net.minecraft.server.v1_6_R3.EntityHuman; import net.minecraft.server.v1_6_R3.InventoryCrafting; import net.minecraft.server.v1_6_R3.ItemStack; public class FBInventory extends InventoryCrafting { private ItemStack[] items = new ItemStack[9]; public FBInventory(Container container, int i, int j) { super(container, i, j); } public FBInventory() { super((Container)null, 3, 3); } public ItemStack[] getContents() { return this.items; } public int getSize() { return 1; } public ItemStack getItem(int i) { return this.items[i]; } public String getName() { return "Result"; } public ItemStack splitStack(int i, int j) { if(this.items[i] != null) { ItemStack itemstack = this.items[i]; this.items[i] = null; return itemstack; } else { return null; } } public void setItem(int i, ItemStack itemstack) { this.items[i] = itemstack; } public int getMaxStackSize() { return 64; } public void update() {} public boolean a(EntityHuman entityhuman) { return true; } public void f() {} public void g() {} }
Escapecraft/FalseBook
src/main/java/com/bukkit/gemo/FalseBook/Cart/utils/FBInventory.java
Java
gpl-3.0
1,292
package com.github.bordertech.wcomponents; import com.github.bordertech.wcomponents.util.Util; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * WVideo is used to display video content on the client. * * @author Yiannis Paschalidis * @since 1.0.0 */ public class WVideo extends AbstractWComponent implements Targetable, AjaxTarget, Disableable { /** * The logger instance for this class. */ private static final Log LOG = LogFactory.getLog(WVideo.class); /** * This request parameter is used to determine which video clip to serve up. */ private static final String VIDEO_INDEX_REQUEST_PARAM_KEY = "WVideo.videoIndex"; /** * This request parameter is used to determine which track to serve up. */ private static final String TRACK_INDEX_REQUEST_PARAM_KEY = "WVideo.trackIndex"; /** * This request parameter is used to request the poster image. */ private static final String POSTER_REQUEST_PARAM_KEY = "WVideo.poster"; /** * This is used to indicate whether pre-loading of content should occur before the clip is played. */ public enum Preload { /** * Do not pre-load any data. */ NONE, /** * Preload meta-data only. */ META_DATA, /** * Let the client determine what to load. */ AUTO } /** * This is used to indicate which playback controls to display for the video. * * <p> * <strong>Note:</strong> * Advancements in video support in clients since this API was first implemented means that most of this is now * redundant. Under most circumstances the UI will display their native video controls. Where a particular WVideo * does not have any source which is able to be played by the client then links to all sources will be provided. * This enum is not worthless as the values NONE and PLAY_PAUSE are used to turn off native video controls in the * client. The value NONE however causes major problems and is incompatible with autoplay for a11y reasons so it * basically makes the media worthless. This enum may be replaced in the future with a simple boolean to trigger * native controls or play/pause only (see https://github.com/BorderTech/wcomponents/issues/503). * </p> */ public enum Controls { /** * Do not display any controls: not recommended. May be incompatible with any of {@link #isAutoplay()} == true, * {@link #isMuted()} == true or {@link #isLoop()} == true. If this value is set then the WVideo control * <strong>MAY NOT WORK AT ALL</strong>. * @deprecated since 1.1.1 as this is incompatible with WCAG requirements. */ NONE, /** * Display all controls. * @deprecated since 1.1.1 as themes use native video controls. */ ALL, /** * A combined play/pause button. */ PLAY_PAUSE, /** * Displays the "default" set of controls for the theme. * @deprecated since 1.1.1 as themes use native video controls. */ DEFAULT, /** * Displays the client's native set of controls. */ NATIVE } /** * Creates a WVideo with no video clips. Video clips must be added later by calling one of the setVideo(...) * methods. */ public WVideo() { } /** * Creates a WVideo with the given video clip. * * @param video the video clip. */ public WVideo(final Video video) { this(new Video[]{video}); } /** * <p> * Creates a WVideo with the given static content. This is provided as a convenience method for when the video file * is included as static content in the class path rather than in the web application's resources. * </p> * <p> * The mime type for the video clip is looked up from the "mimeType.*" mapping configuration parameters using the * resource's file extension. * </p> * * @param resource the resource path to the video file. */ public WVideo(final String resource) { this(new VideoResource(resource)); } /** * Creates a WVideo with the given video clip in multiple formats. The client will try to load the first video clip, * and if it fails or isn't supported, it will move on to the next video clip. Only the first clip which can be * played on the client will be used. * * @param video multiple formats for the same the video clip. */ public WVideo(final Video[] video) { setVideo(video); } /** * Sets the video clip. * * @param video the video clip. */ public void setVideo(final Video video) { setVideo(new Video[]{video}); } /** * Sets the video clip in multiple formats. The client will try to load the first video clip, and if it fails or * isn't supported, it will move on to the next video clip. Only the first clip which can be played on the client * will be used. * * @param video multiple formats for the same the video clip. */ public void setVideo(final Video[] video) { List<Video> list = video == null ? null : Arrays.asList(video); getOrCreateComponentModel().video = list; } /** * Retrieves the video clips associated with this WVideo. * * @return the video clips, may be null. */ public Video[] getVideo() { List<Video> list = getComponentModel().video; return list == null ? null : list.toArray(new Video[]{}); } /** * Indicates whether the video component is disabled. * * @return true if the component is disabled, otherwise false. */ @Override public boolean isDisabled() { return isFlagSet(ComponentModel.DISABLED_FLAG); } /** * Sets whether the video component is disabled. * * @param disabled if true, the component is disabled. If false, it is enabled. */ @Override public void setDisabled(final boolean disabled) { setFlag(ComponentModel.DISABLED_FLAG, disabled); } /** * @return true if the clip should start playing automatically, false for a manual start. */ public boolean isAutoplay() { return getComponentModel().autoplay; } /** * Sets whether the clip should play automatically. * * @param autoplay true to start playing automatically, false for a manual start. */ public void setAutoplay(final boolean autoplay) { getOrCreateComponentModel().autoplay = autoplay; } /** * @return the media group name. */ public String getMediaGroup() { return getComponentModel().mediaGroup; } /** * Sets the media group. * * @param mediaGroup The media group name. */ public void setMediaGroup(final String mediaGroup) { getOrCreateComponentModel().mediaGroup = mediaGroup; } /** * Indicates whether the video clip playback should loop. * * @return true to loop, false to stop at the end. */ public boolean isLoop() { return getComponentModel().loop; } /** * Sets whether the video clip playback should loop or stop at the end. * * @param loop true to loop, false to stop at the end. */ public void setLoop(final boolean loop) { getOrCreateComponentModel().loop = loop; } /** * Indicates whether the video's audio should initially be muted. * * @return true if muted, false otherwise. */ public boolean isMuted() { return getComponentModel().muted; } /** * Sets whether the video's audio should initially be muted. * * @param muted true to mute the audio, false to play normally. */ public void setMuted(final boolean muted) { getOrCreateComponentModel().muted = muted; } /** * Indicates which playback controls (e.g. stop/start/pause) to display on the video component. * * @return the playback controls to display. */ public Controls getControls() { return getComponentModel().controls; } /** * Sets which playback controls (e.g. stop/start/pause) to display on the video component. The values of * {@link Controls#NONE} and {@link Controls#ALL} take precedence over all other values. Passing a null or empty set * of controls will cause the client's default set of controls to be used. * * @param controls the playback controls to display. */ public void setControls(final Controls controls) { getOrCreateComponentModel().controls = controls; } /** * Indicates how pre-loading of content should occur before the clip is played. * * @return the pre-loading mode. */ public Preload getPreload() { return getComponentModel().preload; } /** * Sets how pre-loading of content should occur before the clip is played. * * @param preload the pre-loading mode. */ public void setPreload(final Preload preload) { getOrCreateComponentModel().preload = preload; } /** * @return alternative text to display when the video clip can not be played. */ public String getAltText() { return getComponentModel().altText; } /** * Sets the alternative text to display when the video clip can not be played. * * @param altText the text to set. */ public void setAltText(final String altText) { getOrCreateComponentModel().altText = altText; } /** * @return the width of the video playback region on the client, in pixels. */ public int getWidth() { return getComponentModel().width; } /** * Sets the width of the video playback region on the client. * * @param width the width of the video playback region, in pixels. */ public void setWidth(final int width) { getOrCreateComponentModel().width = width; } /** * @return the height of the video playback region on the client, in pixels. */ public int getHeight() { return getComponentModel().height; } /** * Sets the height of the video playback region on the client. * * @param height the height of the video playback region, in pixels. */ public void setHeight(final int height) { getOrCreateComponentModel().height = height; } /** * Retrieves the default poster image. The poster image is displayed by the client when the video is not playing. * * @return the default poster image. */ public Image getPoster() { return getComponentModel().poster; } /** * Sets the default poster image. The poster image is displayed by the client when the video is not playing. * * @param poster the default poster image. */ public void setPoster(final Image poster) { getOrCreateComponentModel().poster = poster; } /** * Sets the tracks for the video. The tracks are used to provide additional information relating to the video, for * example subtitles. * * @param tracks additional tracks relating to the video. */ public void setTracks(final Track[] tracks) { List<Track> list = tracks == null ? null : Arrays.asList(tracks); getOrCreateComponentModel().tracks = list; } /** * Retrieves additional tracks associated with the video. The tracks provide additional information relating to the * video, for example subtitles. * * @return the video clips, may be null. */ public Track[] getTracks() { List<Track> list = getComponentModel().tracks; return list == null ? null : list.toArray(new Track[]{}); } /** * Creates dynamic URLs that the video clips can be loaded from. In fact the URL points to the main application * servlet, but includes a non-null for the parameter associated with this WComponent (ie, its label). The * handleRequest method below detects this when the browser requests a file. * * @return the urls to load the video files from, or null if there are no clips defined. */ public String[] getVideoUrls() { Video[] video = getVideo(); if (video == null || video.length == 0) { return null; } String[] urls = new String[video.length]; // this variable needs to be set in the portlet environment. String url = getEnvironment().getWServletPath(); Map<String, String> parameters = getBaseParameterMap(); for (int i = 0; i < urls.length; i++) { parameters.put(VIDEO_INDEX_REQUEST_PARAM_KEY, String.valueOf(i)); urls[i] = WebUtilities.getPath(url, parameters, true); } return urls; } /** * Creates dynamic URLs that the video clips can be loaded from. In fact the URL points to the main application * servlet, but includes a non-null for the parameter associated with this WComponent (ie, its label). The * handleRequest method below detects this when the browser requests a file. * * @return the urls to load the video files from, or null if there are no clips defined. */ public String[] getTrackUrls() { Track[] tracks = getTracks(); if (tracks == null || tracks.length == 0) { return null; } String[] urls = new String[tracks.length]; // this variable needs to be set in the portlet environment. String url = getEnvironment().getWServletPath(); Map<String, String> parameters = getBaseParameterMap(); for (int i = 0; i < urls.length; i++) { parameters.put(TRACK_INDEX_REQUEST_PARAM_KEY, String.valueOf(i)); urls[i] = WebUtilities.getPath(url, parameters, true); } return urls; } /** * Creates a dynamic URL that the poster can be loaded from. In fact the URL points to the main application servlet, * but includes a non-null for the parameter associated with this WComponent (ie, its label). The handleRequest * method below detects this when the browser requests a file. * * @return the url to load the poster from, or null if there is no poster defined. */ public String getPosterUrl() { Image poster = getComponentModel().poster; if (poster == null) { return null; } // this variable needs to be set in the portlet environment. String url = getEnvironment().getWServletPath(); Map<String, String> parameters = getBaseParameterMap(); parameters.put(POSTER_REQUEST_PARAM_KEY, "x"); return WebUtilities.getPath(url, parameters, true); } /** * Retrieves the base parameter map for serving content (videos + tracks). * * @return the base map for serving content. */ private Map<String, String> getBaseParameterMap() { Environment env = getEnvironment(); Map<String, String> parameters = env.getHiddenParameters(); parameters.put(Environment.TARGET_ID, getTargetId()); if (Util.empty(getCacheKey())) { // Add some randomness to the URL to prevent caching String random = WebUtilities.generateRandom(); parameters.put(Environment.UNIQUE_RANDOM_PARAM, random); } else { // Remove step counter as not required for cached content parameters.remove(Environment.STEP_VARIABLE); parameters.remove(Environment.SESSION_TOKEN_VARIABLE); // Add the cache key parameters.put(Environment.CONTENT_CACHE_KEY, getCacheKey()); } return parameters; } /** * Override isVisible to also return false if there are no video clips to play. * * @return true if this component is visible in the given context, otherwise false. */ @Override public boolean isVisible() { if (!super.isVisible()) { return false; } Video[] video = getVideo(); return video != null && video.length > 0; } /** * When an video element is rendered to the client, the browser will make a second request to get the video content. * The handleRequest method has been overridden to detect whether the request is the "content fetch" request by * looking for the parameter that we encode in the content url. * * @param request the request being responded to. */ @Override public void handleRequest(final Request request) { super.handleRequest(request); String targ = request.getParameter(Environment.TARGET_ID); boolean contentReqested = (targ != null && targ.equals(getTargetId())); if (contentReqested && request.getParameter(POSTER_REQUEST_PARAM_KEY) != null) { handlePosterRequest(); } if (isDisabled()) { return; } if (contentReqested) { if (request.getParameter(VIDEO_INDEX_REQUEST_PARAM_KEY) != null) { handleVideoRequest(request); } else if (request.getParameter(TRACK_INDEX_REQUEST_PARAM_KEY) != null) { handleTrackRequest(request); } } } /** * Handles a request for the poster. */ private void handlePosterRequest() { Image poster = getComponentModel().poster; if (poster != null) { ContentEscape escape = new ContentEscape(poster); escape.setCacheable(!Util.empty(getCacheKey())); throw escape; } else { LOG.warn("Client requested non-existant poster"); } } /** * Handles a request for a video. * * @param request the request being responded to. */ private void handleVideoRequest(final Request request) { String videoRequested = request.getParameter(VIDEO_INDEX_REQUEST_PARAM_KEY); int videoFileIndex = 0; try { videoFileIndex = Integer.parseInt(videoRequested); } catch (NumberFormatException e) { LOG.error("Failed to parse video index: " + videoFileIndex); } Video[] video = getVideo(); if (video != null && videoFileIndex >= 0 && videoFileIndex < video.length) { ContentEscape escape = new ContentEscape(video[videoFileIndex]); escape.setCacheable(!Util.empty(getCacheKey())); throw escape; } else { LOG.warn("Client requested invalid video clip: " + videoFileIndex); } } /** * Handles a request for an auxillary track. * * @param request the request being responded to. */ private void handleTrackRequest(final Request request) { String trackRequested = request.getParameter(TRACK_INDEX_REQUEST_PARAM_KEY); int trackIndex = 0; try { trackIndex = Integer.parseInt(trackRequested); } catch (NumberFormatException e) { LOG.error("Failed to parse track index: " + trackIndex); } Track[] tracks = getTracks(); if (tracks != null && trackIndex >= 0 && trackIndex < tracks.length) { ContentEscape escape = new ContentEscape(tracks[trackIndex]); escape.setCacheable(!Util.empty(getCacheKey())); throw escape; } else { LOG.warn("Client requested invalid track: " + trackIndex); } } /** * @return the cacheKey */ public String getCacheKey() { return getComponentModel().cacheKey; } /** * @param cacheKey the cacheKey to set. */ public void setCacheKey(final String cacheKey) { getOrCreateComponentModel().cacheKey = cacheKey; } /** * Returns the id to use to target this component. * * @return this component's target id. */ @Override public String getTargetId() { return getId(); } /** * @return a String representation of this component, for debugging purposes. */ @Override public String toString() { String text = getAltText(); return toString(text == null ? null : ('"' + text + '"')); } // -------------------------------- // Extrinsic state management /** * Creates a new component model appropriate for this component. * * @return a new VideoModel. */ @Override protected VideoModel newComponentModel() { return new VideoModel(); } /** * {@inheritDoc} */ @Override // For type safety only protected VideoModel getComponentModel() { return (VideoModel) super.getComponentModel(); } /** * {@inheritDoc} */ @Override // For type safety only protected VideoModel getOrCreateComponentModel() { return (VideoModel) super.getOrCreateComponentModel(); } /** * Holds the extrinsic state information of a WVideo. */ public static class VideoModel extends ComponentModel { /** * The various video clips. */ private List<Video> video; /** * Additional tracks relating to the video, e.g. subtitles. */ private List<Track> tracks; /** * The cache key used to control client-side caching. */ private String cacheKey; /** * Indicates whether the video should play immediately after page load. */ private boolean autoplay; /** * Indicates whether playback of the video clip should be looped. */ private boolean loop; /** * Indicates whether audio should initially be muted. */ private boolean muted; /** * Indicates which playback controls to display. */ private Controls controls; /** * Indicates whether pre-loading of content should occur before the clip is played. */ private Preload preload = Preload.NONE; /** * Alternate text to display if the video clip can not be played. */ private String altText; /** * The width of the video playback region on the client, in pixels. */ private int width; /** * The height of the video playback region on the client, in pixels. */ private int height; /** * The poster image is displayed in place of the video, until it is loaded. */ private Image poster; /** * This is used to group related media together, for example to synchronize tracks. */ private String mediaGroup; } }
Joshua-Barclay/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WVideo.java
Java
gpl-3.0
21,133
import numpy as np import matplotlib.pyplot as plt import spm1d #(0) Load dataset: dataset = spm1d.data.mv1d.cca.Dorn2012() y,x = dataset.get_data() #A:slow, B:fast #(1) Conduct non-parametric test: np.random.seed(0) alpha = 0.05 two_tailed = False snpm = spm1d.stats.nonparam.cca(y, x) snpmi = snpm.inference(alpha, iterations=100) print( snpmi ) #(2) Compare with parametric result: spm = spm1d.stats.cca(y, x) spmi = spm.inference(alpha) print( spmi ) #(3) Plot plt.close('all') plt.figure(figsize=(10,4)) ax0 = plt.subplot(121) ax1 = plt.subplot(122) labels = 'Parametric', 'Non-parametric' for ax,zi,label in zip([ax0,ax1], [spmi,snpmi], labels): zi.plot(ax=ax) zi.plot_threshold_label(ax=ax, fontsize=8) zi.plot_p_values(ax=ax, size=10) ax.set_title( label ) plt.tight_layout() plt.show()
0todd0000/spm1d
spm1d/examples/nonparam/1d/ex_cca.py
Python
gpl-3.0
860
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Question.order' db.add_column(u'survey_question', 'order', self.gf('django.db.models.fields.IntegerField')(default=0), keep_default=False) def backwards(self, orm): # Deleting field 'Question.order' db.delete_column(u'survey_question', 'order') models = { u'survey.option': { 'Meta': {'object_name': 'Option'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'label': ('django.db.models.fields.SlugField', [], {'max_length': '64'}), 'text': ('django.db.models.fields.CharField', [], {'max_length': '254'}) }, u'survey.page': { 'Meta': {'ordering': "['order']", 'unique_together': "(('survey', 'order'),)", 'object_name': 'Page'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Question']"}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Survey']"}) }, u'survey.question': { 'Meta': {'object_name': 'Question'}, 'allow_other': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'info': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'label': ('django.db.models.fields.CharField', [], {'max_length': '254'}), 'modalQuestion': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Question']", 'null': 'True', 'blank': 'True'}), 'options': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['survey.Option']", 'null': 'True', 'blank': 'True'}), 'options_from_previous_answer': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'options_json': ('django.db.models.fields.CharField', [], {'max_length': '254', 'null': 'True', 'blank': 'True'}), 'order': ('django.db.models.fields.IntegerField', [], {}), 'randomize_groups': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '64'}), 'title': ('django.db.models.fields.TextField', [], {}), 'type': ('django.db.models.fields.CharField', [], {'default': "'text'", 'max_length': '20'}) }, u'survey.respondant': { 'Meta': {'object_name': 'Respondant'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '254'}), 'responses': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'responses'", 'symmetrical': 'False', 'to': u"orm['survey.Response']"}), 'survey': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Survey']"}), 'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 30, 0, 0)'}), 'uuid': ('django.db.models.fields.CharField', [], {'default': "'bc967489-023c-46ce-b396-d209c8323fac'", 'max_length': '36', 'primary_key': 'True'}) }, u'survey.response': { 'Meta': {'object_name': 'Response'}, 'answer': ('django.db.models.fields.TextField', [], {}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'question': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Question']"}), 'respondant': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['survey.Respondant']"}), 'ts': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 30, 0, 0)'}) }, u'survey.survey': { 'Meta': {'object_name': 'Survey'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '254'}), 'questions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u"orm['survey.Question']", 'null': 'True', 'through': u"orm['survey.Page']", 'blank': 'True'}), 'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '254'}) } } complete_apps = ['survey']
point97/hapifis
server/apps/survey/migrations/0020_auto__add_field_question_order.py
Python
gpl-3.0
4,857
package me.ccrama.redditslide.Activities; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import java.net.MalformedURLException; import java.net.URL; import me.ccrama.redditslide.SettingValues; /** * Created by ccrama on 9/28/2015. */ public class MakeExternal extends Activity { @Override public void onCreate(Bundle savedInstance) { super.onCreate(savedInstance); String url = getIntent().getStringExtra("url"); if (url != null) { try { URL u = new URL(url); SettingValues.alwaysExternal.add(u.getHost()); SharedPreferences.Editor e = SettingValues.prefs.edit(); e.putStringSet(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal); e.apply(); } catch (MalformedURLException e) { e.printStackTrace(); } } finish(); } }
ccrama/Slide
app/src/main/java/me/ccrama/redditslide/Activities/MakeExternal.java
Java
gpl-3.0
972
#include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define pip pair<int,pii> #define ff first #define ss second #define FOR(i,n) for(int i=0; i<(int)n ;i++) #define REP(i,a,n) for(int i=a;i<(int)n;i++) #define pb push_back #define mp make_pair typedef long long ll; //int dx[]= {-1,0,1,0}; //int dy[]= {0,1,0,-1}; struct node { int val; int sq; ll sum; ll sq_sum; }; node st[4*100000]; int arr[100000+10]; void build_tree(int id,int l,int r) { if(l==r) { st[id].val=st[id].sum=arr[l]; st[id].sq=st[id].sq_sum=arr[l]*arr[l]; } else if(l<r) { int mid=(l+r)/2; build_tree(2*id,l,mid); build_tree(2*id+1,mid+1,r); st[id].sum=st[2*id].sum+st[2*id+1].sum; st[id].sq_sum=st[2*id].sq_sum+st[2*id+1].sq_sum; } } ll query(int id,int l,int r,int x,int y) { if(r<x || y<l) return 0; if(l>=x && r<=y) return st[id].sq_sum; int mid=(l+r)/2; return query(2*id,l,mid,x,y)+query(2*id+1,mid+1,r,x,y); } void update0(int id,int l,int r,int x,int y,int value) { if(r<x || y<l) return; if(l==r && l>=x && l<=y) { st[id].val=st[id].sum=value; st[id].sq=st[id].sq_sum=value*value; return; } int mid=(l+r)/2; update0(2*id ,l,mid,x,y,value); update0(2*id+1,1+mid,r,x,y,value); st[id].sum=st[2*id].sum+st[2*id+1].sum; st[id].sq_sum=st[2*id].sq_sum+st[2*id+1].sq_sum; } void update1(int id,int l,int r,int x,int y,int value) { if(r<x || y<l) return; if(l==r && l>=x && l<=y) { st[id].val+=value; st[id].sum=st[id].val; st[id].sq=st[id].val*st[id].val; st[id].sq_sum=st[id].sq; return; } int mid=(l+r)/2; update1(2*id ,l,mid,x,y,value); update1(2*id+1,1+mid,r,x,y,value); st[id].sum=st[2*id].sum+st[2*id+1].sum; st[id].sq_sum=st[2*id].sq_sum+st[2*id+1].sq_sum; } int main() { int t; scanf("%d",&t); for(int c=1;c<=t;c++) { int n,q; scanf("%d%d",&n,&q); memset(arr,0,n+1); for(int i=0;i<n;i++) scanf("%d",&arr[i]); build_tree(1,0,n-1); cout<<"Case "<<c<<":\n"; while(q--) { int type; scanf("%d",&type); if(type==0)// set all numbers to val { int x,y,val; scanf("%d%d%d",&x,&y,&val); x--;y--; update0(1,0,n-1,x,y,val); } else if(type==1) { int x,y,val; scanf("%d%d%d",&x,&y,&val); x--;y--; update1(1,0,n-1,x,y,val); } else if(type==2)//sum of squares { int x,y; scanf("%d%d",&x,&y); x--;y--; printf("%lld\n",query(1,0,n-1,x,y)); } } } return 0; }
ProgDan/maratona
SPOJ/SEGSQRSS.cpp
C++
gpl-3.0
3,479
// A shortcut header to get all widgets #include "guiengine/widgets/bubble_widget.hpp" #include "guiengine/widgets/button_widget.hpp" #include "guiengine/widgets/icon_button_widget.hpp" #include "guiengine/widgets/list_widget.hpp" #include "guiengine/widgets/dynamic_ribbon_widget.hpp" #include "guiengine/widgets/spinner_widget.hpp" #include "guiengine/widgets/progress_bar_widget.hpp" #include "guiengine/widgets/ribbon_widget.hpp" #include "guiengine/widgets/model_view_widget.hpp" #include "guiengine/widgets/text_box_widget.hpp" #include "guiengine/widgets/label_widget.hpp" #include "guiengine/widgets/check_box_widget.hpp"
langresser/stk
src/guiengine/widgets.hpp
C++
gpl-3.0
632
/* * Copyright 2013-2014 Giulio Camuffo <giuliocamuffo@gmail.com> * * This file is part of Orbital * * Orbital 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 3 of the License, or * (at your option) any later version. * * Orbital 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 Orbital. If not, see <http://www.gnu.org/licenses/>. */ #include <QDebug> #include <pulse/glib-mainloop.h> #include <pulse/volume.h> #include "pulseaudiomixer.h" #include "client.h" struct Sink { Sink() : index(0), volume{}, muted(false) {} uint32_t index; pa_cvolume volume; bool muted; }; PulseAudioMixer::PulseAudioMixer(Mixer *m) : Backend() , m_mixer(m) , m_sink(new Sink) { } PulseAudioMixer::~PulseAudioMixer() { delete m_sink; cleanup(); } PulseAudioMixer *PulseAudioMixer::create(Mixer *mixer) { PulseAudioMixer *pulse = new PulseAudioMixer(mixer); if (!(pulse->m_mainLoop = pa_glib_mainloop_new(nullptr))) { qWarning("pa_mainloop_new() failed."); delete pulse; return nullptr; } pulse->m_mainloopApi = pa_glib_mainloop_get_api(pulse->m_mainLoop); // pluseaudio tries to connect to X if DISPLAY is set. the problem is that if we have // xwayland running it will try to connect to it, and we don't want that. char *dpy = getenv("DISPLAY"); if (dpy) { setenv("DISPLAY", "", 1); } pulse->m_context = pa_context_new(pulse->m_mainloopApi, nullptr); if (dpy) { setenv("DISPLAY", dpy, 1); } if (!pulse->m_context) { qWarning("pa_context_new() failed."); delete pulse; return nullptr; } pa_context_set_state_callback(pulse->m_context, [](pa_context *c, void *ud) { static_cast<PulseAudioMixer *>(ud)->contextStateCallback(c); }, pulse); if (pa_context_connect(pulse->m_context, nullptr, (pa_context_flags_t)0, nullptr) < 0) { qWarning("pa_context_connect() failed: %s", pa_strerror(pa_context_errno(pulse->m_context))); delete pulse; return nullptr; } return pulse; } void PulseAudioMixer::contextStateCallback(pa_context *c) { switch (pa_context_get_state(c)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: pa_context_set_subscribe_callback(c, [](pa_context *c, pa_subscription_event_type_t t, uint32_t index, void *ud) { static_cast<PulseAudioMixer *>(ud)->subscribeCallback(c, t, index); }, this); pa_context_subscribe(c, PA_SUBSCRIPTION_MASK_SINK, nullptr, nullptr); pa_context_get_sink_info_list(c, [](pa_context *c, const pa_sink_info *i, int eol, void *ud) { static_cast<PulseAudioMixer *>(ud)->sinkCallback(c, i, eol); }, this); break; case PA_CONTEXT_TERMINATED: cleanup(); break; case PA_CONTEXT_FAILED: default: qWarning("Connection with the pulseaudio server failed: %s", pa_strerror(pa_context_errno(c))); cleanup(); break; } } void PulseAudioMixer::subscribeCallback(pa_context *c, pa_subscription_event_type_t t, uint32_t index) { switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) { case PA_SUBSCRIPTION_EVENT_SINK: pa_context_get_sink_info_list(c, [](pa_context *c, const pa_sink_info *i, int eol, void *ud) { static_cast<PulseAudioMixer *>(ud)->sinkCallback(c, i, eol); }, this); break; default: break; } } void PulseAudioMixer::sinkCallback(pa_context *c, const pa_sink_info *i, int eol) { if (eol < 0) { if (pa_context_errno(c) == PA_ERR_NOENTITY) return; qWarning() << "Sink callback failure"; return; } if (eol > 0) { return; } m_sink->index = i->index; if (m_sink->muted != (bool)i->mute) { m_sink->muted = (bool)i->mute; emit m_mixer->mutedChanged(); } m_sink->volume = i->volume; emit m_mixer->masterChanged(); } void PulseAudioMixer::cleanup() { } void PulseAudioMixer::getBoundaries(int *min, int *max) const { *min = PA_VOLUME_MUTED; *max = PA_VOLUME_NORM; } void PulseAudioMixer::setRawVol(int vol) { if (!pa_channels_valid(m_sink->volume.channels)) { qWarning("Cannot change Pulseaudio volume: invalid channels %d", m_sink->volume.channels); return; } setMuted(false); pa_cvolume_set(&m_sink->volume, m_sink->volume.channels, vol); pa_context_set_sink_volume_by_index(m_context, m_sink->index, &m_sink->volume, nullptr, nullptr); } int PulseAudioMixer::rawVol() const { return pa_cvolume_avg(&m_sink->volume); } bool PulseAudioMixer::muted() const { return m_sink->muted; } void PulseAudioMixer::setMuted(bool muted) { pa_context_set_sink_mute_by_index(m_context, m_sink->index, muted, nullptr, nullptr); }
giucam/orbital
src/client/services/mixer/pulseaudiomixer.cpp
C++
gpl-3.0
5,443
#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: Clock offset corrector # Author: Piotr Krysik # Generated: Wed Nov 19 08:38:40 2014 ################################################## from gnuradio import blocks from gnuradio import filter from gnuradio import gr from gnuradio.filter import firdes import grgsm import math class clock_offset_corrector(gr.hier_block2): def __init__(self, fc=936.6e6, ppm=0, samp_rate_in=1625000.0/6.0*4.0): gr.hier_block2.__init__( self, "Clock offset corrector", gr.io_signature(1, 1, gr.sizeof_gr_complex*1), gr.io_signature(1, 1, gr.sizeof_gr_complex*1), ) ################################################## # Parameters ################################################## self.fc = fc self.ppm = ppm self.samp_rate_in = samp_rate_in ################################################## # Variables ################################################## self.samp_rate_out = samp_rate_out = samp_rate_in ################################################## # Blocks ################################################## self.ppm_in = None;self.message_port_register_hier_out("ppm_in") self.gsm_controlled_rotator_cc_0 = grgsm.controlled_rotator_cc(0,samp_rate_out) self.gsm_controlled_const_source_f_0 = grgsm.controlled_const_source_f(ppm) self.fractional_resampler_xx_0 = filter.fractional_resampler_cc(0, samp_rate_in/samp_rate_out) self.blocks_multiply_const_vxx_0_0 = blocks.multiply_const_vff((1.0e-6*samp_rate_in/samp_rate_out, )) self.blocks_multiply_const_vxx_0 = blocks.multiply_const_vff((fc/samp_rate_out*(2*math.pi)/1e6, )) self.blocks_add_const_vxx_0 = blocks.add_const_vff((samp_rate_in/samp_rate_out, )) ################################################## # Connections ################################################## self.connect((self, 0), (self.fractional_resampler_xx_0, 0)) self.connect((self.fractional_resampler_xx_0, 0), (self.gsm_controlled_rotator_cc_0, 0)) self.connect((self.blocks_add_const_vxx_0, 0), (self.fractional_resampler_xx_0, 1)) self.connect((self.blocks_multiply_const_vxx_0_0, 0), (self.blocks_add_const_vxx_0, 0)) self.connect((self.blocks_multiply_const_vxx_0, 0), (self.gsm_controlled_rotator_cc_0, 1)) self.connect((self.gsm_controlled_rotator_cc_0, 0), (self, 0)) self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0_0, 0)) self.connect((self.gsm_controlled_const_source_f_0, 0), (self.blocks_multiply_const_vxx_0, 0)) ################################################## # Asynch Message Connections ################################################## self.msg_connect(self, "ppm_in", self.gsm_controlled_const_source_f_0, "constant_msg") def get_fc(self): return self.fc def set_fc(self, fc): self.fc = fc self.blocks_multiply_const_vxx_0.set_k((self.fc/self.samp_rate_out*(2*math.pi)/1e6, )) def get_ppm(self): return self.ppm def set_ppm(self, ppm): self.ppm = ppm self.gsm_controlled_const_source_f_0.set_constant(self.ppm) def get_samp_rate_in(self): return self.samp_rate_in def set_samp_rate_in(self, samp_rate_in): self.samp_rate_in = samp_rate_in self.set_samp_rate_out(self.samp_rate_in) self.fractional_resampler_xx_0.set_resamp_ratio(self.samp_rate_in/self.samp_rate_out) self.blocks_multiply_const_vxx_0_0.set_k((1.0e-6*self.samp_rate_in/self.samp_rate_out, )) self.blocks_add_const_vxx_0.set_k((self.samp_rate_in/self.samp_rate_out, )) def get_samp_rate_out(self): return self.samp_rate_out def set_samp_rate_out(self, samp_rate_out): self.samp_rate_out = samp_rate_out self.blocks_multiply_const_vxx_0.set_k((self.fc/self.samp_rate_out*(2*math.pi)/1e6, )) self.fractional_resampler_xx_0.set_resamp_ratio(self.samp_rate_in/self.samp_rate_out) self.blocks_multiply_const_vxx_0_0.set_k((1.0e-6*self.samp_rate_in/self.samp_rate_out, )) self.gsm_controlled_rotator_cc_0.set_samp_rate(self.samp_rate_out) self.blocks_add_const_vxx_0.set_k((self.samp_rate_in/self.samp_rate_out, ))
martinjlowm/gr-gsm
python/misc_utils/clock_offset_corrector.py
Python
gpl-3.0
4,498
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle 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 3 of the License, or // (at your option) any later version. // // Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. namespace format_theunittest\output\course_format; use renderable; use templatable; use stdClass; /** * Fixture for an invalid output for testing get_output_classname. * * @package core_course * @copyright 2021 Ferran Recio (ferran@moodle.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class invalidoutput implements renderable, templatable { /** * Export some data. * * @param renderer_base $output typically, the renderer that's calling this function * @return stdClass data context for a mustache template */ public function export_for_template(\renderer_base $output): stdClass { return (object)[ 'something' => 'invalid', ]; } }
snake/moodle
course/tests/fixtures/format_theunittest_output_course_format_invalidoutput.php
PHP
gpl-3.0
1,434
//Copyright (C) 2015 dhrapson //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 3 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/>. package configure_test import ( . "github.com/dhrapson/resembleio/configure" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("UrlPathHttpMatcher", func() { var ( path_regex string matcher UrlPathHttpMatcher err error ) Describe("when using a valid regex", func() { JustBeforeEach(func() { matcher, err = NewUrlPathHttpMatcher(path_regex) }) Context("when given an exactly matching regexp", func() { BeforeEach(func() { path_regex = `^/abc/def$` }) It("should return true", func() { Expect(err).NotTo(HaveOccurred()) result := matcher.MatchUrlPath("/abc/def") Expect(result).To(BeTrue()) }) }) Context("when given a loosely matching regexp", func() { BeforeEach(func() { path_regex = `abc` }) It("should return true", func() { Expect(err).NotTo(HaveOccurred()) result := matcher.MatchUrlPath("/abc/def") Expect(result).To(BeTrue()) }) }) Context("when given a non-matching URL path", func() { BeforeEach(func() { path_regex = `^/abc/ghi$` }) It("should return false", func() { Expect(err).NotTo(HaveOccurred()) result := matcher.MatchUrlPath("/abc/def") Expect(result).To(BeFalse()) Expect(err).NotTo(HaveOccurred()) }) }) }) Describe("when using an invalid regex", func() { BeforeEach(func() { path_regex = `^abc++$` }) It("should raise an error on creating the matcher", func() { matcher, err = NewUrlPathHttpMatcher(path_regex) Expect(err).To(HaveOccurred()) }) }) })
dhrapson/resembleio
configure/urlPathHttpMatcher_test.go
GO
gpl-3.0
2,225
package br.org.otus.laboratory.project.builder; import java.util.ArrayList; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import com.google.gson.GsonBuilder; public class ExamResultQueryBuilder { private ArrayList<Bson> pipeline; public ExamResultQueryBuilder() { this.pipeline = new ArrayList<>(); } public List<Bson> build() { return this.pipeline; } public ExamResultQueryBuilder getExamResultsWithAliquotValid() { pipeline.add(this.parseQuery("{$match:{\"objectType\":\"ExamResults\",\"isValid\":true}}")); return this; } public ExamResultQueryBuilder getSortingByExamName() { pipeline.add(this.parseQuery("{$sort:{\"resultName\":1}}")); return this; } public ExamResultQueryBuilder getSortingByRecruitmentNumber() { pipeline.add(this.parseQuery("{$sort:{\"recruitmentNumber\":1}}")); return this; } public ExamResultQueryBuilder getGroupOfExamResultsToExtraction() { Document group = this.parseQuery("{\n" + " $group: {\n" + " _id: \"$recruitmentNumber\",\n" + " results:{\n" + " $push:{\n" + " \"recruitmentNumber\":\"$recruitmentNumber\",\n" + " \"code\":\"$code\",\n" + " \"examName\":\"$examName\",\n" + " \"resultName\":\"$resultName\",\n" + " \"value\":\"$value\",\n" + " \"releaseDate\":\"$releaseDate\",\n" + " \"realizationDate\":\"$realizationDate\",\n" + " \"observations\":\"$observations\",\n" + " \"cutOffValue\":\"$cutOffValue\",\n" + " \"extraVariables\":\"$extraVariables\"\n" + " }\n" + " }\n" + " }\n" + " }"); pipeline.add(group); return this; } public ExamResultQueryBuilder getProjectionOfExamResultsToExtraction() { Document project = this.parseQuery("{\n" + " $project: {\n" + " recruitmentNumber: \"$_id\",\n" + " _id: 0,\n" + " results:\"$results\"\n" + " }\n" + " }"); pipeline.add(project); return this; } private Document parseQuery(String query) { GsonBuilder gsonBuilder = new GsonBuilder(); return gsonBuilder.create().fromJson(query, Document.class); } }
ccem-dev/otus-api
source/otus-persistence/src/main/java/br/org/otus/laboratory/project/builder/ExamResultQueryBuilder.java
Java
gpl-3.0
2,339
<?php class EM_Saleproducts_Model_Mysql4_Saleproducts extends Mage_Core_Model_Mysql4_Abstract { public function _construct() { // Note that the saleproducts_id refers to the key field in your database table. $this->_init('saleproducts/saleproducts', 'saleproducts_id'); } }
novayadi85/galatema
app/code/local/EM/Saleproducts/Model/Mysql4/Saleproducts.php
PHP
gpl-3.0
306
/*************************************************************************** SRC/MIXMOD/XEMOutputControler.cpp description copyright : (C) MIXMOD Team - 2001-2011 email : contact@mixmod.org ***************************************************************************/ /*************************************************************************** This file is part of MIXMOD MIXMOD 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 3 of the License, or (at your option) any later version. MIXMOD 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 MIXMOD. If not, see <http://www.gnu.org/licenses/>. All informations available on : http://www.mixmod.org ***************************************************************************/ #include <string.h> #include "XEMOutputControler.h" #include "XEMUtil.h" //------------ // Constructor //------------ XEMOutputControler::XEMOutputControler(){ int64_t i; _output = NULL; _nbOutputFiles = maxNbOutputFiles; for (i=0; i<_nbOutputFiles; i++){ _tabOutputTypes[i] = (XEMOutputType) i; } createEmptyFiles(); } //------------ // Constructor //------------ XEMOutputControler::XEMOutputControler(XEMOutput * output){ int64_t i; _output = output; _nbOutputFiles = maxNbOutputFiles; for (i=0; i<_nbOutputFiles; i++){ _tabOutputTypes[i] = (XEMOutputType) i; } createEmptyFiles(); } //----------- // Destructor //----------- XEMOutputControler::~XEMOutputControler(){ int64_t i; //cout<<"tabFileName"<<endl; for (i=0; i<maxNbOutputFiles; i++){ //cout<<"tabFileName : "<<_tabFiles[i]<<endl; delete _tabFiles[i]; } } //--------- // Selector //--------- void XEMOutputControler::setOutput(XEMOutput * output){ _output = output; } //--------- // editFile //--------- void XEMOutputControler::editFile(){ int64_t i; if (_output){ _output->editFile(_tabFiles); for (i=0; i<_nbOutputFiles; i++){ _tabFiles[i]->close(); } } } //--------- // editErroMixmodFile //--------- void XEMOutputControler::editErroMixmodFile(XEMErrorType error){ // errorMixmodOutput int64_t i = (int64_t)errorMixmodOutput; *_tabFiles[i]<<error<<endl; } //-------------------------- // Create Empty output Files //-------------------------- void XEMOutputControler::createEmptyFiles(){ int64_t i,j; string charCriterionType= ""; string fileName = ""; int64_t nbOutputFileType = 9; string * fileNameTmp = new string[nbOutputFileType]; for (i=0 ; i<nbOutputFileType; i++){ fileNameTmp[i] = ""; } fileNameTmp[0] = "standard.txt"; fileNameTmp[1] = "numericStandard.txt"; fileNameTmp[2] = "label.txt"; fileNameTmp[3] = "parameter.txt"; fileNameTmp[4] = "posteriorProbabilities.txt"; fileNameTmp[5] = "partition.txt"; fileNameTmp[6] = "likelihood.txt"; fileNameTmp[7] = "Error.txt"; fileNameTmp[8] = "numericLikelihood.txt"; // CV, BIC, NEC, ICL, DCV ... files //--------------------------------- for (i=0;i<nbMaxSelection;i++){ if (i==0){ charCriterionType = "BIC"; } if (i==1){ charCriterionType = "CV"; } if (i==2){ charCriterionType = "ICL"; } if (i==3){ charCriterionType = "NEC"; } if (i==4){ charCriterionType = "DCV"; } for (j=0; j<nbOutputFileType; j++){ fileName = charCriterionType; _tabFiles[nbOutputFileType*i+j] = new ofstream(fileName.append(fileNameTmp[j]).c_str(), ios::out); _tabFiles[nbOutputFileType*i+j]->setf(ios::fixed, ios::floatfield); } } // other files //------------ //char * completeFileName ="complete.txt"; _tabFiles[(int64_t)completeOutput] = new ofstream("complete.txt", ios::out); _tabFiles[(int64_t)completeOutput]->setf(ios::fixed, ios::floatfield); //char * numericCompleteFileName ="numericComplete.txt"; _tabFiles[(int64_t)numericCompleteOutput] = new ofstream("numericComplete.txt", ios::out); _tabFiles[(int64_t)numericCompleteOutput]->setf(ios::fixed, ios::floatfield); //char * CVlabelClassificationFileName = "CVlabelClassification.txt"; _tabFiles[(int64_t)CVlabelClassificationOutput] = new ofstream("CVlabelClassification.txt", ios::out); _tabFiles[(int64_t)CVlabelClassificationOutput]->setf(ios::fixed, ios::floatfield); //char * errorMixmodFileName = "errorMixmod.txt"; _tabFiles[(int64_t)errorMixmodOutput] = new ofstream("errorMixmod.txt", ios::out); _tabFiles[(int64_t)errorMixmodOutput]->setf(ios::fixed, ios::floatfield); //char * errorModelFileName = "errorModel.txt"; _tabFiles[(int64_t)errorModelOutput] = new ofstream("errorModel.txt", ios::out); _tabFiles[(int64_t)errorModelOutput]->setf(ios::fixed, ios::floatfield); // DCV files _tabFiles[(int64_t)DCVinfo] = new ofstream("DCVinfo.txt", ios::out); _tabFiles[(int64_t)DCVinfo]->setf(ios::fixed, ios::floatfield); _tabFiles[(int64_t)DCVnumericInfo] = new ofstream("DCVnumericInfo.txt", ios::out); _tabFiles[(int64_t)DCVnumericInfo]->setf(ios::fixed, ios::floatfield); // verify if files are open for (i=0 ;i<_nbOutputFiles; i++){ if (! _tabFiles[i]->is_open()) throw errorOpenFile; } delete [] fileNameTmp; /*delete completeFileName; delete numericCompleteFileName; delete CVlabelClassificationFileName; delete errorMixmodFileName; delete errorModelFileName; */ }
openturns/otmixmod
lib/src/mixmod/MIXMOD/XEMOutputControler.cpp
C++
gpl-3.0
5,794
/** * This file is part of ankus. * * ankus 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 3 of the License, or * (at your option) any later version. * * ankus 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 ankus. If not, see <http://www.gnu.org/licenses/>. */ package org.ankus.core.repository; /** * Persistence Object의 공통 CRUD를 정의한 Repository. * * @author Edward KIM * @since 0.3 */ public interface PersistentRepository<D, P> { /** * 새로운 객체를 저장한다. * * @param object 저장할 객체 * @param * @param runcase * @return 저장한 건수 */ int insert(D object); /** * 지정한 객체의 정보를 업데이트한다. * * @param object 업데이트할 객객체 * @param runcase * @return 업데이트 건수 */ int update(D object); /** * 지정한 식별자에 해당하는 객체를 삭제한다. * * @param identifier 식별자 * @return 삭제한 건수 */ int delete(P identifier); /** * 지정한 식별자에 해당하는 객체를 조회한다. * * @param identifier 식별자 * @return 식별자로 식별하는 객체 */ D select(P identifier); /** * 지정한 식별자에 해당하는 객체가 존재하는지 확인한다. * * @param identifier 식별자 * @return 존재하는 경우 <tt>true</tt> */ boolean exists(P identifier); }
onycom-ankus/ankus_analyzer_G
trunk_web/ankus-web-services/src/main/java/org/ankus/core/repository/PersistentRepository.java
Java
gpl-3.0
1,895
/* * This file is part of Pentachoron. * * Pentachoron 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 3 of the License, or * (at your option) any later version. * * Pentachoron 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 Pentachoron. If not, see <http://www.gnu.org/licenses/>. */ #include "culling.h" #include "renderer.h" Culling::Culling (void) { } Culling::~Culling (void) { } void Culling::Frame (void) { projmat = mvmat = glm::mat4 (1.0f); culled = 0; } void Culling::SetProjMatrix (const glm::mat4 &mat) { projmat = mat; r->geometry.SetProjMatrix (mat); } const glm::mat4 &Culling::GetProjMatrix (void) { return projmat; } void Culling::SetModelViewMatrix (const glm::mat4 &mat) { mvmat = mat; } const glm::mat4 &Culling::GetModelViewMatrix (void) { return mvmat; } bool Culling::IsVisible (const glm::vec3 &center, float radius) { glm::mat4 mvpmat; glm::vec4 left_plane, right_plane, bottom_plane, top_plane, near_plane, far_plane; float distance; mvpmat = projmat * mvmat; left_plane.x = mvpmat[0].w + mvpmat[0].x; left_plane.y = mvpmat[1].w + mvpmat[1].x; left_plane.z = mvpmat[2].w + mvpmat[2].x; left_plane.w = mvpmat[3].w + mvpmat[3].x; left_plane /= glm::length (glm::vec3 (left_plane)); distance = left_plane.x * center.x + left_plane.y * center.y + left_plane.z * center.z + left_plane.w; if (distance <= -radius) { culled++; return false; } right_plane.x = mvpmat[0].w - mvpmat[0].x; right_plane.y = mvpmat[1].w - mvpmat[1].x; right_plane.z = mvpmat[2].w - mvpmat[2].x; right_plane.w = mvpmat[3].w - mvpmat[3].x; right_plane /= glm::length (glm::vec3 (right_plane)); distance = right_plane.x * center.x + right_plane.y * center.y + right_plane.z * center.z + right_plane.w; if (distance <= -radius) { culled++; return false; } bottom_plane.x = mvpmat[0].w + mvpmat[0].y; bottom_plane.y = mvpmat[1].w + mvpmat[1].y; bottom_plane.z = mvpmat[2].w + mvpmat[2].y; bottom_plane.w = mvpmat[3].w + mvpmat[3].y; bottom_plane /= glm::length (glm::vec3 (bottom_plane)); distance = bottom_plane.x * center.x + bottom_plane.y * center.y + bottom_plane.z * center.z + bottom_plane.w; if (distance <= -radius) { culled++; return false; } top_plane.x = mvpmat[0].w - mvpmat[0].y; top_plane.y = mvpmat[1].w - mvpmat[1].y; top_plane.z = mvpmat[2].w - mvpmat[2].y; top_plane.w = mvpmat[3].w - mvpmat[3].y; top_plane /= glm::length (glm::vec3 (top_plane)); distance = top_plane.x * center.x + top_plane.y * center.y + top_plane.z * center.z + top_plane.w; if (distance <= -radius) { culled++; return false; } near_plane.x = mvpmat[0].w + mvpmat[0].z; near_plane.y = mvpmat[1].w + mvpmat[1].z; near_plane.z = mvpmat[2].w + mvpmat[2].z; near_plane.w = mvpmat[3].w + mvpmat[3].z; near_plane /= glm::length (glm::vec3 (near_plane)); distance = near_plane.x * center.x + near_plane.y * center.y + near_plane.z * center.z + near_plane.w; if (distance <= -radius) { culled++; return false; } far_plane.x = mvpmat[0].w - mvpmat[0].z; far_plane.y = mvpmat[1].w - mvpmat[1].z; far_plane.z = mvpmat[2].w - mvpmat[2].z; far_plane.w = mvpmat[3].w - mvpmat[3].z; far_plane /= glm::length (glm::vec3 (far_plane)); distance = far_plane.x * center.x + far_plane.y * center.y + far_plane.z * center.z + far_plane.w; if (distance <= -radius) { culled++; return false; } return true; }
ekpyron/pentachoron
src/culling.cpp
C++
gpl-3.0
3,808
#include "Function.h" #include "Entry.h" namespace instance { auto Function::lookupParameter(NameView name) const -> OptParameterView { auto r = parameterScope[name]; if (!r.single()) return {}; return &r.frontValue().get(meta::type<Parameter>); } } // namespace instance
rebuild-lang/REC
src/instance.data/instance/Function.cpp
C++
gpl-3.0
301
package scheduler import ( "fmt" "github.com/jonaz/astrotime" "os/exec" "strconv" "time" ) func isSunset(latitude float64, longitude float64) bool { t := astrotime.NextSunset(time.Now(), latitude, longitude) // tzname, _ := t.Zone() // fmt.Println(tzname) // fmt.Printf("The next sunrise is %d:%02d %s on %d/%d/%d.\n", t.Hour(), t.Minute(), tzname, t.Month(), t.Day(), t.Year()) if t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() { return true } return false } func isSunrise(latitude float64, longitude float64) bool { t := astrotime.NextSunrise(time.Now(), latitude, longitude) tzname, _ := t.Zone() // fmt.Println(tzname) // fmt.Printf("The next sunrise is %d:%02d %s on %d/%d/%d.\n", t.Hour()-6, t.Minute()-25, tzname, t.Month(), t.Day(), t.Year()) if t.Hour() == time.Now().Hour() && t.Minute() == time.Now().Minute() { fmt.Printf("The sunrise is %d:%02d %s on %d/%d/%d.\n", t.Hour(), t.Minute(), tzname, t.Month(), t.Day(), t.Year()) return true } return false } func Start(intervalInSeconds int, latitude float64, longitude float64, autoNightLights []int64) { ticker := time.NewTicker(time.Millisecond * time.Duration(intervalInSeconds)) go func() { // Hard code lights to change for now for t := range ticker.C { var state string var changeLights bool if isSunset(latitude, longitude) { fmt.Println("Sunset", t) state = "ON" changeLights = true } else if isSunrise(latitude, longitude) { fmt.Println("Sunrise", t) state = "OFF" changeLights = true } if changeLights == true { fmt.Println("Updating lights") for _, light := range autoNightLights { args := []string{"-u", "-m" + strconv.FormatInt(light, 10), "-t1", "-v" + state} cmd := exec.Command("/usr/sbin/aprontest", args...) cmd.Run() } } } }() }
icecreammatt/gopherwink
scheduler/scheduler.go
GO
gpl-3.0
1,839
package greymerk.roguelike.dungeon.settings; import java.util.Collection; import java.util.Random; import greymerk.roguelike.config.RogueConfig; import greymerk.roguelike.util.WeightedChoice; import greymerk.roguelike.util.WeightedRandomizer; import greymerk.roguelike.worldgen.Coord; import greymerk.roguelike.worldgen.IWorldEditor; public class SettingsResolver { private ISettingsContainer settings; public SettingsResolver(ISettingsContainer settings) throws Exception{ this.settings = settings; } // called from Dungeon class public ISettings getSettings(IWorldEditor editor, Random rand, Coord pos) throws Exception{ if(RogueConfig.getBoolean(RogueConfig.RANDOM)) return new SettingsRandom(rand); DungeonSettings builtin = this.getBuiltin(editor, rand, pos); DungeonSettings custom = this.getCustom(editor, rand, pos); // there are no valid dungeons for this location if(builtin == null && custom == null) return null; DungeonSettings exclusive = (custom != null) ? custom : builtin; DungeonSettings complete = applyInclusives(exclusive, editor, rand, pos); return complete; } public ISettings getWithName(String name, IWorldEditor editor, Random rand, Coord pos) throws Exception{ if(name.equals("random")) return new SettingsRandom(rand); DungeonSettings byName = this.getByName(name); if(byName == null) return null; DungeonSettings withInclusives = applyInclusives(byName, editor, rand, pos); return new DungeonSettings(new SettingsBlank(), withInclusives); } public static DungeonSettings processInheritance(DungeonSettings toProcess, ISettingsContainer settings) throws Exception{ DungeonSettings setting = new SettingsBlank(); if(toProcess == null) throw new Exception("Process Inheritance called with null settings object"); for(SettingIdentifier id : toProcess.getInherits()){ if(settings.contains(id)){ DungeonSettings inherited = new DungeonSettings(settings.get(id)); if(!inherited.getInherits().isEmpty()){ inherited = processInheritance(inherited, settings); } setting = new DungeonSettings(setting, inherited); } else { throw new Exception("Setting not found: " + id.toString()); } } return new DungeonSettings(setting, toProcess); } public ISettings getDefaultSettings(){ return new DungeonSettings(settings.get(new SettingIdentifier(SettingsContainer.BUILTIN_NAMESPACE, "base"))); } private DungeonSettings getByName(String name) throws Exception{ SettingIdentifier id; try{ id = new SettingIdentifier(name); } catch (Exception e){ throw new Exception("Malformed Setting ID String: " + name); } if(!this.settings.contains(id)) return null; DungeonSettings setting = new DungeonSettings(this.settings.get(id)); return processInheritance(setting, this.settings); } private DungeonSettings getBuiltin(IWorldEditor editor, Random rand, Coord pos) throws Exception{ if(!RogueConfig.getBoolean(RogueConfig.SPAWNBUILTIN)) return null; WeightedRandomizer<DungeonSettings> settingsRandomizer = new WeightedRandomizer<DungeonSettings>(); for(DungeonSettings setting : settings.getBuiltinSettings()){ if(setting.isValid(editor, pos)){ settingsRandomizer.add(new WeightedChoice<DungeonSettings>(setting, setting.criteria.weight)); } } if(settingsRandomizer.isEmpty()) return null; DungeonSettings chosen = settingsRandomizer.get(rand); return processInheritance(chosen, settings); } private DungeonSettings getCustom(IWorldEditor editor, Random rand, Coord pos) throws Exception{ WeightedRandomizer<DungeonSettings> settingsRandomizer = new WeightedRandomizer<DungeonSettings>(); for(DungeonSettings setting : settings.getCustomSettings()){ if(setting.isValid(editor, pos) && setting.isExclusive()){ settingsRandomizer.add(new WeightedChoice<DungeonSettings>(setting, setting.criteria.weight)); } } DungeonSettings chosen = settingsRandomizer.get(rand); if(chosen == null) return null; return processInheritance(chosen, settings); } private DungeonSettings applyInclusives(DungeonSettings setting, IWorldEditor editor, Random rand, Coord pos) throws Exception{ DungeonSettings toReturn = new DungeonSettings(setting); for(DungeonSettings s : settings.getCustomSettings()){ if(!s.isValid(editor, pos)) continue; if(s.isExclusive()) continue; toReturn = new DungeonSettings(toReturn, processInheritance(s, settings)); } return toReturn; } public String toString(String namespace){ Collection<DungeonSettings> byNamespace = this.settings.getByNamespace(namespace); if(byNamespace.isEmpty()) return ""; String toReturn = ""; for(DungeonSettings setting : byNamespace){ toReturn += setting.id.toString() + " "; } return toReturn; } @Override public String toString(){ return this.settings.toString(); } }
Greymerk/minecraft-roguelike
src/main/java/greymerk/roguelike/dungeon/settings/SettingsResolver.java
Java
gpl-3.0
4,942
package de.uni_koeln.spinfo.textengineering.ir.eval; import java.util.ArrayList; import java.util.List; import de.uni_koeln.spinfo.textengineering.ir.basic.Work; import de.uni_koeln.spinfo.textengineering.ir.boole.PositionalIndex; import de.uni_koeln.spinfo.textengineering.ir.preprocess.Preprocessor; /* * Erstellung eines Dummy-Goldstandards auf Grundlage unseres Shakespeare-Korpus */ public class GoldStandard { public static List<Integer> create(PositionalIndex index, String query) { List<Integer> result = new ArrayList<Integer>(); Preprocessor p = new Preprocessor(); List<String> q = p.tokenize(query); int docId = 0; for (Work d : index.getWorks()) { /* * Für unsere Experimente mit P, R und F betrachten wir ein Dokument immer dann als relevant, wenn ein Term * der Anfrage im Titel des Dokuments enthalten ist: */ if (containsAny(d.getTitle(), q)) { result.add(docId); } docId++; } return result; } private static boolean containsAny(String title, List<String> query) { for (String q : query) { /* Wir geben true zurück wenn ein Element der Anfrage im Titel enthalten ist: */ if (title.toLowerCase().contains(q.toLowerCase())) { return true; } } return false; } }
claesn/ir2017
ir2017/src/main/java/de/uni_koeln/spinfo/textengineering/ir/eval/GoldStandard.java
Java
gpl-3.0
1,252
/* * choiceKeyFrameDialog.cpp - Keyframe selection for optioned properties * Copyright (C) 2015, D Haley * 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 3 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/>. */ // -*- C++ -*- generated by wxGlade 0.6.5 on Sun Sep 23 22:52:41 2012 #include "choiceKeyFrameDialog.h" // begin wxGlade: ::extracode // end wxGlade #include "wx/wxcommon.h" ChoiceKeyFrameDialog::ChoiceKeyFrameDialog(wxWindow* parent, int id, const wxString& title, const wxPoint& pos, const wxSize& size, long style): wxDialog(parent, id, title, pos, size, wxDEFAULT_DIALOG_STYLE) { // begin wxGlade: ChoiceKeyFrameDialog::ChoiceKeyFrameDialog labelFrame = new wxStaticText(this, wxID_ANY, wxT("Frame")); textFrame = new wxTextCtrl(this, ID_TEXT_FRAME, wxEmptyString); labelSelection = new wxStaticText(this, wxID_ANY, wxT("Selection")); comboChoice = new wxComboBox(this, ID_COMBO_CHOICE, wxT(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_DROPDOWN|wxCB_SIMPLE|wxCB_READONLY); btnCancel = new wxButton(this, wxID_CANCEL, wxEmptyString); btnOK = new wxButton(this, wxID_OK, wxEmptyString); startFrameOK=false; set_properties(); do_layout(); // end wxGlade } BEGIN_EVENT_TABLE(ChoiceKeyFrameDialog, wxDialog) // begin wxGlade: ChoiceKeyFrameDialog::event_table EVT_COMBOBOX(ID_COMBO_CHOICE, ChoiceKeyFrameDialog::OnChoiceCombo) EVT_TEXT(ID_TEXT_FRAME, ChoiceKeyFrameDialog::OnFrameText) // end wxGlade END_EVENT_TABLE(); void ChoiceKeyFrameDialog::OnChoiceCombo(wxCommandEvent &event) { choice=comboChoice->GetSelection(); } void ChoiceKeyFrameDialog::OnFrameText(wxCommandEvent &event) { if(validateTextAsStream(textFrame,startFrame)) startFrameOK=true; updateOKButton(); } // wxGlade: add ChoiceKeyFrameDialog event handlers void ChoiceKeyFrameDialog::updateOKButton() { btnOK->Enable(startFrameOK); } void ChoiceKeyFrameDialog::buildCombo(size_t defaultChoice) { ASSERT(choiceStrings.size()); comboChoice->Clear(); for(size_t ui=0;ui<choiceStrings.size();ui++) comboChoice->Append((choiceStrings[ui])); comboChoice->SetSelection(defaultChoice); } void ChoiceKeyFrameDialog::setChoices(const std::vector<std::string> &choices, size_t defChoice) { choiceStrings=choices; buildCombo(defChoice); choice=defChoice; } void ChoiceKeyFrameDialog::set_properties() { // begin wxGlade: ChoiceKeyFrameDialog::set_properties SetTitle(wxT("Key Frame")); // end wxGlade } void ChoiceKeyFrameDialog::do_layout() { // begin wxGlade: ChoiceKeyFrameDialog::do_layout wxBoxSizer* frameSizer = new wxBoxSizer(wxVERTICAL); wxBoxSizer* buttonSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* comboSizer = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* textSizer = new wxBoxSizer(wxHORIZONTAL); textSizer->Add(labelFrame, 0, wxRIGHT|wxALIGN_CENTER_VERTICAL, 20); textSizer->Add(textFrame, 0, wxLEFT|wxALIGN_CENTER_VERTICAL, 5); frameSizer->Add(textSizer, 0, wxALL|wxEXPAND, 10); comboSizer->Add(labelSelection, 0, wxRIGHT|wxALIGN_CENTER_VERTICAL, 5); comboSizer->Add(comboChoice, 0, wxLEFT, 5); frameSizer->Add(comboSizer, 0, wxLEFT|wxRIGHT|wxTOP|wxEXPAND, 10); buttonSizer->Add(20, 20, 1, 0, 0); buttonSizer->Add(btnCancel, 0, wxRIGHT, 5); buttonSizer->Add(btnOK, 0, wxLEFT, 5); frameSizer->Add(buttonSizer, 0, wxALL|wxEXPAND, 5); SetSizer(frameSizer); frameSizer->Fit(this); Layout(); // end wxGlade }
lukasgartmair/3Depict_Isosurfaces
src/gui/dialogs/animateSubDialogs/choiceKeyFrameDialog.cpp
C++
gpl-3.0
3,928
import { check } from "meteor/check"; import processDoc from "./processDoc"; /** * getDoc * fetch repo profile from github and store in RepoData collection * @param {Object} doc - mongo style selector for the doc * @returns {undefined} returns */ function getDoc(options) { check(options, Object); // get repo details const docRepo = ReDoc.Collections.Repos.findOne({ repo: options.repo }); // we need to have a repo if (!docRepo) { console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`); return false; } // TOC item for this doc const tocItem = ReDoc.Collections.TOC.findOne({ alias: options.alias, repo: options.repo }); processDoc({ branch: options.branch, repo: options.repo, alias: options.alias, docRepo, tocItem }); } export default getDoc; export { flushDocCache };
reactioncommerce/redoc
packages/redoc-core/server/methods/getDoc.js
JavaScript
gpl-3.0
875
/* Um carro, e só */ class Car { constructor(posx, posy, width, height, lifeTime, color) { this.x = posx; this.y = posy; this.lifeTime = lifeTime; this.color = color; this.width = width; this.height = height; this.im = new Image(); this.im.src = carSprite.src; } draw(ctx) { ctx.save(); ctx.fillStyle = this.color; ctx.lineWidth = 1; ctx.drawImage( this.im, carSprite.x, carSprite.y, carSprite.w, carSprite.h, this.x, this.y, this.width, this.height ); } }
Juliano-rb/CrossChallenge
js/basegame/car.js
JavaScript
gpl-3.0
724
package ahmad.aghazadeh.recyclerviewcardview.logic; import android.databinding.BindingAdapter; import android.databinding.BindingConversion; import android.graphics.Bitmap; import android.graphics.Typeface; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.graphics.Palette; import android.text.TextWatcher; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; /** * Created by 890683 on 1/10/2016. */ public class BindingCustom { @BindingAdapter("fontName") public static void setFontName(TextView view, @Nullable String fontName) { String fontPath = "/fonts/" + fontName; view.setTypeface(Project.getTypeFace(view.getContext(),fontPath)); } @BindingAdapter({"imageUrl", "error", "paletteResId"}) public static void loadImage(final ImageView view, String url, @Nullable Drawable error, @Nullable final int paletteResId) { com.squareup.picasso.Callback callback = new Callback() { @Override public void onSuccess() { Bitmap photo = Project.drawableToBitmap(view.getDrawable()); Palette.generateAsync(photo, new Palette.PaletteAsyncListener() { public void onGenerated(Palette palette) { int mutedLight = palette.getMutedColor(view.getContext().getResources().getColor(android.R.color.white)); View paletteLayout = (view.getRootView()).findViewById(paletteResId); if(paletteLayout!=null){ paletteLayout.setBackgroundColor(mutedLight); } } }); } @Override public void onError() { } }; Picasso.with(view.getContext()).load(url).error(error).into(view, callback); } }
ahmadaghazadeh/recyclerviewcardview
app/src/main/java/ahmad/aghazadeh/recyclerviewcardview/logic/BindingCustom.java
Java
gpl-3.0
2,117
require 'rails/generators/named_base' require 'rails/generators/resource_helpers' module Rails module Generators class JbuilderGenerator < NamedBase include Rails::Generators::ResourceHelpers source_root File.expand_path('../templates', __FILE__) argument :attributes, type: :array, default: [], banner: 'field:type field:type' def create_root_folder path = File.join('app/views', controller_file_path) empty_directory path unless File.directory?(path) end def copy_view_files %w(index show).each do |view| filename = filename_with_extensions(view) template filename, File.join('app', 'views', controller_file_path, filename) end end def copy_spec_files copy_spec_file :index #unless options[:singleton] copy_spec_file :show end protected def filename_with_extensions(name) [name, :json, :jbuilder] * '.' end def attributes_list_with_timestamps attributes_list(attributes_names + %w(created_at updated_at)) end def attributes_list(attributes = attributes_names) if self.attributes.any? {|attr| attr.name == 'password' && attr.type == :digest} attributes = attributes.reject {|name| %w(password password_confirmation).include? name} end attributes.map { |a| ":#{a}"} * ', ' end def copy_spec_file(view) template "#{view}_spec.rb", File.join("spec", "views", controller_file_path, "#{view}.json.jbuilder_spec.rb") end # support for namespaced-resources def ns_file_name ns_parts.empty? ? file_name : "#{ns_parts[0].underscore}_#{ns_parts[1].singularize.underscore}" end # support for namespaced-resources def ns_table_name ns_parts.empty? ? table_name : "#{ns_parts[0].underscore}/#{ns_parts[1].tableize}" end def ns_parts @ns_parts ||= begin matches = ARGV[0].to_s.match(/\A(\w+)(?:\/|::)(\w+)/) matches ? [matches[1], matches[2]] : [] end end end end end
dima4p/rails4_jbuilder_with_rspec_generator
jbuilder_generator.rb
Ruby
gpl-3.0
2,160
<?php /* $Id: usps.php,v 1.8 2003/02/14 12:54:37 dgw_ Exp $ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2002 osCommerce Released under the GNU General Public License */ define('MODULE_SHIPPING_USpush_TEXT_TITLE', 'United States Postal Service'); define('MODULE_SHIPPING_USpush_TEXT_DESCRIPTION', 'United States Postal Service<br><br>You will need to have registered an account with USPS at http://www.uspsprioritymail.com/et_regcert.html to use this module<br><br>USPS expects you to use pounds as weight measure for your products.'); define('MODULE_SHIPPING_USpush_TEXT_OPT_PP', 'Parcel Post'); define('MODULE_SHIPPING_USpush_TEXT_OPT_PM', 'Priority Mail'); define('MODULE_SHIPPING_USpush_TEXT_OPT_EX', 'Express Mail'); define('MODULE_SHIPPING_USpush_TEXT_ERROR', 'An error occured with the USPS shipping calculations.<br>If you prefer to use USPS as your shipping method, please contact the store owner.'); ?>
andreaslangsays/pureshop
view/languages/english/modules/shipping/usps.php
PHP
gpl-3.0
967
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dat.V1.Dto.Bom.Exceptions { public class TransportException : BomException { public TransportException() : base() { } public TransportException(string message) : base(message) { } public TransportException(string message, System.Exception ex) : base(message, ex) { } } }
vybeonllc/dat_framework
V1/DataTransferObject/BaseObjectModels/Exceptions/TransportException.cs
C#
gpl-3.0
437
#include<bits/stdc++.h> using namespace std; int main() { freopen("in.txt","r",stdin); int tc,n; int A[1000],B[1000]; scanf("%d",&tc); while(tc--) { scanf("%d",&n); int sum=0; for(int i=0;i<n;i++) { scanf("%d",&A[i]); int j=i; B[i]=0; while(j--) { if(A[j]<=A[i]) B[i]++; } sum+=B[i]; } printf("%d\n",sum); } return 0; }
sillychip/uva
uva_1260.cpp
C++
gpl-3.0
529
var _engine_core_8h = [ [ "EngineCore", "class_ludo_1_1_engine_core.html", "class_ludo_1_1_engine_core" ], [ "LD_EXPORT_ENGINE_CORE", "_engine_core_8h.html#a0ced60c95a44fd7969a8d0b789257241", null ] ];
TwinDrills/Ludo
Docs/html/_engine_core_8h.js
JavaScript
gpl-3.0
209
package com.rockoutwill.letsmodreboot.proxy; public class ServerProxy extends CommonProxy { }
rockoutwill/LetsModReboot
src/main/java/com/rockoutwill/letsmodreboot/proxy/ServerProxy.java
Java
gpl-3.0
95
(function () { 'use strict'; angular.module('ph.account') // http://bartwullems.blogspot.hu/2015/02/angular-13-pending.html .directive("isUniqueEmailAddress", ['$q', '$http', function ($q, $http) { return { restrict: "A", require: "ngModel", link: function (scope, element, attributes, ngModel) { ngModel.$asyncValidators.isUnique = function (modelValue, viewValue) { return $http.post('/api/v0/email-address-check', {emailAddress: viewValue}).then( function (response) { if (!response.data.validEmailAddress) { return $q.reject(response.data.errorMessage); } return true; } ); }; } }; }]); })();
indr/phundus-spa
app/modules/account/directives/is-unique-email-address.js
JavaScript
gpl-3.0
796
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Register</div> <div class="panel-body"> <form class="form-horizontal" role="form" method="POST" action="{{ url('/register') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}"> <label for="name" class="col-md-4 control-label">Nombre</label> <div class="col-md-6"> <input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}" required autofocus> @if ($errors->has('name')) <span class="help-block"> <strong>{{ $errors->first('name') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}"> <label for="email" class="col-md-4 control-label">E-Mail</label> <div class="col-md-6"> <input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}" required> @if ($errors->has('email')) <span class="help-block"> <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}"> <label for="password" class="col-md-4 control-label">Contraseña</label> <div class="col-md-6"> <input id="password" type="password" class="form-control" name="password" required> @if ($errors->has('password')) <span class="help-block"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> </div> <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}"> <label for="password-confirm" class="col-md-4 control-label">Confirmar Contraseña</label> <div class="col-md-6"> <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required> @if ($errors->has('password_confirmation')) <span class="help-block"> <strong>{{ $errors->first('password_confirmation') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-6 col-md-offset-4"> <button type="submit" class="btn btn-primary"> <i class="fa fa-btn fa-user"></i> Registrar </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
e-gob/Consola-de-aplicaciones
resources/views/auth/register.blade.php
PHP
gpl-3.0
3,953
/** * */ package com.ingenitor.blockenvy.proxy; import cpw.mods.fml.common.event.FMLPreInitializationEvent; /** * @author ingenitor * */ public abstract class CommonProxy implements IProxy { }
ingenitor/BlockEnvy
src/main/java/com/ingenitor/blockenvy/proxy/CommonProxy.java
Java
gpl-3.0
203
function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2); ctx.fillStyle = color; ctx.strokeStyle = "#FF0000"; ctx.stroke(); ctx.fill(); ctx.closePath(); }
zacharyacutey/zacharyacutey.github.io
Breakout/ball.js
JavaScript
gpl-3.0
216
package com.gustavomaciel.enterprise; import com.badlogic.gdx.utils.Array; import com.gustavomaciel.enterprise.CollisionGroups.CollisionGroup; /** * Created by Gustavo on 5/22/2016. */ public class CollisionResolver { public static void checkAndResolve(Array<Entity> entities) { for(int i = 0, s = entities.size; i < s; ++i) { Entity first = entities.get(i); if(first.isMarkedForDeletion() || first.isCollisionDisabled()) continue; for(int j = i+1; j < s; ++j) { Entity second = entities.get(j); if(second.isMarkedForDeletion() || second.isCollisionDisabled()) continue; check(first, second); } } } private static void check(Entity first, Entity second) { final CollisionGroup firstCG = first.getCollisionGroup(); final CollisionGroup secondCG = second.getCollisionGroup(); boolean firstInterested = firstCG.matches(secondCG); boolean secondInterested = secondCG.matches(firstCG); if(firstInterested || secondInterested) { if(first.position.x < second.position.x + second.size.x && first.position.x + first.size.x > second.position.x && first.position.y < second.position.y + second.size.y && first.position.y + first.size.y > second.position.y) { float intersectionX = 0.5f * (Math.max(first.position.x, second.position.x) + Math.min(first.position.x + first.size.x, second.position.x + second.size.x)); float intersectionY = 0.5f * (Math.max(first.position.y, second.position.y) + Math.min(first.position.y + first.size.y, second.position.y + second.size.y)); if(firstInterested) { first.onCollision(second, intersectionX, intersectionY); } if(secondInterested) { second.onCollision(first, intersectionX, intersectionY); } } } } }
tavomaciel/games-for-enterprise-programmers
core/src/com/gustavomaciel/enterprise/CollisionResolver.java
Java
gpl-3.0
1,986
<?php defined("_LIVE_NEXUS") or die ("<h1>Direct access to this file is DENIED!</h1>"); // Dependancies $container = $app->getContainer(); // Monolog Logger // -------------- $container['logger'] = function($c) { $logger = new \Monolog\Logger('my_logger'); $file_handler = new \Monolog\Handler\StreamHandler("../logs/app.log"); $logger->pushHandler($file_handler); return $logger; }; // PHP view template // ----------------- $container['view'] = new \Slim\Views\PhpRenderer("templates/"); // PHP Cache // --------- $container['cache'] = function () { return new \Slim\HttpCache\CacheProvider(); }; // Get all routes // -------------- $allRoutes = []; $routes = $app->getContainer()->router->getRoutes(); foreach ($routes as $route) { $current_route = ["name" => $route->getName(), "pattern" => $route->getPattern()]; array_push($allRoutes, $current_route); } $container['allRoutes'] = $allRoutes;
Vlasterx/nexus-framework
project/container.php
PHP
gpl-3.0
941
// Decompiled with JetBrains decompiler // Type: System.Xml.Serialization.CaseInsensitiveKeyComparer // Assembly: System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 50ABAB51-7DC3-4F0A-A797-0D0C2D124D60 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Xml.dll using System; using System.Collections; using System.Globalization; namespace System.Xml.Serialization { internal class CaseInsensitiveKeyComparer : CaseInsensitiveComparer, IEqualityComparer { public CaseInsensitiveKeyComparer() : base(CultureInfo.CurrentCulture) { } bool IEqualityComparer.Equals(object x, object y) { return this.Compare(x, y) == 0; } int IEqualityComparer.GetHashCode(object obj) { string str = obj as string; if (str == null) throw new ArgumentException((string) null, "obj"); return str.ToUpper(CultureInfo.CurrentCulture).GetHashCode(); } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Xml/System/Xml/Serialization/CaseInsensitiveKeyComparer.cs
C#
gpl-3.0
975
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Sonic Visualiser An audio file viewer and annotation editor. Centre for Digital Music, Queen Mary, University of London. This file copyright 2006 Chris Cannam. 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. See the file COPYING included with this distribution for more information. */ #include "TempDirectory.h" #include "ResourceFinder.h" #include "system/System.h" #include "Exceptions.h" #include <QDir> #include <QFile> #include <QMutexLocker> #include <QSettings> #include <iostream> #include <cassert> #include <unistd.h> #include <time.h> TempDirectory * TempDirectory::m_instance = new TempDirectory; TempDirectory * TempDirectory::getInstance() { return m_instance; } TempDirectory::TempDirectory() : m_tmpdir("") { } TempDirectory::~TempDirectory() { cerr << "TempDirectory::~TempDirectory" << endl; cleanup(); } void TempDirectory::cleanup() { cleanupDirectory(""); } QString TempDirectory::getContainingPath() { QMutexLocker locker(&m_mutex); QSettings settings; settings.beginGroup("TempDirectory"); QString svDirParent = settings.value("create-in", "$HOME").toString(); settings.endGroup(); QString svDir = ResourceFinder().getUserResourcePrefix(); if (svDirParent != "$HOME") { //!!! iffy svDir.replace(QDir::home().absolutePath(), svDirParent); } if (!QFileInfo(svDir).exists()) { if (!QDir(svDirParent).mkpath(svDir)) { throw DirectoryCreationFailed(QString("%1 directory in %2") .arg(svDir).arg(svDirParent)); } } else if (!QFileInfo(svDir).isDir()) { throw DirectoryCreationFailed(QString("%1 is not a directory") .arg(svDir)); } cleanupAbandonedDirectories(svDir); return svDir; } QString TempDirectory::getPath() { if (m_tmpdir != "") return m_tmpdir; return createTempDirectoryIn(getContainingPath()); } QString TempDirectory::createTempDirectoryIn(QString dir) { // Entered with mutex held. QDir tempDirBase(dir); // Generate a temporary directory. Qt4.1 doesn't seem to be able // to do this for us, and mkdtemp is not standard. This method is // based on the way glibc does mkdtemp. static QString chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; QString suffix; int padlen = 6, attempts = 100; unsigned int r = (unsigned int)(time(0) ^ getpid()); for (int i = 0; i < padlen; ++i) { suffix += "X"; } for (int j = 0; j < attempts; ++j) { unsigned int v = r; for (int i = 0; i < padlen; ++i) { suffix[i] = chars[v % 62]; v /= 62; } QString candidate = QString("sv_%1").arg(suffix); if (tempDirBase.mkpath(candidate)) { m_tmpdir = tempDirBase.filePath(candidate); break; } r = r + 7777; } if (m_tmpdir == "") { throw DirectoryCreationFailed(QString("temporary subdirectory in %1") .arg(tempDirBase.canonicalPath())); } QString pidpath = QDir(m_tmpdir).filePath(QString("%1.pid").arg(getpid())); QFile pidfile(pidpath); if (!pidfile.open(QIODevice::WriteOnly)) { throw DirectoryCreationFailed(QString("pid file creation in %1") .arg(m_tmpdir)); } else { pidfile.close(); } return m_tmpdir; } QString TempDirectory::getSubDirectoryPath(QString subdir) { QString tmpdirpath = getPath(); QMutexLocker locker(&m_mutex); QDir tmpdir(tmpdirpath); QFileInfo fi(tmpdir.filePath(subdir)); if (!fi.exists()) { if (!tmpdir.mkdir(subdir)) { throw DirectoryCreationFailed(fi.filePath()); } else { return fi.filePath(); } } else if (fi.isDir()) { return fi.filePath(); } else { throw DirectoryCreationFailed(fi.filePath()); } } void TempDirectory::cleanupDirectory(QString tmpdir) { bool isRoot = false; if (tmpdir == "") { m_mutex.lock(); isRoot = true; tmpdir = m_tmpdir; if (tmpdir == "") { m_mutex.unlock(); return; } } QDir dir(tmpdir); dir.setFilter(QDir::Dirs | QDir::Files); for (unsigned int i = 0; i < dir.count(); ++i) { if (dir[i] == "." || dir[i] == "..") continue; QFileInfo fi(dir.filePath(dir[i])); if (fi.isDir()) { cleanupDirectory(fi.absoluteFilePath()); } else { if (!QFile(fi.absoluteFilePath()).remove()) { cerr << "WARNING: TempDirectory::cleanup: " << "Failed to unlink file \"" << fi.absoluteFilePath() << "\"" << endl; } } } QString dirname = dir.dirName(); if (dirname != "") { if (!dir.cdUp()) { cerr << "WARNING: TempDirectory::cleanup: " << "Failed to cd to parent directory of " << tmpdir << endl; return; } if (!dir.rmdir(dirname)) { cerr << "WARNING: TempDirectory::cleanup: " << "Failed to remove directory " << dirname << endl; } } if (isRoot) { m_tmpdir = ""; m_mutex.unlock(); } } void TempDirectory::cleanupAbandonedDirectories(QString svDir) { QDir dir(svDir, "sv_*", QDir::Name, QDir::Dirs); for (unsigned int i = 0; i < dir.count(); ++i) { QString dirpath = dir.filePath(dir[i]); QDir subdir(dirpath, "*.pid", QDir::Name, QDir::Files); if (subdir.count() == 0) { cerr << "INFO: Found temporary directory with no .pid file in it!\n(directory=\"" << dirpath << "\"). Removing it..." << endl; cleanupDirectory(dirpath); cerr << "...done." << endl; continue; } for (unsigned int j = 0; j < subdir.count(); ++j) { bool ok = false; int pid = QFileInfo(subdir[j]).baseName().toInt(&ok); if (!ok) continue; if (GetProcessStatus(pid) == ProcessNotRunning) { cerr << "INFO: Found abandoned temporary directory from " << "a previous, defunct process\n(pid=" << pid << ", directory=\"" << dirpath << "\"). Removing it..." << endl; cleanupDirectory(dirpath); cerr << "...done." << endl; break; } } } }
praaline/Praaline
svcore/base/TempDirectory.cpp
C++
gpl-3.0
7,104
package service; import java.util.List; import java.util.Map; import util.DataBaseUtils; public class ArticleService { /** * 通过类别获取文章列表 * @param categoryId * @param start * @param end */ public List<Map<String,Object>> getArticlesByCategoryId(Integer categoryId,Integer start,Integer end){ String sql = "select id,header,name,author," + "description from t_article where 1 = 1 " + " and is_delete = 0" + " and is_published = 1" + " and category_id = ?" + " order by update_time desc limit ?,?"; return DataBaseUtils.queryForList(sql, categoryId,start,end); } /** * 通过文章id获取文章内容 * @param id * @return */ public Map<String,Object> getContentByArticleId(String id){ String sql = "select a.id,a.name,a.content,a.create_time,a.author,b.name as category_name from t_article a inner join t_category b on a.category_id = b.id where a.id = ?"; return DataBaseUtils.queryForList(sql,id).get(0); } }
DannyHui/Article
src/service/ArticleService.java
Java
gpl-3.0
1,058
/* * Copyright (C) 2000 - 2008 TagServlet Ltd * * This file is part of Open BlueDragon (OpenBD) CFML Server Engine. * * OpenBD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * Free Software Foundation,version 3. * * OpenBD 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 OpenBD. If not, see http://www.gnu.org/licenses/ * * Additional permission under GNU GPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or combining * it with any of the JARS listed in the README.txt (or a modified version of * (that library), containing parts covered by the terms of that JAR, the * licensors of this Program grant you additional permission to convey the * resulting work. * README.txt @ http://www.openbluedragon.org/license/README.txt * * http://www.openbluedragon.org/ */ /* * Created on Jan 8, 2005 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.naryx.tagfusion.cfm.xml.ws.dynws; import java.io.Serializable; /** * Value object to hold operation and parameter information for web service * Stubs. */ public class StubInfo implements Serializable { private static final long serialVersionUID = 1L; protected StubInfo.Operation[] operations = null; protected String lName = null; protected String sName = null; protected String portName = null; protected String wsdlSum = null; public StubInfo() {} public StubInfo(String lName, String sName, String wsdlSum, String portName, StubInfo.Operation[] operations) { this.lName = lName; this.sName = sName; this.portName = portName; this.operations = operations; this.wsdlSum = wsdlSum; } public String getLocatorName() { return this.lName; } public void setLocatorName(String pVal) { this.lName = pVal; } public String getStubName() { return this.sName; } public void setStubName(String pVal) { this.sName = pVal; } public String getWSDLSum() { return this.wsdlSum; } public void setWSDLSum(String pVal) { this.wsdlSum = pVal; } public String getPortName() { return this.portName; } public void setPortName(String pVal) { this.portName = pVal; } public StubInfo.Operation[] getOperations() { return this.operations; } public void setOperations(StubInfo.Operation[] pVal) { this.operations = pVal; } public static class Operation implements Serializable { private static final long serialVersionUID = 1L; protected String name = null; protected StubInfo.Parameter[] parameters = null; protected StubInfo.Parameter[] subParameters = null; public Operation() { } public Operation(String name, StubInfo.Parameter[] parms) { this.name = name; this.parameters = parms; } public String getName() { return this.name; } public void setName(String pVal) { this.name = pVal; } public StubInfo.Parameter[] getParameters() { return this.parameters; } public void setParameters(StubInfo.Parameter[] pVal) { this.parameters = pVal; } public StubInfo.Parameter[] getSubParameters() { return this.subParameters; } public void setSubParameters(StubInfo.Parameter[] pVal) { this.subParameters = pVal; } } public static class Parameter implements Serializable { private static final long serialVersionUID = 1L; protected String name = null; protected boolean nillable = false; protected boolean omittable = false; public Parameter() { } public Parameter(String name, boolean nillable, boolean omittable) { this.name = name; this.omittable = omittable; this.nillable = nillable; } public String getName() { return this.name; } public void setName(String pVal) { this.name = pVal; } public boolean getNillable() { return this.nillable; } public void setNillable(boolean pVal) { this.nillable = pVal; } public boolean getOmittable() { return this.omittable; } public void setOmittable(boolean pVal) { this.omittable = pVal; } } }
OpenBD/openbd-core
src/com/naryx/tagfusion/cfm/xml/ws/dynws/StubInfo.java
Java
gpl-3.0
4,431
<?php /** * Ludus.php * * @package Embera * @author Michael Pratt <yo@michael-pratt.com> * @link http://www.michael-pratt.com/ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Embera\Provider; use Embera\Url; /** * Ludus Provider * @link https://app.ludus.one */ class Ludus extends ProviderAdapter implements ProviderInterface { /** inline {@inheritdoc} */ protected $endpoint = 'https://app.ludus.one/oembed?format=json'; /** inline {@inheritdoc} */ protected static $hosts = [ 'app.ludus.one' ]; /** inline {@inheritdoc} */ protected $allowedParams = [ 'maxwidth', 'maxheight' ]; /** inline {@inheritdoc} */ protected $httpsSupport = true; /** inline {@inheritdoc} */ protected $responsiveSupport = false; /** inline {@inheritdoc} */ public function validateUrl(Url $url) { // a4465cd5-ee82-4534-9755-5e658a7cb198 return (bool) (preg_match('~\.ludus\.one/(\w{8})-((\w{4}-){3})(\w{12})$~i', (string) $url)); } /** inline {@inheritdoc} */ public function normalizeUrl(Url $url) { $url->convertToHttps(); $url->removeQueryString(); $url->removeLastSlash(); return $url; } /** inline {@inheritdoc} */ public function getFakeResponse() { // <iframe width="960" height="540" src="https://app.ludus.one/fd01598e-5ed7-4edb-8d0e-cf75a36e0a07/full" frameborder="0" allowfullscreen></iframe> $embedUrl = $this->url . '/full'; $attr = []; $attr[] = 'width="{width}"'; $attr[] = 'height="{height}"'; $attr[] = 'src="' . $embedUrl . '"'; $attr[] = 'frameborder="0"'; $attr[] = 'allowfullscreen'; return [ 'type' => 'rich', 'provider_name' => 'Ludus', 'provider_url' => 'https://app.ludus.one', 'title' => 'Unknown title', 'html' => '<iframe ' . implode(' ', $attr). '></iframe>', ]; } }
OSTraining/OSEmbed
src/library/mpratt/embera/src/Embera/Provider/Ludus.php
PHP
gpl-3.0
2,084
#region License // /* // Microsoft Public License (Ms-PL) // MonoGame - Copyright © 2009 The MonoGame Team // // All rights reserved. // // This license governs use of the accompanying software. If you use the software, you accept this license. If you do not // accept the license, do not use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under // U.S. copyright law. // // A "contribution" is the original software, or any additions or changes to the software. // A "contributor" is any person that distributes its contribution under this license. // "Licensed patents" are a contributor's patent claims that read directly on its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, // each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, // each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, // your patent license from such contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution // notices that are present in the software. // (D) If you distribute any portion of the software in source code form, you may do so only under this license by including // a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object // code form, you may only do so under a license that complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees // or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent // permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular // purpose and non-infringement. // */ #endregion License #region Using clause using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Xna.Framework.GamerServices; #endregion Using clause namespace Microsoft.Xna.Framework.Net { // Represents a physical machine that is participating in a multiplayer session. // It can be used to detect when more than one NetworkGamer is playing on the same actual machine. public sealed class NetworkMachine { private GamerCollection<NetworkGamer> gamers; #region Constructors public NetworkMachine () { gamers = new GamerCollection<NetworkGamer>(); } #endregion #region Methods /* public void RemoveFromSession () { throw new NotImplementedException(); } */ #endregion #region Methods public GamerCollection<NetworkGamer> Gamers { get { return gamers; } } #endregion } }
Blucky87/Otiose2D
src/libs/MonoGame/MonoGame.Framework/Net/NetworkMachine.cs
C#
gpl-3.0
3,830
package net.infernalized.infernalutils.client.gui; import cpw.mods.fml.client.IModGuiFactory; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import java.util.Set; public class GuiFactory implements IModGuiFactory { @Override public void initialize(Minecraft minecraftInstance) { } @Override public Class<? extends GuiScreen> mainConfigGuiClass() { return null; } @Override public Set<RuntimeOptionCategoryElement> runtimeGuiCategories() { return null; } @Override public RuntimeOptionGuiHandler getHandlerFor(RuntimeOptionCategoryElement element) { return null; } }
Infernalized/InfernalUtils
src/main/java/net/infernalized/infernalutils/client/gui/GuiFactory.java
Java
gpl-3.0
681
#!/usr/bin/python import numpy as np mdir = "mesh3d/" fname = "out_p6-p4-p8" #################### print "input mesh data file" f1 = open(mdir+fname+".mesh", 'r') for line in f1: if line.startswith("Vertices"): break pcount = int(f1.next()) xyz = np.empty((pcount, 3), dtype=np.float) for t in range(pcount): xyz[t] = map(float,f1.next().split()[0:3]) for line in f1: if line.startswith("Triangles"): break trisc = int(f1.next()) tris = np.empty((trisc,4), dtype=int) for t in range(trisc): tris[t] = map(int,f1.next().split()) for line in f1: if line.startswith("Tetrahedra"): break tetsc = int(f1.next()) tets = np.empty((tetsc,5), dtype=int) for t in range(tetsc): tets[t] = map(int,f1.next().split()) f1.close() #################### print "identify geometry" ftype = [('v0', np.int),('v1', np.int),('v2', np.int),('label', 'S2')] faces = np.empty(trisc/2, dtype=ftype) for i in range(len(faces)): faces[i] = (tris[2*i][0],tris[2*i][1],tris[2*i][2],str(tris[2*i][3])+str(tris[2*i+1][3])) face_list,face_count = np.unique(faces['label'], return_counts=True) vtype = [('v0', np.int),('v1', np.int),('v2', np.int),('v3', np.int),('label', 'S1')] vols = np.empty(tetsc, dtype=vtype) for i in range(tetsc): vols[i] = (tets[i][0],tets[i][1],tets[i][2],tets[i][3],str(tets[i][4])) vol_list,vol_count = np.unique(vols['label'], return_counts=True) #################### print "output vtk data files for faces" for i, f in enumerate(face_list): f2 = open(mdir+fname+"_"+face_list[i]+".vtk", 'w') f2.write("# vtk DataFile Version 2.0\n") f2.write("mesh data\n") f2.write("ASCII\n") f2.write("DATASET UNSTRUCTURED_GRID\n") f2.write("POINTS "+str(pcount)+" float\n") # overkill, all points! for v in xyz: f2.write(str(v[0]-35.33)+' '+str(35.33-v[1])+' '+str(12.36-v[2])+'\n') f2.write("CELLS "+str(face_count[i])+" "+str(face_count[i]*4)+"\n") for v in faces: if v[3] == f: f2.write("3 "+str(v[0]-1)+' '+str(v[1]-1)+' '+str(v[2]-1)+'\n') f2.write("CELL_TYPES "+str(face_count[i])+"\n") for t in range(face_count[i]): f2.write("5 ") f2.write("\n") f2.close() #################### print "output vtk data files for volumes" for i, f in enumerate(vol_list): f2 = open(mdir+fname+"_"+vol_list[i]+".vtk", 'w') f2.write("# vtk DataFile Version 2.0\n") f2.write("mesh data\n") f2.write("ASCII\n") f2.write("DATASET UNSTRUCTURED_GRID\n") f2.write("POINTS "+str(pcount)+" float\n") # overkill, all points! for v in xyz: f2.write(str(v[0]-35.33)+' '+str(35.33-v[1])+' '+str(12.36-v[2])+'\n') f2.write("CELLS "+str(vol_count[i])+" "+str(vol_count[i]*5)+"\n") for v in vols: if v[4] == f: f2.write("4 "+str(v[0]-1)+' '+str(v[1]-1)+' '+str(v[2]-1)+' '+str(v[3]-1)+'\n') f2.write("CELL_TYPES "+str(vol_count[i])+"\n") for t in range(vol_count[i]): f2.write("10 ") f2.write("\n") f2.close() ####################
jrugis/cell_mesh
mesh2vtk.py
Python
gpl-3.0
2,909
/******************************************************************************* * Copyright (c) 2012 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.obiba.opal.web.gwt.app.client.administration.presenter; import org.obiba.opal.web.gwt.rest.client.authorization.HasAuthorization; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * Fire this event to have all administration presenters authorize themselves and callback on this * {@code HasAuthorization}. * <p/> * This allows decoupling a link to the administration section from the section's content. */ public class RequestAdministrationPermissionEvent extends GwtEvent<RequestAdministrationPermissionEvent.Handler> { public interface Handler extends EventHandler { void onAdministrationPermissionRequest(RequestAdministrationPermissionEvent event); } private static final Type<Handler> TYPE = new Type<Handler>(); private final HasAuthorization authorization; public RequestAdministrationPermissionEvent(HasAuthorization authorization) { this.authorization = authorization; } public HasAuthorization getHasAuthorization() { return authorization; } public static Type<Handler> getType() { return TYPE; } @Override protected void dispatch(Handler handler) { handler.onAdministrationPermissionRequest(this); } @Override public GwtEvent.Type<Handler> getAssociatedType() { return getType(); } }
apruden/opal
opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/presenter/RequestAdministrationPermissionEvent.java
Java
gpl-3.0
1,805
using System.Threading.Tasks; namespace JumbleRef.Core.Services { public interface IUserInteractionService { Task<string> PromptForText(string title, string message, string initialValue, string acceptText, string cancelText = null); Task<bool> PromptYesNo(string title, string message, string acceptText, string cancelText); } }
garrettpauls/JumbleRef
Source/JumbleRef.Core/Services/IUserInteractionService.cs
C#
gpl-3.0
358
/** * TNTConcept Easy Enterprise Management by Autentia Real Bussiness Solution S.L. * Copyright (C) 2007 Autentia Real Bussiness Solution S.L. * * 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 3 of the License. * * 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/>. */ package com.autentia.tnt.businessobject; public enum InventaryType { PC, LAPTOP, BOOK, KEY, CARD, CAR }
autentia/TNTConcept
tntconcept-core/src/main/java/com/autentia/tnt/businessobject/InventaryType.java
Java
gpl-3.0
862
package fr.guiguilechat.jcelechat.model.jcesi.compiler.compiled.responses; public class R_get_universe_systems_system_id { /** * The constellation this solar system is in */ public int constellation_id; /** * name string */ public String name; /** * planets array */ public get_universe_systems_system_id_planets[] planets; /** * position object */ public M_3_xnumber_ynumber_znumber position; /** * security_class string */ public String security_class; /** * security_status number */ public float security_status; /** * star_id integer */ public int star_id; /** * stargates array */ public int[] stargates; /** * stations array */ public int[] stations; /** * system_id integer */ public int system_id; @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other == null)||(other.getClass()!= getClass())) { return false; } R_get_universe_systems_system_id othersame = ((R_get_universe_systems_system_id) other); if (constellation_id!= othersame.constellation_id) { return false; } if ((name!= othersame.name)&&((name == null)||(!name.equals(othersame.name)))) { return false; } if ((planets!= othersame.planets)&&((planets == null)||(!planets.equals(othersame.planets)))) { return false; } if ((position!= othersame.position)&&((position == null)||(!position.equals(othersame.position)))) { return false; } if ((security_class!= othersame.security_class)&&((security_class == null)||(!security_class.equals(othersame.security_class)))) { return false; } if (security_status!= othersame.security_status) { return false; } if (star_id!= othersame.star_id) { return false; } if ((stargates!= othersame.stargates)&&((stargates == null)||(!stargates.equals(othersame.stargates)))) { return false; } if ((stations!= othersame.stations)&&((stations == null)||(!stations.equals(othersame.stations)))) { return false; } if (system_id!= othersame.system_id) { return false; } return true; } public int hashCode() { return (((((((((constellation_id +((name == null)? 0 :name.hashCode()))+((planets == null)? 0 :planets.hashCode()))+((position == null)? 0 :position.hashCode()))+((security_class == null)? 0 :security_class.hashCode()))+ Double.hashCode(security_status))+ star_id)+((stargates == null)? 0 :stargates.hashCode()))+((stations == null)? 0 :stations.hashCode()))+ system_id); } }
guiguilechat/EveOnline
model/esi/JCESI/src/generated/java/fr/guiguilechat/jcelechat/model/jcesi/compiler/compiled/responses/R_get_universe_systems_system_id.java
Java
gpl-3.0
2,884
#ifndef DECOMPRESSOR_HPP #define DECOMPRESSOR_HPP #include <unordered_map> #include <queue> // #include <memory> #include <iostream> #include <fstream> #include <cassert> #include <queue> // #include "InputBuffer.hpp" #include "OffsetsStream.hpp" #include "EditsStream.hpp" #include "ClipStream.hpp" #include "ReadIDStream.hpp" #include "FlagsStream.hpp" #include "QualityStream.hpp" // #include "MergedEditsStream.hpp" #include "TranscriptsStream.hpp" #include "RefereeHeader.hpp" //////////////////////////////////////////////////////////////// #define D_SEQ 1 #define D_FLAGS 2 #define D_READIDS 4 #define D_QUALS 8 #define D_OPTIONAL_FIELDS 16 //////////////////////////////////////////////////////////////// // // // //////////////////////////////////////////////////////////////// struct InputStreams { shared_ptr<ClipStream> left_clips; shared_ptr<ClipStream> right_clips; shared_ptr<OffsetsStream> offs; shared_ptr<EditsStream> edits; shared_ptr<FlagsStream> flags; shared_ptr<ReadIDStream> readIDs; shared_ptr<QualityStream> qualities; InputStreams() {} }; //////////////////////////////////////////////////////////////////////////////// // // // //////////////////////////////////////////////////////////////////////////////// class Decompressor { unordered_map<int,string> t_map; void write_sam_header(ofstream & recovered_file, RefereeHeader & header) { // write version, sorting info (alignments always sorted by coord) recovered_file << "@HD\t" << header.get_version() << "\tSO:coordinate" << endl; for (auto t_id : header.getTranscriptIDs() ) { recovered_file << "@SQ\tSN:" << header.getMapping(t_id) << "\tLN:" << header.getTranscriptLength(t_id) << endl; } } //////////////////////////////////////////////////////////////////////////// // sync the streams // TODO: take into account where clips start //////////////////////////////////////////////////////////////////////////// void sync_streams(InputStreams & is, pair<int, unsigned long> & off_block_start, // offsets pair<int, unsigned long> & edit_block_start, // edits pair<int, unsigned long> & lc_start, // left clips pair<int, unsigned long> & rc_start, // right clips int const target_ref_id, int const target_coord) { int offset_coord = off_block_start.first; unsigned long offset_num_al = off_block_start.second; int edit_coord = edit_block_start.first; unsigned long edit_num_al = edit_block_start.second; // first sync by the number of alignments preceeding the blocks cerr << "bringing all streams up to speed w/ offset stream" << endl; while (edit_num_al < offset_num_al) { is.edits->next(); // next has_edit byte // skip edit list for this alignment if there is one if (is.edits->hasEdits() ) is.edits->getEdits(); edit_num_al++; } cerr << "edit_num_al: " << edit_num_al << endl; while (offset_num_al < edit_num_al) { // need off to seek forward to edit_start is.offs->getNextOffset(); offset_num_al++; } cerr << "offs_num_al: " << offset_num_al << endl; // now seek to the target coordinate cerr << "seeking to a target coordinate chr=" << target_ref_id << ":" << target_coord << endl; int offset = is.offs->getCurrentOffset(); int ref_id = is.offs->getCurrentTranscript(); assert(offset_coord <= offset); while (ref_id < target_ref_id || offset < target_coord) { offset = is.offs->getNextOffset(); if (offset == END_OF_TRANS) { ref_id = is.offs->getNextTranscript(); if (ref_id == END_OF_STREAM) { cerr << "[ERROR] Unexpected end of offsets stream" << endl; exit(1); } } else if (offset == END_OF_STREAM) { cerr << "[ERROR] unexpected end of offsets stream" << endl; exit(1); } // advance to the next edit is.edits->next(); if (is.edits->hasEdits() ) is.edits->getEdits(); } cerr << "after seeking current coord is: chr=" << ref_id << ":" << offset << endl; } //////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////// public: Decompressor( string const & input_fname, string const & output_fname, string const & ref_path): file_name(input_fname), output_name(output_fname), ref_path(ref_path) { } //////////////////////////////////////////////////////////////////////////// // Reconstruct SAM file by combining the inputs; restoring reads and quals //////////////////////////////////////////////////////////////////////////// void decompress(RefereeHeader & header, InputStreams & is, uint8_t const options) { // sequence-specific streams int read_len = header.getReadLen(); auto t_map = header.getTranscriptIDsMap(); cerr << "[decompress the entire contents]" << endl; cerr << "Read length:\t" << (int)read_len << endl; assert(read_len > 0); TranscriptsStream transcripts(file_name, ref_path, "-d", t_map); recovered_file.open( output_name.c_str() ); check_file_open(recovered_file, file_name); write_sam_header(recovered_file, header); // prime the first blocks in every stream is.offs->seekToBlockStart(-1, 0, 0); is.edits->seekToBlockStart(-1, 0, 0); is.left_clips->seekToBlockStart(-1, 0, 0); is.right_clips->seekToBlockStart(-1, 0, 0); is.flags->seekToBlockStart(-1, 0, 0); is.readIDs->seekToBlockStart(-1, 0, 0); is.qualities->seekToBlockStart(-1, 0, 0); int ref_id = is.offs->getCurrentTranscript(); // cerr << "Starting with transcript " << ref_id << endl; int i = 0; while ( is.offs->hasMoreOffsets() ) { // zero-based offsets int offset_0 = is.offs->getNextOffset(); if (offset_0 == END_OF_TRANS) { // remove the prev transcript sequence -- will not need it anymore transcripts.dropTranscriptSequence(ref_id); // pull the next transcript -- seq will be loaded on first access ref_id = is.offs->getNextTranscript(); if (ref_id == END_OF_STREAM) { cerr << "Done" << endl; return; } cerr << "chr=" << transcripts.getMapping(ref_id) << " "; } else if (offset_0 == END_OF_STREAM) { // break cerr << "Done"; } else { // legit offset int ret = is.edits->next(); // advance to the next alignment if (ret == END_OF_STREAM) { cerr << "no more edits" << endl; } reconstructAlignment(offset_0, read_len, ref_id, transcripts, is.edits, is.left_clips, is.right_clips, is.readIDs, is.flags, is.qualities, options); } i++; if (i % 1000000 == 0) { cerr << i / 1000000 << "mln "; } } cerr << endl; cerr << "quals covered: " << quals_covered << endl; cerr << "new qual requested: " << new_requested << endl; recovered_file.close(); } //////////////////////////////////////////////////////////////// // Decompress alignments within a given interval //////////////////////////////////////////////////////////////// void decompressInterval(GenomicInterval interval, RefereeHeader & header, InputStreams & is, const uint8_t options) { int read_len = header.getReadLen(); auto t_map = header.getTranscriptIDsMap(); TranscriptsStream transcripts(file_name, ref_path, "-d", t_map); recovered_file.open( output_name.c_str() ); if (!recovered_file) { cerr << "[ERROR] Could not open output file." << endl; exit(1); } cerr << "Read len=" << read_len << endl; assert(read_len > 0); cerr << "[decompress alignments from an interval]" << endl; interval.chromosome = transcripts.getID(to_string(interval.chromosome) ); int ref_id = interval.chromosome; // TODO: can return false when no data for that interval is available pair<int,unsigned long> off_start_coord = is.offs->seekToBlockStart(interval.chromosome, interval.start, interval.stop); assert(off_start_coord.first == is.offs->getCurrentOffset() ); // loads the first block overlapping he requested coordinate // cerr << "Seeking to the first edit block" << endl; pair<int,unsigned long> edit_start_coord = is.edits->seekToBlockStart(interval.chromosome, interval.start, interval.stop); // cerr << "syncing input streams" << endl; // TODO: enable and sync clipped regions pair<int,unsigned long> lc_start, rc_start; // auto lc_start = is.left_clips->seekToBlockStart(interval.chromosome, interval.start, interval.stop); // auto rc_start = is.right_clips->seekToBlockStart(interval.chromosome, interval.start, interval.stop); sync_streams(is, off_start_coord, edit_start_coord, lc_start, rc_start, interval.chromosome, interval.start); cerr << "STREAMS SYNCED" << endl; // now restore alignments int i = 0, offset = 0; while ( is.offs->hasMoreOffsets() ) { offset = is.offs->getNextOffset(); // cerr << "offset: " << offset << endl; if (offset >= interval.stop) { cerr << "[INFO] Reached the end of the interval (" << interval.stop << " <= " << offset << ")" << endl; return; } if (offset == END_OF_TRANS) { ref_id = is.offs->getNextTranscript(); if (ref_id == END_OF_STREAM) { return; } } else if (offset == END_OF_STREAM) { // break // cerr << "done"; } else { // legit offset int ret = is.edits->next(); // advance to the next alignment if (ret == END_OF_STREAM) { // cerr << "done with edits" << endl; // break; } reconstructAlignment(offset, read_len, ref_id, transcripts, is.edits, is.left_clips, is.right_clips, is.readIDs, is.flags, is.qualities, options); } i++; if (i % 1000000 == 0) { cerr << i / 1000000 << "mln "; } } cerr << endl; recovered_file.close(); } //////////////////////////////////////////////////////////////// // // Privates // //////////////////////////////////////////////////////////////// private: string file_name; // file prefix for the files with parts of the data string output_name; // file prefix for the files with parts of the data string ref_path; // path to the file with the reference sequence uint8_t read_len; // uniform read length ofstream recovered_file; //////////////////////////////////////////////////////////////// // reconstructs read without edits // offset is 0-based //////////////////////////////////////////////////////////////// void reconstructAlignment(int offset, int read_len, int ref_id, TranscriptsStream & transcripts, shared_ptr<EditsStream> edits, shared_ptr<ClipStream> left_clips, shared_ptr<ClipStream> right_clips, shared_ptr<ReadIDStream> read_ids, shared_ptr<FlagsStream> flags, shared_ptr<QualityStream> qualities, uint8_t const options) { string cigar, md_string, read; bool has_edits = edits->hasEdits(); if (has_edits) { // cerr << "read with edits" << endl; md_string = "MD:Z:"; vector<uint8_t> edit_ops = edits->getEdits(); read = buildEditStrings(read_len, edit_ops, cigar, md_string, left_clips, right_clips, offset, ref_id, transcripts); } else { // cerr << "no edits read" << endl; read = transcripts.getTranscriptSequence(ref_id, offset, read_len); } // to upper case // std::transform(read.begin(), read.end(), read.begin(), ::toupper); // cerr << "getting all other fields " << read_ids << endl; if (options & D_READIDS) { string read_id = "*"; if (read_ids != nullptr) { int status = 0; read_id = read_ids->getNextID(status); if (status != SUCCESS) read_id = "*"; } recovered_file << read_id << "\t"; } int flag = -1, mapq = -1, rnext = -1, pnext = -1, tlen = -1; if (options & D_FLAGS) { if (flags != nullptr) { // cerr << "bla " << flags << endl; auto alignment_flags = flags->getNextFlagSet(); assert(alignment_flags.size() == 5); flag = alignment_flags[0]; mapq = alignment_flags[1]; rnext = alignment_flags[2]; pnext = alignment_flags[3], tlen = alignment_flags[4]; } recovered_file << flag << "\t"; // write out reference name, offset (SAM files use 1-based offsets) recovered_file << transcripts.getMapping(ref_id) << "\t" << (offset + 1); recovered_file << "\t" << mapq; if (has_edits) recovered_file << "\t" << cigar; else recovered_file << "\t" << (int)read_len << "M"; recovered_file << "\t"; if (rnext < 0) { recovered_file << "*"; pnext = 0; tlen = 0; } else if (rnext == 0) { recovered_file << "="; tlen = pnext - tlen; } else recovered_file << rnext; recovered_file << "\t" << pnext << "\t" << tlen << "\t"; } // cerr << "got flags 'n all" << endl; if (options & D_SEQ) { recovered_file << read; // more data to come -- separate if ( (options & D_QUALS) || (options & D_OPTIONAL_FIELDS) ) recovered_file << "\t"; } // write out qual vector bool secondary_alignment = (flag >= 0) ? (flag & 0x100) > 0 : true; if (options & D_QUALS) { quals_covered++; if (secondary_alignment) recovered_file << "*"; else { new_requested++; recovered_file << qualities->getNextQualVector(); } } else { recovered_file << "*"; } // cerr << "wrote out quals" << endl; if (options & D_OPTIONAL_FIELDS) { if (has_edits) recovered_file << "\t" << md_string << " "; // TODO: write out other optional fields } recovered_file << endl; } int quals_covered = 0; int new_requested = 0; //////////////////////////////////////////////////////////////// // build CIGAR, MD strings for the read with edits // offset -- zero based //////////////////////////////////////////////////////////////// string buildEditStrings(int read_len, vector<uint8_t> & edits, string & cigar, string & md_string, shared_ptr<ClipStream> left_clips, shared_ptr<ClipStream> right_clips, int offset, int ref_id, TranscriptsStream & transcripts) { string right_cigar, right_clip, read = transcripts.getTranscriptSequence(ref_id, offset, read_len); int j = 0, last_md_edit_pos = 0, last_cigar_edit_pos = 0, clipped_read_len = read_len; int offset_since_last_cigar = 0; // reset to 0 when on the cigar edit, incremented when on MD edit int offset_since_last_md = 0; int splice_offset = 0; int last_abs_pos = 0, Ds = 0, Is = 0; // number of deletions bool first_md_edit = true, first_cigar_was_clip = false; // if (offset == 18964285 ||offset == 18964286 || offset == 18964284) { // cerr << "len=" << edits.size() << " off=" << offset << " "; // for (auto e : edits) // cerr << (int)e << " "; // cerr << endl; // cerr << "read: " << read << endl; // } uint8_t op; while (j < edits.size() ) { op = edits[j]; // if (offset == 57509325) // cerr << op << " "; switch (op) { case 'L': { first_cigar_was_clip = true; string left_clip; if (left_clips == nullptr) { // clipped data not available break; } else { left_clips->getNext(left_clip); // just concatenate the left clip and the read read = left_clip + read.substr(0, read_len - left_clip.length()); // update cigar string cigar += to_string(left_clip.length()); cigar += "S"; // update counters last_cigar_edit_pos += left_clip.length(); last_abs_pos += left_clip.length(); offset_since_last_cigar = 0; offset_since_last_md = 0; last_md_edit_pos = 0; clipped_read_len -= left_clip.length(); } } break; case 'R': { if (right_clips == nullptr) { // clipped data not available break; } else { right_clips->getNext(right_clip); right_cigar += to_string(right_clip.length()); right_cigar += "S"; clipped_read_len -= right_clip.length(); } } break; case 'l': { j++; first_cigar_was_clip = true; // update the read (shorten) read = read.substr(edits[j]); // update cigar string cigar += to_string(edits[j]); cigar += "H"; last_cigar_edit_pos += edits[j]; last_abs_pos += edits[j]; offset_since_last_cigar = 0; offset_since_last_md = 0; clipped_read_len -= edits[j]; } break; case 'r': { j++; cigar += to_string(edits[j]); cigar += "H"; last_cigar_edit_pos += edits[j]; clipped_read_len -= edits[j]; } break; case 'D': { // handle a deletion int ds = 0; bool first_d = true; offset_since_last_cigar += edits[j+1] - Is; while (j < edits.size()) {// consume all Ds if (edits[j] != 'D') { // end of run of D's break; } else if (!first_d && edits[j+1] > 0 ) { // non contiguous deletions break; } ds++; // cerr << (char)edits[j] << "-" << (int)edits[j+1] << ","; last_abs_pos += edits[j+1]; read.erase(last_abs_pos, 1); first_d = false; j += 2; } j--; assert(j < edits.size()); Ds += ds; // cerr << "D's pos: " << last_abs_pos << " #=" << ds << " "; // compensate for deleted bases by adding to the end of the read from the reference // splice_offset: handles the case when this might be after a splicing event // cerr << "seq past the read: " << transcripts.getTranscriptSequence(ref_id, offset + splice_offset + read_len, 5) << " "; read += transcripts.getTranscriptSequence(ref_id, offset + splice_offset + read_len, ds); // cerr << read << " "; if (offset_since_last_cigar > 0) { cigar += to_string(offset_since_last_cigar); cigar += "M"; } cigar += to_string(ds); cigar += "D"; last_cigar_edit_pos += offset_since_last_cigar; offset_since_last_cigar = 0; } break; case 'E': case 197: { // handle a splice // cerr << "splice "; bool is_long_splice = edits[j] >> 7; j++; offset_since_last_cigar += edits[j] - Is; last_abs_pos += edits[j]; // cerr << "at pos:" << last_abs_pos << " "; // update cigar string cigar += to_string(offset_since_last_cigar); cigar += "M"; // get splice len // cerr << "len: "; j++; int splice_len = ( (int)edits[j] << 8); // cerr << "j=" << j << " " << (int)edits[j] << " "; j++; splice_len |= (int)edits[j]; // cerr << "j=" << j << " " << (int)edits[j] << " "; if (is_long_splice) { j++; splice_len = splice_len << 8; splice_len |= (int)edits[j]; // cerr << "j=" << j << " " << (int)edits[j] << " "; } cigar += to_string(splice_len); cigar += "N"; // update the counters splice_offset += offset_since_last_cigar + splice_len; last_cigar_edit_pos += offset_since_last_cigar; offset_since_last_cigar = 0; // update the read // TODO: test with hard clipped strings if (offset == 57509325) cerr << offset << endl; if (read.size() <= last_cigar_edit_pos) { cerr << "weird stuff: " << read.size() << " cigar: " << last_cigar_edit_pos << " offs: " << offset << endl; } assert(read.size() > last_cigar_edit_pos); read.replace(last_cigar_edit_pos, read_len - last_cigar_edit_pos, transcripts.getTranscriptSequence(ref_id, offset + splice_offset, read_len - last_cigar_edit_pos)); // cerr << "read: " << read << endl; } break; case 'V': case 'W': case 'X': case 'Y': case 'Z': { /* insert bases into the reference to recover the original read */ // TODO: if several Is in a row -- can we handle them together? // if Is are disjoint -- will handle them separately int is = 0; bool first_i = true; offset_since_last_cigar += edits[j+1] - Is; while (j < edits.size()) {// consume all Is if (edits[j] < 'V' || edits[j] > 'Z') { // not an I -- break the loop // cerr << "break loop 1 "; break; } else if (!first_i && edits[j+1] > 0) { // non contiguous Is -- break the loop // cerr << "break loop 2 j=" << j << " "; break; } is++; // cerr << (char)edits[j] << "-" << (int)edits[j+1] << ","; last_abs_pos += edits[j+1]; // insert the missing base read.insert(read.begin() + last_abs_pos, reverseReplace(edits[j]) );// insert a single char j += 2; first_i = false; // adjust by one base for every insert last_abs_pos++; } j--; assert(j < edits.size()); // cerr << "I's pos: " << last_abs_pos << " "; // trim the read to be of appropriate length read.resize(read_len); // update the global insertion counter Is += is; if (offset_since_last_cigar > 0) { cigar += to_string(offset_since_last_cigar); cigar += "M"; } cigar += to_string(is); cigar += "I"; last_cigar_edit_pos += offset_since_last_cigar + is; offset_since_last_cigar = 0; } break; default: { // handle mismatches j++; if (first_md_edit) { // cerr << "(+" << (int)edits[j] + Is << ") "; if (first_cigar_was_clip) { md_string += to_string(edits[j]); last_md_edit_pos += edits[j] + 1; } else { md_string += to_string(edits[j] + last_cigar_edit_pos - Is); last_md_edit_pos += edits[j] + last_cigar_edit_pos + 1; } first_md_edit = false; } else { // cerr << "(+" << (int)edits[j]-1+Is << ") "; md_string += to_string(edits[j] - 1); last_md_edit_pos += edits[j]; } last_abs_pos += edits[j]; // add the letter we see in the reference to the MD string md_string += read[last_abs_pos]; // add correct read to have its original base read[last_abs_pos] = op; offset_since_last_cigar += edits[j]; offset_since_last_md = 0; } } j++; } // update read w/ right soft/hard clip if it took place if (last_cigar_edit_pos < read_len) { if (right_cigar.size() > 0) { cigar += to_string(read_len - last_cigar_edit_pos - right_clip.length()); cigar += "M"; cigar += right_cigar; // update read w/ the right clip assert(read_len - right_clip.length() < read.size() ); read.replace(read_len - right_clip.length(), right_clip.length(), right_clip); } else { cigar += to_string(read_len - last_cigar_edit_pos); cigar += "M"; } } if (last_md_edit_pos < clipped_read_len) { md_string += to_string(clipped_read_len - last_md_edit_pos); } // cerr << cigar << "\t" << md_string << endl; // cerr << "Done w/ edits"; return read; } }; #endif
Kingsford-Group/referee
include/decompress/Decompressor.hpp
C++
gpl-3.0
22,429
import csv import decimal import os import datetime from stocker.common.events import EventStreamNew, EventStockOpen, EventStockClose from stocker.common.orders import OrderBuy, OrderSell from stocker.common.utils import Stream class CompanyProcessor(object): def __init__(self, dirname, company_id): self.dirname = os.path.join(dirname, company_id) self.company_id = company_id def get_dates(self): files = [os.path.splitext(fi)[0] for fi in os.walk(self.dirname).next()[2]] return files def get_row(self, date): filename = os.path.join(self.dirname, date) + ".csv" try: with open(filename, 'r') as f: for row in reversed(list(csv.reader(f, delimiter=';'))): try: desc = row[5] if desc.startswith('TRANSAKCJA'): yield (row, self.company_id) except IndexError: pass except IOError as e: return class Processor(object): def build_stream(self, dirname_in, filename_out): self.stream = Stream() self.stream.begin(filename_out) self.__process_companies(dirname_in) self.stream.end() def __process_companies(self, dirname): companies = [] for company in os.walk(dirname).next()[1]: companies.append(CompanyProcessor(dirname, company)) dates_set = set() for company in companies: dates_set.update(company.get_dates()) dates_ordered = sorted(dates_set, key=lambda date: datetime.datetime.strptime(date, "%Y-%m-%d")) for date in dates_ordered: self.__process_date(date, companies) def __process_date(self, date, companies): rows = [] correct_generators = [] correct_day = False generators = [company.get_row(date) for company in companies] for generator in generators: try: row, company_id = generator.next() row = (company_id, row, generator) rows.append(row) correct_generators.append(generator) except StopIteration as e: pass if correct_generators: # correct day (have transactions) correct_day = True if correct_day: self.stream.add_event(EventStockOpen( datetime.datetime.combine(datetime.datetime.strptime(date, "%Y-%m-%d"), datetime.time(9, 0)))) # main loop, multiplexing rows while correct_generators: row_data = min(rows, key=lambda row: datetime.datetime.strptime(row[1][0], "%H:%M:%S")) rows.remove(row_data) company_id, row, generator = row_data self.__process_row(row, date, company_id) try: row, company_id = generator.next() row = (company_id, row, generator) rows.append(row) except StopIteration as e: correct_generators.remove(generator) if correct_day: self.stream.add_event(EventStockClose( datetime.datetime.combine(datetime.datetime.strptime(date, "%Y-%m-%d"), datetime.time(18, 0)))) def __process_row(self, row, date, company_id): amount = int(row[3]) limit_price = decimal.Decimal(row[1].replace(',', '.')) timestamp = datetime.datetime.strptime("%s %s" % (date, row[0]), "%Y-%m-%d %H:%M:%S") expiration_date = timestamp + datetime.timedelta(days=1) self.stream.add_event( EventStreamNew(timestamp, OrderBuy(company_id, amount, limit_price, expiration_date))) self.stream.add_event( EventStreamNew(timestamp, OrderSell(company_id, amount, limit_price, expiration_date)))
donpiekarz/Stocker
stocker/SEP/processor.py
Python
gpl-3.0
3,868
/* * 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 sw13.executorNegative; import java.util.concurrent.Callable; /** * * @author Steve Ineichen */ public class WorkerCallable implements Callable { final private Worker worker; public WorkerCallable(Worker worker) { this.worker = worker; } @Override public Integer call() throws InterruptedException { worker.doWork(); return worker.getResult(); } }
Inux/nebsynch
SW13/src/sw13/executorNegative/WorkerCallable.java
Java
gpl-3.0
603
package com.gmail.altakey.ray; import android.app.Activity; import android.os.Bundle; import android.os.Parcelable; import android.net.Uri; import android.content.Intent; import android.widget.Toast; import android.util.Log; import android.net.http.AndroidHttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.util.EntityUtils; import java.io.File; import java.io.IOException; import java.util.Random; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.*; import android.os.AsyncTask; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.widget.EditText; import android.app.AlertDialog; import android.content.DialogInterface; import java.util.*; public class EnqueueActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final String action = getIntent().getAction(); final Bundle extras = getIntent().getExtras(); if (Intent.ACTION_SEND.equals(action)) { if (extras.containsKey(Intent.EXTRA_STREAM)) { new EnqueueTaskInvoker((Uri)extras.getParcelable(Intent.EXTRA_STREAM)).invokeOnFriend(); } } else if (Intent.ACTION_SEND_MULTIPLE.equals(action)) { if (extras.containsKey(Intent.EXTRA_STREAM)) { for (Parcelable p : extras.getParcelableArrayList(Intent.EXTRA_STREAM)) { new EnqueueTaskInvoker((Uri)p).invokeOnFriend(); } } } else { finish(); } } private class EnqueueTaskInvoker { private Uri mmForUri; private List<String> mmOptions = new LinkedList<String>(); public EnqueueTaskInvoker(Uri forUri) { mmForUri = forUri; mmOptions.add("(local)"); mmOptions.add("10.0.0.50"); mmOptions.add("10.0.0.52"); mmOptions.add("192.168.1.15"); mmOptions.add("192.168.1.17"); mmOptions.add("Other..."); } public void invokeOnFriend() { AlertDialog.Builder builder = new AlertDialog.Builder(EnqueueActivity.this); builder .setTitle(R.string.dialog_title_send_to) .setOnCancelListener(new CancelAction()) .setItems(mmOptions.toArray(new String[0]), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String choice = mmOptions.get(which); if (choice != null) { if ("Other...".equals(choice)) { LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate( R.layout.friend, (ViewGroup)findViewById(R.id.root)); AlertDialog.Builder builder = new AlertDialog.Builder(EnqueueActivity.this); EditText field = (EditText)layout.findViewById(R.id.name); builder .setTitle(R.string.dialog_title_send_to) .setView(layout) .setOnCancelListener(new CancelAction()) .setNegativeButton(android.R.string.cancel, new CancelAction()) .setPositiveButton(android.R.string.ok, new ConfirmAction(field)); dialog.dismiss(); builder.create().show(); } else if ("(local)".equals(choice)) { dialog.dismiss(); new EnqueueToFriendTask("localhost:8080", mmForUri).execute(); finish(); } else { dialog.dismiss(); new EnqueueToFriendTask(String.format("%s:8080", choice), mmForUri).execute(); finish(); } } else { dialog.dismiss(); } } }); builder.create().show(); } private class CancelAction implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); finish(); } } private class ConfirmAction implements DialogInterface.OnClickListener { private EditText mmmField; public ConfirmAction(EditText field) { mmmField = field; } @Override public void onClick(DialogInterface dialog, int which) { String name = mmmField.getText().toString(); dialog.dismiss(); new EnqueueToFriendTask(name, mmForUri).execute(); finish(); } } } private class EnqueueToFriendTask extends AsyncTask<Void, Void, Throwable> { private Uri mmUri; private String mmFriendAddress; public EnqueueToFriendTask(String friendAddress, Uri uri) { mmUri = uri; mmFriendAddress = friendAddress; } @Override public void onPreExecute() { Toast.makeText(EnqueueActivity.this, "Sending...", Toast.LENGTH_LONG).show(); } @Override public Throwable doInBackground(Void... args) { File tempFile = null; try { tempFile = new Cacher().cache(); new Enqueuer(tempFile).enqueue(); return null; } catch (IOException e) { Log.e("EA", "Cannot send to remote playlist", e); return e; } finally { if (tempFile != null) { tempFile.delete(); } } } @Override public void onPostExecute(Throwable ret) { if (ret == null) { Toast.makeText(EnqueueActivity.this, "Sent to remote playlist.", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(EnqueueActivity.this, "Cannot send to remote playlist", Toast.LENGTH_SHORT).show(); } } private class Enqueuer { private AndroidHttpClient mmmHttpClient; private File mmmBlob; public Enqueuer(File blob) { mmmHttpClient = AndroidHttpClient.newInstance(getUserAgent()); mmmBlob = blob; } private String getUserAgent() { return String.format("%s/%s", getString(R.string.app_name), "0.0.1"); } public void enqueue() throws IOException { HttpPost req = new HttpPost(String.format("http://%s", mmFriendAddress)); MultipartEntity entity = new MultipartEntity(); entity.addPart("stream", new FileBody(mmmBlob, "application/octet-stream")); req.setEntity(entity); int code = mmmHttpClient.execute(req).getStatusLine().getStatusCode(); Log.d("EA", String.format("posted, code=%d", code)); } } private class Cacher { public File cache() throws IOException { FileChannel src = null; FileChannel dest = null; File destFile = null; try { destFile = new File(root(), randomName()); src = new FileInputStream(getContentResolver().openFileDescriptor(mmUri, "r").getFileDescriptor()).getChannel(); dest = new FileOutputStream(destFile).getChannel(); dest.transferFrom(src, 0, Integer.MAX_VALUE); Log.d("MA", String.format("cached %s as %s", mmUri.toString(), destFile.getName())); return destFile; } catch (IOException e) { Log.e("MA", "cannot cache", e); destFile.delete(); throw e; } finally { if (src != null) { try { src.close(); } catch (IOException e) { } } if (dest != null) { try { dest.close(); } catch (IOException e) { } } } } private String randomName() { byte[] buffer = new byte[32]; new Random().nextBytes(buffer); StringBuilder sb = new StringBuilder(); try { for (byte b : MessageDigest.getInstance("MD5").digest(buffer)) { sb.append(Integer.toHexString(((int)b) & 0xff)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } private File root() { return getExternalFilesDir(null); } } } }
taky/ray
src/com/gmail/altakey/ray/EnqueueActivity.java
Java
gpl-3.0
10,120
package br.edu.utfpr.cm.pi.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import br.edu.utfpr.cm.pi.beans.UsuarioSistema; import br.edu.utfpr.cm.pi.ldap.LoginLDAP; @WebServlet(name = "LoginUsuarioServlet", urlPatterns = { "/LoginUsuarioServlet" }) public class LoginUsuarioServlet extends HttpServlet { private static final long serialVersionUID = 1L; public LoginUsuarioServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { service(request, response); } protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LoginLDAP ldap = new LoginLDAP(); String login = request.getParameter("login"); String senha = request.getParameter("senha"); UsuarioSistema usuario = ldap.logarNoLDAP(login, senha); if (usuario != null) { HttpSession sessao = request.getSession(true); sessao.setAttribute("usuario", usuario); response.sendRedirect("bemvindoUsuario.jsp"); } else { response.sendRedirect("loginInvalidoUsuario.jsp"); } } }
sergioramossilva/Sistema-Pagamento-RU
src/main/java/br/edu/utfpr/cm/pi/controller/LoginUsuarioServlet.java
Java
gpl-3.0
1,740
/* * GrGen: graph rewrite generator tool -- release GrGen.NET 4.4 * Copyright (C) 2003-2015 Universitaet Karlsruhe, Institut fuer Programmstrukturen und Datenorganisation, LS Goos; and free programmers * licensed under LGPL v3 (see LICENSE.txt included in the packaging of this file) * www.grgen.net */ // by Edgar Jakumeit using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using de.unika.ipd.grGen.libGr; using de.unika.ipd.grGen.lgsp; namespace de.unika.ipd.grGen.lgsp { /// <summary> /// A class for building the interpretation plan data structure from a scheduled search plan /// </summary> public class InterpretationPlanBuilder { // the scheduled search plan to build an interpretation plan for private ScheduledSearchPlan ssp; // the search plan graph for determining the pattern element needed for attribute checking private SearchPlanGraph spg; // the model over which the patterns are to be searched private IGraphModel model; /// <summary> /// Creates an interpretation plan builder for the given scheduled search plan. /// Only a limited amount of search operations is supported, the ones needed for isomorphy checking. /// </summary> /// <param name="ssp">the scheduled search plan to build an interpretation plan for</param> /// <param name="spg">the search plan graph for determining the pattern element needed for attribute checking</param> /// <param name="model">the model over which the patterns are to be searched</param> public InterpretationPlanBuilder(ScheduledSearchPlan ssp, SearchPlanGraph spg, IGraphModel model) { this.ssp = ssp; this.spg = spg; this.model = model; } /// <summary> /// Builds interpretation plan from scheduled search plan. /// </summary> public InterpretationPlan BuildInterpretationPlan(string comparisonMatcherName) { // create the start operation which is a nop but needed as first insertion point InterpretationPlan plan = new InterpretationPlanStart(comparisonMatcherName); // build the interpretation plan into it, starting with the search operation at position 0 in the scheduled search plan BuildInterpretationPlan(plan, 0); // clean the helper variables in the search plan nodes used in building the interpretation plan for(int i = 0; i < ssp.Operations.Length; ++i) { if(ssp.Operations[i].Element is SearchPlanNodeNode) { SearchPlanNodeNode node = ssp.Operations[i].Element as SearchPlanNodeNode; node.nodeMatcher = null; } else if(ssp.Operations[i].Element is SearchPlanEdgeNode) { SearchPlanEdgeNode edge = ssp.Operations[i].Element as SearchPlanEdgeNode; edge.edgeMatcher = null; edge.directionVariable = null; } } // and return the plan starting with the created start operation return plan; } /// <summary> /// Recursively assembles interpretation plan from scheduled search plan, beginning at index 0. /// Decides which specialized build procedure is to be called. /// The specialized build procedure then calls this procedure again, /// in order to process the next search plan operation at the following index. /// The insertionPoint is the lastly built operation; /// the next operation built is inserted into the next link of it, /// then it becomes the current insertionPoint. /// </summary> private void BuildInterpretationPlan(InterpretationPlan insertionPoint, int index) { if (index >= ssp.Operations.Length) { // end of scheduled search plan reached, stop recursive iteration buildMatchComplete(insertionPoint); return; } SearchOperation op = ssp.Operations[index]; // for current scheduled search plan operation // insert corresponding interpretation plan operations into interpretation plan switch (op.Type) { case SearchOperationType.Lookup: if(((SearchPlanNode)op.Element).NodeType == PlanNodeType.Node) buildLookup(insertionPoint, index, (SearchPlanNodeNode)op.Element); else buildLookup(insertionPoint, index, (SearchPlanEdgeNode)op.Element); break; case SearchOperationType.ImplicitSource: buildImplicit(insertionPoint, index, (SearchPlanEdgeNode)op.SourceSPNode, (SearchPlanNodeNode)op.Element, ImplicitNodeType.Source); break; case SearchOperationType.ImplicitTarget: buildImplicit(insertionPoint, index, (SearchPlanEdgeNode)op.SourceSPNode, (SearchPlanNodeNode)op.Element, ImplicitNodeType.Target); break; case SearchOperationType.Implicit: buildImplicit(insertionPoint, index, (SearchPlanEdgeNode)op.SourceSPNode, (SearchPlanNodeNode)op.Element, ImplicitNodeType.SourceOrTarget); break; case SearchOperationType.Incoming: buildIncident(insertionPoint, index, (SearchPlanNodeNode)op.SourceSPNode, (SearchPlanEdgeNode)op.Element, IncidentEdgeType.Incoming); break; case SearchOperationType.Outgoing: buildIncident(insertionPoint, index, (SearchPlanNodeNode)op.SourceSPNode, (SearchPlanEdgeNode)op.Element, IncidentEdgeType.Outgoing); break; case SearchOperationType.Incident: buildIncident(insertionPoint, index, (SearchPlanNodeNode)op.SourceSPNode, (SearchPlanEdgeNode)op.Element, IncidentEdgeType.IncomingOrOutgoing); break; case SearchOperationType.Condition: buildCondition(insertionPoint, index, (PatternCondition)op.Element); break; default: throw new Exception("Unknown or unsupported search operation"); } } /// <summary> /// Interpretation plan operations implementing the /// Lookup node search plan operation /// are created and inserted into the interpretation plan at the insertion point /// </summary> private void buildLookup( InterpretationPlan insertionPoint, int index, SearchPlanNodeNode target) { // get candidate = iterate available nodes target.nodeMatcher = new InterpretationPlanLookupNode(target.PatternElement.TypeID, target); target.nodeMatcher.prev = insertionPoint; insertionPoint.next = target.nodeMatcher; insertionPoint = insertionPoint.next; // check connectedness of candidate insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFromLookup(insertionPoint, target); // continue with next operation target.Visited = true; BuildInterpretationPlan(insertionPoint, index + 1); target.Visited = false; } /// <summary> /// Interpretation plan operations implementing the /// Lookup edge search plan operation /// are created and inserted into the interpretation plan at the insertion point /// </summary> private void buildLookup( InterpretationPlan insertionPoint, int index, SearchPlanEdgeNode target) { // get candidate = iterate available edges target.edgeMatcher = new InterpretationPlanLookupEdge(target.PatternElement.TypeID, target); target.edgeMatcher.prev = insertionPoint; insertionPoint.next = target.edgeMatcher; insertionPoint = insertionPoint.next; // check connectedness of candidate insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFromLookup(insertionPoint, target); // continue with next operation target.Visited = true; BuildInterpretationPlan(insertionPoint, index + 1); target.Visited = false; } /// <summary> /// Interpretation plan operations implementing the /// Implicit Source|Target|SourceOrTarget search plan operation /// are created and inserted into the interpretation plan at the insertion point /// </summary> private void buildImplicit( InterpretationPlan insertionPoint, int index, SearchPlanEdgeNode source, SearchPlanNodeNode target, ImplicitNodeType nodeType) { // get candidate = demanded node from edge insertionPoint = insertImplicitNodeFromEdge(insertionPoint, source, target, nodeType); // check connectedness of candidate SearchPlanNodeNode otherNodeOfOriginatingEdge = null; if (nodeType == ImplicitNodeType.Source) otherNodeOfOriginatingEdge = source.PatternEdgeTarget; if (nodeType == ImplicitNodeType.Target) otherNodeOfOriginatingEdge = source.PatternEdgeSource; if (source.PatternEdgeTarget == source.PatternEdgeSource) // reflexive sign needed in unfixed direction case, too otherNodeOfOriginatingEdge = source.PatternEdgeSource; insertionPoint = decideOnAndInsertCheckConnectednessOfImplicitNodeFromEdge(insertionPoint, target, source, otherNodeOfOriginatingEdge); // continue with next operation target.Visited = true; BuildInterpretationPlan(insertionPoint, index + 1); target.Visited = false; } /// <summary> /// Interpretation plan operations implementing the /// Extend Incoming|Outgoing|IncomingOrOutgoing search plan operation /// are created and inserted into the interpretation plan at the insertion point /// </summary> private void buildIncident( InterpretationPlan insertionPoint, int index, SearchPlanNodeNode source, SearchPlanEdgeNode target, IncidentEdgeType edgeType) { // get candidate = iterate available incident edges insertionPoint = insertIncidentEdgeFromNode(insertionPoint, source, target, edgeType); // check connectedness of candidate insertionPoint = decideOnAndInsertCheckConnectednessOfIncidentEdgeFromNode(insertionPoint, target, source, edgeType==IncidentEdgeType.Incoming); // continue with next operation target.Visited = true; BuildInterpretationPlan(insertionPoint, index + 1); target.Visited = false; } /// <summary> /// Interpretation plan operations implementing the /// CheckCondition search plan operation /// are created and inserted into the interpretation plan at the insertion point /// </summary> private void buildCondition( InterpretationPlan insertionPoint, int index, PatternCondition condition) { // check condition expression.AreAttributesEqual aae = (expression.AreAttributesEqual)condition.ConditionExpression; foreach(SearchPlanNode spn in spg.Nodes) { if(spn.PatternElement == aae.thisInPattern) { InterpretationPlanCheckCondition checkCondition; if(spn is SearchPlanNodeNode) { SearchPlanNodeNode nodeNode = (SearchPlanNodeNode)spn; checkCondition = new InterpretationPlanCheckCondition( aae, nodeNode.nodeMatcher, Array.IndexOf(aae.thisInPattern.pointOfDefinition.nodes, aae.thisInPattern)); } else { SearchPlanEdgeNode edgeNode = (SearchPlanEdgeNode)spn; checkCondition = new InterpretationPlanCheckCondition( aae, edgeNode.edgeMatcher, Array.IndexOf(aae.thisInPattern.pointOfDefinition.edges, aae.thisInPattern)); } checkCondition.prev = insertionPoint; insertionPoint.next = checkCondition; insertionPoint = insertionPoint.next; // continue with next operation BuildInterpretationPlan(insertionPoint, index + 1); return; } } throw new Exception("Internal error constructing interpretation plan!"); } /// <summary> /// The closing matching completed interpretation plan operation is added at the insertion point /// </summary> private void buildMatchComplete(InterpretationPlan insertionPoint) { insertionPoint.next = new InterpretationPlanMatchComplete( ssp.PatternGraph.nodesPlusInlined.Length, ssp.PatternGraph.edgesPlusInlined.Length); insertionPoint.next.prev = insertionPoint; } /////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Inserts code to get an implicit node from an edge /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan insertImplicitNodeFromEdge( InterpretationPlan insertionPoint, SearchPlanEdgeNode edge, SearchPlanNodeNode currentNode, ImplicitNodeType nodeType) { int targetType = currentNode.PatternElement.TypeID; if (nodeType == ImplicitNodeType.Source) { currentNode.nodeMatcher = new InterpretationPlanImplicitSource(targetType, edge.edgeMatcher, currentNode); } else if(nodeType == ImplicitNodeType.Target) { currentNode.nodeMatcher = new InterpretationPlanImplicitTarget(targetType, edge.edgeMatcher, currentNode); } else { Debug.Assert(nodeType != ImplicitNodeType.TheOther); if (currentNodeIsSecondIncidentNodeOfEdge(currentNode, edge)) { currentNode.nodeMatcher = new InterpretationPlanImplicitTheOther(targetType, edge.edgeMatcher, edge.PatternEdgeSource == currentNode ? edge.PatternEdgeTarget.nodeMatcher : edge.PatternEdgeSource.nodeMatcher, currentNode); } else // edge connects to first incident node { if (edge.PatternEdgeSource == edge.PatternEdgeTarget) { // reflexive edge without direction iteration as we don't want 2 matches currentNode.nodeMatcher = new InterpretationPlanImplicitSource(targetType, edge.edgeMatcher, currentNode); } else { edge.directionVariable = new InterpretationPlanBothDirections(); insertionPoint.next = edge.directionVariable; insertionPoint = insertionPoint.next; currentNode.nodeMatcher = new InterpretationPlanImplicitSourceOrTarget(targetType, edge.edgeMatcher, edge.directionVariable, currentNode); } } } currentNode.nodeMatcher.prev = insertionPoint; insertionPoint.next = currentNode.nodeMatcher; insertionPoint = insertionPoint.next; return insertionPoint; } /// <summary> /// Inserts code to get an incident edge from some node /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan insertIncidentEdgeFromNode( InterpretationPlan insertionPoint, SearchPlanNodeNode node, SearchPlanEdgeNode currentEdge, IncidentEdgeType incidentType) { int targetType = currentEdge.PatternElement.TypeID; if (incidentType == IncidentEdgeType.Incoming) { currentEdge.edgeMatcher = new InterpretationPlanIncoming(targetType, node.nodeMatcher, currentEdge); } else if(incidentType == IncidentEdgeType.Outgoing) { currentEdge.edgeMatcher = new InterpretationPlanOutgoing(targetType, node.nodeMatcher, currentEdge); } else // IncidentEdgeType.IncomingOrOutgoing { if (currentEdge.PatternEdgeSource == currentEdge.PatternEdgeTarget) { // reflexive edge without direction iteration as we don't want 2 matches currentEdge.edgeMatcher = new InterpretationPlanIncoming(targetType, node.nodeMatcher, currentEdge); } else { currentEdge.directionVariable = new InterpretationPlanBothDirections(); insertionPoint.next = currentEdge.directionVariable; insertionPoint = insertionPoint.next; currentEdge.edgeMatcher = new InterpretationPlanIncomingOrOutgoing(targetType, node.nodeMatcher, currentEdge.directionVariable, currentEdge); } } currentEdge.edgeMatcher.prev = insertionPoint; insertionPoint.next = currentEdge.edgeMatcher; insertionPoint = insertionPoint.next; return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given node just determined by lookup /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfNodeFromLookup( InterpretationPlan insertionPoint, SearchPlanNodeNode node) { // check for edges required by the pattern to be incident to the given node foreach (SearchPlanEdgeNode edge in node.OutgoingPatternEdges) { if (((PatternEdge)edge.PatternElement).fixedDirection || edge.PatternEdgeSource == edge.PatternEdgeTarget) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFixedDirection(insertionPoint, node, edge, CheckCandidateForConnectednessType.Source); } else { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeBothDirections(insertionPoint, node, edge); } } foreach (SearchPlanEdgeNode edge in node.IncomingPatternEdges) { if (((PatternEdge)edge.PatternElement).fixedDirection || edge.PatternEdgeSource == edge.PatternEdgeTarget) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFixedDirection(insertionPoint, node, edge, CheckCandidateForConnectednessType.Target); } else { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeBothDirections(insertionPoint, node, edge); } } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given node just drawn from edge /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfImplicitNodeFromEdge( InterpretationPlan insertionPoint, SearchPlanNodeNode node, SearchPlanEdgeNode originatingEdge, SearchPlanNodeNode otherNodeOfOriginatingEdge) { // check for edges required by the pattern to be incident to the given node // only if the node was not taken from the given originating edge // with the exception of reflexive edges, as these won't get checked thereafter foreach (SearchPlanEdgeNode edge in node.OutgoingPatternEdges) { if (((PatternEdge)edge.PatternElement).fixedDirection || edge.PatternEdgeSource == edge.PatternEdgeTarget) { if (edge != originatingEdge || node == otherNodeOfOriginatingEdge) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFixedDirection(insertionPoint, node, edge, CheckCandidateForConnectednessType.Source); } } else { if (edge != originatingEdge || node == otherNodeOfOriginatingEdge) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeBothDirections(insertionPoint, node, edge); } } } foreach (SearchPlanEdgeNode edge in node.IncomingPatternEdges) { if (((PatternEdge)edge.PatternElement).fixedDirection || edge.PatternEdgeSource == edge.PatternEdgeTarget) { if (edge != originatingEdge || node == otherNodeOfOriginatingEdge) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeFixedDirection(insertionPoint, node, edge, CheckCandidateForConnectednessType.Target); } } else { if (edge != originatingEdge || node == otherNodeOfOriginatingEdge) { insertionPoint = decideOnAndInsertCheckConnectednessOfNodeBothDirections(insertionPoint, node, edge); } } } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given node and edge of fixed direction /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfNodeFixedDirection( InterpretationPlan insertionPoint, SearchPlanNodeNode currentNode, SearchPlanEdgeNode edge, CheckCandidateForConnectednessType connectednessType) { Debug.Assert(connectednessType == CheckCandidateForConnectednessType.Source || connectednessType == CheckCandidateForConnectednessType.Target); // check whether the pattern edges which must be incident to the candidate node (according to the pattern) // are really incident to it // only if edge is already matched by now (signaled by visited) if (edge.Visited) { if(connectednessType == CheckCandidateForConnectednessType.Source) { insertionPoint.next = new InterpretationPlanCheckConnectednessSource( currentNode.nodeMatcher, edge.edgeMatcher); insertionPoint = insertionPoint.next; } else //if(connectednessType == CheckCandidateForConnectednessType.Target) { insertionPoint.next = new InterpretationPlanCheckConnectednessTarget( currentNode.nodeMatcher, edge.edgeMatcher); insertionPoint = insertionPoint.next; } } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given node and edge in both directions /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfNodeBothDirections( InterpretationPlan insertionPoint, SearchPlanNodeNode currentNode, SearchPlanEdgeNode edge) { Debug.Assert(edge.PatternEdgeSource != edge.PatternEdgeTarget); // check whether the pattern edges which must be incident to the candidate node (according to the pattern) // are really incident to it if (currentNodeIsFirstIncidentNodeOfEdge(currentNode, edge)) { edge.directionVariable = new InterpretationPlanBothDirections(); insertionPoint.next = edge.directionVariable; insertionPoint = insertionPoint.next; insertionPoint.next = new InterpretationPlanCheckConnectednessSourceOrTarget( currentNode.nodeMatcher, edge.edgeMatcher, edge.directionVariable); insertionPoint = insertionPoint.next; } if (currentNodeIsSecondIncidentNodeOfEdge(currentNode, edge)) { insertionPoint.next = new InterpretationPlanCheckConnectednessTheOther( currentNode.nodeMatcher, edge.edgeMatcher, edge.PatternEdgeSource == currentNode ? edge.PatternEdgeTarget.nodeMatcher : edge.PatternEdgeSource.nodeMatcher); insertionPoint = insertionPoint.next; } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given edge determined by lookup /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfEdgeFromLookup( InterpretationPlan insertionPoint, SearchPlanEdgeNode edge) { if (((PatternEdge)edge.PatternElement).fixedDirection) { // don't need to check if the edge is not required by the pattern to be incident to some given node if (edge.PatternEdgeSource != null) { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFixedDirection(insertionPoint, edge, CheckCandidateForConnectednessType.Source); } if (edge.PatternEdgeTarget != null) { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFixedDirection(insertionPoint, edge, CheckCandidateForConnectednessType.Target); } } else { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeBothDirections(insertionPoint, edge, false); } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given edge determined from incident node /// and inserts them into the interpretation plan /// receives insertion point, returns new insertions point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfIncidentEdgeFromNode( InterpretationPlan insertionPoint, SearchPlanEdgeNode edge, SearchPlanNodeNode originatingNode, bool edgeIncomingAtOriginatingNode) { if (((PatternEdge)edge.PatternElement).fixedDirection) { // don't need to check if the edge is not required by the pattern to be incident to some given node // or if the edge was taken from the given originating node if (edge.PatternEdgeSource != null) { if (!(!edgeIncomingAtOriginatingNode && edge.PatternEdgeSource == originatingNode)) { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFixedDirection(insertionPoint, edge, CheckCandidateForConnectednessType.Source); } } if (edge.PatternEdgeTarget != null) { if (!(edgeIncomingAtOriginatingNode && edge.PatternEdgeTarget == originatingNode)) { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeFixedDirection(insertionPoint, edge, CheckCandidateForConnectednessType.Target); } } } else { insertionPoint = decideOnAndInsertCheckConnectednessOfEdgeBothDirections(insertionPoint, edge, true); } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given edge of fixed direction /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfEdgeFixedDirection( InterpretationPlan insertionPoint, SearchPlanEdgeNode edge, CheckCandidateForConnectednessType connectednessType) { Debug.Assert(connectednessType == CheckCandidateForConnectednessType.Source || connectednessType == CheckCandidateForConnectednessType.Target); // check whether source/target-nodes of the candidate edge // are the same as the already found nodes to which the edge must be incident // don't need to, if that node is not matched by now (signaled by visited) SearchPlanNodeNode nodeRequiringCheck = connectednessType == CheckCandidateForConnectednessType.Source ? edge.PatternEdgeSource : edge.PatternEdgeTarget; if (nodeRequiringCheck.Visited) { if(connectednessType == CheckCandidateForConnectednessType.Source) { insertionPoint.next = new InterpretationPlanCheckConnectednessSource( nodeRequiringCheck.nodeMatcher, edge.edgeMatcher); insertionPoint = insertionPoint.next; } else //if(connectednessType == CheckCandidateForConnectednessType.Target) { insertionPoint.next = new InterpretationPlanCheckConnectednessTarget( nodeRequiringCheck.nodeMatcher, edge.edgeMatcher); insertionPoint = insertionPoint.next; } } return insertionPoint; } /// <summary> /// Decides which check connectedness operations are needed for the given edge in both directions /// and inserts them into the interpretation plan /// receives insertion point, returns new insertion point /// </summary> private InterpretationPlan decideOnAndInsertCheckConnectednessOfEdgeBothDirections( InterpretationPlan insertionPoint, SearchPlanEdgeNode edge, bool edgeDeterminationContainsFirstNodeLoop) { // check whether source/target-nodes of the candidate edge // are the same as the already found nodes to which the edge must be incident if (!edgeDeterminationContainsFirstNodeLoop && currentEdgeConnectsToFirstIncidentNode(edge)) { SearchPlanNodeNode nodeRequiringFirstNodeLoop = edge.PatternEdgeSource != null ? edge.PatternEdgeSource : edge.PatternEdgeTarget; // due to currentEdgeConnectsToFirstIncidentNode: at least on incident node available if (edge.PatternEdgeSource == edge.PatternEdgeTarget) { // reflexive edge without direction iteration as we don't want 2 matches insertionPoint.next = new InterpretationPlanCheckConnectednessSource( nodeRequiringFirstNodeLoop.nodeMatcher, edge.edgeMatcher); // might be Target as well insertionPoint = insertionPoint.next; } else { edge.directionVariable = new InterpretationPlanBothDirections(); insertionPoint.next = edge.directionVariable; insertionPoint = insertionPoint.next; insertionPoint.next = new InterpretationPlanCheckConnectednessSourceOrTarget( nodeRequiringFirstNodeLoop.nodeMatcher, edge.edgeMatcher, edge.directionVariable); insertionPoint = insertionPoint.next; } } if (currentEdgeConnectsToSecondIncidentNode(edge)) { // due to currentEdgeConnectsToSecondIncidentNode: both incident node available insertionPoint.next = new InterpretationPlanCheckConnectednessTheOther( edge.PatternEdgeTarget.nodeMatcher, edge.edgeMatcher, edge.PatternEdgeSource.nodeMatcher); insertionPoint = insertionPoint.next; } return insertionPoint; } /////////////////////////////////////////////////////////////////////////////////// /// <summary> /// returns true if the node which gets currently determined in the schedule /// is the first incident node of the edge which gets connected to it /// only of interest for edges of unfixed direction /// </summary> private bool currentNodeIsFirstIncidentNodeOfEdge( SearchPlanNodeNode currentNode, SearchPlanEdgeNode edge) { //Debug.Assert(!currentNode.Visited); Debug.Assert(!((PatternEdge)edge.PatternElement).fixedDirection); if (!edge.Visited) return false; if (currentNode == edge.PatternEdgeSource) return edge.PatternEdgeTarget==null || !edge.PatternEdgeTarget.Visited; else return edge.PatternEdgeSource==null || !edge.PatternEdgeSource.Visited; } /// <summary> /// returns true if the node which gets currently determined in the schedule /// is the second incident node of the edge which gets connected to it /// only of interest for edges of unfixed direction /// </summary> private bool currentNodeIsSecondIncidentNodeOfEdge( SearchPlanNodeNode currentNode, SearchPlanEdgeNode edge) { //Debug.Assert(!currentNode.Visited); Debug.Assert(!((PatternEdge)edge.PatternElement).fixedDirection); if (!edge.Visited) return false; if (edge.PatternEdgeSource == null || edge.PatternEdgeTarget == null) return false; if (currentNode == edge.PatternEdgeSource) return edge.PatternEdgeTarget.Visited; else return edge.PatternEdgeSource.Visited; } /// <summary> /// returns true if only one incident node of the edge which gets currently determined in the schedule /// was already computed; only of interest for edges of unfixed direction /// </summary> private bool currentEdgeConnectsOnlyToFirstIncidentNode(SearchPlanEdgeNode currentEdge) { //Debug.Assert(!currentEdge.Visited); Debug.Assert(!((PatternEdge)currentEdge.PatternElement).fixedDirection); if (currentEdge.PatternEdgeSource != null && currentEdge.PatternEdgeSource.Visited && (currentEdge.PatternEdgeTarget == null || !currentEdge.PatternEdgeTarget.Visited)) { return true; } if (currentEdge.PatternEdgeTarget != null && currentEdge.PatternEdgeTarget.Visited && (currentEdge.PatternEdgeSource == null || !currentEdge.PatternEdgeSource.Visited)) { return true; } return false; } /// <summary> /// returns true if at least one incident node of the edge which gets currently determined in the schedule /// was already computed; only of interest for edges of unfixed direction /// </summary> private bool currentEdgeConnectsToFirstIncidentNode(SearchPlanEdgeNode currentEdge) { //Debug.Assert(!currentEdge.Visited); Debug.Assert(!((PatternEdge)currentEdge.PatternElement).fixedDirection); if (currentEdge.PatternEdgeSource != null && currentEdge.PatternEdgeSource.Visited) return true; if (currentEdge.PatternEdgeTarget != null && currentEdge.PatternEdgeTarget.Visited) return true; return false; } /// <summary> /// returns true if both incident nodes of the edge which gets currently determined in the schedule /// were already computed; only of interest for edges of unfixed direction /// </summary> private bool currentEdgeConnectsToSecondIncidentNode(SearchPlanEdgeNode currentEdge) { //Debug.Assert(!currentEdge.Visited); Debug.Assert(!((PatternEdge)currentEdge.PatternElement).fixedDirection); if (currentEdge.PatternEdgeSource == null || currentEdge.PatternEdgeTarget == null) return false; if (currentEdge.PatternEdgeSource.Visited && currentEdge.PatternEdgeTarget.Visited) return true; return false; } } }
jblomer/GrGen.NET
engine-net-2/src/lgspBackend/InterpretationPlanBuilder.cs
C#
gpl-3.0
39,542
<?php defined('SYSPATH') or die('No direct script access allowed.'); /******************************************************************************* * ExidoEngine Content Management System * * NOTICE OF LICENSE * * This source file is subject to the GNU General Public License (3.0) * that is bundled with this package in the file license_en.txt * It is also available through the world-wide-web at this URL: * http://exidoengine.com/license/gpl-3.0.html * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@exidoengine.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade ExidoEngine to newer * versions in the future. If you wish to customize ExidoEngine for your * needs please refer to http://www.exidoengine.com for more information. * * @license http://exidoengine.com/license/gpl-3.0.html (GNU General Public License v3) * @author ExidoTeam * @copyright Copyright (c) 2009 - 2012, ExidoEngine Solutions * @link http://exidoengine.com/ * @since Version 1.0 * @filesource *******************************************************************************/ /** * Image manipulation class. * @package core * @subpackage image * @copyright Sharapov A. * @created 29/01/2010 * @version 1.0 */ abstract class Image_Base { public $source_image_path = ''; public $new_image_path = ''; public $create_thumb = true; public $thumb_prfx = '_tmb_'; /* * Whether to maintain aspect ratio when resizing or use hard values * @var */ public $maintain_ratio = true; /* * auto, height, or width. Determines what to use as the master dimension * @var */ public $master_dim = 'auto'; public $rotation_angle = ''; public $x_axis = ''; public $y_axis = ''; public $width = ''; public $height = ''; public $quality = '90'; public $action = ''; public $increase_small = false; public $actions = array(); /* * Allowed mimes */ public $mimes = array( 'jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif' ); // --------------------------------------------------------------------------- /** * Constructor. * @param null $params */ public function __construct($params = null) { if( ! is_array($params)) { $params = array(); } $params['degs'] = range(1, 360); if( ! isset($params['mimes'])) { // Get mimes from config file if($mimes = Exido::config('mime.image')) { $params['mimes'] = $mimes; } } $this->setup($params); } // --------------------------------------------------------------------------- /** * Setup image preferences. * @param array $params * @return void */ public function setup(array $params) { // Convert array elements into class properties if(count($params) > 0) { foreach($params as $key => $val) { $this->$key = $val; } } } // --------------------------------------------------------------------------- /** * Resets the values in case this class is used in a loop. * @return void */ public function clear() { $props = array( '_source_folder', '_dest_folder', 'source_image_path', '_full_src_path', '_full_dst_path', 'new_image_path', '_image_type', '_size_str', 'quality', '_orig_width', '_orig_height', 'rotation_angle', 'x_axis', 'y_axis', 'wm_overlay_path', 'wm_use_truetype', 'wm_font_size', 'wm_text', 'wm_vrt_alignment', 'wm_hor_alignment', 'wm_padding', 'wm_hor_offset', 'wm_vrt_offset', 'wm_font_color', 'wm_use_drop_shadow', 'wm_shadow_color', 'wm_shadow_distance', 'wm_opacity' ); foreach($props as $val) { $this->$val = ''; } // Special consideration for master_dim $this->master_dim = 'auto'; } // --------------------------------------------------------------------------- /** * Throws a processed image to browser. * @return void */ public function get() { $this->_display = true; if($this->action == 'base64') { return $this->_processImage(); } $this->_processImage(); } // --------------------------------------------------------------------------- /** * Saves a processed image to disk. * @return mixed */ public function save() { $this->_display = false; return $this->_processImage(); } // --------------------------------------------------------------------------- /** * Explodes an image filename. * @param string $image * @return array */ public function explodeName($image) { $ext = strrchr($image, '.'); if($ext === false) { $name = $image; } else { $name = substr($image, 0, -strlen($ext)); $ext = ($ext == '.jpeg') ? '.jpg' : $ext; } return array ( 'ext' => $ext, 'name' => $name ); } // --------------------------------------------------------------------------- /** * Re-proportion Image Width/Height * * When creating thumbs, the desired width/height * can end up warping the image due to an incorrect * ratio between the full-sized image and the thumb. * * This function lets us re-proportion the width/height * if users choose to maintain the aspect ratio when resizing. * @return void */ protected function _reproportionImage() { if( ! is_numeric($this->width) or ! is_numeric($this->height) or $this->width == 0 or $this->height == 0) { return; } if( ! is_numeric($this->_orig_width) or ! is_numeric($this->_orig_height) or $this->_orig_width == 0 or $this->_orig_height == 0) { return; } $new_width = ceil($this->_orig_width * $this->height/$this->_orig_height); $new_height = ceil($this->width * $this->_orig_height/$this->_orig_width); $ratio = (($this->_orig_height/$this->_orig_width) - ($this->height/$this->width)); if($this->master_dim != 'width' and $this->master_dim != 'height') { $this->master_dim = ($ratio < 0) ? 'width' : 'height'; } if(($this->width != $new_width) and ($this->height != $new_height)) { if($this->master_dim == 'height') { $this->width = $new_width; } else { $this->height = $new_height; } } } } ?>
sharapovweb/exidoengine
lib/exido/image/base.php
PHP
gpl-3.0
6,591
using System; using Org.BouncyCastle.Asn1.Pkcs; namespace Org.BouncyCastle.Asn1.Smime { public class SmimeCapability : Asn1Encodable { /** * general preferences */ public static readonly DerObjectIdentifier PreferSignedData = PkcsObjectIdentifiers.PreferSignedData; public static readonly DerObjectIdentifier CannotDecryptAny = PkcsObjectIdentifiers.CannotDecryptAny; public static readonly DerObjectIdentifier SmimeCapabilitiesVersions = PkcsObjectIdentifiers.SmimeCapabilitiesVersions; /** * encryption algorithms preferences */ public static readonly DerObjectIdentifier DesCbc = new DerObjectIdentifier("1.3.14.3.2.7"); public static readonly DerObjectIdentifier DesEde3Cbc = PkcsObjectIdentifiers.DesEde3Cbc; public static readonly DerObjectIdentifier RC2Cbc = PkcsObjectIdentifiers.RC2Cbc; private DerObjectIdentifier capabilityID; private Asn1Object parameters; public SmimeCapability( Asn1Sequence seq) { capabilityID = (DerObjectIdentifier) seq[0].ToAsn1Object(); if (seq.Count > 1) { parameters = seq[1].ToAsn1Object(); } } public SmimeCapability( DerObjectIdentifier capabilityID, Asn1Encodable parameters) { if (capabilityID == null) throw new ArgumentNullException("capabilityID"); this.capabilityID = capabilityID; if (parameters != null) { this.parameters = parameters.ToAsn1Object(); } } public static SmimeCapability GetInstance( object obj) { if (obj == null || obj is SmimeCapability) { return (SmimeCapability) obj; } if (obj is Asn1Sequence) { return new SmimeCapability((Asn1Sequence) obj); } throw new ArgumentException("Invalid SmimeCapability"); } public DerObjectIdentifier CapabilityID { get { return capabilityID; } } public Asn1Object Parameters { get { return parameters; } } /** * Produce an object suitable for an Asn1OutputStream. * <pre> * SMIMECapability ::= Sequence { * capabilityID OBJECT IDENTIFIER, * parameters ANY DEFINED BY capabilityID OPTIONAL * } * </pre> */ public override Asn1Object ToAsn1Object() { Asn1EncodableVector v = new Asn1EncodableVector(capabilityID); if (parameters != null) { v.Add(parameters); } return new DerSequence(v); } } }
DSorlov/Sorlov.PowerShell
Sorlov.PowerShell/Lib/BouncyCastle/asn1/smime/SMIMECapability.cs
C#
gpl-3.0
2,695
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProyectoFinalMacoRios { public class Garaje:Propiedades { string abierto; string bodega; public string Abierto { get { return abierto; } set { abierto = value; } } public string Bodega { get { return bodega; } set { bodega = value; } } } }
MacoRios1/ProyectoFinalM
ProyectoFinalMacoRios/ProyectoFinalMacoRios/Garaje.cs
C#
gpl-3.0
627
package com.github.cypher.gui.root.roomcollection; import com.airhacks.afterburner.views.FXMLView; public class RoomCollectionView extends FXMLView { }
Gurgy/Cypher
src/main/java/com/github/cypher/gui/root/roomcollection/RoomCollectionView.java
Java
gpl-3.0
154
<?php namespace reservas\Http\Controllers\Auth; use reservas\User; use reservas\Rol; use Validator; use reservas\Http\Controllers\Controller; use Illuminate\Foundation\Auth\ThrottlesLogins; use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Route; use Illuminate\Routing\Redirector; class AuthController extends Controller { /* |-------------------------------------------------------------------------- | Registration & Login Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users, as well as the | authentication of existing users. By default, this controller uses | a simple trait to add these behaviors. Why don't you explore it? | */ use AuthenticatesAndRegistersUsers, ThrottlesLogins; /** * Where to redirect users after login / registration. * * @var string */ protected $redirectTo = '/'; /** * Create a new authentication controller instance. * * @return void */ public function __construct(Redirector $redirect=null) { //Lista de acciones que no requieren autenticación $arrActionsLogin = [ 'logout', 'login', 'getLogout', 'showLoginForm', ]; //Lista de acciones que solo puede realizar los administradores $arrActionsAdmin = [ 'index', 'edit', 'show', 'update', 'destroy', 'register', 'showRegistrationForm', 'getRegister', 'postRegister', ]; //Requiere que el usuario inicie sesión, excepto en la vista logout. $this->middleware('auth', [ 'except' => $arrActionsLogin ]); if(auth()->check() && isset($redirect)){ //Compatibilidad con el comando "php artisan route:list", ya que ingresa como guest y la ruta es nula. $action = Route::currentRouteAction(); $ROLE_ID = auth()->check() ? auth()->user()->ROLE_ID : 0; if(in_array(explode("@", $action)[1], $arrActionsAdmin))//Si la acción del controlador se encuentra en la lista de acciones de admin... { if( ! in_array($ROLE_ID , [\reservas\Rol::ADMIN]))//Si el rol no es admin, se niega el acceso. { //Session::flash('alert-danger', 'Usuario no tiene permisos.'); abort(403, 'Usuario no tiene permisos!.'); } } } } /** * Validate the user login request. * * @param \Illuminate\Http\Request $request * @return void */ protected function validateLogin(Request $request) { //Convierte a minúsculas el usuario $request->username = strtolower($request->username); $this->validate($request, [ $this->loginUsername() => 'required', 'password' => 'required', ]); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'username' => 'required|max:15|unique:USERS', 'email' => 'required|email|max:255|unique:USERS', 'password' => 'required|min:6|confirmed', 'ROLE_ID' => 'required', ]); } /** * Show the application registration form. * * @return \Illuminate\Http\Response */ public function showRegistrationForm() { if (property_exists($this, 'registerView')) { return view($this->registerView); } //Se crea una colección con los posibles roles. $roles = Rol::orderBy('ROLE_ID') ->select('ROLE_ID', 'ROLE_DESCRIPCION') ->get(); return view('auth.register', compact('roles')); } /** * Handle a registration request for the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function register(Request $request) { $validator = $this->validator($request->all()); if( $validator->fails() ) { $this->throwValidationException( $request, $validator ); } //Auth::guard($this->getGuard())->login($this->create($request->all())); $usuario = $this->create($request->all()); Session::flash('alert-info', 'Usuario '.$usuario->username.' creado exitosamente!'); return redirect('usuarios'); } /** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'username' => $data['username'], 'email' => $data['email'], 'password' => bcrypt($data['password']), 'ROLE_ID' => $data['ROLE_ID'], 'USER_CREADOPOR' => auth()->user()->username, ]); } /** * Get the login username to be used by the controller. * * @return string */ public function loginUsername() { //Se modifica para que la autenticación se realice por username y no por email return property_exists($this, 'username') ? $this->username : 'username'; } /** * Muestra una lista de los registros. * * @return Response */ public function index() { //Se obtienen todos los registros. $usuarios = User::orderBy('USER_ID')->get(); //Se carga la vista y se pasan los registros return view('auth/index', compact('usuarios')); } /** * Muestra información de un registro. * * @param int $USER_ID * @return Response */ public function show($USER_ID) { // Se obtiene el registro $usuario = User::findOrFail($USER_ID); // Muestra la vista y pasa el registro return view('auth/show', compact('usuario')); } /** * Muestra el formulario para editar un registro en particular. * * @param int $USER_ID * @return Response */ public function edit($USER_ID) { // Se obtiene el registro $usuario = User::findOrFail($USER_ID); //Se crea una colección con los posibles roles. $roles = Rol::orderBy('ROLE_ID') ->select('ROLE_ID', 'ROLE_DESCRIPCION') ->get(); // Muestra el formulario de edición y pasa el registro a editar return view('auth/edit', compact('usuario', 'roles')); } /** * Actualiza un registro en la base de datos. * * @param int $USER_ID * @return Response */ public function update($USER_ID) { //Validación de datos $this->validate(request(), [ 'name' => 'required|max:255', 'email' => 'required|email|max:255', 'ROLE_ID' => 'required', 'email' => 'required|email|max:255|unique:USERS,email,'.$USER_ID.',USER_ID' ]); // Se obtiene el registro $usuario = User::findOrFail($USER_ID); $usuario->name = Input::get('name'); $usuario->email = Input::get('email'); $usuario->ROLE_ID = Input::get('ROLE_ID'); //Relación con Rol $usuario->USER_MODIFICADOPOR = auth()->user()->username; //Se guarda modelo $usuario->save(); // redirecciona al index de controlador Session::flash('alert-info', 'Usuario '.$usuario->username.' modificado exitosamente!'); return redirect('usuarios'); } /** * Elimina un registro de la base de datos. * * @param int $USER_ID * @return Response */ public function destroy($USER_ID) { $usuario = User::findOrFail($USER_ID); //Si el usuario fue creado por SYSTEM, no se puede borrar. if($usuario->USER_CREADOPOR == 'SYSTEM'){ Session::flash('alert-danger', '¡Usuario '.$usuario->username.' no se puede borrar!'); } else { if($usuario->personaGeneral) $usuario->personaGeneral->delete(); $usuario->USER_ELIMINADOPOR = auth()->user()->username; $usuario->save(); $usuario->delete(); Session::flash('alert-warning', ['¡Usuario '.$usuario->username.' borrado!']); } return redirect('usuarios'); } }
hgonzalezgaviria/diheke
app/Http/Controllers/Auth/AuthController.php
PHP
gpl-3.0
7,880