code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify #define SA(n, p) int a##n[(p) ? 1 : -1] struct A { int a; }; SA(0, sizeof(A) == 4); struct B { }; SA(1, sizeof(B) == 1); struct C : A, B { }; SA(2, sizeof(C) == 4); struct D { }; struct E : D { }; struct F : E { }; struct G : E, F { }; SA(3, sizeof(G) == 2); struct Empty { Empty(); }; struct I : Empty { Empty e; }; SA(4, sizeof(I) == 2); struct J : Empty { Empty e[2]; }; SA(5, sizeof(J) == 3); template<int N> struct Derived : Empty, Derived<N - 1> { }; template<> struct Derived<0> : Empty { }; struct S1 : virtual Derived<10> { Empty e; }; SA(6, sizeof(S1) == 24); struct S2 : virtual Derived<10> { Empty e[2]; }; SA(7, sizeof(S2) == 24); struct S3 { Empty e; }; struct S4 : Empty, S3 { }; SA(8, sizeof(S4) == 2); struct S5 : S3, Empty {}; SA(9, sizeof(S5) == 2); struct S6 : S5 { }; SA(10, sizeof(S6) == 2); struct S7 : Empty { void *v; }; SA(11, sizeof(S7) == 8); struct S8 : Empty, A { }; SA(12, sizeof(S8) == 4);
vrtadmin/clamav-bytecode-compiler
clang/test/SemaCXX/empty-class-layout.cpp
C++
gpl-2.0
1,034
using Halsign.DWM.Framework; using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading; namespace Halsign.DWM.Domain { public class DwmHost : DwmBase { private int _numCpus = 1; private int _numVCpus; private int _cpuSpeed; private int _numNics = 1; private bool _isPoolMaster; private bool _enabled = true; private string _ipAddress; private bool _isEnterpriseOrHigher; private PowerStatus _powerState; private bool _participatesInPowerManagement; private bool _excludeFromPlacementRecommendations; private bool _excludeFromEvacuationRecommendations; private bool _excludeFromPoolOptimizationAcceptVMs; private long _memOverhead; private DateTime _metricsLastRetrieved = DateTime.MinValue; private DwmVirtualMachineCollection _listVMs; private DwmPifCollection _listPIFs; private DwmPbdCollection _listPBDs; private DwmStorageRepositoryCollection _availableStorage; private DwmHostAverageMetric _metrics; private static Dictionary<string, int> _uuidCache = new Dictionary<string, int>(); private static Dictionary<string, int> _nameCache = new Dictionary<string, int>(); private static Dictionary<string, string> _uuidNameCache = new Dictionary<string, string>(); private static object _uuidCacheLock = new object(); private static object _nameCacheLock = new object(); private static object _uuidNameCacheLock = new object(); private double _cpuScore; public int NumCpus { get { return this._numCpus; } set { this._numCpus = value; } } public int NumVCpus { get { return this._numVCpus; } set { this._numVCpus = value; } } public int CpuSpeed { get { return this._cpuSpeed; } set { this._cpuSpeed = value; } } public int NumNics { get { return this._numNics; } set { this._numNics = value; } } public string IPAddress { get { return this._ipAddress; } set { this._ipAddress = value; } } public bool IsPoolMaster { get { return this._isPoolMaster; } set { this._isPoolMaster = value; } } public bool Enabled { get { return this._enabled; } set { this._enabled = value; } } public bool IsEnterpriseOrHigher { get { return this._isEnterpriseOrHigher; } set { this._isEnterpriseOrHigher = value; } } public PowerStatus PowerState { get { return this._powerState; } set { this._powerState = value; } } public long MemoryOverhead { get { return this._memOverhead; } set { this._memOverhead = value; } } internal bool ParticipatesInPowerManagement { get { return this._participatesInPowerManagement; } set { this._participatesInPowerManagement = value; } } internal bool ExcludeFromPlacementRecommendations { get { return this._excludeFromPlacementRecommendations; } set { this._excludeFromPlacementRecommendations = value; } } internal bool ExcludeFromEvacuationRecommendations { get { return this._excludeFromEvacuationRecommendations; } set { this._excludeFromEvacuationRecommendations = value; } } internal bool ExcludeFromPoolOptimizationAcceptVMs { get { return this._excludeFromPoolOptimizationAcceptVMs; } set { this._excludeFromPoolOptimizationAcceptVMs = value; } } public DwmVirtualMachineCollection VirtualMachines { get { return DwmBase.SafeGetItem<DwmVirtualMachineCollection>(ref this._listVMs); } internal set { this._listVMs = value; } } public DwmPifCollection PIFs { get { return DwmBase.SafeGetItem<DwmPifCollection>(ref this._listPIFs); } } public DwmPbdCollection PBDs { get { return DwmBase.SafeGetItem<DwmPbdCollection>(ref this._listPBDs); } } public DwmStorageRepositoryCollection AvailableStorage { get { return DwmBase.SafeGetItem<DwmStorageRepositoryCollection>(ref this._availableStorage); } internal set { this._availableStorage = value; } } public DwmHostAverageMetric Metrics { get { return DwmBase.SafeGetItem<DwmHostAverageMetric>(ref this._metrics); } internal set { this._metrics = value; } } internal double CpuScore { get { this._cpuScore = (double)(this.NumCpus * this.CpuSpeed); if (this.Metrics.MetricsNow != null) { this._cpuScore *= 1.0 - this.Metrics.MetricsNow.AverageCpuUtilization; } return this._cpuScore; } } public DateTime MetricsLastRetrieved { get { if (this._metricsLastRetrieved == DateTime.MinValue) { string sqlStatement = "get_host_last_metric_time"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@host_id", base.Id)); using (DBAccess dBAccess = new DBAccess()) { this._metricsLastRetrieved = dBAccess.ExecuteScalarDateTime(sqlStatement, storedProcParamCollection); } if (this._metricsLastRetrieved == DateTime.MinValue) { this._metricsLastRetrieved = DateTime.UtcNow.AddMinutes(-1.0); } } return this._metricsLastRetrieved; } set { this._metricsLastRetrieved = value; } } public DwmHost(string uuid, string name, string poolUuid) : base(uuid, name) { base.PoolId = DwmBase.PoolUuidToId(poolUuid); if (!string.IsNullOrEmpty(uuid)) { base.Id = DwmHost.UuidToId(uuid, base.PoolId); } else { if (string.IsNullOrEmpty(name)) { throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null); } base.Id = DwmHost.NameToId(name, base.PoolId); } } public DwmHost(string uuid, string name, int poolId) : base(uuid, name) { base.PoolId = poolId; if (!string.IsNullOrEmpty(uuid)) { base.Id = DwmHost.UuidToId(uuid, base.PoolId); } else { if (string.IsNullOrEmpty(name)) { throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null); } base.Id = DwmHost.NameToId(name, base.PoolId); } } public DwmHost(int hostID) : base(hostID) { } internal static void RefreshCache() { object uuidCacheLock = DwmHost._uuidCacheLock; Monitor.Enter(uuidCacheLock); try { DwmHost._uuidCache.Clear(); } finally { Monitor.Exit(uuidCacheLock); } object nameCacheLock = DwmHost._nameCacheLock; Monitor.Enter(nameCacheLock); try { DwmHost._nameCache.Clear(); } finally { Monitor.Exit(nameCacheLock); } object uuidNameCacheLock = DwmHost._uuidNameCacheLock; Monitor.Enter(uuidNameCacheLock); try { DwmHost._uuidNameCache.Clear(); } finally { Monitor.Exit(uuidNameCacheLock); } } internal static int UuidToId(string uuid, int poolId) { int num = 0; if (!string.IsNullOrEmpty(uuid)) { string key = Localization.Format("{0}|{1}", uuid, poolId); if (!DwmHost._uuidCache.TryGetValue(key, out num)) { using (DBAccess dBAccess = new DBAccess()) { num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where uuid='{0}' and poolid={1}", uuid.Replace("'", "''"), poolId)); if (num != 0) { object uuidCacheLock = DwmHost._uuidCacheLock; Monitor.Enter(uuidCacheLock); try { if (!DwmHost._uuidCache.ContainsKey(key)) { DwmHost._uuidCache.Add(key, num); } } finally { Monitor.Exit(uuidCacheLock); } } } } } return num; } public static int NameToId(string name, int poolId) { int num = 0; if (!string.IsNullOrEmpty(name)) { string key = Localization.Format("{0}|{1}", name, poolId); if (!DwmHost._nameCache.TryGetValue(key, out num)) { using (DBAccess dBAccess = new DBAccess()) { num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where name='{0}' and poolid={1}", name.Replace("'", "''"), poolId)); if (num != 0) { object nameCacheLock = DwmHost._nameCacheLock; Monitor.Enter(nameCacheLock); try { if (!DwmHost._nameCache.ContainsKey(key)) { DwmHost._nameCache.Add(key, num); } } finally { Monitor.Exit(nameCacheLock); } } } } } return num; } public static string UuidToName(string uuid, int poolId) { string text = string.Empty; if (!string.IsNullOrEmpty(uuid)) { string key = Localization.Format("{0}|{1}", uuid, poolId); if (!DwmHost._uuidNameCache.TryGetValue(key, out text)) { using (DBAccess dBAccess = new DBAccess()) { text = dBAccess.ExecuteScalarString(Localization.Format("select name from hv_host where uuid='{0}' and poolid={1}", uuid, poolId)); if (string.IsNullOrEmpty(text)) { object uuidNameCacheLock = DwmHost._uuidNameCacheLock; Monitor.Enter(uuidNameCacheLock); try { if (!DwmHost._uuidNameCache.ContainsKey(key)) { DwmHost._uuidNameCache.Add(key, text); } } finally { Monitor.Exit(uuidNameCacheLock); } } } } } return text; } public DwmHost Copy() { return new DwmHost(base.Uuid, base.Name, base.PoolId) { Id = base.Id, CpuSpeed = this.CpuSpeed, Description = base.Description, IsPoolMaster = this.IsPoolMaster, Name = base.Name, NumCpus = this.NumCpus, NumVCpus = this.NumVCpus, NumNics = this.NumNics, ParticipatesInPowerManagement = this.ParticipatesInPowerManagement, ExcludeFromPlacementRecommendations = this.ExcludeFromPlacementRecommendations, ExcludeFromEvacuationRecommendations = this.ExcludeFromEvacuationRecommendations, ExcludeFromPoolOptimizationAcceptVMs = this.ExcludeFromPoolOptimizationAcceptVMs, PowerState = this.PowerState, MemoryOverhead = this.MemoryOverhead, Metrics = this.Metrics.Copy(), AvailableStorage = this.AvailableStorage.Copy(), VirtualMachines = this.VirtualMachines.Copy() }; } internal static void SetOtherConfig(int hostId, string name, string value) { DwmHost dwmHost = new DwmHost(hostId); dwmHost.SetOtherConfig(name, value); } public void SetOtherConfig(string name, string value) { base.SetOtherConfig("hv_host_config_update", "@host_id", name, value); if (Localization.Compare(name, "ParticipatesInPowerManagement", true) == 0) { DwmPool.GenerateFillOrder(base.PoolId); } } public void SetOtherConfig(Dictionary<string, string> config) { base.SetOtherConfig("hv_host_config_update", "@host_id", config); if (config.ContainsKey("ParticipatesInPowerManagement")) { DwmPool.GenerateFillOrder(base.PoolId); } } public string GetOtherConfigItem(string itemName) { return base.GetOtherConfigItem("hv_host_config_get_item", "@host_id", itemName); } public Dictionary<string, string> GetOtherConfig() { return base.GetOtherConfig("hv_host_config_get", "@host_id"); } public static void SetEnabled(string hostUuid, string poolUuid, bool enabled) { string sqlStatement = "hv_host_set_enabled"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@host_uuid", hostUuid)); storedProcParamCollection.Add(new StoredProcParam("@pool_uuid", poolUuid)); storedProcParamCollection.Add(new StoredProcParam("@enabled", enabled)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection); } } internal static void SetStatus(int hostId, DwmStatus status) { string sqlStatement = "set_host_status"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId)); storedProcParamCollection.Add(new StoredProcParam("@status", (int)status)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection); } } internal static void SetLastResult(int hostId, DwmStatus result) { string sqlStatement = "set_host_last_result"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId)); storedProcParamCollection.Add(new StoredProcParam("@last_result", (int)result)); storedProcParamCollection.Add(new StoredProcParam("@last_result_time", DateTime.UtcNow)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection); } } public static void SetPoweredOffByWlb(int hostId, bool poweredOffByWlb) { string sqlStatement = "set_host_powered_off_by_wlb"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId)); if (poweredOffByWlb) { storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 1)); } else { storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 0)); } using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection); } } internal bool HasRequiredStorage(DwmStorageRepositoryCollection requiredSRs) { bool result = true; int num = 0; while (requiredSRs != null && num < requiredSRs.Count) { if (!this.AvailableStorage.ContainsKey(requiredSRs[num].Id)) { result = false; break; } num++; } return result; } public static void DeleteHost(string hostUuid, string poolUuid) { if (!string.IsNullOrEmpty(hostUuid) && !string.IsNullOrEmpty(poolUuid)) { Logger.Trace("Deleting host {0} by setting active to false", new object[] { hostUuid }); int num = DwmPoolBase.UuidToId(poolUuid); int num2 = DwmHost.UuidToId(hostUuid, num); string sqlStatement = "delete_hv_host"; StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection(); storedProcParamCollection.Add(new StoredProcParam("@pool_id", num)); storedProcParamCollection.Add(new StoredProcParam("@host_id", num2)); storedProcParamCollection.Add(new StoredProcParam("@tstamp", DateTime.UtcNow)); using (DBAccess dBAccess = new DBAccess()) { dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection); } } } internal static DwmHost LoadWithMetrics(IDataReader reader) { string @string = DBAccess.GetString(reader, "uuid"); string string2 = DBAccess.GetString(reader, "name"); int @int = DBAccess.GetInt(reader, "poolid"); return new DwmHost(@string, string2, @int) { Id = DBAccess.GetInt(reader, "id"), NumCpus = DBAccess.GetInt(reader, "num_cpus"), NumVCpus = DBAccess.GetInt(reader, "num_vcpus"), CpuSpeed = DBAccess.GetInt(reader, "cpu_speed"), NumNics = DBAccess.GetInt(reader, "num_pifs"), IsPoolMaster = DBAccess.GetBool(reader, "is_pool_master"), PowerState = (PowerStatus)DBAccess.GetInt(reader, "power_state"), ParticipatesInPowerManagement = DBAccess.GetBool(reader, "can_power"), ExcludeFromPlacementRecommendations = DBAccess.GetBool(reader, "exclude_placements"), ExcludeFromEvacuationRecommendations = DBAccess.GetBool(reader, "exclude_evacuations"), Metrics = { FreeCPUs = DBAccess.GetInt(reader, "free_cpus"), PotentialFreeMemory = DBAccess.GetInt64(reader, "potential_free_memory"), FillOrder = DBAccess.GetInt(reader, "fill_order"), TotalMemory = DBAccess.GetInt64(reader, "total_mem"), FreeMemory = DBAccess.GetInt64(reader, "free_mem"), NumHighFullContentionVCpus = DBAccess.GetInt(reader, "full_contention_count"), NumHighConcurrencyHazardVCpus = DBAccess.GetInt(reader, "concurrency_hazard_count"), NumHighPartialContentionVCpus = DBAccess.GetInt(reader, "partial_contention_count"), NumHighFullrunVCpus = DBAccess.GetInt(reader, "fullrun_count"), NumHighPartialRunVCpus = DBAccess.GetInt(reader, "partial_run_count"), NumHighBlockedVCpus = DBAccess.GetInt(reader, "blocked_count"), MetricsNow = { AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_now", 0L), AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_now", 0.0), AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_now", 0.0), AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_now", 0.0), AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_now", 0.0), AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_now", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_now", 0.0) }, MetricsLast30Minutes = { AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_30", 0L), AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_30", 0.0), AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_30", 0.0), AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_30", 0.0), AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_30", 0.0), AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_30", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_30", 0.0) }, MetricsYesterday = { AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_yesterday", 0L), AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_yesterday", 0.0), AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_yesterday", 0.0), AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_yesterday", 0.0), AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_yesterday", 0.0), AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_yesterday", 0.0), AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_yesterday", 0.0) } } }; } internal void LoadPif(IDataReader reader) { int @int = DBAccess.GetInt(reader, "pif_id"); string @string = DBAccess.GetString(reader, "pif_uuid"); string string2 = DBAccess.GetString(reader, "pif_name"); int int2 = DBAccess.GetInt(reader, "networkid"); int int3 = DBAccess.GetInt(reader, "poolid"); bool @bool = DBAccess.GetBool(reader, "is_management_interface"); DwmPif dwmPif = new DwmPif(@string, string2, int2, int3); dwmPif.Id = @int; dwmPif.IsManagementInterface = @bool; this.PIFs.Add(dwmPif); } public void Save() { using (DBAccess dBAccess = new DBAccess()) { this.Save(dBAccess); } } public void Save(DBAccess db) { if (db != null) { try { string sqlStatement = "add_update_hv_host"; base.Id = db.ExecuteScalarInt(sqlStatement, new StoredProcParamCollection { new StoredProcParam("@uuid", base.Uuid), new StoredProcParam("@name", (base.Name == null) ? string.Empty : base.Name), new StoredProcParam("@pool_id", base.PoolId), new StoredProcParam("@description", (base.Description == null) ? string.Empty : base.Description), new StoredProcParam("@num_cpus", this._numCpus), new StoredProcParam("@cpu_speed", this._cpuSpeed), new StoredProcParam("@num_nics", this._numNics), new StoredProcParam("@is_pool_master", this._isPoolMaster), new StoredProcParam("@ip_address", this._ipAddress), new StoredProcParam("@memory_overhead", this._memOverhead), new StoredProcParam("@enabled", this._enabled), new StoredProcParam("@power_state", (int)this._powerState) }); StringBuilder stringBuilder = new StringBuilder(); string value = "BEGIN;\n"; string value2 = "COMMIT;\n"; stringBuilder.Append(value); stringBuilder.Append(this.SaveHostStorageRelationships()); stringBuilder.Append(this.SaveHostVmRelationships()); stringBuilder.Append(this.SaveHostPifRelationships()); stringBuilder.Append(this.SaveHostPbdRelationships()); stringBuilder.Append(value2); DwmBase.WriteData(db, stringBuilder); } catch (Exception ex) { Logger.Trace("Caught exception saving host {0} uuid={1}", new object[] { base.Name, base.Uuid }); Logger.LogException(ex); } return; } throw new DwmException("Cannot pass null DBAccess instance to Save", DwmErrorCode.NullReference, null); } private StringBuilder SaveHostStorageRelationships() { StringBuilder stringBuilder = new StringBuilder(); if (this._availableStorage != null && this._availableStorage.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._availableStorage.Count; i++) { stringBuilder.AppendFormat("insert into hv_host_storage_repository (host_id, sr_id) select {0}, {1}\nwhere not exists (select id from hv_host_storage_repository where host_id={0} and sr_id={1});\n", base.Id, this._availableStorage[i].Id); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._availableStorage[i].Id); } stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0} and sr_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0};\n", base.Id); } return stringBuilder; } private StringBuilder SaveHostVmRelationships() { StringBuilder stringBuilder = new StringBuilder(); if (this._listVMs != null && this._listVMs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listVMs.Count; i++) { stringBuilder.AppendFormat("select * from add_update_host_vm( {0}, {1}, '{2}');\n", base.Id, this._listVMs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listVMs[i].Id); } stringBuilder.AppendFormat("delete from host_vm where hostid={0} and vmid not in ({1});\nupdate host_vm_history set end_time='{2}' \nwhere host_id={0}\n and end_time is null\n and vm_id not in ({1});\n", base.Id, stringBuilder2.ToString(), Localization.DateTimeToSqlString(DateTime.UtcNow)); } else { stringBuilder.AppendFormat("delete from host_vm where hostid={0};\nupdate host_vm_history set end_time='{1}' \nwhere host_id={0} and end_time is null;\n", base.Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); } return stringBuilder; } private StringBuilder SaveHostPifRelationships() { StringBuilder stringBuilder = new StringBuilder(); if (this._listPIFs != null && this._listPIFs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listPIFs.Count; i++) { stringBuilder.AppendFormat("insert into hv_host_pif (hostid, pif_id, tstamp) select {0}, {1},'{2}'\nwhere not exists (select id from hv_host_pif where hostid={0} and pif_id={1});\n", base.Id, this._listPIFs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPIFs[i].Id); } stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0} and pif_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0};\n", base.Id); } return stringBuilder; } private StringBuilder SaveHostPbdRelationships() { StringBuilder stringBuilder = new StringBuilder(); if (this._listPBDs != null && this._listPBDs.Count > 0) { StringBuilder stringBuilder2 = new StringBuilder(); for (int i = 0; i < this._listPBDs.Count; i++) { stringBuilder.AppendFormat("insert into hv_host_pbd (hostid, pbd_id, tstamp) select {0}, {1}, '{2}'\nwhere not exists (select id from hv_host_pbd where hostid={0} and pbd_id={1});\n", base.Id, this._listPBDs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow)); stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPBDs[i].Id); } stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0} and pbd_id not in ({1});\n", base.Id, stringBuilder2.ToString()); } else { stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0};\n", base.Id); } return stringBuilder; } public void Load() { string sql = "load_host_by_id"; this.InternalLoad(sql, new StoredProcParamCollection { new StoredProcParam("@host_id", base.Id) }); } internal void SimpleLoad() { string sql = "load_host_simple_by_id"; this.InternalLoad(sql, new StoredProcParamCollection { new StoredProcParam("@host_id", base.Id) }); } private void InternalLoad(string sql, StoredProcParamCollection parms) { using (DBAccess dBAccess = new DBAccess()) { dBAccess.UseTransaction = true; using (IDataReader dataReader = dBAccess.ExecuteReader(sql, parms)) { if (dataReader.Read()) { if (string.IsNullOrEmpty(base.Uuid)) { base.Uuid = DBAccess.GetString(dataReader, "uuid"); } if (base.PoolId <= 0) { base.PoolId = DBAccess.GetInt(dataReader, "poolid"); } base.Name = DBAccess.GetString(dataReader, "name"); base.Description = DBAccess.GetString(dataReader, "description"); this.NumCpus = DBAccess.GetInt(dataReader, "num_cpus"); this.CpuSpeed = DBAccess.GetInt(dataReader, "cpu_speed"); this.NumNics = DBAccess.GetInt(dataReader, "num_pifs"); this.IsPoolMaster = DBAccess.GetBool(dataReader, "is_pool_master"); this.Enabled = DBAccess.GetBool(dataReader, "enabled"); this.Metrics.FillOrder = DBAccess.GetInt(dataReader, "fill_order"); this.IPAddress = DBAccess.GetString(dataReader, "ip_address"); this.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead"); base.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status"); base.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result"); base.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time"); this.Metrics.TotalMemory = DBAccess.GetInt64(dataReader, "total_mem"); if (dataReader.NextResult()) { while (dataReader.Read()) { int @int = DBAccess.GetInt(dataReader, "hostid"); int int2 = DBAccess.GetInt(dataReader, "vmid"); string @string = DBAccess.GetString(dataReader, "name"); string string2 = DBAccess.GetString(dataReader, "uuid"); int int3 = DBAccess.GetInt(dataReader, "poolid"); DwmVirtualMachine dwmVirtualMachine = new DwmVirtualMachine(string2, @string, int3); dwmVirtualMachine.Id = int2; dwmVirtualMachine.Description = DBAccess.GetString(dataReader, "description"); dwmVirtualMachine.MinimumDynamicMemory = DBAccess.GetInt64(dataReader, "min_dynamic_memory"); dwmVirtualMachine.MaximumDynamicMemory = DBAccess.GetInt64(dataReader, "max_dynamic_memory"); dwmVirtualMachine.MinimumStaticMemory = DBAccess.GetInt64(dataReader, "min_static_memory"); dwmVirtualMachine.MaximumStaticMemory = DBAccess.GetInt64(dataReader, "max_static_memory"); dwmVirtualMachine.TargetMemory = DBAccess.GetInt64(dataReader, "target_memory"); dwmVirtualMachine.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead"); dwmVirtualMachine.MinimumCpus = DBAccess.GetInt(dataReader, "min_cpus"); dwmVirtualMachine.HvMemoryMultiplier = DBAccess.GetDouble(dataReader, "hv_memory_multiplier"); dwmVirtualMachine.RequiredMemory = DBAccess.GetInt64(dataReader, "required_memory"); dwmVirtualMachine.IsControlDomain = DBAccess.GetBool(dataReader, "is_control_domain"); dwmVirtualMachine.IsAgile = DBAccess.GetBool(dataReader, "is_agile"); dwmVirtualMachine.DriversUpToDate = DBAccess.GetBool(dataReader, "drivers_up_to_date"); dwmVirtualMachine.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status"); dwmVirtualMachine.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result"); dwmVirtualMachine.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time"); this.VirtualMachines.Add(dwmVirtualMachine); } } } } } } public static DwmHost Load(string hostUuid, string poolUuid) { int poolId = DwmPoolBase.UuidToId(poolUuid); int num = DwmHost.UuidToId(hostUuid, poolId); if (num <= 0) { throw new DwmException("Invalid Host uuid", DwmErrorCode.InvalidParameter, null); } return DwmHost.Load(num); } public static DwmHost Load(int hostId) { if (hostId > 0) { DwmHost dwmHost = new DwmHost(hostId); dwmHost.Load(); return dwmHost; } throw new DwmException("Invalid host ID", DwmErrorCode.InvalidParameter, null); } } }
yimng/wlb
wlb/Halsign.Dwm.Domain/Domain/DwmHost.cs
C#
gpl-2.0
29,482
#include "Converter.h" #include <TFormula.h> #include <iomanip> #include <sstream> std::string Converter::doubleToString(double x,int precision,bool scientifiStyle) { std::stringstream xs; if(scientifiStyle) xs<<std::scientific; else xs<<std::fixed; xs<<std::setprecision(precision)<<x; return xs.str(); }; std::string Converter::intToString(int x) { return doubleToString(x,0); }; double Converter::stringToDouble(std::string formula) { TFormula myf("myf",formula.c_str()); return myf.Eval(0); } int Converter::stringToInt(std::string formula) { return (int)(stringToDouble(formula)); }
DingXuefeng/LegendOfNeutrino
libsrc/Converter.cc
C++
gpl-2.0
614
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstring> #include <deque> #include <iostream> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <utility> #include <vector> // #pragma GCC optimize("Ofast") // #pragma GCC optimize("inline") // #pragma GCC optimize("-fgcse") // #pragma GCC optimize("-fgcse-lm") // #pragma GCC optimize("-fipa-sra") // #pragma GCC optimize("-ftree-pre") // #pragma GCC optimize("-ftree-vrp") // #pragma GCC optimize("-fpeephole2") // #pragma GCC optimize("-ffast-math") // #pragma GCC optimize("-fsched-spec") // #pragma GCC optimize("unroll-loops") // #pragma GCC optimize("-falign-jumps") // #pragma GCC optimize("-falign-loops") // #pragma GCC optimize("-falign-labels") // #pragma GCC optimize("-fdevirtualize") // #pragma GCC optimize("-fcaller-saves") // #pragma GCC optimize("-fcrossjumping") // #pragma GCC optimize("-fthread-jumps") // #pragma GCC optimize("-funroll-loops") // #pragma GCC optimize("-fwhole-program") // #pragma GCC optimize("-freorder-blocks") // #pragma GCC optimize("-fschedule-insns") // #pragma GCC optimize("inline-functions") // #pragma GCC optimize("-ftree-tail-merge") // #pragma GCC optimize("-fschedule-insns2") // #pragma GCC optimize("-fstrict-aliasing") // #pragma GCC optimize("-fstrict-overflow") // #pragma GCC optimize("-falign-functions") // #pragma GCC optimize("-fcse-skip-blocks") // #pragma GCC optimize("-fcse-follow-jumps") // #pragma GCC optimize("-fsched-interblock") // #pragma GCC optimize("-fpartial-inlining") // #pragma GCC optimize("no-stack-protector") // #pragma GCC optimize("-freorder-functions") // #pragma GCC optimize("-findirect-inlining") // #pragma GCC optimize("-fhoist-adjacent-loads") // #pragma GCC optimize("-frerun-cse-after-loop") // #pragma GCC optimize("inline-small-functions") // #pragma GCC optimize("-finline-small-functions") // #pragma GCC optimize("-ftree-switch-conversion") // #pragma GCC optimize("-foptimize-sibling-calls") // #pragma GCC optimize("-fexpensive-optimizations") // #pragma GCC optimize("-funsafe-loop-optimizations") // #pragma GCC optimize("inline-functions-called-once") // #pragma GCC optimize("-fdelete-null-pointer-checks") #define rep(i, l, r) for (int i = (l); i <= (r); ++i) #define per(i, l, r) for (int i = (l); i >= (r); --i) using std::cerr; using std::endl; using std::make_pair; using std::pair; typedef pair<int, int> pii; typedef long long ll; typedef unsigned int ui; typedef unsigned long long ull; // #define DEBUG 1 //调试开关 struct IO { #define MAXSIZE (1 << 20) #define isdigit(x) (x >= '0' && x <= '9') char buf[MAXSIZE], *p1, *p2; char pbuf[MAXSIZE], *pp; #if DEBUG #else IO() : p1(buf), p2(buf), pp(pbuf) {} ~IO() { fwrite(pbuf, 1, pp - pbuf, stdout); } #endif inline char gc() { #if DEBUG //调试,可显示字符 return getchar(); #endif if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin); return p1 == p2 ? -1 : *p1++; } inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; } template <class T> inline void read(T &x) { register double tmp = 1; register bool sign = 0; x = 0; register char ch = gc(); for (; !isdigit(ch); ch = gc()) if (ch == '-') sign = 1; for (; isdigit(ch); ch = gc()) x = x * 10 + (ch - '0'); if (ch == '.') for (ch = gc(); isdigit(ch); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0'); if (sign) x = -x; } inline void read(char *s) { register char ch = gc(); for (; blank(ch); ch = gc()) ; for (; !blank(ch); ch = gc()) *s++ = ch; *s = 0; } inline void read(char &c) { for (c = gc(); blank(c); c = gc()) ; } inline void push(const char &c) { #if DEBUG //调试,可显示字符 putchar(c); #else if (pp - pbuf == MAXSIZE) fwrite(pbuf, 1, MAXSIZE, stdout), pp = pbuf; *pp++ = c; #endif } template <class T> inline void write(T x) { if (x < 0) x = -x, push('-'); // 负数输出 static T sta[35]; T top = 0; do { sta[top++] = x % 10, x /= 10; } while (x); while (top) push(sta[--top] + '0'); } inline void write(const char *s) { while (*s != '\0') push(*(s++)); } template <class T> inline void write(T x, char lastChar) { write(x), push(lastChar); } } io; int a[510][510]; int main() { #ifdef LOCAL freopen("input", "r", stdin); #endif int n; io.read(n); rep(i, 1, n) { rep(j, i + 1, n) { io.read(a[i][j]); a[j][i] = a[i][j]; } } int ans = 0; rep(i, 1, n) { std::sort(a[i] + 1, a[i] + 1 + n); ans = std::max(ans, a[i][n - 1]); } io.write("1\n"); io.write(ans); return 0; }
Chaigidel/luogu-code
complete/LG-1199.cpp
C++
gpl-2.0
4,983
<? if (!defined("_GNUBOARD_")) exit; // °³º° ÆäÀÌÁö Á¢±Ù ºÒ°¡ if ($is_dhtml_editor) { include_once("$g4[path]/lib/cheditor.lib.php"); echo "<script src='$g4[editor_path]/cheditor.js'></script>"; echo cheditor1('wr_content', $content); } ?> <script language="javascript"> // ±ÛÀÚ¼ö Á¦ÇÑ var char_min = parseInt(<?=$write_min?>); // ÃÖ¼Ò var char_max = parseInt(<?=$write_max?>); // ÃÖ´ë </script> <form name="fwrite" method="post" action="javascript:fwrite_check(document.fwrite);" enctype="multipart/form-data" style="margin:0px;"> <input type=hidden name=null> <input type=hidden name=w value="<?=$w?>"> <input type=hidden name=bo_table value="<?=$bo_table?>"> <input type=hidden name=wr_id value="<?=$wr_id?>"> <input type=hidden name=sca value="<?=$sca?>"> <input type=hidden name=sfl value="<?=$sfl?>"> <input type=hidden name=stx value="<?=$stx?>"> <input type=hidden name=spt value="<?=$spt?>"> <input type=hidden name=sst value="<?=$sst?>"> <input type=hidden name=sod value="<?=$sod?>"> <input type=hidden name=page value="<?=$page?>"> <table width="<?=$width?>" align=center cellpadding=0 cellspacing=0><tr><td> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <colgroup width=100> <colgroup width=''> <tr><td colspan=2 height=2 bgcolor=#b0adf5></td></tr> <tr><td style='padding-left:20px' colspan=2 height=38 bgcolor=#f8f8f9><strong><?=$title_msg?></strong></td></tr> <? if ($is_name) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ À̸§</td> <td><input class=ed maxlength=20 size=15 name=wr_name itemname="À̸§" required value="<?=$name?>"></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_password) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ ÆÐ½º¿öµå</td> <td><input class=ed type=password maxlength=20 size=15 name=wr_password itemname="ÆÐ½º¿öµå" <?=$password_required?>></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_email) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ À̸ÞÀÏ</td> <td><input class=ed maxlength=100 size=50 name=wr_email email itemname="À̸ÞÀÏ" value="<?=$email?>"></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_homepage) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ ȨÆäÀÌÁö</td> <td><input class=ed size=50 name=wr_homepage itemname="ȨÆäÀÌÁö" value="<?=$homepage?>"></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_notice || $is_html || $is_secret || $is_mail) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ ¿É¼Ç</td> <td><? if ($is_notice) { ?><input type=checkbox name=notice value="1" <?=$notice_checked?>>°øÁö&nbsp;<? } ?> <? if ($is_html) { ?> <? if ($is_dhtml_editor) { ?> <input type=hidden value="html1" name="html"> <? } else { ?> <input onclick="html_auto_br(this);" type=checkbox value="<?=$html_value?>" name="html" <?=$html_checked?>><span class=w_title>html</span>&nbsp; <? } ?> <? } ?> <? if ($is_secret) { ?> <? if ($is_admin || $is_secret==1) { ?> <input type=checkbox value="secret" name="secret" <?=$secret_checked?>><span class=w_title>ºñ¹Ð±Û</span>&nbsp; <? } else { ?> <input type=hidden value="secret" name="secret"> <? } ?> <? } ?> <? if ($is_mail) { ?><input type=checkbox value="mail" name="mail" <?=$recv_email_checked?>>´äº¯¸ÞÀϹޱâ&nbsp;<? } ?></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_category) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ ºÐ·ù</td> <td><select name=ca_name required itemname="ºÐ·ù"><option value="">¼±ÅÃÇϼ¼¿ä<?=$category_option?></select></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ Á¦¸ñ</td> <td><input class=ed style="width:100%;" name=wr_subject itemname="Á¦¸ñ" required value="<?=$subject?>"></td></tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <tr> <td style='padding-left:20px;'>¡¤ ³»¿ë</td> <td style='padding:5 0 5 0;'> <? if ($is_dhtml_editor) { ?> <?=cheditor2('fwrite', 'wr_content', '100%', '350');?> <? } else { ?> <table width=100% cellpadding=0 cellspacing=0> <tr> <td width=50% align=left valign=bottom> <span style="cursor: pointer;" onclick="textarea_decrease('wr_content', 10);"><img src="<?=$board_skin_path?>/img/up.gif"></span> <span style="cursor: pointer;" onclick="textarea_original('wr_content', 10);"><img src="<?=$board_skin_path?>/img/start.gif"></span> <span style="cursor: pointer;" onclick="textarea_increase('wr_content', 10);"><img src="<?=$board_skin_path?>/img/down.gif"></span></td> <td width=50% align=right><? if ($write_min || $write_max) { ?><span id=char_count></span>±ÛÀÚ<?}?></td> </tr> </table> <textarea id=wr_content name=wr_content class=tx style='width:100%; word-break:break-all;' rows=10 itemname="³»¿ë" required <? if ($write_min || $write_max) { ?>onkeyup="check_byte('wr_content', 'char_count');"<?}?>><?=$content?></textarea> <? if ($write_min || $write_max) { ?><script language="javascript"> check_byte('wr_content', 'char_count'); </script><?}?> <? } ?> </td> </tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? if ($is_link) { ?> <? for ($i=1; $i<=$g4[link_count]; $i++) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ ¸µÅ© #<?=$i?></td> <td><input type='text' class=ed size=50 name='wr_link<?=$i?>' itemname='¸µÅ© #<?=$i?>' value='<?=$write["wr_link{$i}"]?>'></td> </tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? } ?> <? if ($is_file) { ?> <tr> <td style='padding-left:20px; height:30px;'><table cellpadding=0 cellspacing=0><tr><td style=" padding-top: 10px;">¡¤ ÆÄÀÏ <span onclick="add_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>+</span> <span onclick="del_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>-</span></td></tr></table></td> <td style='padding:5 0 5 0;'><table id="variableFiles" cellpadding=0 cellspacing=0></table><?// print_r2($file); ?> <script language="JavaScript"> var flen = 0; function add_file(delete_code) { var upload_count = <?=(int)$board[bo_upload_count]?>; if (upload_count && flen >= upload_count) { alert("ÀÌ °Ô½ÃÆÇÀº "+upload_count+"°³ ±îÁö¸¸ ÆÄÀÏ ¾÷·Îµå°¡ °¡´ÉÇÕ´Ï´Ù."); return; } var objTbl; var objRow; var objCell; if (document.getElementById) objTbl = document.getElementById("variableFiles"); else objTbl = document.all["variableFiles"]; objRow = objTbl.insertRow(objTbl.rows.length); objCell = objRow.insertCell(0); objCell.innerHTML = "<input type='file' class=ed size=32 name='bf_file[]' title='ÆÄÀÏ ¿ë·® <?=$upload_max_filesize?> ÀÌÇϸ¸ ¾÷·Îµå °¡´É'>"; if (delete_code) objCell.innerHTML += delete_code; else { <? if ($is_file_content) { ?> objCell.innerHTML += "<br><input type='text' class=ed size=50 name='bf_content[]' title='¾÷·Îµå À̹ÌÁö ÆÄÀÏ¿¡ ÇØ´ç µÇ´Â ³»¿ëÀ» ÀÔ·ÂÇϼ¼¿ä.'>"; <? } ?> ; } flen++; } <?=$file_script; //¼öÁ¤½Ã¿¡ ÇÊ¿äÇÑ ½ºÅ©¸³Æ®?> function del_file() { // file_length ÀÌÇϷδ Çʵ尡 »èÁ¦µÇÁö ¾Ê¾Æ¾ß ÇÕ´Ï´Ù. var file_length = <?=(int)$file_length?>; var objTbl = document.getElementById("variableFiles"); if (objTbl.rows.length - 1 > file_length) { objTbl.deleteRow(objTbl.rows.length - 1); flen--; } } </script></td> </tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_trackback) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ Æ®·¢¹éÁÖ¼Ò</td> <td><input class=ed size=50 name=wr_trackback itemname="Æ®·¢¹é" value="<?=$trackback?>"> <? if ($w=="u") { ?><input type=checkbox name="re_trackback" value="1">ÇÎ º¸³¿<? } ?></td> </tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <? if ($is_norobot) { ?> <tr> <td style='padding-left:20px; height:30px;'>¡¤ <?=$norobot_str?></td> <td><input class=ed type=input size=10 name=wr_key itemname="ÀÚµ¿µî·Ï¹æÁö" required>&nbsp;&nbsp;* ¿ÞÂÊÀÇ ±ÛÀÚÁß <font color="red">»¡°£±ÛÀÚ¸¸</font> ¼ø¼­´ë·Î ÀÔ·ÂÇϼ¼¿ä.</td> </tr> <tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr> <? } ?> <tr><td colspan=2 height=1 bgcolor=#000000></td></tr> </table> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="100%" height="30" background="<?=$board_skin_path?>/img/write_down_bg.gif"></td> </tr> <tr> <td width="100%" align="center" valign="top"> <input type=image id="btn_submit" src="<?=$board_skin_path?>/img/btn_write.gif" border=0 accesskey='s'>&nbsp; <a href="./board.php?bo_table=<?=$bo_table?>"><img id="btn_list" src="<?=$board_skin_path?>/img/btn_list.gif" border=0></a></td> </tr> </table> </td></tr></table> </form> <script language="javascript"> <? // °ü¸®ÀÚ¶ó¸é ºÐ·ù ¼±Åÿ¡ '°øÁö' ¿É¼ÇÀ» Ãß°¡ÇÔ if ($is_admin) { echo " if (typeof(document.fwrite.ca_name) != 'undefined') { document.fwrite.ca_name.options.length += 1; document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].value = '°øÁö'; document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].text = '°øÁö'; }"; } ?> with (document.fwrite) { if (typeof(wr_name) != "undefined") wr_name.focus(); else if (typeof(wr_subject) != "undefined") wr_subject.focus(); else if (typeof(wr_content) != "undefined") wr_content.focus(); if (typeof(ca_name) != "undefined") if (w.value == "u") ca_name.value = "<?=$write[ca_name]?>"; } function html_auto_br(obj) { if (obj.checked) { result = confirm("ÀÚµ¿ ÁٹٲÞÀ» ÇϽðڽÀ´Ï±î?\n\nÀÚµ¿ ÁٹٲÞÀº °Ô½Ã¹° ³»¿ëÁß ÁÙ¹Ù²ï °÷À»<br>ű׷Πº¯È¯ÇÏ´Â ±â´ÉÀÔ´Ï´Ù."); if (result) obj.value = "html2"; else obj.value = "html1"; } else obj.value = ""; } function fwrite_check(f) { var s = ""; if (s = word_filter_check(f.wr_subject.value)) { alert("Á¦¸ñ¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù"); return; } if (s = word_filter_check(f.wr_content.value)) { alert("³»¿ë¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù"); return; } if (char_min > 0 || char_max > 0) { var cnt = parseInt(document.getElementById('char_count').innerHTML); if (char_min > 0 && char_min > cnt) { alert("³»¿ëÀº "+char_min+"±ÛÀÚ ÀÌ»ó ¾²¼Å¾ß ÇÕ´Ï´Ù."); return; } else if (char_max > 0 && char_max < cnt) { alert("³»¿ëÀº "+char_max+"±ÛÀÚ ÀÌÇÏ·Î ¾²¼Å¾ß ÇÕ´Ï´Ù."); return; } } if (typeof(f.wr_key) != "undefined") { if (hex_md5(f.wr_key.value) != md5_norobot_key) { alert("ÀÚµ¿µî·Ï¹æÁö¿ë »¡°£±ÛÀÚ°¡ ¼ø¼­´ë·Î ÀԷµÇÁö ¾Ê¾Ò½À´Ï´Ù."); f.wr_key.focus(); return; } } <? if ($is_dhtml_editor) { echo cheditor3('wr_content'); echo "if (!document.getElementById('wr_content').value) { alert('³»¿ëÀ» ÀÔ·ÂÇϽʽÿÀ.'); return; } "; } ?> document.getElementById('btn_submit').disabled = true; document.getElementById('btn_list').disabled = true; f.action = "./write_update.php"; f.submit(); } </script>
mrquestion/gnuboard4
skin/board/basic_old/write.skin.php
PHP
gpl-2.0
12,050
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: boss_lord_marrowgar SD%Complete: 0% SDComment: SDCategory: Icecrown Citadel EndScriptData */ #include "precompiled.h" enum { SAY_INTRO = -1631001, SAY_AGGRO = -1631002, SAY_BONE_STORM = -1631003, SAY_BONE_SPIKE_1 = -1631004, SAY_BONE_SPIKE_2 = -1631005, SAY_BONE_SPIKE_3 = -1631006, SAY_SLAY_1 = -1631007, SAY_SLAY_2 = -1631008, SAY_DEATH = -1631009, SAY_BERSERK = -1631010, }; void AddSC_boss_lord_marrowgar() { }
udw/mangos_hw2system_335
src/bindings/scriptdev2/scripts/northrend/icecrown_citadel/icecrown_citadel/boss_lord_marrowgar.cpp
C++
gpl-2.0
1,417
var wocs_loading_first_time = true;//simply flag var jQuery(function () { if (woocs_drop_down_view == 'chosen') { try { if (jQuery("select.woocommerce-currency-switcher").length) { jQuery("select.woocommerce-currency-switcher").chosen({ disable_search_threshold: 10 }); jQuery.each(jQuery('.woocommerce-currency-switcher-form .chosen-container'), function (index, obj) { jQuery(obj).css({'width': jQuery(this).prev('select').data('width')}); }); } } catch (e) { console.log(e); } } if (woocs_drop_down_view == 'ddslick') { try { jQuery.each(jQuery('select.woocommerce-currency-switcher'), function (index, obj) { var width = jQuery(obj).data('width'); var flag_position = jQuery(obj).data('flag-position'); jQuery(obj).ddslick({ //data: ddData, width: width, imagePosition: flag_position, selectText: "Select currency", //background:'#ff0000', onSelected: function (data) { if (!wocs_loading_first_time) { jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').find('input[name="woocommerce-currency-switcher"]').eq(0).val(data.selectedData.value); jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').submit(); } } }); }); } catch (e) { console.log(e); } } //for flags view instead of drop-down jQuery('.woocs_flag_view_item').click(function () { if (jQuery(this).hasClass('woocs_flag_view_item_current')) { return false; } //*** if (woocs_is_get_empty) { window.location = window.location.href + '?currency=' + jQuery(this).data('currency'); } else { var l = window.location.href; l = l.replace(/(\?currency=[a-zA-Z]+)/g, '?'); l = l.replace(/(&currency=[a-zA-Z]+)/g, ''); window.location = l + '&currency=' + jQuery(this).data('currency'); } return false; }); wocs_loading_first_time = false; });
asshurimrepo/mont8
wp-content/plugins/woocommerce-currency-switcher/js/front.js
JavaScript
gpl-2.0
2,447
# -*- coding: utf-8 -*- # from rest_framework import viewsets from rest_framework.exceptions import ValidationError from django.db import transaction from django.utils.translation import ugettext as _ from django.conf import settings from orgs.mixins.api import RootOrgViewMixin from common.permissions import IsValidUser from perms.utils import AssetPermissionUtil from ..models import CommandExecution from ..serializers import CommandExecutionSerializer from ..tasks import run_command_execution class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet): serializer_class = CommandExecutionSerializer permission_classes = (IsValidUser,) def get_queryset(self): return CommandExecution.objects.filter( user_id=str(self.request.user.id) ) def check_hosts(self, serializer): data = serializer.validated_data assets = data["hosts"] system_user = data["run_as"] util = AssetPermissionUtil(self.request.user) util.filter_permissions(system_users=system_user.id) permed_assets = util.get_assets().filter(id__in=[a.id for a in assets]) invalid_assets = set(assets) - set(permed_assets) if invalid_assets: msg = _("Not has host {} permission").format( [str(a.id) for a in invalid_assets] ) raise ValidationError({"hosts": msg}) def check_permissions(self, request): if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user: return self.permission_denied(request, "Command execution disabled") return super().check_permissions(request) def perform_create(self, serializer): self.check_hosts(serializer) instance = serializer.save() instance.user = self.request.user instance.save() cols = self.request.query_params.get("cols", '80') rows = self.request.query_params.get("rows", '24') transaction.on_commit(lambda: run_command_execution.apply_async( args=(instance.id,), kwargs={"cols": cols, "rows": rows}, task_id=str(instance.id) ))
zsjohny/jumpserver
apps/ops/api/command.py
Python
gpl-2.0
2,150
package main import ( "bytes" "fmt" "regexp" ) func main() { match, _ := regexp.MatchString("p([a-z]+)ch", "peach") fmt.Println(match) r, _ := regexp.Compile("p([a-z]+)ch") fmt.Println(r.MatchString("peach")) fmt.Println(r.FindString("peach punch")) fmt.Println(r.FindStringIndex("peach punch")) fmt.Println(r.FindStringSubmatch("peach punch")) fmt.Println(r.FindStringSubmatchIndex("peach punch")) fmt.Println(r.FindAllString("peach punch pinch", -1)) fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1)) fmt.Println(r.FindAllString("peach punch pinch", 2)) fmt.Println(r.Match([]byte("peach"))) r = regexp.MustCompile("p([a+z])ch") fmt.Println(r) fmt.Println(r.ReplaceAllString("a peach", "<fruit>")) in := []byte("a peach") out := r.ReplaceAllFunc(in, bytes.ToUpper) fmt.Println(string(out)) }
coyotey/goLearnExample
45_regularexpressions.go
GO
gpl-2.0
845
<?php namespace Sidus\EAVDataGridBundle\Model; use Sidus\DataGridBundle\Model\DataGrid as BaseDataGrid; use Sidus\EAVFilterBundle\Configuration\EAVFilterConfigurationHandler; use Sidus\EAVModelBundle\Model\FamilyInterface; use Sidus\EAVModelBundle\Translator\TranslatableTrait; use Symfony\Component\Translation\TranslatorInterface; /** * Extended datagrid configuration for EAV entities */ class DataGrid extends BaseDataGrid { use TranslatableTrait; /** @var FamilyInterface */ protected $family; /** * DataGrid constructor. * * @param string $code * @param array $configuration * @param TranslatorInterface $translator * * @throws \Exception */ public function __construct($code, array $configuration, TranslatorInterface $translator = null) { $this->translator = $translator; parent::__construct($code, $configuration); } /** * @return FamilyInterface */ public function getFamily() { return $this->family; } /** * @param FamilyInterface $family * * @return DataGrid */ public function setFamily($family) { $this->family = $family; $filterConfig = $this->getFilterConfig(); if ($filterConfig instanceof EAVFilterConfigurationHandler) { $filterConfig->setFamily($family); } return $this; } /** * @param string $key * @param array $columnConfiguration * * @throws \Exception */ protected function createColumn($key, array $columnConfiguration) { if ($this->translator) { $columnConfiguration['translator'] = $this->translator; } $this->columns[] = new Column($key, $this, $columnConfiguration); } }
VincentChalnot/SidusEAVDataGridBundle
Model/DataGrid.php
PHP
gpl-2.0
1,823
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template is_interval_container&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../index.html" title="Chapter&#160;1.&#160;Boost.Icl"> <link rel="up" href="../../header/boost/icl/interval_set_hpp.html" title="Header &lt;boost/icl/interval_set.hpp&gt;"> <link rel="prev" href="is_set_i_idm44994781476752.html" title="Struct template is_set&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;"> <link rel="next" href="is_inter_idm44994781457776.html" title="Struct template is_interval_joiner&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="is_set_i_idm44994781476752.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/interval_set_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_inter_idm44994781457776.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.icl.is_inter_idm44994781467264"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template is_interval_container&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;</span></h2> <p>boost::icl::is_interval_container&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../header/boost/icl/interval_set_hpp.html" title="Header &lt;boost/icl/interval_set.hpp&gt;">boost/icl/interval_set.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> DomainT<span class="special">,</span> <span class="identifier">ICL_COMPARE</span> Compare<span class="special">,</span> <span class="identifier">ICL_INTERVAL</span><span class="special">(</span><span class="identifier">ICL_COMPARE</span><span class="special">)</span> Interval<span class="special">,</span> <span class="identifier">ICL_ALLOC</span> Alloc<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="is_inter_idm44994781467264.html" title="Struct template is_interval_container&lt;icl::interval_set&lt; DomainT, Compare, Interval, Alloc &gt;&gt;">is_interval_container</a><span class="special">&lt;</span><span class="identifier">icl</span><span class="special">::</span><span class="identifier">interval_set</span><span class="special">&lt;</span> <span class="identifier">DomainT</span><span class="special">,</span> <span class="identifier">Compare</span><span class="special">,</span> <span class="identifier">Interval</span><span class="special">,</span> <span class="identifier">Alloc</span> <span class="special">&gt;</span><span class="special">&gt;</span> <span class="special">{</span> <span class="comment">// types</span> <span class="keyword">typedef</span> <span class="identifier">is_interval_container</span><span class="special">&lt;</span> <a class="link" href="interval_set.html" title="Class template interval_set">icl::interval_set</a><span class="special">&lt;</span> <span class="identifier">DomainT</span><span class="special">,</span> <span class="identifier">Compare</span><span class="special">,</span> <span class="identifier">Interval</span><span class="special">,</span> <span class="identifier">Alloc</span> <span class="special">&gt;</span> <span class="special">&gt;</span> <a name="boost.icl.is_inter_idm44994781467264.type"></a><span class="identifier">type</span><span class="special">;</span> <span class="comment">// <a class="link" href="is_inter_idm44994781467264.html#idm44994781460848-bb">public member functions</a></span> <a class="link" href="is_inter_idm44994781467264.html#idm44994781460288-bb"><span class="identifier">BOOST_STATIC_CONSTANT</span></a><span class="special">(</span><span class="keyword">bool</span><span class="special">,</span> <span class="identifier">value</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="idm46161810876816"></a><h2>Description</h2> <div class="refsect2"> <a name="idm46161810876400"></a><h3> <a name="idm44994781460848-bb"></a><code class="computeroutput">is_interval_container</code> public member functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"> <a name="idm44994781460288-bb"></a><span class="identifier">BOOST_STATIC_CONSTANT</span><span class="special">(</span><span class="keyword">bool</span><span class="special">,</span> <span class="identifier">value</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span></pre></li></ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2007-2010 Joachim Faulhaber<br>Copyright &#169; 1999-2006 Cortex Software GmbH<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="is_set_i_idm44994781476752.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/interval_set_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_inter_idm44994781457776.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
FFMG/myoddweb.piger
myodd/boost/libs/icl/doc/html/boost/icl/is_inter_idm44994781467264.html
HTML
gpl-2.0
7,322
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>food blogging | Introduction to New Media</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="shortcut icon" href="../../misc/favicon.ico" type="image/x-icon" /> <style type="text/css" media="all">@import "../../modules/node/node.css";</style> <style type="text/css" media="all">@import "../../modules/poll/poll.css";</style> <style type="text/css" media="all">@import "../../modules/system/defaults.css";</style> <style type="text/css" media="all">@import "../../modules/system/system.css";</style> <style type="text/css" media="all">@import "../../modules/user/user.css";</style> <style type="text/css" media="all">@import "../../sites/all/modules/tagadelic/tagadelic.css";</style> <style type="text/css" media="all">@import "../../modules/comment/comment.css";</style> <style type="text/css" media="all">@import "../../sites/all/themes/newmedia/style.css";</style> <!--[if IE 6]> <style type="text/css" media="all">@import "../../sites/all/themes/newmedia/ie-fixes/ie6.css";</style> <![endif]--> <!--[if lt IE 7.]> <script defer type="text/javascript" src="../../sites/all/themes/newmedia/ie-fixes/pngfix.js"></script> <![endif]--> </head> <body> <div id="page"> <!-- begin wrapper --> <div id="container"> <!-- primary links --> <!-- begin header --> <div id="header"> <!-- site logo --> <!-- end site logo --> <!-- site name --> <h1> <a href="../../index.html" title="Home"> Introduction to New Media </a> </h1> <!-- end site name --> <!-- site slogan --> <!-- end site slogan --> <div id="menu"> <ul class="links-menu"> <li><a href="http://machines.plannedobsolescence.net" title="associate professor of english and media studies">kathleen fitzpatrick</a></li> <li><a href="http://www.pomona.edu" title="in claremont, california">pomona college</a></li> </ul> </div><!-- end primary links --> </div><!-- end header --> <!-- search box in nowhere land - NEEDS WORK--> <!-- end search box --> <!-- content --> <!-- <div id="main">--> <!-- begin main content --> <div id="mainContent" style="width: 530px;"> <div class="breadcrumb"><div class="breadcrumb"><a href="../../index.html">Home</a> » <a href="../../blog/index.html">Blogs</a> » <a href="../../blog/17/index.html">ColoradoGirl&#039;s blog</a></div></div> <h1 class="pageTitle">food blogging</h1> <div class="node"> <div class="submitted">By ColoradoGirl - Posted on 4 February 2007 - 2:06pm.</div> <div class="taxonomy">Tagged: <ul class="links inline"><li class="first taxonomy_term_2"><a href="../../taxonomy/term/2/index.html" rel="tag" title="" class="taxonomy_term_2">blogging</a></li> <li class="last taxonomy_term_39"><a href="../../taxonomy/term/39/index.html" rel="tag" title="" class="taxonomy_term_39">food critics</a></li> </ul></div> <div class="content"><p>I love to eat. Ok, let me clarify that – I love to eat good food. Today while savoring the Sunday NY Times Style section, I saw an article of blogging interest, <a href="http://www.nytimes.com/2007/02/04/fashion/04bloggers.html?_r=1&oref=slogin"> Sharp Bites.</a> Exploring how restaurant critics (or the more likely case on blogs, people like me who just love to eat out and sample new venues) are blogging their way into internet fame; "hundreds of thousands of hits" it what one blog got after it started posting a comical <a href="http://www.amateurgourmet.com/the_amateur_gourmet/2004/02/janet_jackson_b.html"> recipe </a> for cupcakes that resembled Janet Jackson's bare breast at the Super Bowl. </p> <p>I am interested in how the blogs critiquing food and restaurants are able to be more open, more honest, and more vicious (??) with their comments. We talked about the emergence of more opinionated political writing in the blogosphere, and I think you'll agree with me that food critiques on blogs are la même chose. </p> <p>What does this upsurge in food bloggers do to reputation of restaurants? I recently dined at a hole-in-the wall sushi place outside L.A. . . . I consider myself to be a sushi expert (having traveled to Japan and consumed mass amounts of the delicious food there and at good sushi joints elsewhere) and what I tasted at this particular restaurant was absolutely sickening. However, a blog I found congratulated this very restaurant on serving "sushi that even sushi haters will love." Hmmm, where's the truth there?!</p> </div> <div class="links"><ul class="links inline"><li class="first last blog_usernames_blog"><a href="../../blog/17/index.html" title="Read ColoradoGirl&#039;s latest blog entries." class="blog_usernames_blog">ColoradoGirl&#039;s blog</a></li> </ul></div> </div> <div id="comments"><a id="comment-38"></a> <div class="comment"> <div class="commentTitle"><a href="index.html#comment-38" class="active">Not Only Good But Healthy</a></div> <div class="submitted">Submitted by Bumpkins on 4 February 2007 - 7:14pm.</div> <div class="content"><p><a href="http://www.tsl.pomona.edu/index.php?article=2071">See</a>.</p> <p>- If this takes away your anonymity feel free to delete it.</p> </div> <div class="links"></div> </div> </div> </div> <!-- Begin Sidebars --> <div id="sideBars-bg" style="width: 415px;"> <div id="sideBars" style="width: 415px;"> <!-- left sidebar --> <div id="leftSidebar"> <div class="block block-block" id="block-block-1"> <h2 class="title"></h2> <div class="content"><p><a href="../../index.html">introduction to new media</a> is the spring 2007 course website for media studies 51 at pomona college in claremont, california.</p> <p><a href="http://machines.plannedobsolescence.net">the professor</a><br /> <a href="../../syllabus/index.html">the syllabus</a><br /> <a href="../../wiki/index.html">the wiki</a><br /> <a href="https://sakai.claremont.edu/portal/site/CX_mtg_26747">the sakai site</a><br /> <a href="../../taxonomy/term/1/index.html">more information</a></p> </div> </div> <div class="block block-tagadelic" id="block-tagadelic-1"> <h2 class="title">tags</h2> <div class="content"><a href="../../taxonomy/term/56/index.html" class="tagadelic level2" rel="tag">Artificial Intelligence</a> <a href="../../taxonomy/term/14/index.html" class="tagadelic level2" rel="tag">blog</a> <a href="../../taxonomy/term/2/index.html" class="tagadelic level10" rel="tag">blogging</a> <a href="../../taxonomy/term/42/index.html" class="tagadelic level8" rel="tag">class discussion</a> <a href="../../taxonomy/term/4/index.html" class="tagadelic level10" rel="tag">class reading</a> <a href="../../taxonomy/term/8/index.html" class="tagadelic level1" rel="tag">community</a> <a href="../../taxonomy/term/1/index.html" class="tagadelic level2" rel="tag">course information</a> <a href="../../taxonomy/term/106/index.html" class="tagadelic level2" rel="tag">cyborg</a> <a href="../../taxonomy/term/77/index.html" class="tagadelic level3" rel="tag">Facade</a> <a href="../../taxonomy/term/119/index.html" class="tagadelic level3" rel="tag">final project</a> <a href="../../taxonomy/term/7/index.html" class="tagadelic level3" rel="tag">first blog</a> <a href="../../taxonomy/term/36/index.html" class="tagadelic level2" rel="tag">Future</a> <a href="../../taxonomy/term/64/index.html" class="tagadelic level2" rel="tag">Machines</a> <a href="../../taxonomy/term/79/index.html" class="tagadelic level2" rel="tag">midterm project</a> <a href="../../taxonomy/term/13/index.html" class="tagadelic level1" rel="tag">Music</a> <a href="../../taxonomy/term/20/index.html" class="tagadelic level3" rel="tag">new generation</a> <a href="../../taxonomy/term/31/index.html" class="tagadelic level6" rel="tag">new media</a> <a href="../../taxonomy/term/70/index.html" class="tagadelic level8" rel="tag">Proposal</a> <a href="../../taxonomy/term/112/index.html" class="tagadelic level2" rel="tag">sight machine</a> <a href="../../taxonomy/term/22/index.html" class="tagadelic level2" rel="tag">social networking</a> <a href="../../taxonomy/term/98/index.html" class="tagadelic level7" rel="tag">term project</a> <a href="../../taxonomy/term/19/index.html" class="tagadelic level7" rel="tag">web 2.0</a> <a href="../../taxonomy/term/24/index.html" class="tagadelic level8" rel="tag">wiki</a> <a href="../../taxonomy/term/18/index.html" class="tagadelic level6" rel="tag">Wikipedia</a> <a href="../../taxonomy/term/34/index.html" class="tagadelic level6" rel="tag">YouTube</a> <div class='more-link'><a href="../../tagadelic/chunk/1/index.html">more tags</a></div></div> </div> <div class="block block-user" id="block-user-1"> <h2 class="title">Navigation</h2> <div class="content"> <ul class="menu"> <li class="leaf"><a href="../../tracker/index.html">Recent posts</a></li> </ul> </div> </div> </div> <!-- right sidebar --> <div id="rightSidebar"> <div class="block block-comment" id="block-comment-0"> <h2 class="title">Recent comments</h2> <div class="content"><div class="item-list"><ul><li><a href="../247/index.html#comment-440">resistance</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-439">20 hours of source</a><br />3 years 51 weeks ago</li><li><a href="../262/index.html#comment-438">used?</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-437">it&#039;s everywhere</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-436">Really good! I liked how you</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-435">nice!</a><br />3 years 51 weeks ago</li><li><a href="../251/index.html#comment-434">Linux Parody</a><br />3 years 51 weeks ago</li><li><a href="../259/index.html#comment-433">Me Too!</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-432">McDonald&#039;s</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-431">Slash Fan Vid</a><br />3 years 51 weeks ago</li></ul></div></div> </div> <div class="block block-block" id="block-block-2"> <h2 class="title"></h2> <div class="content"><h3>social software tools</h3> <ul> <li><a href="http://technorati.com/" target="_blank">Technorati</a></li> <li><a href="http://del.icio.us/" target="_blank">del.icio.us</a></li> <li><a href="http://www.flickr.com/" target="_blank">Flickr</a></li> <li><a href="http://www.bloglines.com/" target="_blank">Bloglines</a></li> <li><a href="http://www.youtube.com/" target="_blank">YouTube</a></li> </ul> <h3>new media studies sites</h3> <ul> <li><a href="http://www.digitalhumanities.org/companion/" target="_blank">A Companion to Digital Humanities</a></li> </ul> </div> </div> </div> </div><!-- end sidebars --> </div><!-- end sideBars-bg --> <!-- footer --> <div id="footer"> </div><!-- end footer --> </div><!-- end container --> </div><!-- end page --> <!-- Start of StatCounter Code --> <script type="text/javascript"> var sc_project=3034095; var sc_invisible=1; var sc_partition=33; var sc_security="ec028fa0"; </script> <script type="text/javascript" src="http://www.statcounter.com/counter/counter_xhtml.js"></script><noscript><div class="statcounter"><a class="statcounter" href="http://www.statcounter.com/"><img class="statcounter" src="http://c34.statcounter.com/3034095/0/ec028fa0/1/" alt="blog stats" /></a></div></noscript> <!-- End of StatCounter Code --> </body> </html> <!-- Localized -->
kfitz/machines
51-2007/node/48/index.html
HTML
gpl-2.0
12,037
CREATE USER 'iasst'@'localhost' IDENTIFIED BY '123456'; GRANT SELECT ON *.* TO 'iasst'@'localhost'; GRANT SELECT, INSERT, UPDATE, REFERENCES, DELETE, CREATE, DROP, ALTER, INDEX, TRIGGER, CREATE VIEW, SHOW VIEW, EXECUTE, ALTER ROUTINE, CREATE ROUTINE, CREATE TEMPORARY TABLES, LOCK TABLES, EVENT ON `iasst`.* TO 'iasst'@'localhost'; GRANT GRANT OPTION ON `iasst`.* TO 'iasst'@'localhost';
wzx-xle/iAsst
iAsst-web/src/sql/create-user.sql
SQL
gpl-2.0
396
/* MobileRobots Advanced Robotics Interface for Applications (ARIA) Copyright (C) 2004, 2005 ActivMedia Robotics LLC Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc. Copyright (C) 2010, 2011 Adept Technology, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at [email protected] or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481 */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.36 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.mobilerobots.Aria; public class ArDPPTU extends ArPTZ { /* (begin code from javabody_derived typemap) */ private long swigCPtr; /* for internal use by swig only */ public ArDPPTU(long cPtr, boolean cMemoryOwn) { super(AriaJavaJNI.SWIGArDPPTUUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(ArDPPTU obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody_derived typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if(swigCPtr != 0 && swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.delete_ArDPPTU(swigCPtr); } swigCPtr = 0; super.delete(); } public ArDPPTU(ArRobot robot, ArDPPTU.DeviceType deviceType) { this(AriaJavaJNI.new_ArDPPTU__SWIG_0(ArRobot.getCPtr(robot), robot, deviceType.swigValue()), true); } public ArDPPTU(ArRobot robot) { this(AriaJavaJNI.new_ArDPPTU__SWIG_1(ArRobot.getCPtr(robot), robot), true); } public boolean init() { return AriaJavaJNI.ArDPPTU_init(swigCPtr, this); } public boolean canZoom() { return AriaJavaJNI.ArDPPTU_canZoom(swigCPtr, this); } public boolean blank() { return AriaJavaJNI.ArDPPTU_blank(swigCPtr, this); } public boolean resetCalib() { return AriaJavaJNI.ArDPPTU_resetCalib(swigCPtr, this); } public boolean disableReset() { return AriaJavaJNI.ArDPPTU_disableReset(swigCPtr, this); } public boolean resetTilt() { return AriaJavaJNI.ArDPPTU_resetTilt(swigCPtr, this); } public boolean resetPan() { return AriaJavaJNI.ArDPPTU_resetPan(swigCPtr, this); } public boolean resetAll() { return AriaJavaJNI.ArDPPTU_resetAll(swigCPtr, this); } public boolean saveSet() { return AriaJavaJNI.ArDPPTU_saveSet(swigCPtr, this); } public boolean restoreSet() { return AriaJavaJNI.ArDPPTU_restoreSet(swigCPtr, this); } public boolean factorySet() { return AriaJavaJNI.ArDPPTU_factorySet(swigCPtr, this); } public boolean panTilt(double pdeg, double tdeg) { return AriaJavaJNI.ArDPPTU_panTilt(swigCPtr, this, pdeg, tdeg); } public boolean pan(double deg) { return AriaJavaJNI.ArDPPTU_pan(swigCPtr, this, deg); } public boolean panRel(double deg) { return AriaJavaJNI.ArDPPTU_panRel(swigCPtr, this, deg); } public boolean tilt(double deg) { return AriaJavaJNI.ArDPPTU_tilt(swigCPtr, this, deg); } public boolean tiltRel(double deg) { return AriaJavaJNI.ArDPPTU_tiltRel(swigCPtr, this, deg); } public boolean panTiltRel(double pdeg, double tdeg) { return AriaJavaJNI.ArDPPTU_panTiltRel(swigCPtr, this, pdeg, tdeg); } public boolean limitEnforce(boolean val) { return AriaJavaJNI.ArDPPTU_limitEnforce(swigCPtr, this, val); } public boolean immedExec() { return AriaJavaJNI.ArDPPTU_immedExec(swigCPtr, this); } public boolean slaveExec() { return AriaJavaJNI.ArDPPTU_slaveExec(swigCPtr, this); } public boolean awaitExec() { return AriaJavaJNI.ArDPPTU_awaitExec(swigCPtr, this); } public boolean haltAll() { return AriaJavaJNI.ArDPPTU_haltAll(swigCPtr, this); } public boolean haltPan() { return AriaJavaJNI.ArDPPTU_haltPan(swigCPtr, this); } public boolean haltTilt() { return AriaJavaJNI.ArDPPTU_haltTilt(swigCPtr, this); } public double getMaxPosPan() { return AriaJavaJNI.ArDPPTU_getMaxPosPan(swigCPtr, this); } public double getMaxNegPan() { return AriaJavaJNI.ArDPPTU_getMaxNegPan(swigCPtr, this); } public double getMaxPosTilt() { return AriaJavaJNI.ArDPPTU_getMaxPosTilt(swigCPtr, this); } public double getMaxNegTilt() { return AriaJavaJNI.ArDPPTU_getMaxNegTilt(swigCPtr, this); } public double getMaxPanSlew() { return AriaJavaJNI.ArDPPTU_getMaxPanSlew(swigCPtr, this); } public double getMinPanSlew() { return AriaJavaJNI.ArDPPTU_getMinPanSlew(swigCPtr, this); } public double getMaxTiltSlew() { return AriaJavaJNI.ArDPPTU_getMaxTiltSlew(swigCPtr, this); } public double getMinTiltSlew() { return AriaJavaJNI.ArDPPTU_getMinTiltSlew(swigCPtr, this); } public double getMaxPanAccel() { return AriaJavaJNI.ArDPPTU_getMaxPanAccel(swigCPtr, this); } public double getMinPanAccel() { return AriaJavaJNI.ArDPPTU_getMinPanAccel(swigCPtr, this); } public double getMaxTiltAccel() { return AriaJavaJNI.ArDPPTU_getMaxTiltAccel(swigCPtr, this); } public double getMinTiltAccel() { return AriaJavaJNI.ArDPPTU_getMinTiltAccel(swigCPtr, this); } public boolean initMon(double deg1, double deg2, double deg3, double deg4) { return AriaJavaJNI.ArDPPTU_initMon(swigCPtr, this, deg1, deg2, deg3, deg4); } public boolean enMon() { return AriaJavaJNI.ArDPPTU_enMon(swigCPtr, this); } public boolean disMon() { return AriaJavaJNI.ArDPPTU_disMon(swigCPtr, this); } public boolean offStatPower() { return AriaJavaJNI.ArDPPTU_offStatPower(swigCPtr, this); } public boolean regStatPower() { return AriaJavaJNI.ArDPPTU_regStatPower(swigCPtr, this); } public boolean lowStatPower() { return AriaJavaJNI.ArDPPTU_lowStatPower(swigCPtr, this); } public boolean highMotPower() { return AriaJavaJNI.ArDPPTU_highMotPower(swigCPtr, this); } public boolean regMotPower() { return AriaJavaJNI.ArDPPTU_regMotPower(swigCPtr, this); } public boolean lowMotPower() { return AriaJavaJNI.ArDPPTU_lowMotPower(swigCPtr, this); } public boolean panAccel(double deg) { return AriaJavaJNI.ArDPPTU_panAccel(swigCPtr, this, deg); } public boolean tiltAccel(double deg) { return AriaJavaJNI.ArDPPTU_tiltAccel(swigCPtr, this, deg); } public boolean basePanSlew(double deg) { return AriaJavaJNI.ArDPPTU_basePanSlew(swigCPtr, this, deg); } public boolean baseTiltSlew(double deg) { return AriaJavaJNI.ArDPPTU_baseTiltSlew(swigCPtr, this, deg); } public boolean upperPanSlew(double deg) { return AriaJavaJNI.ArDPPTU_upperPanSlew(swigCPtr, this, deg); } public boolean lowerPanSlew(double deg) { return AriaJavaJNI.ArDPPTU_lowerPanSlew(swigCPtr, this, deg); } public boolean upperTiltSlew(double deg) { return AriaJavaJNI.ArDPPTU_upperTiltSlew(swigCPtr, this, deg); } public boolean lowerTiltSlew(double deg) { return AriaJavaJNI.ArDPPTU_lowerTiltSlew(swigCPtr, this, deg); } public boolean indepMove() { return AriaJavaJNI.ArDPPTU_indepMove(swigCPtr, this); } public boolean velMove() { return AriaJavaJNI.ArDPPTU_velMove(swigCPtr, this); } public boolean panSlew(double deg) { return AriaJavaJNI.ArDPPTU_panSlew(swigCPtr, this, deg); } public boolean tiltSlew(double deg) { return AriaJavaJNI.ArDPPTU_tiltSlew(swigCPtr, this, deg); } public boolean panSlewRel(double deg) { return AriaJavaJNI.ArDPPTU_panSlewRel(swigCPtr, this, deg); } public boolean tiltSlewRel(double deg) { return AriaJavaJNI.ArDPPTU_tiltSlewRel(swigCPtr, this, deg); } public double getPan() { return AriaJavaJNI.ArDPPTU_getPan(swigCPtr, this); } public double getTilt() { return AriaJavaJNI.ArDPPTU_getTilt(swigCPtr, this); } public double getPanSlew() { return AriaJavaJNI.ArDPPTU_getPanSlew(swigCPtr, this); } public double getTiltSlew() { return AriaJavaJNI.ArDPPTU_getTiltSlew(swigCPtr, this); } public double getBasePanSlew() { return AriaJavaJNI.ArDPPTU_getBasePanSlew(swigCPtr, this); } public double getBaseTiltSlew() { return AriaJavaJNI.ArDPPTU_getBaseTiltSlew(swigCPtr, this); } public double getPanAccel() { return AriaJavaJNI.ArDPPTU_getPanAccel(swigCPtr, this); } public double getTiltAccel() { return AriaJavaJNI.ArDPPTU_getTiltAccel(swigCPtr, this); } public final static class DeviceType { public final static DeviceType PANTILT_DEFAULT = new DeviceType("PANTILT_DEFAULT"); public final static DeviceType PANTILT_PTUD47 = new DeviceType("PANTILT_PTUD47"); public final int swigValue() { return swigValue; } public String toString() { return swigName; } public static DeviceType swigToEnum(int swigValue) { if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue) return swigValues[swigValue]; for (int i = 0; i < swigValues.length; i++) if (swigValues[i].swigValue == swigValue) return swigValues[i]; throw new IllegalArgumentException("No enum " + DeviceType.class + " with value " + swigValue); } private DeviceType(String swigName) { this.swigName = swigName; this.swigValue = swigNext++; } private DeviceType(String swigName, int swigValue) { this.swigName = swigName; this.swigValue = swigValue; swigNext = swigValue+1; } private DeviceType(String swigName, DeviceType swigEnum) { this.swigName = swigName; this.swigValue = swigEnum.swigValue; swigNext = this.swigValue+1; } private static DeviceType[] swigValues = { PANTILT_DEFAULT, PANTILT_PTUD47 }; private static int swigNext = 0; private final int swigValue; private final String swigName; } }
admo/aria
aria/java/ArDPPTU.java
Java
gpl-2.0
10,851
<?php /********************************************************************************** * * ##### * # # ##### ## ##### # # #### ###### # # #### # # # ###### * # # # # # # # # # ## # # # # ## # # * ##### # # # # # # #### ##### # # # # # # # # ##### * # # ###### # # # # # # # # # ### # # # # # * # # # # # # # # # # # # ## # # # # ## # * ##### # # # # #### #### ###### # # #### # # # ###### * * the missing event broker * Perfdata Backend Extension for Rrdtool * * -------------------------------------------------------------------------------- * * Copyright (c) 2014 - present Daniel Ziegler <[email protected]> * * 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 in version 2 * * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * -------------------------------------------------------------------------------- * * This extension for statusengine uses the parsed performance data and * saves performance data to graphite * So you dont need to install any additional software to get this job done * **********************************************************************************/ class GraphiteBackendTask extends AppShell{ public $Config = []; private $host; private $port; private $prefix; private $socket; private $lastErrNo; private $hostnameCache = []; private $servicenameCache = []; public function init($Config){ $this->Config = $Config; $this->host = $this->Config['host']; $this->port = $this->Config['port']; $this->prefix = $this->Config['prefix']; } /** * @param array $parsedPerfdata * @param string $hostname * @param string $servicedesc * @param int $timestamp */ public function save($parsedPerfdata, $hostname, $servicedesc, $timestamp){ if($this->connect()){ foreach($parsedPerfdata as $ds => $_data){ $data = $this->buildString($ds, $_data, $hostname, $servicedesc, $timestamp); $this->write($data); } } $this->disconnect(); } private function write($message){ $message .= PHP_EOL; $this->lastErrNo = null; if(!@socket_send($this->socket, $message, strlen($message), 0)){ CakeLog::error(sprintf( 'Graphite save error: %s %s', $this->getLastErrNo(), $this->getLastError() )); return false; } return true; } private function connect(){ $this->socket = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP); if(!@socket_connect($this->socket, $this->host, $this->port)){ CakeLog::error(sprintf( 'Graphite connection error: %s %s', $this->getLastErrNo(), $this->getLastError() )); return false; } return true; } private function disconnect(){ if(is_resource($this->socket)){ socket_close($this->socket); } $this->socket = null; } private function getLastErrNo(){ if(is_resource($this->socket)){ $this->lastErrNo = socket_last_error($this->socket); return $this->lastErrNo; } return false; } private function getLastError(){ return socket_strerror($this->lastErrNo); } private function buildString($datasource, $data, $hostname, $servicedesc, $timestamp){ $datasource = $this->replaceCharacters($datasource); $hostname = $this->replaceCharacters($hostname); $servicedesc = $this->replaceCharacters($servicedesc); return sprintf( '%s.%s.%s.%s %s %s', $this->prefix, $hostname, $servicedesc, $datasource, $data['current'], $timestamp ); } public function replaceCharacters($str){ return preg_replace($this->Config['replace_characters'], '_', $str); } public function requireHostNameCaching(){ if($this->Config['use_host_display_name'] === true){ return true; } return false; } public function requireServiceNameCaching(){ if($this->Config['use_service_display_name'] === true){ return true; } return false; } public function requireNameCaching(){ if($this->requireHostNameCaching() === true){ return true; } if($this->requireServiceNameCaching() === true){ return true; } return false; } public function addHostdisplayNameToCache($hostname, $hostdisplayname){ $this->hostnameCache[md5($hostname)] = $hostdisplayname; } public function getHostdisplayNameFromCache($hostname){ if(isset($this->hostnameCache[md5($hostname)])){ return $this->hostnameCache[md5($hostname)]; } return null; } public function addServicedisplayNameToCache($hostname, $servicedesc, $servicedisplayname){ if(!isset($this->servicenameCache[md5($hostname)])){ $this->servicenameCache[md5($hostname)] = []; } $this->servicenameCache[md5($hostname)][md5($servicedesc)] = $servicedisplayname; } public function getServicedisplayNameFromCache($hostname, $servicedesc){ if(isset($this->servicenameCache[md5($hostname)][md5($servicedesc)])){ return $this->servicenameCache[md5($hostname)][md5($servicedesc)]; } return null; } public function clearCache(){ $this->hostnameCache = []; $this->servicenameCache = []; } }
nook24/statusengine
cakephp/app/Console/Command/Task/GraphiteBackendTask.php
PHP
gpl-2.0
5,656
<?php // Global variables global $map_count, $ish_options; $map_count++; // Default SC attributes $defaults = array( 'color' => '', 'zoom' => '15', 'invert_colors' => '', 'height' => '', ); // Extract all attributes $sc_atts = $this->extract_sc_attributes( $defaults, $atts ); // Add ID if empty as it is necessary for Google Maps to work if ( empty( $sc_atts['id'] ) ){ $sc_atts['id'] = 'ish-gmap-' . $map_count; } // Make sure to include the scripts for Google Maps and the Generation of the marker infoboxes on click wp_enqueue_script( 'ish-gmaps' ); // Convert color class to color value if ( isset( $ish_options[ $sc_atts['color'] ] ) ){ $sc_atts['color'] = $ish_options[ $sc_atts['color'] ]; } // SHORTCODE BEGIN $return = ''; $return .= '<div class="' . apply_filters( 'ish_sc_classes', 'ish-sc_map_container', $tag ) . '"><div class="'; // CLASSES $class = 'ish-sc_map'; $class .= ( '' != $sc_atts['css_class'] ) ? ' ' . esc_attr( $sc_atts['css_class'] ) : '' ; $class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_color'] ) ? ' ish-tooltip-' . esc_attr( $sc_atts['tooltip_color'] ) : ''; $class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_text_color'] ) ? ' ish-tooltip-text-' . esc_attr( $sc_atts['tooltip_text_color'] ) : ''; //$return .= apply_filters( 'ish_sc_classes', $class, $tag ); $return .= $class; $return .= '"' ; // ID $return .= ( '' != $sc_atts['id'] ) ? ' id="' . esc_attr( $sc_atts['id'] ) . '"' : ''; // STYLE if ( '' != $sc_atts['style'] || '' != $sc_atts['height'] ){ $return .= ' style="'; $return .= ( '' != $sc_atts['height'] ) ? ' height: ' . esc_attr( $sc_atts['height'] ) . 'px;' : ''; $return .= ( '' != $sc_atts['style'] ) ? ' ' . esc_attr( $sc_atts['style'] ) : ''; $return .= '"'; } // TOOLTIP $return .= ( '' != $sc_atts['tooltip'] ) ? ' data-type="tooltip" title="' . esc_attr( $sc_atts['tooltip'] ) . '"' : '' ; $return .= ( '' != $sc_atts['zoom'] ) ? ' data-zoom="' . esc_attr( $sc_atts['zoom'] ) . '"' : '' ; $return .= ( 'yes' == $sc_atts['invert_colors'] ) ? ' data-invert="' . esc_attr( $sc_atts['invert_colors'] ) . '"' : '' ; $return .= ( '' != $sc_atts['color'] ) ? ' data-color="' . esc_attr( $sc_atts['color'] ) . '"' : '' ; $return .= '>'; $content = wpb_js_remove_wpautop($content, true); // CONTENT $return .= do_shortcode( $content ); // SHORTCODE END $return .= '</div></div>'; echo $return;
tywzdbsd/wp_yanze
wp-content/plugins/ishyoboy-boldial-assets/ishyoboy-shortcodes/assets/backend/vc_extend/shortcodes_templates/ish_map.php
PHP
gpl-2.0
2,476
<?php class acf_Wysiwyg extends acf_Field { /*-------------------------------------------------------------------------------------- * * Constructor * * @author Elliot Condon * @since 1.0.0 * @updated 2.2.0 * *-------------------------------------------------------------------------------------*/ function __construct($parent) { parent::__construct($parent); $this->name = 'wysiwyg'; $this->title = __("Wysiwyg Editor",'acf'); add_action( 'acf_head-input', array( $this, 'acf_head') ); add_filter( 'acf/fields/wysiwyg/toolbars', array( $this, 'toolbars'), 1, 1 ); } /* * get_toolbars * * @description: * @since: 3.5.7 * @created: 10/01/13 */ function toolbars( $toolbars ) { $editor_id = 'acf_settings'; // Full $toolbars['Full'] = array(); $toolbars['Full'][1] = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id); $toolbars['Full'][2] = apply_filters('mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id); $toolbars['Full'][3] = apply_filters('mce_buttons_3', array(), $editor_id); $toolbars['Full'][4] = apply_filters('mce_buttons_4', array(), $editor_id); // Basic $toolbars['Basic'] = array(); $toolbars['Basic'][1] = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ); // Custom - can be added with acf/fields/wysiwyg/toolbars filter return $toolbars; } /*-------------------------------------------------------------------------------------- * * admin_head * - Add the settings for a WYSIWYG editor (as used in wp_editor / wp_tiny_mce) * * @author Elliot Condon * @since 3.2.3 * *-------------------------------------------------------------------------------------*/ function acf_head() { add_action( 'admin_footer', array( $this, 'admin_footer') ); } function admin_footer() { ?> <div style="display:none;"> <?php wp_editor( '', 'acf_settings' ); ?> </div> <?php } /*-------------------------------------------------------------------------------------- * * create_options * * @author Elliot Condon * @since 2.0.6 * @updated 2.2.0 * *-------------------------------------------------------------------------------------*/ function create_options($key, $field) { // vars $defaults = array( 'toolbar' => 'full', 'media_upload' => 'yes', 'the_content' => 'yes', 'default_value' => '', ); $field = array_merge($defaults, $field); ?> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Default Value",'acf'); ?></label> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'textarea', 'name' => 'fields['.$key.'][default_value]', 'value' => $field['default_value'], )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Toolbar",'acf'); ?></label> </td> <td> <?php $toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() ); $choices = array(); if( is_array($toolbars) ) { foreach( $toolbars as $k => $v ) { $label = $k; $name = sanitize_title( $label ); $name = str_replace('-', '_', $name); $choices[ $name ] = $label; } } do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][toolbar]', 'value' => $field['toolbar'], 'layout' => 'horizontal', 'choices' => $choices )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Show Media Upload Buttons?",'acf'); ?></label> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][media_upload]', 'value' => $field['media_upload'], 'layout' => 'horizontal', 'choices' => array( 'yes' => __("Yes",'acf'), 'no' => __("No",'acf'), ) )); ?> </td> </tr> <tr class="field_option field_option_<?php echo $this->name; ?>"> <td class="label"> <label><?php _e("Run filter \"the_content\"?",'acf'); ?></label> <p class="description"><?php _e("Enable this filter to use shortcodes within the WYSIWYG field",'acf'); ?></p> <p class="description"><?php _e("Disable this filter if you encounter recursive template problems with plugins / themes",'acf'); ?></p> </td> <td> <?php do_action('acf/create_field', array( 'type' => 'radio', 'name' => 'fields['.$key.'][the_content]', 'value' => $field['the_content'], 'layout' => 'horizontal', 'choices' => array( 'yes' => __("Yes",'acf'), 'no' => __("No",'acf'), ) )); ?> </td> </tr> <?php } /*-------------------------------------------------------------------------------------- * * create_field * * @author Elliot Condon * @since 2.0.5 * @updated 2.2.0 * *-------------------------------------------------------------------------------------*/ function create_field($field) { global $wp_version; // vars $defaults = array( 'toolbar' => 'full', 'media_upload' => 'yes', ); $field = array_merge($defaults, $field); $id = 'wysiwyg-' . $field['id']; ?> <div id="wp-<?php echo $id; ?>-wrap" class="acf_wysiwyg wp-editor-wrap" data-toolbar="<?php echo $field['toolbar']; ?>" data-upload="<?php echo $field['media_upload']; ?>"> <?php if($field['media_upload'] == 'yes'): ?> <?php if( version_compare($wp_version, '3.3', '<') ): ?> <div id="editor-toolbar"> <div id="media-buttons" class="hide-if-no-js"> <?php do_action( 'media_buttons' ); ?> </div> </div> <?php else: ?> <div id="wp-<?php echo $id; ?>-editor-tools" class="wp-editor-tools"> <div id="wp-<?php echo $id; ?>-media-buttons" class="hide-if-no-js wp-media-buttons"> <?php do_action( 'media_buttons' ); ?> </div> </div> <?php endif; ?> <?php endif; ?> <div id="wp-<?php echo $id; ?>-editor-container" class="wp-editor-container"> <textarea id="<?php echo $id; ?>" class="wp-editor-area" name="<?php echo $field['name']; ?>" ><?php echo wp_richedit_pre($field['value']); ?></textarea> </div> </div> <?php } /*-------------------------------------------------------------------------------------- * * get_value_for_api * * @author Elliot Condon * @since 3.0.0 * *-------------------------------------------------------------------------------------*/ function get_value_for_api($post_id, $field) { // vars $defaults = array( 'the_content' => 'yes', ); $field = array_merge($defaults, $field); $value = parent::get_value($post_id, $field); // filter if( $field['the_content'] == 'yes' ) { $value = apply_filters('the_content',$value); } else { $value = wpautop( $value ); } return $value; } } ?>
SAEBelgradeWeb/vencanje
wp-content/plugins/acf-master/core/fields/wysiwyg.php
PHP
gpl-2.0
7,948
<HTML> <!-- Mirrored from www.w3schools.com/php/showphpcode.asp?source=demo_func_simplexml_addchild by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:12 GMT --> <HEAD></HEAD> <FONT FACE="'Courier New',Verdana, Arial, Helvetica" SIZE=2> &lt;!DOCTYPE html><br>&lt;html><br>&lt;body><br><br><FONT COLOR=#ff0000>&lt;?php<br>$note=&lt;&lt;&lt;XML<br>&lt;note><br>&lt;to>Tove&lt;/to><br>&lt;from>Jani&lt;/from><br>&lt;heading>Reminder&lt;/heading><br>&lt;body>Don't forget me this weekend!&lt;/body><br>&lt;/note><br>XML;<br><br>$xml=new SimpleXMLElement($note);<br><br>// Add a child element to the body element<br>$xml->body->addChild("date","2014-01-01");<br><br>// Add a child element after the last element inside note<br>$footer=$xml->addChild("footer","Some footer text");<br>&nbsp; <br>echo $xml->asXML();<br>?&gt;</FONT><br><br>&lt;p>Select View Source to see the added date element (inside the body element) and the new footer element.&lt;/p><br><br>&lt;/body><br>&lt;/html><br> <!-- Mirrored from www.w3schools.com/php/showphpcode.asp?source=demo_func_simplexml_addchild by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:12 GMT --> </HTML>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/php/showphpcode1e75.html
HTML
gpl-2.0
1,185
/*************************************************************** * Name: RectShape.h * Purpose: Defines rectangular shape class * Author: Michal Bližňák ([email protected]) * Created: 2007-07-22 * Copyright: Michal Bližňák * License: wxWidgets license (www.wxwidgets.org) * Notes: **************************************************************/ #ifndef _WXSFRECTSHAPE_H #define _WXSFRECTSHAPE_H #include <wx/wxsf/ShapeBase.h> // default values /*! \brief Default value of wxSFRectShape::m_nRectSize data member. */ #define sfdvRECTSHAPE_SIZE wxRealPoint(100, 50) /*! \brief Default value of wxSFRectShape::m_Fill data member. */ #define sfdvRECTSHAPE_FILL wxBrush(*wxWHITE) /*! \brief Default value of wxSFRectShape::m_Border data member. */ #define sfdvRECTSHAPE_BORDER wxPen(*wxBLACK) /*! * \brief Class encapsulates basic rectangle shape which is used as a base class * for many other shapes that can be bounded by a simple rectangle. The class * provides all functionality needed for manipulating the rectangle's (bounding box) * size and position. */ class WXDLLIMPEXP_SF wxSFRectShape : public wxSFShapeBase { public: XS_DECLARE_CLONABLE_CLASS(wxSFRectShape); /*! \brief Default constructor. */ wxSFRectShape(void); /*! * \brief User constructor. * \param pos Initial position * \param size Initial size * \param manager Pointer to parent diagram manager */ wxSFRectShape(const wxRealPoint& pos, const wxRealPoint& size, wxSFDiagramManager* manager); /*! * \brief Copy constructor. * \param obj Reference to the source object */ wxSFRectShape(const wxSFRectShape& obj); /*! \brief Destructor. */ virtual ~wxSFRectShape(void); // public virtual functions /*! * \brief Get shapes's bounding box. The function can be overrided if neccessary. * \return Bounding rectangle */ virtual wxRect GetBoundingBox(); /*! * \brief Get intersection point of the shape border and a line leading from * 'start' point to 'end' point. The function can be overrided if neccessary. * \param start Starting point of the virtual intersection line * \param end Ending point of the virtual intersection line * \return Intersection point */ virtual wxRealPoint GetBorderPoint(const wxRealPoint& start, const wxRealPoint& end); /*! * \brief Function called by the framework responsible for creation of shape handles * at the creation time. The function can be overrided if neccesary. */ virtual void CreateHandles(); /*! * \brief Event handler called during dragging of the shape handle. * The function can be overrided if necessary. * * The function is called by the framework (by the shape canvas). * \param handle Reference to dragged handle */ virtual void OnHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called when the user started to drag the shape handle. * The function can be overrided if necessary. * * The function is called by the framework (by the shape canvas). * \param handle Reference to dragged handle */ virtual void OnBeginHandle(wxSFShapeHandle& handle); /*! \brief Resize the shape to bound all child shapes. The function can be overrided if neccessary. */ virtual void FitToChildren(); /*! * \brief Scale the shape size by in both directions. The function can be overrided if necessary * (new implementation should call default one ore scale shape's children manualy if neccesary). * \param x Horizontal scale factor * \param y Vertical scale factor * \param children TRUE if the shape's children shoould be scaled as well, otherwise the shape will be updated after scaling via Update() function. */ virtual void Scale(double x, double y, bool children = sfWITHCHILDREN); // public data accessors /*! * \brief Set rectangle's fill style. * \param brush Refernce to a brush object */ void SetFill(const wxBrush& brush){m_Fill = brush;} /*! * \brief Get current fill style. * \return Current brush */ wxBrush GetFill() const {return m_Fill;} /*! * \brief Set rectangle's border style. * \param pen Reference to a pen object */ void SetBorder(const wxPen& pen){m_Border = pen;} /*! * \brief Get current border style. * \return Current pen */ wxPen GetBorder() const {return m_Border;} /*! * \brief Set the rectangle size. * \param size New size */ void SetRectSize(const wxRealPoint& size){m_nRectSize = size;} /*! * \brief Set the rectangle size. * \param x Horizontal size * \param y Verical size */ void SetRectSize(double x, double y){m_nRectSize.x = x; m_nRectSize.y = y;} /*! * \brief Get the rectangle size. * \return Current size */ wxRealPoint GetRectSize() const {return m_nRectSize;} protected: // protected data members /*! \brief Pen object used for drawing of the rectangle border. */ wxPen m_Border; /*! \brief Brush object used for drawing of the rectangle body. */ wxBrush m_Fill; /*! \brief The rectangle size. */ wxRealPoint m_nRectSize; // protected virtual functions /*! * \brief Draw the shape in the normal way. The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawNormal(wxDC& dc); /*! * \brief Draw the shape in the hower mode (the mouse cursor is above the shape). * The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawHover(wxDC& dc); /*! * \brief Draw the shape in the highlighted mode (another shape is dragged over this * shape and this shape will accept the dragged one if it will be dropped on it). * The function can be overrided if neccessary. * \param dc Reference to device context where the shape will be drawn to */ virtual void DrawHighlighted(wxDC& dc); /*! * \brief Draw shadow under the shape. The function can be overrided if neccessary. * \param dc Reference to device context where the shadow will be drawn to */ virtual void DrawShadow(wxDC& dc); /*! * \brief Event handler called during dragging of the right shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnRightHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the left shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnLeftHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the top shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnTopHandle(wxSFShapeHandle& handle); /*! * \brief Event handler called during dragging of the bottom shape handle. * The function can be overrided if neccessary. * \param handle Reference to dragged shape handle */ virtual void OnBottomHandle(wxSFShapeHandle& handle); private: // private functions /*! \brief Initialize serializable properties. */ void MarkSerializableDataMembers(); /*! \brief Auxiliary data member. */ wxRealPoint m_nPrevSize; /*! \brief Auxiliary data member. */ wxRealPoint m_nPrevPosition; }; #endif //_WXSFRECTSHAPE_H
zuzanak-ondrej/codelite_appmonitor
sdk/wxshapeframework/include/wx/wxsf/RectShape.h
C
gpl-2.0
7,562
// File: $Id: opbranch.h,v 1.1 2001/10/27 22:34:09 ses6442 Exp p334-70f $ // Author: Benjamin Meyer // Contributor: Sean Sicher // Discription: Branch module for // Revisions: // $Log: opbranch.h,v $ // Revision 1.1 2001/10/27 22:34:09 ses6442 // Initial revision // // #ifndef OPBRANCH_H #define OPBRANCH_H #include "operation.h" class OpBranch : public Operation { public: OpBranch(); // Discription: process this instruction and dump if there are any errors. virtual bool process(); }; #endif
icefox/smada
smadatron/opbranch.h
C
gpl-2.0
569
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ESPSharp.Enums { public enum PackageScheduleDays : sbyte { Any = -1, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Weekdays, Weekends, Mon_Wed_Fri, Tue_Thur } }
TaleOfTwoWastelands/ESPSharp
ESPSharp/Enums/PackageScheduleDays.cs
C#
gpl-2.0
417
# zoomzoomzoom.js Simple zoom tool for images inside of DIVs. A very small script that is heavily dependent on its HTML structure. Designed to only work in Chrome.
levi/zoomzoomzoom.js
README.md
Markdown
gpl-2.0
164
<?php /** * @package Adminimize * @subpackage Backend Options * @author Frank Bültge */ if ( ! function_exists( 'add_action' ) ) { echo "Hi there! I'm just a part of plugin, not much I can do when called directly."; exit; } ?> <div id="poststuff" class="ui-sortable meta-box-sortables"> <div class="postbox"> <div class="handlediv" title="<?php _e('Click to toggle'); ?>"><br/></div> <h3 class="hndle" id="backend_options"><?php _e('Backend Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?></h3> <div class="inside"> <?php wp_nonce_field('mw_adminimize_nonce'); ?> <br class="clear" /> <table summary="config" class="widefat"> <tbody> <?php if ( function_exists('is_super_admin') ) { ?> <!-- <tr valign="top" class="form-invalid"> <td><?php _e( 'Use Global Settings', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $mw_adminimize_use_global = '0'; $select_active = ''; $message = ''; if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) ) { $mw_adminimize_use_global = 1; $select_active = ' disabled="disabled"'; $message = __( 'The plugin is active in multiste.', FB_ADMINIMIZE_TEXTDOMAIN ); } $mw_adminimize_use_global = get_option( 'mw_adminimize_use_global' ); ?> <select name="_mw_adminimize_use_global"<?php echo $select_active; ?>> <option value="0"<?php if ( '0' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e( 'False', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ( '1' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e('True', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('Use the settings global in your Multisite network.', FB_ADMINIMIZE_TEXTDOMAIN ); echo ' ' . $message; ?> </td> </tr> --> <tr valign="top" class="form-invalid"> <td><?php _e('Exclude Super Admin', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_exclude_super_admin = _mw_adminimize_get_option_value('_mw_adminimize_exclude_super_admin'); ?> <select name="_mw_adminimize_exclude_super_admin"> <option value="0"<?php if ($_mw_adminimize_exclude_super_admin == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_exclude_super_admin == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('Exclude the Super Admin on a WP Multisite Install from all limitations of this plugin.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <?php } ?> <tr valign="top"> <td><?php _e('User-Info', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_user_info = _mw_adminimize_get_option_value('_mw_adminimize_user_info'); ?> <select name="_mw_adminimize_user_info"> <option value="0"<?php if ($_mw_adminimize_user_info == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_user_info == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="2"<?php if ($_mw_adminimize_user_info == '2') { echo ' selected="selected"'; } ?>><?php _e('Only logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="3"<?php if ($_mw_adminimize_user_info == '3') { echo ' selected="selected"'; } ?>><?php _e('User &amp; Logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('The &quot;User-Info-area&quot; is on the top right side of the backend. You can hide or reduced show.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <?php if ( ($_mw_adminimize_user_info == '') || ($_mw_adminimize_user_info == '1') || ($_mw_adminimize_user_info == '0') ) $disabled_item = ' disabled="disabled"' ?> <tr valign="top" class="form-invalid"> <td><?php _e('Change User-Info, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_ui_redirect = _mw_adminimize_get_option_value('_mw_adminimize_ui_redirect'); ?> <select name="_mw_adminimize_ui_redirect" <?php if ( isset($disabled_item) ) echo $disabled_item; ?>> <option value="0"<?php if ($_mw_adminimize_ui_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_ui_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Frontpage of the Blog', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </select> <?php _e('When the &quot;User-Info-area&quot; change it, then it is possible to change the redirect.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_footer = _mw_adminimize_get_option_value('_mw_adminimize_footer'); ?> <select name="_mw_adminimize_footer"> <option value="0"<?php if ($_mw_adminimize_footer == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_footer == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('The Footer-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Header', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_header = _mw_adminimize_get_option_value('_mw_adminimize_header'); ?> <select name="_mw_adminimize_header"> <option value="0"<?php if ($_mw_adminimize_header == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_header == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('The Header-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Timestamp', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_timestamp = _mw_adminimize_get_option_value('_mw_adminimize_timestamp'); ?> <select name="_mw_adminimize_timestamp"> <option value="0"<?php if ($_mw_adminimize_timestamp == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_timestamp == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('Opens the post timestamp editing fields without you having to click the "Edit" link every time.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Thickbox FullScreen', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_tb_window = _mw_adminimize_get_option_value('_mw_adminimize_tb_window'); ?> <select name="_mw_adminimize_tb_window"> <option value="0"<?php if ($_mw_adminimize_tb_window == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_tb_window == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('All Thickbox-function use the full area of the browser. Thickbox is for example in upload media-files.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Flashuploader', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_control_flashloader = _mw_adminimize_get_option_value('_mw_adminimize_control_flashloader'); ?> <select name="_mw_adminimize_control_flashloader"> <option value="0"<?php if ($_mw_adminimize_control_flashloader == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_control_flashloader == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('Disable the flashuploader and users use only the standard uploader.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Category Height', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_cat_full = _mw_adminimize_get_option_value('_mw_adminimize_cat_full'); ?> <select name="_mw_adminimize_cat_full"> <option value="0"<?php if ($_mw_adminimize_cat_full == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_cat_full == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <?php _e('View the Meta Box with Categories in the full height, no scrollbar or whitespace.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <tr valign="top"> <td><?php _e('Advice in Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_advice = _mw_adminimize_get_option_value('_mw_adminimize_advice'); ?> <select name="_mw_adminimize_advice"> <option value="0"<?php if ($_mw_adminimize_advice == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> <option value="1"<?php if ($_mw_adminimize_advice == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_advice_txt" id="_mw_adminimize_advice_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_advice_txt'))); ?></textarea><br /><?php _e('In the Footer you can display an advice for changing the Default-design, (x)HTML is possible.', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <?php // when remove dashboard foreach ($user_roles as $role) { $disabled_menu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_menu_'. $role .'_items'); $disabled_submenu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_submenu_'. $role .'_items'); } $disabled_menu_all = array(); foreach ($user_roles as $role) { array_push($disabled_menu_all, $disabled_menu_[$role]); array_push($disabled_menu_all, $disabled_submenu_[$role]); } if ( '' != $disabled_menu_all ) { if ( ! _mw_adminimize_recursive_in_array('index.php', $disabled_menu_all) ) { $disabled_item2 = ' disabled="disabled"'; } ?> <tr valign="top" class="form-invalid"> <td><?php _e('Dashboard deactivate, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td> <td> <?php $_mw_adminimize_db_redirect = _mw_adminimize_get_option_value('_mw_adminimize_db_redirect'); ?> <select name="_mw_adminimize_db_redirect"<?php if ( isset($disabled_item2) ) echo $disabled_item2; ?>> <option value="0"<?php if ($_mw_adminimize_db_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (profile.php)</option> <option value="1"<?php if ($_mw_adminimize_db_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Manage Posts', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit.php)</option> <option value="2"<?php if ($_mw_adminimize_db_redirect == '2') { echo ' selected="selected"'; } ?>><?php _e('Manage Pages', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-pages.php)</option> <option value="3"<?php if ($_mw_adminimize_db_redirect == '3') { echo ' selected="selected"'; } ?>><?php _e('Write Post', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (post-new.php)</option> <option value="4"<?php if ($_mw_adminimize_db_redirect == '4') { echo ' selected="selected"'; } ?>><?php _e('Write Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (page-new.php)</option> <option value="5"<?php if ($_mw_adminimize_db_redirect == '5') { echo ' selected="selected"'; } ?>><?php _e('Comments', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-comments.php)</option> <option value="6"<?php if ($_mw_adminimize_db_redirect == '6') { echo ' selected="selected"'; } ?>><?php _e('other Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option> </select> <textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_db_redirect_txt" id="_mw_adminimize_db_redirect_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_db_redirect_txt'))); ?></textarea> <br /><?php _e('You have deactivated the Dashboard, please select a page for redirection or define custom url, include http://?', FB_ADMINIMIZE_TEXTDOMAIN ); ?> </td> </tr> <?php } ?> </tbody> </table> <p id="submitbutton"> <input class="button button-primary" type="submit" name="_mw_adminimize_save" value="<?php _e('Update Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?> &raquo;" /><input type="hidden" name="page_options" value="'dofollow_timeout'" /> </p> <p><a class="alignright button" href="javascript:void(0);" onclick="window.scrollTo(0,0);" style="margin:3px 0 0 30px;"><?php _e('scroll to top', FB_ADMINIMIZE_TEXTDOMAIN); ?></a><br class="clear" /></p> </div> </div> </div>
overneath42/wp-custom-install
wp-content/plugins/adminimize/inc-options/backend_options.php
PHP
gpl-2.0
14,171
<?php /** * Footer functions. * * @package Sento */ /* ---------------------------------------------------------------------------------- FOOTER WIDGETS LAYOUT ---------------------------------------------------------------------------------- */ /* Assign function for widget area 1 */ function thinkup_input_footerw1() { echo '<div id="footer-col1" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w1' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 1.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 2 */ function thinkup_input_footerw2() { echo '<div id="footer-col2" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w2' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 2.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 3 */ function thinkup_input_footerw3() { echo '<div id="footer-col3" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w3' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 3.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 4 */ function thinkup_input_footerw4() { echo '<div id="footer-col4" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w4' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 4.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 5 */ function thinkup_input_footerw5() { echo '<div id="footer-col5" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w5' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 5.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Assign function for widget area 6 */ function thinkup_input_footerw6() { echo '<div id="footer-col6" class="widget-area">'; if ( ! dynamic_sidebar( 'footer-w6' ) ) { echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>', '<div class="error-icon">', '<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 6.', 'sento') . '</p>', '<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>', '</div>'; }; echo '</div>'; } /* Add Custom Footer Layout */ function thinkup_input_footerlayout() { global $thinkup_footer_layout; global $thinkup_footer_widgetswitch; if ( $thinkup_footer_widgetswitch !== "1" and ! empty( $thinkup_footer_layout ) ) { echo '<div id="footer">'; if ( $thinkup_footer_layout == "option1" ) { echo '<div id="footer-core" class="option1">'; thinkup_input_footerw1(); echo '</div>'; } else if ( $thinkup_footer_layout == "option2" ) { echo '<div id="footer-core" class="option2">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option3" ) { echo '<div id="footer-core" class="option3">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); echo '</div>'; } else if ( $thinkup_footer_layout == "option4" ) { echo '<div id="footer-core" class="option4">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); echo '</div>'; } else if ( $thinkup_footer_layout == "option5" ) { echo '<div id="footer-core" class="option5">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); thinkup_input_footerw5(); echo '</div>'; } else if ( $thinkup_footer_layout == "option6" ) { echo '<div id="footer-core" class="option6">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); thinkup_input_footerw5(); thinkup_input_footerw6(); echo '</div>'; } else if ( $thinkup_footer_layout == "option7" ) { echo '<div id="footer-core" class="option7">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option8" ) { echo '<div id="footer-core" class="option8">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option9" ) { echo '<div id="footer-core" class="option9">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option10" ) { echo '<div id="footer-core" class="option10">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option11" ) { echo '<div id="footer-core" class="option11">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option12" ) { echo '<div id="footer-core" class="option12">'; thinkup_input_footerw1(); thinkup_input_footerw2(); echo '</div>'; } else if ( $thinkup_footer_layout == "option13" ) { echo '<div id="footer-core" class="option13">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); echo '</div>'; } else if ( $thinkup_footer_layout == "option14" ) { echo '<div id="footer-core" class="option14">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); echo '</div>'; } else if ( $thinkup_footer_layout == "option15" ) { echo '<div id="footer-core" class="option15">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); echo '</div>'; } else if ( $thinkup_footer_layout == "option16" ) { echo '<div id="footer-core" class="option16">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); echo '</div>'; } else if ( $thinkup_footer_layout == "option17" ) { echo '<div id="footer-core" class="option17">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); thinkup_input_footerw5(); echo '</div>'; } else if ( $thinkup_footer_layout == "option18" ) { echo '<div id="footer-core" class="option18">'; thinkup_input_footerw1(); thinkup_input_footerw2(); thinkup_input_footerw3(); thinkup_input_footerw4(); thinkup_input_footerw5(); echo '</div>'; } echo '</div>'; } } /* ---------------------------------------------------------------------------------- COPYRIGHT TEXT ---------------------------------------------------------------------------------- */ function thinkup_input_copyright() { printf( __( 'Developed by %1$s. Powered by %2$s.', 'sento' ) , '<a href="//www.thinkupthemes.com/" target="_blank">Think Up Themes Ltd</a>', '<a href="//www.wordpress.org/" target="_blank">WordPress</a>'); } ?>
JulioKno/Portal-UNIVIM-2016
wp-content/themes/sento/admin/main/options/04.footer.php
PHP
gpl-2.0
8,650
<script> var panels = new Array(); function addcattab(id, text, title) { var ccc = document.getElementById('categories'); var tab_id = id + '-tab'; var tab_title = (title) ? (' title="' + title + '"') : ''; var _li = document.createElement('li'); _li.id = tab_id; _li.className = 'tab'; _li.innerHTML = '<a href="' + "#tabs" + '" class="cattab" data-subpanel="' + id + '" role="tab" aria-controls="' + id + '"' + tab_title + '><span>' + text + "</span></a>"; ccc.appendChild(_li); } function is_in_array(elem, array) { for (var i = 0, length = array.length; i < length; i++) { // === is correct (IE) if (array[i] === elem) { return i; } } return -1; } function nextTag(node) { var node = node.nextSibling; return (node && node.nodeType != 1) ? nextTag(node) : node; } </script> <div id="tabs" class="sub-panels" role="tablist"> <ul id="categories" class="tabs"></ul> </div>
Tatiana5/CategoriesInTabs
styles/prosilver/template/event/index_body_markforums_after.html
HTML
gpl-2.0
929
/* Copyright (C) 2005 Michael K. McCarty & Fritz Bronner This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** \file future.c This is responsible for Future Mission planning screen. * */ #include <Buzz_inc.h> #include <externs.h> #include <assert.h> #include <logging.h> //Used to read steps from missStep.dat FILE* MSteps; char missStep[1024]; static inline char B_Mis(char x) {return missStep[x]-0x30;} /*missStep.dat is plain text, with: Mission Number (2 first bytes of each line) A Coded letter, each drawing a different line (1105-1127 for all possible letters) Numbers following each letter, which are the parameters of the function Each line must finish with a Z, so the game stops reading Any other char is ignored, but it's easier to read for a human that way */ LOG_DEFAULT_CATEGORY(future) char status[5],lck[5],F1,F2,F3,F4,FMen,F5,Pad; char JointFlag,MarFlag,JupFlag,SatFlag,MisType; GXHEADER vh; struct StepInfo { i16 x_cor; i16 y_cor; } StepBub[MAXBUB]; struct Parameter { char A; /**< DOCKING */ char B; /**< EVA */ char C; /**< LEM */ char D; /**< JOINT */ char E; /**< MANNED/UNMANNED/Duration 0==unmanned 1-6==duration */ char X; /**< the type of mission for assign crew and hardware */ char Z; /**< A duration mission only */ } V[62]; extern int Bub_Count; extern struct mStr Mis; extern struct MisEval Mev[60]; extern int SEG; void Load_FUT_BUT(void) { FILE *fin; unsigned i; fin=sOpen("NFUTBUT.BUT","rb",0); i=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vh.vptr,(unsigned)i,vh.w,vh.h); return; } void DrawFuture(char plr,int mis,char pad) { int i,j; FILE *fin; unsigned sz; strcpy(IKEY,"k011");strcpy(IDT,"i011"); JointFlag=0; // initialize joint flag F1=F2=F3=F4=FMen=F5=0; for (i=0;i<5;i++) lck[i]=status[i]=0; FadeOut(2,pal,10,0,0); Load_FUT_BUT(); fin=sOpen("FMIN.IMG","rb",0); fread(&pal[0],768,1,fin); sz=fread(screen,1,MAX_X*MAX_Y,fin); fclose(fin); RLED_img((char *)screen,(char *)vhptr.vptr,sz,vhptr.w,vhptr.h); gxClearDisplay(0,0); gr_sync (); if (pad==2) JointFlag=0; // third pad automatic no joint mission else if (Data->P[plr].LaunchFacility[pad+1] == 1) { if (Data->P[plr].Future[pad+1].MissionCode==0) JointFlag=1; // if no mission then set joint flag else if (Data->P[plr].Future[pad+1].part==1) // check if the part of that second mission is set { JointFlag=1; Data->P[plr].Future[pad+1].MissionCode=0; // clear mission Data->P[plr].Future[pad+1].part=0; }; }; if (pad==1 || pad==0) { if (Data->P[plr].LaunchFacility[pad+1]==1) JointFlag=1; } i=Data->Year;j=Data->Season; TRACE3("--- Setting i=Year (%d), j=Season (%d)", i, j); if ((i==60 && j==0) || (i==62 && j==0) || (i==64 && j==0) || (i==66 && j==0) || (i==69 && j==1) || (i==71 && j==1) || (i==73 && j==1)) { gxVirtualVirtual(&vhptr,1,2,12,11,&vhptr,198,153,gxSET); /* Mars */ MarFlag=1; } else MarFlag=0; if ((i==60 || i==64 || i==68 || i==72 || i==73 || i==77)) { gxVirtualVirtual(&vhptr,14,2,64,54,&vhptr,214,130,gxSET); /* Jup */ JupFlag=1; } else JupFlag=0; if (i==61 || i==66 || i==72) { gxVirtualVirtual(&vhptr,66,2,114,53,&vhptr,266,135,gxSET); /* Sat */ SatFlag=1; } else SatFlag=0; RectFill(1,1,318,21,3);RectFill(317,22,318,198,3);RectFill(1,197,316,198,3); RectFill(1,22,2,196,3);OutBox(0,0,319,199);InBox(3,3,30,19); InBox(3,22,316,196); IOBox(242,3,315,19); ShBox(5,24,183,47); ShBox(5,24,201,47); //name box ShBox(5,74,41,82); // RESET ShBox(5,49,53,72); //dur/man ShBox(43,74,53,82); // lock ShBox(80,74,90,82); ShBox(117,74,127,82); ShBox(154,74,164,82); ShBox(191,74,201,82); ShBox(5,84,16,130); //arrows up ShBox(5,132,16,146); //middle box ShBox(5,148,16,194); // down ShBox(203,24,238,31); // new right boxes RectFill(206,36,235,44,7); ShBox(203,33,238,47); InBox(205,35,236,45); UPArrow(8,95);DNArrow(8,157); gxVirtualDisplay(&vh,140,5,5,132,15,146,0); Toggle(5,1);draw_Pie(0);OutBox(5,49,53,72); Toggle(1,1);TogBox(55,49,0); Toggle(2,1);TogBox(92,49,0); Toggle(3,1);TogBox(129,49,0); FMen=F1=F2=F3=F4=F5=0; for (i=1;i<4;i++){ if (status[i]!=0) { Toggle(i,1); } }; if (JointFlag==0) { F4=2;lck[4]=1; Toggle(4,1); InBox(191,74,201,82); PlaceRX(5); TogBox(166,49,1); } else { F4=0; lck[4]=0; status[4]=0; Toggle(4,1); OutBox(191,74,201,82); ClearRX(5); TogBox(166,49,0); }; gr_sync (); Missions(plr,8,37,mis,1); GetMinus(plr); grSetColor(5); /* lines of text are 1:8,30 2:8,37 3:8,44 */ switch(pad) { // These used to say Pad 1, 2, 3 -Leon case 0: PrintAt(8,30,"PAD A:");break; case 1: PrintAt(8,30,"PAD B:");break; case 2: PrintAt(8,30,"PAD C:");break; default:break; }; grSetColor(1); PrintAt(9,80,"RESET"); PrintAt(256,13,"CONTINUE"); grSetColor(11); if (Data->Season==0) PrintAt(200,9,"SPRING"); else PrintAt(205,9,"FALL"); PrintAt(206,16,"19"); DispNum(0,0,Data->Year); grSetColor(1); FlagSm(plr,4,4); DispBig(40,5,"FUTURE MISSIONS",0,-1); FadeIn(2,pal,10,0,0); return; } void ClearDisplay(void) { gxVirtualDisplay(&vhptr,202,48,202,48,241,82,0); gxVirtualDisplay(&vhptr,17,83,17,83,241,195,0); gxVirtualDisplay(&vhptr,242,23,242,23,315,195,0); grSetColor(1); return; } int GetMinus(char plr) { char i;int u; i=PrestMin(plr); RectFill(206,36,235,44,7); if (i<3) u=1; //ok else if (i<9) u=10; //caution else u=19; //danger gxVirtualDisplay(&vh,203,u,203,24,238,31,0); grSetColor(11); if (i>0) PrintAt(210,42,"-"); else grMoveTo(210,42); DispNum(0,0,i); grSetColor(1); return 0; } void SetParameters(void) { int i; FILE *fin; fin=sOpen("MISSION.DAT","rb",0); for (i=0;i<62;i++) { fread(&Mis,sizeof Mis,1,fin); V[i].A=Mis.Doc; V[i].B=Mis.EVA; V[i].C=Mis.LM; V[i].D=Mis.Jt; V[i].E=Mis.Days; V[i].X=Mis.mCrew; V[i].Z=Mis.Dur; } fclose(fin); return; } void DrawLocks(void) { int i; for (i=0;i<5;i++) if (lck[i]==1) PlaceRX(i+1); else ClearRX(i+1); return; } /** set the toggles??? * * \param wh the button * \param i in or out */ void Toggle(int wh,int i) { TRACE3("->Toggle(wh %d, i %d)", wh, i); switch(wh) { case 1:if (i==1) gxVirtualDisplay(&vh,1,21,55,49,89,81,0);else gxVirtualDisplay(&vh,1,56,55,49,89,81,0); break; case 2:if(i==1) gxVirtualDisplay(&vh,38,21,92,49,127,81,0);else gxVirtualDisplay(&vh,38,56,92,49,127,81,0); break; case 3:if(i==1) gxVirtualDisplay(&vh,75,21,129,49,163,81,0);else gxVirtualDisplay(&vh,75,56,129,49,163,81,0); break; case 4:if(i==1) gxVirtualDisplay(&vh,112,21,166,49,200,81,0);else gxVirtualDisplay(&vh,112,56,166,49,200,81,0); break; case 5:if (i==1) gxVirtualDisplay(&vh,153,1,5,49,52,71,0); else gxVirtualDisplay(&vh,153,26,5,49,52,71,0); break; default:break; } TRACE1("<-Toggle()"); return; } void TogBox(int x,int y,int st) { TRACE4("->TogBox(x %d, y %d, st %d)", x, y, st); char sta[2][2]={{2,4},{4,2}}; grSetColor(sta[st][0]); grMoveTo(0+x,y+32);grLineTo(0+x,y+0);grLineTo(34+x,y+0); grSetColor(sta[st][1]); grMoveTo(x+0,y+33);grLineTo(23+x,y+33);grLineTo(23+x,y+23); grLineTo(x+35,y+23);grLineTo(x+35,y+0); TRACE1("<-TogBox()"); return; } void PianoKey(int X) { TRACE2("->PianoKey(X %d)", X); int t; if (F1==0) { if (V[X].A==1) {Toggle(1,1);status[1]=1;} else {Toggle(1,0);PlaceRX(1);status[1]=0;}} if (F2==0) { if (V[X].B==1) {Toggle(2,1);status[2]=1;} else {Toggle(2,0);PlaceRX(2);status[2]=0;}} if (F3==0) { if (V[X].C==1) {Toggle(3,1);status[3]=1;} else {Toggle(3,0);PlaceRX(3);status[3]=0;}} if (F4==0) { if (V[X].D==1) {Toggle(4,0);status[4]=1;} else {Toggle(4,1);status[4]=0; }} if (F5==-1 || (F5==0 && V[X].E==0)) { Toggle(5,0); status[0]=0; } else { Toggle(5,1); t=(F5==0) ? V[X].E : F5; assert(0 <= t); draw_Pie(t); status[0]=t; } DrawLocks(); TRACE1("<-PianoKey()"); return; } /** draw a piechart * * The piechart is indicating the number of astronauts on this mission. * * \param s something of an offset... */ void draw_Pie(int s) { int off; if (s==0) off=1; else off=s*20; gxVirtualDisplay(&vh,off,1,7,51,25,69,0); return; } void PlaceRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,8);break; case 2: RectFill(81,75,89,81,8);break; case 3: RectFill(118,75,126,81,8);break; case 4: RectFill(155,75,163,81,8);break; case 5: RectFill(192,75,200,81,8);break; default:break; } return; } void ClearRX(int s) { switch(s) { case 1: RectFill(44,75,52,81,3);break; case 2: RectFill(81,75,89,81,3);break; case 3: RectFill(118,75,126,81,3);break; case 4: RectFill(155,75,163,81,3);break; case 5: RectFill(192,75,200,81,3);break; default:break; } return; } int UpSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num >= 56+plr) num=0; else num++; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; /* condition one is true */ if (F1==0 && V[num].A==1) c1=1; if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; if (F5==0) c5=1; if (F5>1 && V[num].Z==1) c5=1; if (F5==V[num].E) c5=1; }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==56+plr) num=0; else ++num; } }; /* end while */ return(num); } int DownSearchRout(int num,char plr) { int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1; orig=num; if (num<=0) num=56+plr; else --num; while (found==0) { c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1; if (F1==V[num].A) c1=1; if (F1==0 && V[num].A==1) c1=1; /* condition one is true */ if (F1==2 && V[num].A==0) c1=1; if (F2==V[num].B) c2=1; /* condition two is true */ if (F2==0 && V[num].B==1) c2=1; /* condition one is true */ if (F2==2 && V[num].B==0) c2=1; if (F3==V[num].C) c3=1; /* condition three is true */ if (F3==0 && V[num].C==1) c3=1; /* condition one is true */ if (F3==2 && V[num].C==0) c3=1; if (F4==V[num].D) c4=1; /* condition four is true */ if (F4==0 && V[num].D==1) c4=1; /* condition one is true */ if (F4==2 && V[num].D==0) c4=1; if (num==0) c5=1; else { if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; // locked on zero duration if (F5==0) c5=1; // nothing set if (F5>1 && V[num].Z==1) c5=1; // set duration with duration mission if (F5==V[num].E) c5=1; // the duration is equal to what is preset }; if ((num==32 || num==36) && F5==2) c5=0; // planet check if (num==10 && MarFlag==0) c6=0; if (num==12 && JupFlag==0) c7=0; if (num==13 && SatFlag==0) c8=0; if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1; if (num==orig) return(0); if (found==0) { if (num==0) num=56+plr; else --num; } }; /* end while */ return(num); } void Future(char plr) { /** \todo the whole Future()-function is 500 >lines and unreadable */ TRACE1("->Future(plr)"); int MisNum = 0, DuraType = 0, MaxDur = 6, i, ii; int setting = -1, prev_setting = -1; int Ok, NewType; GXHEADER local, local2; GV(&local, 166, 9); GV(&local2, 177, 197); GV(&vh,240,90); /* global variable */ begfut: MisNum = FutureCheck(plr, 0); if (MisNum == 5) { DV(&local); DV(&local2); DV(&vh); return; } F1 = F2 = F3 = F4 = FMen = F5 = 0; // memset(buffer, 0x00, 20000); for (i = 0; i < 5; i++) lck[i] = status[i] = 0; SetParameters(); strcpy(IDT, "i011"); Pad = MisNum; DuraType = FMen = MisType = 0; ClrFut(plr, MisNum); DrawFuture(plr, MisType, MisNum); begfut_noredraw: // for (i=0;i<5;i++) ClearRX(i+1); while (1) { GetMouse(); if (mousebuttons == 0) break; } while (1) { GetMouse(); prev_setting = setting; setting = -1; if (key == '-' && SEG > 1) SEG--; if (key == '+' && SEG < 500) SEG++; if (key >= 65 && key < Bub_Count + 65) setting = key - 65; for (ii = 0; ii < Bub_Count; ii++) { if (x >= StepBub[ii].x_cor && x <= StepBub[ii].x_cor + 7 && y >= StepBub[ii].y_cor && y <= StepBub[ii].y_cor + 7) setting = ii; } if (setting >= 0) { if (prev_setting < 0) gxGetImage(&local, 18, 186, 183, 194, 0); if (prev_setting != setting) { ShBox(18, 186, 183, 194); grSetColor(1); MisStep(21, 192, Mev[setting].loc); } } else if (setting < 0 && prev_setting >= 0) { gxPutImage(&local, gxSET, 18, 186, 0); } if (Mis.Dur <= V[MisType].E && ((x >= 244 && y >= 5 && x <= 313 && y <= 17 && mousebuttons > 0) || key == K_ENTER)) { InBox(244, 5, 313, 17); WaitForMouseUp(); if (key > 0) delay(300); key = 0; OutBox(244, 5, 313, 17); gxGetImage(&local2, 74, 3, 250, 199, 0); NewType = V[MisType].X; Data->P[plr].Future[MisNum].Duration = DuraType; Ok = HardCrewAssign(plr, Pad, MisType, NewType); gxPutImage(&local2, gxSET, 74, 3, 0); // DV(&local2); if (Ok == 1) { Data->P[plr].Future[MisNum].Duration = DuraType; goto begfut; // return to loop } else { ClrFut(plr, MisNum); // DuraType = FMen = MisType = 0; key = 0; goto begfut_noredraw; // DrawFuture(plr, MisType, MisNum); } key = 0; }; // continue if ((((x >= 5 && y >= 49 && x <= 53 && y <= 72) || (x >= 43 && y >= 74 && x <= 53 && y <= 82)) && mousebuttons > 0) || (key == '!' || key == '1')) { if ((x >= 43 && y >= 74 && x <= 53 && y <= 82) || key == '!') { lck[0] = abs(lck[0] - 1); if (lck[0] == 1) InBox(43, 74, 53, 82); else OutBox(43, 74, 53, 82); if (lck[0] == 1) F5 = (status[0] == 0) ? -1 : status[0]; if (lck[0] == 1) PlaceRX(1); else ClearRX(1); if (lck[0] == 0) { F5 = 0; status[0] = 0; } while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[0] != 1) { InBox(5, 49, 53, 72); if (DuraType == MaxDur) DuraType = 0; else DuraType++; Data->P[plr].Future[MisNum].Duration = DuraType; if (DuraType == 0) Toggle(5, 0); else if (DuraType == 1) Toggle(5, 1); if (DuraType != 0) draw_Pie(DuraType); status[0] = DuraType; while (1) { GetMouse(); if (mousebuttons == 0) break; } grSetColor(34); OutBox(5, 49, 53, 72); }; key = 0; /* Duration */ }; if ((x >= 5 && y >= 74 && x <= 41 && y <= 82 && mousebuttons > 0) || (key == K_ESCAPE)) { InBox(5, 74, 41, 82); while (1) { GetMouse(); if (mousebuttons == 0) break; } MisType = 0; if (DuraType != 0) Toggle(5, 0); FMen = DuraType = F1 = F2 = F3 = F4 = F5 = 0; for (i = 1; i < 4; i++) if (status[i] != 0) Toggle(i, 1); if (JointFlag == 0) { F4 = 2; lck[4] = 1; Toggle(4, 1); InBox(191, 74, 201, 82); PlaceRX(5); TogBox(166, 49, 1); } else { F4 = 0; lck[4] = 0; status[4] = 0; Toggle(4, 1); OutBox(191, 74, 201, 82); ClearRX(5); TogBox(166, 49, 0); }; for (i = 0; i < 4; i++) { lck[i] = status[i] = 0; } OutBox(5, 49, 53, 72); OutBox(43, 74, 53, 82); TogBox(55, 49, 0); OutBox(80, 74, 90, 82); TogBox(92, 49, 0); OutBox(117, 74, 127, 82); TogBox(129, 49, 0); OutBox(154, 74, 164, 82); ClrFut(plr, MisNum); Data->P[plr].Future[MisNum].Duration = 0; Missions(plr, 8, 37, MisType, 1); GetMinus(plr); OutBox(5, 74, 41, 82); key = 0; /* Reset */ }; if ((x >= 55 && y >= 49 && x <= 90 && y <= 82 && mousebuttons > 0) || (key == '2' || key == '@')) { if ((x >= 80 && y >= 74 && x <= 90 && y <= 82) || (key == '@')) { if (lck[1] == 0) InBox(80, 74, 90, 82); else OutBox(80, 74, 90, 82); lck[1] = abs(lck[1] - 1); if (lck[1] == 1) PlaceRX(2); else ClearRX(2); if ((status[1] == 0) && (lck[1] == 1)) F1 = 2; else if ((status[1] == 1) && (lck[1] == 1)) F1 = 1; else F1 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[1] != 1) { TogBox(55, 49, 1); if (status[1] == 0) Toggle(1, 1); else Toggle(1, 0); status[1] = abs(status[1] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(55, 49, 0); }; /* Docking */ key = 0; }; if ((x >= 92 && y >= 49 && x <= 127 && y <= 82 && mousebuttons > 0) || (key == '3' || key == '#')) { if ((x >= 117 && y >= 74 && x <= 127 && y <= 82) || (key == '#')) { if (lck[2] == 0) InBox(117, 74, 127, 82); else OutBox(117, 74, 127, 82); lck[2] = abs(lck[2] - 1); if (lck[2] == 1) PlaceRX(3); else ClearRX(3); if ((status[2] == 0) && (lck[2] == 1)) F2 = 2; else if ((status[2] == 1) && (lck[2] == 1)) F2 = 1; else F2 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[2] != 1) { TogBox(92, 49, 1); if (status[2] == 0) Toggle(2, 1); else { Toggle(2, 0); }; status[2] = abs(status[2] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(92, 49, 0); }; /* EVA */ key = 0; }; if ((x >= 129 && y >= 49 && x <= 164 && y <= 82 && mousebuttons > 0) || (key == '4' || key == '$')) { if ((x >= 154 && y >= 74 && x <= 164 && y <= 82) || (key == '$')) { if (lck[3] == 0) InBox(154, 74, 164, 82); else OutBox(154, 74, 164, 82); lck[3] = abs(lck[3] - 1); // F3=lck[3]; if (lck[3] == 1) PlaceRX(4); else ClearRX(4); if ((status[3] == 0) && (lck[3] == 1)) F3 = 2; else if ((status[3] == 1) && (lck[3] == 1)) F3 = 1; else F3 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[3] != 1) { TogBox(129, 49, 1); if (status[3] == 0) Toggle(3, 1); else { Toggle(3, 0); }; status[3] = abs(status[3] - 1); while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(129, 49, 0); }; /* LEM */ key = 0; }; if (((x >= 166 && y >= 49 && x <= 201 && y <= 82 && mousebuttons > 0) || (key == '5' || key == '%')) && (JointFlag == 1)) { if ((x > 191 && y >= 74 && x <= 201 && y <= 82) || (key == '%')) { if (lck[4] == 0) InBox(191, 74, 201, 82); else OutBox(191, 74, 201, 82); lck[4] = abs(lck[4] - 1); if (lck[4] == 1) PlaceRX(5); else ClearRX(5); if ((status[4] == 0) && (lck[4] == 1)) F4 = 2; else if ((status[4] == 1) && (lck[4] == 1)) F4 = 1; else F4 = 0; while (1) { GetMouse(); if (mousebuttons == 0) break; } } else if (lck[4] != 1) { TogBox(166, 49, 1); status[4] = abs(status[4] - 1); if (status[4] == 0) { Toggle(4, 1); } else { Toggle(4, 0); } while (1) { GetMouse(); if (mousebuttons == 0) break; } TogBox(166, 49, 0); }; /* Joint Launch */ key = 0; }; if ((x >= 5 && y >= 84 && x <= 16 && y <= 130 && mousebuttons > 0) || (key == UP_ARROW)) { InBox(5, 84, 16, 130); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } } while (mousebuttons == 1 || key == UP_ARROW) { MisType = UpSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 84, 16, 130); key = 0; /* Mission Type plus */ }; if ((x >= 5 && y >= 132 && x < 16 && y <= 146 && mousebuttons > 0) || (key == K_SPACE)) { InBox(5, 132, 16, 146); WaitForMouseUp(); delay(50); MisType = Data->P[plr].Future[MisNum].MissionCode; assert(0 <= MisType); if (MisType != 0){ Missions(plr, 8, 37, MisType, 1); } else{ Missions(plr, 8, 37, MisType, 3); } OutBox(5, 132, 16, 146); key = 0; } if ((x >= 5 && y >= 148 && x <= 16 && y <= 194 && mousebuttons > 0) || (key == DN_ARROW)) { InBox(5, 148, 16, 194); for (i = 0; i < 50; i++) { key = 0; GetMouse(); delay(10); if (mousebuttons == 0) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; i = 51; } key = 0; } while (mousebuttons == 1 || key == DN_ARROW) { MisType = DownSearchRout(MisType, plr); Data->P[plr].Future[MisNum].MissionCode = MisType; Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; delay(100); key = 0; GetMouse(); } Missions(plr, 8, 37, MisType, 3); DuraType = status[0]; OutBox(5, 148, 16, 194); key = 0; /* Mission Type minus */ }; } // while TRACE1("<-Future()"); } /** draws the bubble on the screen, * starts with upper left coor * * \param x x-coord of the upper left corner of the bubble * \param y y-coord of the upper left corner of the bubble */ void Bd(int x,int y) { int x1,y1,x2,y2; x1=x-2; y1=y; x2=x-1; y2=y-1; RectFill(x1,y1,x1+8,y1+4,21); RectFill(x2,y2,x2+6,y2+6,21); grSetColor(1); grMoveTo(x,y+4); /** \note references Bub_Count to determine the number of the character to draw in the bubble */ DispChr(65+Bub_Count); StepBub[Bub_Count].x_cor=x1; StepBub[Bub_Count].y_cor=y1; ++Bub_Count; return; } /** Print the duration of a mission * * \param x duration code * * \todo Link this at whatever place the duration is actually defined */ void DurPri(int x) { grSetColor(5); switch(x) { case -1:PrintAt(112,30,"NO DURATION");break; case 0:PrintAt(112,30,"NO DURATION");break; case 1:PrintAt(112,30,"1 - 2 DAYS");break; case 2:PrintAt(112,30,"3 - 5 DAYS");break; case 3:PrintAt(112,30,"6 - 7 DAYS");break; case 4:PrintAt(112,30,"8 - 12 DAYS");break; case 5:PrintAt(112,30,"13 - 16 DAYS");break; case 6:PrintAt(112,30,"17 - 20 DAYS");break; default:break; }; return; } void MissionName(int val,int xx,int yy,int len) { TRACE5("->MissionName(val %d, xx %d, yy %d, len %d)", val, xx, yy, len); int i,j=0; GetMisType(val); grMoveTo(xx,yy); for (i=0;i<50;i++) { if (j>len && Mis.Name[i]==' ') {yy+=7;j=0;grMoveTo(xx,yy);} else DispChr(Mis.Name[i]); j++;if (Mis.Name[i]=='\0') break; }; TRACE1("<-MissionName"); return; } /** Missions() will draw the future missions among other things * * \param plr Player * \param X screen coord for mission name string * \param Y screen coord for mission name string * \param val mission number * \param bub if set to 0 or 3 the function will not draw stuff */ void Missions(char plr,int X,int Y,int val,char bub) { TRACE5("->Missions(plr, X %d, Y %d, val %d, bub %c)", X, Y, val, bub); if (bub==1 || bub==3) { PianoKey(val); Bub_Count=0; // set the initial bub_count ClearDisplay(); RectFill(6,31,182,46,3); RectFill(80,25,175,30,3);grSetColor(5); PrintAt(55,30,"TYPE: ");DispNum(0,0,val); grSetColor(5); if (V[val].E>0) { if (F5 > V[val].E && Mis.Dur==1) DurPri(F5); else DurPri(V[val].E);} else DurPri(F5); } else grSetColor(1); MissionName(val,X,Y,24); if (bub==3) GetMinus(plr); if (bub==0 || bub==3) {return;} MSteps=sOpen("missSteps.dat","r",FT_DATA); if (fgets(missStep, 1024, MSteps) == NULL) memset (missStep, 0, sizeof missStep); while (!feof(MSteps)&&((missStep[0]-0x30)*10+(missStep[1]-0x30))!=val) { if (fgets(missStep, 1024, MSteps) == NULL) break; } fclose(MSteps); int n; for (n=2;missStep[n]!='Z';n++) switch (missStep[n]) { case 'A': Draw_IJ (B_Mis(++n)); break; case 'B': Draw_IJV (B_Mis(++n)); break; case 'C': OrbOut (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'D': LefEarth (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'E': OrbIn (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'F': OrbMid (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'G': LefOrb (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'H': Draw_LowS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6)); n+=6; break; case 'I': Fly_By (); break; case 'J': VenMarMerc (B_Mis(++n)); break; case 'K': Draw_PQR (); break; case 'L': Draw_PST (); break; case 'M': Draw_GH (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'N': Q_Patch (); break; case 'O': RghtMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'P': DrawLunPas (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'Q': DrawLefMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break; case 'R': DrawSTUV (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break; case 'S': Draw_HighS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break; case 'T': DrawMoon (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6),B_Mis(n+7)); n+=7; break; case 'U': LefGap (B_Mis(++n)); break; case 'V': S_Patch (B_Mis(++n)); break; case 'W': DrawZ (); break; default : break; } gr_sync (); MissionCodes(plr,MisType,Pad); TRACE1("<-Missions()"); } // end function missions #ifdef DEAD_CODE /** Draws stuff about choosing a program and having < 2 groups available * * \deprecated This function appears to be deprecated. */ char FutBad(void) { char i; grSetColor(0); ShBox(84,41,232,128); InBox(91,47,225,103); IOBox(91,107,225,123); grSetColor(1); PrintAt(150,117,"EXIT"); grSetColor(11); PrintAt(96,60,"YOU HAVE SELECTED A"); PrintAt(96,70,"PROGRAM WITH LESS THAN"); PrintAt(96,80,"TWO GROUPS AVAILABLE."); WaitForMouseUp(); i=0; while(i==0) { GetMouse(); if (mousebuttons!=0) { if (x>=93 && y>=109 && x<=223 && y<=121) { InBox(93,109,223,123);i=3; delay(50); }; }; }; /* End while */ return (i); } #endif /* vim: set noet ts=4 sw=4 tw=77: */
raceintospace/raceintospace-cvs
future.c
C
gpl-2.0
27,931
# SSClusterViewer/app This folder contains the javascript files for the application. # SSClusterViewer/resources This folder contains static resources (typically an `"images"` folder as well). # SSClusterViewer/overrides This folder contains override classes. All overrides in this folder will be automatically included in application builds if the target class of the override is loaded. # SSClusterViewer/sass/etc This folder contains misc. support code for sass builds (global functions, mixins, etc.) # SSClusterViewer/sass/src This folder contains sass files defining css rules corresponding to classes included in the application's javascript code build. By default, files in this folder are mapped to the application's root namespace, 'SSClusterViewer'. The namespace to which files in this directory are matched is controlled by the app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg. # SSClusterViewer/sass/var This folder contains sass files defining sass variables corresponding to classes included in the application's javascript code build. By default, files in this folder are mapped to the application's root namespace, 'SSClusterViewer'. The namespace to which files in this directory are matched is controlled by the app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg.
marcos-garcia/smartsantanderdataanalysis
sswebpage/SSClusterViewer/Readme.md
Markdown
gpl-2.0
1,343
--- layout: post title: Objectify and strange errors with GWT serializations date: '2013-04-04T09:15:00.003-07:00' author: David Hatanian tags: modified_time: '2013-04-04T09:15:34.396-07:00' blogger_id: tag:blogger.com,1999:blog-5219665179084602082.post-7455732729975892877 blogger_orig_url: http://david-codes.blogspot.com/2013/04/objectify-and-strange-errors-with-gwt.html --- <div style="text-align: justify;">OK, so it turns out Objectify returns non-serializable lists when using the <i>list()</i>&nbsp;method. Using the following method : </div> <div style="text-align: justify;"><br/></div> <div style="text-align: justify;"><br/></div><br/> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;">ofy.load().type(Plant.class).list();<br/></pre> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre> <pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre>And directly returning the value to GWT client side throws a cryptic serialization exception, where the class that raises the problem is called <i>Proxy$XX </i>where XX are digits.<br/> <br/>That problem is going to be fixed in GWT next version, but meanwhile we have to use the workaround provided in the <a href="https://code.google.com/p/objectify-appengine/issues/detail?id=120">bug report</a>.
dhatanian/dhatanian.github.io
_posts/2013-04-04-objectify-and-strange-errors-with-gwt.html
HTML
gpl-2.0
1,528
TARGET = rlm_utf8 SRCS = rlm_utf8.c HEADERS = RLM_CFLAGS = RLM_LIBS = include ../rules.mak $(STATIC_OBJS): $(HEADERS) $(DYNAMIC_OBJS): $(HEADERS)
gentoo/freeradius-server
src/modules/rlm_utf8/Makefile
Makefile
gpl-2.0
154
// Copyright (C) 1999-2000 Id Software, Inc. // #include "ui_local.h" /********************************************************************************* SPECIFY SERVER *********************************************************************************/ #define MAX_LISTBOXITEMS 128 #define MAX_LISTBOXWIDTH 40 #define MAX_LEAGUENAME 80 #define SPECIFYLEAGUE_FRAMEL "menu/art/frame2_l" #define SPECIFYLEAGUE_FRAMER "menu/art/frame1_r" #define SPECIFYLEAGUE_BACK0 "menu/art/back_0" #define SPECIFYLEAGUE_BACK1 "menu/art/back_1" #define SPECIFYLEAGUE_ARROWS0 "menu/art/arrows_vert_0" #define SPECIFYLEAGUE_UP "menu/art/arrows_vert_top" #define SPECIFYLEAGUE_DOWN "menu/art/arrows_vert_bot" #define GLOBALRANKINGS_LOGO "menu/art/gr/grlogo" #define GLOBALRANKINGS_LETTERS "menu/art/gr/grletters" #define ID_SPECIFYLEAGUENAME 100 #define ID_SPECIFYLEAGUELIST 101 #define ID_SPECIFYLEAGUEUP 102 #define ID_SPECIFYLEAGUEDOWN 103 #define ID_SPECIFYLEAGUEBACK 104 static char* specifyleague_artlist[] = { SPECIFYLEAGUE_FRAMEL, SPECIFYLEAGUE_FRAMER, SPECIFYLEAGUE_ARROWS0, SPECIFYLEAGUE_UP, SPECIFYLEAGUE_DOWN, SPECIFYLEAGUE_BACK0, SPECIFYLEAGUE_BACK1, GLOBALRANKINGS_LOGO, GLOBALRANKINGS_LETTERS, NULL }; static char playername[80]; typedef struct { menuframework_s menu; menutext_s banner; menubitmap_s framel; menubitmap_s framer; menufield_s rankname; menulist_s list; menubitmap_s arrows; menubitmap_s up; menubitmap_s down; menubitmap_s back; menubitmap_s grlogo; menubitmap_s grletters; } specifyleague_t; static specifyleague_t s_specifyleague; typedef struct { char buff[MAX_LISTBOXWIDTH]; char leaguename[MAX_LEAGUENAME]; } table_t; table_t league_table[MAX_LISTBOXITEMS]; char *leaguename_items[MAX_LISTBOXITEMS]; static void SpecifyLeague_GetList() { int count = 0; int i; /* The Player Name has changed. We need to perform another search */ Q_strncpyz( playername, s_specifyleague.rankname.field.buffer, sizeof(playername) ); count = trap_CL_UI_RankGetLeauges( playername ); for(i = 0; i < count; i++) { char s[MAX_LEAGUENAME]; const char *var; var = va( "leaguename%i", i+1 ); trap_Cvar_VariableStringBuffer( var, s, sizeof(s) ); Q_strncpyz(league_table[i].leaguename, s, sizeof(league_table[i].leaguename) ); Q_strncpyz(league_table[i].buff, league_table[i].leaguename, sizeof(league_table[i].buff) ); } s_specifyleague.list.numitems = count; } /* ================= SpecifyLeague_Event ================= */ static void SpecifyLeague_Event( void* ptr, int event ) { int id; id = ((menucommon_s*)ptr)->id; //if( event != QM_ACTIVATED && id != ID_SPECIFYLEAGUELIST ) { // return; //} switch (id) { case ID_SPECIFYLEAGUELIST: if( event == QM_GOTFOCUS ) { //ArenaServers_UpdatePicture(); } break; case ID_SPECIFYLEAGUEUP: if( event == QM_ACTIVATED ) ScrollList_Key( &s_specifyleague.list, K_UPARROW ); break; case ID_SPECIFYLEAGUEDOWN: if( event == QM_ACTIVATED ) ScrollList_Key( &s_specifyleague.list, K_DOWNARROW ); break; case ID_SPECIFYLEAGUENAME: if( (event == QM_LOSTFOCUS) && (Q_strncmp(playername, s_specifyleague.rankname.field.buffer, strlen(s_specifyleague.rankname.field.buffer)) != 0)) { SpecifyLeague_GetList(); } break; case ID_SPECIFYLEAGUEBACK: if( event == QM_ACTIVATED ) { trap_Cvar_Set( "sv_leagueName", league_table[s_specifyleague.list.curvalue].leaguename); UI_PopMenu(); } break; } } /* ================= SpecifyLeague_MenuInit ================= */ void SpecifyLeague_MenuInit( void ) { int i; // zero set all our globals memset( &s_specifyleague, 0 ,sizeof(specifyleague_t) ); SpecifyLeague_Cache(); s_specifyleague.menu.wrapAround = qtrue; s_specifyleague.menu.fullscreen = qtrue; s_specifyleague.banner.generic.type = MTYPE_BTEXT; s_specifyleague.banner.generic.x = 320; s_specifyleague.banner.generic.y = 16; s_specifyleague.banner.string = "CHOOSE LEAGUE"; s_specifyleague.banner.color = color_white; s_specifyleague.banner.style = UI_CENTER; s_specifyleague.framel.generic.type = MTYPE_BITMAP; s_specifyleague.framel.generic.name = SPECIFYLEAGUE_FRAMEL; s_specifyleague.framel.generic.flags = QMF_INACTIVE; s_specifyleague.framel.generic.x = 0; s_specifyleague.framel.generic.y = 78; s_specifyleague.framel.width = 256; s_specifyleague.framel.height = 334; s_specifyleague.framer.generic.type = MTYPE_BITMAP; s_specifyleague.framer.generic.name = SPECIFYLEAGUE_FRAMER; s_specifyleague.framer.generic.flags = QMF_INACTIVE; s_specifyleague.framer.generic.x = 376; s_specifyleague.framer.generic.y = 76; s_specifyleague.framer.width = 256; s_specifyleague.framer.height = 334; s_specifyleague.grlogo.generic.type = MTYPE_BITMAP; s_specifyleague.grlogo.generic.name = GLOBALRANKINGS_LOGO; s_specifyleague.grlogo.generic.flags = QMF_INACTIVE; s_specifyleague.grlogo.generic.x = 0; s_specifyleague.grlogo.generic.y = 0; s_specifyleague.grlogo.width = 64; s_specifyleague.grlogo.height = 128; s_specifyleague.rankname.generic.type = MTYPE_FIELD; s_specifyleague.rankname.generic.name = "Player Name:"; s_specifyleague.rankname.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT; s_specifyleague.rankname.generic.callback = SpecifyLeague_Event; s_specifyleague.rankname.generic.id = ID_SPECIFYLEAGUENAME; s_specifyleague.rankname.generic.x = 226; s_specifyleague.rankname.generic.y = 128; s_specifyleague.rankname.field.widthInChars = 32; s_specifyleague.rankname.field.maxchars = 80; s_specifyleague.list.generic.type = MTYPE_SCROLLLIST; s_specifyleague.list.generic.flags = QMF_HIGHLIGHT_IF_FOCUS; s_specifyleague.list.generic.id = ID_SPECIFYLEAGUELIST; s_specifyleague.list.generic.callback = SpecifyLeague_Event; s_specifyleague.list.generic.x = 160; s_specifyleague.list.generic.y = 200; s_specifyleague.list.width = MAX_LISTBOXWIDTH; s_specifyleague.list.height = 8; s_specifyleague.list.itemnames = (const char **)leaguename_items; s_specifyleague.list.numitems = 0; for( i = 0; i < MAX_LISTBOXITEMS; i++ ) { league_table[i].buff[0] = 0; league_table[i].leaguename[0] = 0; leaguename_items[i] = league_table[i].buff; } s_specifyleague.arrows.generic.type = MTYPE_BITMAP; s_specifyleague.arrows.generic.name = SPECIFYLEAGUE_ARROWS0; s_specifyleague.arrows.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE; s_specifyleague.arrows.generic.callback = SpecifyLeague_Event; s_specifyleague.arrows.generic.x = 512; s_specifyleague.arrows.generic.y = 240-64+16; s_specifyleague.arrows.width = 64; s_specifyleague.arrows.height = 128; s_specifyleague.up.generic.type = MTYPE_BITMAP; s_specifyleague.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY; s_specifyleague.up.generic.callback = SpecifyLeague_Event; s_specifyleague.up.generic.id = ID_SPECIFYLEAGUEUP; s_specifyleague.up.generic.x = 512; s_specifyleague.up.generic.y = 240-64+16; s_specifyleague.up.width = 64; s_specifyleague.up.height = 64; s_specifyleague.up.focuspic = SPECIFYLEAGUE_UP; s_specifyleague.down.generic.type = MTYPE_BITMAP; s_specifyleague.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY; s_specifyleague.down.generic.callback = SpecifyLeague_Event; s_specifyleague.down.generic.id = ID_SPECIFYLEAGUEDOWN; s_specifyleague.down.generic.x = 512; s_specifyleague.down.generic.y = 240+16; s_specifyleague.down.width = 64; s_specifyleague.down.height = 64; s_specifyleague.down.focuspic = SPECIFYLEAGUE_DOWN; s_specifyleague.back.generic.type = MTYPE_BITMAP; s_specifyleague.back.generic.name = SPECIFYLEAGUE_BACK0; s_specifyleague.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS; s_specifyleague.back.generic.callback = SpecifyLeague_Event; s_specifyleague.back.generic.id = ID_SPECIFYLEAGUEBACK; s_specifyleague.back.generic.x = 0; s_specifyleague.back.generic.y = 480-64; s_specifyleague.back.width = 128; s_specifyleague.back.height = 64; s_specifyleague.back.focuspic = SPECIFYLEAGUE_BACK1; Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.banner ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framel ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framer ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.grlogo ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.rankname ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.list ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.arrows ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.up ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.down ); Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.back ); // initialize any menu variables Q_strncpyz( s_specifyleague.rankname.field.buffer, UI_Cvar_VariableString("name"), sizeof(s_specifyleague.rankname.field.buffer) ); Q_strncpyz( playername, UI_Cvar_VariableString("name"), sizeof(playername) ); SpecifyLeague_GetList(); } /* ================= SpecifyLeague_Cache ================= */ void SpecifyLeague_Cache( void ) { int i; // touch all our pics for (i=0; ;i++) { if (!specifyleague_artlist[i]) break; trap_R_RegisterShaderNoMip(specifyleague_artlist[i]); } } /* ================= UI_SpecifyLeagueMenu ================= */ void UI_SpecifyLeagueMenu( void ) { SpecifyLeague_MenuInit(); UI_PushMenu( &s_specifyleague.menu ); }
tectronics/battle-of-the-sexes
reference/bots_q3_127/code/q3_ui/ui_specifyleague.c
C
gpl-2.0
9,959
<div class="tx-test-extension"> <f:render section="main" /> </div>
ahmedRguei/job
typo3conf/ext/extension_builder/Tests/Fixtures/TestExtensions/test_extension/Resources/Private/Layouts/Default.html
HTML
gpl-2.0
68
/* * Copyright 2010, Intel Corporation * * This file is part of PowerTOP * * This program file 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 2 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 in a file named COPYING; if not, write to the * Free Software Foundation, Inc, * 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * or just google for it. * * Authors: * Arjan van de Ven <[email protected]> */ #include <iostream> #include <fstream> #include <algorithm> #include "calibrate.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <math.h> #include <sys/types.h> #include <dirent.h> #include "../parameters/parameters.h" extern "C" { #include "../tuning/iw.h" } #include <map> #include <vector> #include <string> using namespace std; static vector<string> usb_devices; static vector<string> rfkill_devices; static vector<string> backlight_devices; static vector<string> scsi_link_devices; static int blmax; static map<string, string> saved_sysfs; static volatile int stop_measurement; static int wireless_PS; static void save_sysfs(const char *filename) { char line[4096]; ifstream file; file.open(filename, ios::in); if (!file) return; file.getline(line, 4096); file.close(); saved_sysfs[filename] = line; } static void restore_all_sysfs(void) { map<string, string>::iterator it; for (it = saved_sysfs.begin(); it != saved_sysfs.end(); it++) write_sysfs(it->first, it->second); set_wifi_power_saving("wlan0", wireless_PS); } static void find_all_usb(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/bus/usb/devices/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/bus/usb/devices/%s/power/active_duration", entry->d_name); if (access(filename, R_OK)!=0) continue; sprintf(filename, "/sys/bus/usb/devices/%s/power/idVendor", entry->d_name); file.open(filename, ios::in); if (file) { file.getline(filename, 4096); file.close(); if (strcmp(filename, "1d6b")==0) continue; } sprintf(filename, "/sys/bus/usb/devices/%s/power/control", entry->d_name); save_sysfs(filename); usb_devices.push_back(filename); } closedir(dir); } static void suspend_all_usb_devices(void) { unsigned int i; for (i = 0; i < usb_devices.size(); i++) write_sysfs(usb_devices[i], "auto\n"); } static void find_all_rfkill(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/rfkill/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/rfkill/%s/soft", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); rfkill_devices.push_back(filename); } closedir(dir); } static void rfkill_all_radios(void) { unsigned int i; for (i = 0; i < rfkill_devices.size(); i++) write_sysfs(rfkill_devices[i], "1\n"); } static void unrfkill_all_radios(void) { unsigned int i; for (i = 0; i < rfkill_devices.size(); i++) write_sysfs(rfkill_devices[i], "0\n"); } static void find_backlight(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/backlight/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/backlight/%s/brightness", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); backlight_devices.push_back(filename); sprintf(filename, "/sys/class/backlight/%s/max_brightness", entry->d_name); blmax = read_sysfs(filename); } closedir(dir); } static void lower_backlight(void) { unsigned int i; for (i = 0; i < backlight_devices.size(); i++) write_sysfs(backlight_devices[i], "0\n"); } static void find_scsi_link(void) { struct dirent *entry; DIR *dir; char filename[4096]; dir = opendir("/sys/class/scsi_host/"); if (!dir) return; while (1) { ifstream file; entry = readdir(dir); if (!entry) break; if (entry->d_name[0] == '.') continue; sprintf(filename, "/sys/class/scsi_host/%s/link_power_management_policy", entry->d_name); if (access(filename, R_OK)!=0) continue; save_sysfs(filename); scsi_link_devices.push_back(filename); } closedir(dir); } static void set_scsi_link(const char *state) { unsigned int i; for (i = 0; i < scsi_link_devices.size(); i++) write_sysfs(scsi_link_devices[i], state); } static void *burn_cpu(void *dummy) { volatile double d = 1.1; while (!stop_measurement) { d = pow(d, 1.0001); } return NULL; } static void *burn_cpu_wakeups(void *dummy) { struct timespec tm; while (!stop_measurement) { tm.tv_sec = 0; tm.tv_nsec = (unsigned long)dummy; nanosleep(&tm, NULL); } return NULL; } static void *burn_disk(void *dummy) { int fd; char buffer[64*1024]; char filename[256]; strcpy(filename ,"/tmp/powertop.XXXXXX"); fd = mkstemp(filename); if (fd < 0) { printf(_("Cannot create temp file\n")); return NULL; } while (!stop_measurement) { lseek(fd, 0, SEEK_SET); write(fd, buffer, 64*1024); fdatasync(fd); } close(fd); return NULL; } static void cpu_calibration(int threads) { int i; pthread_t thr; printf(_("Calibrating: CPU usage on %i threads\n"), threads); stop_measurement = 0; for (i = 0; i < threads; i++) pthread_create(&thr, NULL, burn_cpu, NULL); one_measurement(15); stop_measurement = 1; sleep(1); } static void wakeup_calibration(unsigned long interval) { pthread_t thr; printf(_("Calibrating: CPU wakeup power consumption\n")); stop_measurement = 0; pthread_create(&thr, NULL, burn_cpu_wakeups, (void *)interval); one_measurement(15); stop_measurement = 1; sleep(1); } static void usb_calibration(void) { unsigned int i; /* chances are one of the USB devices is bluetooth; unrfkill first */ unrfkill_all_radios(); printf(_("Calibrating USB devices\n")); for (i = 0; i < usb_devices.size(); i++) { printf(_(".... device %s \n"), usb_devices[i].c_str()); suspend_all_usb_devices(); write_sysfs(usb_devices[i], "on\n"); one_measurement(15); suspend_all_usb_devices(); sleep(3); } rfkill_all_radios(); sleep(4); } static void rfkill_calibration(void) { unsigned int i; printf(_("Calibrating radio devices\n")); for (i = 0; i < rfkill_devices.size(); i++) { printf(_(".... device %s \n"), rfkill_devices[i].c_str()); rfkill_all_radios(); write_sysfs(rfkill_devices[i], "0\n"); one_measurement(15); rfkill_all_radios(); sleep(3); } for (i = 0; i < rfkill_devices.size(); i++) { printf(_(".... device %s \n"), rfkill_devices[i].c_str()); unrfkill_all_radios(); write_sysfs(rfkill_devices[i], "1\n"); one_measurement(15); unrfkill_all_radios(); sleep(3); } rfkill_all_radios(); } static void backlight_calibration(void) { unsigned int i; printf(_("Calibrating backlight\n")); for (i = 0; i < backlight_devices.size(); i++) { char str[4096]; printf(_(".... device %s \n"), backlight_devices[i].c_str()); lower_backlight(); one_measurement(15); sprintf(str, "%i\n", blmax / 4); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", blmax / 2); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", 3 * blmax / 4 ); write_sysfs(backlight_devices[i], str); one_measurement(15); sprintf(str, "%i\n", blmax); write_sysfs(backlight_devices[i], str); one_measurement(15); lower_backlight(); sleep(1); } printf(_("Calibrating idle\n")); system("DISPLAY=:0 /usr/bin/xset dpms force off"); one_measurement(15); system("DISPLAY=:0 /usr/bin/xset dpms force on"); } static void idle_calibration(void) { printf(_("Calibrating idle\n")); system("DISPLAY=:0 /usr/bin/xset dpms force off"); one_measurement(15); system("DISPLAY=:0 /usr/bin/xset dpms force on"); } static void disk_calibration(void) { pthread_t thr; printf(_("Calibrating: disk usage \n")); set_scsi_link("min_power"); stop_measurement = 0; pthread_create(&thr, NULL, burn_disk, NULL); one_measurement(15); stop_measurement = 1; sleep(1); } void calibrate(void) { find_all_usb(); find_all_rfkill(); find_backlight(); find_scsi_link(); wireless_PS = get_wifi_power_saving("wlan0"); save_sysfs("/sys/module/snd_hda_intel/parameters/power_save"); cout << _("Starting PowerTOP power estimate calibration \n"); suspend_all_usb_devices(); rfkill_all_radios(); lower_backlight(); set_wifi_power_saving("wlan0", 1); sleep(4); idle_calibration(); disk_calibration(); backlight_calibration(); write_sysfs("/sys/module/snd_hda_intel/parameters/power_save", "1\n"); cpu_calibration(1); cpu_calibration(4); wakeup_calibration(10000); wakeup_calibration(100000); wakeup_calibration(1000000); set_wifi_power_saving("wlan0", 0); usb_calibration(); rfkill_calibration(); cout << _("Finishing PowerTOP power estimate calibration \n"); restore_all_sysfs(); learn_parameters(300, 1); printf(_("Parameters after calibration:\n")); dump_parameter_bundle(); save_parameters("saved_parameters.powertop"); save_all_results("saved_results.powertop"); }
AllenDou/powertop
src/calibrate/calibrate.cpp
C++
gpl-2.0
9,814
/* This file is part of the KDE project Copyright (C) 2007, 2012 Dag Andersen danders@get2net> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "kptdocumentseditor.h" #include "kptcommand.h" #include "kptitemmodelbase.h" #include "kptduration.h" #include "kptnode.h" #include "kptproject.h" #include "kpttask.h" #include "kptdocuments.h" #include "kptdatetime.h" #include "kptitemviewsettup.h" #include "kptdebug.h" #include <QMenu> #include <QList> #include <QVBoxLayout> #include <kaction.h> #include <kicon.h> #include <kglobal.h> #include <klocale.h> #include <kactioncollection.h> #include <kdebug.h> #include <KoDocument.h> namespace KPlato { //-------------------- DocumentTreeView::DocumentTreeView( QWidget *parent ) : TreeViewBase( parent ) { // header()->setContextMenuPolicy( Qt::CustomContextMenu ); setStretchLastSection( true ); DocumentItemModel *m = new DocumentItemModel(); setModel( m ); setRootIsDecorated ( false ); setSelectionBehavior( QAbstractItemView::SelectRows ); setSelectionMode( QAbstractItemView::SingleSelection ); createItemDelegates( m ); setAcceptDrops( true ); setDropIndicatorShown( true ); connect( selectionModel(), SIGNAL( selectionChanged ( const QItemSelection&, const QItemSelection& ) ), SLOT( slotSelectionChanged( const QItemSelection& ) ) ); setColumnHidden( DocumentModel::Property_Status, true ); // not used atm } Document *DocumentTreeView::currentDocument() const { return model()->document( selectionModel()->currentIndex() ); } QModelIndexList DocumentTreeView::selectedRows() const { return selectionModel()->selectedRows(); } void DocumentTreeView::slotSelectionChanged( const QItemSelection &selected ) { emit selectionChanged( selected.indexes() ); } QList<Document*> DocumentTreeView::selectedDocuments() const { QList<Document*> lst; foreach ( const QModelIndex &i, selectionModel()->selectedRows() ) { Document *doc = model()->document( i ); if ( doc ) { lst << doc; } } return lst; } //----------------------------------- DocumentsEditor::DocumentsEditor( KoDocument *part, QWidget *parent ) : ViewBase( part, parent ) { setupGui(); QVBoxLayout * l = new QVBoxLayout( this ); l->setMargin( 0 ); m_view = new DocumentTreeView( this ); l->addWidget( m_view ); m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed ); connect( model(), SIGNAL( executeCommand( KUndo2Command* ) ), part, SLOT( addCommand( KUndo2Command* ) ) ); connect( m_view, SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( slotCurrentChanged( const QModelIndex & ) ) ); connect( m_view, SIGNAL( selectionChanged( const QModelIndexList ) ), this, SLOT( slotSelectionChanged( const QModelIndexList ) ) ); connect( m_view, SIGNAL( contextMenuRequested( QModelIndex, const QPoint& ) ), this, SLOT( slotContextMenuRequested( QModelIndex, const QPoint& ) ) ); connect( m_view, SIGNAL( headerContextMenuRequested( const QPoint& ) ), SLOT( slotHeaderContextMenuRequested( const QPoint& ) ) ); } void DocumentsEditor::updateReadWrite( bool readwrite ) { kDebug(planDbg())<<isReadWrite()<<"->"<<readwrite; ViewBase::updateReadWrite( readwrite ); m_view->setReadWrite( readwrite ); updateActionsEnabled( readwrite ); } void DocumentsEditor::draw( Documents &docs ) { m_view->setDocuments( &docs ); } void DocumentsEditor::draw() { } void DocumentsEditor::setGuiActive( bool activate ) { kDebug(planDbg())<<activate; updateActionsEnabled( true ); ViewBase::setGuiActive( activate ); if ( activate && !m_view->selectionModel()->currentIndex().isValid() ) { m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate); } } void DocumentsEditor::slotContextMenuRequested( QModelIndex index, const QPoint& pos ) { //kDebug(planDbg())<<index.row()<<","<<index.column()<<":"<<pos; QString name; if ( index.isValid() ) { Document *obj = m_view->model()->document( index ); if ( obj ) { name = "documentseditor_popup"; } } emit requestPopupMenu( name, pos ); } void DocumentsEditor::slotHeaderContextMenuRequested( const QPoint &pos ) { kDebug(planDbg()); QList<QAction*> lst = contextActionList(); if ( ! lst.isEmpty() ) { QMenu::exec( lst, pos, lst.first() ); } } Document *DocumentsEditor::currentDocument() const { return m_view->currentDocument(); } void DocumentsEditor::slotCurrentChanged( const QModelIndex & ) { //kDebug(planDbg())<<curr.row()<<","<<curr.column(); // slotEnableActions(); } void DocumentsEditor::slotSelectionChanged( const QModelIndexList list ) { kDebug(planDbg())<<list.count(); updateActionsEnabled( true ); } void DocumentsEditor::slotEnableActions( bool on ) { updateActionsEnabled( on ); } void DocumentsEditor::updateActionsEnabled( bool on ) { QList<Document*> lst = m_view->selectedDocuments(); if ( lst.isEmpty() || lst.count() > 1 ) { actionEditDocument->setEnabled( false ); actionViewDocument->setEnabled( false ); return; } Document *doc = lst.first(); actionViewDocument->setEnabled( on ); actionEditDocument->setEnabled( on && doc->type() == Document::Type_Product && isReadWrite() ); } void DocumentsEditor::setupGui() { QString name = "documentseditor_edit_list"; actionEditDocument = new KAction(KIcon( "document-properties" ), i18n("Edit..."), this); actionCollection()->addAction("edit_documents", actionEditDocument ); // actionEditDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) ); connect( actionEditDocument, SIGNAL( triggered( bool ) ), SLOT( slotEditDocument() ) ); addAction( name, actionEditDocument ); actionViewDocument = new KAction(KIcon( "document-preview" ), i18nc("@action View a document", "View..."), this); actionCollection()->addAction("view_documents", actionViewDocument ); // actionViewDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) ); connect( actionViewDocument, SIGNAL( triggered( bool ) ), SLOT( slotViewDocument() ) ); addAction( name, actionViewDocument ); /* actionDeleteSelection = new KAction(KIcon( "edit-delete" ), i18n("Delete"), this); actionCollection()->addAction("delete_selection", actionDeleteSelection ); actionDeleteSelection->setShortcut( KShortcut( Qt::Key_Delete ) ); connect( actionDeleteSelection, SIGNAL( triggered( bool ) ), SLOT( slotDeleteSelection() ) ); addAction( name, actionDeleteSelection );*/ // Add the context menu actions for the view options createOptionAction(); } void DocumentsEditor::slotOptions() { kDebug(planDbg()); ItemViewSettupDialog dlg( this, m_view/*->masterView()*/ ); dlg.exec(); } void DocumentsEditor::slotEditDocument() { QList<Document*> dl = m_view->selectedDocuments(); if ( dl.isEmpty() ) { return; } kDebug(planDbg())<<dl; emit editDocument( dl.first() ); } void DocumentsEditor::slotViewDocument() { QList<Document*> dl = m_view->selectedDocuments(); if ( dl.isEmpty() ) { return; } kDebug(planDbg())<<dl; emit viewDocument( dl.first() ); } void DocumentsEditor::slotAddDocument() { //kDebug(planDbg()); QList<Document*> dl = m_view->selectedDocuments(); Document *after = 0; if ( dl.count() > 0 ) { after = dl.last(); } Document *doc = new Document(); QModelIndex i = m_view->model()->insertDocument( doc, after ); if ( i.isValid() ) { m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate ); m_view->edit( i ); } } void DocumentsEditor::slotDeleteSelection() { QList<Document*> lst = m_view->selectedDocuments(); //kDebug(planDbg())<<lst.count()<<" objects"; if ( ! lst.isEmpty() ) { emit deleteDocumentList( lst ); } } bool DocumentsEditor::loadContext( const KoXmlElement &context ) { return m_view->loadContext( m_view->model()->columnMap(), context ); } void DocumentsEditor::saveContext( QDomElement &context ) const { m_view->saveContext( m_view->model()->columnMap(), context ); } } // namespace KPlato #include "kptdocumentseditor.moc"
wyuka/calligra
plan/libs/ui/kptdocumentseditor.cpp
C++
gpl-2.0
9,173
#ifndef GRAPHICS_FX_H #define GRAPHICS_FX_H #include "video/video.h" // PlayerVisual #include "game/game_data.h" // Player #include "game/camera.h" // Camera #include "video/nebu_video_types.h" // Visual void drawImpact(int player); void drawGlow(PlayerVisual *pV, Player *pTarget, float dim); #endif
sugao516/gltron-code
src/include/video/graphics_fx.h
C
gpl-2.0
304
/** * Copyright (C) 2004 - 2012 Nils Asmussen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package bbcodeeditor.control.actions; import bbcodeeditor.control.Controller; import bbcodeeditor.control.SecImage; import bbcodeeditor.control.SecSmiley; /** * @author Assi Nilsmussen * */ public final class AddImageAction extends HistoryAction { /** * the image to add */ private final SecImage _image; /** * constructor * * @param con the controller of the text-field * @param start the start-position of this action * @param end the end-position of this action * @param image the image */ public AddImageAction(Controller con,int start,int end,SecImage image) { super(con,start,end); _image = image; } public void performAction() { switch(_actionType) { case UNDO: _con.removeText(_start,_end,false); _actionType = REDO; break; case REDO: _con.addImage(_image,_start); _con.goToPosition(_start + 1); _actionType = UNDO; break; } } public String getName() { String imgName; if(_image instanceof SecSmiley) imgName = "smiley '" + ((SecSmiley)_image).getPrimaryCode() + "'"; else imgName = "image"; String res; if(_actionType == UNDO) res = "Remove " + imgName; else res = "Add " + imgName; return res + " [" + _start + "," + _end + "]"; } public String toString() { return getName(); } }
script-solution/BBCodeEditor
bbcodeeditor/control/actions/AddImageAction.java
Java
gpl-2.0
2,158
<?php /** * */ # Define namespace namespace WCFE\Modules\Editor\View\Editor\Templates\Tabs\Tabs; # Imports use WCFE\Modules\Editor\View\Editor\Templates\Tabs\FieldsTab; /** * */ class MultiSiteOptionsTab extends FieldsTab { /** * put your comment there... * * @var mixed */ protected $fieldsPluggableFilterName = \WCFE\Hooks::FILTER_VIEW_TABS_TAB_MULTISITE_FIELDS; /** * put your comment there... * * @var mixed */ protected $fields = array ( 'WCFE\Modules\Editor\View\Editor\Templates\Fields' => array ( 'MultiSiteAllow', 'MultiSite', 'MultiSiteSubDomainInstall', 'MultiSiteDomainCurrentSite', 'MultiSitePathCurrentSite', 'MultiSiteSiteId', 'MultiSiteBlogId', 'MultiSitePrimaryNetworkId', ) ); /** * put your comment there... * */ protected function initialize() { $this->title = $this->_( 'Multi Sites' ); $this->fields = $this->bcCreateFieldsList( $this->fields ); } }
kinko912000/public_html
wp-content/plugins/wp-config-file-editor/Modules/Editor/View/Editor/Templates/Tabs/Tabs/MultiSite.class.php
PHP
gpl-2.0
957
<?php /*************************************************************************** * * 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. * * Portions of this program are derived from publicly licensed software * projects including, but not limited to phpBB, Magelo Clone, * EQEmulator, EQEditor, and Allakhazam Clone. * * Author: * Maudigan(Airwalking) * * November 24, 2013 - Maudigan * Updated query to be compatible with the new way factions are stored in * the database * General code/comment/whitespace cleanup * September 26, 2014 - Maudigan * Updated character table name * September 28, 2014 - Maudigan * added code to monitor database performance * altered character profile initialization to remove redundant query * May 24, 2016 - Maudigan * general code cleanup, whitespace correction, removed old comments, * organized some code. A lot has changed, but not much functionally * do a compare to 2.41 to see the differences. * Implemented new database wrapper. * October 3, 2016 - Maudigan * Made the faction links customizable * January 7, 2018 - Maudigan * Modified database to use a class. * March 9, 2020 - Maudigan * modularized the profile menu output * March 22, 2020 - Maudigan * impemented common.php * April 25, 2020 - Maudigan * implement multi-tenancy * May 4, 2020 - Maudigan * clean up of the content/character data join * ***************************************************************************/ /********************************************* INCLUDES *********************************************/ define('INCHARBROWSER', true); include_once(__DIR__ . "/include/common.php"); include_once(__DIR__ . "/include/profile.php"); include_once(__DIR__ . "/include/db.php"); /********************************************* SUPPORT FUNCTIONS *********************************************/ //converts faction values into a the string from the language file. function FactionToString($character_value) { global $language; if($character_value >= 1101) return $language['FACTION_ALLY']; if($character_value >= 701 && $character_value <= 1100) return $language['FACTION_WARMLY']; if($character_value >= 401 && $character_value <= 700) return $language['FACTION_KINDLY']; if($character_value >= 101 && $character_value <= 400) return $language['FACTION_AMIABLE']; if($character_value >= 0 && $character_value <= 100) return $language['FACTION_INDIFF']; if($character_value >= -100 && $character_value <= -1) return $language['FACTION_APPR']; if($character_value >= -700 && $character_value <= -101) return $language['FACTION_DUBIOUS']; if($character_value >= -999 && $character_value <= -701) return $language['FACTION_THREAT']; if($character_value <= -1000) return $language['FACTION_SCOWLS']; return $language['FACTION_INDIFF']; } /********************************************* SETUP PROFILE/PERMISSIONS *********************************************/ if(!$_GET['char']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_NO_CHAR']); else $charName = $_GET['char']; //character initializations $char = new profile($charName, $cbsql, $cbsql_content, $language, $showsoftdelete, $charbrowser_is_admin_page); //the profile class will sanitize the character name $charID = $char->char_id(); $name = $char->GetValue('name'); $mypermission = GetPermissions($char->GetValue('gm'), $char->GetValue('anon'), $char->char_id()); //block view if user level doesnt have permission if ($mypermission['factions']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_ITEM_NO_VIEW']); /********************************************* GATHER RELEVANT PAGE DATA *********************************************/ //get content factions from the content db $tpl = <<<TPL SELECT fl.id, fl.name, IFNULL(fl.base, 0) AS base, IFNULL(flmc.mod, 0) AS classmod, IFNULL(flmr.mod, 0) AS racemod, IFNULL(flmd.mod, 0) AS deitymod FROM faction_list AS fl LEFT JOIN faction_list_mod AS flmc ON fl.id = flmc.faction_id AND (flmc.mod_name = 'c%d') LEFT JOIN faction_list_mod AS flmr ON fl.id = flmr.faction_id AND (flmr.mod_name = 'r%d') LEFT JOIN faction_list_mod AS flmd ON fl.id = flmd.faction_id AND (flmd.mod_name = 'd%d') ORDER BY name ASC TPL; $query = sprintf( $tpl, $char->GetValue('class'), $char->GetValue('race'), ($char->GetValue('deity') == 396) ? "140" : $char->GetValue('deity') ); $result = $cbsql_content->query($query); $content_factions = $cbsql_content->fetch_all($result); //get the characters factions from the player db $tpl = <<<TPL SELECT current_value, faction_ID FROM faction_values WHERE char_id = '%s' TPL; $query = sprintf($tpl, $charID); $result = $cbsql->query($query); $character_factions = $cbsql->fetch_all($result); //DO A MANUAL JOIN OF THE RESULTS $joined_factions = manual_join($content_factions, 'id', $character_factions, 'faction_ID', 'left'); /********************************************* DROP HEADER *********************************************/ $d_title = " - ".$name.$language['PAGE_TITLES_FACTIONS']; include(__DIR__ . "/include/header.php"); /********************************************* DROP PROFILE MENU *********************************************/ output_profile_menu($name, 'factions'); /********************************************* POPULATE BODY *********************************************/ if (!$mypermission['advfactions']) { $cb_template->set_filenames(array( 'factions' => 'factions_advanced_body.tpl') ); } else { $cb_template->set_filenames(array( 'factions' => 'factions_basic_body.tpl') ); } $cb_template->assign_both_vars(array( 'NAME' => $name) ); $cb_template->assign_vars(array( 'L_FACTIONS' => $language['FACTION_FACTIONS'], 'L_NAME' => $language['FACTION_NAME'], 'L_FACTION' => $language['FACTION_FACTION'], 'L_BASE' => $language['FACTION_BASE'], 'L_CHAR' => $language['FACTION_CHAR'], 'L_CLASS' => $language['FACTION_CLASS'], 'L_RACE' => $language['FACTION_RACE'], 'L_DEITY' => $language['FACTION_DEITY'], 'L_TOTAL' => $language['FACTION_TOTAL'], 'L_DONE' => $language['BUTTON_DONE']) ); foreach($joined_factions as $faction) { $charmod = intval($faction['current_value']); $total = $faction['base'] + $charmod + $faction['classmod'] + $faction['racemod'] + $faction['deitymod']; $cb_template->assign_both_block_vars("factions", array( 'ID' => $faction['id'], 'LINK' => QuickTemplate($link_faction, array('FACTION_ID' => $faction['id'])), 'NAME' => $faction['name'], 'FACTION' => FactionToString($total), 'BASE' => $faction['base'], 'CHAR' => $charmod, 'CLASS' => $faction['classmod'], 'RACE' => $faction['racemod'], 'DEITY' => $faction['deitymod'], 'TOTAL' => $total) ); } /********************************************* OUTPUT BODY AND FOOTER *********************************************/ $cb_template->pparse('factions'); $cb_template->destroy; include(__DIR__ . "/include/footer.php"); ?>
maudigan/charbrowser
factions.php
PHP
gpl-2.0
7,654
var elixir = require('laravel-elixir'); var gulp = require("gulp"); require('laravel-elixir-wiredep'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Less | file for our application, as well as publishing vendor resources. | */ var bowerDir = "public/vendor/"; var lessPaths = [ bowerDir + "bootstrap/less/" ] var templatePaths = [ "resources/assets/js/app/components/*/*.html", ]; elixir.extend("templates", function(src, base, dest) { gulp.task("templates", function () { // the base option sets the relative root for the set of files, // preserving the folder structure gulp.src(src, {base: base}) .pipe(gulp.dest(dest)); }); // Watch each glob in src for (idx in src){ var glob = src[idx]; this.registerWatcher("templates", glob); } return this.queueTask("templates"); }); elixir(function(mix) { // Complile LESS into CSS mix.less("main.less", "public/css/", {paths: lessPaths}); // Inject dependencies into layout (except bootstrap css, since that is compiled into main css) mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"}); // Combine app js into one file mix.scriptsIn("resources/assets/js/", "public/js/main.js"); // Copy angular templates to public folder mix.templates(templatePaths, "resources/assets/js/app/components/", "public"); });
levofski/web-2-cv
gulpfile.js
JavaScript
gpl-2.0
1,696
package com.onkiup.minedroid; import com.onkiup.minedroid.gui.resources.*; import com.onkiup.minedroid.gui.MineDroid; /** * This class is auto generated. * Manually made changes will be discarded. **/ public final class R { final static String MODID = "minedroid"; public final static class id { public final static int message = 268435456; public final static int hint = 268435457; public final static int test = 268435458; public final static int text = 268435459; public final static int debug = 268435460; public final static int close = 268435461; public final static int edit = 268435462; public final static int edit_multiline = 268435463; public final static int progress = 268435464; public final static int list = 268435465; } public final static class string { public final static ValueLink cancel = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Cancel") }); public final static ValueLink test_window = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Minedroid Test") }); public final static ValueLink test = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "test") }); public final static ValueLink alert_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "click or press Y to dismiss") }); public final static ValueLink confirm_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "press Y/N to respond") }); public final static ValueLink ok = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Ok") }); public final static ValueLink close = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "close") }); } public final static class layout { public final static ResourceLink minedroid_test = new ResourceLink(MODID, "layouts", "minedroid_test.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink alert = new ResourceLink(MODID, "layouts", "alert.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink holder_string = new ResourceLink(MODID, "layouts", "holder_string.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink config_main = new ResourceLink(MODID, "layouts", "config_main.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink confirm = new ResourceLink(MODID, "layouts", "confirm.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class drawable { public final static ResourceLink shadow = new ResourceLink(MODID, "drawables", "shadow.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink check = new ResourceLink(MODID, "drawables", "check.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink scroll = new ResourceLink(MODID, "drawables", "scroll.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_overlay = new ResourceLink(MODID, "drawables", "bg_overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_checkbox = new ResourceLink(MODID, "drawables", "bg_checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink fg_progress_view = new ResourceLink(MODID, "drawables", "fg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_edit_text = new ResourceLink(MODID, "drawables", "bg_edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink overlay = new ResourceLink(MODID, "drawables", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_button = new ResourceLink(MODID, "drawables", "bg_button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); public final static ResourceLink bg_progress_view = new ResourceLink(MODID, "drawables", "bg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class ninepatch { public final static ResourceLink panel = new ResourceLink(MODID, "ninepatches", "panel", new EnvParams[] { new EnvParams(null, null, null, null)}); } public final static class style { public final static Style focus = new Style(new ResourceLink(MODID, "styles", "focus.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout"); public final static Style content_view = new Style(new ResourceLink(MODID, "styles", "content_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view"); public final static Style relative_layout = new Style(new ResourceLink(MODID, "styles", "relative_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group"); public final static Style checkbox = new Style(new ResourceLink(MODID, "styles", "checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style entity_view = new Style(new ResourceLink(MODID, "styles", "entity_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style edit_text = new Style(new ResourceLink(MODID, "styles", "edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view"); public final static Style view_group = new Style(new ResourceLink(MODID, "styles", "view_group.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style scroll_view = new Style(new ResourceLink(MODID, "styles", "scroll_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style overlay = new Style(new ResourceLink(MODID, "styles", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style progress_view = new Style(new ResourceLink(MODID, "styles", "progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style text = new Style(new ResourceLink(MODID, "styles", "text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style theme = new Style(new ResourceLink(MODID, "styles", "theme.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style text_view = new Style(new ResourceLink(MODID, "styles", "text_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view"); public final static Style list_view = new Style(new ResourceLink(MODID, "styles", "list_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout"); public final static Style button = new Style(new ResourceLink(MODID, "styles", "button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view"); public final static Style view = new Style(new ResourceLink(MODID, "styles", "view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class); public final static Style linear_layout = new Style(new ResourceLink(MODID, "styles", "linear_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group"); } }
chedim/minedriod
src/main/java/com/onkiup/minedroid/R.java
Java
gpl-2.0
7,740
package thesis; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import termo.component.Compound; import termo.eos.Cubic; import termo.eos.EquationsOfState; import termo.eos.alpha.Alphas; import termo.matter.Mixture; import termo.matter.Substance; import termo.phase.Phase; import compounds.CompoundReader; public class CubicFileGenerator extends FileGenerator { Substance substance; public CubicFileGenerator(){ CompoundReader reader = new CompoundReader(); Compound heptane = reader.getCompoundByExactName("N-heptane"); substance = new Substance(EquationsOfState.vanDerWaals() ,Alphas.getVanDerWaalsIndependent() ,heptane,Phase.VAPOR); } public void cubicEquationPressureVolumeTemperatureFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{ PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.println(" Volumen Presion Temperatura"); double min_volume = 0.245; double max_volume = 1.2; int n = 60; double pass = (max_volume- min_volume)/n; int nt =20; double min_temperature = 150; double max_temperature = 400; double tempPass = (max_temperature - min_temperature)/nt; for(int j = 0; j < nt; j++){ double temperature = min_temperature + tempPass *j ; for(int i=0;i < n; i++){ double volume = min_volume + pass*i; double pressure = calculatePressure(volume, temperature); writer.println(" "+ volume + " " + temperature + " " + pressure); } writer.println(); } writer.close(); } public double calculatePressure(double volume, double temperature){ return substance.calculatePressure(temperature,volume); //parametros de van der waals para el heptano // double a = 3107000.0; //double b = 0.2049; // return cubic.calculatePressure(temperature, volume,a,b); } public void cubicEquationPressureVolumeFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{ PrintWriter writer = new PrintWriter(fileName, "UTF-8"); writer.println(" Volumen Presion"); double min_volume = 0.245; double max_volume = 1.2; int n = 100; double pass = (max_volume- min_volume)/n; for(int i=0;i < n; i++){ double volume = min_volume + pass*i; double pressure =calculatePressure(volume, 300); writer.println(" "+ volume + " " + pressure); } writer.close(); } public void cubicEquationCompresibilitiFactorFiles(String folderName) throws FileNotFoundException, UnsupportedEncodingException{ File directory = new File(folderName); if(!directory.exists()){ directory.mkdir(); } Cubic cubic = EquationsOfState.vanDerWaals(); double min_reducedPressure = 0.1; double max_reducedPressure= 7; double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100; double min_reducedTemperature= 1 ; double max_reducedTemperature=2; double criticalTemperature = 540.2; double criticalPressure = 2.74000E+06; double a = 3107000.0; double b = 0.2049; PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8"); writer.println(" p z rt"); for(double reducedTemperature = min_reducedTemperature; reducedTemperature <= max_reducedTemperature; reducedTemperature +=0.1){ for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){ double temperature = criticalTemperature * reducedTemperature; double pressure = criticalPressure * reducedPressure; // double A =cubic.get_A(temperature, pressure, a); // double B = cubic.get_B(temperature, pressure, b); substance.setPressure(pressure); substance.setTemperature(temperature); double z = substance.calculateCompresibilityFactor(); //double z =cubic.calculateCompresibilityFactor(A, B, Phase.LIQUID); writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature); } writer.println(); } writer.close(); } }
HugoRedon/thesis-examples
src/main/java/thesis/CubicFileGenerator.java
Java
gpl-2.0
4,031
/* * FileBrowser.cpp - implementation of the project-, preset- and * sample-file-browser * * Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net> * * This file is part of LMMS - http://lmms.io * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program (see COPYING); if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA. * */ #include <QHBoxLayout> #include <QKeyEvent> #include <QLineEdit> #include <QMenu> #include <QPushButton> #include <QMdiArea> #include <QMdiSubWindow> #include "FileBrowser.h" #include "BBTrackContainer.h" #include "ConfigManager.h" #include "debug.h" #include "embed.h" #include "Engine.h" #include "gui_templates.h" #include "ImportFilter.h" #include "Instrument.h" #include "InstrumentTrack.h" #include "MainWindow.h" #include "DataFile.h" #include "PresetPreviewPlayHandle.h" #include "SamplePlayHandle.h" #include "Song.h" #include "StringPairDrag.h" #include "TextFloat.h" enum TreeWidgetItemTypes { TypeFileItem = QTreeWidgetItem::UserType, TypeDirectoryItem } ; FileBrowser::FileBrowser(const QString & directories, const QString & filter, const QString & title, const QPixmap & pm, QWidget * parent, bool dirs_as_items ) : SideBarWidget( title, pm, parent ), m_directories( directories ), m_filter( filter ), m_dirsAsItems( dirs_as_items ) { setWindowTitle( tr( "Browser" ) ); m_l = new FileBrowserTreeWidget( contentParent() ); addContentWidget( m_l ); QWidget * ops = new QWidget( contentParent() ); ops->setFixedHeight( 24 ); QHBoxLayout * opl = new QHBoxLayout( ops ); opl->setMargin( 0 ); opl->setSpacing( 0 ); m_filterEdit = new QLineEdit( ops ); connect( m_filterEdit, SIGNAL( textEdited( const QString & ) ), this, SLOT( filterItems( const QString & ) ) ); QPushButton * reload_btn = new QPushButton( embed::getIconPixmap( "reload" ), QString::null, ops ); connect( reload_btn, SIGNAL( clicked() ), this, SLOT( reloadTree() ) ); opl->addWidget( m_filterEdit ); opl->addSpacing( 5 ); opl->addWidget( reload_btn ); addContentWidget( ops ); reloadTree(); show(); } FileBrowser::~FileBrowser() { } void FileBrowser::filterItems( const QString & filter ) { const bool show_all = filter.isEmpty(); for( int i = 0; i < m_l->topLevelItemCount(); ++i ) { QTreeWidgetItem * it = m_l->topLevelItem( i ); // show all items if filter is empty if( show_all ) { it->setHidden( false ); if( it->childCount() ) { filterItems( it, filter ); } } // is directory? else if( it->childCount() ) { // matches filter? if( it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ) { // yes, then show everything below it->setHidden( false ); filterItems( it, QString::null ); } else { // only show if item below matches filter it->setHidden( !filterItems( it, filter ) ); } } // a standard item (i.e. no file or directory item?) else if( it->type() == QTreeWidgetItem::Type ) { // hide in every case when filtering it->setHidden( true ); } else { // file matches filter? it->setHidden( !it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ); } } } bool FileBrowser::filterItems(QTreeWidgetItem * item, const QString & filter ) { const bool show_all = filter.isEmpty(); bool matched = false; for( int i = 0; i < item->childCount(); ++i ) { QTreeWidgetItem * it = item->child( i ); bool cm = false; // whether current item matched // show all items if filter is empty if( show_all ) { it->setHidden( false ); if( it->childCount() ) { filterItems( it, filter ); } } // is directory? else if( it->childCount() ) { // matches filter? if( it->text( 0 ). contains( filter, Qt::CaseInsensitive ) ) { // yes, then show everything below it->setHidden( false ); filterItems( it, QString::null ); cm = true; } else { // only show if item below matches filter cm = filterItems( it, filter ); it->setHidden( !cm ); } } // a standard item (i.e. no file or directory item?) else if( it->type() == QTreeWidgetItem::Type ) { // hide in every case when filtering it->setHidden( true ); } else { // file matches filter? cm = it->text( 0 ). contains( filter, Qt::CaseInsensitive ); it->setHidden( !cm ); } if( cm ) { matched = true; } } return matched; } void FileBrowser::reloadTree( void ) { const QString text = m_filterEdit->text(); m_filterEdit->clear(); m_l->clear(); QStringList paths = m_directories.split( '*' ); for( QStringList::iterator it = paths.begin(); it != paths.end(); ++it ) { addItems( *it ); } m_filterEdit->setText( text ); filterItems( text ); } void FileBrowser::addItems(const QString & path ) { if( m_dirsAsItems ) { m_l->addTopLevelItem( new Directory( path, QString::null, m_filter ) ); return; } QDir cdir( path ); QStringList files = cdir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < m_l->topLevelItemCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( m_l->topLevelItem( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { m_l->insertTopLevelItem( i, new Directory( cur_file, path, m_filter ) ); orphan = false; break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); orphan = false; break; } } if( orphan ) { m_l->addTopLevelItem( new Directory( cur_file, path, m_filter ) ); } } } files = cdir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { // TODO: don't insert instead of removing, order changed // remove existing file-items QList<QTreeWidgetItem *> existing = m_l->findItems( cur_file, Qt::MatchFixedString ); if( !existing.empty() ) { delete existing.front(); } (void) new FileItem( m_l, cur_file, path ); } } } void FileBrowser::keyPressEvent(QKeyEvent * ke ) { if( ke->key() == Qt::Key_F5 ) { reloadTree(); } else { ke->ignore(); } } FileBrowserTreeWidget::FileBrowserTreeWidget(QWidget * parent ) : QTreeWidget( parent ), m_mousePressed( false ), m_pressPos(), m_previewPlayHandle( NULL ), m_pphMutex( QMutex::Recursive ), m_contextMenuItem( NULL ) { setColumnCount( 1 ); headerItem()->setHidden( true ); setSortingEnabled( false ); setFont( pointSizeF( font(), 7.5f ) ); connect( this, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ), SLOT( activateListItem( QTreeWidgetItem *, int ) ) ); connect( this, SIGNAL( itemCollapsed( QTreeWidgetItem * ) ), SLOT( updateDirectory( QTreeWidgetItem * ) ) ); connect( this, SIGNAL( itemExpanded( QTreeWidgetItem * ) ), SLOT( updateDirectory( QTreeWidgetItem * ) ) ); } FileBrowserTreeWidget::~FileBrowserTreeWidget() { } void FileBrowserTreeWidget::contextMenuEvent(QContextMenuEvent * e ) { FileItem * f = dynamic_cast<FileItem *>( itemAt( e->pos() ) ); if( f != NULL && ( f->handling() == FileItem::LoadAsPreset || f->handling() == FileItem::LoadByPlugin ) ) { m_contextMenuItem = f; QMenu contextMenu( this ); contextMenu.addAction( tr( "Send to active instrument-track" ), this, SLOT( sendToActiveInstrumentTrack() ) ); contextMenu.addAction( tr( "Open in new instrument-track/" "Song-Editor" ), this, SLOT( openInNewInstrumentTrackSE() ) ); contextMenu.addAction( tr( "Open in new instrument-track/" "B+B Editor" ), this, SLOT( openInNewInstrumentTrackBBE() ) ); contextMenu.exec( e->globalPos() ); m_contextMenuItem = NULL; } } void FileBrowserTreeWidget::mousePressEvent(QMouseEvent * me ) { QTreeWidget::mousePressEvent( me ); if( me->button() != Qt::LeftButton ) { return; } QTreeWidgetItem * i = itemAt( me->pos() ); if ( i ) { // TODO: Restrict to visible selection // if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) ) // + treeStepSize() * ( i->depth() + ( rootIsDecorated() ? // 1 : 0 ) ) + itemMargin() || // _me->x() < header()->cellPos( // header()->mapToActual( 0 ) ) ) // { m_pressPos = me->pos(); m_mousePressed = true; // } } FileItem * f = dynamic_cast<FileItem *>( i ); if( f != NULL ) { m_pphMutex.lock(); if( m_previewPlayHandle != NULL ) { Engine::mixer()->removePlayHandle( m_previewPlayHandle ); m_previewPlayHandle = NULL; } // in special case of sample-files we do not care about // handling() rather than directly creating a SamplePlayHandle if( f->type() == FileItem::SampleFile ) { TextFloat * tf = TextFloat::displayMessage( tr( "Loading sample" ), tr( "Please wait, loading sample for " "preview..." ), embed::getIconPixmap( "sample_file", 24, 24 ), 0 ); qApp->processEvents( QEventLoop::ExcludeUserInputEvents ); SamplePlayHandle * s = new SamplePlayHandle( f->fullName() ); s->setDoneMayReturnTrue( false ); m_previewPlayHandle = s; delete tf; } else if( f->type() != FileItem::VstPluginFile && ( f->handling() == FileItem::LoadAsPreset || f->handling() == FileItem::LoadByPlugin ) ) { m_previewPlayHandle = new PresetPreviewPlayHandle( f->fullName(), f->handling() == FileItem::LoadByPlugin ); } if( m_previewPlayHandle != NULL ) { if( !Engine::mixer()->addPlayHandle( m_previewPlayHandle ) ) { m_previewPlayHandle = NULL; } } m_pphMutex.unlock(); } } void FileBrowserTreeWidget::mouseMoveEvent( QMouseEvent * me ) { if( m_mousePressed == true && ( m_pressPos - me->pos() ).manhattanLength() > QApplication::startDragDistance() ) { // make sure any playback is stopped mouseReleaseEvent( NULL ); FileItem * f = dynamic_cast<FileItem *>( itemAt( m_pressPos ) ); if( f != NULL ) { switch( f->type() ) { case FileItem::PresetFile: new StringPairDrag( f->handling() == FileItem::LoadAsPreset ? "presetfile" : "pluginpresetfile", f->fullName(), embed::getIconPixmap( "preset_file" ), this ); break; case FileItem::SampleFile: new StringPairDrag( "samplefile", f->fullName(), embed::getIconPixmap( "sample_file" ), this ); break; case FileItem::SoundFontFile: new StringPairDrag( "soundfontfile", f->fullName(), embed::getIconPixmap( "soundfont_file" ), this ); break; case FileItem::VstPluginFile: new StringPairDrag( "vstpluginfile", f->fullName(), embed::getIconPixmap( "vst_plugin_file" ), this ); break; case FileItem::MidiFile: // don't allow dragging FLP-files as FLP import filter clears project // without asking // case fileItem::FlpFile: new StringPairDrag( "importedproject", f->fullName(), embed::getIconPixmap( "midi_file" ), this ); break; default: break; } } } } void FileBrowserTreeWidget::mouseReleaseEvent(QMouseEvent * me ) { m_mousePressed = false; m_pphMutex.lock(); if( m_previewPlayHandle != NULL ) { // if there're samples shorter than 3 seconds, we don't // stop them if the user releases mouse-button... if( m_previewPlayHandle->type() == PlayHandle::TypeSamplePlayHandle ) { SamplePlayHandle * s = dynamic_cast<SamplePlayHandle *>( m_previewPlayHandle ); if( s && s->totalFrames() - s->framesDone() <= static_cast<f_cnt_t>( Engine::mixer()-> processingSampleRate() * 3 ) ) { s->setDoneMayReturnTrue( true ); m_previewPlayHandle = NULL; m_pphMutex.unlock(); return; } } Engine::mixer()->removePlayHandle( m_previewPlayHandle ); m_previewPlayHandle = NULL; } m_pphMutex.unlock(); } void FileBrowserTreeWidget::handleFile(FileItem * f, InstrumentTrack * it ) { Engine::mixer()->lock(); switch( f->handling() ) { case FileItem::LoadAsProject: if( Engine::mainWindow()->mayChangeProject() ) { Engine::getSong()->loadProject( f->fullName() ); } break; case FileItem::LoadByPlugin: { const QString e = f->extension(); Instrument * i = it->instrument(); if( i == NULL || !i->descriptor()->supportsFileType( e ) ) { i = it->loadInstrument( Engine::pluginFileHandling()[e] ); } i->loadFile( f->fullName() ); break; } case FileItem::LoadAsPreset: { DataFile dataFile( f->fullName() ); InstrumentTrack::removeMidiPortNode( dataFile ); it->setSimpleSerializing(); it->loadSettings( dataFile.content().toElement() ); break; } case FileItem::ImportAsProject: if( f->type() == FileItem::FlpFile && !Engine::mainWindow()->mayChangeProject() ) { break; } ImportFilter::import( f->fullName(), Engine::getSong() ); break; case FileItem::NotSupported: default: break; } Engine::mixer()->unlock(); } void FileBrowserTreeWidget::activateListItem(QTreeWidgetItem * item, int column ) { FileItem * f = dynamic_cast<FileItem *>( item ); if( f == NULL ) { return; } if( f->handling() == FileItem::LoadAsProject || f->handling() == FileItem::ImportAsProject ) { handleFile( f, NULL ); } else if( f->handling() != FileItem::NotSupported ) { // engine::mixer()->lock(); InstrumentTrack * it = dynamic_cast<InstrumentTrack *>( Track::create( Track::InstrumentTrack, Engine::getBBTrackContainer() ) ); handleFile( f, it ); // engine::mixer()->unlock(); } } void FileBrowserTreeWidget::openInNewInstrumentTrack( TrackContainer* tc ) { if( m_contextMenuItem->handling() == FileItem::LoadAsPreset || m_contextMenuItem->handling() == FileItem::LoadByPlugin ) { // engine::mixer()->lock(); InstrumentTrack * it = dynamic_cast<InstrumentTrack *>( Track::create( Track::InstrumentTrack, tc ) ); handleFile( m_contextMenuItem, it ); // engine::mixer()->unlock(); } } void FileBrowserTreeWidget::openInNewInstrumentTrackBBE( void ) { openInNewInstrumentTrack( Engine::getBBTrackContainer() ); } void FileBrowserTreeWidget::openInNewInstrumentTrackSE( void ) { openInNewInstrumentTrack( Engine::getSong() ); } void FileBrowserTreeWidget::sendToActiveInstrumentTrack( void ) { // get all windows opened in the workspace QList<QMdiSubWindow*> pl = Engine::mainWindow()->workspace()-> subWindowList( QMdiArea::StackingOrder ); QListIterator<QMdiSubWindow *> w( pl ); w.toBack(); // now we travel through the window-list until we find an // instrument-track while( w.hasPrevious() ) { InstrumentTrackWindow * itw = dynamic_cast<InstrumentTrackWindow *>( w.previous()->widget() ); if( itw != NULL && itw->isHidden() == false ) { handleFile( m_contextMenuItem, itw->model() ); break; } } } void FileBrowserTreeWidget::updateDirectory(QTreeWidgetItem * item ) { Directory * dir = dynamic_cast<Directory *>( item ); if( dir != NULL ) { dir->update(); } } QPixmap * Directory::s_folderPixmap = NULL; QPixmap * Directory::s_folderOpenedPixmap = NULL; QPixmap * Directory::s_folderLockedPixmap = NULL; Directory::Directory(const QString & filename, const QString & path, const QString & filter ) : QTreeWidgetItem( QStringList( filename ), TypeDirectoryItem ), m_directories( path ), m_filter( filter ) { initPixmaps(); setChildIndicatorPolicy( QTreeWidgetItem::ShowIndicator ); if( !QDir( fullName() ).isReadable() ) { setIcon( 0, *s_folderLockedPixmap ); } else { setIcon( 0, *s_folderPixmap ); } } void Directory::initPixmaps( void ) { if( s_folderPixmap == NULL ) { s_folderPixmap = new QPixmap( embed::getIconPixmap( "folder" ) ); } if( s_folderOpenedPixmap == NULL ) { s_folderOpenedPixmap = new QPixmap( embed::getIconPixmap( "folder_opened" ) ); } if( s_folderLockedPixmap == NULL ) { s_folderLockedPixmap = new QPixmap( embed::getIconPixmap( "folder_locked" ) ); } } void Directory::update( void ) { if( !isExpanded() ) { setIcon( 0, *s_folderPixmap ); return; } setIcon( 0, *s_folderOpenedPixmap ); if( !childCount() ) { for( QStringList::iterator it = m_directories.begin(); it != m_directories.end(); ++it ) { int top_index = childCount(); if( addItems( fullName( *it ) ) && ( *it ).contains( ConfigManager::inst()->dataDir() ) ) { QTreeWidgetItem * sep = new QTreeWidgetItem; sep->setText( 0, FileBrowserTreeWidget::tr( "--- Factory files ---" ) ); sep->setIcon( 0, embed::getIconPixmap( "factory_files" ) ); insertChild( top_index, sep ); } } } } bool Directory::addItems(const QString & path ) { QDir thisDir( path ); if( !thisDir.isReadable() ) { return false; } treeWidget()->setUpdatesEnabled( false ); bool added_something = false; QStringList files = thisDir.entryList( QDir::Dirs, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' ) { bool orphan = true; for( int i = 0; i < childCount(); ++i ) { Directory * d = dynamic_cast<Directory *>( child( i ) ); if( d == NULL || cur_file < d->text( 0 ) ) { insertChild( i, new Directory( cur_file, path, m_filter ) ); orphan = false; break; } else if( cur_file == d->text( 0 ) ) { d->addDirectory( path ); orphan = false; break; } } if( orphan ) { addChild( new Directory( cur_file, path, m_filter ) ); } added_something = true; } } QList<QTreeWidgetItem*> items; files = thisDir.entryList( QDir::Files, QDir::Name ); for( QStringList::const_iterator it = files.constBegin(); it != files.constEnd(); ++it ) { QString cur_file = *it; if( cur_file[0] != '.' && thisDir.match( m_filter, cur_file.toLower() ) ) { items << new FileItem( cur_file, path ); added_something = true; } } addChildren( items ); treeWidget()->setUpdatesEnabled( true ); return added_something; } QPixmap * FileItem::s_projectFilePixmap = NULL; QPixmap * FileItem::s_presetFilePixmap = NULL; QPixmap * FileItem::s_sampleFilePixmap = NULL; QPixmap * FileItem::s_soundfontFilePixmap = NULL; QPixmap * FileItem::s_vstPluginFilePixmap = NULL; QPixmap * FileItem::s_midiFilePixmap = NULL; QPixmap * FileItem::s_flpFilePixmap = NULL; QPixmap * FileItem::s_unknownFilePixmap = NULL; FileItem::FileItem(QTreeWidget * parent, const QString & name, const QString & path ) : QTreeWidgetItem( parent, QStringList( name) , TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } FileItem::FileItem(const QString & name, const QString & path ) : QTreeWidgetItem( QStringList( name ), TypeFileItem ), m_path( path ) { determineFileType(); initPixmaps(); } void FileItem::initPixmaps( void ) { if( s_projectFilePixmap == NULL ) { s_projectFilePixmap = new QPixmap( embed::getIconPixmap( "project_file", 16, 16 ) ); } if( s_presetFilePixmap == NULL ) { s_presetFilePixmap = new QPixmap( embed::getIconPixmap( "preset_file", 16, 16 ) ); } if( s_sampleFilePixmap == NULL ) { s_sampleFilePixmap = new QPixmap( embed::getIconPixmap( "sample_file", 16, 16 ) ); } if ( s_soundfontFilePixmap == NULL ) { s_soundfontFilePixmap = new QPixmap( embed::getIconPixmap( "soundfont_file", 16, 16 ) ); } if ( s_vstPluginFilePixmap == NULL ) { s_vstPluginFilePixmap = new QPixmap( embed::getIconPixmap( "vst_plugin_file", 16, 16 ) ); } if( s_midiFilePixmap == NULL ) { s_midiFilePixmap = new QPixmap( embed::getIconPixmap( "midi_file", 16, 16 ) ); } if( s_flpFilePixmap == NULL ) { s_flpFilePixmap = new QPixmap( embed::getIconPixmap( "midi_file", 16, 16 ) ); } if( s_unknownFilePixmap == NULL ) { s_unknownFilePixmap = new QPixmap( embed::getIconPixmap( "unknown_file" ) ); } switch( m_type ) { case ProjectFile: setIcon( 0, *s_projectFilePixmap ); break; case PresetFile: setIcon( 0, *s_presetFilePixmap ); break; case SoundFontFile: setIcon( 0, *s_soundfontFilePixmap ); break; case VstPluginFile: setIcon( 0, *s_vstPluginFilePixmap ); break; case SampleFile: case PatchFile: // TODO setIcon( 0, *s_sampleFilePixmap ); break; case MidiFile: setIcon( 0, *s_midiFilePixmap ); break; case FlpFile: setIcon( 0, *s_flpFilePixmap ); break; case UnknownFile: default: setIcon( 0, *s_unknownFilePixmap ); break; } } void FileItem::determineFileType( void ) { m_handling = NotSupported; const QString ext = extension(); if( ext == "mmp" || ext == "mpt" || ext == "mmpz" ) { m_type = ProjectFile; m_handling = LoadAsProject; } else if( ext == "xpf" || ext == "xml" ) { m_type = PresetFile; m_handling = LoadAsPreset; } else if( ext == "xiz" && Engine::pluginFileHandling().contains( ext ) ) { m_type = PresetFile; m_handling = LoadByPlugin; } else if( ext == "sf2" ) { m_type = SoundFontFile; } else if( ext == "pat" ) { m_type = PatchFile; } else if( ext == "mid" ) { m_type = MidiFile; m_handling = ImportAsProject; } else if( ext == "flp" ) { m_type = FlpFile; m_handling = ImportAsProject; } else if( ext == "dll" ) { m_type = VstPluginFile; m_handling = LoadByPlugin; } else { m_type = UnknownFile; } if( m_handling == NotSupported && !ext.isEmpty() && Engine::pluginFileHandling().contains( ext ) ) { m_handling = LoadByPlugin; // classify as sample if not classified by anything yet but can // be handled by a certain plugin if( m_type == UnknownFile ) { m_type = SampleFile; } } } QString FileItem::extension( void ) { return extension( fullName() ); } QString FileItem::extension(const QString & file ) { return QFileInfo( file ).suffix().toLower(); }
badosu/lmms
src/gui/FileBrowser.cpp
C++
gpl-2.0
22,711
/* * Copyright (c) 2002-2009 BalaBit IT Ltd, Budapest, Hungary * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * Note that this permission is granted for only version 2 of the GPL. * * As an additional exemption you are allowed to compile & link against the * OpenSSL libraries as published by the OpenSSL project. See the file * COPYING for details. * * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "gprocess.h" #include "misc.h" #include "messages.h" #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <time.h> #include <sys/resource.h> #include <sys/wait.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <signal.h> #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <pwd.h> #include <grp.h> #if ENABLE_LINUX_CAPS # include <sys/capability.h> # include <sys/prctl.h> #endif /* * NOTES: * * * pidfile is created and removed by the daemon (e.g. the child) itself, * the parent does not touch that * * * we communicate with the user using stderr (using fprintf) as long as it * is available and using syslog() afterwards * * * there are 3 processes involved in safe_background mode (e.g. auto-restart) * - startup process which was started by the user (zorpctl) * - supervisor process which automatically restarts the daemon when it exits abnormally * - daemon processes which perform the actual task at hand * * The startup process delivers the result of the first startup to its * caller, if we can deliver a failure in this case then restarts will not * be performed (e.g. if the first startup fails, the daemon will not be * restarted even if auto-restart was enabled). After the first successful * start, the startup process exits (delivering that startup was * successful) and the supervisor process wait()s for the daemon processes * to exit. If they exit prematurely (e.g. they crash) they will be * restarted, if the startup is not successful in this case the restart * will be attempted again just as if they crashed. * * The processes communicate with two pairs of pipes, startup_result_pipe * is used to indicate success/failure to the startup process, * init_result_pipe (as in "initialization") is used to deliver success * reports from the daemon to the supervisor. */ typedef enum { G_PK_STARTUP, G_PK_SUPERVISOR, G_PK_DAEMON, } GProcessKind; #define G_PROCESS_FD_LIMIT_RESERVE 64 #define G_PROCESS_FAILURE_NOTIFICATION PATH_PREFIX "/sbin/syslog-ng-failure" /* pipe used to deliver the initialization result to the calling process */ static gint startup_result_pipe[2] = { -1, -1 }; /* pipe used to deliver initialization result to the supervisor */ static gint init_result_pipe[2] = { -1, -1 }; static GProcessKind process_kind = G_PK_STARTUP; static gboolean stderr_present = TRUE; /* global variables */ static struct { GProcessMode mode; const gchar *name; const gchar *user; gint uid; const gchar *group; gint gid; const gchar *chroot_dir; const gchar *pidfile; const gchar *pidfile_dir; const gchar *cwd; const gchar *caps; gint argc; gchar **argv; gchar *argv_start; size_t argv_env_len; gchar *argv_orig; gboolean core; gint fd_limit_min; gint check_period; gboolean (*check_fn)(void); } process_opts = { .mode = G_PM_SAFE_BACKGROUND, .argc = 0, .argv = NULL, .argv_start = NULL, .argv_env_len = 0, #ifdef __CYGWIN__ .fd_limit_min = 256, #else .fd_limit_min = 4096, #endif .check_period = -1, .check_fn = NULL, .uid = -1, .gid = -1 }; #if ENABLE_LINUX_CAPS /** * g_process_cap_modify: * @capability: capability to turn off or on * @onoff: specifies whether the capability should be enabled or disabled * * This function modifies the current permitted set of capabilities by * enabling or disabling the capability specified in @capability. * * Returns: whether the operation was successful. **/ gboolean g_process_cap_modify(int capability, int onoff) { cap_t caps; if (!process_opts.caps) return TRUE; caps = cap_get_proc(); if (!caps) return FALSE; if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &capability, onoff) == -1) { msg_error("Error managing capability set, cap_set_flag returned an error", evt_tag_errno("error", errno), NULL); cap_free(caps); return FALSE; } if (cap_set_proc(caps) == -1) { gchar *cap_text; cap_text = cap_to_text(caps, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); cap_free(caps); return FALSE; } cap_free(caps); return TRUE; } /** * g_process_cap_save: * * Save the set of current capabilities and return it. The caller might * restore the saved set of capabilities by using cap_restore(). * * Returns: the current set of capabilities **/ cap_t g_process_cap_save(void) { if (!process_opts.caps) return NULL; return cap_get_proc(); } /** * cap_restore: * @r: capability set saved by cap_save() * * Restore the set of current capabilities specified by @r. * * Returns: whether the operation was successful. **/ void g_process_cap_restore(cap_t r) { gboolean rc; if (!process_opts.caps) return; rc = cap_set_proc(r) != -1; cap_free(r); if (!rc) { gchar *cap_text; cap_text = cap_to_text(r, NULL); msg_error("Error managing capability set, cap_set_proc returned an error", evt_tag_str("caps", cap_text), evt_tag_errno("error", errno), NULL); cap_free(cap_text); return; } return; } #endif /** * g_process_set_mode: * @mode: an element from ZProcessMode * * This function should be called by the daemon to set the processing mode * as specified by @mode. **/ void g_process_set_mode(GProcessMode mode) { process_opts.mode = mode; } /** * g_process_set_name: * @name: the name of the process to be reported as program name * * This function should be called by the daemon to set the program name * which is present in various error message and might influence the PID * file if not overridden by g_process_set_pidfile(). **/ void g_process_set_name(const gchar *name) { process_opts.name = name; } /** * g_process_set_user: * @user: the name of the user the process should switch to during startup * * This function should be called by the daemon to set the user name. **/ void g_process_set_user(const gchar *user) { if (!process_opts.user) process_opts.user = user; } /** * g_process_set_group: * @group: the name of the group the process should switch to during startup * * This function should be called by the daemon to set the group name. **/ void g_process_set_group(const gchar *group) { if (!process_opts.group) process_opts.group = group; } /** * g_process_set_chroot: * @chroot_dir: the name of the chroot directory the process should switch to during startup * * This function should be called by the daemon to set the chroot directory **/ void g_process_set_chroot(const gchar *chroot_dir) { if (!process_opts.chroot_dir) process_opts.chroot_dir = chroot_dir; } /** * g_process_set_pidfile: * @pidfile: the name of the complete pid file with full path * * This function should be called by the daemon to set the PID file name to * store the pid of the process. This value will be used as the pidfile * directly, neither name nor pidfile_dir influences the pidfile location if * this is set. **/ void g_process_set_pidfile(const gchar *pidfile) { if (!process_opts.pidfile) process_opts.pidfile = pidfile; } /** * g_process_set_pidfile_dir: * @pidfile_dir: name of the pidfile directory * * This function should be called by the daemon to set the PID file * directory. This value is not used if set_pidfile() was called. **/ void g_process_set_pidfile_dir(const gchar *pidfile_dir) { if (!process_opts.pidfile_dir) process_opts.pidfile_dir = pidfile_dir; } /** * g_process_set_working_dir: * @working_dir: name of the working directory * * This function should be called by the daemon to set the working * directory. The process will change its current directory to this value or * to pidfile_dir if it is unset. **/ void g_process_set_working_dir(const gchar *cwd) { if (!process_opts.cwd) process_opts.cwd = cwd; } /** * g_process_set_caps: * @caps: capability specification in text form * * This function should be called by the daemon to set the initial * capability set. The process will change its capabilities to this value * during startup, provided it has enough permissions to do so. **/ void g_process_set_caps(const gchar *caps) { if (!process_opts.caps) process_opts.caps = caps; } /** * g_process_set_argv_space: * @argc: Original argc, as received by the main function in it's first parameter * @argv: Original argv, as received by the main function in it's second parameter * * This function should be called by the daemon if it wants to enable * process title manipulation in the supervisor process. **/ void g_process_set_argv_space(gint argc, gchar **argv) { extern char **environ; gchar *lastargv = NULL; gchar **envp = environ; gint i; if (process_opts.argv) return; process_opts.argv = argv; process_opts.argc = argc; for (i = 0; envp[i] != NULL; i++) ; environ = g_new(char *, i + 1); /* * Find the last argv string or environment variable within * our process memory area. */ for (i = 0; i < process_opts.argc; i++) { if (lastargv == NULL || lastargv + 1 == process_opts.argv[i]) lastargv = process_opts.argv[i] + strlen(process_opts.argv[i]); } for (i = 0; envp[i] != NULL; i++) { if (lastargv + 1 == envp[i]) lastargv = envp[i] + strlen(envp[i]); } process_opts.argv_start = process_opts.argv[0]; process_opts.argv_env_len = lastargv - process_opts.argv[0] - 1; process_opts.argv_orig = malloc(sizeof(gchar) * process_opts.argv_env_len); memcpy(process_opts.argv_orig, process_opts.argv_start, process_opts.argv_env_len); /* * Copy environment * XXX - will truncate env on strdup fail */ for (i = 0; envp[i] != NULL; i++) environ[i] = g_strdup(envp[i]); environ[i] = NULL; } /** * g_process_set_check: * @check_period: check period in seconds * @check_fn: checker function * * Installs a checker function that is called at the specified rate. * The checked process is allowed to run as long as this function * returns TRUE. */ void g_process_set_check(gint check_period, gboolean (*check_fn)(void)) { process_opts.check_period = check_period; process_opts.check_fn = check_fn; } /** * g_process_message: * @fmt: format string * @...: arguments to @fmt * * This function sends a message to the client preferring to use the stderr * channel as long as it is available and switching to using syslog() if it * isn't. Generally the stderr channell will be available in the startup * process and in the beginning of the first startup in the * supervisor/daemon processes. Later on the stderr fd will be closed and we * have to fall back to using the system log. **/ void g_process_message(const gchar *fmt, ...) { gchar buf[2048]; va_list ap; va_start(ap, fmt); g_vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (stderr_present) fprintf(stderr, "%s: %s\n", process_opts.name, buf); else { gchar name[32]; g_snprintf(name, sizeof(name), "%s/%s", process_kind == G_PK_SUPERVISOR ? "supervise" : "daemon", process_opts.name); openlog(name, LOG_PID, LOG_DAEMON); syslog(LOG_CRIT, "%s\n", buf); closelog(); } } /** * g_process_detach_tty: * * This function is called from g_process_start() to detach from the * controlling tty. **/ static void g_process_detach_tty(void) { if (process_opts.mode != G_PM_FOREGROUND) { /* detach ourselves from the tty when not staying in the foreground */ if (isatty(STDIN_FILENO)) { #ifdef TIOCNOTTY ioctl(STDIN_FILENO, TIOCNOTTY, 0); #endif setsid(); } } } /** * g_process_change_limits: * * Set fd limit. * **/ static void g_process_change_limits(void) { struct rlimit limit; limit.rlim_cur = limit.rlim_max = process_opts.fd_limit_min; if (setrlimit(RLIMIT_NOFILE, &limit) < 0) g_process_message("Error setting file number limit; limit='%d'; error='%s'", process_opts.fd_limit_min, g_strerror(errno)); } /** * g_process_detach_stdio: * * Use /dev/null as input/output/error. This function is idempotent, can be * called any number of times without harm. **/ static void g_process_detach_stdio(void) { gint devnull_fd; if (process_opts.mode != G_PM_FOREGROUND && stderr_present) { devnull_fd = open("/dev/null", O_RDONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDIN_FILENO); close(devnull_fd); } devnull_fd = open("/dev/null", O_WRONLY); if (devnull_fd >= 0) { dup2(devnull_fd, STDOUT_FILENO); dup2(devnull_fd, STDERR_FILENO); close(devnull_fd); } stderr_present = FALSE; } } /** * g_process_enable_core: * * Enable core file dumping by setting PR_DUMPABLE and changing the core * file limit to infinity. **/ static void g_process_enable_core(void) { struct rlimit limit; if (process_opts.core) { #if ENABLE_LINUX_CAPS if (!prctl(PR_GET_DUMPABLE, 0, 0, 0, 0)) { gint rc; rc = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0); if (rc < 0) g_process_message("Cannot set process to be dumpable; error='%s'", g_strerror(errno)); } #endif limit.rlim_cur = limit.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &limit) < 0) g_process_message("Error setting core limit to infinity; error='%s'", g_strerror(errno)); } } /** * g_process_format_pidfile_name: * @buf: buffer to store the pidfile name * @buflen: size of @buf * * Format the pid file name according to the settings specified by the * process. **/ static const gchar * g_process_format_pidfile_name(gchar *buf, gsize buflen) { const gchar *pidfile = process_opts.pidfile; if (pidfile == NULL) { g_snprintf(buf, buflen, "%s/%s.pid", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, process_opts.name); pidfile = buf; } else if (pidfile[0] != '/') { /* complete path to pidfile not specified, assume it is a relative path to pidfile_dir */ g_snprintf(buf, buflen, "%s/%s", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, pidfile); pidfile = buf; } return pidfile; } /** * g_process_write_pidfile: * @pid: pid to write into the pidfile * * Write the pid to the pidfile. **/ static void g_process_write_pidfile(pid_t pid) { gchar buf[256]; const gchar *pidfile; FILE *fd; pidfile = g_process_format_pidfile_name(buf, sizeof(buf)); fd = fopen(pidfile, "w"); if (fd != NULL) { fprintf(fd, "%d\n", (int) pid); fclose(fd); } else { g_process_message("Error creating pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * g_process_remove_pidfile: * * Remove the pidfile. **/ static void g_process_remove_pidfile(void) { gchar buf[256]; const gchar *pidfile; pidfile = g_process_format_pidfile_name(buf, sizeof(buf)); if (unlink(pidfile) < 0) { g_process_message("Error removing pid file; file='%s', error='%s'", pidfile, g_strerror(errno)); } } /** * g_process_change_root: * * Change the current root to the value specified by the user, causes the * startup process to fail if this function returns FALSE. (e.g. the user * specified a chroot but we could not change to that directory) * * Returns: TRUE to indicate success **/ static gboolean g_process_change_root(void) { if (process_opts.chroot_dir) { if (chroot(process_opts.chroot_dir) < 0) { g_process_message("Error in chroot(); chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } if (chdir("/") < 0) { g_process_message("Error in chdir() after chroot; chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno)); return FALSE; } } return TRUE; } /** * g_process_change_user: * * Change the current user/group/groups to the value specified by the user. * causes the startup process to fail if this function returns FALSE. (e.g. * the user requested the uid/gid to change we could not change to that uid) * * Returns: TRUE to indicate success **/ static gboolean g_process_change_user(void) { #if ENABLE_LINUX_CAPS if (process_opts.caps) prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); #endif if (process_opts.gid >= 0) { if (setgid((gid_t) process_opts.gid) < 0) { g_process_message("Error in setgid(); group='%s', gid='%d', error='%s'", process_opts.group, process_opts.gid, g_strerror(errno)); if (getuid() == 0) return FALSE; } if (process_opts.user && initgroups(process_opts.user, (gid_t) process_opts.gid) < 0) { g_process_message("Error in initgroups(); user='%s', error='%s'", process_opts.user, g_strerror(errno)); if (getuid() == 0) return FALSE; } } if (process_opts.uid >= 0) { if (setuid((uid_t) process_opts.uid) < 0) { g_process_message("Error in setuid(); user='%s', uid='%d', error='%s'", process_opts.user, process_opts.uid, g_strerror(errno)); if (getuid() == 0) return FALSE; } } return TRUE; } #if ENABLE_LINUX_CAPS /** * g_process_change_caps: * * Change the current capset to the value specified by the user. causes the * startup process to fail if this function returns FALSE, but we only do * this if the capset cannot be parsed, otherwise a failure changing the * capabilities will not result in failure * * Returns: TRUE to indicate success **/ static gboolean g_process_change_caps(void) { if (process_opts.caps) { cap_t cap = cap_from_text(process_opts.caps); if (cap == NULL) { g_process_message("Error parsing capabilities: %s", process_opts.caps); process_opts.caps = NULL; return FALSE; } else { if (cap_set_proc(cap) == -1) { g_process_message("Error setting capabilities, capability management disabled; error='%s'", g_strerror(errno)); process_opts.caps = NULL; } cap_free(cap); } } return TRUE; } #else static gboolean g_process_change_caps(void) { return TRUE; } #endif static void g_process_resolve_names(void) { if (process_opts.user && !resolve_user(process_opts.user, &process_opts.uid)) { g_process_message("Error resolving user; user='%s'", process_opts.user); process_opts.uid = -1; } if (process_opts.group && !resolve_group(process_opts.group, &process_opts.gid)) { g_process_message("Error resolving group; group='%s'", process_opts.group); process_opts.gid = -1; } } /** * g_process_change_dir: * * Change the current working directory to the value specified by the user * and verify that the daemon would be able to dump core to that directory * if that is requested. **/ static void g_process_change_dir(void) { const gchar *cwd = NULL; if (process_opts.mode != G_PM_FOREGROUND) { if (process_opts.cwd) cwd = process_opts.cwd; else if (process_opts.pidfile_dir) cwd = process_opts.pidfile_dir; if (!cwd) cwd = PATH_PIDFILEDIR; if (cwd) chdir(cwd); } /* this check is here to avoid having to change directory early in the startup process */ if ((process_opts.core) && access(".", W_OK) < 0) { gchar buf[256]; getcwd(buf, sizeof(buf)); g_process_message("Unable to write to current directory, core dumps will not be generated; dir='%s', error='%s'", buf, g_strerror(errno)); } } /** * g_process_send_result: * @ret_num: exit code of the process * * This function is called to notify our parent process (which is the same * executable process but separated with a fork()) about the result of the * process startup phase. Specifying ret_num == 0 means that everything was * dandy, all other values mean that the initialization failed and the * parent should exit using ret_num as the exit code. The function behaves * differently depending on which process it was called from, determined by * the value of the process_kind global variable. In the daemon process it * writes to init_result_pipe, in the startup process it writes to the * startup_result_pipe. * * This function can only be called once, further invocations will do nothing. **/ static void g_process_send_result(guint ret_num) { gchar buf[10]; guint buf_len; gint *fd; if (process_kind == G_PK_SUPERVISOR) fd = &startup_result_pipe[1]; else if (process_kind == G_PK_DAEMON) fd = &init_result_pipe[1]; else g_assert_not_reached(); if (*fd != -1) { buf_len = g_snprintf(buf, sizeof(buf), "%d\n", ret_num); write(*fd, buf, buf_len); close(*fd); *fd = -1; } } /** * g_process_recv_result: * * Retrieves an exit code value from one of the result pipes depending on * which process the function was called from. This function can be called * only once, further invocations will return non-zero result code. **/ static gint g_process_recv_result(void) { gchar ret_buf[6]; gint ret_num = 1; gint *fd; /* FIXME: use a timer */ if (process_kind == G_PK_SUPERVISOR) fd = &init_result_pipe[0]; else if (process_kind == G_PK_STARTUP) fd = &startup_result_pipe[0]; else g_assert_not_reached(); if (*fd != -1) { memset(ret_buf, 0, sizeof(ret_buf)); if (read(*fd, ret_buf, sizeof(ret_buf)) > 0) { ret_num = atoi(ret_buf); } else { /* the process probably crashed without telling a proper exit code */ ret_num = 1; } close(*fd); *fd = -1; } return ret_num; } /** * g_process_perform_startup: * * This function is the startup process, never returns, the startup process exits here. **/ static void g_process_perform_startup(void) { /* startup process */ exit(g_process_recv_result()); } #define SPT_PADCHAR '\0' static void g_process_setproctitle(const gchar* proc_title) { size_t len; g_assert(process_opts.argv_start != NULL); len = g_strlcpy(process_opts.argv_start, proc_title, process_opts.argv_env_len); for (; len < process_opts.argv_env_len; ++len) process_opts.argv_start[len] = SPT_PADCHAR; } #define PROC_TITLE_SPACE 1024 /** * g_process_perform_supervise: * * Supervise process, returns only in the context of the daemon process, the * supervisor process exits here. **/ static void g_process_perform_supervise(void) { pid_t pid; gboolean first = TRUE, exited = FALSE; gchar proc_title[PROC_TITLE_SPACE]; g_snprintf(proc_title, PROC_TITLE_SPACE, "supervising %s", process_opts.name); g_process_setproctitle(proc_title); while (1) { if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); g_process_startup_failed(1, TRUE); } /* fork off a child process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); g_process_startup_failed(1, TRUE); } else if (pid != 0) { gint rc; gboolean deadlock = FALSE; /* this is the supervisor process */ /* shut down init_result_pipe write side */ close(init_result_pipe[1]); init_result_pipe[1] = -1; rc = g_process_recv_result(); if (first) { /* first time encounter, we have a chance to report back, do it */ g_process_send_result(rc); if (rc != 0) break; g_process_detach_stdio(); } first = FALSE; if (rc != 0) { gint i = 0; /* initialization failed in daemon, it will probably exit soon, wait and restart */ while (i < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (i > 3) kill(pid, i > 4 ? SIGKILL : SIGTERM); sleep(1); i++; } if (i == 6) g_process_message("Initialization failed but the daemon did not exit, even when forced to, trying to recover; pid='%d'", pid); continue; } if (process_opts.check_fn && (process_opts.check_period >= 0)) { gint i = 1; while (!(exited = waitpid(pid, &rc, WNOHANG))) { if (i >= process_opts.check_period) { if (!process_opts.check_fn()) break; i = 0; } sleep(1); i++; } if (!exited) { gint j = 0; g_process_message("Daemon deadlock detected, killing process;"); deadlock = TRUE; while (j < 6 && waitpid(pid, &rc, WNOHANG) == 0) { if (j > 3) kill(pid, j > 4 ? SIGKILL : SIGABRT); sleep(1); j++; } if (j == 6) g_process_message("The daemon did not exit after deadlock, even when forced to, trying to recover; pid='%d'", pid); } } else { waitpid(pid, &rc, 0); } if (deadlock || WIFSIGNALED(rc) || (WIFEXITED(rc) && WEXITSTATUS(rc) != 0)) { gchar argbuf[64]; if (!access(G_PROCESS_FAILURE_NOTIFICATION, R_OK | X_OK)) { const gchar *notify_reason; pid_t npid = fork(); gint nrc; switch (npid) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); break; case 0: switch(fork()) { case -1: g_process_message("Could not fork for external notification; reason='%s'", strerror(errno)); exit(1); break; case 0: if (deadlock) { notify_reason = "deadlock detected"; argbuf[0] = 0; } else { snprintf(argbuf, sizeof(argbuf), "%d", WIFSIGNALED(rc) ? WTERMSIG(rc) : WEXITSTATUS(rc)); if (WIFSIGNALED(rc)) notify_reason = "signalled"; else notify_reason = "non-zero exit code"; } execlp(G_PROCESS_FAILURE_NOTIFICATION, G_PROCESS_FAILURE_NOTIFICATION, SAFE_STRING(process_opts.name), SAFE_STRING(process_opts.chroot_dir), SAFE_STRING(process_opts.pidfile_dir), SAFE_STRING(process_opts.pidfile), SAFE_STRING(process_opts.cwd), SAFE_STRING(process_opts.caps), notify_reason, argbuf, (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) ? "restarting" : "not-restarting", (gchar*) NULL); g_process_message("Could not execute external notification; reason='%s'", strerror(errno)); break; default: exit(0); break; } /* child process */ default: waitpid(npid, &nrc, 0); break; } } if (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) { g_process_message("Daemon exited due to a deadlock/signal/failure, restarting; exitcode='%d'", rc); sleep(1); } else { g_process_message("Daemon was killed, not restarting; exitcode='%d'", rc); break; } } else { g_process_message("Daemon exited gracefully, not restarting; exitcode='%d'", rc); break; } } else { /* this is the daemon process, thus we should return to the caller of g_process_start() */ /* shut down init_result_pipe read side */ process_kind = G_PK_DAEMON; close(init_result_pipe[0]); init_result_pipe[0] = -1; memcpy(process_opts.argv_start, process_opts.argv_orig, process_opts.argv_env_len); return; } } exit(0); } /** * g_process_start: * * Start the process as directed by the options set by various * g_process_set_*() functions. **/ void g_process_start(void) { pid_t pid; g_process_detach_tty(); g_process_change_limits(); g_process_resolve_names(); if (process_opts.mode == G_PM_BACKGROUND) { /* no supervisor, sends result to startup process directly */ if (pipe(init_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* shut down init_result_pipe write side */ close(init_result_pipe[1]); /* connect startup_result_pipe with init_result_pipe */ startup_result_pipe[0] = init_result_pipe[0]; init_result_pipe[0] = -1; g_process_perform_startup(); /* NOTE: never returns */ g_assert_not_reached(); } process_kind = G_PK_DAEMON; /* shut down init_result_pipe read side */ close(init_result_pipe[0]); init_result_pipe[0] = -1; } else if (process_opts.mode == G_PM_SAFE_BACKGROUND) { /* full blown startup/supervisor/daemon */ if (pipe(startup_result_pipe) != 0) { g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno)); exit(1); } /* first fork off supervisor process */ if ((pid = fork()) < 0) { g_process_message("Error forking child process; error='%s'", g_strerror(errno)); exit(1); } else if (pid != 0) { /* this is the startup process */ /* shut down startup_result_pipe write side */ close(startup_result_pipe[1]); startup_result_pipe[1] = -1; /* NOTE: never returns */ g_process_perform_startup(); g_assert_not_reached(); } /* this is the supervisor process */ /* shut down startup_result_pipe read side */ close(startup_result_pipe[0]); startup_result_pipe[0] = -1; process_kind = G_PK_SUPERVISOR; g_process_perform_supervise(); /* we only return in the daamon process here */ } else if (process_opts.mode == G_PM_FOREGROUND) { process_kind = G_PK_DAEMON; } else { g_assert_not_reached(); } /* daemon process, we should return to the caller to perform work */ setsid(); /* NOTE: we need to signal the parent in case of errors from this point. * This is accomplished by writing the appropriate exit code to * init_result_pipe, the easiest way doing so is calling g_process_startup_failed. * */ if (!g_process_change_root() || !g_process_change_user() || !g_process_change_caps()) { g_process_startup_failed(1, TRUE); } g_process_enable_core(); g_process_change_dir(); } /** * g_process_startup_failed: * @ret_num: exit code * @may_exit: whether to exit the process * * This is a public API function to be called by the user code when * initialization failed. **/ void g_process_startup_failed(guint ret_num, gboolean may_exit) { if (process_kind != G_PK_STARTUP) g_process_send_result(ret_num); if (may_exit) { exit(ret_num); } else { g_process_detach_stdio(); } } /** * g_process_startup_ok: * * This is a public API function to be called by the user code when * initialization was successful, we can report back to the user. **/ void g_process_startup_ok(void) { g_process_write_pidfile(getpid()); g_process_send_result(0); g_process_detach_stdio(); } /** * g_process_finish: * * This is a public API function to be called by the user code when the * daemon exits after properly initialized (e.g. when it terminates because * of SIGTERM). This function currently only removes the PID file. **/ void g_process_finish(void) { g_process_remove_pidfile(); } static gboolean g_process_process_mode_arg(const gchar *option_name G_GNUC_UNUSED, const gchar *value, gpointer data G_GNUC_UNUSED, GError **error) { if (strcmp(value, "foreground") == 0) { process_opts.mode = G_PM_FOREGROUND; } else if (strcmp(value, "background") == 0) { process_opts.mode = G_PM_BACKGROUND; } else if (strcmp(value, "safe-background") == 0) { process_opts.mode = G_PM_SAFE_BACKGROUND; } else { g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Error parsing process-mode argument"); return FALSE; } return TRUE; } static GOptionEntry g_process_option_entries[] = { { "foreground", 'F', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.mode, "Do not go into the background after initialization", NULL }, { "process-mode", 0, 0, G_OPTION_ARG_CALLBACK, g_process_process_mode_arg , "Set process running mode", "<foreground|background|safe-background>" }, { "user", 'u', 0, G_OPTION_ARG_STRING, &process_opts.user, "Set the user to run as", "<user>" }, { "uid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.user, NULL, NULL }, { "group", 'g', 0, G_OPTION_ARG_STRING, &process_opts.group, "Set the group to run as", "<group>" }, { "gid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.group, NULL, NULL }, { "chroot", 'C', 0, G_OPTION_ARG_STRING, &process_opts.chroot_dir, "Chroot to this directory", "<dir>" }, { "caps", 0, 0, G_OPTION_ARG_STRING, &process_opts.caps, "Set default capability set", "<capspec>" }, { "no-caps", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.caps, "Disable managing Linux capabilities", NULL }, { "pidfile", 'p', 0, G_OPTION_ARG_STRING, &process_opts.pidfile, "Set path to pid file", "<pidfile>" }, { "enable-core", 0, 0, G_OPTION_ARG_NONE, &process_opts.core, "Enable dumping core files", NULL }, { "fd-limit", 0, 0, G_OPTION_ARG_INT, &process_opts.fd_limit_min, "The minimum required number of fds", NULL }, { NULL, 0, 0, 0, NULL, NULL, NULL }, }; void g_process_add_option_group(GOptionContext *ctx) { GOptionGroup *group; group = g_option_group_new("process", "Process options", "Process options", NULL, NULL); g_option_group_add_entries(group, g_process_option_entries); g_option_context_add_group(ctx, group); }
ystk/debian-syslog-ng
src/gprocess.c
C
gpl-2.0
37,305
<div id="forum_points_options"> <fieldset> <legend>{{ lang('FORUM_POINT_SETTINGS') }}</legend> <p>{{ lang('FORUM_POINT_SETTINGS_EXPLAIN') }}</p> <dl> <dt><label>{{ lang('FORUM_PERTOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PERTOPIC_EXPLAIN') }}</span> </dt> <dd><input type="text" id="forum_pertopic" maxlength="6" size="5" name="forum_pertopic" value="{{ FORUM_PERTOPIC }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_PERPOST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PERPOST_EXPLAIN') }}</span> </dt> <dd><input type="text" id="forum_perpost" maxlength="6" size="5" name="forum_perpost" value="{{ FORUM_PERPOST }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_PEREDIT') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PEREDIT_EXPLAIN') }}</span> </dt> <dd><input type="text" id="forum_peredit" maxlength="6" size="5" name="forum_peredit" value="{{ FORUM_PEREDIT }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_EXPLAIN') }}</span></dt> <dd><input type="text" id="forum_cost" maxlength="6" size="5" name="forum_cost" value="{{ FORUM_COST }}"/> </dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST_TOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_TOPIC_EXPLAIN') }}</span> </dt> <dd><input type="text" id="forum_cost_topic" maxlength="6" size="5" name="forum_cost_topic" value="{{ FORUM_COST_TOPIC }}"/></dd> </dl> <dl> <dt><label>{{ lang('FORUM_COST_POST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_POST_EXPLAIN') }}</span> </dt> <dd><input type="text" id="forum_cost_post" maxlength="6" size="5" name="forum_cost_post" value="{{ FORUM_COST_POST }}"/></dd> </dl> </fieldset> </div>
dmzx/Ultimate-Points-Extension
adm/style/event/acp_forums_normal_settings_prepend.html
HTML
gpl-2.0
1,838
# -*- coding: utf-8 -*- """ Created on Tue May 28 12:20:59 2013 === MAYAXES (v1.1) === Generates a set of MayaVI axes using the mayavi.mlab.axes() object with a white background, small black text and a centred title. Designed to better mimic MATLAB style plots. Unspecified arguments will be set to default values when mayaxes is called (note that default settings are configured for a figure measuring 1024 x 768 pixels and may not display correctly on plots that are significantly larger or smaller). === Inputs === 'title' Figure title text (default = 'VOID') 'xlabel' X axis label text (default = 'X') 'ylabel' Y axis label text (default = 'Y') 'zlabel' Z axis label text (default = 'Z') 'handle' Graphics handle of object (if bounding box is to be plotted) 'title_size' Font size of the title text (default = 25) 'ticks' Number of divisions on each axis (default = 7) 'font_scaling' Font scaling factor for axis text (default = 0.7) 'background' Background colour (can be 'b' (black) or 'w' (white)) === Notes === Disbaling figure title: specify title_string='void' OR title_string='Void' OR title_string='VOID' to disable figure title. Disabling bounding box: specify handle='void' OR handle='Void' OR handle='VOID' to disable figure bounding box. === Usage === from mayaxes import mayaxes mayaxes('Figure title','X axis label','Y axis label','Z axis label') OR mayaxes(title_string='TITLE',xlabel='X',ylabel='Y',zlabel='Z',title_size=25,ticks=7,font_scaling=0.7) === Example === from mayaxes import test_mayaxes test_mayaxes() @author: Nathan Donaldson """ def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \ title_size=25, ticks=7, font_scaling=0.7, background='w'): if type(title_string) != str or type(xlabel) != str or type(ylabel) != str or type(zlabel) != str: print('ERROR: label inputs must all be strings') return elif type(ticks) != int: print('ERROR: number of ticks must be an integer') return elif type(font_scaling) != float and type(font_scaling) != int: print('Error: font scaling factor must be an integer or a float') return from mayavi.mlab import axes,title,gcf,outline # Create axes object ax = axes() # Font factor globally adjusts figure text size ax.axes.font_factor = font_scaling # Number of ticks along each axis ax.axes.number_of_labels = ticks # Set axis labels to input strings # (spaces are included for padding so that labels do not intersect with axes) if xlabel=='void' or xlabel=='Void' or xlabel=='VOID': print 'X axis label title disabled' else: ax.axes.x_label = ' ' + xlabel if ylabel=='void' or ylabel=='Void' or ylabel=='VOID': print 'Y axis label disabled' else: ax.axes.y_label = ylabel + ' ' if zlabel=='void' or zlabel=='Void' or zlabel=='VOID': print 'Z axis label disabled' else: ax.axes.z_label = zlabel + ' ' # Create figure title if title_string=='void' or title_string=='Void' or title_string=='VOID': print 'Figure title disabled' else: text_title = title(title_string) text_title.x_position = 0.5 text_title.y_position = 0.9 text_title.property.color = (0.0, 0.0, 0.0) text_title.actor.text_scale_mode = 'none' text_title.property.font_size = title_size text_title.property.justification = 'centered' # Create bounding box if handle=='void' or handle=='Void' or handle=='VOID': print 'Bounding box disabled' else: if background == 'w': bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2) elif background == 'b': bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2) # Set axis, labels and titles to neat black text #ax.property.color = (0.0, 0.0, 0.0) #ax.title_text_property.color = (0.0, 0.0, 0.0) #ax.label_text_property.color = (0.0, 0.0, 0.0) ax.label_text_property.bold = False ax.label_text_property.italic = False ax.title_text_property.italic = False ax.title_text_property.bold = False # Reset axis range ax.axes.use_ranges = True # Set scene background, axis and text colours fig = gcf() if background == 'w': fig.scene.background = (1.0, 1.0, 1.0) ax.label_text_property.color = (0.0, 0.0, 0.0) ax.property.color = (0.0, 0.0, 0.0) ax.title_text_property.color = (0.0, 0.0, 0.0) elif background == 'b': fig.scene.background = (0.0, 0.0, 0.0) ax.label_text_property.color = (1.0, 1.0, 1.0) ax.property.color = (1.0, 1.0, 1.0) ax.title_text_property.color = (1.0, 1.0, 1.0) fig.scene.parallel_projection = True def test_mayaxes(): from mayaxes import mayaxes from scipy import sqrt,sin,meshgrid,linspace,pi import mayavi.mlab as mlab resolution = 200 lambda_var = 3 theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution) x, y = meshgrid(theta, theta) r = sqrt(x**2 + y**2) z = sin(r)/r fig = mlab.figure(size=(1024,768)) surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto') mayaxes(title_string='Figure 1: Diminishing polar cosine series', \ xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf) fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287] fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856] fig.scene.camera.view_angle = 30.0 fig.scene.camera.view_up = [0.0, 0.0, 1.0] fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255] fig.scene.camera.compute_view_plane_normal() fig.scene.render() mlab.show()
Nate28/mayaxes
mayaxes.py
Python
gpl-2.0
6,007
/* This file is a part of the Depecher (Telegram client) Copyright (C) 2017 Alexandr Akulich <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <QGuiApplication> #include <QQuickView> #include <sailfishapp.h> int main(int argc, char *argv[]) { QScopedPointer<QGuiApplication> application(SailfishApp::application(argc, argv)); application->setApplicationName(QStringLiteral("depecher")); application->setApplicationDisplayName(QStringLiteral("Depecher")); QScopedPointer<QQuickView> view(SailfishApp::createView()); view->setSource(SailfishApp::pathTo(QStringLiteral("qml/main.qml"))); view->setTitle(application->applicationDisplayName()); view->setResizeMode(QQuickView::SizeRootObjectToView); view->show(); return application->exec(); }
depecher/depecher
main.cpp
C++
gpl-2.0
1,505
<?php /** * @version 1.0.0 * @package com_farmapp * @copyright Copyright (C) 2012. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * @author Created by com_combuilder - http://www.notwebdesign.com */ // No direct access. defined('_JEXEC') or die; /** * Items list controller class. */ class CropsControllerFarmapp extends FarmappController { /** * Constructor. * * @param array $config An optional associative array of configuration settings. * @see JController * @since 1.6 */ public function __construct($config = array()) { parent::__construct($config); } function display() { $model=$this->getModel('crops'); $items=$model->getItems(); $pagination = $model->getPagination(); $state = $model->getState(); $view=$this->getView('crops','html'); $view->assign('items',$items); $view->assign('pagination',$pagination); $view->assign('state',$state); $view->display(); } function edit() { $id = JRequest::getVar('cid','0'); $model=$this->getModel('crop'); // get the Data $item = $model->getItem($id[0]); $form = $model->getForm($id[0]); $view=$this->getView('crop','html'); $view->assign('form',$form); $view->assign('item',$item); $view->setLayout('edit'); $view->display(); } /* * Method for save data from farm-form...... * */ function save() { $task = $this->getTask(); $data=JRequest::get('post'); $bed_ids = $data['bed_id']; $bed_id = implode(',',$bed_ids); $data['bed_id'] = $bed_id; $model=$this->getModel('crop'); $id=$model->save($data); if($id!=='') { switch ( $task ) { case 'save2new': $link = 'index.php?option=com_farmapp&view=crops&task=add'; $this->setRedirect($link, $msg); break; case 'save': $msg = JText::_( 'Crop save successfully' ); $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); break; case 'apply': $msg = JText::_( 'Crop save successfully' ); $link = 'index.php?option=com_farmapp&view=crops&task=edit&cid[]='.$id; $this->setRedirect($link, $msg); break; } } } /* * Method for deleting single/multiple crops...... * */ function delete() { $model = $this->getModel('crops'); if(!$model->delete()) { $msg = JText::_( 'Error: One or More crop Could not be Deleted' ); }else{ $msg = JText::_( 'crop(s) Deleted' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /* * Method for publish single/multiple farms...... * */ function multiplepublish() { $model = $this->getModel('crops'); if(!$model->multiplepublish()) { $msg = JText::_( 'Error: One or More crops Could not be published' ); } else { $msg = JText::_( 'crop(s) Published.' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /* * Method for unpublish single/multiple farms...... * */ function multipleunpublish() { $model = $this->getModel('crops'); if(!$model->multipleunpublish()){ $msg = JText::_( 'Error: One or More crop Could not be unpublished' ); }else{ $msg = JText::_( 'crop(s) UnPublished.' ); } $link = 'index.php?option=com_farmapp&view=crops'; $this->setRedirect($link, $msg); } /*method single row publish and unpublish on click on tick mark*/ function publish(){ // Initialise variables. $ids = JRequest::getVar('cid', array(), '', 'array'); $values = array('publish' => 1, 'unpublish' => 0); $task = $this->getTask(); $value = JArrayHelper::getValue($values, $task, 0, 'int'); if (empty($ids)) { JError::raiseWarning(500, JText::_('JERROR_NO_ITEMS_SELECTED')); } else { // Get the model. $model = $this->getModel('crops'); // Publish the items. if (!$model->publish($ids, $value)) { JError::raiseWarning(500, $model->getError()); } } $this->setRedirect('index.php?option=com_farmapp&view=crops'); } /* * * Method to get the beds according to the farm/zones........ */ function findbeds() { $model=$this->getModel('crops'); $farmzoneid = JRequest::getVar('val'); $cropid = JRequest::getVar('cropid'); $bedslist = $model->getbedslist($farmzoneid, $cropid); echo $bedslist; } }
yogendra9891/farmapplication
administrator/components/com_farmapp/controllers/crops.php
PHP
gpl-2.0
4,429
<?php namespace Drupal\search_api_autocomplete\Suggestion; use Drupal\Core\Render\RenderableInterface; /** * Defines a single autocompletion suggestion. */ interface SuggestionInterface extends RenderableInterface { /** * Retrieves the keywords this suggestion will autocomplete to. * * @return string|null * The suggested keywords, or NULL if the suggestion should direct to a URL * instead. */ public function getSuggestedKeys(); /** * Retrieves the URL to which the suggestion should redirect. * * A URL to which the suggestion should redirect instead of completing the * user input in the text field. This overrides the normal behavior and thus * makes the suggested keys obsolete. * * @return \Drupal\Core\Url|null * The URL to which the suggestion should redirect to, or NULL if none was * set. */ public function getUrl(); /** * Retrieves the prefix for the suggestion. * * For special kinds of suggestions, this will contain some kind of prefix * describing them. * * @return string|null * The prefix, if set. */ public function getPrefix(); /** * Retrieves the label to use for the suggestion. * * Should only be used if the other fields that will be displayed (suggestion * prefix/suffix and user input) are empty. * * @return string * The suggestion's label. */ public function getLabel(); /** * Retrieves the prefix suggested for the entered keys. * * @return string|null * The suggested prefix, if any. */ public function getSuggestionPrefix(); /** * The input entered by the user, if it should be included in the label. * * @return string|null * The input provided by the user. */ public function getUserInput(); /** * A suggested suffix for the entered input. * * @return string|null * A suffix. */ public function getSuggestionSuffix(); /** * Returns the estimated number of results for this suggestion. * * @return int|null * The estimated number of results, or NULL if no estimate is available. */ public function getResultsCount(); /** * Returns the render array set for this suggestion. * * This should be displayed to the user for this suggestion. If missing, the * suggestion is instead rendered with the * "search_api_autocomplete_suggestion" theme. * * @return array|null * A renderable array of the suggestion results, or NULL if none was set. */ public function getRender(); /** * Sets the keys. * * @param string|null $keys * The keys. * * @return $this */ public function setSuggestedKeys($keys); /** * Sets the URL. * * @param \Drupal\Core\Url|null $url * The URL. * * @return $this */ public function setUrl($url); /** * Sets the prefix. * * @param string|null $prefix * The prefix. * * @return $this */ public function setPrefix($prefix); /** * Sets the label. * * @param string|null $label * The new label. * * @return $this */ public function setLabel($label); /** * Sets the suggestion prefix. * * @param string|null $suggestion_prefix * The suggestion prefix. * * @return $this */ public function setSuggestionPrefix($suggestion_prefix); /** * Sets the user input. * * @param string|null $user_input * The user input. * * @return $this */ public function setUserInput($user_input); /** * Sets the suggestion suffix. * * @param string|null $suggestion_suffix * The suggestion suffix. * * @return $this */ public function setSuggestionSuffix($suggestion_suffix); /** * Sets the result count. * * @param string|null $results * The result count. * * @return $this */ public function setResultsCount($results); /** * Sets the render array. * * @param array|null $render * The render array. * * @return $this */ public function setRender($render); }
NickGH/agronomia
web/modules/contrib/search_api_autocomplete/src/Suggestion/SuggestionInterface.php
PHP
gpl-2.0
4,087
/* * PROJECT: Boot Loader * LICENSE: BSD - See COPYING.ARM in the top level directory * FILE: boot/armllb/hw/versatile/hwclcd.c * PURPOSE: LLB CLCD Routines for Versatile * PROGRAMMERS: ReactOS Portable Systems Group */ #include "precomp.h" #define LCDTIMING0_PPL(x) ((((x) / 16 - 1) & 0x3f) << 2) #define LCDTIMING1_LPP(x) (((x) & 0x3ff) - 1) #define LCDCONTROL_LCDPWR (1 << 11) #define LCDCONTROL_LCDEN (1) #define LCDCONTROL_LCDBPP(x) (((x) & 7) << 1) #define LCDCONTROL_LCDTFT (1 << 5) #define PL110_LCDTIMING0 (PVOID)0x10120000 #define PL110_LCDTIMING1 (PVOID)0x10120004 #define PL110_LCDTIMING2 (PVOID)0x10120008 #define PL110_LCDUPBASE (PVOID)0x10120010 #define PL110_LCDLPBASE (PVOID)0x10120014 #define PL110_LCDCONTROL (PVOID)0x10120018 PUSHORT LlbHwVideoBuffer; VOID NTAPI LlbHwVersaClcdInitialize(VOID) { /* Set framebuffer address */ WRITE_REGISTER_ULONG(PL110_LCDUPBASE, (ULONG)LlbHwGetFrameBuffer()); WRITE_REGISTER_ULONG(PL110_LCDLPBASE, (ULONG)LlbHwGetFrameBuffer()); /* Initialize timings to 720x400 */ WRITE_REGISTER_ULONG(PL110_LCDTIMING0, LCDTIMING0_PPL(LlbHwGetScreenWidth())); WRITE_REGISTER_ULONG(PL110_LCDTIMING1, LCDTIMING1_LPP(LlbHwGetScreenHeight())); /* Enable the TFT/LCD Display */ WRITE_REGISTER_ULONG(PL110_LCDCONTROL, LCDCONTROL_LCDEN | LCDCONTROL_LCDTFT | LCDCONTROL_LCDPWR | LCDCONTROL_LCDBPP(4)); } ULONG NTAPI LlbHwGetScreenWidth(VOID) { return 720; } ULONG NTAPI LlbHwGetScreenHeight(VOID) { return 400; } PVOID NTAPI LlbHwGetFrameBuffer(VOID) { return (PVOID)0x000A0000; } ULONG NTAPI LlbHwVideoCreateColor(IN ULONG Red, IN ULONG Green, IN ULONG Blue) { return (((Blue >> 3) << 11)| ((Green >> 2) << 5)| ((Red >> 3) << 0)); } /* EOF */
GreenteaOS/Kernel
third-party/reactos/boot/armllb/hw/versatile/hwclcd.c
C
gpl-2.0
1,933
<?php /** * @package FrameworkOnFramework * @subpackage database * @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt * * This file is adapted from the Joomla! Platform. It is used to iterate a database cursor returning FOFTable objects * instead of plain stdClass objects */ // Protect from unauthorized access defined('FOF_INCLUDED') or die; /** * Query Building Class. * * @package Joomla.Platform * @subpackage Database * @since 3.4 */ class FOFDatabaseQueryPdomysql extends FOFDatabaseQueryMysqli { }
alessandrorusso/Furia
libraries/fof/database/query/pdomysql.php
PHP
gpl-2.0
687
/* * Copyright (C) 2011 ST-Ericsson SA. * Copyright (C) 2009 Motorola, Inc. * * License Terms: GNU General Public License v2 * * Simple driver for National Semiconductor LM3530 Backlight driver chip * * Author: Shreshtha Kumar SAHU <[email protected]> * based on leds-lm3530.c by Dan Murphy <[email protected]> */ #include <linux/i2c.h> #include <linux/leds.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/input.h> #include <linux/led-lm3530.h> #include <linux/types.h> #include <linux/regulator/consumer.h> #include <linux/module.h> #define LM3530_LED_DEV "lcd-backlight" #define LM3530_NAME "lm3530-led" #define LM3530_GEN_CONFIG 0x10 #define LM3530_ALS_CONFIG 0x20 #define LM3530_BRT_RAMP_RATE 0x30 #define LM3530_ALS_IMP_SELECT 0x41 #define LM3530_BRT_CTRL_REG 0xA0 #define LM3530_ALS_ZB0_REG 0x60 #define LM3530_ALS_ZB1_REG 0x61 #define LM3530_ALS_ZB2_REG 0x62 #define LM3530_ALS_ZB3_REG 0x63 #define LM3530_ALS_Z0T_REG 0x70 #define LM3530_ALS_Z1T_REG 0x71 #define LM3530_ALS_Z2T_REG 0x72 #define LM3530_ALS_Z3T_REG 0x73 #define LM3530_ALS_Z4T_REG 0x74 #define LM3530_REG_MAX 14 /* General Control Register */ #define LM3530_EN_I2C_SHIFT (0) #define LM3530_RAMP_LAW_SHIFT (1) #define LM3530_MAX_CURR_SHIFT (2) #define LM3530_EN_PWM_SHIFT (5) #define LM3530_PWM_POL_SHIFT (6) #define LM3530_EN_PWM_SIMPLE_SHIFT (7) #define LM3530_ENABLE_I2C (1 << LM3530_EN_I2C_SHIFT) #define LM3530_ENABLE_PWM (1 << LM3530_EN_PWM_SHIFT) #define LM3530_POL_LOW (1 << LM3530_PWM_POL_SHIFT) #define LM3530_ENABLE_PWM_SIMPLE (1 << LM3530_EN_PWM_SIMPLE_SHIFT) /* ALS Config Register Options */ #define LM3530_ALS_AVG_TIME_SHIFT (0) #define LM3530_EN_ALS_SHIFT (3) #define LM3530_ALS_SEL_SHIFT (5) #define LM3530_ENABLE_ALS (3 << LM3530_EN_ALS_SHIFT) /* Brightness Ramp Rate Register */ #define LM3530_BRT_RAMP_FALL_SHIFT (0) #define LM3530_BRT_RAMP_RISE_SHIFT (3) /* ALS Resistor Select */ #define LM3530_ALS1_IMP_SHIFT (0) #define LM3530_ALS2_IMP_SHIFT (4) /* Zone Boundary Register defaults */ #define LM3530_ALS_ZB_MAX (4) #define LM3530_ALS_WINDOW_mV (1000) #define LM3530_ALS_OFFSET_mV (4) /* Zone Target Register defaults */ #define LM3530_DEF_ZT_0 (0x7F) #define LM3530_DEF_ZT_1 (0x66) #define LM3530_DEF_ZT_2 (0x4C) #define LM3530_DEF_ZT_3 (0x33) #define LM3530_DEF_ZT_4 (0x19) /* 7 bits are used for the brightness : LM3530_BRT_CTRL_REG */ #define MAX_BRIGHTNESS (127) struct lm3530_mode_map { const char *mode; enum lm3530_mode mode_val; }; static struct lm3530_mode_map mode_map[] = { { "man", LM3530_BL_MODE_MANUAL }, { "als", LM3530_BL_MODE_ALS }, { "pwm", LM3530_BL_MODE_PWM }, }; /** * struct lm3530_data * @led_dev: led class device * @client: i2c client * @pdata: LM3530 platform data * @mode: mode of operation - manual, ALS, PWM * @regulator: regulator * @brighness: previous brightness value * @enable: regulator is enabled */ struct lm3530_data { struct led_classdev led_dev; struct i2c_client *client; struct lm3530_platform_data *pdata; enum lm3530_mode mode; struct regulator *regulator; enum led_brightness brightness; bool enable; }; static const u8 lm3530_reg[LM3530_REG_MAX] = { LM3530_GEN_CONFIG, LM3530_ALS_CONFIG, LM3530_BRT_RAMP_RATE, LM3530_ALS_IMP_SELECT, LM3530_BRT_CTRL_REG, LM3530_ALS_ZB0_REG, LM3530_ALS_ZB1_REG, LM3530_ALS_ZB2_REG, LM3530_ALS_ZB3_REG, LM3530_ALS_Z0T_REG, LM3530_ALS_Z1T_REG, LM3530_ALS_Z2T_REG, LM3530_ALS_Z3T_REG, LM3530_ALS_Z4T_REG, }; static int lm3530_get_mode_from_str(const char *str) { int i; for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (sysfs_streq(str, mode_map[i].mode)) return mode_map[i].mode_val; return -1; } static int lm3530_init_registers(struct lm3530_data *drvdata) { int ret = 0; int i; u8 gen_config; u8 als_config = 0; u8 brt_ramp; u8 als_imp_sel = 0; u8 brightness; u8 reg_val[LM3530_REG_MAX]; u8 zones[LM3530_ALS_ZB_MAX]; u32 als_vmin, als_vmax, als_vstep; struct lm3530_platform_data *pdata = drvdata->pdata; struct i2c_client *client = drvdata->client; struct lm3530_pwm_data *pwm = &pdata->pwm_data; gen_config = (pdata->brt_ramp_law << LM3530_RAMP_LAW_SHIFT) | ((pdata->max_current & 7) << LM3530_MAX_CURR_SHIFT); switch (drvdata->mode) { case LM3530_BL_MODE_MANUAL: case LM3530_BL_MODE_ALS: gen_config |= LM3530_ENABLE_I2C; break; case LM3530_BL_MODE_PWM: gen_config |= LM3530_ENABLE_PWM | LM3530_ENABLE_PWM_SIMPLE | (pdata->pwm_pol_hi << LM3530_PWM_POL_SHIFT); break; } if (drvdata->mode == LM3530_BL_MODE_ALS) { if (pdata->als_vmax == 0) { pdata->als_vmin = 0; pdata->als_vmax = LM3530_ALS_WINDOW_mV; } als_vmin = pdata->als_vmin; als_vmax = pdata->als_vmax; if ((als_vmax - als_vmin) > LM3530_ALS_WINDOW_mV) pdata->als_vmax = als_vmax = als_vmin + LM3530_ALS_WINDOW_mV; /* n zone boundary makes n+1 zones */ als_vstep = (als_vmax - als_vmin) / (LM3530_ALS_ZB_MAX + 1); for (i = 0; i < LM3530_ALS_ZB_MAX; i++) zones[i] = (((als_vmin + LM3530_ALS_OFFSET_mV) + als_vstep + (i * als_vstep)) * LED_FULL) / 1000; als_config = (pdata->als_avrg_time << LM3530_ALS_AVG_TIME_SHIFT) | (LM3530_ENABLE_ALS) | (pdata->als_input_mode << LM3530_ALS_SEL_SHIFT); als_imp_sel = (pdata->als1_resistor_sel << LM3530_ALS1_IMP_SHIFT) | (pdata->als2_resistor_sel << LM3530_ALS2_IMP_SHIFT); } brt_ramp = (pdata->brt_ramp_fall << LM3530_BRT_RAMP_FALL_SHIFT) | (pdata->brt_ramp_rise << LM3530_BRT_RAMP_RISE_SHIFT); if (drvdata->brightness) brightness = drvdata->brightness; else brightness = drvdata->brightness = pdata->brt_val; if (brightness > drvdata->led_dev.max_brightness) brightness = drvdata->led_dev.max_brightness; reg_val[0] = gen_config; /* LM3530_GEN_CONFIG */ reg_val[1] = als_config; /* LM3530_ALS_CONFIG */ reg_val[2] = brt_ramp; /* LM3530_BRT_RAMP_RATE */ reg_val[3] = als_imp_sel; /* LM3530_ALS_IMP_SELECT */ reg_val[4] = brightness; /* LM3530_BRT_CTRL_REG */ reg_val[5] = zones[0]; /* LM3530_ALS_ZB0_REG */ reg_val[6] = zones[1]; /* LM3530_ALS_ZB1_REG */ reg_val[7] = zones[2]; /* LM3530_ALS_ZB2_REG */ reg_val[8] = zones[3]; /* LM3530_ALS_ZB3_REG */ reg_val[9] = LM3530_DEF_ZT_0; /* LM3530_ALS_Z0T_REG */ reg_val[10] = LM3530_DEF_ZT_1; /* LM3530_ALS_Z1T_REG */ reg_val[11] = LM3530_DEF_ZT_2; /* LM3530_ALS_Z2T_REG */ reg_val[12] = LM3530_DEF_ZT_3; /* LM3530_ALS_Z3T_REG */ reg_val[13] = LM3530_DEF_ZT_4; /* LM3530_ALS_Z4T_REG */ if (!drvdata->enable) { ret = regulator_enable(drvdata->regulator); if (ret) { dev_err(&drvdata->client->dev, "Enable regulator failed\n"); return ret; } drvdata->enable = true; } for (i = 0; i < LM3530_REG_MAX; i++) { /* do not update brightness register when pwm mode */ if (lm3530_reg[i] == LM3530_BRT_CTRL_REG && drvdata->mode == LM3530_BL_MODE_PWM) { if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(reg_val[i], drvdata->led_dev.max_brightness); continue; } ret = i2c_smbus_write_byte_data(client, lm3530_reg[i], reg_val[i]); if (ret) break; } return ret; } static void lm3530_brightness_set(struct led_classdev *led_cdev, enum led_brightness brt_val) { int err; struct lm3530_data *drvdata = container_of(led_cdev, struct lm3530_data, led_dev); struct lm3530_platform_data *pdata = drvdata->pdata; struct lm3530_pwm_data *pwm = &pdata->pwm_data; u8 max_brightness = led_cdev->max_brightness; switch (drvdata->mode) { case LM3530_BL_MODE_MANUAL: if (!drvdata->enable) { err = lm3530_init_registers(drvdata); if (err) { dev_err(&drvdata->client->dev, "Register Init failed: %d\n", err); break; } } /* set the brightness in brightness control register*/ err = i2c_smbus_write_byte_data(drvdata->client, LM3530_BRT_CTRL_REG, brt_val); if (err) dev_err(&drvdata->client->dev, "Unable to set brightness: %d\n", err); else drvdata->brightness = brt_val; if (brt_val == 0) { err = regulator_disable(drvdata->regulator); if (err) dev_err(&drvdata->client->dev, "Disable regulator failed\n"); drvdata->enable = false; } break; case LM3530_BL_MODE_ALS: break; case LM3530_BL_MODE_PWM: if (pwm->pwm_set_intensity) pwm->pwm_set_intensity(brt_val, max_brightness); break; default: break; } } static ssize_t lm3530_mode_get(struct device *dev, struct device_attribute *attr, char *buf) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; int i, len = 0; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); for (i = 0; i < ARRAY_SIZE(mode_map); i++) if (drvdata->mode == mode_map[i].mode_val) len += sprintf(buf + len, "[%s] ", mode_map[i].mode); else len += sprintf(buf + len, "%s ", mode_map[i].mode); len += sprintf(buf + len, "\n"); return len; } static ssize_t lm3530_mode_set(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct led_classdev *led_cdev = dev_get_drvdata(dev); struct lm3530_data *drvdata; struct lm3530_pwm_data *pwm; u8 max_brightness; int mode, err; drvdata = container_of(led_cdev, struct lm3530_data, led_dev); pwm = &drvdata->pdata->pwm_data; max_brightness = led_cdev->max_brightness; mode = lm3530_get_mode_from_str(buf); if (mode < 0) { dev_err(dev, "Invalid mode\n"); return -EINVAL; } drvdata->mode = mode; /* set pwm to low if unnecessary */ if (mode != LM3530_BL_MODE_PWM && pwm->pwm_set_intensity) pwm->pwm_set_intensity(0, max_brightness); err = lm3530_init_registers(drvdata); if (err) { dev_err(dev, "Setting %s Mode failed :%d\n", buf, err); return err; } return sizeof(drvdata->mode); } static DEVICE_ATTR(mode, 0644, lm3530_mode_get, lm3530_mode_set); static int __devinit lm3530_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct lm3530_platform_data *pdata = client->dev.platform_data; struct lm3530_data *drvdata; int err = 0; if (pdata == NULL) { dev_err(&client->dev, "platform data required\n"); err = -ENODEV; goto err_out; } /* BL mode */ if (pdata->mode > LM3530_BL_MODE_PWM) { dev_err(&client->dev, "Illegal Mode request\n"); err = -EINVAL; goto err_out; } if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { dev_err(&client->dev, "I2C_FUNC_I2C not supported\n"); err = -EIO; goto err_out; } drvdata = kzalloc(sizeof(struct lm3530_data), GFP_KERNEL); if (drvdata == NULL) { err = -ENOMEM; goto err_out; } drvdata->mode = pdata->mode; drvdata->client = client; drvdata->pdata = pdata; drvdata->brightness = LED_OFF; drvdata->enable = false; drvdata->led_dev.name = LM3530_LED_DEV; drvdata->led_dev.brightness_set = lm3530_brightness_set; drvdata->led_dev.max_brightness = MAX_BRIGHTNESS; i2c_set_clientdata(client, drvdata); drvdata->regulator = regulator_get(&client->dev, "vin"); if (IS_ERR(drvdata->regulator)) { dev_err(&client->dev, "regulator get failed\n"); err = PTR_ERR(drvdata->regulator); drvdata->regulator = NULL; goto err_regulator_get; } if (drvdata->pdata->brt_val) { err = lm3530_init_registers(drvdata); if (err < 0) { dev_err(&client->dev, "Register Init failed: %d\n", err); err = -ENODEV; goto err_reg_init; } } err = led_classdev_register(&client->dev, &drvdata->led_dev); if (err < 0) { dev_err(&client->dev, "Register led class failed: %d\n", err); err = -ENODEV; goto err_class_register; } err = device_create_file(drvdata->led_dev.dev, &dev_attr_mode); if (err < 0) { dev_err(&client->dev, "File device creation failed: %d\n", err); err = -ENODEV; goto err_create_file; } return 0; err_create_file: led_classdev_unregister(&drvdata->led_dev); err_class_register: err_reg_init: regulator_put(drvdata->regulator); err_regulator_get: kfree(drvdata); err_out: return err; } static int __devexit lm3530_remove(struct i2c_client *client) { struct lm3530_data *drvdata = i2c_get_clientdata(client); device_remove_file(drvdata->led_dev.dev, &dev_attr_mode); if (drvdata->enable) regulator_disable(drvdata->regulator); regulator_put(drvdata->regulator); led_classdev_unregister(&drvdata->led_dev); kfree(drvdata); return 0; } static const struct i2c_device_id lm3530_id[] = { {LM3530_NAME, 0}, {} }; MODULE_DEVICE_TABLE(i2c, lm3530_id); static struct i2c_driver lm3530_i2c_driver = { .probe = lm3530_probe, .remove = __devexit_p(lm3530_remove), .id_table = lm3530_id, .driver = { .name = LM3530_NAME, .owner = THIS_MODULE, }, }; module_i2c_driver(lm3530_i2c_driver); MODULE_DESCRIPTION("Back Light driver for LM3530"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Shreshtha Kumar SAHU <[email protected]>");
Jackeagle/android_kernel_sony_c2305
drivers/leds/leds-lm3530.c
C
gpl-2.0
13,280
package sergio; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Calendar; import java.util.GregorianCalendar; //Ejercicio Metodos 18 //Realiza una clase llamada milibreria que contenga al menos cinco de los metodos realizados. //Usalas de 3 formas diferentes //Autor: Sergio Tobal //Fecha: 12-02-2012 public class EjerMetods18 { /** * @param args * @throws IOException * @throws NumberFormatException */ public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in)); int numsend=10,edad; char nombre; boolean nombreceive; String msgname = null; System.out.println("Dame tu inicial:"); nombre=lectura.readLine().charAt(0); nombreceive=EsMayus(nombre); if (nombreceive==true) { msgname="MAYUSCULAS"; } else if (nombreceive==false) { msgname="minusculas"; } EsPerfecto(numsend); System.out.println("Tu primer numero perfecto es "+numsend+" porque tienes "+(edad=ObtenerEdad())+" años, y tu inicial esta escrita en "+msgname); } private static boolean EsPerfecto(int numsend) { int perfect=0; for (int i = 1; i < numsend; i++) { if (numsend % i == 0) { perfect += i; } } if (perfect == numsend) { return true; }else { return false; } } private static int ObtenerEdad()throws NumberFormatException, IOException{ BufferedReader lectura = new BufferedReader(new InputStreamReader(System.in)); int year,month,day; System.out.println("Dime tu dia de nacimiento: "); day=Integer.parseInt(lectura.readLine()); System.out.println("Dime tu mes de nacimiento: "); month=Integer.parseInt(lectura.readLine()); System.out.println("Dime tu año de nacimiento: "); year=Integer.parseInt(lectura.readLine()); Calendar cal = new GregorianCalendar(year, month, day); Calendar now = new GregorianCalendar(); int edad = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR); if ((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH)) || (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH) && cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH))) { edad--; } return edad; } private static int Factorial(int num) { int factorial=1; // Va multiplicando el numero del usuario por 1 hasta que el numero llega ha cero y retorna // la multiplicacion de todos los numeros while (num!=0) { factorial=factorial*num; num--; } return factorial; } private static boolean ValFecha(int day, int month) { if ((day>=1 && day<=31) && (month>=1 && month<=12)) { return true; }else { return false; } } private static boolean EsMayus(char nombre) { boolean opt=true; // La funcion isUpperCase comprueba que el contenido de num sea mayuscula if (Character.isUpperCase(nombre) == true) { opt=true; // La funcion isLowerCase comprueba que el contenido de num sea minuscula } else if(Character.isLowerCase(nombre) == true){ opt=false; } return opt; } }
set92/Small-Programs
Java/CFGS/Interfaces-Ejercicios/Ejercicios propuestos de metodos/sergio/EjerMetods18.java
Java
gpl-2.0
3,147
@import judgels.fs.FileInfo @import org.iatoki.judgels.sandalphon.problem.programming.grading.blackbox.BatchGradingConfigForm @import play.api.mvc.Call @(batchGradingConfigForm: Form[BatchGradingConfigForm], postUpdateGradingConfigCall: Call, testDataFiles: List[FileInfo], helperFiles: List[FileInfo]) @implicitFieldConstructor = @{ b3.horizontal.fieldConstructor("col-md-3", "col-md-9") } <script type="text/javascript" src="@controllers.routes.Assets.at("lib/jquery/jquery.min.js")"></script> <script type="text/javascript"> $(document).ready(function() { var sampleTestCaseTemplate = $('#sample-test-case-template'); var sampleTestDataContainer = $('#sample-test-data'); var sampleTestData = { container: sampleTestDataContainer, newSampleTestCase: { inSelect: sampleTestDataContainer.find('select').first(), outSelect: sampleTestDataContainer.find('select').last(), addButton: sampleTestDataContainer.find('a').last() }, sampleTestCases: [] }; var testCaseTemplate = $('#test-case-template'); var testDataContainer = $('#test-data'); var testData = { container: testDataContainer, newTestCase: { inSelect: testDataContainer.find('select').first(), outSelect: testDataContainer.find('select').last(), addButton: testDataContainer.find('a').last() }, testCases: [] }; function addNewSampleTestCase(inputVal, outputVal) { if (!inputVal || !outputVal) { alert("You don't have any test data files"); return; } var container = sampleTestCaseTemplate.clone().removeAttr('id'); var inInput = container.find('input').first(); var outInput = container.find('input').last(); var removeButton = container.find('a').last(); var caseNo = sampleTestData.sampleTestCases.length; // Update input values inInput .prop('name', 'sampleTestCaseInputs[' + caseNo + ']') .val(inputVal); outInput .prop('name', 'sampleTestCaseOutputs[' + caseNo + ']') .val(outputVal); // Update remove test case button removeButton.on('click', function() { removeSampleTestCase(caseNo); return false; }); var sampleTestCase = { container: container, inInput: inInput, outInput: outInput, removeButton: removeButton }; sampleTestData.sampleTestCases.push(sampleTestCase); // Append this sample test case container.insertBefore(sampleTestData.container.find('tr').last()); refreshSampleTestData(); container.show(); } function removeSampleTestCase(caseNo) { sampleTestData.sampleTestCases[caseNo].container.remove(); sampleTestData.sampleTestCases.splice(caseNo, 1); refreshSampleTestData(); } function refreshSampleTestData() { var sampleTestCasesCount = sampleTestData.sampleTestCases.length; for (var caseNo = 0; caseNo < sampleTestCasesCount; caseNo++) { var sampleTestCase = sampleTestData.sampleTestCases[caseNo]; sampleTestCase.inInput.prop('name', 'sampleTestCaseInputs[' + caseNo + ']'); sampleTestCase.outInput.prop('name', 'sampleTestCaseOutputs[' + caseNo + ']'); (function(caseNo) { sampleTestCase.removeButton.off('click').on('click', function() { removeSampleTestCase(caseNo); return false ; }); })(caseNo); } } function addNewTestCase(inputVal, outputVal) { if (!inputVal || !outputVal) { alert("You don't have any test data files"); return; } var container = testCaseTemplate.clone().removeAttr('id'); var inInput = container.find('input').first(); var outInput = container.find('input').last(); var removeButton = container.find('a').last(); var caseNo = testData.testCases.length; // Update input values inInput .prop('name', 'testCaseInputs[0][' + caseNo + ']') .val(inputVal); outInput .prop('name', 'testCaseOutputs[0][' + caseNo + ']') .val(outputVal); // Update remove test case button removeButton.on('click', function() { removeTestCase(caseNo); return false; }); var testCase = { container: container, inInput: inInput, outInput: outInput, removeButton: removeButton }; testData.testCases.push(testCase); // Append this test case container.insertBefore(testData.container.find('tr').last()); refreshTestData(); container.show(); } function removeTestCase(caseNo) { testData.testCases[caseNo].container.remove(); testData.testCases.splice(caseNo, 1); refreshTestData(); } function refreshTestData() { var testCasesCount = testData.testCases.length; for (var caseNo = 0; caseNo < testCasesCount; caseNo++) { var testCase = testData.testCases[caseNo]; testCase.inInput.prop('name', 'testCaseInputs[0][' + caseNo + ']'); testCase.outInput.prop('name', 'testCaseOutputs[0][' + caseNo + ']'); (function(caseNo) { testCase.removeButton.off('click').on('click', function() { removeTestCase(caseNo) ; return false ; }); })(caseNo); } } sampleTestData.newSampleTestCase.addButton.on('click', function() { addNewSampleTestCase(sampleTestData.newSampleTestCase.inSelect.val(), sampleTestData.newSampleTestCase.outSelect.val()); return false; }); testData.newTestCase.addButton.on('click', function() { addNewTestCase(testData.newTestCase.inSelect.val(), testData.newTestCase.outSelect.val()); return false; }); @for(i <- 0 until batchGradingConfigForm.get.sampleTestCaseInputs.size) { addNewSampleTestCase('@batchGradingConfigForm.get.sampleTestCaseInputs.get(i)', '@batchGradingConfigForm.get.sampleTestCaseOutputs.get(i)'); } @for(i <- 0 until batchGradingConfigForm.get.testCaseInputs.size) { @for(j <- 0 until batchGradingConfigForm.get.testCaseInputs.get(i).size) { addNewTestCase('@batchGradingConfigForm.get.testCaseInputs.get(i).get(j)', '@batchGradingConfigForm.get.testCaseOutputs.get(i).get(j)'); } } }); </script> @b3.form(postUpdateGradingConfigCall) { @helper.CSRF.formField @b3.inputWrapped("timeLimit", batchGradingConfigForm("timeLimit"), '_label -> "Time Limit") { input => <div class="input-group"> @input <div class="input-group-addon">milliseconds</div> </div> } @b3.inputWrapped("memoryLimit", batchGradingConfigForm("memoryLimit"), '_label -> "Memory Limit") { input => <div class="input-group"> @input <div class="input-group-addon">kilobytes</div> </div> } <div class="row" style="margin-bottom: 10px;"> <div class="col-md-3"> <label class="control-label">Sample Test Data</label> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-condensed"> <thead> <tr> <th>Sample Input</th> <th>Sample Output</th> <th></th> </tr> </thead> <tbody id="sample-test-data"> <tr id="sample-test-case-template" style="display: none"> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" /> </td> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" /> </td> <td class="text-center"> <a href="#"><span class="glyphicon glyphicon-remove"></span></a> </td> </tr> <tr class="active"> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td class="text-center"> <a href=""><span class="glyphicon glyphicon-plus"></span></a> </td> </tr> </tbody> </table> </div> </div> </div> </div> <div class="row" style="margin-bottom: 10px;"> <div class="col-md-3"> <label class="control-label">Test Data</label> </div> <div class="col-md-9"> <div class="panel panel-default"> <div class="panel-body"> <table class="table table-condensed"> <thead> <tr> <th>Input</th> <th>Output</th> <th></th> </tr> </thead> <tbody id="test-data"> <tr id="test-case-template" style="display: none"> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.in" /> </td> <td> <input class="form-control input-sm" type="text" readonly="readonly" value="file_0_0.out" /> </td> <td class="text-center"> <a href="#"><span class="glyphicon glyphicon-remove"></span></a> </td> </tr> <tr class="active"> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td> <select> @for(file <- testDataFiles) { <option value="@file.getName">@file.getName</option> } </select> </td> <td class="text-center"> <a href=""><span class="glyphicon glyphicon-plus"></span></a> </td> </tr> </tbody> </table> </div> </div> </div> </div> @b3.select(batchGradingConfigForm("customScorer"), helperFiles.map(f => f.getName -> f.getName).toSeq ++ Seq("(none)" -> "(None)"), '_label -> "Custom Scorer") @b3.submit('class -> "btn btn-primary") { Update } }
ia-toki/judgels
judgels-backends/sandalphon/sandalphon-app/app/org/iatoki/judgels/sandalphon/problem/programming/grading/blackbox/batchGradingConfigView.scala.html
HTML
gpl-2.0
12,567
#!/bin/sh # # Support routines for hand-crafting weird or malicious packs. # # You can make a complete pack like: # # pack_header 2 >foo.pack && # pack_obj e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 >>foo.pack && # pack_obj e68fe8129b546b101aee9510c5328e7f21ca1d18 >>foo.pack && # pack_trailer foo.pack # Print the big-endian 4-byte octal representation of $1 uint32_octal () { n=$1 printf '\%o' $(($n / 16777216)); n=$((n % 16777216)) printf '\%o' $(($n / 65536)); n=$((n % 65536)) printf '\%o' $(($n / 256)); n=$((n % 256)) printf '\%o' $(($n )); } # Print the big-endian 4-byte binary representation of $1 uint32_binary () { printf "$(uint32_octal "$1")" } # Print a pack header, version 2, for a pack with $1 objects pack_header () { printf 'PACK' && printf '\0\0\0\2' && uint32_binary "$1" } # Print the pack data for object $1, as a delta against object $2 (or as a full # object if $2 is missing or empty). The output is suitable for including # directly in the packfile, and represents the entirety of the object entry. # Doing this on the fly (especially picking your deltas) is quite tricky, so we # have hardcoded some well-known objects. See the case statements below for the # complete list. pack_obj () { case "$1" in # empty blob e69de29bb2d1d6434b8b29ae775ad8c2e48c5391) case "$2" in '') printf '\060\170\234\003\0\0\0\0\1' return ;; esac ;; # blob containing "\7\76" e68fe8129b546b101aee9510c5328e7f21ca1d18) case "$2" in '') printf '\062\170\234\143\267\3\0\0\116\0\106' return ;; 01d7713666f4de822776c7622c10f1b07de280dc) printf '\165\1\327\161\66\146\364\336\202\47\166' && printf '\307\142\54\20\361\260\175\342\200\334\170' && printf '\234\143\142\142\142\267\003\0\0\151\0\114' return ;; esac ;; # blob containing "\7\0" 01d7713666f4de822776c7622c10f1b07de280dc) case "$2" in '') printf '\062\170\234\143\147\0\0\0\20\0\10' return ;; e68fe8129b546b101aee9510c5328e7f21ca1d18) printf '\165\346\217\350\22\233\124\153\20\32\356' && printf '\225\20\305\62\216\177\41\312\35\30\170\234' && printf '\143\142\142\142\147\0\0\0\53\0\16' return ;; esac ;; esac echo >&2 "BUG: don't know how to print $1${2:+ (from $2)}" return 1 } # Compute and append pack trailer to "$1" pack_trailer () { test-sha1 -b <"$1" >trailer.tmp && cat trailer.tmp >>"$1" && rm -f trailer.tmp } # Remove any existing packs to make sure that # whatever we index next will be the pack that we # actually use. clear_packs () { rm -f .git/objects/pack/* }
bboyfeiyu/git
t/lib-pack.sh
Shell
gpl-2.0
2,593
#region using System.Collections.Generic; using System.Data; using Albian.Persistence.Model; #endregion namespace Albian.Persistence.Context { public interface IStorageContext { string StorageName { get; set; } IList<IFakeCommandAttribute> FakeCommand { get; set; } IDbConnection Connection { get; set; } IDbTransaction Transaction { get; set; } IList<IDbCommand> Command { get; set; } IStorageAttribute Storage { get; set; } } }
xvhfeng/albian
Albian.Persistence/Context/IStorageContext.cs
C#
gpl-2.0
514
/** * $Id$ * Copyright (C) 2008 - 2014 Nils Asmussen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <esc/proto/socket.h> #include <esc/stream/fstream.h> #include <esc/stream/istringstream.h> #include <esc/stream/ostream.h> #include <esc/dns.h> #include <sys/common.h> #include <sys/endian.h> #include <sys/proc.h> #include <sys/thread.h> #include <signal.h> namespace esc { /* based on http://tools.ietf.org/html/rfc1035 */ #define DNS_RECURSION_DESIRED 0x100 #define DNS_PORT 53 #define BUF_SIZE 512 uint16_t DNS::_nextId = 0; esc::Net::IPv4Addr DNS::_nameserver; enum Type { TYPE_A = 1, /* a host address */ TYPE_NS = 2, /* an authoritative name server */ TYPE_CNAME = 5, /* the canonical name for an alias */ TYPE_HINFO = 13, /* host information */ TYPE_MX = 15, /* mail exchange */ }; enum Class { CLASS_IN = 1 /* the Internet */ }; struct DNSHeader { uint16_t id; uint16_t flags; uint16_t qdCount; uint16_t anCount; uint16_t nsCount; uint16_t arCount; } A_PACKED; struct DNSQuestionEnd { uint16_t type; uint16_t cls; } A_PACKED; struct DNSAnswer { uint16_t name; uint16_t type; uint16_t cls; uint32_t ttl; uint16_t length; } A_PACKED; esc::Net::IPv4Addr DNS::getHost(const char *name,uint timeout) { if(isIPAddress(name)) { esc::Net::IPv4Addr addr; IStringStream is(name); is >> addr; return addr; } return resolve(name,timeout); } bool DNS::isIPAddress(const char *name) { int dots = 0; int len = 0; // ignore whitespace at the beginning while(isspace(*name)) name++; while(dots < 4 && len < 4 && *name) { if(*name == '.') { dots++; len = 0; } else if(isdigit(*name)) len++; else break; name++; } // ignore whitespace at the end while(isspace(*name)) name++; return dots == 3 && len > 0 && len < 4; } esc::Net::IPv4Addr DNS::resolve(const char *name,uint timeout) { uint8_t buffer[BUF_SIZE]; if(_nameserver.value() == 0) { FStream in(getResolveFile(),"r"); in >> _nameserver; if(_nameserver.value() == 0) VTHROWE("No nameserver",-EHOSTNOTFOUND); } size_t nameLen = strlen(name); size_t total = sizeof(DNSHeader) + nameLen + 2 + sizeof(DNSQuestionEnd); if(total > sizeof(buffer)) VTHROWE("Hostname too long",-EINVAL); // generate a unique uint16_t txid = (getpid() << 16) | _nextId; // build DNS request message DNSHeader *h = reinterpret_cast<DNSHeader*>(buffer); h->id = cputobe16(txid); h->flags = cputobe16(DNS_RECURSION_DESIRED); h->qdCount = cputobe16(1); h->anCount = 0; h->nsCount = 0; h->arCount = 0; convertHostname(reinterpret_cast<char*>(h + 1),name,nameLen); DNSQuestionEnd *qend = reinterpret_cast<DNSQuestionEnd*>(buffer + sizeof(*h) + nameLen + 2); qend->type = cputobe16(TYPE_A); qend->cls = cputobe16(CLASS_IN); // create socket esc::Socket sock(esc::Socket::SOCK_DGRAM,esc::Socket::PROTO_UDP); // send over socket esc::Socket::Addr addr; addr.family = esc::Socket::AF_INET; addr.d.ipv4.addr = _nameserver.value(); addr.d.ipv4.port = DNS_PORT; sock.sendto(addr,buffer,total); sighandler_t oldhandler; if((oldhandler = signal(SIGALRM,sigalarm)) == SIG_ERR) VTHROW("Unable to set SIGALRM handler"); int res; if((res = ualarm(timeout * 1000)) < 0) VTHROWE("ualarm(" << (timeout * 1000) << ")",res); try { // receive response sock.recvfrom(addr,buffer,sizeof(buffer)); } catch(const esc::default_error &e) { if(e.error() == -EINTR) VTHROWE("Received no response from DNS server " << _nameserver,-ETIMEOUT); // ignore errors here if(signal(SIGALRM,oldhandler) == SIG_ERR) {} throw; } // ignore errors here if(signal(SIGALRM,oldhandler) == SIG_ERR) {} if(be16tocpu(h->id) != txid) VTHROWE("Received DNS response with wrong transaction id",-EHOSTNOTFOUND); int questions = be16tocpu(h->qdCount); int answers = be16tocpu(h->anCount); // skip questions uint8_t *data = reinterpret_cast<uint8_t*>(h + 1); for(int i = 0; i < questions; ++i) { size_t len = questionLength(data); data += len + sizeof(DNSQuestionEnd); } // parse answers for(int i = 0; i < answers; ++i) { DNSAnswer *ans = reinterpret_cast<DNSAnswer*>(data); if(be16tocpu(ans->type) == TYPE_A && be16tocpu(ans->length) == esc::Net::IPv4Addr::LEN) return esc::Net::IPv4Addr(data + sizeof(DNSAnswer)); } VTHROWE("Unable to find IP address in DNS response",-EHOSTNOTFOUND); } void DNS::convertHostname(char *dst,const char *src,size_t len) { // leave one byte space for the length of the first part const char *from = src + len++; char *to = dst + len; // we start with the \0 at the end int partLen = -1; for(size_t i = 0; i < len; i++, to--, from--) { if(*from == '.') { *to = partLen; partLen = 0; } else { *to = *from; partLen++; } } *to = partLen; } size_t DNS::questionLength(const uint8_t *data) { size_t total = 0; while(*data != 0) { uint8_t len = *data; // skip this name-part total += len + 1; data += len + 1; } // skip zero ending, too return total + 1; } }
Nils-TUD/Escape
source/lib/esc/dns.cc
C++
gpl-2.0
5,678
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1"> <title>PushReceiver</title> <link rel="stylesheet" href="style.css"/> <!-- Inline scripts are forbidden in Firefox OS apps (CSP restrictions), so we use a script file. --> <script src="app.js" defer></script> </head> <body> <!-- This code is in the public domain. Enjoy! --> <h1>PushReceiver</h1> <div class="row control"><button id="go">Register</button></div> <div id="status"> Not Connected. <div> </body> </html>
royneary/mod_push_test
mozilla-push/Firefox OS/PushReceiver/index.html
HTML
gpl-2.0
627
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef AUDIORECORD_H_ #define AUDIORECORD_H_ #include <binder/IMemory.h> #include <cutils/sched_policy.h> #include <media/AudioSystem.h> #include <media/IAudioRecord.h> #include <system/audio.h> #include <utils/RefBase.h> #include <utils/Errors.h> #include <utils/threads.h> #ifndef ANDROID_DEFAULT_CODE #include <media/AudioEffect.h> #endif namespace android { class audio_track_cblk_t; // ---------------------------------------------------------------------------- class AudioRecord : virtual public RefBase { public: static const int DEFAULT_SAMPLE_RATE = 8000; #ifndef ANDROID_DEFAULT_CODE static const int MATV_SAMPLE_RATE = 32000; #endif /* Events used by AudioRecord callback function (callback_t). * Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*. */ enum event_type { EVENT_MORE_DATA = 0, // Request to read more data from PCM buffer. EVENT_OVERRUN = 1, // PCM buffer overrun occured. EVENT_MARKER = 2, // Record head is at the specified marker position // (See setMarkerPosition()). EVENT_NEW_POS = 3, // Record head is at a new position // (See setPositionUpdatePeriod()). #ifndef ANDROID_DEFAULT_CODE EVENT_WAIT_TIEMOUT = 0xffff, #endif }; /* Create Buffer on the stack and pass it to obtainBuffer() * and releaseBuffer(). */ class Buffer { public: enum { MUTE = 0x00000001 }; uint32_t flags; int channelCount; audio_format_t format; size_t frameCount; size_t size; // total size in bytes == frameCount * frameSize union { void* raw; short* i16; int8_t* i8; }; }; /* As a convenience, if a callback is supplied, a handler thread * is automatically created with the appropriate priority. This thread * invokes the callback when a new buffer becomes ready or an overrun condition occurs. * Parameters: * * event: type of event notified (see enum AudioRecord::event_type). * user: Pointer to context for use by the callback receiver. * info: Pointer to optional parameter according to event type: * - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read * more bytes than indicated by 'size' field and update 'size' if less bytes are * read. * - EVENT_OVERRUN: unused. * - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames. * - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames. */ typedef void (*callback_t)(int event, void* user, void *info); /* Returns the minimum frame count required for the successful creation of * an AudioRecord object. * Returned status (from utils/Errors.h) can be: * - NO_ERROR: successful operation * - NO_INIT: audio server or audio hardware not initialized * - BAD_VALUE: unsupported configuration */ static status_t getMinFrameCount(int* frameCount, uint32_t sampleRate, audio_format_t format, audio_channel_mask_t channelMask); /* Constructs an uninitialized AudioRecord. No connection with * AudioFlinger takes place. */ AudioRecord(); /* Creates an AudioRecord track and registers it with AudioFlinger. * Once created, the track needs to be started before it can be used. * Unspecified values are set to the audio hardware's current * values. * * Parameters: * * inputSource: Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT). * sampleRate: Track sampling rate in Hz. * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed * 16 bits per sample). * channelMask: Channel mask. * frameCount: Total size of track PCM buffer in frames. This defines the * latency of the track. * cbf: Callback function. If not null, this function is called periodically * to provide new PCM data. * user: Context for use by the callback receiver. * notificationFrames: The callback function is called each time notificationFrames PCM * frames are ready in record track output buffer. * sessionId: Not yet supported. */ //\\ AAMTF, Jau, Fix Build Error { // FIXME consider removing this alias and replacing it by audio_in_acoustics_t // or removing the parameter entirely if it is unused enum record_flags { RECORD_AGC_ENABLE = AUDIO_IN_ACOUSTICS_AGC_ENABLE, RECORD_NS_ENABLE = AUDIO_IN_ACOUSTICS_NS_ENABLE, RECORD_IIR_ENABLE = AUDIO_IN_ACOUSTICS_TX_IIR_ENABLE, }; //\\ AAMTF, Jau, Fix Build Error } AudioRecord(audio_source_t inputSource, uint32_t sampleRate = 0, audio_format_t format = AUDIO_FORMAT_DEFAULT, audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, int frameCount = 0, callback_t cbf = NULL, void* user = NULL, int notificationFrames = 0, int sessionId = 0); //MTK80721 HDRecord 2011-12-23 //#ifdef MTK_AUDIO_HD_REC_SUPPORT #ifndef ANDROID_DEFAULT_CODE AudioRecord(audio_source_t inputSource, String8 Params, uint32_t sampleRate = 0, audio_format_t format = AUDIO_FORMAT_DEFAULT, audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, int frameCount = 0, callback_t cbf = NULL, void* user = NULL, int notificationFrames = 0, int sessionId = 0); #endif // /* Terminates the AudioRecord and unregisters it from AudioFlinger. * Also destroys all resources associated with the AudioRecord. */ ~AudioRecord(); /* Initialize an uninitialized AudioRecord. * Returned status (from utils/Errors.h) can be: * - NO_ERROR: successful intialization * - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use * - BAD_VALUE: invalid parameter (channels, format, sampleRate...) * - NO_INIT: audio server or audio hardware not initialized * - PERMISSION_DENIED: recording is not allowed for the requesting process * */ status_t set(audio_source_t inputSource = AUDIO_SOURCE_DEFAULT, uint32_t sampleRate = 0, audio_format_t format = AUDIO_FORMAT_DEFAULT, audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, int frameCount = 0, callback_t cbf = NULL, void* user = NULL, int notificationFrames = 0, bool threadCanCallJava = false, int sessionId = 0); /* Result of constructing the AudioRecord. This must be checked * before using any AudioRecord API (except for set()), using * an uninitialized AudioRecord produces undefined results. * See set() method above for possible return codes. */ status_t initCheck() const; /* Returns this track's latency in milliseconds. * This includes the latency due to AudioRecord buffer size * and audio hardware driver. */ uint32_t latency() const; /* getters, see constructor and set() */ audio_format_t format() const; int channelCount() const; uint32_t frameCount() const; size_t frameSize() const; audio_source_t inputSource() const; /* After it's created the track is not active. Call start() to * make it active. If set, the callback will start being called. * if event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until * the specified event occurs on the specified trigger session. */ status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE, int triggerSession = 0); /* Stop a track. If set, the callback will cease being called and * obtainBuffer returns STOPPED. Note that obtainBuffer() still works * and will fill up buffers until the pool is exhausted. */ void stop(); bool stopped() const; /* get sample rate for this record track */ uint32_t getSampleRate() const; /* Sets marker position. When record reaches the number of frames specified, * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition * with marker == 0 cancels marker notification callback. * If the AudioRecord has been opened with no callback function associated, * the operation will fail. * * Parameters: * * marker: marker position expressed in frames. * * Returned status (from utils/Errors.h) can be: * - NO_ERROR: successful operation * - INVALID_OPERATION: the AudioRecord has no callback installed. */ status_t setMarkerPosition(uint32_t marker); status_t getMarkerPosition(uint32_t *marker) const; /* Sets position update period. Every time the number of frames specified has been recorded, * a callback with event type EVENT_NEW_POS is called. * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification * callback. * If the AudioRecord has been opened with no callback function associated, * the operation will fail. * * Parameters: * * updatePeriod: position update notification period expressed in frames. * * Returned status (from utils/Errors.h) can be: * - NO_ERROR: successful operation * - INVALID_OPERATION: the AudioRecord has no callback installed. */ status_t setPositionUpdatePeriod(uint32_t updatePeriod); status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; /* Gets record head position. The position is the total number of frames * recorded since record start. * * Parameters: * * position: Address where to return record head position within AudioRecord buffer. * * Returned status (from utils/Errors.h) can be: * - NO_ERROR: successful operation * - BAD_VALUE: position is NULL */ status_t getPosition(uint32_t *position) const; /* returns a handle on the audio input used by this AudioRecord. * * Parameters: * none. * * Returned value: * handle on audio hardware input */ audio_io_handle_t getInput() const; /* returns the audio session ID associated with this AudioRecord. * * Parameters: * none. * * Returned value: * AudioRecord session ID. */ int getSessionId() const; /* obtains a buffer of "frameCount" frames. The buffer must be * filled entirely. If the track is stopped, obtainBuffer() returns * STOPPED instead of NO_ERROR as long as there are buffers available, * at which point NO_MORE_BUFFERS is returned. * Buffers will be returned until the pool (buffercount()) * is exhausted, at which point obtainBuffer() will either block * or return WOULD_BLOCK depending on the value of the "blocking" * parameter. */ enum { NO_MORE_BUFFERS = 0x80000001, STOPPED = 1 }; status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount); void releaseBuffer(Buffer* audioBuffer); /* As a convenience we provide a read() interface to the audio buffer. * This is implemented on top of obtainBuffer/releaseBuffer. */ ssize_t read(void* buffer, size_t size); /* Return the amount of input frames lost in the audio driver since the last call of this * function. Audio driver is expected to reset the value to 0 and restart counting upon * returning the current value by this function call. Such loss typically occurs when the * user space process is blocked longer than the capacity of audio driver buffers. * Unit: the number of input audio frames */ unsigned int getInputFramesLost() const; private: /* copying audio tracks is not allowed */ AudioRecord(const AudioRecord& other); AudioRecord& operator = (const AudioRecord& other); #ifndef ANDROID_DEFAULT_CODE void fn_ReleaseEffect(AudioEffect *&pEffect); #endif /* a small internal class to handle the callback */ class AudioRecordThread : public Thread { public: AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false); // Do not call Thread::requestExitAndWait() without first calling requestExit(). // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. virtual void requestExit(); void pause(); // suspend thread from execution at next loop boundary void resume(); // allow thread to execute, if not requested to exit private: friend class AudioRecord; virtual bool threadLoop(); AudioRecord& mReceiver; virtual ~AudioRecordThread(); Mutex mMyLock; // Thread::mLock is private Condition mMyCond; // Thread::mThreadExitedCondition is private bool mPaused; // whether thread is currently paused }; // body of AudioRecordThread::threadLoop() bool processAudioBuffer(const sp<AudioRecordThread>& thread); status_t openRecord_l(uint32_t sampleRate, audio_format_t format, audio_channel_mask_t channelMask, int frameCount, audio_io_handle_t input); audio_io_handle_t getInput_l(); status_t restoreRecord_l(audio_track_cblk_t*& cblk); sp<AudioRecordThread> mAudioRecordThread; mutable Mutex mLock; bool mActive; // protected by mLock // for client callback handler callback_t mCbf; void* mUserData; // for notification APIs uint32_t mNotificationFrames; uint32_t mRemainingFrames; uint32_t mMarkerPosition; // in frames bool mMarkerReached; uint32_t mNewPosition; // in frames uint32_t mUpdatePeriod; // in ms // constant after constructor or set() uint32_t mFrameCount; audio_format_t mFormat; uint8_t mChannelCount; audio_source_t mInputSource; status_t mStatus; uint32_t mLatency; audio_channel_mask_t mChannelMask; audio_io_handle_t mInput; // returned by AudioSystem::getInput() int mSessionId; // may be changed if IAudioRecord object is re-created sp<IAudioRecord> mAudioRecord; sp<IMemory> mCblkMemory; audio_track_cblk_t* mCblk; int mPreviousPriority; // before start() SchedPolicy mPreviousSchedulingGroup; }; }; // namespace android #endif /*AUDIORECORD_H_*/
rex-xxx/mt6572_x201
frameworks/av/include/media/AudioRecord.h
C
gpl-2.0
17,125
<?php /* included from WPML_Translation_Management::icl_dashboard_widget_content */?> <p><?php if ($docs_sent) printf(__('%d documents sent to translation.<br />%d are complete, %d waiting for translation.', 'wpml-translation-management'), $docs_sent, $docs_completed, $docs_waiting); ?></p> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php" class="button secondary"><strong><?php _e('Translate content', 'wpml-translation-management'); ?></strong></a></p> <?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?> <h5 style="margin: 15px 0 0 0;"><?php _e('Need translation work?', 'wpml-translation-management'); ?></h5> <p><?php printf(__('%s offers affordable professional translation via a streamlined process.','wpml-translation-management'), '<a target="_blank" href="http://www.icanlocalize.com/site/">ICanLocalize</a>') ?></p> <p><a href="<?php echo admin_url('index.php?icl_ajx_action=quote-get'); ?>" class="button secondary thickbox"><strong><?php _e('Get quote','wpml-translation-management') ?></strong></a> <a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=icanlocalize" class="button secondary"><strong><?php _e('Get translators','wpml-translation-management') ?></strong></a> </p> <?php endif;?> <?php // shows only when translation polling is on and there are translations in progress $ICL_Pro_Translation->get_icl_manually_tranlations_box('icl_cyan_box'); ?> <?php if (count($active_languages = $sitepress->get_active_languages()) > 1): ?> <div><a href="javascript:void(0)" onclick="jQuery(this).parent().next('.wrapper').slideToggle();" style="display:block; padding:5px; border: 1px solid #eee; margin-bottom:2px; background-color: #F7F7F7;"><?php _e('Content translation', 'wpml-translation-management') ?></a> </div> <div class="wrapper" style="display:none; padding: 5px 10px; border: 1px solid #eee; border-top: 0px; margin:-11px 0 2px 0;"> <?php $your_translators = TranslationManagement::get_blog_translators(); $other_service_translators = TranslationManagement::icanlocalize_translators_list(); if (!empty($your_translators) || !empty($other_service_translators)) { echo '<p><strong>' . __('Your translators', 'wpml-translation-management') . '</strong></p><ul>'; if (!empty($your_translators)) foreach ($your_translators as $your_translator) { echo '<li>'; if ($current_user->ID == $your_translator->ID) { $edit_link = 'profile.php'; } else { $edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(esc_url(stripslashes($_SERVER['REQUEST_URI']))), "user-edit.php?user_id=$your_translator->ID")); } echo '<a href="' . $edit_link . '"><strong>' . $your_translator->display_name . '</strong></a> - '; foreach ($your_translator->language_pairs as $from => $lp) { $tos = array(); foreach ($lp as $to => $null) { $tos[] = $active_languages[$to]['display_name']; } printf(__('%s to %s', 'wpml-translation-management'), $active_languages[$from]['display_name'], join(', ', $tos)); } echo '</li>'; } if (!empty($other_service_translators)){ $langs = $sitepress->get_active_languages(); foreach ($other_service_translators as $rows){ foreach($rows['langs'] as $from => $lp){ $from = isset($langs[$from]['display_name']) ? $langs[$from]['display_name'] : $from; $tos = array(); foreach($lp as $to){ $tos[] = isset($langs[$to]['display_name']) ? $langs[$to]['display_name'] : $to; } } echo '<li>'; echo '<strong>' . $rows['name'] . '</strong> | ' . sprintf(__('%s to %s', 'wpml-translation-management'), $from, join(', ', $tos)) . ' | ' . $rows['action']; echo '</li>'; } } echo '</ul><hr />'; } ?> <?php if(!defined('ICL_DONT_PROMOTE') || !ICL_DONT_PROMOTE):?> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=icanlocalize"><strong><?php _e('Add translators from ICanLocalize &raquo;', 'wpml-translation-management'); ?></strong></a></p> <?php endif; ?> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php&amp;sm=translators&amp;service=local"><strong><?php _e('Add your own translators &raquo;', 'wpml-translation-management'); ?></strong></a></p> <p><a href="admin.php?page=<?php echo WPML_TM_FOLDER; ?>/menu/main.php"><strong><?php _e('Translate contents &raquo;', 'wpml-translation-management'); ?></strong></a></p> </div> <?php endif; ?>
ilfungo/stefanopierini
wp-content/plugins/wpml-translation-management/menu/_icl_dashboard_widget.php
PHP
gpl-2.0
5,985
<HEAD><TITLE>rle.sp</TITLE></HEAD> <BODY> <HR><DIV ALIGN="center"><H1> File : rle.sp </H1></DIV><HR> <DIV ALIGN="center"> <TABLE CELLSPACING="0" CELLPADDING="3" WIDTH="80%" SUMMARY=""> <TR> <TD BGCOLOR="black"><SPAN STYLE="color: #00CC00"> <PRE> $ spar rle 12W1B12W3B24W1B14W WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW </PRE> </SPAN> </TD> </TR> </TABLE> </DIV> <HR> <PRE> #!/usr/local/bin/spar <b>pragma</b> <b>is</b> annotate( summary, "rle" ); annotate( description, "Given a string containing uppercase characters (A-Z)," ); annotate( description, "compress repeated 'runs' of the same character by" ); annotate( description, "storing the length of that run, and provide a function to" ); annotate( description, "reverse the compression. The output can be anything, as" ); annotate( description, "long as you can recreate the input with it." ); annotate( description, "" ); annotate( description, "Example:" ); annotate( description, "Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" ); annotate( description, "Output: 12W1B12W3B24W1B14W" ); annotate( see_also, "http://rosettacode.org/wiki/Run-length_encoding" ); annotate( author, "Ken O. Burtch" ); license( unrestricted ); restriction( no_external_commands ); <b>end</b> <b>pragma</b>; <b>procedure</b> rle <b>is</b> <b>function</b> to_rle( s : string ) <b>return</b> string <b>is</b> <b>begin</b> <b>if</b> strings.length( s ) = 0 <b>then</b> <b>return</b> ""; <b>end</b> <b>if</b>; <b>declare</b> result : string; code : character; prefix : string; first : natural := 1; index : natural := 1; <b>begin</b> <b>while</b> index &lt;= strings.length( s ) <b>loop</b> first := index; index := @+1; code := strings.element( s, positive(first) ); <b>while</b> index &lt;= strings.length( s ) <b>loop</b> <b>exit</b> <b>when</b> code /= strings.element( s, positive(index) ); index := @+1; <b>exit</b> <b>when</b> index-first = 99; <b>end</b> <b>loop</b>; prefix := strings.trim( strings.image( index - first ), trim_end.left ); result := @ &amp; prefix &amp; code; <b>end</b> <b>loop</b>; <b>return</b> result; <b>end</b>; <b>end</b> to_rle; <b>function</b> from_rle( s : string ) <b>return</b> string <b>is</b> <b>begin</b> <b>if</b> strings.length( s ) = 0 <b>then</b> <b>return</b> ""; <b>end</b> <b>if</b>; <b>declare</b> result : string; index : positive := 1; prefix : string; code : character; <b>begin</b> <b>loop</b> prefix := "" &amp; strings.element( s, index ); index := @+1; <b>if</b> strings.is_digit( strings.element( s, index ) ) <b>then</b> prefix := @ &amp; strings.element( s, index ); index := @+1; <b>end</b> <b>if</b>; code := strings.element( s, index ); index := @+1; result := @ &amp; ( numerics.value( prefix ) * code ); <b>exit</b> <b>when</b> natural(index) &gt; strings.length( s ); <b>end</b> <b>loop</b>; <b>return</b> result; <b>end</b>; <b>end</b> from_rle; <b>begin</b> ? to_rle( "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" ); ? from_rle( "12W1B12W3B24W1B14W"); <b>end</b> rle; <FONT COLOR=green><EM>-- VIM editor formatting instructions</EM></FONT> <FONT COLOR=green><EM>-- vim: ft=spar</EM></FONT> </PRE></BODY></HTML>
kburtch/SparForte
examples/rle.html
HTML
gpl-2.0
3,557
# Install script for directory: /home/parallels/new-pi/utils # Set the install prefix IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/usr/local") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "DEBUG") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE)
leftarm/pi-io
build/utils/cmake_install.cmake
CMake
gpl-2.0
1,157
#include <cstdio> #include <cstdlib> #include <cstdarg> #include <cstring> #include "../../Port.h" #include "../../NLS.h" #include "../GBA.h" #include "../GBAGlobals.h" #include "../GBAinline.h" #include "../GBACheats.h" #include "GBACpu.h" #include "../GBAGfx.h" #include "../GBASound.h" #include "../EEprom.h" #include "../Flash.h" #include "../Sram.h" #include "../bios.h" #include "../elf.h" #include "../RTC.h" #include "../agbprint.h" #include "../../common/System.h" #include "../../common/SystemGlobals.h" #include "../../common/Util.h" #include "../../common/movie.h" #include "../../common/vbalua.h" #ifdef PROFILING #include "../prof/prof.h" #endif #ifdef __GNUC__ #define _stricmp strcasecmp #endif static inline void interp_rate() { /* empty for now */ } int32 SWITicks = 0; int32 IRQTicks = 0; u32 mastercode = 0; int32 layerEnableDelay = 0; bool8 busPrefetch = false; bool8 busPrefetchEnable = false; u32 busPrefetchCount = 0; u32 cpuPrefetch[2]; int32 cpuDmaTicksToUpdate = 0; int32 cpuDmaCount = 0; bool8 cpuDmaHack = 0; u32 cpuDmaLast = 0; int32 dummyAddress = 0; int32 gbaSaveType = 0; // used to remember the save type on reset bool8 intState = false; bool8 stopState = false; bool8 holdState = false; int32 holdType = 0; bool8 cpuSramEnabled = true; bool8 cpuFlashEnabled = true; bool8 cpuEEPROMEnabled = true; bool8 cpuEEPROMSensorEnabled = false; #ifdef SDL bool8 cpuBreakLoop = false; #endif // These don't seem to affect determinism int32 cpuNextEvent = 0; int32 cpuTotalTicks = 0; #ifdef PROFILING int profilingTicks = 0; int profilingTicksReload = 0; static profile_segment *profilSegment = NULL; #endif #ifdef BKPT_SUPPORT u8 freezeWorkRAM[0x40000]; u8 freezeInternalRAM[0x8000]; u8 freezeVRAM[0x18000]; u8 freezePRAM[0x400]; u8 freezeOAM[0x400]; bool debugger_last; #endif int32 lcdTicks = (useBios && !skipBios) ? 1008 : 208; u8 timerOnOffDelay = 0; u16 timer0Value = 0; bool8 timer0On = false; int32 timer0Ticks = 0; int32 timer0Reload = 0; int32 timer0ClockReload = 0; u16 timer1Value = 0; bool8 timer1On = false; int32 timer1Ticks = 0; int32 timer1Reload = 0; int32 timer1ClockReload = 0; u16 timer2Value = 0; bool8 timer2On = false; int32 timer2Ticks = 0; int32 timer2Reload = 0; int32 timer2ClockReload = 0; u16 timer3Value = 0; bool8 timer3On = false; int32 timer3Ticks = 0; int32 timer3Reload = 0; int32 timer3ClockReload = 0; u32 dma0Source = 0; u32 dma0Dest = 0; u32 dma1Source = 0; u32 dma1Dest = 0; u32 dma2Source = 0; u32 dma2Dest = 0; u32 dma3Source = 0; u32 dma3Dest = 0; void (*cpuSaveGameFunc)(u32, u8) = flashSaveDecide; void (*renderLine)() = mode0RenderLine; bool8 fxOn = false; bool8 windowOn = false; char buffer[1024]; FILE *out = NULL; const int32 TIMER_TICKS[4] = { 0, 6, 8, 10 }; extern bool8 cpuIsMultiBoot; extern const u32 objTilesAddress[3] = { 0x010000, 0x014000, 0x014000 }; const u8 gamepakRamWaitState[4] = { 4, 3, 2, 8 }; const u8 gamepakWaitState[4] = { 4, 3, 2, 8 }; const u8 gamepakWaitState0[2] = { 2, 1 }; const u8 gamepakWaitState1[2] = { 4, 1 }; const u8 gamepakWaitState2[2] = { 8, 1 }; const bool8 isInRom[16] = { false, false, false, false, false, false, false, false, true, true, true, true, true, true, false, false }; u8 memoryWait[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4, 4, 4, 0 }; u8 memoryWait32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 7, 7, 9, 9, 13, 13, 4, 0 }; u8 memoryWaitSeq[16] = { 0, 0, 2, 0, 0, 0, 0, 0, 2, 2, 4, 4, 8, 8, 4, 0 }; u8 memoryWaitSeq32[16] = { 0, 0, 5, 0, 0, 1, 1, 0, 5, 5, 9, 9, 17, 17, 4, 0 }; // The videoMemoryWait constants are used to add some waitstates // if the opcode access video memory data outside of vblank/hblank // It seems to happen on only one ticks for each pixel. // Not used for now (too problematic with current code). //const u8 videoMemoryWait[16] = // {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}; static int32 romSize = 0x2000000; u8 biosProtected[4]; u8 cpuBitsSet[256]; u8 cpuLowestBitSet[256]; #ifdef WORDS_BIGENDIAN bool8 cpuBiosSwapped = false; #endif u32 myROM[] = { 0xEA000006, 0xEA000093, 0xEA000006, 0x00000000, 0x00000000, 0x00000000, 0xEA000088, 0x00000000, 0xE3A00302, 0xE1A0F000, 0xE92D5800, 0xE55EC002, 0xE28FB03C, 0xE79BC10C, 0xE14FB000, 0xE92D0800, 0xE20BB080, 0xE38BB01F, 0xE129F00B, 0xE92D4004, 0xE1A0E00F, 0xE12FFF1C, 0xE8BD4004, 0xE3A0C0D3, 0xE129F00C, 0xE8BD0800, 0xE169F00B, 0xE8BD5800, 0xE1B0F00E, 0x0000009C, 0x0000009C, 0x0000009C, 0x0000009C, 0x000001F8, 0x000001F0, 0x000000AC, 0x000000A0, 0x000000FC, 0x00000168, 0xE12FFF1E, 0xE1A03000, 0xE1A00001, 0xE1A01003, 0xE2113102, 0x42611000, 0xE033C040, 0x22600000, 0xE1B02001, 0xE15200A0, 0x91A02082, 0x3AFFFFFC, 0xE1500002, 0xE0A33003, 0x20400002, 0xE1320001, 0x11A020A2, 0x1AFFFFF9, 0xE1A01000, 0xE1A00003, 0xE1B0C08C, 0x22600000, 0x42611000, 0xE12FFF1E, 0xE92D0010, 0xE1A0C000, 0xE3A01001, 0xE1500001, 0x81A000A0, 0x81A01081, 0x8AFFFFFB, 0xE1A0000C, 0xE1A04001, 0xE3A03000, 0xE1A02001, 0xE15200A0, 0x91A02082, 0x3AFFFFFC, 0xE1500002, 0xE0A33003, 0x20400002, 0xE1320001, 0x11A020A2, 0x1AFFFFF9, 0xE0811003, 0xE1B010A1, 0xE1510004, 0x3AFFFFEE, 0xE1A00004, 0xE8BD0010, 0xE12FFF1E, 0xE0010090, 0xE1A01741, 0xE2611000, 0xE3A030A9, 0xE0030391, 0xE1A03743, 0xE2833E39, 0xE0030391, 0xE1A03743, 0xE2833C09, 0xE283301C, 0xE0030391, 0xE1A03743, 0xE2833C0F, 0xE28330B6, 0xE0030391, 0xE1A03743, 0xE2833C16, 0xE28330AA, 0xE0030391, 0xE1A03743, 0xE2833A02, 0xE2833081, 0xE0030391, 0xE1A03743, 0xE2833C36, 0xE2833051, 0xE0030391, 0xE1A03743, 0xE2833CA2, 0xE28330F9, 0xE0000093, 0xE1A00840, 0xE12FFF1E, 0xE3A00001, 0xE3A01001, 0xE92D4010, 0xE3A03000, 0xE3A04001, 0xE3500000, 0x1B000004, 0xE5CC3301, 0xEB000002, 0x0AFFFFFC, 0xE8BD4010, 0xE12FFF1E, 0xE3A0C301, 0xE5CC3208, 0xE15C20B8, 0xE0110002, 0x10222000, 0x114C20B8, 0xE5CC4208, 0xE12FFF1E, 0xE92D500F, 0xE3A00301, 0xE1A0E00F, 0xE510F004, 0xE8BD500F, 0xE25EF004, 0xE59FD044, 0xE92D5000, 0xE14FC000, 0xE10FE000, 0xE92D5000, 0xE3A0C302, 0xE5DCE09C, 0xE35E00A5, 0x1A000004, 0x05DCE0B4, 0x021EE080, 0xE28FE004, 0x159FF018, 0x059FF018, 0xE59FD018, 0xE8BD5000, 0xE169F00C, 0xE8BD5000, 0xE25EF004, 0x03007FF0, 0x09FE2000, 0x09FFC000, 0x03007FE0 }; variable_desc saveGameStruct[] = { { &DISPCNT, sizeof(u16) }, { &DISPSTAT, sizeof(u16) }, { &VCOUNT, sizeof(u16) }, { &BG0CNT, sizeof(u16) }, { &BG1CNT, sizeof(u16) }, { &BG2CNT, sizeof(u16) }, { &BG3CNT, sizeof(u16) }, { &BG0HOFS, sizeof(u16) }, { &BG0VOFS, sizeof(u16) }, { &BG1HOFS, sizeof(u16) }, { &BG1VOFS, sizeof(u16) }, { &BG2HOFS, sizeof(u16) }, { &BG2VOFS, sizeof(u16) }, { &BG3HOFS, sizeof(u16) }, { &BG3VOFS, sizeof(u16) }, { &BG2PA, sizeof(u16) }, { &BG2PB, sizeof(u16) }, { &BG2PC, sizeof(u16) }, { &BG2PD, sizeof(u16) }, { &BG2X_L, sizeof(u16) }, { &BG2X_H, sizeof(u16) }, { &BG2Y_L, sizeof(u16) }, { &BG2Y_H, sizeof(u16) }, { &BG3PA, sizeof(u16) }, { &BG3PB, sizeof(u16) }, { &BG3PC, sizeof(u16) }, { &BG3PD, sizeof(u16) }, { &BG3X_L, sizeof(u16) }, { &BG3X_H, sizeof(u16) }, { &BG3Y_L, sizeof(u16) }, { &BG3Y_H, sizeof(u16) }, { &WIN0H, sizeof(u16) }, { &WIN1H, sizeof(u16) }, { &WIN0V, sizeof(u16) }, { &WIN1V, sizeof(u16) }, { &WININ, sizeof(u16) }, { &WINOUT, sizeof(u16) }, { &MOSAIC, sizeof(u16) }, { &BLDMOD, sizeof(u16) }, { &COLEV, sizeof(u16) }, { &COLY, sizeof(u16) }, { &DM0SAD_L, sizeof(u16) }, { &DM0SAD_H, sizeof(u16) }, { &DM0DAD_L, sizeof(u16) }, { &DM0DAD_H, sizeof(u16) }, { &DM0CNT_L, sizeof(u16) }, { &DM0CNT_H, sizeof(u16) }, { &DM1SAD_L, sizeof(u16) }, { &DM1SAD_H, sizeof(u16) }, { &DM1DAD_L, sizeof(u16) }, { &DM1DAD_H, sizeof(u16) }, { &DM1CNT_L, sizeof(u16) }, { &DM1CNT_H, sizeof(u16) }, { &DM2SAD_L, sizeof(u16) }, { &DM2SAD_H, sizeof(u16) }, { &DM2DAD_L, sizeof(u16) }, { &DM2DAD_H, sizeof(u16) }, { &DM2CNT_L, sizeof(u16) }, { &DM2CNT_H, sizeof(u16) }, { &DM3SAD_L, sizeof(u16) }, { &DM3SAD_H, sizeof(u16) }, { &DM3DAD_L, sizeof(u16) }, { &DM3DAD_H, sizeof(u16) }, { &DM3CNT_L, sizeof(u16) }, { &DM3CNT_H, sizeof(u16) }, { &TM0D, sizeof(u16) }, { &TM0CNT, sizeof(u16) }, { &TM1D, sizeof(u16) }, { &TM1CNT, sizeof(u16) }, { &TM2D, sizeof(u16) }, { &TM2CNT, sizeof(u16) }, { &TM3D, sizeof(u16) }, { &TM3CNT, sizeof(u16) }, { &P1, sizeof(u16) }, { &IE, sizeof(u16) }, { &IF, sizeof(u16) }, { &IME, sizeof(u16) }, { &holdState, sizeof(bool8) }, { &holdType, sizeof(int32) }, { &lcdTicks, sizeof(int32) }, { &timer0On, sizeof(bool8) }, { &timer0Ticks, sizeof(int32) }, { &timer0Reload, sizeof(int32) }, { &timer0ClockReload, sizeof(int32) }, { &timer1On, sizeof(bool8) }, { &timer1Ticks, sizeof(int32) }, { &timer1Reload, sizeof(int32) }, { &timer1ClockReload, sizeof(int32) }, { &timer2On, sizeof(bool8) }, { &timer2Ticks, sizeof(int32) }, { &timer2Reload, sizeof(int32) }, { &timer2ClockReload, sizeof(int32) }, { &timer3On, sizeof(bool8) }, { &timer3Ticks, sizeof(int32) }, { &timer3Reload, sizeof(int32) }, { &timer3ClockReload, sizeof(int32) }, { &dma0Source, sizeof(u32) }, { &dma0Dest, sizeof(u32) }, { &dma1Source, sizeof(u32) }, { &dma1Dest, sizeof(u32) }, { &dma2Source, sizeof(u32) }, { &dma2Dest, sizeof(u32) }, { &dma3Source, sizeof(u32) }, { &dma3Dest, sizeof(u32) }, { &fxOn, sizeof(bool8) }, { &windowOn, sizeof(bool8) }, { &N_FLAG, sizeof(bool8) }, { &C_FLAG, sizeof(bool8) }, { &Z_FLAG, sizeof(bool8) }, { &V_FLAG, sizeof(bool8) }, { &armState, sizeof(bool8) }, { &armIrqEnable, sizeof(bool8) }, { &armNextPC, sizeof(u32) }, { &armMode, sizeof(int32) }, { &saveType, sizeof(int32) }, { NULL, 0 } }; ///////////////////////////////////////////// #ifdef PROFILING void cpuProfil(profile_segment *seg) { profilSegment = seg; } void cpuEnableProfiling(int hz) { if (hz == 0) hz = 100; profilingTicks = profilingTicksReload = 16777216 / hz; profSetHertz(hz); } #endif inline int CPUUpdateTicks() { int cpuLoopTicks = lcdTicks; if (soundTicks < cpuLoopTicks) cpuLoopTicks = soundTicks; if (timer0On && (timer0Ticks < cpuLoopTicks)) { cpuLoopTicks = timer0Ticks; } if (timer1On && !(TM1CNT & 4) && (timer1Ticks < cpuLoopTicks)) { cpuLoopTicks = timer1Ticks; } if (timer2On && !(TM2CNT & 4) && (timer2Ticks < cpuLoopTicks)) { cpuLoopTicks = timer2Ticks; } if (timer3On && !(TM3CNT & 4) && (timer3Ticks < cpuLoopTicks)) { cpuLoopTicks = timer3Ticks; } #ifdef PROFILING if (profilingTicksReload != 0) { if (profilingTicks < cpuLoopTicks) { cpuLoopTicks = profilingTicks; } } #endif if (SWITicks) { if (SWITicks < cpuLoopTicks) cpuLoopTicks = SWITicks; } if (IRQTicks) { if (IRQTicks < cpuLoopTicks) cpuLoopTicks = IRQTicks; } return cpuLoopTicks; } void CPUUpdateWindow0() { int x00 = WIN0H >> 8; int x01 = WIN0H & 255; if (x00 <= x01) { for (int i = 0; i < 240; i++) { gfxInWin0[i] = (i >= x00 && i < x01); } } else { for (int i = 0; i < 240; i++) { gfxInWin0[i] = (i >= x00 || i < x01); } } } void CPUUpdateWindow1() { int x00 = WIN1H >> 8; int x01 = WIN1H & 255; if (x00 <= x01) { for (int i = 0; i < 240; i++) { gfxInWin1[i] = (i >= x00 && i < x01); } } else { for (int i = 0; i < 240; i++) { gfxInWin1[i] = (i >= x00 || i < x01); } } } #define CLEAR_ARRAY(a) \ { \ u32 *array = (a); \ for (int i = 0; i < 240; i++) { \ *array++ = 0x80000000; \ } \ } \ void CPUUpdateRenderBuffers(bool force) { if (!(layerEnable & 0x0100) || force) { CLEAR_ARRAY(line0); } if (!(layerEnable & 0x0200) || force) { CLEAR_ARRAY(line1); } if (!(layerEnable & 0x0400) || force) { CLEAR_ARRAY(line2); } if (!(layerEnable & 0x0800) || force) { CLEAR_ARRAY(line3); } } #undef CLEAR_ARRAY bool CPUWriteStateToStream(gzFile gzFile) { utilWriteInt(gzFile, SAVE_GAME_VERSION); utilGzWrite(gzFile, &rom[0xa0], 16); utilWriteInt(gzFile, useBios); utilGzWrite(gzFile, &reg[0], sizeof(reg)); utilWriteData(gzFile, saveGameStruct); // new to version 0.7.1 utilWriteInt(gzFile, stopState); // new to version 0.8 utilWriteInt(gzFile, intState); utilGzWrite(gzFile, internalRAM, 0x8000); utilGzWrite(gzFile, paletteRAM, 0x400); utilGzWrite(gzFile, workRAM, 0x40000); utilGzWrite(gzFile, vram, 0x20000); utilGzWrite(gzFile, oam, 0x400); utilGzWrite(gzFile, pix, 4 * 241 * 162); utilGzWrite(gzFile, ioMem, 0x400); eepromSaveGame(gzFile); flashSaveGame(gzFile); soundSaveGame(gzFile); cheatsSaveGame(gzFile); // version 1.5 rtcSaveGame(gzFile); // SAVE_GAME_VERSION_9 (new to re-recording version which is based on 1.72) { utilGzWrite(gzFile, &sensorX, sizeof(sensorX)); utilGzWrite(gzFile, &sensorY, sizeof(sensorY)); bool8 movieActive = VBAMovieIsActive(); utilGzWrite(gzFile, &movieActive, sizeof(movieActive)); if (movieActive) { uint8 *movie_freeze_buf = NULL; uint32 movie_freeze_size = 0; int code = VBAMovieFreeze(&movie_freeze_buf, &movie_freeze_size); if (movie_freeze_buf) { utilGzWrite(gzFile, &movie_freeze_size, sizeof(movie_freeze_size)); utilGzWrite(gzFile, movie_freeze_buf, movie_freeze_size); delete [] movie_freeze_buf; } else { if (code == MOVIE_UNRECORDED_INPUT) { systemMessage(0, N_("Cannot make a movie snapshot as long as there are unrecorded input changes.")); } else { systemMessage(0, N_("Failed to save movie snapshot.")); } return false; } } utilGzWrite(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount)); } // SAVE_GAME_VERSION_13 { utilGzWrite(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount)); utilGzWrite(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged)); utilGzWrite(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast)); } // SAVE_GAME_VERSION_14 { utilGzWrite(gzFile, memoryWait, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWait32, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWaitSeq, 16 * sizeof(u8)); utilGzWrite(gzFile, memoryWaitSeq32, 16 * sizeof(u8)); utilGzWrite(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used... } return true; } bool CPUWriteState(const char *file) { gzFile gzFile = utilGzOpen(file, "wb"); if (gzFile == NULL) { systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), file); return false; } bool res = CPUWriteStateToStream(gzFile); utilGzClose(gzFile); return res; } bool CPUWriteMemState(char *memory, int available) { gzFile gzFile = utilMemGzOpen(memory, available, "w"); if (gzFile == NULL) { return false; } bool res = CPUWriteStateToStream(gzFile); long pos = utilGzTell(gzFile) + 8; if (pos >= (available)) res = false; utilGzClose(gzFile); return res; } bool CPUReadStateFromStream(gzFile gzFile) { char tempBackupName[128]; if (tempSaveSafe) { sprintf(tempBackupName, "gbatempsave%d.sav", tempSaveID++); CPUWriteState(tempBackupName); } int version = utilReadInt(gzFile); if (version > SAVE_GAME_VERSION || version < SAVE_GAME_VERSION_1) { systemMessage(MSG_UNSUPPORTED_VBA_SGM, N_("Unsupported VisualBoyAdvance save game version %d"), version); goto failedLoad; } u8 romname[17]; utilGzRead(gzFile, romname, 16); if (memcmp(&rom[0xa0], romname, 16) != 0) { romname[16] = 0; for (int i = 0; i < 16; i++) if (romname[i] < 32) romname[i] = 32; systemMessage(MSG_CANNOT_LOAD_SGM, N_("Cannot load save game for %s"), romname); goto failedLoad; } bool8 ub = utilReadInt(gzFile) ? true : false; if (ub != useBios) { if (useBios) systemMessage(MSG_SAVE_GAME_NOT_USING_BIOS, N_("Save game is not using the BIOS files")); else systemMessage(MSG_SAVE_GAME_USING_BIOS, N_("Save game is using the BIOS file")); goto failedLoad; } utilGzRead(gzFile, &reg[0], sizeof(reg)); utilReadData(gzFile, saveGameStruct); if (version < SAVE_GAME_VERSION_3) stopState = false; else stopState = utilReadInt(gzFile) ? true : false; if (version < SAVE_GAME_VERSION_4) intState = false; else intState = utilReadInt(gzFile) ? true : false; utilGzRead(gzFile, internalRAM, 0x8000); utilGzRead(gzFile, paletteRAM, 0x400); utilGzRead(gzFile, workRAM, 0x40000); utilGzRead(gzFile, vram, 0x20000); utilGzRead(gzFile, oam, 0x400); if (version < SAVE_GAME_VERSION_6) utilGzRead(gzFile, pix, 4 * 240 * 160); else utilGzRead(gzFile, pix, 4 * 241 * 162); utilGzRead(gzFile, ioMem, 0x400); if (skipSaveGameBattery) { // skip eeprom data eepromReadGameSkip(gzFile, version); // skip flash data flashReadGameSkip(gzFile, version); } else { eepromReadGame(gzFile, version); flashReadGame(gzFile, version); } soundReadGame(gzFile, version); if (version > SAVE_GAME_VERSION_1) { if (skipSaveGameCheats) { // skip cheats list data cheatsReadGameSkip(gzFile, version); } else { cheatsReadGame(gzFile, version); } } if (version > SAVE_GAME_VERSION_6) { rtcReadGame(gzFile); } if (version <= SAVE_GAME_VERSION_7) { u32 temp; #define SWAP(a, b, c) \ temp = (a); \ (a) = (b) << 16 | (c); \ (b) = (temp) >> 16; \ (c) = (temp) & 0xFFFF; SWAP(dma0Source, DM0SAD_H, DM0SAD_L); SWAP(dma0Dest, DM0DAD_H, DM0DAD_L); SWAP(dma1Source, DM1SAD_H, DM1SAD_L); SWAP(dma1Dest, DM1DAD_H, DM1DAD_L); SWAP(dma2Source, DM2SAD_H, DM2SAD_L); SWAP(dma2Dest, DM2DAD_H, DM2DAD_L); SWAP(dma3Source, DM3SAD_H, DM3SAD_L); SWAP(dma3Dest, DM3DAD_H, DM3DAD_L); } #undef SWAP if (version <= SAVE_GAME_VERSION_8) { timer0ClockReload = TIMER_TICKS[TM0CNT & 3]; timer1ClockReload = TIMER_TICKS[TM1CNT & 3]; timer2ClockReload = TIMER_TICKS[TM2CNT & 3]; timer3ClockReload = TIMER_TICKS[TM3CNT & 3]; timer0Ticks = ((0x10000 - TM0D) << timer0ClockReload) - timer0Ticks; timer1Ticks = ((0x10000 - TM1D) << timer1ClockReload) - timer1Ticks; timer2Ticks = ((0x10000 - TM2D) << timer2ClockReload) - timer2Ticks; timer3Ticks = ((0x10000 - TM3D) << timer3ClockReload) - timer3Ticks; interp_rate(); } // set pointers! layerEnable = layerSettings & DISPCNT; CPUUpdateRender(); CPUUpdateRenderBuffers(true); CPUUpdateWindow0(); CPUUpdateWindow1(); gbaSaveType = 0; switch (saveType) { case 0: cpuSaveGameFunc = flashSaveDecide; break; case 1: cpuSaveGameFunc = sramWrite; gbaSaveType = 1; break; case 2: cpuSaveGameFunc = flashWrite; gbaSaveType = 2; break; case 3: break; case 5: gbaSaveType = 5; break; default: systemMessage(MSG_UNSUPPORTED_SAVE_TYPE, N_("Unsupported save type %d"), saveType); break; } if (eepromInUse) gbaSaveType = 3; systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED; bool wasPlayingMovie = VBAMovieIsActive() && VBAMovieIsPlaying(); if (version >= SAVE_GAME_VERSION_9) // new to re-recording version: { utilGzRead(gzFile, &sensorX, sizeof(sensorX)); utilGzRead(gzFile, &sensorY, sizeof(sensorY)); bool8 movieSnapshot; utilGzRead(gzFile, &movieSnapshot, sizeof(movieSnapshot)); if (VBAMovieIsActive() && !movieSnapshot) { systemMessage(0, N_("Can't load a non-movie snapshot while a movie is active.")); goto failedLoad; } if (movieSnapshot) // even if a movie isn't active we still want to parse through this // because we have already got stuff added in this save format { uint32 movieInputDataSize = 0; utilGzRead(gzFile, &movieInputDataSize, sizeof(movieInputDataSize)); uint8 *local_movie_data = new uint8[movieInputDataSize]; int readBytes = utilGzRead(gzFile, local_movie_data, movieInputDataSize); if (readBytes != movieInputDataSize) { systemMessage(0, N_("Corrupt movie snapshot.")); delete [] local_movie_data; goto failedLoad; } int code = VBAMovieUnfreeze(local_movie_data, movieInputDataSize); delete [] local_movie_data; if (code != MOVIE_SUCCESS && VBAMovieIsActive()) { char errStr [1024]; strcpy(errStr, "Failed to load movie snapshot"); switch (code) { case MOVIE_NOT_FROM_THIS_MOVIE: strcat(errStr, ";\nSnapshot not from this movie"); break; case MOVIE_NOT_FROM_A_MOVIE: strcat(errStr, ";\nNot a movie snapshot"); break; // shouldn't get here... case MOVIE_UNVERIFIABLE_POST_END: sprintf(errStr, "%s;\nSnapshot unverifiable with movie after End Frame %u", errStr, VBAMovieGetLastErrorInfo()); break; case MOVIE_TIMELINE_INCONSISTENT_AT: sprintf(errStr, "%s;\nSnapshot inconsistent with movie at Frame %u", errStr, VBAMovieGetLastErrorInfo()); break; case MOVIE_WRONG_FORMAT: strcat(errStr, ";\nWrong format"); break; } strcat(errStr, "."); systemMessage(0, N_(errStr)); goto failedLoad; } } utilGzRead(gzFile, &systemCounters.frameCount, sizeof(systemCounters.frameCount)); } if (version < SAVE_GAME_VERSION_14) { if (version >= SAVE_GAME_VERSION_10) { utilGzSeek(gzFile, 16 * sizeof(int32) * 6, SEEK_CUR); } if (version >= SAVE_GAME_VERSION_11) { utilGzSeek(gzFile, sizeof(bool8) * 3, SEEK_CUR); } if (version >= SAVE_GAME_VERSION_12) { utilGzSeek(gzFile, sizeof(bool8) * 2, SEEK_CUR); } } if (version >= SAVE_GAME_VERSION_13) { utilGzRead(gzFile, &systemCounters.lagCount, sizeof(systemCounters.lagCount)); utilGzRead(gzFile, &systemCounters.lagged, sizeof(systemCounters.lagged)); utilGzRead(gzFile, &systemCounters.laggedLast, sizeof(systemCounters.laggedLast)); } if (version >= SAVE_GAME_VERSION_14) { utilGzRead(gzFile, memoryWait, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWait32, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWaitSeq, 16 * sizeof(u8)); utilGzRead(gzFile, memoryWaitSeq32, 16 * sizeof(u8)); utilGzRead(gzFile, &speedHack, sizeof(bool8)); // just in case it's ever used... } if (armState) { ARM_PREFETCH; } else { THUMB_PREFETCH; } CPUUpdateRegister(0x204, CPUReadHalfWordQuick(0x4000204)); systemSetJoypad(0, ~P1 & 0x3FF); VBAUpdateButtonPressDisplay(); VBAUpdateFrameCountDisplay(); systemRefreshScreen(); if (tempSaveSafe) { remove(tempBackupName); tempSaveAttempts = 0; } return true; failedLoad: if (tempSaveSafe) { tempSaveAttempts++; if (tempSaveAttempts < 3) // fail no more than 2 times in a row CPUReadState(tempBackupName); remove(tempBackupName); } if (wasPlayingMovie && VBAMovieIsRecording()) { VBAMovieSwitchToPlaying(); } return false; } bool CPUReadMemState(char *memory, int available) { gzFile gzFile = utilMemGzOpen(memory, available, "r"); tempSaveSafe = false; bool res = CPUReadStateFromStream(gzFile); tempSaveSafe = true; utilGzClose(gzFile); return res; } bool CPUReadState(const char *file) { gzFile gzFile = utilGzOpen(file, "rb"); if (gzFile == NULL) return false; bool res = CPUReadStateFromStream(gzFile); utilGzClose(gzFile); return res; } bool CPUExportEepromFile(const char *fileName) { if (eepromInUse) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), fileName); return false; } for (int i = 0; i < eepromSize; ) { for (int j = 0; j < 8; j++) { if (fwrite(&eepromData[i + 7 - j], 1, 1, file) != 1) { fclose(file); return false; } } i += 8; } fclose(file); } return true; } bool CPUWriteBatteryToStream(gzFile gzFile) { if (!gzFile) return false; utilWriteInt(gzFile, SAVE_GAME_VERSION); // for simplicity, we put both types of battery files should be in the stream, even if one's empty eepromSaveGame(gzFile); flashSaveGame(gzFile); return true; } bool CPUWriteBatteryFile(const char *fileName) { if (gbaSaveType == 0) { if (eepromInUse) gbaSaveType = 3; else switch (saveType) { case 1: gbaSaveType = 1; break; case 2: gbaSaveType = 2; break; } } if ((gbaSaveType != 0) && (gbaSaveType != 5)) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(MSG_ERROR_CREATING_FILE, N_("Error creating file %s"), fileName); return false; } // only save if Flash/Sram in use or EEprom in use if (gbaSaveType != 3) { if (gbaSaveType == 2) { if (fwrite(flashSaveMemory, 1, flashSize, file) != (size_t)flashSize) { fclose(file); return false; } } else { if (fwrite(flashSaveMemory, 1, 0x10000, file) != 0x10000) { fclose(file); return false; } } } else { if (fwrite(eepromData, 1, eepromSize, file) != (size_t)eepromSize) { fclose(file); return false; } } fclose(file); } return true; } bool CPUReadGSASnapshot(const char *fileName) { int i; FILE *file = fopen(fileName, "rb"); if (!file) { systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName); return false; } // check file size to know what we should read fseek(file, 0, SEEK_END); // long size = ftell(file); fseek(file, 0x0, SEEK_SET); fread(&i, 1, 4, file); fseek(file, i, SEEK_CUR); // Skip SharkPortSave fseek(file, 4, SEEK_CUR); // skip some sort of flag fread(&i, 1, 4, file); // name length fseek(file, i, SEEK_CUR); // skip name fread(&i, 1, 4, file); // desc length fseek(file, i, SEEK_CUR); // skip desc fread(&i, 1, 4, file); // notes length fseek(file, i, SEEK_CUR); // skip notes int saveSize; fread(&saveSize, 1, 4, file); // read length saveSize -= 0x1c; // remove header size char buffer[17]; char buffer2[17]; fread(buffer, 1, 16, file); buffer[16] = 0; for (i = 0; i < 16; i++) if (buffer[i] < 32) buffer[i] = 32; memcpy(buffer2, &rom[0xa0], 16); buffer2[16] = 0; for (i = 0; i < 16; i++) if (buffer2[i] < 32) buffer2[i] = 32; if (memcmp(buffer, buffer2, 16)) { systemMessage(MSG_CANNOT_IMPORT_SNAPSHOT_FOR, N_("Cannot import snapshot for %s. Current game is %s"), buffer, buffer2); fclose(file); return false; } fseek(file, 12, SEEK_CUR); // skip some flags if (saveSize >= 65536) { if (fread(flashSaveMemory, 1, saveSize, file) != (size_t)saveSize) { fclose(file); return false; } } else { systemMessage(MSG_UNSUPPORTED_SNAPSHOT_FILE, N_("Unsupported snapshot file %s"), fileName); fclose(file); return false; } fclose(file); CPUReset(); return true; } bool CPUWriteGSASnapshot(const char *fileName, const char *title, const char *desc, const char *notes) { FILE *file = fopen(fileName, "wb"); if (!file) { systemMessage(MSG_CANNOT_OPEN_FILE, N_("Cannot open file %s"), fileName); return false; } u8 buffer[17]; utilPutDword(buffer, 0x0d); // SharkPortSave length fwrite(buffer, 1, 4, file); fwrite("SharkPortSave", 1, 0x0d, file); utilPutDword(buffer, 0x000f0000); fwrite(buffer, 1, 4, file); // save type 0x000f0000 = GBA save utilPutDword(buffer, (u32)strlen(title)); fwrite(buffer, 1, 4, file); // title length fwrite(title, 1, strlen(title), file); utilPutDword(buffer, (u32)strlen(desc)); fwrite(buffer, 1, 4, file); // desc length fwrite(desc, 1, strlen(desc), file); utilPutDword(buffer, (u32)strlen(notes)); fwrite(buffer, 1, 4, file); // notes length fwrite(notes, 1, strlen(notes), file); int saveSize = 0x10000; if (gbaSaveType == 2) saveSize = flashSize; int totalSize = saveSize + 0x1c; utilPutDword(buffer, totalSize); // length of remainder of save - CRC fwrite(buffer, 1, 4, file); char *temp = new char[0x2001c]; memset(temp, 0, 28); memcpy(temp, &rom[0xa0], 16); // copy internal name temp[0x10] = rom[0xbe]; // reserved area (old checksum) temp[0x11] = rom[0xbf]; // reserved area (old checksum) temp[0x12] = rom[0xbd]; // complement check temp[0x13] = rom[0xb0]; // maker temp[0x14] = 1; // 1 save ? memcpy(&temp[0x1c], flashSaveMemory, saveSize); // copy save fwrite(temp, 1, totalSize, file); // write save + header u32 crc = 0; for (int i = 0; i < totalSize; i++) { crc += ((u32)temp[i] << (crc % 0x18)); } utilPutDword(buffer, crc); fwrite(buffer, 1, 4, file); // CRC? fclose(file); delete [] temp; return true; } bool CPUImportEepromFile(const char *fileName) { FILE *file = fopen(fileName, "rb"); if (!file) return false; // check file size to know what we should read fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); if (size == 512 || size == 0x2000) { if (fread(eepromData, 1, size, file) != (size_t)size) { fclose(file); return false; } for (int i = 0; i < size; ) { u8 tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; tmp = eepromData[i]; eepromData[i] = eepromData[7 - i]; eepromData[7 - i] = tmp; i++; i += 4; } } else { fclose(file); return false; } fclose(file); return true; } bool CPUReadBatteryFromStream(gzFile gzFile) { if (!gzFile) return false; int version = utilReadInt(gzFile); // for simplicity, we put both types of battery files should be in the stream, even if one's empty eepromReadGame(gzFile, version); flashReadGame(gzFile, version); return true; } bool CPUReadBatteryFile(const char *fileName) { FILE *file = fopen(fileName, "rb"); if (!file) return false; // check file size to know what we should read fseek(file, 0, SEEK_END); long size = ftell(file); fseek(file, 0, SEEK_SET); systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED; if (size == 512 || size == 0x2000) { if (fread(eepromData, 1, size, file) != (size_t)size) { fclose(file); return false; } } else { if (size == 0x20000) { if (fread(flashSaveMemory, 1, 0x20000, file) != 0x20000) { fclose(file); return false; } flashSetSize(0x20000); } else { if (fread(flashSaveMemory, 1, 0x10000, file) != 0x10000) { fclose(file); return false; } flashSetSize(0x10000); } } fclose(file); return true; } bool CPUWritePNGFile(const char *fileName) { return utilWritePNGFile(fileName, 240, 160, pix); } bool CPUWriteBMPFile(const char *fileName) { return utilWriteBMPFile(fileName, 240, 160, pix); } void CPUCleanUp() { #ifdef PROFILING if (profilingTicksReload) { profCleanup(); } #endif PIX_FREE(pix); pix = NULL; free(bios); bios = NULL; free(rom); rom = NULL; free(internalRAM); internalRAM = NULL; free(workRAM); workRAM = NULL; free(paletteRAM); paletteRAM = NULL; free(vram); vram = NULL; free(oam); oam = NULL; free(ioMem); ioMem = NULL; #if 0 eepromErase(); flashErase(); #endif #ifndef NO_DEBUGGER elfCleanUp(); #endif systemCleanUp(); systemRefreshScreen(); } int CPULoadRom(const char *szFile) { int size = 0x2000000; if (rom != NULL) { CPUCleanUp(); } systemSaveUpdateCounter = SYSTEM_SAVE_NOT_UPDATED; rom = (u8 *)malloc(0x2000000); if (rom == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "ROM"); return 0; } // FIXME: size+4 is so RAM search and watch are safe to read any byte in the allocated region as a 4-byte int workRAM = (u8 *)RAM_CALLOC(0x40000); if (workRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "WRAM"); return 0; } u8 *whereToLoad = cpuIsMultiBoot ? workRAM : rom; #ifndef NO_DEBUGGER if (utilIsELF(szFile)) { FILE *f = fopen(szFile, "rb"); if (!f) { systemMessage(MSG_ERROR_OPENING_IMAGE, N_("Error opening image %s"), szFile); CPUCleanUp(); return 0; } bool res = elfRead(szFile, size, f); if (!res || size == 0) { CPUCleanUp(); elfCleanUp(); return 0; } } else #endif //NO_DEBUGGER if (szFile != NULL) { if (!utilLoad(szFile, utilIsGBAImage, whereToLoad, size)) { CPUCleanUp(); return 0; } } u16 *temp = (u16 *)(rom + ((size + 1) & ~1)); for (int i = (size + 1) & ~1; i < 0x2000000; i += 2) { WRITE16LE(temp, (i >> 1) & 0xFFFF); temp++; } pix = (u8 *)PIX_CALLOC(4 * 241 * 162); if (pix == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "PIX"); CPUCleanUp(); return 0; } bios = (u8 *)RAM_CALLOC(0x4000); if (bios == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "BIOS"); CPUCleanUp(); return 0; } internalRAM = (u8 *)RAM_CALLOC(0x8000); if (internalRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "IRAM"); CPUCleanUp(); return 0; } paletteRAM = (u8 *)RAM_CALLOC(0x400); if (paletteRAM == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "PRAM"); CPUCleanUp(); return 0; } vram = (u8 *)RAM_CALLOC(0x20000); if (vram == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "VRAM"); CPUCleanUp(); return 0; } oam = (u8 *)RAM_CALLOC(0x400); if (oam == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "OAM"); CPUCleanUp(); return 0; } ioMem = (u8 *)RAM_CALLOC(0x400); if (ioMem == NULL) { systemMessage(MSG_OUT_OF_MEMORY, N_("Failed to allocate memory for %s"), "IO"); CPUCleanUp(); return 0; } flashInit(); eepromInit(); CPUUpdateRenderBuffers(true); romSize = size; return size; } void CPUDoMirroring(bool b) { u32 mirroredRomSize = (((romSize) >> 20) & 0x3F) << 20; u32 mirroredRomAddress = romSize; if ((mirroredRomSize <= 0x800000) && (b)) { mirroredRomAddress = mirroredRomSize; if (mirroredRomSize == 0) mirroredRomSize = 0x100000; while (mirroredRomAddress < 0x01000000) { memcpy((u16 *)(rom + mirroredRomAddress), (u16 *)(rom), mirroredRomSize); mirroredRomAddress += mirroredRomSize; } } } // Emulates the Cheat System (m) code void CPUMasterCodeCheck() { if (cheatsEnabled) { if ((mastercode) && (mastercode == armNextPC)) { u32 joy = 0; if (systemReadJoypads()) joy = systemGetJoypad(0, cpuEEPROMSensorEnabled); u32 ext = (joy >> 10); cpuTotalTicks += cheatsCheckKeys(P1 ^ 0x3FF, ext); } } } void CPUUpdateRender() { switch (DISPCNT & 7) { case 0: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode0RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode0RenderLineNoWindow; else renderLine = mode0RenderLineAll; break; case 1: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode1RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode1RenderLineNoWindow; else renderLine = mode1RenderLineAll; break; case 2: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode2RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode2RenderLineNoWindow; else renderLine = mode2RenderLineAll; break; case 3: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode3RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode3RenderLineNoWindow; else renderLine = mode3RenderLineAll; break; case 4: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode4RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode4RenderLineNoWindow; else renderLine = mode4RenderLineAll; break; case 5: if ((!fxOn && !windowOn && !(layerEnable & 0x8000)) || cpuDisableSfx) renderLine = mode5RenderLine; else if (fxOn && !windowOn && !(layerEnable & 0x8000)) renderLine = mode5RenderLineNoWindow; else renderLine = mode5RenderLineAll; default: break; } } void CPUUpdateCPSR() { u32 CPSR = reg[16].I & 0x40; if (N_FLAG) CPSR |= 0x80000000; if (Z_FLAG) CPSR |= 0x40000000; if (C_FLAG) CPSR |= 0x20000000; if (V_FLAG) CPSR |= 0x10000000; if (!armState) CPSR |= 0x00000020; if (!armIrqEnable) CPSR |= 0x80; CPSR |= (armMode & 0x1F); reg[16].I = CPSR; } void CPUUpdateFlags(bool breakLoop) { u32 CPSR = reg[16].I; N_FLAG = (CPSR & 0x80000000) ? true : false; Z_FLAG = (CPSR & 0x40000000) ? true : false; C_FLAG = (CPSR & 0x20000000) ? true : false; V_FLAG = (CPSR & 0x10000000) ? true : false; armState = (CPSR & 0x20) ? false : true; armIrqEnable = (CPSR & 0x80) ? false : true; if (breakLoop) { if (armIrqEnable && (IF & IE) && (IME & 1)) cpuNextEvent = cpuTotalTicks; } } void CPUUpdateFlags() { CPUUpdateFlags(true); } #ifdef WORDS_BIGENDIAN static void CPUSwap(volatile u32 *a, volatile u32 *b) { volatile u32 c = *b; *b = *a; *a = c; } #else static void CPUSwap(u32 *a, u32 *b) { u32 c = *b; *b = *a; *a = c; } #endif void CPUSwitchMode(int mode, bool saveState, bool breakLoop) { // if(armMode == mode) // return; CPUUpdateCPSR(); switch (armMode) { case 0x10: case 0x1F: reg[R13_USR].I = reg[13].I; reg[R14_USR].I = reg[14].I; reg[17].I = reg[16].I; break; case 0x11: CPUSwap(&reg[R8_FIQ].I, &reg[8].I); CPUSwap(&reg[R9_FIQ].I, &reg[9].I); CPUSwap(&reg[R10_FIQ].I, &reg[10].I); CPUSwap(&reg[R11_FIQ].I, &reg[11].I); CPUSwap(&reg[R12_FIQ].I, &reg[12].I); reg[R13_FIQ].I = reg[13].I; reg[R14_FIQ].I = reg[14].I; reg[SPSR_FIQ].I = reg[17].I; break; case 0x12: reg[R13_IRQ].I = reg[13].I; reg[R14_IRQ].I = reg[14].I; reg[SPSR_IRQ].I = reg[17].I; break; case 0x13: reg[R13_SVC].I = reg[13].I; reg[R14_SVC].I = reg[14].I; reg[SPSR_SVC].I = reg[17].I; break; case 0x17: reg[R13_ABT].I = reg[13].I; reg[R14_ABT].I = reg[14].I; reg[SPSR_ABT].I = reg[17].I; break; case 0x1b: reg[R13_UND].I = reg[13].I; reg[R14_UND].I = reg[14].I; reg[SPSR_UND].I = reg[17].I; break; } u32 CPSR = reg[16].I; u32 SPSR = reg[17].I; switch (mode) { case 0x10: case 0x1F: reg[13].I = reg[R13_USR].I; reg[14].I = reg[R14_USR].I; reg[16].I = SPSR; break; case 0x11: CPUSwap(&reg[8].I, &reg[R8_FIQ].I); CPUSwap(&reg[9].I, &reg[R9_FIQ].I); CPUSwap(&reg[10].I, &reg[R10_FIQ].I); CPUSwap(&reg[11].I, &reg[R11_FIQ].I); CPUSwap(&reg[12].I, &reg[R12_FIQ].I); reg[13].I = reg[R13_FIQ].I; reg[14].I = reg[R14_FIQ].I; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_FIQ].I; break; case 0x12: reg[13].I = reg[R13_IRQ].I; reg[14].I = reg[R14_IRQ].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_IRQ].I; break; case 0x13: reg[13].I = reg[R13_SVC].I; reg[14].I = reg[R14_SVC].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_SVC].I; break; case 0x17: reg[13].I = reg[R13_ABT].I; reg[14].I = reg[R14_ABT].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_ABT].I; break; case 0x1b: reg[13].I = reg[R13_UND].I; reg[14].I = reg[R14_UND].I; reg[16].I = SPSR; if (saveState) reg[17].I = CPSR; else reg[17].I = reg[SPSR_UND].I; break; default: systemMessage(MSG_UNSUPPORTED_ARM_MODE, N_("Unsupported ARM mode %02x"), mode); break; } armMode = mode; CPUUpdateFlags(breakLoop); CPUUpdateCPSR(); } void CPUSwitchMode(int mode, bool saveState) { CPUSwitchMode(mode, saveState, true); } void CPUUndefinedException() { u32 PC = reg[15].I; bool savedArmState = armState; CPUSwitchMode(0x1b, true, false); reg[14].I = PC - (savedArmState ? 4 : 2); reg[15].I = 0x04; armState = true; armIrqEnable = false; armNextPC = 0x04; ARM_PREFETCH; reg[15].I += 4; } void CPUSoftwareInterrupt() { u32 PC = reg[15].I; bool savedArmState = armState; CPUSwitchMode(0x13, true, false); reg[14].I = PC - (savedArmState ? 4 : 2); reg[15].I = 0x08; armState = true; armIrqEnable = false; armNextPC = 0x08; ARM_PREFETCH; reg[15].I += 4; } void CPUSoftwareInterrupt(int comment) { static bool disableMessage = false; if (armState) comment >>= 16; #ifdef BKPT_SUPPORT if (comment == 0xff) { dbgOutput(NULL, reg[0].I); return; } #endif #ifdef PROFILING if (comment == 0xfe) { profStartup(reg[0].I, reg[1].I); return; } if (comment == 0xfd) { profControl(reg[0].I); return; } if (comment == 0xfc) { profCleanup(); return; } if (comment == 0xfb) { profCount(); return; } #endif if (comment == 0xfa) { agbPrintFlush(); return; } #ifdef SDL if (comment == 0xf9) { emulating = 0; cpuNextEvent = cpuTotalTicks; cpuBreakLoop = true; return; } #endif if (useBios) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment, armState ? armNextPC - 4 : armNextPC - 2, reg[0].I, reg[1].I, reg[2].I, VCOUNT); } #endif CPUSoftwareInterrupt(); return; } // This would be correct, but it causes problems if uncommented // else { // biosProtected = 0xe3a02004; // } switch (comment) { case 0x00: BIOS_SoftReset(); ARM_PREFETCH; break; case 0x01: BIOS_RegisterRamReset(); break; case 0x02: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("Halt: (VCOUNT = %2d)\n", VCOUNT); } #endif holdState = true; holdType = -1; cpuNextEvent = cpuTotalTicks; break; case 0x03: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("Stop: (VCOUNT = %2d)\n", VCOUNT); } #endif holdState = true; holdType = -1; stopState = true; cpuNextEvent = cpuTotalTicks; break; case 0x04: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("IntrWait: 0x%08x,0x%08x (VCOUNT = %2d)\n", reg[0].I, reg[1].I, VCOUNT); } #endif CPUSoftwareInterrupt(); break; case 0x05: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("VBlankIntrWait: (VCOUNT = %2d)\n", VCOUNT); } #endif CPUSoftwareInterrupt(); break; case 0x06: CPUSoftwareInterrupt(); break; case 0x07: CPUSoftwareInterrupt(); break; case 0x08: BIOS_Sqrt(); break; case 0x09: BIOS_ArcTan(); break; case 0x0A: BIOS_ArcTan2(); break; case 0x0B: { int len = (reg[2].I & 0x1FFFFF) >> 1; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) { if ((reg[2].I >> 24) & 1) { if ((reg[2].I >> 26) & 1) SWITicks = (7 + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1); else SWITicks = (8 + memoryWait[(reg[1].I >> 24) & 0xF]) * (len); } else { if ((reg[2].I >> 26) & 1) SWITicks = (10 + memoryWait32[(reg[0].I >> 24) & 0xF] + memoryWait32[(reg[1].I >> 24) & 0xF]) * (len >> 1); else SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } } } BIOS_CpuSet(); break; case 0x0C: { int len = (reg[2].I & 0x1FFFFF) >> 5; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) { if ((reg[2].I >> 24) & 1) SWITicks = (6 + memoryWait32[(reg[1].I >> 24) & 0xF] + 7 * (memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 1)) * len; else SWITicks = (9 + memoryWait32[(reg[0].I >> 24) & 0xF] + memoryWait32[(reg[1].I >> 24) & 0xF] + 7 * (memoryWaitSeq32[(reg[0].I >> 24) & 0xF] + memoryWaitSeq32[(reg[1].I >> 24) & 0xF] + 2)) * len; } } BIOS_CpuFastSet(); break; case 0x0D: BIOS_GetBiosChecksum(); break; case 0x0E: BIOS_BgAffineSet(); break; case 0x0F: BIOS_ObjAffineSet(); break; case 0x10: { int len = CPUReadHalfWord(reg[2].I); if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + len) & 0xe000000) == 0)) SWITicks = (32 + memoryWait[(reg[0].I >> 24) & 0xF]) * len; } BIOS_BitUnPack(); break; case 0x11: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (9 + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_LZ77UnCompWram(); break; case 0x12: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (19 + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_LZ77UnCompVram(); break; case 0x13: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (29 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1)) * len; } BIOS_HuffUnComp(); break; case 0x14: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (11 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_RLUnCompWram(); break; case 0x15: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (34 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_RLUnCompVram(); break; case 0x16: { u32 len = CPUReadMemory(reg[0].I) >> 8; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_Diff8bitUnFilterWram(); break; case 0x17: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (39 + (memoryWait[(reg[0].I >> 24) & 0xF] << 1) + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_Diff8bitUnFilterVram(); break; case 0x18: { u32 len = CPUReadMemory(reg[0].I) >> 9; if (!(((reg[0].I & 0xe000000) == 0) || ((reg[0].I + (len & 0x1fffff)) & 0xe000000) == 0)) SWITicks = (13 + memoryWait[(reg[0].I >> 24) & 0xF] + memoryWait[(reg[1].I >> 24) & 0xF]) * len; } BIOS_Diff16bitUnFilter(); break; case 0x19: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SoundBiasSet: 0x%08x (VCOUNT = %2d)\n", reg[0].I, VCOUNT); } #endif if (reg[0].I) systemSoundPause(); else systemSoundResume(); break; case 0x1F: BIOS_MidiKey2Freq(); break; case 0x2A: BIOS_SndDriverJmpTableCopy(); // let it go, because we don't really emulate this function // FIXME (?) default: #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_SWI) { log("SWI: %08x at %08x (0x%08x,0x%08x,0x%08x,VCOUNT = %2d)\n", comment, armState ? armNextPC - 4 : armNextPC - 2, reg[0].I, reg[1].I, reg[2].I, VCOUNT); } #endif if (!disableMessage) { systemMessage(MSG_UNSUPPORTED_BIOS_FUNCTION, N_("Unsupported BIOS function %02x called from %08x. A BIOS file is needed in order to get correct behaviour."), comment, armMode ? armNextPC - 4 : armNextPC - 2); disableMessage = true; } break; } } void CPUCompareVCOUNT() { if (VCOUNT == (DISPSTAT >> 8)) { DISPSTAT |= 4; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 0x20) { IF |= 4; UPDATE_REG(0x202, IF); } } else { DISPSTAT &= 0xFFFB; UPDATE_REG(0x4, DISPSTAT); } if (layerEnableDelay > 0) { --layerEnableDelay; if (layerEnableDelay == 1) layerEnable = layerSettings & DISPCNT; } } static void doDMA(u32 &s, u32 &d, u32 si, u32 di, u32 c, int transfer32) { int sm = s >> 24; int dm = d >> 24; int sw = 0; int dw = 0; int sc = c; cpuDmaCount = c; // This is done to get the correct waitstates. if (sm > 15) sm = 15; if (dm > 15) dm = 15; //if ((sm>=0x05) && (sm<=0x07) || (dm>=0x05) && (dm <=0x07)) // blank = (((DISPSTAT | ((DISPSTAT>>1)&1))==1) ? true : false); if (transfer32) { s &= 0xFFFFFFFC; if (s < 0x02000000 && (reg[15].I >> 24)) { while (c != 0) { CPUWriteMemory(d, 0); d += di; c--; } } else { while (c != 0) { cpuDmaLast = CPUReadMemory(s); CPUWriteMemory(d, cpuDmaLast); d += di; s += si; c--; } } } else { s &= 0xFFFFFFFE; si = (int)si >> 1; di = (int)di >> 1; if (s < 0x02000000 && (reg[15].I >> 24)) { while (c != 0) { CPUWriteHalfWord(d, 0); d += di; c--; } } else { while (c != 0) { cpuDmaLast = CPUReadHalfWord(s); CPUWriteHalfWord(d, cpuDmaLast); cpuDmaLast |= (cpuDmaLast << 16); d += di; s += si; c--; } } } cpuDmaCount = 0; int totalTicks = 0; if (transfer32) { sw = 1 + memoryWaitSeq32[sm & 15]; dw = 1 + memoryWaitSeq32[dm & 15]; totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait32[sm & 15] + memoryWaitSeq32[dm & 15]; } else { sw = 1 + memoryWaitSeq[sm & 15]; dw = 1 + memoryWaitSeq[dm & 15]; totalTicks = (sw + dw) * (sc - 1) + 6 + memoryWait[sm & 15] + memoryWaitSeq[dm & 15]; } cpuDmaTicksToUpdate += totalTicks; } void CPUCheckDMA(int reason, int dmamask) { // DMA 0 if ((DM0CNT_H & 0x8000) && (dmamask & 1)) { if (((DM0CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM0CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM0CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA0) { int count = (DM0CNT_L ? DM0CNT_L : 0x4000) << 1; if (DM0CNT_H & 0x0400) count <<= 1; log("DMA0: s=%08x d=%08x c=%04x count=%08x\n", dma0Source, dma0Dest, DM0CNT_H, count); } #endif doDMA(dma0Source, dma0Dest, sourceIncrement, destIncrement, DM0CNT_L ? DM0CNT_L : 0x4000, DM0CNT_H & 0x0400); cpuDmaHack = true; if (DM0CNT_H & 0x4000) { IF |= 0x0100; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM0CNT_H >> 5) & 3) == 3) { dma0Dest = DM0DAD_L | (DM0DAD_H << 16); } if (!(DM0CNT_H & 0x0200) || (reason == 0)) { DM0CNT_H &= 0x7FFF; UPDATE_REG(0xBA, DM0CNT_H); } } } // DMA 1 if ((DM1CNT_H & 0x8000) && (dmamask & 2)) { if (((DM1CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM1CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM1CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } if (reason == 3) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA1) { log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest, DM1CNT_H, 16); } #endif doDMA(dma1Source, dma1Dest, sourceIncrement, 0, 4, 0x0400); } else { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA1) { int count = (DM1CNT_L ? DM1CNT_L : 0x4000) << 1; if (DM1CNT_H & 0x0400) count <<= 1; log("DMA1: s=%08x d=%08x c=%04x count=%08x\n", dma1Source, dma1Dest, DM1CNT_H, count); } #endif doDMA(dma1Source, dma1Dest, sourceIncrement, destIncrement, DM1CNT_L ? DM1CNT_L : 0x4000, DM1CNT_H & 0x0400); } cpuDmaHack = true; if (DM1CNT_H & 0x4000) { IF |= 0x0200; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM1CNT_H >> 5) & 3) == 3) { dma1Dest = DM1DAD_L | (DM1DAD_H << 16); } if (!(DM1CNT_H & 0x0200) || (reason == 0)) { DM1CNT_H &= 0x7FFF; UPDATE_REG(0xC6, DM1CNT_H); } } } // DMA 2 if ((DM2CNT_H & 0x8000) && (dmamask & 4)) { if (((DM2CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM2CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM2CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } if (reason == 3) { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA2) { int count = (4) << 2; log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest, DM2CNT_H, count); } #endif doDMA(dma2Source, dma2Dest, sourceIncrement, 0, 4, 0x0400); } else { #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA2) { int count = (DM2CNT_L ? DM2CNT_L : 0x4000) << 1; if (DM2CNT_H & 0x0400) count <<= 1; log("DMA2: s=%08x d=%08x c=%04x count=%08x\n", dma2Source, dma2Dest, DM2CNT_H, count); } #endif doDMA(dma2Source, dma2Dest, sourceIncrement, destIncrement, DM2CNT_L ? DM2CNT_L : 0x4000, DM2CNT_H & 0x0400); } cpuDmaHack = true; if (DM2CNT_H & 0x4000) { IF |= 0x0400; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM2CNT_H >> 5) & 3) == 3) { dma2Dest = DM2DAD_L | (DM2DAD_H << 16); } if (!(DM2CNT_H & 0x0200) || (reason == 0)) { DM2CNT_H &= 0x7FFF; UPDATE_REG(0xD2, DM2CNT_H); } } } // DMA 3 if ((DM3CNT_H & 0x8000) && (dmamask & 8)) { if (((DM3CNT_H >> 12) & 3) == reason) { u32 sourceIncrement = 4; u32 destIncrement = 4; switch ((DM3CNT_H >> 7) & 3) { case 0: break; case 1: sourceIncrement = (u32) - 4; break; case 2: sourceIncrement = 0; break; } switch ((DM3CNT_H >> 5) & 3) { case 0: break; case 1: destIncrement = (u32) - 4; break; case 2: destIncrement = 0; break; } #ifdef GBA_LOGGING if (systemVerbose & VERBOSE_DMA3) { int count = (DM3CNT_L ? DM3CNT_L : 0x10000) << 1; if (DM3CNT_H & 0x0400) count <<= 1; log("DMA3: s=%08x d=%08x c=%04x count=%08x\n", dma3Source, dma3Dest, DM3CNT_H, count); } #endif doDMA(dma3Source, dma3Dest, sourceIncrement, destIncrement, DM3CNT_L ? DM3CNT_L : 0x10000, DM3CNT_H & 0x0400); if (DM3CNT_H & 0x4000) { IF |= 0x0800; UPDATE_REG(0x202, IF); cpuNextEvent = cpuTotalTicks; } if (((DM3CNT_H >> 5) & 3) == 3) { dma3Dest = DM3DAD_L | (DM3DAD_H << 16); } if (!(DM3CNT_H & 0x0200) || (reason == 0)) { DM3CNT_H &= 0x7FFF; UPDATE_REG(0xDE, DM3CNT_H); } } } } void CPUUpdateRegister(u32 address, u16 value) { switch (address) { case 0x00: { if ((value & 7) > 5) { // display modes above 0-5 are prohibited DISPCNT = (value & 7); } bool change = (0 != ((DISPCNT ^ value) & 0x80)); bool changeBG = (0 != ((DISPCNT ^ value) & 0x0F00)); u16 changeBGon = ((~DISPCNT) & value) & 0x0F00; // these layers are being activated DISPCNT = (value & 0xFFF7); // bit 3 can only be accessed by the BIOS to enable GBC mode UPDATE_REG(0x00, DISPCNT); if (changeBGon) { layerEnableDelay = 4; layerEnable = layerSettings & value & (~changeBGon); } else { layerEnable = layerSettings & value; // CPUUpdateTicks(); // what does this do? } windowOn = (layerEnable & 0x6000) ? true : false; if (change && !((value & 0x80))) { if (!(DISPSTAT & 1)) { lcdTicks = 1008; // VCOUNT = 0; // UPDATE_REG(0x06, VCOUNT); DISPSTAT &= 0xFFFC; UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } // (*renderLine)(); } CPUUpdateRender(); // we only care about changes in BG0-BG3 if (changeBG) { CPUUpdateRenderBuffers(false); } break; } case 0x04: DISPSTAT = (value & 0xFF38) | (DISPSTAT & 7); UPDATE_REG(0x04, DISPSTAT); break; case 0x06: // not writable break; case 0x08: BG0CNT = (value & 0xDFCF); UPDATE_REG(0x08, BG0CNT); break; case 0x0A: BG1CNT = (value & 0xDFCF); UPDATE_REG(0x0A, BG1CNT); break; case 0x0C: BG2CNT = (value & 0xFFCF); UPDATE_REG(0x0C, BG2CNT); break; case 0x0E: BG3CNT = (value & 0xFFCF); UPDATE_REG(0x0E, BG3CNT); break; case 0x10: BG0HOFS = value & 511; UPDATE_REG(0x10, BG0HOFS); break; case 0x12: BG0VOFS = value & 511; UPDATE_REG(0x12, BG0VOFS); break; case 0x14: BG1HOFS = value & 511; UPDATE_REG(0x14, BG1HOFS); break; case 0x16: BG1VOFS = value & 511; UPDATE_REG(0x16, BG1VOFS); break; case 0x18: BG2HOFS = value & 511; UPDATE_REG(0x18, BG2HOFS); break; case 0x1A: BG2VOFS = value & 511; UPDATE_REG(0x1A, BG2VOFS); break; case 0x1C: BG3HOFS = value & 511; UPDATE_REG(0x1C, BG3HOFS); break; case 0x1E: BG3VOFS = value & 511; UPDATE_REG(0x1E, BG3VOFS); break; case 0x20: BG2PA = value; UPDATE_REG(0x20, BG2PA); break; case 0x22: BG2PB = value; UPDATE_REG(0x22, BG2PB); break; case 0x24: BG2PC = value; UPDATE_REG(0x24, BG2PC); break; case 0x26: BG2PD = value; UPDATE_REG(0x26, BG2PD); break; case 0x28: BG2X_L = value; UPDATE_REG(0x28, BG2X_L); gfxBG2Changed |= 1; break; case 0x2A: BG2X_H = (value & 0xFFF); UPDATE_REG(0x2A, BG2X_H); gfxBG2Changed |= 1; break; case 0x2C: BG2Y_L = value; UPDATE_REG(0x2C, BG2Y_L); gfxBG2Changed |= 2; break; case 0x2E: BG2Y_H = value & 0xFFF; UPDATE_REG(0x2E, BG2Y_H); gfxBG2Changed |= 2; break; case 0x30: BG3PA = value; UPDATE_REG(0x30, BG3PA); break; case 0x32: BG3PB = value; UPDATE_REG(0x32, BG3PB); break; case 0x34: BG3PC = value; UPDATE_REG(0x34, BG3PC); break; case 0x36: BG3PD = value; UPDATE_REG(0x36, BG3PD); break; case 0x38: BG3X_L = value; UPDATE_REG(0x38, BG3X_L); gfxBG3Changed |= 1; break; case 0x3A: BG3X_H = value & 0xFFF; UPDATE_REG(0x3A, BG3X_H); gfxBG3Changed |= 1; break; case 0x3C: BG3Y_L = value; UPDATE_REG(0x3C, BG3Y_L); gfxBG3Changed |= 2; break; case 0x3E: BG3Y_H = value & 0xFFF; UPDATE_REG(0x3E, BG3Y_H); gfxBG3Changed |= 2; break; case 0x40: WIN0H = value; UPDATE_REG(0x40, WIN0H); CPUUpdateWindow0(); break; case 0x42: WIN1H = value; UPDATE_REG(0x42, WIN1H); CPUUpdateWindow1(); break; case 0x44: WIN0V = value; UPDATE_REG(0x44, WIN0V); break; case 0x46: WIN1V = value; UPDATE_REG(0x46, WIN1V); break; case 0x48: WININ = value & 0x3F3F; UPDATE_REG(0x48, WININ); break; case 0x4A: WINOUT = value & 0x3F3F; UPDATE_REG(0x4A, WINOUT); break; case 0x4C: MOSAIC = value; UPDATE_REG(0x4C, MOSAIC); break; case 0x50: BLDMOD = value & 0x3FFF; UPDATE_REG(0x50, BLDMOD); fxOn = ((BLDMOD >> 6) & 3) != 0; CPUUpdateRender(); break; case 0x52: COLEV = value & 0x1F1F; UPDATE_REG(0x52, COLEV); break; case 0x54: COLY = value & 0x1F; UPDATE_REG(0x54, COLY); break; case 0x60: case 0x62: case 0x64: case 0x68: case 0x6c: case 0x70: case 0x72: case 0x74: case 0x78: case 0x7c: case 0x80: case 0x84: soundEvent(address & 0xFF, (u8)(value & 0xFF)); soundEvent((address & 0xFF) + 1, (u8)(value >> 8)); break; case 0x82: case 0x88: case 0xa0: case 0xa2: case 0xa4: case 0xa6: case 0x90: case 0x92: case 0x94: case 0x96: case 0x98: case 0x9a: case 0x9c: case 0x9e: soundEvent(address & 0xFF, value); break; case 0xB0: DM0SAD_L = value; UPDATE_REG(0xB0, DM0SAD_L); break; case 0xB2: DM0SAD_H = value & 0x07FF; UPDATE_REG(0xB2, DM0SAD_H); break; case 0xB4: DM0DAD_L = value; UPDATE_REG(0xB4, DM0DAD_L); break; case 0xB6: DM0DAD_H = value & 0x07FF; UPDATE_REG(0xB6, DM0DAD_H); break; case 0xB8: DM0CNT_L = value & 0x3FFF; UPDATE_REG(0xB8, 0); break; case 0xBA: { bool start = ((DM0CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM0CNT_H = value; UPDATE_REG(0xBA, DM0CNT_H); if (start && (value & 0x8000)) { dma0Source = DM0SAD_L | (DM0SAD_H << 16); dma0Dest = DM0DAD_L | (DM0DAD_H << 16); CPUCheckDMA(0, 1); } break; } case 0xBC: DM1SAD_L = value; UPDATE_REG(0xBC, DM1SAD_L); break; case 0xBE: DM1SAD_H = value & 0x0FFF; UPDATE_REG(0xBE, DM1SAD_H); break; case 0xC0: DM1DAD_L = value; UPDATE_REG(0xC0, DM1DAD_L); break; case 0xC2: DM1DAD_H = value & 0x07FF; UPDATE_REG(0xC2, DM1DAD_H); break; case 0xC4: DM1CNT_L = value & 0x3FFF; UPDATE_REG(0xC4, 0); break; case 0xC6: { bool start = ((DM1CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM1CNT_H = value; UPDATE_REG(0xC6, DM1CNT_H); if (start && (value & 0x8000)) { dma1Source = DM1SAD_L | (DM1SAD_H << 16); dma1Dest = DM1DAD_L | (DM1DAD_H << 16); CPUCheckDMA(0, 2); } break; } case 0xC8: DM2SAD_L = value; UPDATE_REG(0xC8, DM2SAD_L); break; case 0xCA: DM2SAD_H = value & 0x0FFF; UPDATE_REG(0xCA, DM2SAD_H); break; case 0xCC: DM2DAD_L = value; UPDATE_REG(0xCC, DM2DAD_L); break; case 0xCE: DM2DAD_H = value & 0x07FF; UPDATE_REG(0xCE, DM2DAD_H); break; case 0xD0: DM2CNT_L = value & 0x3FFF; UPDATE_REG(0xD0, 0); break; case 0xD2: { bool start = ((DM2CNT_H ^ value) & 0x8000) ? true : false; value &= 0xF7E0; DM2CNT_H = value; UPDATE_REG(0xD2, DM2CNT_H); if (start && (value & 0x8000)) { dma2Source = DM2SAD_L | (DM2SAD_H << 16); dma2Dest = DM2DAD_L | (DM2DAD_H << 16); CPUCheckDMA(0, 4); } break; } case 0xD4: DM3SAD_L = value; UPDATE_REG(0xD4, DM3SAD_L); break; case 0xD6: DM3SAD_H = value & 0x0FFF; UPDATE_REG(0xD6, DM3SAD_H); break; case 0xD8: DM3DAD_L = value; UPDATE_REG(0xD8, DM3DAD_L); break; case 0xDA: DM3DAD_H = value & 0x0FFF; UPDATE_REG(0xDA, DM3DAD_H); break; case 0xDC: DM3CNT_L = value; UPDATE_REG(0xDC, 0); break; case 0xDE: { bool start = ((DM3CNT_H ^ value) & 0x8000) ? true : false; value &= 0xFFE0; DM3CNT_H = value; UPDATE_REG(0xDE, DM3CNT_H); if (start && (value & 0x8000)) { dma3Source = DM3SAD_L | (DM3SAD_H << 16); dma3Dest = DM3DAD_L | (DM3DAD_H << 16); CPUCheckDMA(0, 8); } break; } case 0x100: timer0Reload = value; interp_rate(); break; case 0x102: timer0Value = value; timerOnOffDelay |= 1; cpuNextEvent = cpuTotalTicks; break; case 0x104: timer1Reload = value; interp_rate(); break; case 0x106: timer1Value = value; timerOnOffDelay |= 2; cpuNextEvent = cpuTotalTicks; break; case 0x108: timer2Reload = value; break; case 0x10A: timer2Value = value; timerOnOffDelay |= 4; cpuNextEvent = cpuTotalTicks; break; case 0x10C: timer3Reload = value; break; case 0x10E: timer3Value = value; timerOnOffDelay |= 8; cpuNextEvent = cpuTotalTicks; break; case 0x128: if (value & 0x80) { value &= 0xff7f; if (value & 1 && (value & 0x4000)) { UPDATE_REG(0x12a, 0xFF); IF |= 0x80; UPDATE_REG(0x202, IF); value &= 0x7f7f; } } UPDATE_REG(0x128, value); break; case 0x130: P1 |= (value & 0x3FF); UPDATE_REG(0x130, P1); break; case 0x132: UPDATE_REG(0x132, value & 0xC3FF); break; case 0x200: IE = value & 0x3FFF; UPDATE_REG(0x200, IE); if ((IME & 1) && (IF & IE) && armIrqEnable) cpuNextEvent = cpuTotalTicks; break; case 0x202: IF ^= (value & IF); UPDATE_REG(0x202, IF); break; case 0x204: { memoryWait[0x0e] = memoryWaitSeq[0x0e] = gamepakRamWaitState[value & 3]; if (!speedHack) { memoryWait[0x08] = memoryWait[0x09] = gamepakWaitState[(value >> 2) & 3]; memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = gamepakWaitState0[(value >> 4) & 1]; memoryWait[0x0a] = memoryWait[0x0b] = gamepakWaitState[(value >> 5) & 3]; memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = gamepakWaitState1[(value >> 7) & 1]; memoryWait[0x0c] = memoryWait[0x0d] = gamepakWaitState[(value >> 8) & 3]; memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = gamepakWaitState2[(value >> 10) & 1]; } else { memoryWait[0x08] = memoryWait[0x09] = 3; memoryWaitSeq[0x08] = memoryWaitSeq[0x09] = 1; memoryWait[0x0a] = memoryWait[0x0b] = 3; memoryWaitSeq[0x0a] = memoryWaitSeq[0x0b] = 1; memoryWait[0x0c] = memoryWait[0x0d] = 3; memoryWaitSeq[0x0c] = memoryWaitSeq[0x0d] = 1; } for (int i = 8; i < 15; i++) { memoryWait32[i] = memoryWait[i] + memoryWaitSeq[i] + 1; memoryWaitSeq32[i] = memoryWaitSeq[i] * 2 + 1; } if ((value & 0x4000) == 0x4000) { busPrefetchEnable = true; busPrefetch = false; busPrefetchCount = 0; } else { busPrefetchEnable = false; busPrefetch = false; busPrefetchCount = 0; } UPDATE_REG(0x204, value & 0x7FFF); } break; case 0x208: IME = value & 1; UPDATE_REG(0x208, IME); if ((IME & 1) && (IF & IE) && armIrqEnable) cpuNextEvent = cpuTotalTicks; break; case 0x300: if (value != 0) value &= 0xFFFE; UPDATE_REG(0x300, value); break; default: UPDATE_REG(address & 0x3FE, value); break; } } void applyTimer() { if (timerOnOffDelay & 1) { timer0ClockReload = TIMER_TICKS[timer0Value & 3]; if (!timer0On && (timer0Value & 0x80)) { // reload the counter TM0D = timer0Reload; timer0Ticks = (0x10000 - TM0D) << timer0ClockReload; UPDATE_REG(0x100, TM0D); } timer0On = timer0Value & 0x80 ? true : false; TM0CNT = timer0Value & 0xC7; interp_rate(); UPDATE_REG(0x102, TM0CNT); // CPUUpdateTicks(); } if (timerOnOffDelay & 2) { timer1ClockReload = TIMER_TICKS[timer1Value & 3]; if (!timer1On && (timer1Value & 0x80)) { // reload the counter TM1D = timer1Reload; timer1Ticks = (0x10000 - TM1D) << timer1ClockReload; UPDATE_REG(0x104, TM1D); } timer1On = timer1Value & 0x80 ? true : false; TM1CNT = timer1Value & 0xC7; interp_rate(); UPDATE_REG(0x106, TM1CNT); } if (timerOnOffDelay & 4) { timer2ClockReload = TIMER_TICKS[timer2Value & 3]; if (!timer2On && (timer2Value & 0x80)) { // reload the counter TM2D = timer2Reload; timer2Ticks = (0x10000 - TM2D) << timer2ClockReload; UPDATE_REG(0x108, TM2D); } timer2On = timer2Value & 0x80 ? true : false; TM2CNT = timer2Value & 0xC7; UPDATE_REG(0x10A, TM2CNT); } if (timerOnOffDelay & 8) { timer3ClockReload = TIMER_TICKS[timer3Value & 3]; if (!timer3On && (timer3Value & 0x80)) { // reload the counter TM3D = timer3Reload; timer3Ticks = (0x10000 - TM3D) << timer3ClockReload; UPDATE_REG(0x10C, TM3D); } timer3On = timer3Value & 0x80 ? true : false; TM3CNT = timer3Value & 0xC7; UPDATE_REG(0x10E, TM3CNT); } cpuNextEvent = CPUUpdateTicks(); timerOnOffDelay = 0; } void CPULoadInternalBios() { // load internal BIOS #ifdef WORDS_BIGENDIAN for (size_t i = 0; i < sizeof(myROM) / 4; ++i) { WRITE32LE(&bios[i], myROM[i]); } #else memcpy(bios, myROM, sizeof(myROM)); #endif } void CPUInit() { biosProtected[0] = 0x00; biosProtected[1] = 0xf0; biosProtected[2] = 0x29; biosProtected[3] = 0xe1; int i = 0; for (i = 0; i < 256; i++) { int cpuBitSetCount = 0; int j; for (j = 0; j < 8; j++) if (i & (1 << j)) cpuBitSetCount++; cpuBitsSet[i] = cpuBitSetCount; for (j = 0; j < 8; j++) if (i & (1 << j)) break; cpuLowestBitSet[i] = j; } for (i = 0; i < 0x400; i++) ioReadable[i] = true; for (i = 0x10; i < 0x48; i++) ioReadable[i] = false; for (i = 0x4c; i < 0x50; i++) ioReadable[i] = false; for (i = 0x54; i < 0x60; i++) ioReadable[i] = false; for (i = 0x8c; i < 0x90; i++) ioReadable[i] = false; for (i = 0xa0; i < 0xb8; i++) ioReadable[i] = false; for (i = 0xbc; i < 0xc4; i++) ioReadable[i] = false; for (i = 0xc8; i < 0xd0; i++) ioReadable[i] = false; for (i = 0xd4; i < 0xdc; i++) ioReadable[i] = false; for (i = 0xe0; i < 0x100; i++) ioReadable[i] = false; for (i = 0x110; i < 0x120; i++) ioReadable[i] = false; for (i = 0x12c; i < 0x130; i++) ioReadable[i] = false; for (i = 0x138; i < 0x140; i++) ioReadable[i] = false; for (i = 0x144; i < 0x150; i++) ioReadable[i] = false; for (i = 0x15c; i < 0x200; i++) ioReadable[i] = false; for (i = 0x20c; i < 0x300; i++) ioReadable[i] = false; for (i = 0x304; i < 0x400; i++) ioReadable[i] = false; if (romSize < 0x1fe2000) { *((u16 *)&rom[0x1fe209c]) = 0xdffa; // SWI 0xFA *((u16 *)&rom[0x1fe209e]) = 0x4770; // BX LR } else { agbPrintEnable(false); } gbaSaveType = 0; eepromInUse = 0; saveType = 0; } void CPUReset() { systemReset(); if (gbaSaveType == 0) { if (eepromInUse) gbaSaveType = 3; else switch (saveType) { case 1: gbaSaveType = 1; break; case 2: gbaSaveType = 2; break; } } // clean picture memset(pix, 0, 4 * 241 * 162); // clean registers memset(&reg[0], 0, sizeof(reg)); // clean OAM memset(oam, 0, 0x400); // clean palette memset(paletteRAM, 0, 0x400); // clean vram memset(vram, 0, 0x20000); // clean io memory memset(ioMem, 0, 0x400); DISPCNT = 0x0080; DISPSTAT = 0x0000; VCOUNT = (useBios && !skipBios) ? 0 : 0x007E; BG0CNT = 0x0000; BG1CNT = 0x0000; BG2CNT = 0x0000; BG3CNT = 0x0000; BG0HOFS = 0x0000; BG0VOFS = 0x0000; BG1HOFS = 0x0000; BG1VOFS = 0x0000; BG2HOFS = 0x0000; BG2VOFS = 0x0000; BG3HOFS = 0x0000; BG3VOFS = 0x0000; BG2PA = 0x0100; BG2PB = 0x0000; BG2PC = 0x0000; BG2PD = 0x0100; BG2X_L = 0x0000; BG2X_H = 0x0000; BG2Y_L = 0x0000; BG2Y_H = 0x0000; BG3PA = 0x0100; BG3PB = 0x0000; BG3PC = 0x0000; BG3PD = 0x0100; BG3X_L = 0x0000; BG3X_H = 0x0000; BG3Y_L = 0x0000; BG3Y_H = 0x0000; WIN0H = 0x0000; WIN1H = 0x0000; WIN0V = 0x0000; WIN1V = 0x0000; WININ = 0x0000; WINOUT = 0x0000; MOSAIC = 0x0000; BLDMOD = 0x0000; COLEV = 0x0000; COLY = 0x0000; DM0SAD_L = 0x0000; DM0SAD_H = 0x0000; DM0DAD_L = 0x0000; DM0DAD_H = 0x0000; DM0CNT_L = 0x0000; DM0CNT_H = 0x0000; DM1SAD_L = 0x0000; DM1SAD_H = 0x0000; DM1DAD_L = 0x0000; DM1DAD_H = 0x0000; DM1CNT_L = 0x0000; DM1CNT_H = 0x0000; DM2SAD_L = 0x0000; DM2SAD_H = 0x0000; DM2DAD_L = 0x0000; DM2DAD_H = 0x0000; DM2CNT_L = 0x0000; DM2CNT_H = 0x0000; DM3SAD_L = 0x0000; DM3SAD_H = 0x0000; DM3DAD_L = 0x0000; DM3DAD_H = 0x0000; DM3CNT_L = 0x0000; DM3CNT_H = 0x0000; TM0D = 0x0000; TM0CNT = 0x0000; TM1D = 0x0000; TM1CNT = 0x0000; TM2D = 0x0000; TM2CNT = 0x0000; TM3D = 0x0000; TM3CNT = 0x0000; P1 = 0x03FF; IE = 0x0000; IF = 0x0000; IME = 0x0000; armMode = 0x1F; armState = true; if (cpuIsMultiBoot) { reg[13].I = 0x03007F00; reg[15].I = 0x02000000; reg[16].I = 0x00000000; reg[R13_IRQ].I = 0x03007FA0; reg[R13_SVC].I = 0x03007FE0; armIrqEnable = true; } else { if (useBios && !skipBios) { reg[15].I = 0x00000000; armMode = 0x13; armIrqEnable = false; } else { reg[13].I = 0x03007F00; reg[15].I = 0x08000000; reg[16].I = 0x00000000; reg[R13_IRQ].I = 0x03007FA0; reg[R13_SVC].I = 0x03007FE0; armIrqEnable = true; } } C_FLAG = V_FLAG = N_FLAG = Z_FLAG = false; UPDATE_REG(0x00, DISPCNT); UPDATE_REG(0x06, VCOUNT); UPDATE_REG(0x20, BG2PA); UPDATE_REG(0x26, BG2PD); UPDATE_REG(0x30, BG3PA); UPDATE_REG(0x36, BG3PD); UPDATE_REG(0x130, P1); UPDATE_REG(0x88, 0x200); // disable FIQ reg[16].I |= 0x40; CPUUpdateCPSR(); armNextPC = reg[15].I; reg[15].I += 4; // reset internal state intState = false; stopState = false; holdState = false; holdType = 0; biosProtected[0] = 0x00; biosProtected[1] = 0xf0; biosProtected[2] = 0x29; biosProtected[3] = 0xe1; lcdTicks = (useBios && !skipBios) ? 1008 : 208; timer0On = false; timer0Ticks = 0; timer0Reload = 0; timer0ClockReload = 0; timer1On = false; timer1Ticks = 0; timer1Reload = 0; timer1ClockReload = 0; timer2On = false; timer2Ticks = 0; timer2Reload = 0; timer2ClockReload = 0; timer3On = false; timer3Ticks = 0; timer3Reload = 0; timer3ClockReload = 0; dma0Source = 0; dma0Dest = 0; dma1Source = 0; dma1Dest = 0; dma2Source = 0; dma2Dest = 0; dma3Source = 0; dma3Dest = 0; cpuSaveGameFunc = flashSaveDecide; renderLine = mode0RenderLine; fxOn = false; windowOn = false; saveType = 0; layerEnable = DISPCNT & layerSettings; CPUUpdateRenderBuffers(true); for (int i = 0; i < 256; i++) { memoryMap[i].address = (u8 *)&dummyAddress; memoryMap[i].mask = 0; } memoryMap[0].address = bios; memoryMap[0].mask = 0x3FFF; memoryMap[2].address = workRAM; memoryMap[2].mask = 0x3FFFF; memoryMap[3].address = internalRAM; memoryMap[3].mask = 0x7FFF; memoryMap[4].address = ioMem; memoryMap[4].mask = 0x3FF; memoryMap[5].address = paletteRAM; memoryMap[5].mask = 0x3FF; memoryMap[6].address = vram; memoryMap[6].mask = 0x1FFFF; memoryMap[7].address = oam; memoryMap[7].mask = 0x3FF; memoryMap[8].address = rom; memoryMap[8].mask = 0x1FFFFFF; memoryMap[9].address = rom; memoryMap[9].mask = 0x1FFFFFF; memoryMap[10].address = rom; memoryMap[10].mask = 0x1FFFFFF; memoryMap[12].address = rom; memoryMap[12].mask = 0x1FFFFFF; memoryMap[14].address = flashSaveMemory; memoryMap[14].mask = 0xFFFF; eepromReset(); flashReset(); rtcReset(); CPUUpdateWindow0(); CPUUpdateWindow1(); // make sure registers are correctly initialized if not using BIOS if (!useBios) { if (cpuIsMultiBoot) BIOS_RegisterRamReset(0xfe); else BIOS_RegisterRamReset(0xff); } else { if (cpuIsMultiBoot) BIOS_RegisterRamReset(0xfe); } switch (cpuSaveType) { case 0: // automatic cpuSramEnabled = true; cpuFlashEnabled = true; cpuEEPROMEnabled = true; cpuEEPROMSensorEnabled = false; saveType = gbaSaveType = 0; break; case 1: // EEPROM cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = true; cpuEEPROMSensorEnabled = false; saveType = gbaSaveType = 3; // EEPROM usage is automatically detected break; case 2: // SRAM cpuSramEnabled = true; cpuFlashEnabled = false; cpuEEPROMEnabled = false; cpuEEPROMSensorEnabled = false; cpuSaveGameFunc = sramDelayedWrite; // to insure we detect the write saveType = gbaSaveType = 1; break; case 3: // FLASH cpuSramEnabled = false; cpuFlashEnabled = true; cpuEEPROMEnabled = false; cpuEEPROMSensorEnabled = false; cpuSaveGameFunc = flashDelayedWrite; // to insure we detect the write saveType = gbaSaveType = 2; break; case 4: // EEPROM+Sensor cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = true; cpuEEPROMSensorEnabled = true; // EEPROM usage is automatically detected saveType = gbaSaveType = 3; break; case 5: // NONE cpuSramEnabled = false; cpuFlashEnabled = false; cpuEEPROMEnabled = false; cpuEEPROMSensorEnabled = false; // no save at all saveType = gbaSaveType = 5; break; } ARM_PREFETCH; cpuDmaHack = false; SWITicks = 0; IRQTicks = 0; soundReset(); systemRefreshScreen(); } void CPUInterrupt() { u32 PC = reg[15].I; bool savedState = armState; CPUSwitchMode(0x12, true, false); reg[14].I = PC; if (!savedState) reg[14].I += 2; reg[15].I = 0x18; armState = true; armIrqEnable = false; armNextPC = reg[15].I; reg[15].I += 4; ARM_PREFETCH; // if(!holdState) biosProtected[0] = 0x02; biosProtected[1] = 0xc0; biosProtected[2] = 0x5e; biosProtected[3] = 0xe5; } static inline void CPUDrawPixLine() { switch (systemColorDepth) { case 16: { u16 *dest = (u16 *)pix + 241 * (VCOUNT + 1); for (int x = 0; x < 240; ) { *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap16[lineMix[x++] & 0xFFFF]; } // for filters that read past the screen *dest++ = 0; break; } case 24: { u8 *dest = (u8 *)pix + 240 * VCOUNT * 3; for (int x = 0; x < 240; ) { *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; *((u32 *)dest) = systemColorMap32[lineMix[x++] & 0xFFFF]; dest += 3; } break; } case 32: { u32 *dest = (u32 *)pix + 241 * (VCOUNT + 1); for (int x = 0; x < 240; ) { *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; *dest++ = systemColorMap32[lineMix[x++] & 0xFFFF]; } break; } } } static inline u32 CPUGetUserInput() { // update joystick information systemReadJoypads(); u32 joy = systemGetJoypad(0, cpuEEPROMSensorEnabled); P1 = 0x03FF ^ (joy & 0x3FF); UPDATE_REG(0x130, P1); // HACK: some special "buttons" extButtons = (joy >> 18); speedup = (extButtons & 1) != 0; return joy; } static inline void CPUBeforeEmulation() { if (newFrame) { CallRegisteredLuaFunctions(LUACALL_BEFOREEMULATION); u32 joy = CPUGetUserInput(); // this seems wrong, but there are cases where the game // can enter the stop state without requesting an IRQ from // the joypad. // FIXME: where is the right place??? u16 P1CNT = READ16LE(((u16 *)&ioMem[0x132])); if ((P1CNT & 0x4000) || stopState) { u16 p1 = (0x3FF ^ P1) & 0x3FF; if (P1CNT & 0x8000) { if (p1 == (P1CNT & 0x3FF)) { IF |= 0x1000; UPDATE_REG(0x202, IF); } } else { if (p1 & P1CNT) { IF |= 0x1000; UPDATE_REG(0x202, IF); } } } //if (cpuEEPROMSensorEnabled) //systemUpdateMotionSensor(0); VBAMovieResetIfRequested(); newFrame = false; } } static inline void CPUFrameBoundaryWork() { // HACK: some special "buttons" if (cheatsEnabled) cheatsCheckKeys(P1 ^ 0x3FF, extButtons); systemFrameBoundaryWork(); } void CPULoop(int _ticks) { CPUBeforeEmulation(); int32 ticks = _ticks; int32 clockTicks; int32 timerOverflow = 0; bool newVideoFrame = false; // variable used by the CPU core cpuTotalTicks = 0; cpuNextEvent = CPUUpdateTicks(); if (cpuNextEvent > ticks) cpuNextEvent = ticks; #ifdef SDL cpuBreakLoop = false; #endif for (;;) { #ifndef FINAL_VERSION if (systemDebug) { if (systemDebug >= 10 && !holdState) { CPUUpdateCPSR(); #ifdef BKPT_SUPPORT if (debugger_last) { sprintf( buffer, "R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n", oldreg[0], oldreg[1], oldreg[2], oldreg[3], oldreg[4], oldreg[5], oldreg[6], oldreg[7], oldreg[8], oldreg[9], oldreg[10], oldreg[11], oldreg[12], oldreg[13], oldreg[14], oldreg[15], oldreg[16], oldreg[17]); } #endif sprintf( buffer, "R00=%08x R01=%08x R02=%08x R03=%08x R04=%08x R05=%08x R06=%08x R07=%08x R08=%08x" "R09=%08x R10=%08x R11=%08x R12=%08x R13=%08x R14=%08x R15=%08x R16=%08x R17=%08x\n", reg[0].I, reg[1].I, reg[2].I, reg[3].I, reg[4].I, reg[5].I, reg[6].I, reg[7].I, reg[8].I, reg[9].I, reg[10].I, reg[11].I, reg[12].I, reg[13].I, reg[14].I, reg[15].I, reg[16].I, reg[17].I); log(buffer); } else if (!holdState) { log("PC=%08x\n", armNextPC); } } #endif /* FINAL_VERSION */ if (!holdState && !SWITicks) { if (armState) { if (!armExecute()) return; } else { if (!thumbExecute()) return; } clockTicks = 0; } else clockTicks = CPUUpdateTicks(); cpuTotalTicks += clockTicks; if (cpuTotalTicks >= cpuNextEvent) { int32 remainingTicks = cpuTotalTicks - cpuNextEvent; if (SWITicks) { SWITicks -= clockTicks; if (SWITicks < 0) SWITicks = 0; } clockTicks = cpuNextEvent; cpuTotalTicks = 0; cpuDmaHack = false; updateLoop: if (IRQTicks) { IRQTicks -= clockTicks; if (IRQTicks < 0) IRQTicks = 0; } lcdTicks -= clockTicks; if (lcdTicks <= 0) { if (DISPSTAT & 1) // V-BLANK { // if in V-Blank mode, keep computing... if (DISPSTAT & 2) { lcdTicks += 1008; VCOUNT++; UPDATE_REG(0x06, VCOUNT); DISPSTAT &= 0xFFFD; UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } else { lcdTicks += 224; DISPSTAT |= 2; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 16) { IF |= 2; UPDATE_REG(0x202, IF); } } if (VCOUNT >= 228) //Reaching last line { DISPSTAT &= 0xFFFC; UPDATE_REG(0x04, DISPSTAT); VCOUNT = 0; UPDATE_REG(0x06, VCOUNT); CPUCompareVCOUNT(); } } else { if (DISPSTAT & 2) { // if in H-Blank, leave it and move to drawing mode VCOUNT++; UPDATE_REG(0x06, VCOUNT); lcdTicks += 1008; DISPSTAT &= 0xFFFD; if (VCOUNT == 160) { DISPSTAT |= 1; DISPSTAT &= 0xFFFD; UPDATE_REG(0x04, DISPSTAT); if (DISPSTAT & 0x0008) { IF |= 1; UPDATE_REG(0x202, IF); } CPUCheckDMA(1, 0x0f); newVideoFrame = true; } UPDATE_REG(0x04, DISPSTAT); CPUCompareVCOUNT(); } else { if (systemFrameDrawingRequired()) { (*renderLine)(); CPUDrawPixLine(); } // entering H-Blank DISPSTAT |= 2; UPDATE_REG(0x04, DISPSTAT); lcdTicks += 224; CPUCheckDMA(2, 0x0f); if (DISPSTAT & 16) { IF |= 2; UPDATE_REG(0x202, IF); } } } } // we shouldn't be doing sound in stop state, but we lose synchronization // if sound is disabled, so in stop state, soundTick will just produce // mute sound soundTicks -= clockTicks; if (soundTicks <= 0) { soundTick(); soundTicks += soundTickStep; } if (!stopState) { if (timer0On) { timer0Ticks -= clockTicks; if (timer0Ticks <= 0) { timer0Ticks += (0x10000 - timer0Reload) << timer0ClockReload; timerOverflow |= 1; soundTimerOverflow(0); if (TM0CNT & 0x40) { IF |= 0x08; UPDATE_REG(0x202, IF); } } TM0D = 0xFFFF - (timer0Ticks >> timer0ClockReload) & 0xFFFF; UPDATE_REG(0x100, TM0D); } if (timer1On) { if (TM1CNT & 4) { if (timerOverflow & 1) { TM1D++; if (TM1D == 0) { TM1D += timer1Reload; timerOverflow |= 2; soundTimerOverflow(1); if (TM1CNT & 0x40) { IF |= 0x10; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x104, TM1D); } } else { timer1Ticks -= clockTicks; if (timer1Ticks <= 0) { timer1Ticks += (0x10000 - timer1Reload) << timer1ClockReload; timerOverflow |= 2; soundTimerOverflow(1); if (TM1CNT & 0x40) { IF |= 0x10; UPDATE_REG(0x202, IF); } } TM1D = 0xFFFF - (timer1Ticks >> timer1ClockReload) & 0xFFFF; UPDATE_REG(0x104, TM1D); } } if (timer2On) { if (TM2CNT & 4) { if (timerOverflow & 2) { TM2D++; if (TM2D == 0) { TM2D += timer2Reload; timerOverflow |= 4; if (TM2CNT & 0x40) { IF |= 0x20; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x108, TM2D); } } else { timer2Ticks -= clockTicks; if (timer2Ticks <= 0) { timer2Ticks += (0x10000 - timer2Reload) << timer2ClockReload; timerOverflow |= 4; if (TM2CNT & 0x40) { IF |= 0x20; UPDATE_REG(0x202, IF); } } TM2D = 0xFFFF - (timer2Ticks >> timer2ClockReload) & 0xFFFF; UPDATE_REG(0x108, TM2D); } } if (timer3On) { if (TM3CNT & 4) { if (timerOverflow & 4) { TM3D++; if (TM3D == 0) { TM3D += timer3Reload; if (TM3CNT & 0x40) { IF |= 0x40; UPDATE_REG(0x202, IF); } } UPDATE_REG(0x10C, TM3D); } } else { timer3Ticks -= clockTicks; if (timer3Ticks <= 0) { timer3Ticks += (0x10000 - timer3Reload) << timer3ClockReload; if (TM3CNT & 0x40) { IF |= 0x40; UPDATE_REG(0x202, IF); } } TM3D = 0xFFFF - (timer3Ticks >> timer3ClockReload) & 0xFFFF; UPDATE_REG(0x10C, TM3D); } } } timerOverflow = 0; #ifdef PROFILING profilingTicks -= clockTicks; if (profilingTicks <= 0) { profilingTicks += profilingTicksReload; if (profilSegment) { profile_segment *seg = profilSegment; do { u16 *b = (u16 *)seg->sbuf; int pc = ((reg[15].I - seg->s_lowpc) * seg->s_scale) / 0x10000; if (pc >= 0 && pc < seg->ssiz) { b[pc]++; break; } seg = seg->next; } while (seg); } } #endif if (newVideoFrame) { newVideoFrame = false; CPUFrameBoundaryWork(); } ticks -= clockTicks; cpuNextEvent = CPUUpdateTicks(); if (cpuDmaTicksToUpdate > 0) { if (cpuDmaTicksToUpdate > cpuNextEvent) clockTicks = cpuNextEvent; else clockTicks = cpuDmaTicksToUpdate; cpuDmaTicksToUpdate -= clockTicks; cpuDmaHack = true; goto updateLoop; // this is evil } if (IF && (IME & 1) && armIrqEnable) { int res = IF & IE; if (stopState) res &= 0x3080; if (res) { if (intState) { if (!IRQTicks) { CPUInterrupt(); intState = false; holdState = false; stopState = false; holdType = 0; } } else { if (!holdState) { intState = true; IRQTicks = 7; if (cpuNextEvent > IRQTicks) cpuNextEvent = IRQTicks; } else { CPUInterrupt(); holdState = false; stopState = false; holdType = 0; } } // Stops the SWI Ticks emulation if an IRQ is executed //(to avoid problems with nested IRQ/SWI) if (SWITicks) SWITicks = 0; } } if (remainingTicks > 0) { if (remainingTicks > cpuNextEvent) clockTicks = cpuNextEvent; else clockTicks = remainingTicks; remainingTicks -= clockTicks; goto updateLoop; // this is evil, too } if (timerOnOffDelay) applyTimer(); //if (cpuNextEvent > ticks) // FIXME: can be negative and slow down // cpuNextEvent = ticks; #ifdef SDL if (newFrame || useOldFrameTiming && ticks <= 0 || cpuBreakLoop) #else if (newFrame || useOldFrameTiming && ticks <= 0) #endif { break; } } } } struct EmulatedSystem GBASystem = { // emuMain CPULoop, // emuReset CPUReset, // emuCleanUp CPUCleanUp, // emuReadBattery CPUReadBatteryFile, // emuWriteBattery CPUWriteBatteryFile, // emuReadBatteryFromStream CPUReadBatteryFromStream, // emuWriteBatteryToStream CPUWriteBatteryToStream, // emuReadState CPUReadState, // emuWriteState CPUWriteState, // emuReadStateFromStream CPUReadStateFromStream, // emuWriteStateToStream CPUWriteStateToStream, // emuReadMemState CPUReadMemState, // emuWriteMemState CPUWriteMemState, // emuWritePNG CPUWritePNGFile, // emuWriteBMP CPUWriteBMPFile, // emuUpdateCPSR CPUUpdateCPSR, // emuHasDebugger true, // emuCount #ifdef FINAL_VERSION 250000, #else 5000, #endif };
TASVideos/vba-rerecording
src/gba/V8/GBA.cpp
C++
gpl-2.0
91,319
using UnityEngine; using System.Collections; [RequireComponent(typeof(SpriteRenderer))] public class SpriteRandomiser : MonoBehaviour { [System.Serializable] public class PossibleState { public Sprite texture = null; public Color color = Color.white; }; public PossibleState[] possibleStates = new PossibleState[0]; public void RandomiseSprite() { Random.seed = (int)Time.time; if(possibleStates.Length > 0) { PossibleState state = possibleStates[Random.Range(0,possibleStates.Length)]; SpriteRenderer spriteRenderer = GetComponent<Renderer>() as SpriteRenderer; spriteRenderer.sprite = state.texture; spriteRenderer.color = state.color; } } // Use this for initialization void Start () { RandomiseSprite(); } }
Almax27/LD31
Assets/Scripts/Utility/SpriteRandomiser.cs
C#
gpl-2.0
759
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppTestDeployment")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AppTestDeployment")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
EpicPonyTeam/RarityUpdater
AppTestDeployment/Properties/AssemblyInfo.cs
C#
gpl-2.0
2,393
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include head.html %} </head> <body id="post"> {% include navigation.html %} <div id="main" role="main"> <article class="hentry"> {% if page.image.feature %}<img src="{{ site.url }}/images/{{ page.image.feature }}" class="entry-feature-image" alt="{{ page.title }}">{% if page.image.credit %}<p class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a>{% endif %}{% endif %} <div class="entry-wrapper"> <header class="entry-header"> <span class="entry-tags">{% for tag in page.tags %}<a href="{{ site.url }}/tags.html#{{ tag | cgi_encode }}" title="Pages tagged {{ tag }}">{{ tag }}</a>{% unless forloop.last %}&nbsp;&bull;&nbsp;{% endunless %}{% endfor %}</span> {% if page.link %} <h1 class="entry-title"><a href="{{ page.link }}">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %} <span class="link-arrow">&rarr;</span></a></h1> {% else %} <h1 class="entry-title">{% if page.headline %}{{ page.headline }}{% else %}{{ page.title }}{% endif %}</h1> {% endif %} </header> <footer class="entry-meta"> <img src="{{ site.url }}/images/{{ site.owner.avatar }}" alt="{{ site.owner.name }} photo" class="author-photo"> <span class="author vcard">By <span class="fn"><a href="{{ site.url }}/about/" title="About {{ site.owner.name }}">{{ site.owner.name }}</a></span></span> <span class="entry-date date published"><time datetime="{{ page.date | date_to_xmlschema }}"><i class="icon-calendar-empty"></i> {{ page.date | date: "%B %d, %Y" }}</time></span> {% if page.modified %}<span class="entry-date date modified"><time datetime="{{ page.modified }}"><i class="icon-pencil"></i> {{ page.modified | date: "%B %d, %Y" }}</time></span>{% endif %} {% if site.disqus_shortname and page.comments %}<span class="entry-comments"><i class="icon-comment-alt"></i> <a href="#disqus_thread">Comment</a></span>{% endif %} <span><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}"><i class="icon-link"></i> Permalink</a></span> {% if page.share %} <span class="social-share-facebook"> <a href="https://www.facebook.com/sharer/sharer.php?u={{ site.url }}{{ page.url }}" title="Share on Facebook" itemprop="Facebook"><i class="icon-facebook-sign"></i> Like</a></span> <span class="social-share-twitter"> <a href="https://twitter.com/intent/tweet?text={{ site.url }}{{ page.url }}" title="Share on Twitter" itemprop="Twitter"><i class="icon-twitter-sign"></i> Tweet</a></span> <span class="social-share-googleplus"> <a href="https://plus.google.com/share?url={{ site.url }}{{ page.url }}" title="Share on Google Plus" itemprop="GooglePlus"><i class="icon-google-plus-sign"></i> +1</a></span> <!-- /.social-share -->{% endif %} </footer> <div class="entry-content"> {{ content }} {% if site.disqus_shortname and page.comments %}<div id="disqus_thread"></div><!-- /#disqus_thread -->{% endif %} </div><!-- /.entry-content --> </div><!-- /.entry-wrapper --> <nav class="pagination" role="navigation"> {% if page.previous %} <a href="{{ site.url }}{{ page.previous.url }}" class="btn" title="{{ page.previous.title }}">Previous article</a> {% endif %} {% if page.next %} <a href="{{ site.url }}{{ page.next.url }}" class="btn" title="{{ page.next.title }}">Next article</a> {% endif %} </nav><!-- /.pagination --> </article> </div><!-- /#main --> <div class="footer-wrapper"> <footer role="contentinfo"> {% include footer.html %} </footer> </div><!-- /.footer-wrapper --> {% include scripts.html %} </body> </html>
junjiemao/junjiemao.github.com
stage/_layouts/post.html
HTML
gpl-2.0
4,146
using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Session; using System.Threading.Tasks; using MediaBrowser.Model.Services; namespace MediaBrowser.Controller.Net { public interface ISessionContext { Task<SessionInfo> GetSession(object requestContext); Task<User> GetUser(object requestContext); Task<SessionInfo> GetSession(IRequest requestContext); Task<User> GetUser(IRequest requestContext); } }
jose-pr/Emby
MediaBrowser.Controller/Net/ISessionContext.cs
C#
gpl-2.0
469
/* About Css */ body { -webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */ -webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */ -webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */ background: #333333; background-attachment:fixed; font-family:'HelveticaNeue-Light', 'HelveticaNeue', Helvetica, Arial, sans-serif; font-size:12px; height:100%; margin:0px; padding:0px; width:100%; } /* Portrait layout (default) */ .app { height:250px; width:300px; margin:30px; } /* Landscape layout (with min-width) */ @media screen and (min-aspect-ratio: 1/1) and (min-width:400px) { .app { margin-left:160px; } } h1{ font-size:30px; font-weight:normal; margin:0px; overflow:visible; padding:0px; text-align:center; color:#FEFEFE; } .button{ background:#9f9f9f; border-radius:10px; margin:auto; text-align:center; text-decoration:none; border:#8f8f8f solid 1px; } .button p{ color:#fefefe; text-align:center; text-decoration:none; font-size:24px; padding:15px 0; margin:0; } .button:hover,.button:active{ background:#6f6f6f; color:#efefef; } .back{ margin-left:-25px; margin-right:15px; color:#fefefe; font-size:20px; padding:10px; background-color: #428bca; border-color: #357ebd; } .back:hover,.back:active{ background-color: #3071a9; border-color: #285e8e; }
JaydenMajor/expence_tracker
www/css/aboutExpense.css
CSS
gpl-2.0
1,490
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #define MAX_SIZE 1010 int getarray(int a[]) { int i=0,count; scanf("%d",&count); for(; i<count ; i++) scanf("%d",&a[i]); return count; } int find(int a[], int n, int val) { int i,true=0; for(i=0; i<n; i++) { if(a[i]==val) { true=1; return i; } } if(true==0) return -1; } int main() { int cases, i; int arr[MAX_SIZE], size; int val, found = 0; scanf("%d", &cases); for(i = 1; i <= cases; i++) { size = getarray(arr); scanf("%d", &val); found = find(arr, size, val); if(found == -1) { printf("NOT FOUND\n"); continue; } printf("%d\n", found); } return 0; }
zning1994/practice
Program/CLanguage/exp/exp7/exA.c
C
gpl-2.0
890
<section id="options"> <?php $terms = array(); $vid = NULL; $vid_machine_name = 'portfolio_categories'; $vocabulary = taxonomy_vocabulary_machine_name_load($vid_machine_name); if (!empty($vocabulary->vid)) { $vid = $vocabulary->vid; } if (!empty($vid)) { $terms = taxonomy_get_tree($vid); } ?> <ul id="filters" class="option-set right" data-option-key="filter"> <li><a href="#filter" data-option-value="*" class="button small selected"><?php print t('Show All'); ?></a></li> <?php if (!empty($terms)): ?> <?php foreach ($terms as $term): ?> <li><a href="#filter" data-option-value=".tid-<?php print $term->tid; ?>" class="button small"><?php print $term->name; ?></a></li> <?php endforeach; ?> <?php endif; ?> </ul> </section>
emperorcow/chaosbrewclub
sites/all/modules/tabvn/portfolio/portfolio_filter.tpl.php
PHP
gpl-2.0
791
/** * jBorZoi - An Elliptic Curve Cryptography Library * * Copyright (C) 2003 Dragongate Technologies Ltd. * * 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, 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, write to the Free Software Foundation, * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.dragongate_technologies.borZoi; import java.math.BigInteger; import java.security.SecureRandom; /** * Elliptic Curve Private Keys consisting of two member variables: dp, * the EC domain parameters and s, the private key which must * be kept secret. * @author <a href="http://www.dragongate-technologies.com">Dragongate Technologies Ltd.</a> * @version 0.90 */ public class ECPrivKey { /** * The EC Domain Parameters */ public ECDomainParameters dp; /** * The Private Key */ public BigInteger s; /** * Generate a random private key with ECDomainParameters dp */ public ECPrivKey(ECDomainParameters dp) { this.dp = (ECDomainParameters) dp.clone(); SecureRandom rnd = new SecureRandom(); s = new BigInteger(dp.m, rnd); s = s.mod(dp.r); } /** * Generate a private key with ECDomainParameters dp * and private key s */ public ECPrivKey(ECDomainParameters dp, BigInteger s) { this.dp = dp; this.s = s; } public String toString() { String str = new String("dp: ").concat(dp.toString()).concat("\n"); str = str.concat("s: ").concat(s.toString()).concat("\n"); return str; } protected Object clone() { return new ECPrivKey(dp, s); } }
HateBreed/old-codes-from-studies
cryptoclient_in_java/com/dragongate_technologies/borZoi/ECPrivKey.java
Java
gpl-2.0
2,027
<!DOCTYPE html> <html xml:lang="en-US" lang="en-US" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-US"> <title>My Family Tree - Sanchez, John</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.2 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> <link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">My Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="IndividualDetail"> <h3>Sanchez, John<sup><small> <a href="#sref1">1</a></small></sup></h3> <div id="summaryarea"> <table class="infolist"> <tr> <td class="ColumnAttribute">Birth Name</td> <td class="ColumnValue"> Sanchez, John </td> </tr> <tr> <td class="ColumnAttribute">Gramps&nbsp;ID</td> <td class="ColumnValue">I0685</td> </tr> <tr> <td class="ColumnAttribute">Gender</td> <td class="ColumnValue">male</td> </tr> <tr> <td class="ColumnAttribute">Age at Death</td> <td class="ColumnValue">about 65 years</td> </tr> </table> </div> <div class="subsection" id="events"> <h4>Events</h4> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Birth </td> <td class="ColumnDate">about 1480</td> <td class="ColumnPlace"> <a href="../../../plc/l/v/II6KQCD2F8F42WXMVL.html" title="Phoenix, Maricopa, AZ, USA"> Phoenix, Maricopa, AZ, USA </a> </td> <td class="ColumnDescription"> Birth of Sanchez, John </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> <tr> <td class="ColumnEvent"> Death </td> <td class="ColumnDate">1545</td> <td class="ColumnPlace"> <a href="../../../plc/l/v/II6KQCD2F8F42WXMVL.html" title="Phoenix, Maricopa, AZ, USA"> Phoenix, Maricopa, AZ, USA </a> </td> <td class="ColumnDescription"> Death of Sanchez, John </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </div> <div class="subsection" id="parents"> <h4>Parents</h4> <table class="infolist"> <thead> <tr> <th class="ColumnAttribute">Relation to main person</th> <th class="ColumnValue">Name</th> <th class="ColumnValue">Relation within this family (if not by birth)</th> </tr> </thead> <tbody> </tbody> <tr> <td class="ColumnAttribute">Father</td> <td class="ColumnValue"> <a href="../../../ppl/b/c/4GGKQCM55ID425VACB.html">Molina, Robert<span class="grampsid"> [I1154]</span></a> </td> </tr> <tr> <td class="ColumnAttribute">&nbsp;&nbsp;&nbsp;&nbsp;</td> <td class="ColumnValue">&nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../ppl/e/0/9I6KQCF5N90G0VRI0E.html">Sanchez, John<span class="grampsid"> [I0685]</span></a></td> <td class="ColumnValue"></td> </tr> </table> </div> <div class="subsection" id="families"> <h4>Families</h4> <table class="infolist"> <tr class="BeginFamily"> <td class="ColumnType">&nbsp</td> <td class="ColumnAttribute">&nbsp</td> <td class="ColumnValue"><a href="" title="Family of Sanchez, John and Curtis, Margaret">Family of Sanchez, John and Curtis, Margaret<span class="grampsid"> [F0382]</span></a></td> </tr> <tr class="BeginFamily"> <td class="ColumnType">Married</td> <td class="ColumnAttribute">Wife</td> <td class="ColumnValue"> <a href="../../../ppl/j/h/4EGKQC200RACB7Y6HJ.html">Curtis, Margaret<span class="grampsid"> [I1150]</span></a> </td> </tr> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">&nbsp;</td> <td class="ColumnValue"> <table class="infolist eventlist"> <thead> <tr> <th class="ColumnEvent">Event</th> <th class="ColumnDate">Date</th> <th class="ColumnPlace">Place</th> <th class="ColumnDescription">Description</th> <th class="ColumnNotes">Notes</th> <th class="ColumnSources">Sources</th> </tr> </thead> <tbody> <tr> <td class="ColumnEvent"> Marriage </td> <td class="ColumnDate">&nbsp;</td> <td class="ColumnPlace"> <a href="../../../plc/l/8/OFGKQC9VTT55S65K8L.html" title="Deming, NM, USA"> Deming, NM, USA </a> </td> <td class="ColumnDescription"> Marriage of Sanchez, John and Curtis, Margaret </td> <td class="ColumnNotes"> <div> </div> </td> <td class="ColumnSources"> &nbsp; </td> </tr> </tbody> </table> </td> <tr> <td class="ColumnType">&nbsp;</td> <td class="ColumnAttribute">Children</td> <td class="ColumnValue"> <ol> <li> <a href="../../../ppl/z/7/2J6KQC39AHC9O4YD7Z.html">Lefebvre, Robert<span class="grampsid"> [I0686]</span></a> </li> </ol> </td> </tr> </tr> </table> </div> <div class="subsection" id="pedigree"> <h4>Pedigree</h4> <ol class="pedigreegen"> <li> <a href="../../../ppl/b/c/4GGKQCM55ID425VACB.html">Molina, Robert<span class="grampsid"> [I1154]</span></a> <ol> <li class="thisperson"> Sanchez, John <ol class="spouselist"> <li class="spouse"> <a href="../../../ppl/j/h/4EGKQC200RACB7Y6HJ.html">Curtis, Margaret<span class="grampsid"> [I1150]</span></a> <ol> <li> <a href="../../../ppl/z/7/2J6KQC39AHC9O4YD7Z.html">Lefebvre, Robert<span class="grampsid"> [I0686]</span></a> </li> </ol> </li> </ol> </li> </ol> </li> </ol> </div> <div class="subsection" id="tree"> <h4>Ancestors</h4> <div id="treeContainer" style="width:735px; height:602px;"> <div class="boxbg male AncCol0" style="top: 269px; left: 6px;"> <a class="noThumb" href="../../../ppl/e/0/9I6KQCF5N90G0VRI0E.html"> Sanchez, John </a> </div> <div class="shadow" style="top: 274px; left: 10px;"></div> <div class="bvline" style="top: 301px; left: 165px; width: 15px"></div> <div class="gvline" style="top: 306px; left: 165px; width: 20px"></div> <div class="boxbg male AncCol1" style="top: 119px; left: 196px;"> <a class="noThumb" href="../../../ppl/b/c/4GGKQCM55ID425VACB.html"> Molina, Robert </a> </div> <div class="shadow" style="top: 124px; left: 200px;"></div> <div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div> <div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div> <div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div> <div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div> <div class="bvline" style="top: 151px; left: 355px; width: 15px"></div> <div class="gvline" style="top: 156px; left: 355px; width: 20px"></div> <div class="boxbg male AncCol2" style="top: 44px; left: 386px;"> <a class="noThumb" href="../../../ppl/b/m/VGGKQC6Z87K666ENMB.html"> Guerrero, Robert </a> </div> <div class="shadow" style="top: 49px; left: 390px;"></div> <div class="bvline" style="top: 76px; left: 370px; width: 15px;"></div> <div class="gvline" style="top: 81px; left: 375px; width: 20px;"></div> <div class="bhline" style="top: 76px; left: 370px; height: 75px;"></div> <div class="gvline" style="top: 81px; left: 375px; height: 75px;"></div> <div class="bvline" style="top: 76px; left: 545px; width: 15px"></div> <div class="gvline" style="top: 81px; left: 545px; width: 20px"></div> <div class="boxbg male AncCol3" style="top: 7px; left: 576px;"> <a class="noThumb" href="../../../ppl/g/r/GHGKQCAPWR3J6XMRG.html"> Guerrero, Robert </a> </div> <div class="shadow" style="top: 12px; left: 580px;"></div> <div class="bvline" style="top: 39px; left: 560px; width: 15px;"></div> <div class="gvline" style="top: 44px; left: 565px; width: 20px;"></div> <div class="bhline" style="top: 39px; left: 560px; height: 37px;"></div> <div class="gvline" style="top: 44px; left: 565px; height: 37px;"></div> </div> </div> <div class="subsection" id="sourcerefs"> <h4>Source References</h4> <ol> <li> <a href="../../../src/x/a/X5TJQC9JXU4RKT6VAX.html" title="Import from test2.ged" name ="sref1"> Import from test2.ged <span class="grampsid"> [S0003]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.2 on 2015-12-25<br />Last change was the 2007-07-26 08:34:25 </p> <p id="copyright"> </p> </div> </body> </html>
belissent/testing-example-reports
gramps42/gramps/example_NAVWEB0/ppl/e/0/9I6KQCF5N90G0VRI0E.html
HTML
gpl-2.0
10,470
/* The GTKWorkbook Project <http://gtkworkbook.sourceforge.net/> Copyright (C) 2008, 2009 John Bellone, Jr. <[email protected]> This library 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 2.1 of the License, or (at your option) any later version. This library 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 PRACTICAL 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 the library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301 USA */ #include <sstream> #include <gdk/gdkkeysyms.h> #include <libgtkworkbook/workbook.h> #include <proactor/Proactor.hpp> #include <proactor/Event.hpp> #include <network/Tcp.hpp> #include "Realtime.hpp" using namespace realtime; /* @description: This method creates a filename with the prefix supplied and uses the pid of the process as its suffix. @pre: The prefix (should be a file path, obviously). */ static std::string AppendProcessId (const gchar * pre) { std::stringstream s; s << pre << getppid(); return s.str(); } static void StreamOpenDialogCallback (GtkWidget * w, gpointer data) { Realtime * rt = (Realtime *)data; OpenStreamDialog * dialog = rt->streamdialog(); if (dialog->widget == NULL) { dialog->rt = rt; dialog->widget = gtk_dialog_new_with_buttons ("Open stream ", GTK_WINDOW (rt->app()->gtkwindow()), (GtkDialogFlags) (GTK_DIALOG_MODAL|GTK_DIALOG_NO_SEPARATOR), GTK_STOCK_OK, GTK_RESPONSE_OK, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, NULL); GtkWidget * gtk_frame = gtk_frame_new ("Connection Options"); GtkWidget * hbox = gtk_hbox_new(FALSE, 0); GtkWidget * box = GTK_DIALOG (dialog->widget)->vbox; dialog->host_entry = gtk_entry_new(); dialog->port_entry = gtk_entry_new(); gtk_entry_set_max_length (GTK_ENTRY (dialog->host_entry), 15); gtk_entry_set_max_length (GTK_ENTRY (dialog->port_entry), 5); gtk_entry_set_width_chars (GTK_ENTRY (dialog->host_entry), 15); gtk_entry_set_width_chars (GTK_ENTRY (dialog->port_entry), 5); gtk_box_pack_start (GTK_BOX (hbox), dialog->host_entry, FALSE, FALSE, 0); gtk_box_pack_end (GTK_BOX (hbox), dialog->port_entry, FALSE, FALSE, 0); gtk_container_add (GTK_CONTAINER (gtk_frame), hbox); gtk_box_pack_start (GTK_BOX (box), gtk_frame, FALSE, FALSE, 0); g_signal_connect (G_OBJECT (dialog->widget), "delete-event", G_CALLBACK (gtk_widget_hide_on_delete), NULL); } gtk_widget_show_all ( dialog->widget ); if (gtk_dialog_run (GTK_DIALOG (dialog->widget)) == GTK_RESPONSE_OK) { const char * host_value = gtk_entry_get_text (GTK_ENTRY (dialog->host_entry)); const char * port_value = gtk_entry_get_text (GTK_ENTRY (dialog->port_entry)); Sheet * sheet = rt->workbook()->add_new_sheet (rt->workbook(), host_value, 100, 20); if (IS_NULLSTR (host_value) || IS_NULLSTR (port_value)) { g_warning ("One of requird values are empty"); } else if (sheet == NULL) { g_warning ("Cannot open connection to %s:%s because of failure to add sheet", host_value, port_value); } else if (rt->OpenTcpClient (sheet, host_value, atoi (port_value)) == false) { // STUB: Popup an alertbox about failing to connect? } else { // STUB: Success. Do we want to do anything else here? g_message ("Client connection opened on %s:%s on sheet %s", host_value, port_value, sheet->name); } } gtk_widget_hide_all ( dialog->widget ); } Realtime::Realtime (Application * appstate, Handle * platform) : Plugin (appstate, platform) { ConfigPair * logpath = appstate->config()->get_pair (appstate->config(), "realtime", "log", "path"); if (IS_NULL (logpath)) { g_critical ("Failed loading log->path from configuration file. Exiting application."); exit(1); } std::string logname = std::string (logpath->value).append("/"); logname.append (AppendProcessId("realtime.").append(".log")); if ((pktlog = fopen (logname.c_str(), "w")) == NULL) { g_critical ("Failed opening file '%s' for packet logging", logname.c_str()); } this->wb = workbook_open (appstate->gtkwindow(), "realtime"); this->packet_parser = NULL; this->tcp_server = NULL; } Realtime::~Realtime (void) { // Iterate through the list of active connections, and begin closing them. This should also // include deleting the pointers to all of the accepting threads. Eventually there should be // a boost::shared_ptr here so that we don't have to do the dirty work. ActiveThreads::iterator it = this->threads.begin(); while (it != this->threads.end()) { network::TcpSocket * socket = ((*it).first); concurrent::Thread * thread = ((*it).second); it = this->threads.erase (it); if (socket) delete socket; if (thread) { thread->stop(); delete thread; } } if (this->packet_parser) { this->packet_parser->stop(); delete this->packet_parser; } if (this->tcp_server) { this->tcp_server->stop(); delete this->tcp_server; } FCLOSE (this->pktlog); } bool Realtime::CreateNewServerConnection (network::TcpServerSocket * socket, AcceptThread * accept_thread) { this->threads.push_back ( ActiveThread (socket, accept_thread) ); if (this->tcp_server->addWorker (accept_thread) == false) { g_critical ("Failed starting accepting thread on socket %d", socket->getPort() ); return false; } return true; } bool Realtime::CreateNewClientConnection (network::TcpClientSocket * socket, CsvParser * csv, NetworkDispatcher * nd) { this->threads.push_back ( ActiveThread (socket, csv) ); this->threads.push_back ( ActiveThread (NULL, nd) ); // this is a hack ConnectionThread * reader = new ConnectionThread (socket); if (nd->addWorker (reader) == false) { g_critical ("Failed starting the client reader"); delete reader; return false; } this->threads.push_back ( ActiveThread (NULL, reader) ); // this is a hack return true; } bool Realtime::OpenTcpServer (int port) { // Has to be above the service ports. if (port < 1000) { g_warning ("Failed starting Tcp server: port (%d) must be above 1000", port); return false; } // The first time we attempt to create a port to receive input on we need to create a dispatcher, and // specify an event identifier so that we can communicate with it from workers. At this point the // Packet Parser is created as well. if (this->tcp_server == NULL) { int eventId = proactor::Event::uniqueEventId(); NetworkDispatcher * nd = new NetworkDispatcher (eventId); PacketParser * pp = new PacketParser (this->workbook(), this->pktlog, 0); if (nd->start() == false) { g_critical ("Failed starting network dispatcher for tcp server"); return false; } if (this->app()->proactor()->addWorker (eventId, pp) == false) { g_critical ("Failed starting packet parser for tcp server"); return false; } this->tcp_server = nd; this->packet_parser = pp; } network::TcpServerSocket * socket = new network::TcpServerSocket (port); if (socket->start(5) == false) { g_critical ("Failed starting network socket for tcp server on port %d", port); return false; } AcceptThread * accept_thread = new AcceptThread (socket->newAcceptor()); return this->CreateNewServerConnection (socket, accept_thread); } bool Realtime::OpenTcpClient (Sheet * sheet, const std::string & address, int port) { // Has to be above the service ports. if (port < 1000) { g_warning ("Failed starting Tcp client: port (%d) must be above 1000", port); return false; } // We need to create a network dispatcher for each one of these connections because of // the current limitation of the Proactor design. It really needs to be rewritten, but // that is a separate project in and of itself. For now a list of dispatchers must be // kept so that we do not lose track. int eventId = proactor::Event::uniqueEventId(); NetworkDispatcher * dispatcher = new NetworkDispatcher (eventId); if (dispatcher->start() == false) { g_critical ("Failed starting network dispatcher for %s:%d", address.c_str(), port); delete dispatcher; return false; } // Keeping this simple is the reason why we need multiple dispatchers. If I could come // up with a simple way to strap on the ability to have multiple sheets without the need // for an additioanl dispatcher/csv combo I would. It totally destroys the principle of // the proactor design. CsvParser * csv = new CsvParser (sheet, this->pktlog, 0); if (this->app()->proactor()->addWorker (eventId, csv) == false) { g_critical ("Failed starting csv parser and adding to proactor for %s:%d", address.c_str(), port); delete csv; delete dispatcher; return false; } network::TcpClientSocket * socket = new network::TcpClientSocket; if (socket->connect (address.c_str(), port) == false) { g_critical ("Failed making Tcp connection to %s:%d", address.c_str(), port); delete socket; delete csv; delete dispatcher; return false; } return this->CreateNewClientConnection (socket, csv, dispatcher); } void Realtime::Start(void) { Config * cfg = this->app()->config(); ConfigPair * servport = cfg->get_pair (cfg, "realtime", "tcp", "port"); int port = atoi (servport->value); if (this->OpenTcpServer (port) == true) { g_message ("Opened Tcp server on port %d", port); } } GtkWidget * Realtime::CreateMainMenu (void) { GtkWidget * rtmenu = gtk_menu_new(); GtkWidget * rtmenu_item = gtk_menu_item_new_with_label ("Realtime"); GtkWidget * rtmenu_open = gtk_menu_item_new_with_label ("Open Csv stream..."); gtk_menu_shell_append (GTK_MENU_SHELL (rtmenu), rtmenu_open); g_signal_connect (G_OBJECT (rtmenu_open), "activate", G_CALLBACK (StreamOpenDialogCallback), this); gtk_menu_item_set_submenu (GTK_MENU_ITEM (rtmenu_item), rtmenu); return rtmenu_item; } GtkWidget * Realtime::BuildLayout (void) { GtkWidget * gtk_menu = this->app()->gtkmenu(); GtkWidget * box = gtk_vbox_new (FALSE, 0); GtkWidget * realtime_menu = this->CreateMainMenu(); // Append to the existing menu structure from the application. gtk_menu_shell_prepend (GTK_MENU_SHELL (gtk_menu), realtime_menu); // Setup the workbook. wb->signals[SIG_WORKBOOK_CHANGED] = this->app()->signals[Application::SHEET_CHANGED]; wb->gtk_box = box; // Pack all of the objects into a vertical box, and then pack that box into the application. gtk_box_pack_start (GTK_BOX (box), wb->gtk_notebook, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (this->app()->gtkvbox()), box, TRUE, TRUE, 0); return box; }
johnbellone/gtkworkbook
src/realtime/Realtime.cpp
C++
gpl-2.0
10,844
<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xml:base="http://machines.plannedobsolescence.net/149-2007" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <title>postmodernism - apathy</title> <link>http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72/0</link> <description></description> <language>en</language> <item> <title>Postmodern Political Apathy</title> <link>http://machines.plannedobsolescence.net/149-2007/node/27</link> <description>&lt;p&gt;I identified with the some of Jameson&#039;s views on postmodern feelings, or lack thereof.&lt;/p&gt; &lt;p&gt;&lt;a href=&quot;http://machines.plannedobsolescence.net/149-2007/node/27&quot;&gt;read more&lt;/a&gt;&lt;/p&gt;</description> <comments>http://machines.plannedobsolescence.net/149-2007/node/27#comments</comments> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/72">apathy</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/73">feeling</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/55">Jameson</category> <category domain="http://machines.plannedobsolescence.net/149-2007/taxonomy/term/71">politics</category> <pubDate>Mon, 24 Sep 2007 02:42:00 +0000</pubDate> <dc:creator>blankman</dc:creator> <guid isPermaLink="false">27 at http://machines.plannedobsolescence.net/149-2007</guid> </item> </channel> </rss>
kfitz/machines
149-2007/taxonomy/term/72/0/feed/index.html
HTML
gpl-2.0
1,441
/*************************************************************************** qgscalloutwidget.cpp --------------------- begin : July 2019 copyright : (C) 2019 by Nyall Dawson email : nyall dot dawson at gmail dot 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 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgscalloutwidget.h" #include "qgsvectorlayer.h" #include "qgsexpressioncontextutils.h" #include "qgsunitselectionwidget.h" #include "qgscallout.h" #include "qgsnewauxiliaryfielddialog.h" #include "qgsnewauxiliarylayerdialog.h" #include "qgsauxiliarystorage.h" QgsExpressionContext QgsCalloutWidget::createExpressionContext() const { if ( auto *lExpressionContext = mContext.expressionContext() ) return *lExpressionContext; QgsExpressionContext expContext( mContext.globalProjectAtlasMapLayerScopes( vectorLayer() ) ); QgsExpressionContextScope *symbolScope = QgsExpressionContextUtils::updateSymbolScope( nullptr, new QgsExpressionContextScope() ); symbolScope->addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_SYMBOL_COLOR, QColor(), true ) ); expContext << symbolScope; // additional scopes const auto constAdditionalExpressionContextScopes = mContext.additionalExpressionContextScopes(); for ( const QgsExpressionContextScope &scope : constAdditionalExpressionContextScopes ) { expContext.appendScope( new QgsExpressionContextScope( scope ) ); } //TODO - show actual value expContext.setOriginalValueVariable( QVariant() ); expContext.setHighlightedVariables( QStringList() << QgsExpressionContext::EXPR_ORIGINAL_VALUE << QgsExpressionContext::EXPR_SYMBOL_COLOR ); return expContext; } void QgsCalloutWidget::setContext( const QgsSymbolWidgetContext &context ) { mContext = context; const auto unitSelectionWidgets = findChildren<QgsUnitSelectionWidget *>(); for ( QgsUnitSelectionWidget *unitWidget : unitSelectionWidgets ) { unitWidget->setMapCanvas( mContext.mapCanvas() ); } const auto symbolButtonWidgets = findChildren<QgsSymbolButton *>(); for ( QgsSymbolButton *symbolWidget : symbolButtonWidgets ) { symbolWidget->setMapCanvas( mContext.mapCanvas() ); symbolWidget->setMessageBar( mContext.messageBar() ); } } QgsSymbolWidgetContext QgsCalloutWidget::context() const { return mContext; } void QgsCalloutWidget::registerDataDefinedButton( QgsPropertyOverrideButton *button, QgsCallout::Property key ) { button->init( key, callout()->dataDefinedProperties(), QgsCallout::propertyDefinitions(), mVectorLayer, true ); connect( button, &QgsPropertyOverrideButton::changed, this, &QgsCalloutWidget::updateDataDefinedProperty ); connect( button, &QgsPropertyOverrideButton::createAuxiliaryField, this, &QgsCalloutWidget::createAuxiliaryField ); button->registerExpressionContextGenerator( this ); } void QgsCalloutWidget::createAuxiliaryField() { // try to create an auxiliary layer if not yet created if ( !mVectorLayer->auxiliaryLayer() ) { QgsNewAuxiliaryLayerDialog dlg( mVectorLayer, this ); dlg.exec(); } // return if still not exists if ( !mVectorLayer->auxiliaryLayer() ) return; QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() ); QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() ); QgsPropertyDefinition def = QgsCallout::propertyDefinitions()[key]; // create property in auxiliary storage if necessary if ( !mVectorLayer->auxiliaryLayer()->exists( def ) ) { QgsNewAuxiliaryFieldDialog dlg( def, mVectorLayer, true, this ); if ( dlg.exec() == QDialog::Accepted ) def = dlg.propertyDefinition(); } // return if still not exist if ( !mVectorLayer->auxiliaryLayer()->exists( def ) ) return; // update property with join field name from auxiliary storage QgsProperty property = button->toProperty(); property.setField( QgsAuxiliaryLayer::nameFromProperty( def, true ) ); property.setActive( true ); button->updateFieldLists(); button->setToProperty( property ); callout()->dataDefinedProperties().setProperty( key, button->toProperty() ); emit changed(); } void QgsCalloutWidget::updateDataDefinedProperty() { QgsPropertyOverrideButton *button = qobject_cast<QgsPropertyOverrideButton *>( sender() ); QgsCallout::Property key = static_cast< QgsCallout::Property >( button->propertyKey() ); callout()->dataDefinedProperties().setProperty( key, button->toProperty() ); emit changed(); } /// @cond PRIVATE // // QgsSimpleLineCalloutWidget // QgsSimpleLineCalloutWidget::QgsSimpleLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent ) : QgsCalloutWidget( parent, vl ) { setupUi( this ); // Callout options - to move to custom widgets when multiple callout styles exist mCalloutLineStyleButton->setSymbolType( QgsSymbol::Line ); mCalloutLineStyleButton->setDialogTitle( tr( "Callout Symbol" ) ); mCalloutLineStyleButton->registerExpressionContextGenerator( this ); mCalloutLineStyleButton->setLayer( vl ); mMinCalloutWidthUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches ); mOffsetFromAnchorUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches ); mOffsetFromLabelUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMetersInMapUnits << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches ); connect( mMinCalloutWidthUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged ); connect( mMinCalloutLengthSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::minimumLengthChanged ); connect( mOffsetFromAnchorUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged ); connect( mOffsetFromAnchorSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromAnchorChanged ); connect( mOffsetFromLabelUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged ); connect( mOffsetFromLabelSpin, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsSimpleLineCalloutWidget::offsetFromLabelChanged ); connect( mDrawToAllPartsCheck, &QCheckBox::toggled, this, &QgsSimpleLineCalloutWidget::drawToAllPartsToggled ); // Anchor point options mAnchorPointComboBox->addItem( tr( "Pole of Inaccessibility" ), static_cast< int >( QgsCallout::PoleOfInaccessibility ) ); mAnchorPointComboBox->addItem( tr( "Point on Exterior" ), static_cast< int >( QgsCallout::PointOnExterior ) ); mAnchorPointComboBox->addItem( tr( "Point on Surface" ), static_cast< int >( QgsCallout::PointOnSurface ) ); mAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::Centroid ) ); connect( mAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged ); mLabelAnchorPointComboBox->addItem( tr( "Closest Point" ), static_cast< int >( QgsCallout::LabelPointOnExterior ) ); mLabelAnchorPointComboBox->addItem( tr( "Centroid" ), static_cast< int >( QgsCallout::LabelCentroid ) ); mLabelAnchorPointComboBox->addItem( tr( "Top Left" ), static_cast< int >( QgsCallout::LabelTopLeft ) ); mLabelAnchorPointComboBox->addItem( tr( "Top Center" ), static_cast< int >( QgsCallout::LabelTopMiddle ) ); mLabelAnchorPointComboBox->addItem( tr( "Top Right" ), static_cast< int >( QgsCallout::LabelTopRight ) ); mLabelAnchorPointComboBox->addItem( tr( "Left Middle" ), static_cast< int >( QgsCallout::LabelMiddleLeft ) ); mLabelAnchorPointComboBox->addItem( tr( "Right Middle" ), static_cast< int >( QgsCallout::LabelMiddleRight ) ); mLabelAnchorPointComboBox->addItem( tr( "Bottom Left" ), static_cast< int >( QgsCallout::LabelBottomLeft ) ); mLabelAnchorPointComboBox->addItem( tr( "Bottom Center" ), static_cast< int >( QgsCallout::LabelBottomMiddle ) ); mLabelAnchorPointComboBox->addItem( tr( "Bottom Right" ), static_cast< int >( QgsCallout::LabelBottomRight ) ); connect( mLabelAnchorPointComboBox, static_cast<void ( QComboBox::* )( int )>( &QComboBox::currentIndexChanged ), this, &QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged ); connect( mCalloutLineStyleButton, &QgsSymbolButton::changed, this, &QgsSimpleLineCalloutWidget::lineSymbolChanged ); } void QgsSimpleLineCalloutWidget::setCallout( QgsCallout *callout ) { if ( !callout ) return; mCallout.reset( dynamic_cast<QgsSimpleLineCallout *>( callout->clone() ) ); if ( !mCallout ) return; mMinCalloutWidthUnitWidget->blockSignals( true ); mMinCalloutWidthUnitWidget->setUnit( mCallout->minimumLengthUnit() ); mMinCalloutWidthUnitWidget->setMapUnitScale( mCallout->minimumLengthMapUnitScale() ); mMinCalloutWidthUnitWidget->blockSignals( false ); whileBlocking( mMinCalloutLengthSpin )->setValue( mCallout->minimumLength() ); mOffsetFromAnchorUnitWidget->blockSignals( true ); mOffsetFromAnchorUnitWidget->setUnit( mCallout->offsetFromAnchorUnit() ); mOffsetFromAnchorUnitWidget->setMapUnitScale( mCallout->offsetFromAnchorMapUnitScale() ); mOffsetFromAnchorUnitWidget->blockSignals( false ); mOffsetFromLabelUnitWidget->blockSignals( true ); mOffsetFromLabelUnitWidget->setUnit( mCallout->offsetFromLabelUnit() ); mOffsetFromLabelUnitWidget->setMapUnitScale( mCallout->offsetFromLabelMapUnitScale() ); mOffsetFromLabelUnitWidget->blockSignals( false ); whileBlocking( mOffsetFromAnchorSpin )->setValue( mCallout->offsetFromAnchor() ); whileBlocking( mOffsetFromLabelSpin )->setValue( mCallout->offsetFromLabel() ); whileBlocking( mCalloutLineStyleButton )->setSymbol( mCallout->lineSymbol()->clone() ); whileBlocking( mDrawToAllPartsCheck )->setChecked( mCallout->drawCalloutToAllParts() ); whileBlocking( mAnchorPointComboBox )->setCurrentIndex( mAnchorPointComboBox->findData( static_cast< int >( callout->anchorPoint() ) ) ); whileBlocking( mLabelAnchorPointComboBox )->setCurrentIndex( mLabelAnchorPointComboBox->findData( static_cast< int >( callout->labelAnchorPoint() ) ) ); registerDataDefinedButton( mMinCalloutLengthDDBtn, QgsCallout::MinimumCalloutLength ); registerDataDefinedButton( mOffsetFromAnchorDDBtn, QgsCallout::OffsetFromAnchor ); registerDataDefinedButton( mOffsetFromLabelDDBtn, QgsCallout::OffsetFromLabel ); registerDataDefinedButton( mDrawToAllPartsDDBtn, QgsCallout::DrawCalloutToAllParts ); registerDataDefinedButton( mAnchorPointDDBtn, QgsCallout::AnchorPointPosition ); registerDataDefinedButton( mLabelAnchorPointDDBtn, QgsCallout::LabelAnchorPointPosition ); registerDataDefinedButton( mOriginXDDBtn, QgsCallout::OriginX ); registerDataDefinedButton( mOriginYDDBtn, QgsCallout::OriginY ); registerDataDefinedButton( mDestXDDBtn, QgsCallout::DestinationX ); registerDataDefinedButton( mDestYDDBtn, QgsCallout::DestinationY ); } void QgsSimpleLineCalloutWidget::setGeometryType( QgsWkbTypes::GeometryType type ) { bool isPolygon = type == QgsWkbTypes::PolygonGeometry; mAnchorPointLbl->setEnabled( isPolygon ); mAnchorPointLbl->setVisible( isPolygon ); mAnchorPointComboBox->setEnabled( isPolygon ); mAnchorPointComboBox->setVisible( isPolygon ); mAnchorPointDDBtn->setEnabled( isPolygon ); mAnchorPointDDBtn->setVisible( isPolygon ); } QgsCallout *QgsSimpleLineCalloutWidget::callout() { return mCallout.get(); } void QgsSimpleLineCalloutWidget::minimumLengthChanged() { mCallout->setMinimumLength( mMinCalloutLengthSpin->value() ); emit changed(); } void QgsSimpleLineCalloutWidget::minimumLengthUnitWidgetChanged() { mCallout->setMinimumLengthUnit( mMinCalloutWidthUnitWidget->unit() ); mCallout->setMinimumLengthMapUnitScale( mMinCalloutWidthUnitWidget->getMapUnitScale() ); emit changed(); } void QgsSimpleLineCalloutWidget::offsetFromAnchorUnitWidgetChanged() { mCallout->setOffsetFromAnchorUnit( mOffsetFromAnchorUnitWidget->unit() ); mCallout->setOffsetFromAnchorMapUnitScale( mOffsetFromAnchorUnitWidget->getMapUnitScale() ); emit changed(); } void QgsSimpleLineCalloutWidget::offsetFromAnchorChanged() { mCallout->setOffsetFromAnchor( mOffsetFromAnchorSpin->value() ); emit changed(); } void QgsSimpleLineCalloutWidget::offsetFromLabelUnitWidgetChanged() { mCallout->setOffsetFromLabelUnit( mOffsetFromLabelUnitWidget->unit() ); mCallout->setOffsetFromLabelMapUnitScale( mOffsetFromLabelUnitWidget->getMapUnitScale() ); emit changed(); } void QgsSimpleLineCalloutWidget::offsetFromLabelChanged() { mCallout->setOffsetFromLabel( mOffsetFromLabelSpin->value() ); emit changed(); } void QgsSimpleLineCalloutWidget::lineSymbolChanged() { mCallout->setLineSymbol( mCalloutLineStyleButton->clonedSymbol< QgsLineSymbol >() ); emit changed(); } void QgsSimpleLineCalloutWidget::mAnchorPointComboBox_currentIndexChanged( int index ) { mCallout->setAnchorPoint( static_cast<QgsCallout::AnchorPoint>( mAnchorPointComboBox->itemData( index ).toInt() ) ); emit changed(); } void QgsSimpleLineCalloutWidget::mLabelAnchorPointComboBox_currentIndexChanged( int index ) { mCallout->setLabelAnchorPoint( static_cast<QgsCallout::LabelAnchorPoint>( mLabelAnchorPointComboBox->itemData( index ).toInt() ) ); emit changed(); } void QgsSimpleLineCalloutWidget::drawToAllPartsToggled( bool active ) { mCallout->setDrawCalloutToAllParts( active ); emit changed(); } // // QgsManhattanLineCalloutWidget // QgsManhattanLineCalloutWidget::QgsManhattanLineCalloutWidget( QgsVectorLayer *vl, QWidget *parent ) : QgsSimpleLineCalloutWidget( vl, parent ) { } ///@endcond
JamesShaeffer/QGIS
src/gui/callouts/qgscalloutwidget.cpp
C++
gpl-2.0
15,015
/* * ws2san.h * * WinSock Direct (SAN) support * * This file is part of the w32api package. * * Contributors: * Created by Casper S. Hornstrup <[email protected]> * * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #ifndef __WS2SAN_H #define __WS2SAN_H #if __GNUC__ >=3 #pragma GCC system_header #endif #ifdef __cplusplus extern "C" { #endif #pragma pack(push,4) #include <winsock2.h> #include "ntddk.h" #define WSPAPI STDCALL /* FIXME: Unknown definitions */ typedef PVOID LPWSPDATA; typedef PDWORD LPWSATHREADID; typedef PVOID LPWSPPROC_TABLE; typedef struct _WSPUPCALLTABLEEX WSPUPCALLTABLEEX; typedef WSPUPCALLTABLEEX *LPWSPUPCALLTABLEEX; #define SO_MAX_RDMA_SIZE 0x700D #define SO_RDMA_THRESHOLD_SIZE 0x700E #define WSAID_REGISTERMEMORY \ {0xC0B422F5, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_DEREGISTERMEMORY \ {0xC0B422F6, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_REGISTERRDMAMEMORY \ {0xC0B422F7, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_DEREGISTERRDMAMEMORY \ {0xC0B422F8, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_RDMAWRITE \ {0xC0B422F9, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_RDMAREAD \ {0xC0B422FA, 0xF58C, 0x11d1, {0xAD, 0x6C, 0x00, 0xC0, 0x4F, 0xA3, 0x4A, 0x2D}} #define WSAID_MEMORYREGISTRATIONCACHECALLBACK \ {0xE5DA4AF8, 0xD824, 0x48CD, {0xA7, 0x99, 0x63, 0x37, 0xA9, 0x8E, 0xD2, 0xAF}} typedef struct _WSABUFEX { u_long len; char FAR *buf; HANDLE handle; } WSABUFEX, FAR * LPWSABUFEX; #if 0 typedef struct _WSPUPCALLTABLEEX { LPWPUCLOSEEVENT lpWPUCloseEvent; LPWPUCLOSESOCKETHANDLE lpWPUCloseSocketHandle; LPWPUCREATEEVENT lpWPUCreateEvent; LPWPUCREATESOCKETHANDLE lpWPUCreateSocketHandle; LPWPUFDISSET lpWPUFDIsSet; LPWPUGETPROVIDERPATH lpWPUGetProviderPath; LPWPUMODIFYIFSHANDLE lpWPUModifyIFSHandle; LPWPUPOSTMESSAGE lpWPUPostMessage; LPWPUQUERYBLOCKINGCALLBACK lpWPUQueryBlockingCallback; LPWPUQUERYSOCKETHANDLECONTEXT lpWPUQuerySocketHandleContext; LPWPUQUEUEAPC lpWPUQueueApc; LPWPURESETEVENT lpWPUResetEvent; LPWPUSETEVENT lpWPUSetEvent; LPWPUOPENCURRENTTHREAD lpWPUOpenCurrentThread; LPWPUCLOSETHREAD lpWPUCloseThread; LPWPUCOMPLETEOVERLAPPEDREQUEST lpWPUCompleteOverlappedRequest; } WSPUPCALLTABLEEX, FAR * LPWSPUPCALLTABLEEX; #endif int WSPAPI WSPStartupEx( IN WORD wVersionRequested, OUT LPWSPDATA lpWSPData, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN LPWSPUPCALLTABLEEX lpUpcallTable, OUT LPWSPPROC_TABLE lpProcTable); typedef int WSPAPI (*LPWSPSTARTUPEX)( IN WORD wVersionRequested, OUT LPWSPDATA lpWSPData, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN LPWSPUPCALLTABLEEX lpUpcallTable, OUT LPWSPPROC_TABLE lpProcTable); #define MEM_READ 1 #define MEM_WRITE 2 #define MEM_READWRITE 3 int WSPAPI WSPDeregisterMemory( IN SOCKET s, IN HANDLE Handle, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPDEREGISTERMEMORY)( IN SOCKET s, IN HANDLE Handle, OUT LPINT lpErrno); int WSPAPI WSPDeregisterRdmaMemory( IN SOCKET s, IN LPVOID lpRdmaBufferDescriptor, IN DWORD dwDescriptorLength, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPDEREGISTERRDMAMEMORY)( IN SOCKET s, IN LPVOID lpRdmaBufferDescriptor, IN DWORD dwDescriptorLength, OUT LPINT lpErrno); int WSPAPI WSPMemoryRegistrationCacheCallback( IN PVOID lpvAddress, IN SIZE_T Size, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPMEMORYREGISTRATIONCACHECALLBACK)( IN PVOID lpvAddress, IN SIZE_T Size, OUT LPINT lpErrno); int WSPAPI WSPRdmaRead( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID lpTargetBufferDescriptor, IN DWORD dwTargetDescriptorLength, IN DWORD dwTargetBufferOffset, OUT LPDWORD lpdwNumberOfBytesRead, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPRDMAREAD)( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID lpTargetBufferDescriptor, IN DWORD dwTargetDescriptorLength, IN DWORD dwTargetBufferOffset, OUT LPDWORD lpdwNumberOfBytesRead, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); int WSPAPI WSPRdmaWrite( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID lpTargetBufferDescriptor, IN DWORD dwTargetDescriptorLength, IN DWORD dwTargetBufferOffset, OUT LPDWORD lpdwNumberOfBytesWritten, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPRDMAWRITE)( IN SOCKET s, IN LPWSABUFEX lpBuffers, IN DWORD dwBufferCount, IN LPVOID lpTargetBufferDescriptor, IN DWORD dwTargetDescriptorLength, IN DWORD dwTargetBufferOffset, OUT LPDWORD lpdwNumberOfBytesWritten, IN DWORD dwFlags, IN LPWSAOVERLAPPED lpOverlapped, IN LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine, IN LPWSATHREADID lpThreadId, OUT LPINT lpErrno); HANDLE WSPAPI WSPRegisterMemory( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPINT lpErrno); int WSPAPI WSPRegisterRdmaMemory( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPVOID lpRdmaBufferDescriptor, IN OUT LPDWORD lpdwDescriptorLength, OUT LPINT lpErrno); typedef int WSPAPI (*LPFN_WSPREGISTERRDMAMEMORY)( IN SOCKET s, IN PVOID lpBuffer, IN DWORD dwBufferLength, IN DWORD dwFlags, OUT LPVOID lpRdmaBufferDescriptor, IN OUT LPDWORD lpdwDescriptorLength, OUT LPINT lpErrno); #pragma pack(pop) #ifdef __cplusplus } #endif #endif /* __WS2SAN_H */
alji2106/CS1300Terminal
include/ddk/ws2san.h
C
gpl-2.0
6,546
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. * However, the following notice accompanied the original version of this * file: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent.atomic; /** * An {@code AtomicMarkableReference} maintains an object reference * along with a mark bit, that can be updated atomically. * * <p>Implementation note: This implementation maintains markable * references by creating internal objects representing "boxed" * [reference, boolean] pairs. * * @since 1.5 * @author Doug Lea * @param <V> The type of object referred to by this reference */ public class AtomicMarkableReference<V> { private static class Pair<T> { final T reference; final boolean mark; private Pair(T reference, boolean mark) { this.reference = reference; this.mark = mark; } static <T> Pair<T> of(T reference, boolean mark) { return new Pair<T>(reference, mark); } } private volatile Pair<V> pair; /** * Creates a new {@code AtomicMarkableReference} with the given * initial values. * * @param initialRef the initial reference * @param initialMark the initial mark */ public AtomicMarkableReference(V initialRef, boolean initialMark) { pair = Pair.of(initialRef, initialMark); } /** * Returns the current value of the reference. * * @return the current value of the reference */ public V getReference() { return pair.reference; } /** * Returns the current value of the mark. * * @return the current value of the mark */ public boolean isMarked() { return pair.mark; } /** * Returns the current values of both the reference and the mark. * Typical usage is {@code boolean[1] holder; ref = v.get(holder); }. * * @param markHolder an array of size of at least one. On return, * {@code markholder[0]} will hold the value of the mark. * @return the current value of the reference */ public V get(boolean[] markHolder) { Pair<V> pair = this.pair; markHolder[0] = pair.mark; return pair.reference; } /** * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * * <p><a href="package-summary.html#weakCompareAndSet">May fail * spuriously and does not provide ordering guarantees</a>, so is * only rarely an appropriate alternative to {@code compareAndSet}. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean weakCompareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { return compareAndSet(expectedReference, newReference, expectedMark, newMark); } /** * Atomically sets the value of both the reference and mark * to the given update values if the * current reference is {@code ==} to the expected reference * and the current mark is equal to the expected mark. * * @param expectedReference the expected value of the reference * @param newReference the new value for the reference * @param expectedMark the expected value of the mark * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean compareAndSet(V expectedReference, V newReference, boolean expectedMark, boolean newMark) { Pair<V> current = pair; return expectedReference == current.reference && expectedMark == current.mark && ((newReference == current.reference && newMark == current.mark) || casPair(current, Pair.of(newReference, newMark))); } /** * Unconditionally sets the value of both the reference and mark. * * @param newReference the new value for the reference * @param newMark the new value for the mark */ public void set(V newReference, boolean newMark) { Pair<V> current = pair; if (newReference != current.reference || newMark != current.mark) this.pair = Pair.of(newReference, newMark); } /** * Atomically sets the value of the mark to the given update value * if the current reference is {@code ==} to the expected * reference. Any given invocation of this operation may fail * (return {@code false}) spuriously, but repeated invocation * when the current value holds the expected value and no other * thread is also attempting to set the value will eventually * succeed. * * @param expectedReference the expected value of the reference * @param newMark the new value for the mark * @return {@code true} if successful */ public boolean attemptMark(V expectedReference, boolean newMark) { Pair<V> current = pair; return expectedReference == current.reference && (newMark == current.mark || casPair(current, Pair.of(expectedReference, newMark))); } // Unsafe mechanics private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); // private static final long pairOffset = // objectFieldOffset(UNSAFE, "pair", AtomicMarkableReference.class); private boolean casPair(Pair<V> cmp, Pair<V> val) { return UNSAFE.compareAndSwapObject(this, pairOffset, cmp, val); } public static volatile long pairOffset; static { try { pairOffset = 0; UNSAFE.registerStaticFieldOffset( AtomicMarkableReference.class.getDeclaredField("pairOffset"), AtomicMarkableReference.class.getDeclaredField("pair")); } catch (Exception ex) { throw new Error(ex); } } }
upenn-acg/REMIX
jvm-remix/openjdk/jdk/src/share/classes/java/util/concurrent/atomic/AtomicMarkableReference.java
Java
gpl-2.0
7,816
(function ($) { $(document).ready(function(){ $("#edit-title-0-value").change(update); $("#edit-field-carac1-0-value").click(update); $("#edit-field-carac1-0-value").change(update); $("#edit-field-carac2-0-value").change(update); $("#edit-field-carac3-0-value").change(update); $("#edit-field-carac4-0-value").change(update); $("#edit-field-skill-0-value").change(update); $("#edit-field-question-0-value").change(update); $("#edit-field-answer-0-value").change(update); $("#edit-field-img-game-card-0-upload").change(update); $("#edit-field-upload_image_verso").change(update); var bgimagerecto = undefined; var bgimageverso = undefined; if($('span.file--image > a').length == 1) { if($('#edit-field-img-game-card-0-remove-button')) { console.log("length11"); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); } else { console.log("length12"); bgimageverso = $("span.file--image > a:eq(0)").attr('href'); } } if($('span.file--image > a').length == 2) { console.log("length2"); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); bgimageverso = $("span.file--image > a:eq(1)").attr('href'); } if (bgimagerecto !== undefined) { console.log("imagerecto"); $('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')'); $('.field--name-field-img-game-card .ajax-new-content').addClass('processed'); } if (bgimageverso !== undefined) { console.log("imageverso"); $('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')'); $('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed'); } $(document).ajaxComplete(function(event, xhr, settings) { //RECTO console.log(event.target); console.log("azer " + bgimagerecto); console.log("qsdf " + bgimageverso); if(~settings.url.indexOf("field_img_game_card")) { console.log('entering recto'); if ($('.field--name-field-img-game-card .ajax-new-content').hasClass('processed')) { console.log("remove recto"); //$('.ajax-new-content').remove(); $('#gamecardrectolayout').removeAttr('style'); $('.field--name-field-img-game-card .ajax-new-content').removeClass('processed'); return; } if(!$('#edit-field-img-game-card-0-remove-button')) { console.log("remoooooove"); $('#gamecardrectolayout').removeAttr('style'); $('.field--name-field-img-game-card .ajax-new-content').removeClass('processed'); return; } console.log("addingrecto"); $('.field--name-field-img-game-card .ajax-new-content').addClass('processed'); bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double if (bgimagerecto !== undefined) { console.log("gorecto"); $('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')'); } return; } //VERSO if(~settings.url.indexOf("field_upload_image_verso")) { if ($('.field--name-field-upload-image-verso .ajax-new-content').hasClass('processed') || !$('#edit-field-upload-image-verso-0-remove-button')) { console.log("remove verso"); //$('.ajax-new-content').remove(); $('#gamecardversolayout').removeAttr('style'); $('.field--name-field-upload-image-verso .ajax-new-content').removeClass('processed'); return; } console.log("adding verso"); $('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed'); if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href'); if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href'); if (bgimageverso !== undefined) { console.log("Verso added"); $('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')'); } } }); }); function update(){ var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : ""); var carac1 = (($("#edit-field-carac1-0-value").val() != "") ? $("#edit-field-carac1-0-value").val() : ""); var carac2 = (($("#edit-field-carac2-0-value").val() != "") ? $("#edit-field-carac2-0-value").val() : ""); var carac3 = (($("#edit-field-carac3-0-value").val() != "") ? $("#edit-field-carac3-0-value").val() : ""); var carac4 = (($("#edit-field-carac4-0-value").val() != "") ? $("#edit-field-carac4-0-value").val() : ""); var skill = (($("#edit-field-skill-0-value").val() != "") ? $("#edit-field-skill-0-value").val() : "") ; var question = (($("#edit-field-question-0-value").val() != "") ? $("#edit-field-question-0-value").val() : ""); var answer = (($("#edit-field-answer-0-value").val() != "") ? $("#edit-field-answer-0-value").val() : "") ; var rectoImg = (($("#edit-field-img-game-card-0-upload").val() != "") ? $("#edit-field-img-game-card-0-upload").val() : ""); var versoImg = (($("#edit-field-upload_image_verso").val() != "") ? $("#edit-field-upload_image_verso").val() : ""); if(rectoImg !== undefined) { if (rectoImg != null) { $('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")'); } else { rectoImg = $("span.file--image > a:eq(0)").attr('href'); $('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')'); } } if(versoImg !== undefined) { if (versoImg != null) { $('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")'); } else { versoImg = $("span.file--image > a:eq(1)").attr('href'); $('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')'); } } $('#displayCardname').html(cardname); $('#displayCarac1').html(carac1); $('#displayCarac2').html(carac2); $('#displayCarac3').html(carac3); $('#displayCarac4').html(carac4); $('#displaySkill').html(skill); $('#displayQuestion').html(question); $('#displayAnswer').html(answer); } })(jQuery);
TGR05/POEI-mini-projet
modules/custom/cardform/js/gamecards.js
JavaScript
gpl-2.0
6,227
<?php /** * @package WordPress * @subpackage HTML5-Reset-WordPress-Theme * @since HTML5 Reset 2.0 Template Name: Groups */ get_header(); ?> <div class="content-background"> <div id="content-wrap"> <div class="grid"> <div class="col col-1-4"> <?php wp_nav_menu( array('menu' => 'Groups Menu', 'container_class' => 'side-menu-container', 'menu_class' => 'side-menu' )); ?> <div class="fb-like-box" data-href="https://www.facebook.com/skisnowstar" data-width="200" data-height="300" data-colorscheme="light" data-show-faces="true" data-header="true" data-stream="false" data-show-border="true"></div> <a href="https://twitter.com/SkiSnowstar" class="twitter-follow-button" data-width="90%" data-align="right" data-show-count="false" data-lang="en" data-size="large">Follow @twitter</a> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> </div><!-- END COL-1-4 --> <div class="col col-3-4"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <article class="post" id="post-<?php the_ID(); ?>"> <!-- <h2><?php the_title(); ?></h2> --> <!-- <?php posted_on(); ?> --> <?php if ( has_post_thumbnail() ) {the_post_thumbnail('full', array('class' => 'content-img'));} ?> <div class="entry"> <?php the_content(); ?> <?php wp_link_pages(array('before' => __('Pages: '), 'next_or_number' => 'number')); ?> </div> <?php edit_post_link(__('Edit this entry.'), '<p>', '</p>'); ?> </article> <?php endwhile; endif; ?> </div><!-- END COL-3-4 --> </div><!-- END GRID --> </div> <!-- End Content Wrap --> <?php get_footer(); ?>
markfaust/snowstar
wp-content/themes/snowstar/groups.php
PHP
gpl-2.0
1,854
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Caixa.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Caixa.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
davividal/sistema-bomba
Caixa/Caixa/Properties/Resources.Designer.cs
C#
gpl-2.0
2,769
/* * Copyright (C) 2019 Paul Davis <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _ardour_transport_api_h_ #define _ardour_transport_api_h_ #include "ardour/types.h" #include "ardour/libardour_visibility.h" namespace ARDOUR { class LIBARDOUR_API TransportAPI { public: TransportAPI() {} virtual ~TransportAPI() {} private: friend struct TransportFSM; virtual void locate (samplepos_t, bool with_roll, bool with_flush, bool with_loop=false, bool force=false, bool with_mmc=true) = 0; virtual void stop_transport (bool abort = false, bool clear_state = false) = 0; virtual void start_transport () = 0; virtual void butler_completed_transport_work () = 0; virtual void schedule_butler_for_transport_work () = 0; virtual bool should_roll_after_locate () const = 0; virtual double speed() const = 0; virtual void set_transport_speed (double speed, bool abort_capture, bool clear_state, bool as_default) = 0; virtual samplepos_t position() const = 0; virtual bool need_declick_before_locate () const = 0; }; } /* end namespace ARDOUR */ #endif
tartina/ardour
libs/ardour/ardour/transport_api.h
C
gpl-2.0
1,784
/* * Copyright (C) 2015-2016 FixCore <FixCore Develops> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TRINITY_GAMEOBJECTAI_H #define TRINITY_GAMEOBJECTAI_H #include "Define.h" #include <list> #include "Object.h" #include "GameObject.h" #include "CreatureAI.h" class GameObjectAI { protected: GameObject* const go; public: explicit GameObjectAI(GameObject* g) : go(g) {} virtual ~GameObjectAI() {} virtual void UpdateAI(uint32 /*diff*/) {} virtual void InitializeAI() { Reset(); } virtual void Reset() { } // Pass parameters between AI virtual void DoAction(const int32 /*param = 0 */) {} virtual void SetGUID(uint64 /*guid*/, int32 /*id = 0 */) {} virtual uint64 GetGUID(int32 /*id = 0 */) const { return 0; } static int Permissible(GameObject const* go); virtual bool GossipHello(Player* /*player*/) { return false; } virtual bool GossipSelect(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/) { return false; } virtual bool GossipSelectCode(Player* /*player*/, uint32 /*sender*/, uint32 /*action*/, char const* /*code*/) { return false; } virtual bool QuestAccept(Player* /*player*/, Quest const* /*quest*/) { return false; } virtual bool QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { return false; } virtual uint32 GetDialogStatus(Player* /*player*/) { return 100; } virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) {} virtual uint32 GetData(uint32 /*id*/) const { return 0; } virtual void SetData64(uint32 /*id*/, uint64 /*value*/) {} virtual uint64 GetData64(uint32 /*id*/) const { return 0; } virtual void SetData(uint32 /*id*/, uint32 /*value*/) {} virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) {} virtual void OnStateChanged(uint32 /*state*/, Unit* /*unit*/) {} virtual void EventInform(uint32 /*eventId*/) {} }; class NullGameObjectAI : public GameObjectAI { public: explicit NullGameObjectAI(GameObject* g); void UpdateAI(uint32 /*diff*/) {} static int Permissible(GameObject const* /*go*/) { return PERMIT_BASE_IDLE; } }; #endif
Desarrollo-zeros/ZerosCore
src/server/game/AI/CoreAI/GameObjectAI.h
C
gpl-2.0
2,867
/**************************************************************************** ** ** This file is part of the Qtopia Opensource Edition Package. ** ** Copyright (C) 2008 Trolltech ASA. ** ** Contact: Qt Extended Information ([email protected]) ** ** This file may be used under the terms of the GNU General Public License ** versions 2.0 as published by the Free Software Foundation and appearing ** in the file LICENSE.GPL included in the packaging of this file. ** ** Please review the following information to ensure GNU General Public ** Licensing requirements will be met: ** http://www.fsf.org/licensing/licenses/info/GPLv2.html. ** ** ****************************************************************************/ #ifndef BROWSER_H #define BROWSER_H #include <QList> #include <QMailAddress> #include <QMap> #include <QString> #include <QTextBrowser> #include <QUrl> #include <QVariant> class QWidget; class QMailMessage; class QMailMessagePart; class Browser: public QTextBrowser { Q_OBJECT public: Browser(QWidget *parent = 0); virtual ~Browser(); void setResource( const QUrl& name, QVariant var ); void clearResources(); void setMessage( const QMailMessage& mail, bool plainTextMode ); void scrollBy(int dx, int dy); virtual QVariant loadResource(int type, const QUrl& name); QList<QString> embeddedNumbers() const; signals: void finished(); public slots: virtual void setSource(const QUrl &name); protected: void keyPressEvent(QKeyEvent* event); private: void displayPlainText(const QMailMessage* mail); void displayHtml(const QMailMessage* mail); void setTextResource(const QUrl& name, const QString& textData); void setImageResource(const QUrl& name, const QByteArray& imageData); void setPartResource(const QMailMessagePart& part); QString renderPart(const QMailMessagePart& part); QString renderAttachment(const QMailMessagePart& part); QString describeMailSize(uint bytes) const; QString formatText(const QString& txt) const; QString smsBreakReplies(const QString& txt) const; QString noBreakReplies(const QString& txt) const; QString handleReplies(const QString& txt) const; QString buildParagraph(const QString& txt, const QString& prepend, bool preserveWs = false) const; QString encodeUrlAndMail(const QString& txt) const; QString listRefMailTo(const QList<QMailAddress>& list) const; QString refMailTo(const QMailAddress& address) const; QString refNumber(const QString& number) const; QMap<QUrl, QVariant> resourceMap; QString (Browser::*replySplitter)(const QString&) const; mutable QList<QString> numbers; }; #endif // BROWSER_H
muromec/qtopia-ezx
src/plugins/viewers/generic/browser.h
C
gpl-2.0
2,706
/* * Turbo Sliders++ * Copyright (C) 2013-2014 Martin Newhouse * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #pragma once #ifndef TRACK_METADATA_HPP #define TRACK_METADATA_HPP #include "track_identifier.hpp" namespace ts { namespace resources { class Track_handle; struct Track_metadata { Track_identifier identifier; utf8_string gamemode; }; Track_metadata load_track_metadata(const resources::Track_handle& track_handle); } } #endif
mnewhouse/tspp
src/resources/track_metadata.hpp
C++
gpl-2.0
1,222
package edu.stanford.nlp.time; import java.io.Serializable; import java.util.Calendar; import java.util.Map; import java.util.regex.Pattern; import edu.stanford.nlp.util.Pair; import org.w3c.dom.Element; /** * Stores one TIMEX3 expression. This class is used for both TimeAnnotator and * GUTimeAnnotator for storing information for TIMEX3 tags. * * <p> * Example text with TIMEX3 annotation:<br> * <code>In Washington &lt;TIMEX3 tid="t1" TYPE="DATE" VAL="PRESENT_REF" * temporalFunction="true" valueFromFunction="tf1" * anchorTimeID="t0"&gt;today&lt;/TIMEX3&gt;, the Federal Aviation Administration * released air traffic control tapes from the night the TWA Flight eight * hundred went down. * </code> * <p> * <br> * TIMEX3 specification: * <br> * <pre><code> * attributes ::= tid type [functionInDocument] [beginPoint] [endPoint] * [quant] [freq] [temporalFunction] (value | valueFromFunction) * [mod] [anchorTimeID] [comment] * * tid ::= ID * {tid ::= TimeID * TimeID ::= t<integer>} * type ::= 'DATE' | 'TIME' | 'DURATION' | 'SET' * beginPoint ::= IDREF * {beginPoint ::= TimeID} * endPoint ::= IDREF * {endPoint ::= TimeID} * quant ::= CDATA * freq ::= Duration * functionInDocument ::= 'CREATION_TIME' | 'EXPIRATION_TIME' | 'MODIFICATION_TIME' | * 'PUBLICATION_TIME' | 'RELEASE_TIME'| 'RECEPTION_TIME' | * 'NONE' {default, if absent, is 'NONE'} * temporalFunction ::= 'true' | 'false' {default, if absent, is 'false'} * {temporalFunction ::= boolean} * value ::= Duration | Date | Time | WeekDate | WeekTime | Season | PartOfYear | PaPrFu * valueFromFunction ::= IDREF * {valueFromFunction ::= TemporalFunctionID * TemporalFunctionID ::= tf<integer>} * mod ::= 'BEFORE' | 'AFTER' | 'ON_OR_BEFORE' | 'ON_OR_AFTER' |'LESS_THAN' | 'MORE_THAN' | * 'EQUAL_OR_LESS' | 'EQUAL_OR_MORE' | 'START' | 'MID' | 'END' | 'APPROX' * anchorTimeID ::= IDREF * {anchorTimeID ::= TimeID} * comment ::= CDATA * </code></pre> * * <p> * References * <br> * Guidelines: <a href="http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf"> * http://www.timeml.org/tempeval2/tempeval2-trial/guidelines/timex3guidelines-072009.pdf</a> * <br> * Specifications: <a href="http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3"> * http://www.timeml.org/site/publications/timeMLdocs/timeml_1.2.1.html#timex3</a> * <br> * XSD: <a href="http://www.timeml.org/timeMLdocs/TimeML.xsd">http://www.timeml.org/timeMLdocs/TimeML.xsd</a> **/ public class Timex implements Serializable { private static final long serialVersionUID = 385847729549981302L; /** * XML representation of the TIMEX tag */ private String xml; /** * TIMEX3 value attribute - Time value (given in extended ISO 8601 format). */ private String val; /** * Alternate representation for time value (not part of TIMEX3 standard). * used when value of the time expression cannot be expressed as a standard TIMEX3 value. */ private String altVal; /** * Actual text that make up the time expression */ private String text; /** * TIMEX3 type attribute - Type of the time expression (DATE, TIME, DURATION, or SET) */ private String type; /** * TIMEX3 tid attribute - TimeID. ID to identify this time expression. * Should have the format of {@code t<integer>} */ private String tid; // TODO: maybe its easier if these are just strings... /** * TIMEX3 beginPoint attribute - integer indicating the TimeID of the begin time * that anchors this duration/range (-1 is not present). */ private int beginPoint; /** * TIMEX3 beginPoint attribute - integer indicating the TimeID of the end time * that anchors this duration/range (-1 is not present). */ private int endPoint; /** * Range begin/end/duration * (this is not part of the timex standard and is typically null, available if sutime.includeRange is true) */ private Range range; public static class Range implements Serializable { private static final long serialVersionUID = 1L; public String begin; public String end; public String duration; public Range(String begin, String end, String duration) { this.begin = begin; this.end = end; this.duration = duration; } } public String value() { return val; } public String altVal() { return altVal; } public String text() { return text; } public String timexType() { return type; } public String tid() { return tid; } public Range range() { return range; } public Timex() { } public Timex(Element element) { this.val = null; this.beginPoint = -1; this.endPoint = -1; /* * ByteArrayOutputStream os = new ByteArrayOutputStream(); Serializer ser = * new Serializer(os, "UTF-8"); ser.setIndent(2); // this is the default in * JDOM so let's keep the same ser.setMaxLength(0); // no line wrapping for * content ser.write(new Document(element)); */ init(element); } public Timex(String val) { this(null, val); } public Timex(String type, String val) { this.val = val; this.type = type; this.beginPoint = -1; this.endPoint = -1; this.xml = (val == null ? "<TIMEX3/>" : String.format("<TIMEX3 VAL=\"%s\" TYPE=\"%s\"/>", this.val, this.type)); } public Timex(String type, String val, String altVal, String tid, String text, int beginPoint, int endPoint) { this.type = type; this.val = val; this.altVal = altVal; this.tid = tid; this.text = text; this.beginPoint = beginPoint; this.endPoint = endPoint; } private void init(Element element) { init(XMLUtils.nodeToString(element, false), element); } private void init(String xml, Element element) { this.xml = xml; this.text = element.getTextContent(); // Mandatory attributes this.tid = XMLUtils.getAttribute(element, "tid"); this.val = XMLUtils.getAttribute(element, "VAL"); if (this.val == null) { this.val = XMLUtils.getAttribute(element, "value"); } this.altVal = XMLUtils.getAttribute(element, "alt_value"); this.type = XMLUtils.getAttribute(element, "type"); if (type == null) { this.type = XMLUtils.getAttribute(element, "TYPE"); } // if (this.type != null) { // this.type = this.type.intern(); // } // Optional attributes String beginPoint = XMLUtils.getAttribute(element, "beginPoint"); this.beginPoint = (beginPoint == null || beginPoint.length() == 0)? -1 : Integer.parseInt(beginPoint.substring(1)); String endPoint = XMLUtils.getAttribute(element, "endPoint"); this.endPoint = (endPoint == null || endPoint.length() == 0)? -1 : Integer.parseInt(endPoint.substring(1)); // Optional range String rangeStr = XMLUtils.getAttribute(element, "range"); if (rangeStr != null) { if (rangeStr.startsWith("(") && rangeStr.endsWith(")")) { rangeStr = rangeStr.substring(1, rangeStr.length()-1); } String[] parts = rangeStr.split(","); this.range = new Range(parts.length > 0? parts[0]:"", parts.length > 1? parts[1]:"", parts.length > 2? parts[2]:""); } } public int beginPoint() { return beginPoint; } public int endPoint() { return endPoint; } public String toString() { return (this.xml != null) ? this.xml : this.val; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Timex timex = (Timex) o; if (beginPoint != timex.beginPoint) { return false; } if (endPoint != timex.endPoint) { return false; } if (type != null ? !type.equals(timex.type) : timex.type != null) { return false; } if (val != null ? !val.equals(timex.val) : timex.val != null) { return false; } return true; } @Override public int hashCode() { int result = val != null ? val.hashCode() : 0; result = 31 * result + (type != null ? type.hashCode() : 0); result = 31 * result + beginPoint; result = 31 * result + endPoint; return result; } public Element toXmlElement() { Element element = XMLUtils.createElement("TIMEX3"); if (tid != null) { element.setAttribute("tid", tid); } if (value() != null) { element.setAttribute("value", val); } if (altVal != null) { element.setAttribute("altVal", altVal); } if (type != null) { element.setAttribute("type", type); } if (beginPoint != -1) { element.setAttribute("beginPoint", "t" + String.valueOf(beginPoint)); } if (endPoint != -1) { element.setAttribute("endPoint", "t" + String.valueOf(endPoint)); } if (text != null) { element.setTextContent(text); } return element; } // Used to create timex from XML (mainly for testing) public static Timex fromXml(String xml) { Element element = XMLUtils.parseElement(xml); if ("TIMEX3".equals(element.getNodeName())) { Timex t = new Timex(); // t.init(xml, element); // Doesn't preserve original input xml // Will reorder attributes of xml so can match xml of test timex and actual timex // (for which we can't control the order of the attributes now we don't use nu.xom...) t.init(element); return t; } else { throw new IllegalArgumentException("Invalid timex xml: " + xml); } } public static Timex fromMap(String text, Map<String, String> map) { try { Element element = XMLUtils.createElement("TIMEX3"); for (Map.Entry<String, String> entry : map.entrySet()) { if (entry.getValue() != null) { element.setAttribute(entry.getKey(), entry.getValue()); } } element.setTextContent(text); return new Timex(element); } catch (Exception ex) { throw new RuntimeException(ex); } } /** * Gets the Calendar matching the year, month and day of this Timex. * * @return The matching Calendar. */ public Calendar getDate() { if (Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); int day = Integer.parseInt(this.val.substring(8, 10)); return makeCalendar(year, month, day); } else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return makeCalendar(year, month, day); } throw new UnsupportedOperationException(String.format("%s is not a fully specified date", this)); } /** * Gets two Calendars, marking the beginning and ending of this Timex's range. * * @return The begin point and end point Calendars. */ public Pair<Calendar, Calendar> getRange() { return this.getRange(null); } /** * Gets two Calendars, marking the beginning and ending of this Timex's range. * * @param documentTime * The time the document containing this Timex was written. (Not * necessary for resolving all Timex expressions. This may be * {@code null}, but then relative time expressions cannot be * resolved.) * @return The begin point and end point Calendars. */ public Pair<Calendar, Calendar> getRange(Timex documentTime) { if (this.val == null) { throw new UnsupportedOperationException("no value specified for " + this); } // YYYYMMDD or YYYYMMDDT... where the time is concatenated directly with the // date else if (val.length() >= 8 && Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d", this.val.substring(0, 8))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYY-MM-DD or YYYY-MM-DDT... else if (val.length() >= 10 && Pattern.matches("\\d\\d\\d\\d-\\d\\d-\\d\\d", this.val.substring(0, 10))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); int day = Integer.parseInt(this.val.substring(8, 10)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYYMMDDL+ else if (Pattern.matches("\\d\\d\\d\\d\\d\\d\\d\\d[A-Z]+", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); int day = Integer.parseInt(this.val.substring(6, 8)); return new Pair<>(makeCalendar(year, month, day), makeCalendar(year, month, day)); } // YYYYMM or YYYYMMT... else if (val.length() >= 6 && Pattern.matches("\\d\\d\\d\\d\\d\\d", this.val.substring(0, 6))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(4, 6)); Calendar begin = makeCalendar(year, month, 1); int lastDay = begin.getActualMaximum(Calendar.DATE); Calendar end = makeCalendar(year, month, lastDay); return new Pair<>(begin, end); } // YYYY-MM or YYYY-MMT... else if (val.length() >= 7 && Pattern.matches("\\d\\d\\d\\d-\\d\\d", this.val.substring(0, 7))) { int year = Integer.parseInt(this.val.substring(0, 4)); int month = Integer.parseInt(this.val.substring(5, 7)); Calendar begin = makeCalendar(year, month, 1); int lastDay = begin.getActualMaximum(Calendar.DATE); Calendar end = makeCalendar(year, month, lastDay); return new Pair<>(begin, end); } // YYYY or YYYYT... else if (val.length() >= 4 && Pattern.matches("\\d\\d\\d\\d", this.val.substring(0, 4))) { int year = Integer.parseInt(this.val.substring(0, 4)); return new Pair<>(makeCalendar(year, 1, 1), makeCalendar(year, 12, 31)); } // PDDY if (Pattern.matches("P\\d+Y", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int yearRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.YEAR, yearRange); return new Pair<>(start, end); } // in the past else if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.YEAR, 0 - yearRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // PDDM if (Pattern.matches("P\\d+M", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int monthRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.MONTH, monthRange); return new Pair<>(start, end); } // in the past if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.MONTH, 0 - monthRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // PDDD if (Pattern.matches("P\\d+D", this.val) && documentTime != null) { Calendar rc = documentTime.getDate(); int dayRange = Integer.parseInt(this.val.substring(1, this.val.length() - 1)); // in the future if (this.beginPoint < this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); end.add(Calendar.DAY_OF_MONTH, dayRange); return new Pair<>(start, end); } // in the past if (this.beginPoint > this.endPoint) { Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); start.add(Calendar.DAY_OF_MONTH, 0 - dayRange); return new Pair<>(start, end); } throw new RuntimeException("begin and end are equal " + this); } // YYYYSP if (Pattern.matches("\\d+SP", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 2, 1); Calendar end = makeCalendar(year, 4, 31); return new Pair<>(start, end); } // YYYYSU if (Pattern.matches("\\d+SU", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 5, 1); Calendar end = makeCalendar(year, 7, 31); return new Pair<>(start, end); } // YYYYFA if (Pattern.matches("\\d+FA", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 8, 1); Calendar end = makeCalendar(year, 10, 31); return new Pair<>(start, end); } // YYYYWI if (Pattern.matches("\\d+WI", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); Calendar start = makeCalendar(year, 11, 1); Calendar end = makeCalendar(year + 1, 1, 29); return new Pair<>(start, end); } // YYYYWDD if (Pattern.matches("\\d\\d\\d\\dW\\d+", this.val)) { int year = Integer.parseInt(this.val.substring(0, 4)); int week = Integer.parseInt(this.val.substring(5)); int startDay = (week - 1) * 7; int endDay = startDay + 6; Calendar start = makeCalendar(year, startDay); Calendar end = makeCalendar(year, endDay); return new Pair<>(start, end); } // PRESENT_REF if (this.val.equals("PRESENT_REF")) { Calendar rc = documentTime.getDate(); // todo: This case doesn't check for documentTime being null and will NPE Calendar start = copyCalendar(rc); Calendar end = copyCalendar(rc); return new Pair<>(start, end); } throw new RuntimeException(String.format("unknown value \"%s\" in %s", this.val, this)); } private static Calendar makeCalendar(int year, int month, int day) { Calendar date = Calendar.getInstance(); date.clear(); date.set(year, month - 1, day, 0, 0, 0); return date; } private static Calendar makeCalendar(int year, int dayOfYear) { Calendar date = Calendar.getInstance(); date.clear(); date.set(Calendar.YEAR, year); date.set(Calendar.DAY_OF_YEAR, dayOfYear); return date; } private static Calendar copyCalendar(Calendar c) { Calendar date = Calendar.getInstance(); date.clear(); date.set(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.HOUR_OF_DAY), c .get(Calendar.MINUTE), c.get(Calendar.SECOND)); return date; } }
rupenp/CoreNLP
src/edu/stanford/nlp/time/Timex.java
Java
gpl-2.0
19,256
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This file is part of guh. * * * * Guh 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 2 of the License. * * * * Guh 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 guh. If not, see <http://www.gnu.org/licenses/>. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*! \page openweathermap.html \title Open Weather Map \ingroup plugins \ingroup services This plugin alows you to get the current weather data from \l{http://www.openweathermap.org}. The plugin offers two different search methods: if the user searches for a empty string, the plugin makes an autodetction with the WAN ip and offers the user the found autodetectresult. Otherwise the plugin return the list with the found searchresults. \section1 Examples \section2 Autodetect location If you want to autodetect your location dend a discovery request with an empty string. \code { "id":1, "method":"Devices.GetDiscoveredDevices", "params":{ "deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7", "discoveryParams": { "location":"" } } } \endcode response from autodetection... \code { "id": 1, "params": { "deviceDescriptors": [ { "description": "AT", "id": "{75607672-5354-428f-a752-910140c22b18}", "title": "Vienna" } ], "errorMessage": "", "success": true }, "status": "success" } \endcode \section2 Searching city If you want to search a string send following discovery message: \code { "id":1, "method":"Devices.GetDiscoveredDevices", "params":{ "deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7", "discoveryParams": { "location":"Vie" } } } \endcode response... \code { "id": 1, "params": { "deviceDescriptors": [ { "description": "DE", "id": "{6dc6be43-5bdc-4dbd-bcbf-6f8e1f90000b}", "title": "Viersen" }, { "description": "VN", "id": "{af275298-77f1-40b4-843a-d0f3c7aef6bb}", "title": "Viet Tri" }, { "description": "DE", "id": "{86a4ab63-41b4-4348-9830-4bf6c87474bf}", "title": "Viernheim" }, { "description": "AR", "id": "{3b5f8eea-6159-4375-bd01-1f07de9c3a9d}", "title": "Viedma" }, { "description": "FR", "id": "{f3b91f26-3275-4bb4-a594-924202a2124e}", "title": "Vierzon" }, { "description": "AT", "id": "{b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd}", "title": "Vienna" } ], "errorMessage": "", "success": true }, "status": "success" } \endcode \section2 Adding a discovered city If you want to add a dicovered city send the add "AddConfiguredDevice" message with the deviceDescriptorId from the searchresult list. In this example the id for Vienna. \code { "id":1, "method":"Devices.AddConfiguredDevice", "params":{ "deviceClassId":"985195aa-17ad-4530-88a4-cdd753d747d7", "deviceDescriptorId": "b59d15f7-f52b-43a0-a9c5-a3fa80cbc2bd" } } \endcode response... \code { "id": 1, "params": { "deviceId": "{af0f1958-b901-48da-ad97-d4d64af88cf8}", "errorMessage": "", "success": true }, "status": "success" } \endcode \section1 Plugin propertys: \section2 Plugin parameters Each configured plugin has following paramters: \table \header \li Name \li Description \li Data Type \row \li location \li This parameter holds the name of the city \li string \row \li country \li This parameter holds the country of the city \li string \row \li id \li This parameter holds the city id from \l{http://www.openweathermap.org} \li string \endtable \section2 Actions Following list contains all plugin \l{Action}s: \table \header \li Name \li Description \li UUID \row \li refresh \li This action refreshes all states. \li cfbc6504-d86f-4856-8dfa-97b6fbb385e4 \endtable \section2 States Following list contains all plugin \l{State}s: \table \header \li Name \li Description \li UUID \li Data Type \row \li city name \li The name of the city \li fd9e7b7f-cf1f-4093-8f6d-fff5b223471f \li string \row \li city id \li The city ID for openweathermap.org \li c6ef1c07-e817-4251-b83d-115bbf6f0ae9 \li string \row \li country name \li The country name \li 0e607a5f-1938-4e77-a146-15e9ad15bfad \li string \row \li last update \li The timestamp of the weather data from the weatherstation in unixtime format \li 98e48095-87da-47a4-b812-28c6c17a3e76 \li unsignend int \row \li temperature \li Current temperature [Celsius] \li 2f949fa3-ff21-4721-87ec-0a5c9d0a5b8a \li double \row \li temperature minimum \li Today temperature minimum [Clesius] \li 701338b3-80de-4c95-8abf-26f44529d620 \li double \row \li temperature maximum \li Today temperature maximum [Clesius] \li f69bedd2-c997-4a7d-9242-76bf2aab3d3d \li double \row \li humidity \li Current relative humidity [%] \li 3f01c9f0-206b-4477-afa2-80d6e5e54fbb \li int \row \li pressure \li Current pressure [hPa] \li 6a57b6e9-7010-4a89-982c-ce0bc2a71f11 \li double \row \li wind speed \li Current wind speed [m/s] \li 12dc85a9-825d-4375-bef4-abd66e9e301b \li double \row \li wind direction \li The wind direction rellative to the north pole [degree] \li a8b0383c-d615-41fe-82b8-9b797f045cc9 \li int \row \li cloudiness \li This value represents how much of the sky is clowdy [%] \li 0c1dc881-560e-40ac-a4a1-9ab69138cfe3 \li int \row \li weather description \li This string describes the current weather condition in clear words \li e71d98e3-ebd8-4abf-ad25-9ecc2d05276a \li string \row \li sunset \li The time of todays sunset in unixtime format \li 5dd6f5a3-25d6-4e60-82ca-e934ad76a4b6 \li unsigned int \row \li sunrise \li The time of todays sunrise in unixtime format \li 413b3fc6-bd1c-46fb-8c86-03096254f94f \li unsigned int \endtable */ #include "devicepluginopenweathermap.h" #include "plugin/device.h" #include "devicemanager.h" #include <QDebug> #include <QJsonDocument> #include <QVariantMap> #include <QDateTime> DeviceClassId openweathermapDeviceClassId = DeviceClassId("985195aa-17ad-4530-88a4-cdd753d747d7"); ActionTypeId updateWeatherActionTypeId = ActionTypeId("cfbc6504-d86f-4856-8dfa-97b6fbb385e4"); StateTypeId updateTimeStateTypeId = StateTypeId("36b2f09b-7d77-4fbc-a68f-23d735dda0b1"); StateTypeId temperatureStateTypeId = StateTypeId("6013402f-b5b1-46b3-8490-f0c20d62fe61"); StateTypeId temperatureMinStateTypeId = StateTypeId("14ec2781-cb04-4bbf-b097-7d01ef982630"); StateTypeId temperatureMaxStateTypeId = StateTypeId("fefe5563-452f-4833-b5cf-49c3cc67c772"); StateTypeId humidityStateTypeId = StateTypeId("6f32ec73-3240-4630-ada9-1c10b8e98123"); StateTypeId pressureStateTypeId = StateTypeId("4a42eea9-00eb-440b-915e-dbe42180f83b"); StateTypeId windSpeedStateTypeId = StateTypeId("2bf63430-e9e2-4fbf-88e6-6f1b4770f287"); StateTypeId windDirectionStateTypeId = StateTypeId("589e2ea5-65b2-4afd-9b72-e3708a589a12"); StateTypeId cloudinessStateTypeId = StateTypeId("798553bc-45c7-42eb-9105-430bddb5d9b7"); StateTypeId weatherDescriptionStateTypeId = StateTypeId("f9539108-0e0e-4736-a306-6408f8e20a26"); StateTypeId sunriseStateTypeId = StateTypeId("af155e94-9492-44e1-8608-7d0ee8b5d50d"); StateTypeId sunsetStateTypeId = StateTypeId("a1dddc3d-549f-4f20-b78b-be850548f286"); DevicePluginOpenweathermap::DevicePluginOpenweathermap() { m_openweaher = new OpenWeatherMap(this); connect(m_openweaher, &OpenWeatherMap::searchResultReady, this, &DevicePluginOpenweathermap::searchResultsReady); connect(m_openweaher, &OpenWeatherMap::weatherDataReady, this, &DevicePluginOpenweathermap::weatherDataReady); } DeviceManager::DeviceError DevicePluginOpenweathermap::discoverDevices(const DeviceClassId &deviceClassId, const ParamList &params) { if(deviceClassId != openweathermapDeviceClassId){ return DeviceManager::DeviceErrorDeviceClassNotFound; } QString location; foreach (const Param &param, params) { if (param.name() == "location") { location = param.value().toString(); } } // if we have an empty search string, perform an autodetection of the location with the WAN ip... if (location.isEmpty()){ m_openweaher->searchAutodetect(); } else { m_openweaher->search(location); } // otherwise search the given string m_openweaher->search(location); return DeviceManager::DeviceErrorAsync; } DeviceManager::DeviceSetupStatus DevicePluginOpenweathermap::setupDevice(Device *device) { foreach (Device *deviceListDevice, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) { if(deviceListDevice->paramValue("id").toString() == device->paramValue("id").toString()){ qWarning() << QString("Location " + device->paramValue("location").toString() + " already added."); return DeviceManager::DeviceSetupStatusFailure; } } device->setName("Weather from OpenWeatherMap (" + device->paramValue("location").toString() + ")"); m_openweaher->update(device->paramValue("id").toString(), device->id()); return DeviceManager::DeviceSetupStatusSuccess; } DeviceManager::HardwareResources DevicePluginOpenweathermap::requiredHardware() const { return DeviceManager::HardwareResourceTimer; } DeviceManager::DeviceError DevicePluginOpenweathermap::executeAction(Device *device, const Action &action) { if(action.actionTypeId() == updateWeatherActionTypeId){ m_openweaher->update(device->paramValue("id").toString(), device->id()); } return DeviceManager::DeviceErrorNoError; } void DevicePluginOpenweathermap::guhTimer() { foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) { m_openweaher->update(device->paramValue("id").toString(), device->id()); } } void DevicePluginOpenweathermap::searchResultsReady(const QList<QVariantMap> &cityList) { QList<DeviceDescriptor> retList; foreach (QVariantMap elemant, cityList) { DeviceDescriptor descriptor(openweathermapDeviceClassId, elemant.value("name").toString(),elemant.value("country").toString()); ParamList params; Param locationParam("location", elemant.value("name")); params.append(locationParam); Param countryParam("country", elemant.value("country")); params.append(countryParam); Param idParam("id", elemant.value("id")); params.append(idParam); descriptor.setParams(params); retList.append(descriptor); } emit devicesDiscovered(openweathermapDeviceClassId,retList); } void DevicePluginOpenweathermap::weatherDataReady(const QByteArray &data, const DeviceId &deviceId) { QJsonParseError error; QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error); if(error.error != QJsonParseError::NoError) { qWarning() << "failed to parse data" << data << ":" << error.errorString(); return; } QVariantMap dataMap = jsonDoc.toVariant().toMap(); foreach (Device *device, deviceManager()->findConfiguredDevices(openweathermapDeviceClassId)) { if(device->id() == deviceId){ if(dataMap.contains("clouds")){ int cloudiness = dataMap.value("clouds").toMap().value("all").toInt(); device->setStateValue(cloudinessStateTypeId,cloudiness); } if(dataMap.contains("dt")){ uint lastUpdate = dataMap.value("dt").toUInt(); device->setStateValue(updateTimeStateTypeId,lastUpdate); } if(dataMap.contains("main")){ double temperatur = dataMap.value("main").toMap().value("temp").toDouble(); double temperaturMax = dataMap.value("main").toMap().value("temp_max").toDouble(); double temperaturMin = dataMap.value("main").toMap().value("temp_min").toDouble(); double pressure = dataMap.value("main").toMap().value("pressure").toDouble(); int humidity = dataMap.value("main").toMap().value("humidity").toInt(); device->setStateValue(temperatureStateTypeId,temperatur); device->setStateValue(temperatureMinStateTypeId,temperaturMin); device->setStateValue(temperatureMaxStateTypeId,temperaturMax); device->setStateValue(pressureStateTypeId,pressure); device->setStateValue(humidityStateTypeId,humidity); } if(dataMap.contains("sys")){ uint sunrise = dataMap.value("sys").toMap().value("sunrise").toUInt(); uint sunset = dataMap.value("sys").toMap().value("sunset").toUInt(); device->setStateValue(sunriseStateTypeId,sunrise); device->setStateValue(sunsetStateTypeId,sunset); } if(dataMap.contains("weather")){ QString description = dataMap.value("weather").toMap().value("description").toString(); device->setStateValue(weatherDescriptionStateTypeId,description); } if(dataMap.contains("wind")){ int windDirection = dataMap.value("wind").toMap().value("deg").toInt(); double windSpeed = dataMap.value("wind").toMap().value("speed").toDouble(); device->setStateValue(windDirectionStateTypeId,windDirection); device->setStateValue(windSpeedStateTypeId,windSpeed); } } } }
mzanetti/guh
plugins/deviceplugins/openweathermap/devicepluginopenweathermap.cpp
C++
gpl-2.0
17,008
/*************************************************************************/ /*! @File @Title Services definitions required by external drivers @Copyright Copyright (c) Imagination Technologies Ltd. All Rights Reserved @Description Provides services data structures, defines and prototypes required by external drivers @License Dual MIT/GPLv2 The contents of this file are subject to the MIT license as set out below. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Alternatively, the contents of this file may be used under the terms of the GNU General Public License Version 2 ("GPL") in which case the provisions of GPL are applicable instead of those above. If you wish to allow use of your version of this file only under the terms of GPL, and not to allow others to use your version of this file under the terms of the MIT license, indicate your decision by deleting the provisions above and replace them with the notice and other provisions required by GPL as set out in the file called "GPL-COPYING" included in this distribution. If you do not delete the provisions above, a recipient may use your version of this file under the terms of either the MIT license or GPL. This License is also included in this distribution in the file called "MIT-COPYING". EXCEPT AS OTHERWISE STATED IN A NEGOTIATED AGREEMENT: (A) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT; AND (B) IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #if !defined (__SERVICESEXT_H__) #define __SERVICESEXT_H__ /* include/ */ #include "pvrsrv_error.h" #include "img_types.h" #include "pvrsrv_device_types.h" /* * Lock buffer read/write flags */ #define PVRSRV_LOCKFLG_READONLY (1) /*!< The locking process will only read the locked surface */ /*! ***************************************************************************** * Services State *****************************************************************************/ typedef enum _PVRSRV_SERVICES_STATE_ { PVRSRV_SERVICES_STATE_OK = 0, PVRSRV_SERVICES_STATE_BAD, } PVRSRV_SERVICES_STATE; /*! ***************************************************************************** * States for power management *****************************************************************************/ /*! System Power State Enum */ typedef enum _PVRSRV_SYS_POWER_STATE_ { PVRSRV_SYS_POWER_STATE_Unspecified = -1, /*!< Unspecified : Uninitialised */ PVRSRV_SYS_POWER_STATE_OFF = 0, /*!< Off */ PVRSRV_SYS_POWER_STATE_ON = 1, /*!< On */ PVRSRV_SYS_POWER_STATE_FORCE_I32 = 0x7fffffff /*!< Force enum to be at least 32-bits wide */ } PVRSRV_SYS_POWER_STATE, *PPVRSRV_SYS_POWER_STATE; /*!< Typedef for ptr to PVRSRV_SYS_POWER_STATE */ /*! Device Power State Enum */ typedef enum _PVRSRV_DEV_POWER_STATE_ { PVRSRV_DEV_POWER_STATE_DEFAULT = -1, /*!< Default state for the device */ PVRSRV_DEV_POWER_STATE_OFF = 0, /*!< Unpowered */ PVRSRV_DEV_POWER_STATE_ON = 1, /*!< Running */ PVRSRV_DEV_POWER_STATE_FORCE_I32 = 0x7fffffff /*!< Force enum to be at least 32-bits wide */ } PVRSRV_DEV_POWER_STATE, *PPVRSRV_DEV_POWER_STATE; /*!< Typedef for ptr to PVRSRV_DEV_POWER_STATE */ /* PRQA S 3205 */ /* Power transition handler prototypes */ /*! Typedef for a pointer to a Function that will be called before a transition from one power state to another. See also PFN_POST_POWER. */ typedef PVRSRV_ERROR (*PFN_PRE_POWER) (IMG_HANDLE hDevHandle, PVRSRV_DEV_POWER_STATE eNewPowerState, PVRSRV_DEV_POWER_STATE eCurrentPowerState, IMG_BOOL bForced); /*! Typedef for a pointer to a Function that will be called after a transition from one power state to another. See also PFN_PRE_POWER. */ typedef PVRSRV_ERROR (*PFN_POST_POWER) (IMG_HANDLE hDevHandle, PVRSRV_DEV_POWER_STATE eNewPowerState, PVRSRV_DEV_POWER_STATE eCurrentPowerState, IMG_BOOL bForced); /* Clock speed handler prototypes */ /*! Typedef for a pointer to a Function that will be caled before a transition from one clockspeed to another. See also PFN_POST_CLOCKSPEED_CHANGE. */ typedef PVRSRV_ERROR (*PFN_PRE_CLOCKSPEED_CHANGE) (IMG_HANDLE hDevHandle, IMG_BOOL bIdleDevice, PVRSRV_DEV_POWER_STATE eCurrentPowerState); /*! Typedef for a pointer to a Function that will be caled after a transition from one clockspeed to another. See also PFN_PRE_CLOCKSPEED_CHANGE. */ typedef PVRSRV_ERROR (*PFN_POST_CLOCKSPEED_CHANGE) (IMG_HANDLE hDevHandle, IMG_BOOL bIdleDevice, PVRSRV_DEV_POWER_STATE eCurrentPowerState); /*! ***************************************************************************** * Enumeration of possible alpha types. *****************************************************************************/ typedef enum _PVRSRV_ALPHA_FORMAT_ { PVRSRV_ALPHA_FORMAT_UNKNOWN = 0x00000000, /*!< Alpha Format: Unknown */ PVRSRV_ALPHA_FORMAT_PRE = 0x00000001, /*!< Alpha Format: Pre-Alpha */ PVRSRV_ALPHA_FORMAT_NONPRE = 0x00000002, /*!< Alpha Format: Non-Pre-Alpha */ PVRSRV_ALPHA_FORMAT_MASK = 0x0000000F, /*!< Alpha Format Mask */ } PVRSRV_ALPHA_FORMAT; /*! ***************************************************************************** * Enumeration of possible alpha types. *****************************************************************************/ typedef enum _PVRSRV_COLOURSPACE_FORMAT_ { PVRSRV_COLOURSPACE_FORMAT_UNKNOWN = 0x00000000, /*!< Colourspace Format: Unknown */ PVRSRV_COLOURSPACE_FORMAT_LINEAR = 0x00010000, /*!< Colourspace Format: Linear */ PVRSRV_COLOURSPACE_FORMAT_NONLINEAR = 0x00020000, /*!< Colourspace Format: Non-Linear */ PVRSRV_COLOURSPACE_FORMAT_MASK = 0x000F0000, /*!< Colourspace Format Mask */ } PVRSRV_COLOURSPACE_FORMAT; /*! * Drawable orientation (in degrees clockwise). */ typedef enum _PVRSRV_ROTATION_ { PVRSRV_ROTATE_0 = 0, /*!< Rotate by 0 degres */ PVRSRV_ROTATE_90 = 1, /*!< Rotate by 90 degrees */ PVRSRV_ROTATE_180 = 2, /*!< Rotate by 180 degrees */ PVRSRV_ROTATE_270 = 3, /*!< Rotate by 270 degrees */ PVRSRV_FLIP_Y = 4, /*!< Flip in Y axis */ } PVRSRV_ROTATION; /*! ***************************************************************************** * This structure is used for OS independent registry (profile) access *****************************************************************************/ typedef struct _PVRSRV_REGISTRY_INFO { IMG_UINT32 ui32DevCookie; IMG_PCHAR pszKey; IMG_PCHAR pszValue; IMG_PCHAR pszBuf; IMG_UINT32 ui32BufSize; } PVRSRV_REGISTRY_INFO, *PPVRSRV_REGISTRY_INFO; #endif /* __SERVICESEXT_H__ */ /***************************************************************************** End of file (servicesext.h) *****************************************************************************/
jmztaylor/android_kernel_amazon_ariel
drivers/gpu/mt8135/rgx_1.3_2876724/include/servicesext.h
C
gpl-2.0
7,801
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_sel_lastoftypediff.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:35:39 GMT --> <head> <script src="../../ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var btn = $(this).text(); $("p").css("background-color","white"); $("p" + btn).css("background-color","yellow"); }); }); </script> </head> <body> <button>:last</button> <button>:last-child</button> <button>:last-of-type</button><br> <p>The first paragraph in body, and the first child in div.</p> <div style="border:1px solid;"> <p>The first paragraph in div, and the first child in div.</p> <p>The last paragraph in div, and the last child in div.</p> </div><br> <div style="border:1px solid;"> <span>This is a span element, and the first child in this div.</span> <p>The first paragraph in another div, and the second child in this div.</p> <p>The last paragraph in another div, and the third child in this div.</p> <span>This is a span element, and the last child in this div.</span> </div><br> <div style="border:1px solid"> <p>The first paragraph in another div, and the first child in this div.</p> <p>The last paragraph in the another div, and the last child in this div.</p> </div> <p>The last paragraph in body, and the last child in div.</p> </body> <!-- Mirrored from www.w3schools.com/jquery/tryjquery_sel_lastoftypediff.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:35:39 GMT --> </html>
platinhom/ManualHom
Coding/W3School/W3Schools_Offline_2015/www.w3schools.com/jquery/tryjquery_sel_lastoftypediff.html
HTML
gpl-2.0
1,591
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible"content="IE=9; IE=8; IE=7; IE=EDGE"> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <meta name="desCRipTion" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®»¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨" /> <title>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®_±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®-dld158ÓéÀÖ{°Ù¶ÈÐÂÎÅ}°Ù¶ÈÈÏÖ¤</title> <!--ÈÈÁ¦Í¼¿ªÊ¼--> <meta name="uctk" content="enabled"> <!--ÈÈÁ¦Í¼½áÊø--> <meta name="keywords" content="±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®"/> <meta name="desCRipTion" content="»¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨"/> <meta name="sitename" content="Ê×¶¼Ö®´°-±±¾©ÊÐÕþÎñÃÅ»§ÍøÕ¾"> <meta name="siteurl" content="http://www.beijing.gov.cn"> <meta name="district" content="±±¾©" > <meta name="filetype" content="0"> <meta name="publishedtype" content="1"> <meta name="pagetype" content="2"> <meta name="subject" content="28428;1"> <!-- Le styles --> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap150609.css" rel="stylesheet"> <link href="http://www.beijing.gov.cn/images/zhuanti/xysym/bootstrap-responsive150609.css" rel="stylesheet"> <style> body { background:#E8E8E8; /* 60px to make the container go all the way to the bottom of the topbar */ } .navbar .btn-navbar { position:absolute; right:0; margin-top:50px;} #othermessage p {width:50%;} #othermessage dl { width:50%;} #breadcrumbnav ul { width:100%;} #breadcrumbnav ul li { line-height:14px; font-family:"ËÎÌå"; padding:0px 10px; margin:0; background:none; } #othermessage span { padding:0px 10px;} #footer { margin:20px -20px 0px -20px;} .navbar .nav li a { font-family:"Microsoft YaHei";} #div_zhengwen { font-family:"SimSun";} #div_zhengwen p{ font-family:"SimSun"; padding:0;} select { width:75px; float:left; height:35px;} .search .input{ border:1px solid #c1c1c1; width:290px;} .bdsharebuttonbox { float:left; width:80%;} .navbar .nav li a { padding: 10px 48px 11px 49px;} .nav_weather span { float:right;} #footer { position:absolute; left:0; right:0; margin:20px 0 0 0;} #essaybottom {font-family:"simsun"; } #pic { text-align:center; } #pic ul { padding-top:10px; display:none; } #pic li {font-family:"SimSun";} .content_text h1 {line-height:150%;} .version { float:right; padding:48px 50px 0 0} .search { padding: 50px 0 0 70px;} .nav_weather a { font-family:simsun;} .version li a { font-family:simsun;} .footer-class { font-family:simsun;} @media only screen and (max-width: 480px) { #pic img { width:100%;} } @media only screen and (max-width: 320px) { #pic img { width:100%;} } @media only screen and (max-width: 640px) { #pic img { width:100%;} } #filerider .filelink {font-family:"SimSun";} #filerider .filelink a:link { color:#0000ff; font-family:"SimSun";} </style> <sCRipT type="text/javasCRipT"> var pageName = "t1424135"; var pageExt = "htm"; var pageIndex = 0 + 1; var pageCount = 1; function getCurrentPage() { document.write(pageIndex); } function generatePageList() { for (i=0;i<1;i++) { var curPage = i+1; document.write('<option value=' + curPage); if (curPage == pageIndex) document.write(' selected'); document.write('>' + curPage + '</option>'); } } function preVious(n) { if (pageIndex == 1) { alert('ÒѾ­ÊÇÊ×Ò³£¡'); } else { getPageLocation(pageIndex-1); } } function next(n) { if (pageIndex == pageCount) { alert('ÒѾ­ÊÇβҳ£¡'); } else { nextPage(pageIndex); } } function nextPage(page) { var gotoPage = ""; if (page == 0) { gotoPage = pageName + "." + pageExt; } else { gotoPage = pageName + "_" + page + "." + pageExt; } location.href = gotoPage; } function getPageLocation(page) { var gotoPage = ""; var tpage; if (page == 1) { gotoPage = pageName + "." + pageExt; } else { tpage=page-1; gotoPage = pageName + "_" + tpage + "." + pageExt; } location.href = gotoPage; } </sCRipT> <SCRIPT type=text/javasCRipT> function $(xixi) { return document.getElementById(xixi); } //ת»»×ֺŠfunction doZoom(size){ if(size==12){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = ""; $("fs14").style.display = "none"; $("fs16").style.display = "none"; } if(size==14){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = ""; $("fs16").style.display = "none"; } if(size==16){ $("contentText").style.fontSize = size + "px"; $("fs12").style.display = "none"; $("fs14").style.display = "none"; $("fs16").style.display = ""; } } </SCRIPT> <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <sCRipT src="//html5shim.googlecode.com/svn/trunk/html5.js"></sCRipT> <![endif]--> <!-- Le fav and touch icons --> <link rel="shortcut icon" href="images/favicon.ico"> <link rel="apple-touch-icon" href="images/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png"> <sCRipT type="text/javasCRipT"> window.onload = function(){ var picurl = [ "", "", "", "", "", "", "", "", "", "" ]; var i=0; for(i=0;i<picurl.length;i++) { picurl[i].index=i; if(picurl[i]!="") { document.getElementById("pic_"+i).style.display = "block"; } } } </sCRipT> </head> <body> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="nav_weather"> <div class="container"><a href="http://zhengwu.beijing.gov.cn/sld/swld/swsj/t1232150.htm" title="ÊÐί" target="_blank">ÊÐί</a> | <a href="http://www.bjrd.gov.cn/" title="ÊÐÈË´ó" target="_blank">ÊÐÈË´ó</a> | <a href="http://www.beijing.gov.cn/" title="ÊÐÕþ¸®" target="_blank">ÊÐÕþ¸®</a> | <a href="http://www.bjzx.gov.cn/" title="ÊÐÕþЭ" target="_blank">ÊÐÕþЭ</a></div> </div> <div class="container"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <div class="span12"> <a class="brand" href="http://www.beijing.gov.cn/"><img src="http://www.beijing.gov.cn/images/zhuanti/xysym/logo.png" /></a> <div class="search"> <sCRipT language="JavaScript" type="text/javasCRipT"> function checkForm(){ var temp = searchForm.temp.value; var database = searchForm.database.value; if(temp==null || temp==""){ alert("ÇëÊäÈëËÑË÷Ìõ¼þ"); } else{ var url="http://so.beijing.gov.cn/Query?qt="+encodeURIComponent(temp)+"&database="+encodeURIComponent(database); window.open(url); } return false; } </sCRipT> <form id="search" method="get" name="searchForm" action="" target="_blank" onSubmit="return checkForm()"> <input type="hidden" value="bj" id="database" name="database" /> <input name="temp" id="keyword" type="text" value="È«ÎÄËÑË÷" class="input" title="È«ÎÄËÑË÷¹Ø¼ü×Ö" /> <input id="searchbutton" type="image" src="http://www.beijing.gov.cn/images/zhuanti/xysym/search_btn.gif" width="66" height="35" title="µã»÷ËÑË÷" alt="ËÑË÷" /> </form> </div> <div class="version"><ul> <li><a title="ÎÞÕϰ­" href="http://wza.beijing.gov.cn/" target="_blank" id="yx_style_nav">ÎÞÕϰ­</a></li> <li><a target="_blank" title="·±Ìå°æ" href="http://210.75.193.158/gate/big5/www.beijing.gov.cn">·±Ìå</a></li> <li><a target="_blank" title="¼òÌå°æ" href="http://www.beijing.gov.cn">¼òÌå</a></li> <li class="last"><a target="_blank" title="English Version" href="http://www.ebeijing.gov.cn">English</a></li></ul><ul> <li><a href="javasCRipT:void(0)" onclick="SetHome(this,window.location)" title="ÉèΪÊ×Ò³">ÉèΪÊ×Ò³</a></li> <li><a title="¼ÓÈëÊÕ²Ø" href="javasCRipT:void(0)" onclick="shoucang(document.title,window.location)">¼ÓÈëÊÕ²Ø</a></li> <li class="last"><a target="_blank" title="ÒÆ¶¯°æ" href="http://www.beijing.gov.cn/sjbsy/">ÒÆ¶¯°æ</a></li></ul></div> </div> </div> <div class="nav-collapse"> <div class="container"> <ul class="nav"> <li ><a href="http://www.beijing.gov.cn/" class="normal" title="Ê×Ò³">Ê×Ò³</a></li> <li><a href="http://zhengwu.beijing.gov.cn/" class="normal" title="ÕþÎñÐÅÏ¢">ÕþÎñÐÅÏ¢</a></li> <li><a href="http://www.beijing.gov.cn/sqmy/default.htm" class="normal" title="ÉçÇéÃñÒâ">ÉçÇéÃñÒâ</a></li> <li><a href="http://banshi.beijing.gov.cn" class="normal" title="ÕþÎñ·þÎñ">ÕþÎñ·þÎñ</a></li> <li><a href="http://www.beijing.gov.cn/bmfw" class="normal" title="±ãÃñ·þÎñ">±ãÃñ·þÎñ</a></li> <li style="background:none;"><a href="http://www.beijing.gov.cn/rwbj/default.htm" class="normal" title="ÈËÎı±¾©">ÈËÎı±¾©</a></li> </ul> </div> </div><!--/.nav-collapse --> </div> </div> </div> <div class="container" style="background:#fff; margin-top:24px;"> <div class="content_text"> <div id="breadcrumbnav"> <ul> <li>Ê×Ò³¡¡>¡¡±ãÃñ·þÎñ¡¡>¡¡×îÐÂÌáʾ</li> </ul> <div class="clearboth"></div> </div> <h1>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <div id="othermessage"> <p> <span>À´Ô´£º±±¾©ÈÕ±¨</span> <span>ÈÕÆÚ£º2017-04-21 20:52:12</span></p> <dl> <sCRipT language='JavaScript' type="text/javasCRipT"> function changeSize(size){document.getElementById('div_zhengwen').style.fontSize=size+'px'}</sCRipT> ¡¾×ÖºÅ&nbsp;&nbsp;<a href='javasCRipT:changeSize(18)' style="font-size:16px;">´ó</a>&nbsp;&nbsp;<a href='javasCRipT:changeSize(14)' style="font-size:14px;">ÖÐ</a>&nbsp;&nbsp;<a href='javasCRipT:changeSize(12)' style="font-size:12px;">С</a>¡¿</dl> </div> </h1> <div id="div_zhengwen"> <div id="pic"> <ul id="pic_0"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_1"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_2"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_3"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_4"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_5"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_6"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_7"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_8"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> <ul id="pic_9"> <li><img src="" border="0" alt="" title="" /></li> <li></li> </ul> </div> <div class=TRS_Editor><p align="justify">¡¡¡¡±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® »¶Ó­´ó¼ÒÀ´µ½dld158.comÓéÀÖÆ½Ì¨</p> <img src="{img}" width="300" height="330"/> <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q8512341.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q4572165.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q2591990.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q8561463.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<a href="http://sapience.com.tw/logs/meng/q4521287.html">±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»®</a></p>±±¾©Èü³µpk10Ö®°ËÂë¹öÑ©Çò¼Æ»® <p align="justify">¡¡¡¡<p>¡¡¡¡ÈÕǰ£¬Â½¾üÊ×Ö§Å®×Óµ¼µ¯Á¬£¬Ó­À´ÁËËýÃǵÄ4Ëê¡°ÉúÈÕ¡±¡£</p> <p>¡¡¡¡2013Ä꣬°´ÕÕ½«Å®±ø±àÅä´Ó±£ÕϸÚλÏò×÷Õ½¸ÚÎ»ÍØÕ¹µÄÒªÇ󣬵Ú41¼¯Ížüµ³Î¯¾ö¶¨£¬´ÓËùÊô²¿¶Ó³éµ÷Å®±ø×齨һ¸öµ¼µ¯·¢ÉäÁ¬¡£µ±Äê3ÔÂ20ÈÕ£¬Ä³Âõ¼µ¯¶þÓªËÑË÷·¢ÉäÁ¬×齨Íê±ÏÕýʽµ®Éú¡£</p> <div align="center"><img src="http://photocdn.sohu.com/20170327/Img485062022.jpeg" alt="¡°Õþʶù¡±(gcxxjgzh)ÊáÀí·¢ÏÖ£¬¶Ì¶ÌËÄÄêÀ´£¬ÕâȺŮº¢10Óà´Î½ÓÊÜÉϼ¶¾üÊ¿¼ºË£¬´´ÏÂÁ˵¼µ¯Ò¹¼äÉä»÷¡¢´ò»÷³¬µÍ¿Õ¸ßËٰлúµÈ¶àÏîÈ«¾ü¼Í¼£¬±»ÆÀΪ¡°È«¹úÈý°ËºìÆì¼¯Ì塱¡¢¡°È«¹úÎåËĺìÆìÍÅÖ§²¿¡±¡¢Ô­¹ãÖݾüÇø¡°»ù²ã½¨Éè±ê±øµ¥Î»¡±¡¢¡°¾üÊÂѵÁ·¼â×ÓÁ¬¡±µÈÈÙÓþ³ÆºÅ¡£" align="middle" border="1" /</p></div> <div id="filerider"> <div class="filelink" style="margin:10px 0 0 0;"><a href="./P020160207382291268334.doc">¸½¼þ£º2016Äê±±¾©µØÇø²©Îï¹Ý´º½ÚϵÁлһÀÀ±í</a></div> </div> </div> <div id="essaybottom" style="border:0; overflow:hidden; margin-bottom:0;"> <div style="padding-bottom:8px;" id="proclaim"><p style="float:left; line-height:30px;">·ÖÏíµ½£º</p><div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone"></a><a href="#" class="bds_tsina" data-cmd="tsina"></a><a href="#" class="bds_tqq" data-cmd="tqq"></a><a href="#" class="bds_renren" data-cmd="renren"></a><a href="#" class="bds_weixin" data-cmd="weixin"></a></div> <sCRipT>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","tqq","renren","weixin"],"viewText":"·ÖÏíµ½£º","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","tqq","renren","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('sCRipT')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</sCRipT></div> </div> <div id="essaybottom" style="margin-top:0;"> <div style="padding-bottom:8px;" id="proclaim">תժÉùÃ÷£º×ªÕªÇë×¢Ã÷³ö´¦²¢×ö»ØÁ´</div> </div> </div> </div> <!-- /container --> <div id="footer"> <div class="container"> <div class="span1" style="text-align:center"><sCRipT type="text/javasCRipT">document.write(unescape("%3Cspan id='_ideConac' %3E%3C/span%3E%3CsCRipT src='http://dcs.conac.cn/js/01/000/0000/60429971/CA010000000604299710004.js' type='text/javasCRipT'%3E%3C/sCRipT%3E"));</sCRipT></div> <div class="span8"> <div class="footer-top"> <div class="footer-class"> <p> <a title="¹ØÓÚÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306339.htm" style=" background:0">¹ØÓÚÎÒÃÇ</a><a target="_blank" title="Õ¾µãµØÍ¼" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306342.htm">Õ¾µãµØÍ¼</a><a target="_blank" title="ÁªÏµÎÒÃÇ" href="http://www.beijing.gov.cn/zdxx/sdzcjs/t1306343.htm">ÁªÏµÎÒÃÇ</a><a target="_blank" title="ÆÀ¼ÛÊ×¶¼Ö®´°" href="mailto:[email protected]">ÆÀ¼ÛÊ×¶¼Ö®´°</a><a target="_blank" title="·¨ÂÉÉùÃ÷" href="http://www.beijing.gov.cn/zdxx/t709204.htm">·¨ÂÉÉùÃ÷</a> </p> <p>Ö÷°ì£º±±¾©ÊÐÈËÃñÕþ¸® °æÈ¨ËùÓга죺±±¾©Êо­¼ÃºÍÐÅÏ¢»¯Î¯Ô±»á ¾©ICP±¸05060933ºÅ ÔËÐйÜÀí£ºÊ×¶¼Ö®´°ÔËÐйÜÀíÖÐÐÄ</p> <p>¾©¹«Íø°²±¸ 110105000722 µØÖ·£º±±¾©Êг¯ÑôÇø±±³½Î÷·Êý×Ö±±¾©´óÏÃÄϰ˲㠴«Õ棺84371700 ¿Í·þÖÐÐĵ绰£º59321109</p> </div> </div> </div> </div> </div> <div style="display:none"> <sCRipT type="text/javasCRipT">document.write(unescape("%3CsCRipT src='http://yhfx.beijing.gov.cn/webdig.js?z=12' type='text/javasCRipT'%3E%3C/sCRipT%3E"));</sCRipT> <sCRipT type="text/javasCRipT">wd_paramtracker("_wdxid=000000000000000000000000000000000000000000")</sCRipT> </div> <sCRipT src="http://static.gridsumdissector.com/js/Clients/GWD-800003-C99186/gs.js" language="JavaScript"></sCRipT> <sCRipT type="text/javasCRipT"> // ÉèÖÃΪÖ÷Ò³ function SetHome(obj,vrl){ try{ obj.style.behavior='url(#default#homepage)';obj.setHomePage(vrl); } catch(e){ if(window.netscape) { try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); } catch (e) { alert("´Ë²Ù×÷±»ä¯ÀÀÆ÷¾Ü¾ø£¡\nÇëÔÚä¯ÀÀÆ÷µØÖ·À¸ÊäÈë¡°about:config¡±²¢»Ø³µ\nÈ»ºó½« [signed.applets.codebase_principal_support]µÄÖµÉèÖÃΪ'true',Ë«»÷¼´¿É¡£"); } var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); prefs.setCharPref('browser.startup.homepage',vrl); }else{ alert("ÄúµÄä¯ÀÀÆ÷²»Ö§³Ö£¬Çë°´ÕÕÏÂÃæ²½Öè²Ù×÷£º1.´ò¿ªä¯ÀÀÆ÷ÉèÖá£2.µã»÷ÉèÖÃÍøÒ³¡£3.ÊäÈ룺"+vrl+"µã»÷È·¶¨¡£"); } } } // ¼ÓÈëÊÕ²Ø ¼æÈÝ360ºÍIE6 function shoucang(sTitle,sURL) { try { window.external.addFavorite(sURL, sTitle); } catch (e) { try { window.sidebar.addPanel(sTitle, sURL, ""); } catch (e) { alert("¼ÓÈëÊÕ²ØÊ§°Ü£¬ÇëʹÓÃCtrl+D½øÐÐÌí¼Ó"); } } } </sCRipT> <!-- Le javasCRipT ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <sCRipT src="/images/zhuanti/xysym/jquery.js"></sCRipT> <sCRipT src="/images/zhuanti/xysym/bootstrap-collapse.js"></sCRipT> <sCRipT> $(document).ready(function(){ $(".ui-select").selectWidget({ change : function (changes) { return changes; }, effect : "slide", keyControl : true, speed : 200, scrollHeight : 250 }); }); </sCRipT> </body> </html>
ForAEdesWeb/AEW25
logs/meng/q0502601.html
HTML
gpl-2.0
17,668
ExpData_plot2 =============
erebuslabs/ExpData_plot2
README.md
Markdown
gpl-2.0
28
<HTML> <HEAD> <TITLE> Paint by Numbers - 32x32 #27</TITLE> </HEAD> <BODY> <h1> Paint by Numbers - 32x32 #27</h1> <p> <applet code=PBN10a.class name=Paint by Numbers width=616 height=556 > <param name=filename value=32x32/bridge.xbm> <param name=solved value=false> </applet> <p> Each number to the right of the grid gives the sizes of the contiguous blocks of black squares within that row. Each number below the grid does the same for its column. <p> <table border=1 cellpadding=3> <tr><td>To turn a square: <td>use this mouse button:<td>or this key with the mouse button: <tr><td align=center>black <td align=center>left <td align=center>none <tr><td align=center>white <td align=center>right <td align=center>Control <tr><td align=center>gray <td align=center>middle <td align=center>Shift </table> <p> You can drag the mouse to set a bunch of squares at one time. <p> <a href="printable/g32x32-27.html">Printable version of this puzzle</a><br> <a href="puzzles.html">Back to main page</a> </BODY> </HTML>
alijc/Paint-by-numbers
pbn-bnw/g32x32-27.html
HTML
gpl-2.0
1,035
#!/usr/bin/env python # # Copyright (C) 2007 Sascha Peilicke <[email protected]> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA # from random import randrange from zipfile import ZipFile from StringIO import StringIO # Constants DEFAULT_LEVELPACK = './data/default_pack.zip' SKILL_EASY = 'Easy' # These values should match the SKILL_MEDIUM = 'Medium' # the level files! SKILL_HARD = 'Hard' FIELD_INVALID = 0 # Constants describing a field on FIELD_VALID = 1 # the playfield FIELD_MARKED_VALID = 2 FIELD_MARKED_INVALID = 4 FIELD_OPEN = 8 class Game(object): """A paint by numbers game also called nonogram. """ def __init__(self, skill=None): """Creates a picross game. Parameters: skill - Desired skill level (None == random) """ self.__level = None self.__name = None self.__skill = None self.__fieldsToOpen = 0 self.__fieldsOpened = 0 self.load(skill=skill) # # Miscellaneous methods # def _debug_print(self): print self.getInfo() print 'go: %s' % (self.__gameOver) for row in self.__level: print row # # Game information retrieval # def getInfo(self): """Returns the name, skill and size of the level """ return self.__name,self.__skill,len(self.__level) def getRowHint(self,row): """Returns the hint for a specific row. """ hint,count = [],0 for columnItem in self.__level[row]: if columnItem == FIELD_VALID: count += 1 else: if count > 0: hint.append(count) count = 0 if count > 0: hint.append(count) if not hint: hint.append(0) return hint def getColumnHint(self,col): """Returns the hint for a specific column. """ hint,count = [],0 for row in self.__level: if row[col] == FIELD_VALID: count += 1 else: if count > 0: hint.append(count) count = 0 if count > 0: hint.append(count) if not hint: hint.append(0) return hint def getField(self,col,row): return self.__level[row][col] def isGameWon(self): return self.__fieldsOpened == self.__fieldsToOpen # # Game manipulation methods # def restart(self): """Reinitializes the current game """ for i, row in enumerate(self.__level): for j, field in enumerate(row): if field == FIELD_OPEN or field == FIELD_MARKED_VALID: self.__level[i][j] = FIELD_VALID elif field == FIELD_MARKED_INVALID: self.__level[i][j] = FIELD_INVALID self.__gameOver = False self.__fieldsOpened = 0 def openField(self,col,row): field = self.__level[row][col] if field == FIELD_VALID or field == FIELD_MARKED_VALID: self.__level[row][col] = FIELD_OPEN self.__fieldsOpened += 1 return True else: return False def markField(self,col,row): field = self.__level[row][col] if field == FIELD_VALID: self.__level[row][col] = FIELD_MARKED_VALID elif field == FIELD_MARKED_VALID: self.__level[row][col] = FIELD_VALID elif field == FIELD_INVALID: self.__level[row][col] = FIELD_MARKED_INVALID elif field == FIELD_MARKED_INVALID: self.__level[row][col] = FIELD_INVALID return self.__level[row][col] def load(self,file=DEFAULT_LEVELPACK,skill=None): """Loads a level either from a zipped levelpack or from a textfile. Parameters: file - Can be a file path or zipped levelpack skill - Desired level skill (None == random) """ if file.endswith('.lvl'): # Set the skill variable if file.startswith('easy'): self.__skill = SKILL_EASY elif file.startswith('medium'): self.__skill = SKILL_MEDIUM elif file.startswith('hard'): self.__skill = SKILL_HARD self.__loadFileContent(open(file,'r')) elif file.endswith('.zip'): zip = ZipFile(file) # We have to select from which files in the zipfile we # want to choose randomly based on the level's skill candidates = [] if skill == SKILL_EASY: for file in zip.namelist(): if file.startswith('easy'): candidates.append(file) elif skill == SKILL_MEDIUM: for file in zip.namelist(): if file.startswith('medium'): candidates.append(file) elif skill == SKILL_HARD: for file in zip.namelist(): if file.startswith('hard'): candidates.append(file) # This should never happen in a good levelpack, but if it # is malformed, just pick something! if not candidates: candidates = zip.namelist() # Select one candidate randomly which = candidates[randrange(len(candidates))] # Set the skill variable if which.startswith('easy'): self.__skill = SKILL_EASY elif which.startswith('medium'):self.__skill = SKILL_MEDIUM elif which.startswith('hard'): self.__skill = SKILL_HARD # Read from zipfile and load file content buf = zip.read(which) self.__loadFileContent(StringIO(buf)) def __loadFileContent(self,file): """Actually loads the level data from a file. """ self.__level = [] for line in file: if line.startswith('name:'): self.__name = line[5:].strip() elif line[0] == '0' or line[0] == '1': row = [] for field in line: if field == '0': row.append(FIELD_INVALID) elif field == '1': self.__fieldsToOpen += 1 row.append(FIELD_VALID) self.__level.append(row)
saschpe/gnome_picross
gnomepicross/game.py
Python
gpl-2.0
5,836
/* * Copyright (C) 2001-2015 Jacek Sieka, arnetheduck on gmail point 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 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "stdinc.h" #include "Mapper_WinUPnP.h" #include "Util.h" #include "Text.h" #include "w.h" #include "AirUtil.h" #ifdef HAVE_WINUPNP_H #include <ole2.h> #include <natupnp.h> #else // HAVE_WINUPNP_H struct IUPnPNAT { }; struct IStaticPortMappingCollection { }; #endif // HAVE_WINUPNP_H namespace dcpp { const string Mapper_WinUPnP::name = "Windows UPnP"; Mapper_WinUPnP::Mapper_WinUPnP(const string& localIp, bool v6) : Mapper(localIp, v6) { } bool Mapper_WinUPnP::supportsProtocol(bool aV6) const { return !aV6; } #ifdef HAVE_WINUPNP_H bool Mapper_WinUPnP::init() { HRESULT hr = ::CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); if(FAILED(hr)) return false; if(pUN) return true; // Lacking the __uuidof in mingw... CLSID upnp; OLECHAR upnps[] = L"{AE1E00AA-3FD5-403C-8A27-2BBDC30CD0E1}"; CLSIDFromString(upnps, &upnp); IID iupnp; OLECHAR iupnps[] = L"{B171C812-CC76-485A-94D8-B6B3A2794E99}"; CLSIDFromString(iupnps, &iupnp); pUN = 0; hr = ::CoCreateInstance(upnp, 0, CLSCTX_INPROC_SERVER, iupnp, reinterpret_cast<LPVOID*>(&pUN)); if(FAILED(hr)) pUN = 0; return pUN ? true : false; } void Mapper_WinUPnP::uninit() { ::CoUninitialize(); } bool Mapper_WinUPnP::add(const string& port, const Protocol protocol, const string& description) { IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection(); if(!pSPMC) return false; /// @todo use a BSTR wrapper BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str()); BSTR description_ = SysAllocString(Text::toT(description).c_str()); BSTR localIP = !localIp.empty() ? SysAllocString(Text::toT(localIp).c_str()) : nullptr; auto port_ = Util::toInt(port); IStaticPortMapping* pSPM = 0; HRESULT hr = pSPMC->Add(port_, protocol_, port_, localIP, VARIANT_TRUE, description_, &pSPM); SysFreeString(protocol_); SysFreeString(description_); SysFreeString(localIP); bool ret = SUCCEEDED(hr); if(ret) { pSPM->Release(); lastPort = port_; lastProtocol = protocol; } pSPMC->Release(); return ret; } bool Mapper_WinUPnP::remove(const string& port, const Protocol protocol) { IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection(); if(!pSPMC) return false; /// @todo use a BSTR wrapper BSTR protocol_ = SysAllocString(Text::toT(protocols[protocol]).c_str()); auto port_ = Util::toInt(port); HRESULT hr = pSPMC->Remove(port_, protocol_); pSPMC->Release(); SysFreeString(protocol_); bool ret = SUCCEEDED(hr); if(ret && port_ == lastPort && protocol == lastProtocol) { lastPort = 0; } return ret; } string Mapper_WinUPnP::getDeviceName() { /// @todo use IUPnPDevice::ModelName <http://msdn.microsoft.com/en-us/library/aa381670(VS.85).aspx>? return Util::emptyString; } string Mapper_WinUPnP::getExternalIP() { // Get the External IP from the last added mapping if(!lastPort) return Util::emptyString; IStaticPortMappingCollection* pSPMC = getStaticPortMappingCollection(); if(!pSPMC) return Util::emptyString; /// @todo use a BSTR wrapper BSTR protocol_ = SysAllocString(Text::toT(protocols[lastProtocol]).c_str()); // Lets Query our mapping IStaticPortMapping* pSPM; HRESULT hr = pSPMC->get_Item(lastPort, protocol_, &pSPM); SysFreeString(protocol_); // Query failed! if(FAILED(hr) || !pSPM) { pSPMC->Release(); return Util::emptyString; } BSTR bstrExternal = 0; hr = pSPM->get_ExternalIPAddress(&bstrExternal); if(FAILED(hr) || !bstrExternal) { pSPM->Release(); pSPMC->Release(); return Util::emptyString; } // convert the result string ret = Text::wideToAcp(bstrExternal); // no longer needed SysFreeString(bstrExternal); // no longer needed pSPM->Release(); pSPMC->Release(); return ret; } IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() { if(!pUN) return 0; IStaticPortMappingCollection* ret = 0; HRESULT hr = 0; // some routers lag here for(int i = 0; i < 3; i++) { hr = pUN->get_StaticPortMappingCollection (&ret); if(SUCCEEDED(hr) && ret) break; Sleep(1500); } if(FAILED(hr)) return 0; return ret; } #else // HAVE_WINUPNP_H bool Mapper_WinUPnP::init() { return false; } void Mapper_WinUPnP::uninit() { } bool Mapper_WinUPnP::add(const string& /*port*/, const Protocol /*protocol*/, const string& /*description*/) { return false; } bool Mapper_WinUPnP::remove(const string& /*port*/, const Protocol /*protocol*/) { return false; } string Mapper_WinUPnP::getDeviceName() { return Util::emptyString; } string Mapper_WinUPnP::getExternalIP() { return Util::emptyString; } IStaticPortMappingCollection* Mapper_WinUPnP::getStaticPortMappingCollection() { return 0; } #endif // HAVE_WINUPNP_H } // dcpp namespace
airdcnano/airdcnano
client/Mapper_WinUPnP.cpp
C++
gpl-2.0
5,723
<?php /******************************************************************************* * HA2.php * year : 2014 * * The HA2 algorithm is a combination between two algorithms (CBA and WBA), where * the first one is based on the language characters, and the second one is * based on the language and common words. The HA2 algorithm consists of adding * the sum of frequencies of the two algorithms for each language, and * consequently, the promising language is the one having the highest new sum. * * NOTE: the algorithm requires including CBA.h, WBA.h and defines.h header * files to work perfectly. ******************************************************************************/ require_once('CBA.php'); require_once('WBA.php'); class HA2 { private $cba; private $wba; /* * Constructor, in which the reference characters and reference words are * loaded for each language. */ public function HA2() { // instantiate the CBA and WBA classes $this->cba = new CBA(); $this->wba = new WBA(); } /* * Identification: function concerns the identification of an input text * file, and it consists of adding the probabilities computed by the CBA * and WBA for each language. * * [output]: the number of the promising language (between 0-31). * * @param text: is the text to identify. */ public function identification($text) { $cbaProbabilities = $this->cba->computeProbabilities($text); // retrieve probabilities computed by CBA $wbaProbabilities = $this->wba->computeProbabilities($text); // retrieve probabilities computed by WBA // add the probabilities for each language $probabilities = array(); for($language=0; $language<NUMBER_LANGUAGES; $language++) { $probabilities[$language] = $cbaProbabilities[$language] + $wbaProbabilities[$language]; } return $this->classification($probabilities); } /* * Classification: function to classify the input text to the * corresponding language using the sum of probabilities (CBA + WBA). * * [output]: the number of the promising language (between 0-31). * * @param probabilities: a table of probabilities of all the languages. */ public function classification($probabilities) { // retrieve the highest probability (sum of frequencies) $max = 0; // keeps the highest probability $promising_language = -1; // keeps the promising language for($language=0; $language<NUMBER_LANGUAGES; $language++) { if($probabilities[$language] > $max) { $max = $probabilities[$language]; $promising_language = $language; } } // determine exactly the promising language by applying an order of classification if($promising_language != LNG_CHINESE && $promising_language != LNG_GREEK && $promising_language != LNG_HEBREW && $promising_language != LNG_HINDI && $promising_language != LNG_THAI) { if($max == $probabilities[LNG_ARABIC]) $promising_language = LNG_ARABIC; else if($max == $probabilities[LNG_PERSIAN]) $promising_language = LNG_PERSIAN; else if($max == $probabilities[LNG_URDU]) $promising_language = LNG_URDU; else if($max == $probabilities[LNG_BULGARIAN]) $promising_language = LNG_BULGARIAN; else if($max == $probabilities[LNG_RUSSIAN]) $promising_language = LNG_RUSSIAN; else if($max == $probabilities[LNG_ENGLISH]) $promising_language = LNG_ENGLISH; else if($max == $probabilities[LNG_DUTCH]) $promising_language = LNG_DUTCH; else if($max == $probabilities[LNG_INDONESIAN]) $promising_language = LNG_INDONESIAN; else if($max == $probabilities[LNG_MALAYSIAN]) $promising_language = LNG_MALAYSIAN; else if($max == $probabilities[LNG_LATIN]) $promising_language = LNG_LATIN; else if($max == $probabilities[LNG_ROMAN]) $promising_language = LNG_ROMAN; else if($max == $probabilities[LNG_FRENCH]) $promising_language = LNG_FRENCH; else if($max == $probabilities[LNG_ITALIAN]) $promising_language = LNG_ITALIAN; else if($max == $probabilities[LNG_IRISH]) $promising_language = LNG_IRISH; else if($max == $probabilities[LNG_SPANISH]) $promising_language = LNG_SPANISH; else if($max == $probabilities[LNG_PORTUGUESE]) $promising_language = LNG_PORTUGUESE; else if($max == $probabilities[LNG_ALBANIAN]) $promising_language = LNG_ALBANIAN; else if($max == $probabilities[LNG_CZECH]) $promising_language = LNG_CZECH; else if($max == $probabilities[LNG_FINNISH]) $promising_language = LNG_FINNISH; else if($max == $probabilities[LNG_HUNGARIAN]) $promising_language = LNG_HUNGARIAN; else if($max == $probabilities[LNG_SWEDISH]) $promising_language = LNG_SWEDISH; else if($max == $probabilities[LNG_GERMAN]) $promising_language = LNG_GERMAN; else if($max == $probabilities[LNG_NORWEGIAN]) $promising_language = LNG_NORWEGIAN; else if($max == $probabilities[LNG_DANISH]) $promising_language = LNG_DANISH; else if($max == $probabilities[LNG_ICELANDIC]) $promising_language = LNG_ICELANDIC; else if($max == $probabilities[LNG_TURKISH]) $promising_language = LNG_TURKISH; else if($max == $probabilities[LNG_POLISH]) $promising_language = LNG_POLISH; } return $promising_language; } } ?>
xprogramer/Language-Identification
HA2.php
PHP
gpl-2.0
5,238
/* * IRIS -- Intelligent Roadway Information System * Copyright (C) 2007-2016 Minnesota Department of Transportation * Copyright (C) 2014 AHMCT, University of California * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package us.mn.state.dot.tms.server.comm; import us.mn.state.dot.tms.DeviceRequest; import us.mn.state.dot.tms.server.CameraImpl; /** * CameraPoller is an interface for pollers which can send camera control * messages. * * @author Douglas Lau * @author Travis Swanston */ public interface CameraPoller { /** Send a PTZ camera move command */ void sendPTZ(CameraImpl c, float p, float t, float z); /** Send a store camera preset command */ void sendStorePreset(CameraImpl c, int preset); /** Send a recall camera preset command */ void sendRecallPreset(CameraImpl c, int preset); /** Send a device request * @param c The CameraImpl object. * @param r The desired DeviceRequest. */ void sendRequest(CameraImpl c, DeviceRequest r); }
CA-IRIS/mn-iris
src/us/mn/state/dot/tms/server/comm/CameraPoller.java
Java
gpl-2.0
1,437
# WordPlay Word Play is basic two player game that removes the letters from a word where the other play is the guess the original word. Word Play is one the first games that made, definitely the first use looping as base. WordPlay is considered to complete and will not change.
PhilipColman/WordPlay
README.md
Markdown
gpl-2.0
280
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- """Windowing and user-interface events. This module allows applications to create and display windows with an OpenGL context. Windows can be created with a variety of border styles or set fullscreen. You can register event handlers for keyboard, mouse and window events. For games and kiosks you can also restrict the input to your windows, for example disabling users from switching away from the application with certain key combinations or capturing and hiding the mouse. Getting started --------------- Call the Window constructor to create a new window:: from pyglet.window import Window win = Window(width=640, height=480) Attach your own event handlers:: @win.event def on_key_press(symbol, modifiers): # ... handle this event ... Place drawing code for the window within the `Window.on_draw` event handler:: @win.event def on_draw(): # ... drawing code ... Call `pyglet.app.run` to enter the main event loop (by default, this returns when all open windows are closed):: from pyglet import app app.run() Creating a game window ---------------------- Use `Window.set_exclusive_mouse` to hide the mouse cursor and receive relative mouse movement events. Specify ``fullscreen=True`` as a keyword argument to the `Window` constructor to render to the entire screen rather than opening a window:: win = Window(fullscreen=True) win.set_exclusive_mouse() Working with multiple screens ----------------------------- By default, fullscreen windows are opened on the primary display (typically set by the user in their operating system settings). You can retrieve a list of attached screens and select one manually if you prefer. This is useful for opening a fullscreen window on each screen:: display = window.get_platform().get_default_display() screens = display.get_screens() windows = [] for screen in screens: windows.append(window.Window(fullscreen=True, screen=screen)) Specifying a screen has no effect if the window is not fullscreen. Specifying the OpenGL context properties ---------------------------------------- Each window has its own context which is created when the window is created. You can specify the properties of the context before it is created by creating a "template" configuration:: from pyglet import gl # Create template config config = gl.Config() config.stencil_size = 8 config.aux_buffers = 4 # Create a window using this config win = window.Window(config=config) To determine if a given configuration is supported, query the screen (see above, "Working with multiple screens"):: configs = screen.get_matching_configs(config) if not configs: # ... config is not supported else: win = window.Window(config=configs[0]) """ from __future__ import division from builtins import object from future.utils import with_metaclass __docformat__ = 'restructuredtext' __version__ = '$Id$' import sys import pyglet from pyglet import gl from pyglet.event import EventDispatcher import pyglet.window.key import pyglet.window.event _is_epydoc = hasattr(sys, 'is_epydoc') and sys.is_epydoc class WindowException(Exception): """The root exception for all window-related errors.""" pass class NoSuchDisplayException(WindowException): """An exception indicating the requested display is not available.""" pass class NoSuchConfigException(WindowException): """An exception indicating the requested configuration is not available.""" pass class NoSuchScreenModeException(WindowException): """An exception indicating the requested screen resolution could not be met.""" pass class MouseCursorException(WindowException): """The root exception for all mouse cursor-related errors.""" pass class MouseCursor(object): """An abstract mouse cursor.""" #: Indicates if the cursor is drawn using OpenGL. This is True #: for all mouse cursors except system cursors. drawable = True def draw(self, x, y): """Abstract render method. The cursor should be drawn with the "hot" spot at the given coordinates. The projection is set to the pyglet default (i.e., orthographic in window-space), however no other aspects of the state can be assumed. :Parameters: `x` : int X coordinate of the mouse pointer's hot spot. `y` : int Y coordinate of the mouse pointer's hot spot. """ raise NotImplementedError('abstract') class DefaultMouseCursor(MouseCursor): """The default mouse cursor used by the operating system.""" drawable = False class ImageMouseCursor(MouseCursor): """A user-defined mouse cursor created from an image. Use this class to create your own mouse cursors and assign them to windows. There are no constraints on the image size or format. """ drawable = True def __init__(self, image, hot_x=0, hot_y=0): """Create a mouse cursor from an image. :Parameters: `image` : `pyglet.image.AbstractImage` Image to use for the mouse cursor. It must have a valid ``texture`` attribute. `hot_x` : int X coordinate of the "hot" spot in the image relative to the image's anchor. `hot_y` : int Y coordinate of the "hot" spot in the image, relative to the image's anchor. """ self.texture = image.get_texture() self.hot_x = hot_x self.hot_y = hot_y def draw(self, x, y): gl.glPushAttrib(gl.GL_ENABLE_BIT | gl.GL_CURRENT_BIT) gl.glColor4f(1, 1, 1, 1) gl.glEnable(gl.GL_BLEND) gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA) self.texture.blit(x - self.hot_x, y - self.hot_y, 0) gl.glPopAttrib() def _PlatformEventHandler(data): """Decorator for platform event handlers. Apply giving the platform-specific data needed by the window to associate the method with an event. See platform-specific subclasses of this decorator for examples. The following attributes are set on the function, which is returned otherwise unchanged: _platform_event True _platform_event_data List of data applied to the function (permitting multiple decorators on the same method). """ def _event_wrapper(f): f._platform_event = True if not hasattr(f, '_platform_event_data'): f._platform_event_data = [] f._platform_event_data.append(data) return f return _event_wrapper def _ViewEventHandler(f): f._view = True return f class _WindowMetaclass(type): """Sets the _platform_event_names class variable on the window subclass. """ def __init__(cls, name, bases, dict): cls._platform_event_names = set() for base in bases: if hasattr(base, '_platform_event_names'): cls._platform_event_names.update(base._platform_event_names) for name, func in dict.items(): if hasattr(func, '_platform_event'): cls._platform_event_names.add(name) super(_WindowMetaclass, cls).__init__(name, bases, dict) class BaseWindow(with_metaclass(_WindowMetaclass, EventDispatcher)): """Platform-independent application window. A window is a "heavyweight" object occupying operating system resources. The "client" or "content" area of a window is filled entirely with an OpenGL viewport. Applications have no access to operating system widgets or controls; all rendering must be done via OpenGL. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). When floating, windows may appear borderless or decorated with a platform-specific frame (including, for example, the title bar, minimize and close buttons, resize handles, and so on). While it is possible to set the location of a window, it is recommended that applications allow the platform to place it according to local conventions. This will ensure it is not obscured by other windows, and appears on an appropriate screen for the user. To render into a window, you must first call `switch_to`, to make it the current OpenGL context. If you use only one window in the application, there is no need to do this. :Ivariables: `has_exit` : bool True if the user has attempted to close the window. :deprecated: Windows are closed immediately by the default `on_close` handler when `pyglet.app.event_loop` is being used. """ # Filled in by metaclass with the names of all methods on this (sub)class # that are platform event handlers. _platform_event_names = set() #: The default window style. WINDOW_STYLE_DEFAULT = None #: The window style for pop-up dialogs. WINDOW_STYLE_DIALOG = 'dialog' #: The window style for tool windows. WINDOW_STYLE_TOOL = 'tool' #: A window style without any decoration. WINDOW_STYLE_BORDERLESS = 'borderless' #: The default mouse cursor. CURSOR_DEFAULT = None #: A crosshair mouse cursor. CURSOR_CROSSHAIR = 'crosshair' #: A pointing hand mouse cursor. CURSOR_HAND = 'hand' #: A "help" mouse cursor; typically a question mark and an arrow. CURSOR_HELP = 'help' #: A mouse cursor indicating that the selected operation is not permitted. CURSOR_NO = 'no' #: A mouse cursor indicating the element can be resized. CURSOR_SIZE = 'size' #: A mouse cursor indicating the element can be resized from the top #: border. CURSOR_SIZE_UP = 'size_up' #: A mouse cursor indicating the element can be resized from the #: upper-right corner. CURSOR_SIZE_UP_RIGHT = 'size_up_right' #: A mouse cursor indicating the element can be resized from the right #: border. CURSOR_SIZE_RIGHT = 'size_right' #: A mouse cursor indicating the element can be resized from the lower-right #: corner. CURSOR_SIZE_DOWN_RIGHT = 'size_down_right' #: A mouse cursor indicating the element can be resized from the bottom #: border. CURSOR_SIZE_DOWN = 'size_down' #: A mouse cursor indicating the element can be resized from the lower-left #: corner. CURSOR_SIZE_DOWN_LEFT = 'size_down_left' #: A mouse cursor indicating the element can be resized from the left #: border. CURSOR_SIZE_LEFT = 'size_left' #: A mouse cursor indicating the element can be resized from the upper-left #: corner. CURSOR_SIZE_UP_LEFT = 'size_up_left' #: A mouse cursor indicating the element can be resized vertically. CURSOR_SIZE_UP_DOWN = 'size_up_down' #: A mouse cursor indicating the element can be resized horizontally. CURSOR_SIZE_LEFT_RIGHT = 'size_left_right' #: A text input mouse cursor (I-beam). CURSOR_TEXT = 'text' #: A "wait" mouse cursor; typically an hourglass or watch. CURSOR_WAIT = 'wait' #: The "wait" mouse cursor combined with an arrow. CURSOR_WAIT_ARROW = 'wait_arrow' has_exit = False #: Window display contents validity. The `pyglet.app` event loop #: examines every window each iteration and only dispatches the `on_draw` #: event to windows that have `invalid` set. By default, windows always #: have `invalid` set to ``True``. #: #: You can prevent redundant redraws by setting this variable to ``False`` #: in the window's `on_draw` handler, and setting it to True again in #: response to any events that actually do require a window contents #: update. #: #: :type: bool #: :since: pyglet 1.1 invalid = True #: Legacy invalidation flag introduced in pyglet 1.2: set by all event #: dispatches that go to non-empty handlers. The default 1.2 event loop #: will therefore redraw after any handled event or scheduled function. _legacy_invalid = True # Instance variables accessible only via properties _width = None _height = None _caption = None _resizable = False _style = WINDOW_STYLE_DEFAULT _fullscreen = False _visible = False _vsync = False _screen = None _config = None _context = None # Used to restore window size and position after fullscreen _windowed_size = None _windowed_location = None # Subclasses should update these after relevant events _mouse_cursor = DefaultMouseCursor() _mouse_x = 0 _mouse_y = 0 _mouse_visible = True _mouse_exclusive = False _mouse_in_window = False _event_queue = None _enable_event_queue = True # overridden by EventLoop. _allow_dispatch_event = False # controlled by dispatch_events stack frame # Class attributes _default_width = 640 _default_height = 480 def __init__(self, width=None, height=None, caption=None, resizable=False, style=WINDOW_STYLE_DEFAULT, fullscreen=False, visible=True, vsync=True, display=None, screen=None, config=None, context=None, mode=None): """Create a window. All parameters are optional, and reasonable defaults are assumed where they are not specified. The `display`, `screen`, `config` and `context` parameters form a hierarchy of control: there is no need to specify more than one of these. For example, if you specify `screen` the `display` will be inferred, and a default `config` and `context` will be created. `config` is a special case; it can be a template created by the user specifying the attributes desired, or it can be a complete `config` as returned from `Screen.get_matching_configs` or similar. The context will be active as soon as the window is created, as if `switch_to` was just called. :Parameters: `width` : int Width of the window, in pixels. Defaults to 640, or the screen width if `fullscreen` is True. `height` : int Height of the window, in pixels. Defaults to 480, or the screen height if `fullscreen` is True. `caption` : str or unicode Initial caption (title) of the window. Defaults to ``sys.argv[0]``. `resizable` : bool If True, the window will be resizable. Defaults to False. `style` : int One of the ``WINDOW_STYLE_*`` constants specifying the border style of the window. `fullscreen` : bool If True, the window will cover the entire screen rather than floating. Defaults to False. `visible` : bool Determines if the window is visible immediately after creation. Defaults to True. Set this to False if you would like to change attributes of the window before having it appear to the user. `vsync` : bool If True, buffer flips are synchronised to the primary screen's vertical retrace, eliminating flicker. `display` : `Display` The display device to use. Useful only under X11. `screen` : `Screen` The screen to use, if in fullscreen. `config` : `pyglet.gl.Config` Either a template from which to create a complete config, or a complete config. `context` : `pyglet.gl.Context` The context to attach to this window. The context must not already be attached to another window. `mode` : `ScreenMode` The screen will be switched to this mode if `fullscreen` is True. If None, an appropriate mode is selected to accomodate `width` and `height.` """ EventDispatcher.__init__(self) self._event_queue = [] if not display: display = get_platform().get_default_display() if not screen: screen = display.get_default_screen() if not config: for template_config in [ gl.Config(double_buffer=True, depth_size=24), gl.Config(double_buffer=True, depth_size=16), None]: try: config = screen.get_best_config(template_config) break except NoSuchConfigException: pass if not config: raise NoSuchConfigException('No standard config is available.') if not config.is_complete(): config = screen.get_best_config(config) if not context: context = config.create_context(gl.current_context) # Set these in reverse order to above, to ensure we get user # preference self._context = context self._config = self._context.config # XXX deprecate config's being screen-specific if hasattr(self._config, 'screen'): self._screen = self._config.screen else: display = self._config.canvas.display self._screen = display.get_default_screen() self._display = self._screen.display if fullscreen: if width is None and height is None: self._windowed_size = self._default_width, self._default_height width, height = self._set_fullscreen_mode(mode, width, height) if not self._windowed_size: self._windowed_size = width, height else: if width is None: width = self._default_width if height is None: height = self._default_height self._width = width self._height = height self._resizable = resizable self._fullscreen = fullscreen self._style = style if pyglet.options['vsync'] is not None: self._vsync = pyglet.options['vsync'] else: self._vsync = vsync if caption is None: caption = sys.argv[0] # Decode hack for Python2 unicode support: if hasattr(caption, "decode"): try: caption = caption.decode("utf8") except UnicodeDecodeError: caption = "pyglet" self._caption = caption from pyglet import app app.windows.add(self) self._create() self.switch_to() if visible: self.set_visible(True) self.activate() def __del__(self): # Always try to clean up the window when it is dereferenced. # Makes sure there are no dangling pointers or memory leaks. # If the window is already closed, pass silently. try: self.close() except: # XXX Avoid a NoneType error if already closed. pass def __repr__(self): return '%s(width=%d, height=%d)' % \ (self.__class__.__name__, self.width, self.height) def _create(self): raise NotImplementedError('abstract') def _recreate(self, changes): """Recreate the window with current attributes. :Parameters: `changes` : list of str List of attribute names that were changed since the last `_create` or `_recreate`. For example, ``['fullscreen']`` is given if the window is to be toggled to or from fullscreen. """ raise NotImplementedError('abstract') def flip(self): """Swap the OpenGL front and back buffers. Call this method on a double-buffered window to update the visible display with the back buffer. The contents of the back buffer is undefined after this operation. Windows are double-buffered by default. This method is called automatically by `EventLoop` after the `on_draw` event. """ raise NotImplementedError('abstract') def switch_to(self): """Make this window the current OpenGL rendering context. Only one OpenGL context can be active at a time. This method sets the current window's context to be current. You should use this method in preference to `pyglet.gl.Context.set_current`, as it may perform additional initialisation functions. """ raise NotImplementedError('abstract') def set_fullscreen(self, fullscreen=True, screen=None, mode=None, width=None, height=None): """Toggle to or from fullscreen. After toggling fullscreen, the GL context should have retained its state and objects, however the buffers will need to be cleared and redrawn. If `width` and `height` are specified and `fullscreen` is True, the screen may be switched to a different resolution that most closely matches the given size. If the resolution doesn't match exactly, a higher resolution is selected and the window will be centered within a black border covering the rest of the screen. :Parameters: `fullscreen` : bool True if the window should be made fullscreen, False if it should be windowed. `screen` : Screen If not None and fullscreen is True, the window is moved to the given screen. The screen must belong to the same display as the window. `mode` : `ScreenMode` The screen will be switched to the given mode. The mode must have been obtained by enumerating `Screen.get_modes`. If None, an appropriate mode will be selected from the given `width` and `height`. `width` : int Optional width of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 `height` : int Optional height of the window. If unspecified, defaults to the previous window size when windowed, or the screen size if fullscreen. **Since:** pyglet 1.2 """ if (fullscreen == self._fullscreen and (screen is None or screen is self._screen) and (width is None or width == self._width) and (height is None or height == self._height)): return if not self._fullscreen: # Save windowed size self._windowed_size = self.get_size() self._windowed_location = self.get_location() if fullscreen and screen is not None: assert screen.display is self.display self._screen = screen self._fullscreen = fullscreen if self._fullscreen: self._width, self._height = self._set_fullscreen_mode( mode, width, height) else: self.screen.restore_mode() self._width, self._height = self._windowed_size if width is not None: self._width = width if height is not None: self._height = height self._recreate(['fullscreen']) if not self._fullscreen and self._windowed_location: # Restore windowed location. # TODO: Move into platform _create? # Not harmless on Carbon because upsets _width and _height # via _on_window_bounds_changed. if pyglet.compat_platform != 'darwin' or pyglet.options['darwin_cocoa']: self.set_location(*self._windowed_location) def _set_fullscreen_mode(self, mode, width, height): if mode is not None: self.screen.set_mode(mode) if width is None: width = self.screen.width if height is None: height = self.screen.height elif width is not None or height is not None: if width is None: width = 0 if height is None: height = 0 mode = self.screen.get_closest_mode(width, height) if mode is not None: self.screen.set_mode(mode) elif self.screen.get_modes(): # Only raise exception if mode switching is at all possible. raise NoSuchScreenModeException( 'No mode matching %dx%d' % (width, height)) else: width = self.screen.width height = self.screen.height return width, height def on_resize(self, width, height): """A default resize event handler. This default handler updates the GL viewport to cover the entire window and sets the ``GL_PROJECTION`` matrix to be orthogonal in window space. The bottom-left corner is (0, 0) and the top-right corner is the width and height of the window in pixels. Override this event handler with your own to create another projection, for example in perspective. """ # XXX avoid GLException by not allowing 0 width or height. width = max(1, width) height = max(1, height) gl.glViewport(0, 0, width, height) gl.glMatrixMode(gl.GL_PROJECTION) gl.glLoadIdentity() gl.glOrtho(0, width, 0, height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) def on_close(self): """Default on_close handler.""" self.has_exit = True from pyglet import app if app.event_loop.is_running: self.close() def on_key_press(self, symbol, modifiers): """Default on_key_press handler.""" if symbol == key.ESCAPE and not (modifiers & ~(key.MOD_NUMLOCK | key.MOD_CAPSLOCK | key.MOD_SCROLLLOCK)): self.dispatch_event('on_close') def close(self): """Close the window. After closing the window, the GL context will be invalid. The window instance cannot be reused once closed (see also `set_visible`). The `pyglet.app.EventLoop.on_window_close` event is dispatched on `pyglet.app.event_loop` when this method is called. """ from pyglet import app if not self._context: return app.windows.remove(self) self._context.destroy() self._config = None self._context = None if app.event_loop: app.event_loop.dispatch_event('on_window_close', self) self._event_queue = [] def draw_mouse_cursor(self): """Draw the custom mouse cursor. If the current mouse cursor has ``drawable`` set, this method is called before the buffers are flipped to render it. This method always leaves the ``GL_MODELVIEW`` matrix as current, regardless of what it was set to previously. No other GL state is affected. There is little need to override this method; instead, subclass ``MouseCursor`` and provide your own ``draw`` method. """ # Draw mouse cursor if set and visible. # XXX leaves state in modelview regardless of starting state if (self._mouse_cursor.drawable and self._mouse_visible and self._mouse_in_window): gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.width, 0, self.height, -1, 1) gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() self._mouse_cursor.draw(self._mouse_x, self._mouse_y) gl.glMatrixMode(gl.GL_PROJECTION) gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() # Properties provide read-only access to instance variables. Use # set_* methods to change them if applicable. @property def caption(self): """The window caption (title). Read-only. :type: str """ return self._caption @property def resizeable(self): """True if the window is resizable. Read-only. :type: bool """ return self._resizable @property def style(self): """The window style; one of the ``WINDOW_STYLE_*`` constants. Read-only. :type: int """ return self._style @property def fullscreen(self): """True if the window is currently fullscreen. Read-only. :type: bool """ return self._fullscreen @property def visible(self): """True if the window is currently visible. Read-only. :type: bool """ return self._visible @property def vsync(self): """True if buffer flips are synchronised to the screen's vertical retrace. Read-only. :type: bool """ return self._vsync @property def display(self): """The display this window belongs to. Read-only. :type: `Display` """ return self._display @property def screen(self): """The screen this window is fullscreen in. Read-only. :type: `Screen` """ return self._screen @property def config(self): """A GL config describing the context of this window. Read-only. :type: `pyglet.gl.Config` """ return self._config @property def context(self): """The OpenGL context attached to this window. Read-only. :type: `pyglet.gl.Context` """ return self._context # These are the only properties that can be set @property def width(self): """The width of the window, in pixels. Read-write. :type: int """ return self.get_size()[0] @width.setter def width(self, new_width): self.set_size(new_width, self.height) @property def height(self): """The height of the window, in pixels. Read-write. :type: int """ return self.get_size()[1] @height.setter def height(self, new_height): self.set_size(self.width, new_height) def set_caption(self, caption): """Set the window's caption. The caption appears in the titlebar of the window, if it has one, and in the taskbar on Windows and many X11 window managers. :Parameters: `caption` : str or unicode The caption to set. """ raise NotImplementedError('abstract') def set_minimum_size(self, width, height): """Set the minimum size of the window. Once set, the user will not be able to resize the window smaller than the given dimensions. There is no way to remove the minimum size constraint on a window (but you could set it to 0,0). The behaviour is undefined if the minimum size is set larger than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Minimum width of the window, in pixels. `height` : int Minimum height of the window, in pixels. """ raise NotImplementedError('abstract') def set_maximum_size(self, width, height): """Set the maximum size of the window. Once set, the user will not be able to resize the window larger than the given dimensions. There is no way to remove the maximum size constraint on a window (but you could set it to a large value). The behaviour is undefined if the maximum size is set smaller than the current size of the window. The window size does not include the border or title bar. :Parameters: `width` : int Maximum width of the window, in pixels. `height` : int Maximum height of the window, in pixels. """ raise NotImplementedError('abstract') def set_size(self, width, height): """Resize the window. The behaviour is undefined if the window is not resizable, or if it is currently fullscreen. The window size does not include the border or title bar. :Parameters: `width` : int New width of the window, in pixels. `height` : int New height of the window, in pixels. """ raise NotImplementedError('abstract') def get_size(self): """Return the current size of the window. The window size does not include the border or title bar. :rtype: (int, int) :return: The width and height of the window, in pixels. """ raise NotImplementedError('abstract') def set_location(self, x, y): """Set the position of the window. :Parameters: `x` : int Distance of the left edge of the window from the left edge of the virtual desktop, in pixels. `y` : int Distance of the top edge of the window from the top edge of the virtual desktop, in pixels. """ raise NotImplementedError('abstract') def get_location(self): """Return the current position of the window. :rtype: (int, int) :return: The distances of the left and top edges from their respective edges on the virtual desktop, in pixels. """ raise NotImplementedError('abstract') def activate(self): """Attempt to restore keyboard focus to the window. Depending on the window manager or operating system, this may not be successful. For example, on Windows XP an application is not allowed to "steal" focus from another application. Instead, the window's taskbar icon will flash, indicating it requires attention. """ raise NotImplementedError('abstract') def set_visible(self, visible=True): """Show or hide the window. :Parameters: `visible` : bool If True, the window will be shown; otherwise it will be hidden. """ raise NotImplementedError('abstract') def minimize(self): """Minimize the window. """ raise NotImplementedError('abstract') def maximize(self): """Maximize the window. The behaviour of this method is somewhat dependent on the user's display setup. On a multi-monitor system, the window may maximize to either a single screen or the entire virtual desktop. """ raise NotImplementedError('abstract') def set_vsync(self, vsync): """Enable or disable vertical sync control. When enabled, this option ensures flips from the back to the front buffer are performed only during the vertical retrace period of the primary display. This can prevent "tearing" or flickering when the buffer is updated in the middle of a video scan. Note that LCD monitors have an analogous time in which they are not reading from the video buffer; while it does not correspond to a vertical retrace it has the same effect. With multi-monitor systems the secondary monitor cannot be synchronised to, so tearing and flicker cannot be avoided when the window is positioned outside of the primary display. In this case it may be advisable to forcibly reduce the framerate (for example, using `pyglet.clock.set_fps_limit`). :Parameters: `vsync` : bool If True, vsync is enabled, otherwise it is disabled. """ raise NotImplementedError('abstract') def set_mouse_visible(self, visible=True): """Show or hide the mouse cursor. The mouse cursor will only be hidden while it is positioned within this window. Mouse events will still be processed as usual. :Parameters: `visible` : bool If True, the mouse cursor will be visible, otherwise it will be hidden. """ self._mouse_visible = visible self.set_mouse_platform_visible() def set_mouse_platform_visible(self, platform_visible=None): """Set the platform-drawn mouse cursor visibility. This is called automatically after changing the mouse cursor or exclusive mode. Applications should not normally need to call this method, see `set_mouse_visible` instead. :Parameters: `platform_visible` : bool or None If None, sets platform visibility to the required visibility for the current exclusive mode and cursor type. Otherwise, a bool value will override and force a visibility. """ raise NotImplementedError() def set_mouse_cursor(self, cursor=None): """Change the appearance of the mouse cursor. The appearance of the mouse cursor is only changed while it is within this window. :Parameters: `cursor` : `MouseCursor` The cursor to set, or None to restore the default cursor. """ if cursor is None: cursor = DefaultMouseCursor() self._mouse_cursor = cursor self.set_mouse_platform_visible() def set_exclusive_mouse(self, exclusive=True): """Hide the mouse cursor and direct all mouse events to this window. When enabled, this feature prevents the mouse leaving the window. It is useful for certain styles of games that require complete control of the mouse. The position of the mouse as reported in subsequent events is meaningless when exclusive mouse is enabled; you should only use the relative motion parameters ``dx`` and ``dy``. :Parameters: `exclusive` : bool If True, exclusive mouse is enabled, otherwise it is disabled. """ raise NotImplementedError('abstract') def set_exclusive_keyboard(self, exclusive=True): """Prevent the user from switching away from this window using keyboard accelerators. When enabled, this feature disables certain operating-system specific key combinations such as Alt+Tab (Command+Tab on OS X). This can be useful in certain kiosk applications, it should be avoided in general applications or games. :Parameters: `exclusive` : bool If True, exclusive keyboard is enabled, otherwise it is disabled. """ raise NotImplementedError('abstract') def get_system_mouse_cursor(self, name): """Obtain a system mouse cursor. Use `set_mouse_cursor` to make the cursor returned by this method active. The names accepted by this method are the ``CURSOR_*`` constants defined on this class. :Parameters: `name` : str Name describing the mouse cursor to return. For example, ``CURSOR_WAIT``, ``CURSOR_HELP``, etc. :rtype: `MouseCursor` :return: A mouse cursor which can be used with `set_mouse_cursor`. """ raise NotImplementedError() def set_icon(self, *images): """Set the window icon. If multiple images are provided, one with an appropriate size will be selected (if the correct size is not provided, the image will be scaled). Useful sizes to provide are 16x16, 32x32, 64x64 (Mac only) and 128x128 (Mac only). :Parameters: `images` : sequence of `pyglet.image.AbstractImage` List of images to use for the window icon. """ pass def clear(self): """Clear the window. This is a convenience method for clearing the color and depth buffer. The window must be the active context (see `switch_to`). """ gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT) def dispatch_event(self, *args): if not self._enable_event_queue or self._allow_dispatch_event: if EventDispatcher.dispatch_event(self, *args) != False: self._legacy_invalid = True else: self._event_queue.append(args) def dispatch_events(self): """Poll the operating system event queue for new events and call attached event handlers. This method is provided for legacy applications targeting pyglet 1.0, and advanced applications that must integrate their event loop into another framework. Typical applications should use `pyglet.app.run`. """ raise NotImplementedError('abstract') # If documenting, show the event methods. Otherwise, leave them out # as they are not really methods. if _is_epydoc: def on_key_press(symbol, modifiers): """A key on the keyboard was pressed (and held down). In pyglet 1.0 the default handler sets `has_exit` to ``True`` if the ``ESC`` key is pressed. In pyglet 1.1 the default handler dispatches the `on_close` event if the ``ESC`` key is pressed. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: """ def on_key_release(symbol, modifiers): """A key on the keyboard was released. :Parameters: `symbol` : int The key symbol pressed. `modifiers` : int Bitwise combination of the key modifiers active. :event: """ def on_text(text): """The user input some text. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is held down (key repeating); or called without key presses if another input method was used (e.g., a pen input). You should always use this method for interpreting text, as the key symbols often have complex mappings to their unicode representation which this event takes care of. :Parameters: `text` : unicode The text entered by the user. :event: """ def on_text_motion(motion): """The user moved the text input cursor. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for moving the text input cursor (caret), as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE * MOTION_BACKSPACE * MOTION_DELETE :Parameters: `motion` : int The direction of motion; see remarks. :event: """ def on_text_motion_select(motion): """The user moved the text input cursor while extending the selection. Typically this is called after `on_key_press` and before `on_key_release`, but may also be called multiple times if the key is help down (key repeating). You should always use this method for responding to text selection events rather than the raw `on_key_press`, as different platforms have different default keyboard mappings, and key repeats are handled correctly. The values that `motion` can take are defined in `pyglet.window.key`: * MOTION_UP * MOTION_RIGHT * MOTION_DOWN * MOTION_LEFT * MOTION_NEXT_WORD * MOTION_PREVIOUS_WORD * MOTION_BEGINNING_OF_LINE * MOTION_END_OF_LINE * MOTION_NEXT_PAGE * MOTION_PREVIOUS_PAGE * MOTION_BEGINNING_OF_FILE * MOTION_END_OF_FILE :Parameters: `motion` : int The direction of selection motion; see remarks. :event: """ def on_mouse_motion(x, y, dx, dy): """The mouse was moved with no buttons held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. :event: """ def on_mouse_drag(x, y, dx, dy, buttons, modifiers): """The mouse was moved with one or more mouse buttons pressed. This event will continue to be fired even if the mouse leaves the window, so long as the drag buttons are continuously held down. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `dx` : int Relative X position from the previous mouse position. `dy` : int Relative Y position from the previous mouse position. `buttons` : int Bitwise combination of the mouse buttons currently pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: """ def on_mouse_press(x, y, button, modifiers): """A mouse button was pressed (and held down). :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was pressed. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: """ def on_mouse_release(x, y, button, modifiers): """A mouse button was released. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `button` : int The mouse button that was released. `modifiers` : int Bitwise combination of any keyboard modifiers currently active. :event: """ def on_mouse_scroll(x, y, scroll_x, scroll_y): """The mouse wheel was scrolled. Note that most mice have only a vertical scroll wheel, so `scroll_x` is usually 0. An exception to this is the Apple Mighty Mouse, which has a mouse ball in place of the wheel which allows both `scroll_x` and `scroll_y` movement. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. `scroll_x` : int Number of "clicks" towards the right (left if negative). `scroll_y` : int Number of "clicks" upwards (downwards if negative). :event: """ def on_close(): """The user attempted to close the window. This event can be triggered by clicking on the "X" control box in the window title bar, or by some other platform-dependent manner. The default handler sets `has_exit` to ``True``. In pyglet 1.1, if `pyglet.app.event_loop` is being used, `close` is also called, closing the window immediately. :event: """ def on_mouse_enter(x, y): """The mouse was moved into the window. This event will not be trigged if the mouse is currently being dragged. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: """ def on_mouse_leave(x, y): """The mouse was moved outside of the window. This event will not be trigged if the mouse is currently being dragged. Note that the coordinates of the mouse pointer will be outside of the window rectangle. :Parameters: `x` : int Distance in pixels from the left edge of the window. `y` : int Distance in pixels from the bottom edge of the window. :event: """ def on_expose(): """A portion of the window needs to be redrawn. This event is triggered when the window first appears, and any time the contents of the window is invalidated due to another window obscuring it. There is no way to determine which portion of the window needs redrawing. Note that the use of this method is becoming increasingly uncommon, as newer window managers composite windows automatically and keep a backing store of the window contents. :event: """ def on_resize(width, height): """The window was resized. The window will have the GL context when this event is dispatched; there is no need to call `switch_to` in this handler. :Parameters: `width` : int The new width of the window, in pixels. `height` : int The new height of the window, in pixels. :event: """ def on_move(x, y): """The window was moved. :Parameters: `x` : int Distance from the left edge of the screen to the left edge of the window. `y` : int Distance from the top edge of the screen to the top edge of the window. Note that this is one of few methods in pyglet which use a Y-down coordinate system. :event: """ def on_activate(): """The window was activated. This event can be triggered by clicking on the title bar, bringing it to the foreground; or by some platform-specific method. When a window is "active" it has the keyboard focus. :event: """ def on_deactivate(): """The window was deactivated. This event can be triggered by clicking on another application window. When a window is deactivated it no longer has the keyboard focus. :event: """ def on_show(): """The window was shown. This event is triggered when a window is restored after being minimised, or after being displayed for the first time. :event: """ def on_hide(): """The window was hidden. This event is triggered when a window is minimised or (on Mac OS X) hidden by the user. :event: """ def on_context_lost(): """The window's GL context was lost. When the context is lost no more GL methods can be called until it is recreated. This is a rare event, triggered perhaps by the user switching to an incompatible video mode. When it occurs, an application will need to reload all objects (display lists, texture objects, shaders) as well as restore the GL state. :event: """ def on_context_state_lost(): """The state of the window's GL context was lost. pyglet may sometimes need to recreate the window's GL context if the window is moved to another video device, or between fullscreen or windowed mode. In this case it will try to share the objects (display lists, texture objects, shaders) between the old and new contexts. If this is possible, only the current state of the GL context is lost, and the application should simply restore state. :event: """ def on_draw(): """The window contents must be redrawn. The `EventLoop` will dispatch this event when the window should be redrawn. This will happen during idle time after any window events and after any scheduled functions were called. The window will already have the GL context, so there is no need to call `switch_to`. The window's `flip` method will be called after this event, so your event handler should not. You should make no assumptions about the window contents when this event is triggered; a resize or expose event may have invalidated the framebuffer since the last time it was drawn. :since: pyglet 1.1 :event: """ BaseWindow.register_event_type('on_key_press') BaseWindow.register_event_type('on_key_release') BaseWindow.register_event_type('on_text') BaseWindow.register_event_type('on_text_motion') BaseWindow.register_event_type('on_text_motion_select') BaseWindow.register_event_type('on_mouse_motion') BaseWindow.register_event_type('on_mouse_drag') BaseWindow.register_event_type('on_mouse_press') BaseWindow.register_event_type('on_mouse_release') BaseWindow.register_event_type('on_mouse_scroll') BaseWindow.register_event_type('on_mouse_enter') BaseWindow.register_event_type('on_mouse_leave') BaseWindow.register_event_type('on_close') BaseWindow.register_event_type('on_expose') BaseWindow.register_event_type('on_resize') BaseWindow.register_event_type('on_move') BaseWindow.register_event_type('on_activate') BaseWindow.register_event_type('on_deactivate') BaseWindow.register_event_type('on_show') BaseWindow.register_event_type('on_hide') BaseWindow.register_event_type('on_context_lost') BaseWindow.register_event_type('on_context_state_lost') BaseWindow.register_event_type('on_draw') class FPSDisplay(object): """Display of a window's framerate. This is a convenience class to aid in profiling and debugging. Typical usage is to create an `FPSDisplay` for each window, and draw the display at the end of the windows' `on_draw` event handler:: window = pyglet.window.Window() fps_display = FPSDisplay(window) @window.event def on_draw(): # ... perform ordinary window drawing operations ... fps_display.draw() The style and position of the display can be modified via the `label` attribute. Different text can be substituted by overriding the `set_fps` method. The display can be set to update more or less often by setting the `update_period` attribute. :Ivariables: `label` : Label The text label displaying the framerate. """ #: Time in seconds between updates. #: #: :type: float update_period = 0.25 def __init__(self, window): from time import time from pyglet.text import Label self.label = Label('', x=10, y=10, font_size=24, bold=True, color=(127, 127, 127, 127)) self.window = window self._window_flip = window.flip window.flip = self._hook_flip self.time = 0.0 self.last_time = time() self.count = 0 def update(self): """Records a new data point at the current time. This method is called automatically when the window buffer is flipped. """ from time import time t = time() self.count += 1 self.time += t - self.last_time self.last_time = t if self.time >= self.update_period: self.set_fps(self.count / self.update_period) self.time %= self.update_period self.count = 0 def set_fps(self, fps): """Set the label text for the given FPS estimation. Called by `update` every `update_period` seconds. :Parameters: `fps` : float Estimated framerate of the window. """ self.label.text = '%.2f' % fps def draw(self): """Draw the label. The OpenGL state is assumed to be at default values, except that the MODELVIEW and PROJECTION matrices are ignored. At the return of this method the matrix mode will be MODELVIEW. """ gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPushMatrix() gl.glLoadIdentity() gl.glMatrixMode(gl.GL_PROJECTION) gl.glPushMatrix() gl.glLoadIdentity() gl.glOrtho(0, self.window.width, 0, self.window.height, -1, 1) self.label.draw() gl.glPopMatrix() gl.glMatrixMode(gl.GL_MODELVIEW) gl.glPopMatrix() def _hook_flip(self): self.update() self._window_flip() if _is_epydoc: # We are building documentation Window = BaseWindow Window.__name__ = 'Window' del BaseWindow else: # Try to determine which platform to use. if pyglet.compat_platform == 'darwin': if pyglet.options['darwin_cocoa']: from pyglet.window.cocoa import CocoaWindow as Window else: from pyglet.window.carbon import CarbonWindow as Window elif pyglet.compat_platform in ('win32', 'cygwin'): from pyglet.window.win32 import Win32Window as Window else: # XXX HACK around circ problem, should be fixed after removal of # shadow nonsense #pyglet.window = sys.modules[__name__] #import key, mouse from pyglet.window.xlib import XlibWindow as Window # Deprecated API def get_platform(): """Get an instance of the Platform most appropriate for this system. :deprecated: Use `pyglet.canvas.Display`. :rtype: `Platform` :return: The platform instance. """ return Platform() class Platform(object): """Operating-system-level functionality. The platform instance can only be obtained with `get_platform`. Use the platform to obtain a `Display` instance. :deprecated: Use `pyglet.canvas.Display` """ def get_display(self, name): """Get a display device by name. This is meaningful only under X11, where the `name` is a string including the host name and display number; for example ``"localhost:1"``. On platforms other than X11, `name` is ignored and the default display is returned. pyglet does not support multiple multiple video devices on Windows or OS X. If more than one device is attached, they will appear as a single virtual device comprising all the attached screens. :deprecated: Use `pyglet.canvas.get_display`. :Parameters: `name` : str The name of the display to connect to. :rtype: `Display` """ for display in pyglet.app.displays: if display.name == name: return display return pyglet.canvas.Display(name) def get_default_display(self): """Get the default display device. :deprecated: Use `pyglet.canvas.get_display`. :rtype: `Display` """ return pyglet.canvas.get_display() if _is_epydoc: class Display(object): """A display device supporting one or more screens. Use `Platform.get_display` or `Platform.get_default_display` to obtain an instance of this class. Use a display to obtain `Screen` instances. :deprecated: Use `pyglet.canvas.Display`. """ def __init__(self): raise NotImplementedError('deprecated') def get_screens(self): """Get the available screens. A typical multi-monitor workstation comprises one `Display` with multiple `Screen` s. This method returns a list of screens which can be enumerated to select one for full-screen display. For the purposes of creating an OpenGL config, the default screen will suffice. :rtype: list of `Screen` """ raise NotImplementedError('deprecated') def get_default_screen(self): """Get the default screen as specified by the user's operating system preferences. :rtype: `Screen` """ raise NotImplementedError('deprecated') def get_windows(self): """Get the windows currently attached to this display. :rtype: sequence of `Window` """ raise NotImplementedError('deprecated') else: Display = pyglet.canvas.Display Screen = pyglet.canvas.Screen # XXX remove # Create shadow window. (trickery is for circular import) if not _is_epydoc: pyglet.window = sys.modules[__name__] gl._create_shadow_window()
ajhager/copycat
lib/pyglet/window/__init__.py
Python
gpl-2.0
65,226
/* * Copyright (c) 2010 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef __INC_BLOCK_H #define __INC_BLOCK_H #include "vp8/common/onyx.h" #include "vp8/common/blockd.h" #include "vp8/common/entropymv.h" #include "vp8/common/entropy.h" #include "vpx_ports/mem.h" #define MAX_MODES 20 #define MAX_ERROR_BINS 1024 typedef struct { MV mv; int offset; } search_site; typedef struct block { short *src_diff; short *coeff; short *quant; short *quant_fast; short *quant_shift; short *zbin; short *zrun_zbin_boost; short *round; short zbin_extra; unsigned char **base_src; int src; int src_stride; } BLOCK; typedef struct { int count; struct { B_PREDICTION_MODE mode; int_mv mv; } bmi[16]; } PARTITION_INFO; typedef struct macroblock { DECLARE_ALIGNED(16, short, src_diff[400]); DECLARE_ALIGNED(16, short, coeff[400]); DECLARE_ALIGNED(16, unsigned char, thismb[256]); unsigned char *thismb_ptr; BLOCK block[25]; YV12_BUFFER_CONFIG src; MACROBLOCKD e_mbd; PARTITION_INFO *partition_info; PARTITION_INFO *pi; PARTITION_INFO *pip; int ref_frame_cost[MAX_REF_FRAMES]; search_site *ss; int ss_count; int searches_per_step; int errorperbit; int sadperbit16; int sadperbit4; int rddiv; int rdmult; unsigned int * mb_activity_ptr; int * mb_norm_activity_ptr; signed int act_zbin_adj; signed int last_act_zbin_adj; int *mvcost[2]; int *mvsadcost[2]; int (*mbmode_cost)[MB_MODE_COUNT]; int (*intra_uv_mode_cost)[MB_MODE_COUNT]; int (*bmode_costs)[10][10]; int *inter_bmode_costs; int (*token_costs)[COEF_BANDS][PREV_COEF_CONTEXTS] [MAX_ENTROPY_TOKENS]; int mv_col_min; int mv_col_max; int mv_row_min; int mv_row_max; int skip; unsigned int encode_breakout; signed char *gf_active_ptr; unsigned char *active_ptr; MV_CONTEXT *mvc; int optimize; int q_index; #if CONFIG_TEMPORAL_DENOISING MB_PREDICTION_MODE best_sse_inter_mode; int_mv best_sse_mv; MV_REFERENCE_FRAME best_reference_frame; MV_REFERENCE_FRAME best_zeromv_reference_frame; unsigned char need_to_clamp_best_mvs; #endif int skip_true_count; unsigned int coef_counts [BLOCK_TYPES] [COEF_BANDS] [PREV_COEF_CONTEXTS] [MAX_ENTROPY_TOKENS]; unsigned int MVcount [2] [MVvals]; int ymode_count [VP8_YMODES]; int uv_mode_count[VP8_UV_MODES]; int64_t prediction_error; int64_t intra_error; int count_mb_ref_frame_usage[MAX_REF_FRAMES]; int rd_thresh_mult[MAX_MODES]; int rd_threshes[MAX_MODES]; unsigned int mbs_tested_so_far; unsigned int mode_test_hit_counts[MAX_MODES]; int zbin_mode_boost_enabled; int zbin_mode_boost; int last_zbin_mode_boost; int last_zbin_over_quant; int zbin_over_quant; int error_bins[MAX_ERROR_BINS]; void (*short_fdct4x4)(short *input, short *output, int pitch); void (*short_fdct8x4)(short *input, short *output, int pitch); void (*short_walsh4x4)(short *input, short *output, int pitch); void (*quantize_b)(BLOCK *b, BLOCKD *d); void (*quantize_b_pair)(BLOCK *b1, BLOCK *b2, BLOCKD *d0, BLOCKD *d1); } MACROBLOCK; #endif
qtekfun/htcDesire820Kernel
external/libvpx/libvpx/vp8/encoder/block.h
C
gpl-2.0
3,672
// ********************************************************************** // // Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved. // // ********************************************************************** #include <Ice/Ice.h> #include <IceGrid/IceGrid.h> #include <Hello.h> using namespace std; using namespace Demo; class HelloClient : public Ice::Application { public: HelloClient(); virtual int run(int, char*[]); private: void menu(); void usage(); }; int main(int argc, char* argv[]) { HelloClient app; return app.main(argc, argv, "config.client"); } HelloClient::HelloClient() : // // Since this is an interactive demo we don't want any signal // handling. // Ice::Application(Ice::NoSignalHandling) { } int HelloClient::run(int argc, char* argv[]) { if(argc > 2) { usage(); return EXIT_FAILURE; } bool addContext = false; if(argc == 2) { if(string(argv[1]) == "--context") { addContext = true; } else { usage(); return EXIT_FAILURE; } } // // Add the context entry that allows the client to use the locator // if(addContext) { Ice::LocatorPrx locator = communicator()->getDefaultLocator(); Ice::Context ctx; ctx["SECRET"] = "LetMeIn"; communicator()->setDefaultLocator(locator->ice_context(ctx)); } // // Now we try to connect to the object with the `hello' identity. // HelloPrx hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello")); if(!hello) { cerr << argv[0] << ": couldn't find a `hello' object." << endl; return EXIT_FAILURE; } menu(); char c = 'x'; do { try { cout << "==> "; cin >> c; if(c == 't') { hello->sayHello(); } else if(c == 't') { hello->sayHello(); } else if(c == 's') { hello->shutdown(); } else if(c == 'x') { // Nothing to do } else if(c == '?') { menu(); } else { cout << "unknown command `" << c << "'" << endl; menu(); } } catch(const Ice::Exception& ex) { cerr << ex << endl; } } while(cin.good() && c != 'x'); return EXIT_SUCCESS; } void HelloClient::menu() { cout << "usage:\n" "t: send greeting\n" "s: shutdown server\n" "x: exit\n" "?: help\n"; } void HelloClient::usage() { cerr << "Usage: " << appName() << " [--context]" << endl; }
lejingw/ice-java
cpp/IceGrid/customLocator/Client.cpp
C++
gpl-2.0
2,877
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Luayats: src/win/winobj.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.6.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="files.html"><span>File&nbsp;List</span></a></li> <li><a href="globals.html"><span>File&nbsp;Members</span></a></li> </ul> </div> <h1>src/win/winobj.h</h1><a href="winobj_8h.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/*************************************************************************</span> <a name="l00002"></a>00002 <span class="comment">*</span> <a name="l00003"></a>00003 <span class="comment">* YATS - Yet Another Tiny Simulator</span> <a name="l00004"></a>00004 <span class="comment">*</span> <a name="l00005"></a>00005 <span class="comment">**************************************************************************</span> <a name="l00006"></a>00006 <span class="comment">*</span> <a name="l00007"></a>00007 <span class="comment">* Copyright (C) 1995-1997 Chair for Telecommunications</span> <a name="l00008"></a>00008 <span class="comment">* Dresden University of Technology</span> <a name="l00009"></a>00009 <span class="comment">* D-01062 Dresden</span> <a name="l00010"></a>00010 <span class="comment">* Germany</span> <a name="l00011"></a>00011 <span class="comment">*</span> <a name="l00012"></a>00012 <span class="comment">*</span> <a name="l00013"></a>00013 <span class="comment">**************************************************************************</span> <a name="l00014"></a>00014 <span class="comment">*</span> <a name="l00015"></a>00015 <span class="comment">* This program is free software; you can redistribute it and/or modify</span> <a name="l00016"></a>00016 <span class="comment">* it under the terms of the GNU General Public License as published by</span> <a name="l00017"></a>00017 <span class="comment">* the Free Software Foundation; either version 2 of the License, or</span> <a name="l00018"></a>00018 <span class="comment">* (at your option) any later version.</span> <a name="l00019"></a>00019 <span class="comment">*</span> <a name="l00020"></a>00020 <span class="comment">* This program is distributed in the hope that it will be useful,</span> <a name="l00021"></a>00021 <span class="comment">* but WITHOUT ANY WARRANTY; without even the implied warranty of</span> <a name="l00022"></a>00022 <span class="comment">* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the</span> <a name="l00023"></a>00023 <span class="comment">* GNU General Public License for more details.</span> <a name="l00024"></a>00024 <span class="comment">*</span> <a name="l00025"></a>00025 <span class="comment">* You should have received a copy of the GNU General Public License</span> <a name="l00026"></a>00026 <span class="comment">* along with this program; if not, write to the Free Software</span> <a name="l00027"></a>00027 <span class="comment">* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.</span> <a name="l00028"></a>00028 <span class="comment">*</span> <a name="l00029"></a>00029 <span class="comment">**************************************************************************</span> <a name="l00030"></a>00030 <span class="comment">*</span> <a name="l00031"></a>00031 <span class="comment">* Module author: Herbert Leuwer, Marconi Ondata GmbH</span> <a name="l00032"></a>00032 <span class="comment">* Creation: 2004</span> <a name="l00033"></a>00033 <span class="comment">*</span> <a name="l00034"></a>00034 <span class="comment">*************************************************************************/</span> <a name="l00035"></a>00035 <span class="preprocessor">#ifndef _WINOBJ_H_</span> <a name="l00036"></a>00036 <span class="preprocessor"></span><span class="preprocessor">#define _WINOBJ_H_</span> <a name="l00037"></a>00037 <span class="preprocessor"></span> <a name="l00038"></a>00038 <span class="keyword">extern</span> <span class="stringliteral">&quot;C&quot;</span> { <a name="l00039"></a>00039 <span class="preprocessor">#include &quot;lua.h&quot;</span> <a name="l00040"></a>00040 <span class="preprocessor">#include &quot;iup/iup.h&quot;</span> <a name="l00041"></a>00041 <span class="preprocessor">#include &quot;cd/cd.h&quot;</span> <a name="l00042"></a>00042 <span class="preprocessor">#include &quot;cd/wd.h&quot;</span> <a name="l00043"></a>00043 <span class="preprocessor">#include &quot;cd/cddbuf.h&quot;</span> <a name="l00044"></a>00044 <span class="preprocessor">#include &quot;cd/cdimage.h&quot;</span> <a name="l00045"></a>00045 <span class="preprocessor">#include &quot;cd/cdirgb.h&quot;</span> <a name="l00046"></a>00046 } <a name="l00047"></a>00047 <span class="preprocessor">#include &quot;<a class="code" href="inxout_8h.html">inxout.h</a>&quot;</span> <a name="l00048"></a>00048 <a name="l00049"></a><a class="code" href="structXSegment.html">00049</a> <span class="keyword">typedef</span> <span class="keyword">struct </span>{ <a name="l00050"></a><a class="code" href="structXSegment.html#a081c4c4ec2bb306f365ee4ebc8b47178">00050</a> <span class="keywordtype">short</span> x1, x2, y1, y2; <a name="l00051"></a>00051 } <a class="code" href="structXSegment.html">XSegment</a>; <a name="l00052"></a>00052 <a name="l00053"></a><a class="code" href="structviewport.html">00053</a> <span class="keyword">struct </span><a class="code" href="structviewport.html">viewport</a> { <a name="l00054"></a><a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">00054</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a>; <a name="l00055"></a><a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">00055</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a>; <a name="l00056"></a><a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">00056</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a>; <a name="l00057"></a><a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">00057</a> <span class="keywordtype">int</span> <a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a>; <a name="l00058"></a>00058 }; <a name="l00059"></a>00059 <a name="l00060"></a>00060 <span class="comment">//tolua_begin</span> <a name="l00061"></a><a class="code" href="winobj_8h.html#ae54e510918b5a97af07c7e5b037b56cb">00061</a> <span class="preprocessor">#define CDTYPE_IUP (1)</span> <a name="l00062"></a><a class="code" href="winobj_8h.html#ae321be6df0b536ec7572a418135c2d0e">00062</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_DBUFFER (2)</span> <a name="l00063"></a><a class="code" href="winobj_8h.html#a9a682ca41774ce6b098dd6f355dc6879">00063</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_SERVERIMG (3)</span> <a name="l00064"></a><a class="code" href="winobj_8h.html#ad3765b329e172e60ae940ec8b1e81895">00064</a> <span class="preprocessor"></span><span class="preprocessor">#define CDTYPE_CLIENTIMG (4)</span> <a name="l00065"></a><a class="code" href="classwinobj.html">00065</a> <span class="preprocessor"></span><span class="keyword">class </span><a class="code" href="classwinobj.html">winobj</a>: <span class="keyword">public</span> <a class="code" href="classinxout.html">inxout</a> { <a name="l00066"></a>00066 <span class="keyword">typedef</span> <a class="code" href="classinxout.html">inxout</a> <a class="code" href="classroot.html">baseclass</a>; <a name="l00067"></a>00067 <span class="keyword">public</span>: <a name="l00068"></a>00068 <a class="code" href="classwinobj.html#a962fb38e7d8aeb9f5b7b9ca816e54eb4">winobj</a>(); <a name="l00069"></a>00069 <a class="code" href="classwinobj.html#a9a171bc1a1fd0e561407b518e41c16b0">~winobj</a>(); <a name="l00070"></a>00070 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#aed06bad9352dfac934a357143b7c41f0">set_textsize</a>(<span class="keywordtype">int</span>); <a name="l00071"></a>00071 cdCanvas *<a class="code" href="classwinobj.html#ac01559e41120617f805ebf24cad8eef3">map</a>(<span class="keywordtype">void</span> *iupcanvas, <span class="keywordtype">void</span> *wid, <a name="l00072"></a>00072 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#af4e4e80ea9fd32096b91a6144f8d51ae">width</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a39a9abca0530f1cc1d765464fc6c2818">height</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14d9c26ffe911a780edaa863a61cd5db">xpos</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a09d31c0505a11232509d3e5b8174cd39">ypos</a>, <a name="l00073"></a>00073 <span class="keyword">const</span> <span class="keywordtype">char</span> *wrtypeface = <span class="stringliteral">&quot;Helvetica&quot;</span>, <a name="l00074"></a>00074 <span class="keywordtype">int</span> wrstyle = <a class="code" href="cd__pkg_8h.html#a385c44f6fb256e5716a2302a5b940388a5acd5688fe1a05dc4dff09cb8ce98c9c">CD_BOLD</a>, <a name="l00075"></a>00075 <span class="keywordtype">int</span> wrsize = 10, <a name="l00076"></a>00076 <span class="keywordtype">void</span> *wrcol = (<span class="keywordtype">void</span> *) <a class="code" href="cd__pkg_8h.html#aa151cc8bc4b43aab96d04e04e8def2e2">CD_BLACK</a>, <a name="l00077"></a>00077 <span class="keywordtype">int</span> wrmode = <a class="code" href="cd__pkg_8h.html#ac705ce3d609ed366b0efeb8787b9f98aadec23484c84b6a6b5a8284fe3342fcc4">CD_REPLACE</a>, <a name="l00078"></a>00078 <span class="keywordtype">void</span> *fgcol = (<span class="keywordtype">void</span> *) CD_BLACK, <a name="l00079"></a>00079 <span class="keywordtype">int</span> fgmode = <a class="code" href="cd__pkg_8h.html#ac705ce3d609ed366b0efeb8787b9f98aadec23484c84b6a6b5a8284fe3342fcc4">CD_REPLACE</a>, <a name="l00080"></a>00080 <span class="keywordtype">int</span> fgstyle = <a class="code" href="cd__pkg_8h.html#a05d5745a26f0528e3bffebd8a03dcedba48e2d0b7258a5f49989f914e51882930">CD_CONTINUOUS</a>, <a name="l00081"></a>00081 <span class="keywordtype">int</span> fgwidth = 1, <a name="l00082"></a>00082 <span class="keywordtype">void</span> *bgcol = (<span class="keywordtype">void</span> *) <a class="code" href="cd__pkg_8h.html#a38a02e70691cf61759ee97b041857acc">CD_WHITE</a>, <a name="l00083"></a>00083 <span class="keywordtype">int</span> opacity = <a class="code" href="cd__pkg_8h.html#a7e59f212705e8a9d21a7225cf48bb7adab5e3c20eea4e0c4470106fb608529f84">CD_TRANSPARENT</a>, <a name="l00084"></a>00084 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">usepoly</a> = 0, <a name="l00085"></a>00085 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b24189118f91e41ef35a3dd52d7c9a">polytype</a> = CD_OPEN_LINES, <a name="l00086"></a>00086 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a99435c16c71caef3c37cca6438a55c28">polystep</a> = 0, <a name="l00087"></a>00087 <span class="keywordtype">int</span> canvastype = <a class="code" href="winobj_8h.html#a9a682ca41774ce6b098dd6f355dc6879">CDTYPE_SERVERIMG</a>); <a name="l00088"></a>00088 <span class="comment">// void * map(void *, void*, </span> <a name="l00089"></a>00089 <span class="comment">// int, int, int, int, </span> <a name="l00090"></a>00090 <span class="comment">// int, int, int, int, </span> <a name="l00091"></a>00091 <span class="comment">// int, int, int, int,</span> <a name="l00092"></a>00092 <span class="comment">// int, int, int);</span> <a name="l00093"></a>00093 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#ab6103b0a4f873a6b2d3aa265722c91a9">unmap</a>(<span class="keywordtype">void</span>); <a name="l00094"></a>00094 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a8815c22efb95f851421df6cafecdd92b">draw_values</a>(<span class="keywordtype">int</span> *, <span class="keywordtype">void</span> *color, <span class="keywordtype">int</span> nvals, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">usepoly</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b24189118f91e41ef35a3dd52d7c9a">polytype</a>, <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a99435c16c71caef3c37cca6438a55c28">polystep</a>, <span class="keywordtype">int</span> flush); <a name="l00095"></a>00095 <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a8815c22efb95f851421df6cafecdd92b">draw_values</a>(<span class="keywordtype">double</span> *, <span class="keywordtype">double</span> *, <span class="keywordtype">void</span> *color, <span class="keywordtype">int</span> nvals, <span class="keywordtype">int</span> usepoly, <span class="keywordtype">int</span> polytype, <span class="keywordtype">int</span> polystep, <span class="keywordtype">int</span> flush); <a name="l00096"></a><a class="code" href="classwinobj.html#a1211aaf8fb8f77713217543c85c741f5">00096</a> <span class="keyword">virtual</span> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#a1211aaf8fb8f77713217543c85c741f5">drawWin</a>(<span class="keywordtype">int</span> activate = 1, <span class="keywordtype">int</span> clear = 1, <span class="keywordtype">int</span> flush = 1){} <a name="l00097"></a>00097 <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#aa9d178670489edfaffcca4cb427500fe">getexp</a>(<a class="code" href="structexp__typ.html">exp_typ</a> *); <a name="l00098"></a><a class="code" href="classwinobj.html#a3fb336be24d1eea6577db8c0521ad7e4">00098</a> cdCanvas* <a class="code" href="classwinobj.html#a3fb336be24d1eea6577db8c0521ad7e4">setCanvas</a>(cdCanvas * cv){ <a name="l00099"></a>00099 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">false</span>) <a name="l00100"></a>00100 <span class="keywordflow">return</span> NULL; <a name="l00101"></a>00101 cdCanvas *ocv = <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>; <a name="l00102"></a>00102 <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a> = cv; <a name="l00103"></a>00103 <span class="keywordflow">return</span> ocv; <a name="l00104"></a>00104 } <a name="l00105"></a><a class="code" href="classwinobj.html#ad5fc8e3c0bfcff77680baafb8d6667a6">00105</a> cdCanvas* <a class="code" href="classwinobj.html#ad5fc8e3c0bfcff77680baafb8d6667a6">getCanvas</a>(<span class="keywordtype">void</span>){ <a name="l00106"></a>00106 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">true</span>) <a name="l00107"></a>00107 <span class="keywordflow">return</span> <a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>; <a name="l00108"></a>00108 <span class="keywordflow">else</span> <a name="l00109"></a>00109 <span class="keywordflow">return</span> NULL; <a name="l00110"></a>00110 } <a name="l00111"></a><a class="code" href="classwinobj.html#a14b0bccef2254fdacded2f26baba207a">00111</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a14b0bccef2254fdacded2f26baba207a">activateCanvas</a>(<span class="keywordtype">void</span>){ <a name="l00112"></a>00112 <span class="keywordflow">if</span> (<a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a> == <span class="keyword">true</span>) <a name="l00113"></a>00113 <span class="keywordflow">return</span> cdCanvasActivate(<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>); <a name="l00114"></a>00114 <span class="keywordflow">else</span> <a name="l00115"></a>00115 <span class="keywordflow">return</span> CD_ERROR; <a name="l00116"></a>00116 } <a name="l00117"></a><a class="code" href="classwinobj.html#afc77036e1293f0f4581b54d8acf34053">00117</a> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#afc77036e1293f0f4581b54d8acf34053">setScale</a>(<span class="keywordtype">double</span> scx, <span class="keywordtype">double</span> scy){ <a name="l00118"></a>00118 <a class="code" href="classwinobj.html#a6633c6e017e3f60fb2d547943c13b9f6">sx</a> = scx; <a name="l00119"></a>00119 <a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">sy</a> = scy; <a name="l00120"></a>00120 } <a name="l00121"></a><a class="code" href="classwinobj.html#afbf73470c5f5faf16ac7d5e695d3bb63">00121</a> <span class="keywordtype">void</span> <a class="code" href="classwinobj.html#afbf73470c5f5faf16ac7d5e695d3bb63">setViewport</a>(<span class="keywordtype">int</span> xmin, <span class="keywordtype">int</span> xmax, <span class="keywordtype">int</span> ymin, <span class="keywordtype">int</span> ymax){ <a name="l00122"></a>00122 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a> = xmin; <a name="l00123"></a>00123 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a> = xmax; <a name="l00124"></a>00124 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a> = ymin; <a name="l00125"></a>00125 <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a> = ymax; <a name="l00126"></a>00126 wdCanvasViewport(<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#ad9b05f6251917e453290a040a8dcfc18">xmin</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#a208da7172a2614ef2b378472aaca3dd2">xmax</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aeffd66914138d0e2d44447ceeea51ac3">ymin</a>, <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>.<a class="code" href="structviewport.html#aed23763a123c3d00941fdcaf660279c2">ymax</a>); <a name="l00127"></a>00127 } <a name="l00128"></a><a class="code" href="classwinobj.html#af2dadec9ca2c5ac161ce99c4120e479d">00128</a> <a class="code" href="classroot.html">root</a> *<a class="code" href="classwinobj.html#af2dadec9ca2c5ac161ce99c4120e479d">exp_obj</a>; <a name="l00129"></a><a class="code" href="classwinobj.html#a5f149b5a6efe246f794a90b09ce8f3b0">00129</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#a5f149b5a6efe246f794a90b09ce8f3b0">exp_varname</a>; <a name="l00130"></a><a class="code" href="classwinobj.html#a0161fea8d4972fc0265b54ec76821e73">00130</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a0161fea8d4972fc0265b54ec76821e73">exp_idx</a>; <a name="l00131"></a><a class="code" href="classwinobj.html#abecc923a3e18888f6103d86916d5df04">00131</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#abecc923a3e18888f6103d86916d5df04">exp_idx2</a>; <a name="l00132"></a><a class="code" href="classwinobj.html#a9f40c79216ca22a23b4f6f428e30ba8b">00132</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#a9f40c79216ca22a23b4f6f428e30ba8b">title</a>; <a name="l00133"></a><a class="code" href="classwinobj.html#a42e844b0cf15416d055476503a6c1d09">00133</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a42e844b0cf15416d055476503a6c1d09">cvtype</a>; <a name="l00134"></a><a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">00134</a> cdCanvas *<a class="code" href="classwinobj.html#af487912f9cbe04ebb5e0370f669e6567">canvas</a>; <a name="l00135"></a><a class="code" href="classwinobj.html#a16b472b5a9b0c49bc8f44873e32e8b51">00135</a> cdCanvas *<a class="code" href="classwinobj.html#a16b472b5a9b0c49bc8f44873e32e8b51">bcanvas</a>; <a name="l00136"></a><a class="code" href="classwinobj.html#a9f8ebe79dfa0683610bdf68c6d8d8582">00136</a> cdImage *<a class="code" href="classwinobj.html#a9f8ebe79dfa0683610bdf68c6d8d8582">simg</a>; <a name="l00137"></a><a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">00137</a> <span class="keywordtype">bool</span> <a class="code" href="classwinobj.html#a06ac21edba964c6b76fab35bf8039dbc">canvas_mapped</a>; <a name="l00138"></a><a class="code" href="classwinobj.html#af041c6b7fd6ff07d92ae3eb9beeb457e">00138</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#af041c6b7fd6ff07d92ae3eb9beeb457e">drawoper</a>; <a name="l00139"></a><a class="code" href="classwinobj.html#a47c066fcf1692dbb6632f9d4eb2c8b65">00139</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a47c066fcf1692dbb6632f9d4eb2c8b65">drawstyle</a>; <a name="l00140"></a><a class="code" href="classwinobj.html#a8e8b11ae02ced81b825726bfb3830d7c">00140</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a8e8b11ae02ced81b825726bfb3830d7c">drawwidth</a>; <a name="l00141"></a><a class="code" href="classwinobj.html#a3d5d467da7f531e6615143a2e0cda205">00141</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a3d5d467da7f531e6615143a2e0cda205">textoper</a>; <a name="l00142"></a><a class="code" href="classwinobj.html#aa7a79ced697fded84c60d9b9c62784e1">00142</a> <span class="keywordtype">char</span> *<a class="code" href="classwinobj.html#aa7a79ced697fded84c60d9b9c62784e1">texttypeface</a>; <a name="l00143"></a><a class="code" href="classwinobj.html#a88151f63245aac2924f2488a055dc1fe">00143</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a88151f63245aac2924f2488a055dc1fe">textstyle</a>; <a name="l00144"></a><a class="code" href="classwinobj.html#a6213da470644191345393eb791d6d721">00144</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a6213da470644191345393eb791d6d721">textcolor</a>; <a name="l00145"></a><a class="code" href="classwinobj.html#a92ecfdc12216529a62fc4e24ba56a297">00145</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a92ecfdc12216529a62fc4e24ba56a297">bgcolor</a>; <a name="l00146"></a><a class="code" href="classwinobj.html#a292b1a68c62ca6b54b4db924d65f785a">00146</a> <span class="keywordtype">void</span> *<a class="code" href="classwinobj.html#a292b1a68c62ca6b54b4db924d65f785a">drawcolor</a>; <a name="l00147"></a><a class="code" href="classwinobj.html#ab88ceec0bb8f96ee18e3a3f1afbd2dca">00147</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#ab88ceec0bb8f96ee18e3a3f1afbd2dca">textsize</a>; <a name="l00148"></a><a class="code" href="classwinobj.html#a7fe1494c3b52b71e5fa2df6aed1a6059">00148</a> <span class="keywordtype">int</span> <a class="code" href="classwinobj.html#a7fe1494c3b52b71e5fa2df6aed1a6059">bgopacity</a>; <a name="l00149"></a><a class="code" href="classwinobj.html#a09d31c0505a11232509d3e5b8174cd39">00149</a> <span class="keywordtype">int</span> width, height, xpos, ypos; <a name="l00150"></a><a class="code" href="classwinobj.html#a338445bcf35090a13f8991aa1384cbe3">00150</a> <span class="keywordtype">int</span> usepoly, polytype, polystep; <a name="l00151"></a><a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">00151</a> <span class="keywordtype">double</span> <a class="code" href="classwinobj.html#a6633c6e017e3f60fb2d547943c13b9f6">sx</a>, <a class="code" href="classwinobj.html#a67bb589183765fc767a323df2c94070c">sy</a>; <a name="l00152"></a><a class="code" href="classwinobj.html#a8e3848bb4c631cbaf167e42d44ed1a6a">00152</a> <span class="keywordtype">double</span> <a class="code" href="classwinobj.html#a38a0e70c065d42cd3d82fa3c58071eea">xlast</a>, <a class="code" href="classwinobj.html#a8e3848bb4c631cbaf167e42d44ed1a6a">ylast</a>; <a name="l00153"></a>00153 <span class="comment">//tolua_end</span> <a name="l00154"></a><a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">00154</a> <span class="keyword">struct </span><a class="code" href="structviewport.html">viewport</a> <a class="code" href="classwinobj.html#ac288eb1da38136f8065a2e0df17c1ae5">vp</a>; <a name="l00155"></a>00155 <span class="comment">//tolua_begin</span> <a name="l00156"></a>00156 }; <a name="l00157"></a>00157 <span class="comment">//tolua_end</span> <a name="l00158"></a>00158 <span class="preprocessor">#endif </span> </pre></div></div> <hr size="1"/><address style="text-align: right;"><small>Generated on Sun Feb 14 12:31:43 2010 for Luayats by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.6.1 </small></address> </body> </html>
hleuwer/luayats
doc/cpp/html/winobj_8h_source.html
HTML
gpl-2.0
26,742
<?php /** --------------------------------------------------------------------- * JavascriptLoadManager.php : class to control loading of Javascript libraries * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2009-2010 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage Misc * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ require_once(__CA_LIB_DIR__.'/core/Configuration.php'); /* * Globals used by Javascript load manager */ /** * Contains configuration object for javascript.conf file */ $g_javascript_config = null; /** * Contains list of Javascript libraries to load */ $g_javascript_load_list = null; /** * Contains array of complementary Javasscript code to load */ $g_javascript_complementary = null; class JavascriptLoadManager { # -------------------------------------------------------------------------------- # -------------------------------------------------------------------------------- static function init() { global $g_javascript_config, $g_javascript_load_list; $o_config = Configuration::load(); $g_javascript_config = Configuration::load($o_config->get('javascript_config')); $g_javascript_load_list = array(); JavascriptLoadManager::register('_default'); } # -------------------------------------------------------------------------------- /** * Causes the specified Javascript library (or libraries) to be loaded for the current request. * There are two ways you can trigger loading of Javascript: * (1) If you pass via the $ps_package parameter a loadSet name defined in javascript.conf then all of the libraries in that loadSet will be loaded * (2) If you pass a package and library name (via $ps_package and $ps_library) then the specified library will be loaded * * Whether you use a loadSet or a package/library combination, if it doesn't have a definition in javascript.conf nothing will be loaded. * * @param $ps_package (string) - The package name containing the library to be loaded *or* a loadSet name. LoadSets describe a set of libraries to be loaded as a unit. * @param $ps_library (string) - The name of the library contained in $ps_package to be loaded. * @return bool - false if load failed, true if load succeeded */ static function register($ps_package, $ps_library=null) { global $g_javascript_config, $g_javascript_load_list; if (!$g_javascript_config) { JavascriptLoadManager::init(); } $va_packages = $g_javascript_config->getAssoc('packages'); if ($ps_library) { // register package/library $va_pack_path = explode('/', $ps_package); $vs_main_package = array_shift($va_pack_path); if (!($va_list = $va_packages[$vs_main_package])) { return false; } while(sizeof($va_pack_path) > 0) { $vs_pack = array_shift($va_pack_path); $va_list = $va_list[$vs_pack]; } if ($va_list[$ps_library]) { $g_javascript_load_list[$ps_package.'/'.$va_list[$ps_library]] = true; return true; } } else { // register loadset $va_loadsets = $g_javascript_config->getAssoc('loadSets'); if ($va_loadset = $va_loadsets[$ps_package]) { $vs_loaded_ok = true; foreach($va_loadset as $vs_path) { $va_tmp = explode('/', $vs_path); $vs_library = array_pop($va_tmp); $vs_package = join('/', $va_tmp); if (!JavascriptLoadManager::register($vs_package, $vs_library)) { $vs_loaded_ok = false; } } return $vs_loaded_ok; } } return false; } # -------------------------------------------------------------------------------- /** * Causes the specified Javascript code to be loaded. * * @param $ps_scriptcontent (string) - script content to load * @return (bool) - false if empty code, true if load succeeded */ static function addComplementaryScript($ps_content=null) { global $g_javascript_config, $g_javascript_load_list, $g_javascript_complementary; if (!$g_javascript_config) { JavascriptLoadManager::init(); } if (!$ps_content) return false; $g_javascript_complementary[]=$ps_content; return true; } # -------------------------------------------------------------------------------- /** * Returns HTML to load registered libraries. Typically you'll output this HTML in the <head> of your page. * * @param $ps_baseurlpath (string) - URL path containing the application's "js" directory. * @return string - HTML loading registered libraries */ static function getLoadHTML($ps_baseurlpath) { global $g_javascript_config, $g_javascript_load_list, $g_javascript_complementary; if (!$g_javascript_config) { JavascriptLoadManager::init(); } $vs_buf = ''; if (is_array($g_javascript_load_list)) { foreach($g_javascript_load_list as $vs_lib => $vn_x) { if (preg_match('!(http[s]{0,1}://.*)!', $vs_lib, $va_matches)) { $vs_url = $va_matches[1]; } else { $vs_url = "{$ps_baseurlpath}/js/{$vs_lib}"; } $vs_buf .= "<script src='{$vs_url}' type='text/javascript'></script>\n"; } } if (is_array($g_javascript_complementary)) { foreach($g_javascript_complementary as $vs_code) { $vs_buf .= "<script type='text/javascript'>\n".$vs_code."</script>\n"; } } return $vs_buf; } # -------------------------------------------------------------------------------- } ?>
avpreserve/nfai
app/lib/ca/JavascriptLoadManager.php
PHP
gpl-2.0
6,453
<?php /** * @package Joomla.Site * @subpackage mod_menu * * @copyright Copyright (C) 2005 - 2016 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; <<<<<<< HEAD // Note. It is important to remove spaces between elements. $class = $item->anchor_css ? ' ' . $item->anchor_css : ''; $title = $item->anchor_title ? ' title="' . $item->anchor_title . '" ' : ''; ======= $title = $item->anchor_title ? ' title="' . $item->anchor_title . '"' : ''; $anchor_css = $item->anchor_css ? $item->anchor_css : ''; $linktype = $item->title; >>>>>>> joomla/staging if ($item->menu_image) { $linktype = JHtml::_('image', $item->menu_image, $item->title); if ($item->params->get('menu_text', 1)) { <<<<<<< HEAD $item->params->get('menu_text', 1) ? $linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" /><span class="image-title">' . $item->title . '</span> ' : $linktype = '<img src="' . $item->menu_image . '" alt="' . $item->title . '" />'; } else { $linktype = $item->title; } ?> <span class="separator<?php echo $class;?>"<?php echo $title; ?>> <?php echo $linktype; ?> </span> ======= $linktype .= '<span class="image-title">' . $item->title . '</span>'; } } ?> <span class="separator <?php echo $anchor_css; ?>"<?php echo $title; ?>><?php echo $linktype; ?></span> >>>>>>> joomla/staging
JoomliC/joomla-cms
modules/mod_menu/tmpl/default_separator.php
PHP
gpl-2.0
1,436